<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const util = require("util");

const DependenciesBlock = require("./DependenciesBlock");
const ModuleReason = require("./ModuleReason");
const SortableSet = require("./util/SortableSet");
const Template = require("./Template");

let debugId = 1000;

const sortById = (a, b) => {
	return a.id - b.id;
};

const sortByDebugId = (a, b) => {
	return a.debugId - b.debugId;
};

class Module extends DependenciesBlock {

	constructor() {
		super();
		this.context = null;
		this.reasons = [];
		this.debugId = debugId++;
		this.id = null;
		this.portableId = null;
		this.index = null;
		this.index2 = null;
		this.depth = null;
		this.used = null;
		this.usedExports = null;
		this.providedExports = null;
		this._chunks = new SortableSet(undefined, sortById);
		this._chunksDebugIdent = undefined;
		this.warnings = [];
		this.dependenciesWarnings = [];
		this.errors = [];
		this.dependenciesErrors = [];
		this.strict = false;
		this.meta = {};
		this.optimizationBailout = [];
	}

	disconnect() {
		this.reasons.length = 0;
		this.id = null;
		this.index = null;
		this.index2 = null;
		this.depth = null;
		this.used = null;
		this.usedExports = null;
		this.providedExports = null;
		this._chunks.clear();
		this._chunksDebugIdent = undefined;
		super.disconnect();
	}

	unseal() {
		this.id = null;
		this.index = null;
		this.index2 = null;
		this.depth = null;
		this._chunks.clear();
		this._chunksDebugIdent = undefined;
		super.unseal();
	}

	setChunks(chunks) {
		this._chunks = new SortableSet(chunks, sortById);
		this._chunksDebugIdent = undefined;
	}

	addChunk(chunk) {
		this._chunks.add(chunk);
		this._chunksDebugIdent = undefined;
	}

	removeChunk(chunk) {
		if(this._chunks.delete(chunk)) {
			this._chunksDebugIdent = undefined;
			chunk.removeModule(this);
			return true;
		}
		return false;
	}

	isInChunk(chunk) {
		return this._chunks.has(chunk);
	}

	getChunkIdsIdent() {
		if(this._chunksDebugIdent !== undefined) return this._chunksDebugIdent;
		this._chunks.sortWith(sortByDebugId);
		const chunks = this._chunks;
		const list = [];
		for(const chunk of chunks) {
			const debugId = chunk.debugId;

			if(typeof debugId !== "number") {
				return this._chunksDebugIdent = null;
			}

			list.push(debugId);
		}

		return this._chunksDebugIdent = list.join(",");
	}

	forEachChunk(fn) {
		this._chunks.forEach(fn);
	}

	mapChunks(fn) {
		return Array.from(this._chunks, fn);
	}

	getChunks() {
		return Array.from(this._chunks);
	}

	getNumberOfChunks() {
		return this._chunks.size;
	}

	hasEqualsChunks(otherModule) {
		if(this._chunks.size !== otherModule._chunks.size) return false;
		this._chunks.sortWith(sortByDebugId);
		otherModule._chunks.sortWith(sortByDebugId);
		const a = this._chunks[Symbol.iterator]();
		const b = otherModule._chunks[Symbol.iterator]();
		while(true) { // eslint-disable-line
			const aItem = a.next();
			const bItem = b.next();
			if(aItem.done) return true;
			if(aItem.value !== bItem.value) return false;
		}
	}

	addReason(module, dependency) {
		this.reasons.push(new ModuleReason(module, dependency));
	}

	removeReason(module, dependency) {
		for(let i = 0; i < this.reasons.length; i++) {
			let r = this.reasons[i];
			if(r.module === module && r.dependency === dependency) {
				this.reasons.splice(i, 1);
				return true;
			}
		}
		return false;
	}

	hasReasonForChunk(chunk) {
		for(let i = 0; i < this.reasons.length; i++) {
			if(this.reasons[i].hasChunk(chunk))
				return true;
		}
		return false;
	}

	rewriteChunkInReasons(oldChunk, newChunks) {
		for(let i = 0; i < this.reasons.length; i++) {
			this.reasons[i].rewriteChunks(oldChunk, newChunks);
		}
	}

	isUsed(exportName) {
		if(this.used === null) return exportName;
		if(!exportName) return !!this.used;
		if(!this.used) return false;
		if(!this.usedExports) return false;
		if(this.usedExports === true) return exportName;
		let idx = this.usedExports.indexOf(exportName);
		if(idx < 0) return false;
		if(this.isProvided(exportName))
			return Template.numberToIdentifer(idx);
		return exportName;
	}

	isProvided(exportName) {
		if(!Array.isArray(this.providedExports))
			return null;
		return this.providedExports.indexOf(exportName) >= 0;
	}

	toString() {
		return `Module[${this.id || this.debugId}]`;
	}

	needRebuild(fileTimestamps, contextTimestamps) {
		return true;
	}

	updateHash(hash) {
		hash.update(this.id + "" + this.used);
		hash.update(JSON.stringify(this.usedExports));
		super.updateHash(hash);
	}

	sortItems(sortChunks) {
		super.sortItems();
		if(sortChunks)
			this._chunks.sort();
		this.reasons.sort((a, b) => sortById(a.module, b.module));
		if(Array.isArray(this.usedExports)) {
			this.usedExports.sort();
		}
	}

	unbuild() {
		this.disconnect();
	}
}

Object.defineProperty(Module.prototype, "entry", {
	configurable: false,
	get() {
		throw new Error("Module.entry was removed. Use Chunk.entryModule");
	},
	set() {
		throw new Error("Module.entry was removed. Use Chunk.entryModule");
	}
});

Object.defineProperty(Module.prototype, "chunks", {
	configurable: false,
	get: util.deprecate(function() {
		return Array.from(this._chunks);
	}, "Module.chunks: Use Module.forEachChunk/mapChunks/getNumberOfChunks/isInChunk/addChunk/removeChunk instead"),
	set() {
		throw new Error("Readonly. Use Module.addChunk/removeChunk to modify chunks.");
	}
});

Module.prototype.identifier = null;
Module.prototype.readableIdentifier = null;
Module.prototype.build = null;
Module.prototype.source = null;
Module.prototype.size = null;
Module.prototype.nameForCondition = null;

module.exports = Module;
<commit_msg>fix: Clear optimization bailouts on module.disconnect<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const util = require("util");

const DependenciesBlock = require("./DependenciesBlock");
const ModuleReason = require("./ModuleReason");
const SortableSet = require("./util/SortableSet");
const Template = require("./Template");

let debugId = 1000;

const sortById = (a, b) => {
	return a.id - b.id;
};

const sortByDebugId = (a, b) => {
	return a.debugId - b.debugId;
};

class Module extends DependenciesBlock {

	constructor() {
		super();
		this.context = null;
		this.reasons = [];
		this.debugId = debugId++;
		this.id = null;
		this.portableId = null;
		this.index = null;
		this.index2 = null;
		this.depth = null;
		this.used = null;
		this.usedExports = null;
		this.providedExports = null;
		this._chunks = new SortableSet(undefined, sortById);
		this._chunksDebugIdent = undefined;
		this.warnings = [];
		this.dependenciesWarnings = [];
		this.errors = [];
		this.dependenciesErrors = [];
		this.strict = false;
		this.meta = {};
		this.optimizationBailout = [];
	}

	disconnect() {
		this.reasons.length = 0;
		this.id = null;
		this.index = null;
		this.index2 = null;
		this.depth = null;
		this.used = null;
		this.usedExports = null;
		this.providedExports = null;
		this._chunks.clear();
		this._chunksDebugIdent = undefined;
		this.optimizationBailout.length = 0;
		super.disconnect();
	}

	unseal() {
		this.id = null;
		this.index = null;
		this.index2 = null;
		this.depth = null;
		this._chunks.clear();
		this._chunksDebugIdent = undefined;
		super.unseal();
	}

	setChunks(chunks) {
		this._chunks = new SortableSet(chunks, sortById);
		this._chunksDebugIdent = undefined;
	}

	addChunk(chunk) {
		this._chunks.add(chunk);
		this._chunksDebugIdent = undefined;
	}

	removeChunk(chunk) {
		if(this._chunks.delete(chunk)) {
			this._chunksDebugIdent = undefined;
			chunk.removeModule(this);
			return true;
		}
		return false;
	}

	isInChunk(chunk) {
		return this._chunks.has(chunk);
	}

	getChunkIdsIdent() {
		if(this._chunksDebugIdent !== undefined) return this._chunksDebugIdent;
		this._chunks.sortWith(sortByDebugId);
		const chunks = this._chunks;
		const list = [];
		for(const chunk of chunks) {
			const debugId = chunk.debugId;

			if(typeof debugId !== "number") {
				return this._chunksDebugIdent = null;
			}

			list.push(debugId);
		}

		return this._chunksDebugIdent = list.join(",");
	}

	forEachChunk(fn) {
		this._chunks.forEach(fn);
	}

	mapChunks(fn) {
		return Array.from(this._chunks, fn);
	}

	getChunks() {
		return Array.from(this._chunks);
	}

	getNumberOfChunks() {
		return this._chunks.size;
	}

	hasEqualsChunks(otherModule) {
		if(this._chunks.size !== otherModule._chunks.size) return false;
		this._chunks.sortWith(sortByDebugId);
		otherModule._chunks.sortWith(sortByDebugId);
		const a = this._chunks[Symbol.iterator]();
		const b = otherModule._chunks[Symbol.iterator]();
		while(true) { // eslint-disable-line
			const aItem = a.next();
			const bItem = b.next();
			if(aItem.done) return true;
			if(aItem.value !== bItem.value) return false;
		}
	}

	addReason(module, dependency) {
		this.reasons.push(new ModuleReason(module, dependency));
	}

	removeReason(module, dependency) {
		for(let i = 0; i < this.reasons.length; i++) {
			let r = this.reasons[i];
			if(r.module === module && r.dependency === dependency) {
				this.reasons.splice(i, 1);
				return true;
			}
		}
		return false;
	}

	hasReasonForChunk(chunk) {
		for(let i = 0; i < this.reasons.length; i++) {
			if(this.reasons[i].hasChunk(chunk))
				return true;
		}
		return false;
	}

	rewriteChunkInReasons(oldChunk, newChunks) {
		for(let i = 0; i < this.reasons.length; i++) {
			this.reasons[i].rewriteChunks(oldChunk, newChunks);
		}
	}

	isUsed(exportName) {
		if(this.used === null) return exportName;
		if(!exportName) return !!this.used;
		if(!this.used) return false;
		if(!this.usedExports) return false;
		if(this.usedExports === true) return exportName;
		let idx = this.usedExports.indexOf(exportName);
		if(idx < 0) return false;
		if(this.isProvided(exportName))
			return Template.numberToIdentifer(idx);
		return exportName;
	}

	isProvided(exportName) {
		if(!Array.isArray(this.providedExports))
			return null;
		return this.providedExports.indexOf(exportName) >= 0;
	}

	toString() {
		return `Module[${this.id || this.debugId}]`;
	}

	needRebuild(fileTimestamps, contextTimestamps) {
		return true;
	}

	updateHash(hash) {
		hash.update(this.id + "" + this.used);
		hash.update(JSON.stringify(this.usedExports));
		super.updateHash(hash);
	}

	sortItems(sortChunks) {
		super.sortItems();
		if(sortChunks)
			this._chunks.sort();
		this.reasons.sort((a, b) => sortById(a.module, b.module));
		if(Array.isArray(this.usedExports)) {
			this.usedExports.sort();
		}
	}

	unbuild() {
		this.disconnect();
	}
}

Object.defineProperty(Module.prototype, "entry", {
	configurable: false,
	get() {
		throw new Error("Module.entry was removed. Use Chunk.entryModule");
	},
	set() {
		throw new Error("Module.entry was removed. Use Chunk.entryModule");
	}
});

Object.defineProperty(Module.prototype, "chunks", {
	configurable: false,
	get: util.deprecate(function() {
		return Array.from(this._chunks);
	}, "Module.chunks: Use Module.forEachChunk/mapChunks/getNumberOfChunks/isInChunk/addChunk/removeChunk instead"),
	set() {
		throw new Error("Readonly. Use Module.addChunk/removeChunk to modify chunks.");
	}
});

Module.prototype.identifier = null;
Module.prototype.readableIdentifier = null;
Module.prototype.build = null;
Module.prototype.source = null;
Module.prototype.size = null;
Module.prototype.nameForCondition = null;

module.exports = Module;
<|endoftext|>


<commit_before>function render() {
  return (

);
}
<commit_msg>Test that spread attributes are closed over<commit_after>function render() {
  var test =
;
  return (

);
}
<|endoftext|>


<commit_before>const Writable = require('stream').Writable;

function isBlankNode (string) {
    return string.indexOf('_:') === 0;
}

module.exports = (scope, event, args) => {

    return new Writable({
        objectMode: true,
        write: (triple, enc, done) => {

            let subject = triple[0] || triple.subject;
            let predicate = triple[1] || triple.predicate;
            let object = triple[2] || triple.object;

            console.log(subject, predicate, object);
            switch (predicate) {
                case 'http://schema.jillix.net/vocab/module':
                    event.module(subject, object, args, scope);
                    break;

                case 'http://schema.jillix.net/vocab/sequence':

                    if (isBlankNode(subject)) {
                        event.link(subject, object);
                        break;
                    }

                    event.first(subject, object);
                    break;

                case 'http://schema.jillix.net/vocab/onEnd':
                    event.onEnd(object, args, scope);
                    break;

                case 'http://schema.jillix.net/vocab/onError':
                    event.onError(object, args, scope);
                    break;

                case 'http://schema.jillix.net/vocab/instance':
                    event.instance(subject, object, args, scope);
                    break;

                case 'http://schema.jillix.net/vocab/roles':
                    event.role(subject, object);
                    break;

                case 'http://schema.jillix.net/vocab/dataHandler':
                    event.data(subject, object);
                    break;

                case 'http://schema.jillix.net/vocab/streamHandler':
                    event.stream(subject, object);
                    break;

                case 'http://schema.jillix.net/vocab/emit':
                    event.emit(subject, object);
                    break;

                case 'http://schema.jillix.net/vocab/args':
                    event.args(object, subject);
                    break;

                default:
                    event.collect(object, subject, predicate);
            }

            done();
        }
    });
};
<commit_msg>emit is already used by event emitter<commit_after>const Writable = require('stream').Writable;

function isBlankNode (string) {
    return string.indexOf('_:') === 0;
}

module.exports = (scope, event, args) => {

    return new Writable({
        objectMode: true,
        write: (triple, enc, done) => {

            let subject = triple[0] || triple.subject;
            let predicate = triple[1] || triple.predicate;
            let object = triple[2] || triple.object;

            //console.log(subject, predicate, object);
            switch (predicate) {
                case 'http://schema.jillix.net/vocab/module':
                    event.module(subject, object, args, scope);
                    break;

                case 'http://schema.jillix.net/vocab/sequence':

                    if (isBlankNode(subject)) {
                        event.link(subject, object);
                        break;
                    }

                    event.setFirst(subject, object);
                    break;

                case 'http://schema.jillix.net/vocab/onEnd':
                    event.onEnd(object, args, scope);
                    break;

                case 'http://schema.jillix.net/vocab/onError':
                    event.onError(object, args, scope);
                    break;

                case 'http://schema.jillix.net/vocab/instance':
                    event.instance(subject, object, args, scope);
                    break;

                case 'http://schema.jillix.net/vocab/roles':
                    event.role(subject, object);
                    break;

                case 'http://schema.jillix.net/vocab/dataHandler':
                    event.data(subject, object);
                    break;

                case 'http://schema.jillix.net/vocab/streamHandler':
                    event.stream(subject, object);
                    break;

                case 'http://schema.jillix.net/vocab/emit':
                    event.event(subject, object);
                    break;

                case 'http://schema.jillix.net/vocab/args':
                    event.args(object, subject);
                    break;

                default:
                    event.collect(object, subject, predicate);
            }

            done();
        }
    });
};
<|endoftext|>


<commit_before>// should have a length of 1
assert.equal(Array.prototype.find.length, 1);

// should handle basic case
assert.equal([1, 2, 3].find(function(v) {
  return v * v === 4;
}), 2);

// should handle arrow functions
assert.equal([1, 2, 3].find(v => v * v === 4), 2);

// should return undefined when not found
assert.equal([1, 2, 3].find(v => v > 10), undefined);

// should return first match
assert.equal([2, 2, 3].find(v => v * v === 4), 2);

// should handle custom objects
assert.equal(Array.prototype.find.call({
  'length': 2,
  '0': false,
  '1': true
}, v => v), true);

// should handle bad predicate
assert.throws(function() {
  [1, 2, 3].find(1)
}, TypeError);

// should handle bad this
assert.throws(function() {
  Array.prototype.find.call(null, function() {})
}, TypeError);

// should correctly handle this
var global = this;
({
  assert: function() {
    var self = this;

    // should be global this
    [1, 2, 3].find(function() {
      assert.notEqual(this, self);
      assert.equal(this, global);
    });

    // should be the same this
    [1, 2, 3].find(function() {
      assert.equal(this, self);
    }, self);

    // should not have an effect on arrow functions
    [1, 2, 3].find(() => assert.equal(this, self));
    [1, 2, 3].find(() => assert.equal(this, self), self);

    // should call with correct args
    var arr = [5];
    arr.find(function(value, i, object) {
      assert.equal(value, 5);
      assert.equal(i, 0);
      assert.equal(arr, object);
    });
  }
}).assert();

var lengthCalls = 0;
var itemCalls = 0;
var callbackCalls = 0;
var object = {
  length: {
    valueOf() {
      lengthCalls++;
      return 3;
    }
  },
  get 2() {
    itemCalls++;
    return 'a';
  }
};

assert.equal(Array.prototype.find.call(object, (v) => {
  callbackCalls++;
  return v === 'a';
}), 'a');
assert.equal(lengthCalls, 1);
assert.equal(itemCalls, 1);
assert.equal(callbackCalls, 3);
<commit_msg>remove arity traceur test check<commit_after>// should have a length of 1
//assert.equal(Array.prototype.find.length, 1);

// should handle basic case
assert.equal([1, 2, 3].find(function(v) {
  return v * v === 4;
}), 2);

// should handle arrow functions
assert.equal([1, 2, 3].find(v => v * v === 4), 2);

// should return undefined when not found
assert.equal([1, 2, 3].find(v => v > 10), undefined);

// should return first match
assert.equal([2, 2, 3].find(v => v * v === 4), 2);

// should handle custom objects
assert.equal(Array.prototype.find.call({
  'length': 2,
  '0': false,
  '1': true
}, v => v), true);

// should handle bad predicate
assert.throws(function() {
  [1, 2, 3].find(1)
}, TypeError);

// should handle bad this
assert.throws(function() {
  Array.prototype.find.call(null, function() {})
}, TypeError);

// should correctly handle this
var global = this;
({
  assert: function() {
    var self = this;

    // should be global this
    [1, 2, 3].find(function() {
      assert.notEqual(this, self);
      assert.equal(this, global);
    });

    // should be the same this
    [1, 2, 3].find(function() {
      assert.equal(this, self);
    }, self);

    // should not have an effect on arrow functions
    [1, 2, 3].find(() => assert.equal(this, self));
    [1, 2, 3].find(() => assert.equal(this, self), self);

    // should call with correct args
    var arr = [5];
    arr.find(function(value, i, object) {
      assert.equal(value, 5);
      assert.equal(i, 0);
      assert.equal(arr, object);
    });
  }
}).assert();

var lengthCalls = 0;
var itemCalls = 0;
var callbackCalls = 0;
var object = {
  length: {
    valueOf() {
      lengthCalls++;
      return 3;
    }
  },
  get 2() {
    itemCalls++;
    return 'a';
  }
};

assert.equal(Array.prototype.find.call(object, (v) => {
  callbackCalls++;
  return v === 'a';
}), 'a');
assert.equal(lengthCalls, 1);
assert.equal(itemCalls, 1);
assert.equal(callbackCalls, 3);
<|endoftext|>


<commit_before>import * as eva from '@eva-design/eva';
import { ApplicationProvider, IconRegistry, Text } from '@ui-kitten/components';
import { EvaIconsPack } from '@ui-kitten/eva-icons';
import * as SplashScreen from 'expo-splash-screen';
import * as Updates from 'expo-updates';
import * as React from 'react';
import { LogBox, View } from 'react-native';
import ErrorBoundary from 'react-native-error-boundary';
import 'react-native-get-random-values';
import { QueryClient, QueryClientProvider } from 'react-query';
import * as Sentry from 'sentry-expo';
import { AuthContextProvider } from './auth/context';
import AppNavigator from './components/AppNavigator';
import { default as theme } from './custom-theme.json';
import packs from './services/icons';

const queryClient = new QueryClient();

Sentry.init({
  dsn: 'https://2a36299ed52445d3b8c2817800c39dc7@o297301.ingest.sentry.io/5880366',
  environment: Updates.releaseChannel,
});

if (__DEV__) {
  /*
    react-query causes these types of logs to be shown but they say that they are nothing to worry about
    this may be able to be removed after upgrading to RN 0.65
    ref: https://github.com/tannerlinsley/react-query/issues/1259
  */
  LogBox.ignoreLogs(['Setting a timer']);
}

export default function App() {
  const [authIsReady, setAuthIsReady] = React.useState(false);
  const splashIsHidden = React.useRef(false);

  React.useEffect(() => {
    if (!splashIsHidden.current) {
      SplashScreen.preventAutoHideAsync();
    }
  }, []);

  const onReady = () => {
    console.log('onReady', authIsReady, splashIsHidden.current);
    if (authIsReady && !splashIsHidden.current) {
      SplashScreen.hideAsync();
      splashIsHidden.current = true;
    }
  };

  const onError = (error) => {
    Sentry.Native.captureException(error);
    SplashScreen.hideAsync();
  };

  return (
    <ErrorBoundary onError={onError}>
      <IconRegistry icons={[EvaIconsPack, ...packs]} />
      <ApplicationProvider {...eva} theme={{ ...eva.light, ...theme }}>
        <QueryClientProvider client={queryClient}>
          <AuthContextProvider onReady={() => setAuthIsReady(true)}>
            {authIsReady ? (
              <View onLayout={onReady} style={{ flex: 1 }}>
                <AppNavigator />
              </View>
            ) : (
              <Text>Loading...</Text>
            )}
          </AuthContextProvider>
        </QueryClientProvider>
      </ApplicationProvider>
    </ErrorBoundary>
  );
}
<commit_msg>feat(front): make sure that status bar is visible in dark mode<commit_after>import * as eva from '@eva-design/eva';
import { ApplicationProvider, IconRegistry, Text } from '@ui-kitten/components';
import { EvaIconsPack } from '@ui-kitten/eva-icons';
import * as SplashScreen from 'expo-splash-screen';
import { StatusBar } from 'expo-status-bar';
import * as Updates from 'expo-updates';
import * as React from 'react';
import { LogBox, View } from 'react-native';
import ErrorBoundary from 'react-native-error-boundary';
import 'react-native-get-random-values';
import { QueryClient, QueryClientProvider } from 'react-query';
import * as Sentry from 'sentry-expo';
import { AuthContextProvider } from './auth/context';
import AppNavigator from './components/AppNavigator';
import { default as theme } from './custom-theme.json';
import packs from './services/icons';

const queryClient = new QueryClient();

Sentry.init({
  dsn: 'https://2a36299ed52445d3b8c2817800c39dc7@o297301.ingest.sentry.io/5880366',
  environment: Updates.releaseChannel,
});

if (__DEV__) {
  /*
    react-query causes these types of logs to be shown but they say that they are nothing to worry about
    this may be able to be removed after upgrading to RN 0.65
    ref: https://github.com/tannerlinsley/react-query/issues/1259
  */
  LogBox.ignoreLogs(['Setting a timer']);
}

export default function App() {
  const [authIsReady, setAuthIsReady] = React.useState(false);
  const splashIsHidden = React.useRef(false);

  React.useEffect(() => {
    if (!splashIsHidden.current) {
      SplashScreen.preventAutoHideAsync();
    }
  }, []);

  const onReady = () => {
    console.log('onReady', authIsReady, splashIsHidden.current);
    if (authIsReady && !splashIsHidden.current) {
      SplashScreen.hideAsync();
      splashIsHidden.current = true;
    }
  };

  const onError = (error) => {
    Sentry.Native.captureException(error);
    SplashScreen.hideAsync();
  };

  return (
    <ErrorBoundary onError={onError}>
      <IconRegistry icons={[EvaIconsPack, ...packs]} />
      <ApplicationProvider {...eva} theme={{ ...eva.light, ...theme }}>
        <QueryClientProvider client={queryClient}>
          <AuthContextProvider onReady={() => setAuthIsReady(true)}>
            {authIsReady ? (
              <View onLayout={onReady} style={{ flex: 1 }}>
                <AppNavigator />
              </View>
            ) : (
              <Text>Loading...</Text>
            )}
          </AuthContextProvider>
        </QueryClientProvider>
      </ApplicationProvider>
      <StatusBar style="dark" />
    </ErrorBoundary>
  );
}
<|endoftext|>


<commit_before>'use strict';

var util = require('util');

module.exports = {
    name: 'spaceAfterPropertyName',
    nodeTypes: ['decl'],
    message: 'Colon after property should%s be preceded by %s space.',

    lint: function spaceAfterPropertyNameLinter (config, node) {

        var styles = {
            'no_space': /^:/,
            'one_space': /^\s:/
        };

        if (config.style && !styles[config.style]) {
            throw new Error('Invalid setting value for spaceAfterPropertyName: ' + config.style);
        }

        if (!styles[config.style].test(node.raws.between)) {
            return [{
                column: node.source.start.column + node.prop.length,
                line: node.source.start.line,
                message: util.format(
                    this.message,
                    config.style === 'no_space' ? ' not' : '',
                    config.style === 'no_space' ? 'any' : 'one'
                )
            }];
        }
    }
};
<commit_msg>Rewrite spaceAfterPropertyName to ES6<commit_after>'use strict';

const util = require('util');

module.exports = {
    name: 'spaceAfterPropertyName',
    nodeTypes: ['decl'],
    message: 'Colon after property should%s be preceded by %s space.',

    lint: function spaceAfterPropertyNameLinter (config, node) {
        const styles = {
            'no_space': /^:/,
            'one_space': /^\s:/
        };

        if (config.style && !styles[config.style]) {
            throw new Error(`Invalid setting value for spaceAfterPropertyName: ${ config.style }`);
        }

        if (!styles[config.style].test(node.raws.between)) {
            return [{
                column: node.source.start.column + node.prop.length,
                line: node.source.start.line,
                message: util.format(
                    this.message,
                    config.style === 'no_space' ? ' not' : '',
                    config.style === 'no_space' ? 'any' : 'one'
                )
            }];
        }
    }
};
<|endoftext|>


<commit_before>var expect = require('chai').expect,
  sinon = require('sinon'),
  inherits = require('util').inherits,
  EventEmitter = require('events').EventEmitter,
  AppService = require('../../../../lib/daemon/service/AppService')

describe('AppService', function() {
  var service

  beforeEach(function() {
    service = new AppService()
    service._config = {
      deployments: {
        enabled: true
      }
    }
    service._applicationStore = {
      create: sinon.stub(),
      warn: sinon.stub(),
      error: sinon.stub(),
      debug: sinon.stub(),
      log: sinon.stub()
    }
  })

  it('should deploy a project', function() {

  })
})
<commit_msg>added tests for deploying apps<commit_after>var expect = require('chai').expect,
  sinon = require('sinon'),
  inherits = require('util').inherits,
  EventEmitter = require('events').EventEmitter,
  AppService = require('../../../../lib/daemon/service/AppService')

describe('AppService', function() {
  var service

  beforeEach(function() {
    service = new AppService()
    service._config = {
      deployments: {
        enabled: true
      }
    }
    service._applicationStore = {
      find: sinon.stub(),
      create: sinon.stub(),
      save: sinon.stub(),
      remove: sinon.stub()
    }
  })

  it('should deploy a project', function(done) {
    var name = 'foo'
    var url = 'bar'
    var user = 'baz'
    var onOut = sinon.stub()
    var onErr = sinon.stub()
    var appInfo = {
      clone: sinon.stub(),
      installDependencies: sinon.stub()
    }

    appInfo.clone.callsArg(2)
    appInfo.installDependencies.callsArg(2)

    service._applicationStore.save.callsArg(0)

    service._applicationStore.create.withArgs([{
      name: name,
      url: url,
      user: user
    }]).callsArgWith(1, undefined, appInfo)

    var eventEmitted = false

    service.once('app:installed', function() {
      eventEmitted = true
    })

    service.deploy(name, url, user, onOut, onErr, function(error) {
      expect(error).to.not.exist
      expect(service._applicationStore.find.withArgs('name', name).called).to.be.true
      expect(eventEmitted).to.be.true

      done()
    })
  })

  it('should not deploy a project with a duplicate name', function(done) {
    var name = 'foo'
    var url = 'bar'
    var user = 'baz'
    var onOut = sinon.stub()
    var onErr = sinon.stub()

    service._applicationStore.find.withArgs('name', name).returns({})

    service.deploy(name, url, user, onOut, onErr, function(error) {
      expect(error.message).to.contain('already exists')

      done()
    })
  })

  it('should pass error encountered when creating an application', function(done) {
    var name = 'foo'
    var url = 'bar'
    var user = 'baz'
    var onOut = sinon.stub()
    var onErr = sinon.stub()
    var appCreationError = new Error('urk!')

    service._applicationStore.create.withArgs([{
      name: name,
      url: url,
      user: user
    }]).callsArgWith(1, appCreationError)

    service.deploy(name, url, user, onOut, onErr, function(error) {
      expect(error).to.equal(appCreationError)

      done()
    })
  })

  it('should remove repo when cloning or installing fails', function(done) {
    var name = 'foo'
    var url = 'bar'
    var user = 'baz'
    var onOut = sinon.stub()
    var onErr = sinon.stub()
    var appInfo = {
      clone: sinon.stub(),
      installDependencies: sinon.stub(),
      remove: sinon.stub()
    }
    var installError = new Error('urk!')

    appInfo.clone.callsArg(2)
    appInfo.installDependencies.callsArgWith(2, installError)
    appInfo.remove.callsArg(0)

    service._applicationStore.create.withArgs([{
      name: name,
      url: url,
      user: user
    }]).callsArgWith(1, undefined, appInfo)

    var eventEmitted = false

    service.once('app:installed', function() {
      eventEmitted = true
    })

    service.deploy(name, url, user, onOut, onErr, function(error) {
      expect(error).to.equal(installError)

      done()
    })
  })
})
<|endoftext|>


<commit_before>'use strict'

import { buildLiteralFromJs, sfRound } from './utils'

// Math Operators

export const sf$add = (value1, value2) => {
  return buildLiteralFromJs(value1.value + value2.value)
}

export const sf$subtract = (value1, value2) => {
  return buildLiteralFromJs(value1.value - value2.value)
}

export const sf$multiply = (value1, value2) => {
  return buildLiteralFromJs(value1.value * value2.value)
}

export const sf$divide = (value1, value2) => {
  return buildLiteralFromJs(value1.value / value2.value)
}

export const sf$exponentiate = (value1, value2) => {
  return buildLiteralFromJs(Math.pow(value1.value, value2.value))
}

// Logical Operators and Functions

export const sf$and = (logical1, logical2) => {
  return buildLiteralFromJs(logical1.value && logical2.value)
}

export const sf$or = (logical1, logical2) => {
  return buildLiteralFromJs(logical1.value || logical2.value)
}

export const sf$not = (logical) => {
  return buildLiteralFromJs(!logical.value)
}

export const sf$if = (logicalTest, valueIfTrue, valueIfFalse) => {
  return logicalTest.value ? valueIfTrue : valueIfFalse
}

// Math Functions

export const sf$abs = (number) => {
  return buildLiteralFromJs(Math.abs(number.value))
}

export const sf$ceiling = (number) => {
  return buildLiteralFromJs(Math.ceil(number.value))
}

export const sf$exp = (number) => {
  return buildLiteralFromJs(Math.exp(number.value))
}

export const sf$floor = (number) => {
  return buildLiteralFromJs(Math.floor(number.value))
}

export const sf$ln = (number) => {
  return buildLiteralFromJs(Math.log(number.value))
}

export const sf$log = (number) => {
  return buildLiteralFromJs(Math.log10(number.value))
}

export const sf$max = (...numbers) => {
  let values = numbers.map((v) => v.value)
  return buildLiteralFromJs(Math.max(...values))
}

export const sf$min = (...numbers) => {
  let values = numbers.map((v) => v.value)
  return buildLiteralFromJs(Math.min(...values))
}

export const sf$mod = (number, divisor) => {
  return buildLiteralFromJs(number.value % divisor.value)
}

export const sf$round = (number, numDigits) => {
  return buildLiteralFromJs(sfRound(number.value, numDigits.value))
}

export const sf$sqrt = (number) => {
  return buildLiteralFromJs(Math.sqrt(number.value))
}

// Text Functions

export const sf$begins = (text, compareText) => {
  return buildLiteralFromJs(text.value.startsWith(compareText.value))
}

export const sf$br = () => {
  return buildLiteralFromJs('\n')
}

export const sf$contains = (text, compareText) => {
  return buildLiteralFromJs(text.value.includes(compareText.value))
}

export const sf$left = (text, numChars) => {
  return sf$mid(text, buildLiteralFromJs(1), numChars)
}

export const sf$len = (text) => {
  return buildLiteralFromJs(text.value.length)
}

export const sf$mid = (text, start_num, numChars) => {
  return buildLiteralFromJs(text.value.substr(start_num.value - 1, numChars.value))
}

export const sf$right = (text, numChars) => {
  return buildLiteralFromJs(text.value.substr(text.value.length - numChars.value))
}

export const sf$trim = (text) => {
  return buildLiteralFromJs(text.value.trim())
}
<commit_msg>change to camelCase<commit_after>'use strict'

import { buildLiteralFromJs, sfRound } from './utils'

// Math Operators

export const sf$add = (value1, value2) => {
  return buildLiteralFromJs(value1.value + value2.value)
}

export const sf$subtract = (value1, value2) => {
  return buildLiteralFromJs(value1.value - value2.value)
}

export const sf$multiply = (value1, value2) => {
  return buildLiteralFromJs(value1.value * value2.value)
}

export const sf$divide = (value1, value2) => {
  return buildLiteralFromJs(value1.value / value2.value)
}

export const sf$exponentiate = (value1, value2) => {
  return buildLiteralFromJs(Math.pow(value1.value, value2.value))
}

// Logical Operators and Functions

export const sf$and = (logical1, logical2) => {
  return buildLiteralFromJs(logical1.value && logical2.value)
}

export const sf$or = (logical1, logical2) => {
  return buildLiteralFromJs(logical1.value || logical2.value)
}

export const sf$not = (logical) => {
  return buildLiteralFromJs(!logical.value)
}

export const sf$if = (logicalTest, valueIfTrue, valueIfFalse) => {
  return logicalTest.value ? valueIfTrue : valueIfFalse
}

// Math Functions

export const sf$abs = (number) => {
  return buildLiteralFromJs(Math.abs(number.value))
}

export const sf$ceiling = (number) => {
  return buildLiteralFromJs(Math.ceil(number.value))
}

export const sf$exp = (number) => {
  return buildLiteralFromJs(Math.exp(number.value))
}

export const sf$floor = (number) => {
  return buildLiteralFromJs(Math.floor(number.value))
}

export const sf$ln = (number) => {
  return buildLiteralFromJs(Math.log(number.value))
}

export const sf$log = (number) => {
  return buildLiteralFromJs(Math.log10(number.value))
}

export const sf$max = (...numbers) => {
  let values = numbers.map((v) => v.value)
  return buildLiteralFromJs(Math.max(...values))
}

export const sf$min = (...numbers) => {
  let values = numbers.map((v) => v.value)
  return buildLiteralFromJs(Math.min(...values))
}

export const sf$mod = (number, divisor) => {
  return buildLiteralFromJs(number.value % divisor.value)
}

export const sf$round = (number, numDigits) => {
  return buildLiteralFromJs(sfRound(number.value, numDigits.value))
}

export const sf$sqrt = (number) => {
  return buildLiteralFromJs(Math.sqrt(number.value))
}

// Text Functions

export const sf$begins = (text, compareText) => {
  return buildLiteralFromJs(text.value.startsWith(compareText.value))
}

export const sf$br = () => {
  return buildLiteralFromJs('\n')
}

export const sf$contains = (text, compareText) => {
  return buildLiteralFromJs(text.value.includes(compareText.value))
}

export const sf$left = (text, numChars) => {
  return sf$mid(text, buildLiteralFromJs(1), numChars)
}

export const sf$len = (text) => {
  return buildLiteralFromJs(text.value.length)
}

export const sf$mid = (text, startNum, numChars) => {
  return buildLiteralFromJs(text.value.substr(startNum.value - 1, numChars.value))
}

export const sf$right = (text, numChars) => {
  return buildLiteralFromJs(text.value.substr(text.value.length - numChars.value))
}

export const sf$trim = (text) => {
  return buildLiteralFromJs(text.value.trim())
}
<|endoftext|>


<commit_before>/*
 * A bootstrap select box with pure angular backing
 * Allows arbitrary values from <input> or from a list of values
 * Valid attributes: ng-model,
 *
 * fzSelectItems:       Expects an Array or Function
 *                      The source list for the select component. If it is a
 *                      function, the return is expected to be either an
 *                      array or a $q promise.
 *                      If the source list is a $q, then the list will not sort
 *                      locally.
 *
 * fzRefresh:           Expects a function
 *                      Requires fzRefreshRate
 *                      signature should look something like:
 *                      function refresh(searchString)
 *                      If set, the component will call the supplied function
 *                      when it comes time to refresh the list.
 *
 * fzRefreshRate:       Expects integer
 *                      Requires fzRefresh
 *                      How often the component will call the refresh function
 *
 * fzMatchAttribute:    Expects string
 *                      if the list contains objects, this is the attribute name
 *                      of the desired value EG: if your list looks like
 *                      [ { a: 'val' }, .... ] setting fzMatchAttribute to 'a',
 *                      the component will return the value of a of the selected
 *                      item.
 *
 * fzReturnAttribute:   Expects string
 *                      Useful if you have a list like [ {name: '', email: ''}
 *                      and want to search by name, but return the email
 *
 * fzIncludeNullOption: Expects boolean
 *                      Set to true if you want a null item prepended to the
 *                      result list to allow for a blank option
 *
 * fzReturnObjects:     Expects boolean
 *                      Component will return objects, even for arbitrary input.
 *                      This is useful in conjunction with fzReturnAttribute.
 *                      If you are searching a list of contacts by name, but
 *                      also want to be able to return some arbitrary email,
 *                      the component will return an object like:
 *                      { email: 'asd@asd.com' } instead of just a string value.
 */

angular.module( "fzSelect", [] )
.directive( "fzSelect", ['$filter', '$timeout', '$parse', '$interval',
  function($filter, $timeout, $parse, $interval){
    return {
      restrict: 'EA',
      scope: true,
      template:
'
'+
  '<input class="fz-select-input" ng-model="searchString" ' +
    'ng-keydown="inputKeyDown($event)"></input>'+
  '' +
    '<button class="fz-select-button" ng-click="showAll()" > ' +
      '&#9660 ' +
      '&#9650 ' +
    '</button>'+
  '' +
'
'+
'
 '+
  '
 '+
    '
{{getItemDisplayString(item)}}
'+
  '
' +
'
',

      link: function($scope, element, attrs){

        function initilizeError(message){
          element.html('Error initlizing component.');
          throw message;
        };

        angular.element(element).addClass('fz-select-component');

        var itemsGetter = $parse(attrs.fzSelectItems);
        var valueGetter = $parse(attrs.ngModel);
        var valueSetter = valueGetter.assign;

        $scope.orderObject = {attribute: '', reverse: false};
        var itemAttributeName = null;
        var itemAttributeGetter = null;
        if( attrs.hasOwnProperty('fzMatchAttribute') ){
          itemAttributeGetter = $parse(attrs.fzMatchAttribute);
          itemAttributeName = attrs.fzMatchAttribute;
          $scope.orderObject.attribute = attrs.fzMatchAttribute;
        }

        var itemReturnAttributeName = "value";
        var itemReturnAttributeGetter = null;
        if( attrs.hasOwnProperty('fzReturnAttribute') ){
          itemReturnAttributeGetter = $parse(attrs.fzReturnAttribute);
          itemReturnAttributeName = attrs.fzReturnAttribute;
        } else if( attrs.hasOwnProperty('fzMatchAttribute') ){
          itemReturnAttributeGetter = $parse(attrs.fzMatchAttribute);
          itemReturnAttributeName = attrs.fzMatchAttribute;
        }

        var returnObjects = false;
        if( attrs.hasOwnProperty("fzReturnObjects") ){
          returnObjects = attrs.fzReturnObjects == "true";
        }

        //Either refreshRate and Refresh are set, or neither
        //are set
        if(!(
            (attrs.hasOwnProperty("fzRefreshRate") &&
             attrs.hasOwnProperty("fzRefresh")) ||
            (!attrs.hasOwnProperty("fzRefreshRate") &&
             !attrs.hasOwnProperty("fzRefresh")))
        ){
          initilizeError(
            "fzSelect have both fzRefreshRate and fzRefresh or " +
            "have neither set." )
        }

        // item list is async
        var isAsync =  attrs.hasOwnProperty("fzRefresh");

        var refreshRate = null;
        if(attrs.hasOwnProperty("fzRefreshRate"))
          refreshRate = parseInt( attrs.fzRefreshRate );

        var refreshFunction = null;
        var refreshPromise = null;
        if(attrs.hasOwnProperty("fzRefresh"))
          refreshFunction = $parse(attrs.fzRefresh);

        var includeNullOption = false;
        if(attrs.hasOwnProperty("fzIncludeNullOption"))
          includeNullOption = attrs.fzIncludeNullOption == "true";

        $scope.selectedRowIndex = 0;
        $scope.searchString = valueGetter($scope);
        $scope.filteredItems = [];
        $scope.resultsVisible = {value: false};
        $scope.selectedValue = null;
        var valueWasSelected = false;

        $scope.showResults = function(show){
          $timeout(function(){
            $scope.resultsVisible.value = show;
          });
        };

        $scope.getItemDisplayString = function(item){
          if( itemAttributeGetter != null  ){
            return itemAttributeGetter(item);
          }else{
            return item;
          }
        };

        $scope.showAll = function(){
          //if the results are visible, don't show
          if($scope.resultsVisible.value)
            $scope.showResults(false);
          else
            $scope.filterItems(true);
        };

        $scope.updateSourceValue = function(){
          if($scope.selectedValue != null){
            if( itemReturnAttributeGetter != null  && !returnObjects){
              valueSetter( $scope,
                  itemReturnAttributeGetter($scope.selectedValue));
            } else {
              valueSetter($scope, $scope.selectedValue);
            }
          } else {
            if(returnObjects){
              var returnObject = {}
              returnObject[itemReturnAttributeName] = $scope.searchString;
              valueSetter($scope, returnObject);
            } else {
              valueSetter($scope, $scope.searchString);
            }
          }
        };

        $scope.resultsKeydown = function($event, item){
          function moveResults(isUp){
            $event.preventDefault();
            if( isUp )
              angular.element(angular.element($event.target).prev()).focus();
            else
              angular.element(angular.element($event.target).next()).focus();
          }
          switch($event.keyCode){
            case 40:
              moveResults(false);
              break;
            case 38:
              moveResults(true);
              break;
            case 13:
              $scope.resultItemClicked(item);
            default:
              return;
          }
        }

        function getResultsContainer(){
          var children = angular.element(element).children();
          var container = null;
          angular.forEach(children, function(child){
            if( angular.element(child).hasClass( 'fz-select-results-wrapper' ) )
              container = angular.element(child).children()[0];
          });
          return container;
        }

        $scope.resultFocused = function($event, item){
          $scope.selectedRowIndex = $scope.filteredItems.indexOf(item);
        }

        var focusResults = function($event){
          $scope.resultsVisible.value = true;
          if($event != undefined)
            $event.preventDefault();
          $timeout(function(){
            var container = getResultsContainer()
            if( container != null )
              angular.element(angular.element(container).children()[0]).focus();
          });
        };

        $scope.inputKeyDown = function($event){

          switch($event.keyCode){
            case 40:
              focusResults($event);
              break;
            case 38:
              focusResults($event);
              break;

            default:
              return;
          }
        };

        $scope.resultItemClicked = function(item){
          $scope.selectedValue = item;
          $scope.searchString = $scope.getItemDisplayString(item);
          valueWasSelected = true;
          $scope.updateSourceValue();
          $scope.showResults(false);
        };

        function orderItems(items){
          return $filter('orderBy')(
              items,
              $scope.orderObject.attribute,
              $scope.orderObject.reverse);
        }

        function getItems(){
          return itemsGetter($scope);
        }

        // update items, should not be used for async
        function updateItems(onlyOrder){

          var tempList = getItems();

          //if we are filtering, put it
          if(!onlyOrder)
            tempList = $filter('filter')(tempList, $scope.searchString);

          //order the items if it's not async
          tempList = orderItems(tempList);

          if(includeNullOption)
            tempList.unshift(null);

          $scope.filteredItems = tempList;
        }

        var initialFilter = true;
        /*
         * Filter the item list based on the search string
         * This method is the only place showResults(true) should be called
         * onlyOrder: boolean; only order the list, do not filter
         */
        $scope.filterItems = function(onlyOrder){

          var searchObject = {};
          if( itemAttributeName != null )
            searchObject[itemAttributeName] = $scope.searchString;
          else
            searchObject = $scope.searchString;

          if( !isAsync )
            updateItems(onlyOrder);

          //Do not show results if the search string is set to null and
          //we're not only ordering
          if( $scope.searchString == null && !onlyOrder ){
            $scope.showResults(false);
          } else {
            if( onlyOrder){
              $scope.showResults(true);
            //If it's the initial filter, do not show items.
            //This prevents the results from being shown when the component
            //is initilized
            } else if( $scope.searchString.length > 0
                && !$scope.resultsVisible.value && !initialFilter ) {
              $scope.showResults(true);
            } else if( $scope.searchString.length == 0 &&
                       $scope.resultsVisible.value ){
              $scope.showResults(false);
            }
            initialFilter = false;
          }
        };

        var searchStringChanged = false;

        $scope.$watch('searchString', function(){
          searchStringChanged = true;
          $scope.filterItems();
          $scope.selectedRowIndex = 0;
          if( !valueWasSelected )
            $scope.selectedValue = null;
          else
            valueWasSelected = false;
          $scope.updateSourceValue();
        }, true);

        $scope.$watch('selectedRowIndex', function(){
          if($scope.selectedRowIndex < 0 ||
            $scope.selectedRowIndex > ($scope.filteredItems.length - 1))
            $scope.selectedRowIndex = 0;
        }, true);

        $scope.$on('$destroy', function(){
          $interval.cancel(refreshPromise);
        });

        function callRefreshFunction(searchString){
          refreshFunction($scope)(searchString);
        };

        // code to run once setup is finished
        function initComponent(){
          if(isAsync){
            refreshPromise = $interval(function(){
              if(searchStringChanged)
                callRefreshFunction($scope.searchString);
              searchStringChanged = false;
              $scope.filteredItems = getItems();
            }, refreshRate);

          }
        }
        initComponent();
      }
    }
  }
])
<commit_msg>fixing issue with initializing search string<commit_after>/*
 * A bootstrap select box with pure angular backing
 * Allows arbitrary values from <input> or from a list of values
 * Valid attributes: ng-model,
 *
 * fzSelectItems:       Expects an Array or Function
 *                      The source list for the select component. If it is a
 *                      function, the return is expected to be either an
 *                      array or a $q promise.
 *                      If the source list is a $q, then the list will not sort
 *                      locally.
 *
 * fzRefresh:           Expects a function
 *                      Requires fzRefreshRate
 *                      signature should look something like:
 *                      function refresh(searchString)
 *                      If set, the component will call the supplied function
 *                      when it comes time to refresh the list.
 *
 * fzRefreshRate:       Expects integer
 *                      Requires fzRefresh
 *                      How often the component will call the refresh function
 *
 * fzMatchAttribute:    Expects string
 *                      if the list contains objects, this is the attribute name
 *                      of the desired value EG: if your list looks like
 *                      [ { a: 'val' }, .... ] setting fzMatchAttribute to 'a',
 *                      the component will return the value of a of the selected
 *                      item.
 *
 * fzReturnAttribute:   Expects string
 *                      Useful if you have a list like [ {name: '', email: ''}
 *                      and want to search by name, but return the email
 *
 * fzIncludeNullOption: Expects boolean
 *                      Set to true if you want a null item prepended to the
 *                      result list to allow for a blank option
 *
 * fzReturnObjects:     Expects boolean
 *                      Component will return objects, even for arbitrary input.
 *                      This is useful in conjunction with fzReturnAttribute.
 *                      If you are searching a list of contacts by name, but
 *                      also want to be able to return some arbitrary email,
 *                      the component will return an object like:
 *                      { email: 'asd@asd.com' } instead of just a string value.
 */

angular.module( "fzSelect", [] )
.directive( "fzSelect", ['$filter', '$timeout', '$parse', '$interval',
  function($filter, $timeout, $parse, $interval){
    return {
      restrict: 'EA',
      scope: true,
      template:
'
'+
  '<input class="fz-select-input" ng-model="searchString" ' +
    'ng-keydown="inputKeyDown($event)"></input>'+
  '' +
    '<button class="fz-select-button" ng-click="showAll()" > ' +
      '&#9660 ' +
      '&#9650 ' +
    '</button>'+
  '' +
'
'+
'
 '+
  '
 '+
    '
{{getItemDisplayString(item)}}
'+
  '
' +
'
',

      link: function($scope, element, attrs){

        function initilizeError(message){
          element.html('Error initlizing component.');
          throw message;
        };

        angular.element(element).addClass('fz-select-component');

        var itemsGetter = $parse(attrs.fzSelectItems);
        var valueGetter = $parse(attrs.ngModel);
        var valueSetter = valueGetter.assign;

        $scope.orderObject = {attribute: '', reverse: false};
        var itemAttributeName = null;
        var itemAttributeGetter = null;
        if( attrs.hasOwnProperty('fzMatchAttribute') ){
          itemAttributeGetter = $parse(attrs.fzMatchAttribute);
          itemAttributeName = attrs.fzMatchAttribute;
          $scope.orderObject.attribute = attrs.fzMatchAttribute;
        }

        var itemReturnAttributeName = "value";
        var itemReturnAttributeGetter = null;
        if( attrs.hasOwnProperty('fzReturnAttribute') ){
          itemReturnAttributeGetter = $parse(attrs.fzReturnAttribute);
          itemReturnAttributeName = attrs.fzReturnAttribute;
        } else if( attrs.hasOwnProperty('fzMatchAttribute') ){
          itemReturnAttributeGetter = $parse(attrs.fzMatchAttribute);
          itemReturnAttributeName = attrs.fzMatchAttribute;
        }

        var returnObjects = false;
        if( attrs.hasOwnProperty("fzReturnObjects") ){
          returnObjects = attrs.fzReturnObjects == "true";
        }

        //Either refreshRate and Refresh are set, or neither
        //are set
        if(!(
            (attrs.hasOwnProperty("fzRefreshRate") &&
             attrs.hasOwnProperty("fzRefresh")) ||
            (!attrs.hasOwnProperty("fzRefreshRate") &&
             !attrs.hasOwnProperty("fzRefresh")))
        ){
          initilizeError(
            "fzSelect have both fzRefreshRate and fzRefresh or " +
            "have neither set." )
        }

        // item list is async
        var isAsync =  attrs.hasOwnProperty("fzRefresh");

        var refreshRate = null;
        if(attrs.hasOwnProperty("fzRefreshRate"))
          refreshRate = parseInt( attrs.fzRefreshRate );

        var refreshFunction = null;
        var refreshPromise = null;
        if(attrs.hasOwnProperty("fzRefresh"))
          refreshFunction = $parse(attrs.fzRefresh);

        var includeNullOption = false;
        if(attrs.hasOwnProperty("fzIncludeNullOption"))
          includeNullOption = attrs.fzIncludeNullOption == "true";

        $scope.selectedRowIndex = 0;

        $scope.filteredItems = [];
        $scope.resultsVisible = {value: false};
        $scope.selectedValue = null;
        var valueWasSelected = false;

        //initilize the search string value
        function initSearchString(){
          //if there is no return attribute specified, return the value
          if(itemReturnAttributeGetter == null){
            $scope.searchString = valueGetter($scope);
          } else if(itemAttributeGetter != null){
            $scope.searchString = itemAttributeGetter();
          } else {
            $scope.searchString = valueGetter();
          }
        }

        $scope.showResults = function(show){
          $timeout(function(){
            $scope.resultsVisible.value = show;
          });
        };

        $scope.getItemDisplayString = function(item){
          if( itemAttributeGetter != null  ){
            return itemAttributeGetter(item);
          }else{
            return item;
          }
        };

        $scope.showAll = function(){
          //if the results are visible, don't show
          if($scope.resultsVisible.value)
            $scope.showResults(false);
          else
            $scope.filterItems(true);
        };

        $scope.updateSourceValue = function(){
          if($scope.selectedValue != null){
            if( itemReturnAttributeGetter != null  && !returnObjects){
              valueSetter( $scope,
                  itemReturnAttributeGetter($scope.selectedValue));
            } else {
              valueSetter($scope, $scope.selectedValue);
            }
          } else {
            if(returnObjects){
              var returnObject = {}
              returnObject[itemReturnAttributeName] = $scope.searchString;
              valueSetter($scope, returnObject);
            } else {
              valueSetter($scope, $scope.searchString);
            }
          }
        };

        $scope.resultsKeydown = function($event, item){
          function moveResults(isUp){
            $event.preventDefault();
            if( isUp )
              angular.element(angular.element($event.target).prev()).focus();
            else
              angular.element(angular.element($event.target).next()).focus();
          }
          switch($event.keyCode){
            case 40:
              moveResults(false);
              break;
            case 38:
              moveResults(true);
              break;
            case 13:
              $scope.resultItemClicked(item);
            default:
              return;
          }
        }

        function getResultsContainer(){
          var children = angular.element(element).children();
          var container = null;
          angular.forEach(children, function(child){
            if( angular.element(child).hasClass( 'fz-select-results-wrapper' ) )
              container = angular.element(child).children()[0];
          });
          return container;
        }

        $scope.resultFocused = function($event, item){
          $scope.selectedRowIndex = $scope.filteredItems.indexOf(item);
        }

        var focusResults = function($event){
          $scope.resultsVisible.value = true;
          if($event != undefined)
            $event.preventDefault();
          $timeout(function(){
            var container = getResultsContainer()
            if( container != null )
              angular.element(angular.element(container).children()[0]).focus();
          });
        };

        $scope.inputKeyDown = function($event){

          switch($event.keyCode){
            case 40:
              focusResults($event);
              break;
            case 38:
              focusResults($event);
              break;

            default:
              return;
          }
        };

        $scope.resultItemClicked = function(item){
          $scope.selectedValue = item;
          $scope.searchString = $scope.getItemDisplayString(item);
          valueWasSelected = true;
          $scope.updateSourceValue();
          $scope.showResults(false);
        };

        function orderItems(items){
          return $filter('orderBy')(
              items,
              $scope.orderObject.attribute,
              $scope.orderObject.reverse);
        }

        function getItems(){
          return itemsGetter($scope);
        }

        // update items, should not be used for async
        function updateItems(onlyOrder){

          var tempList = getItems();

          //if we are filtering, put it
          if(!onlyOrder)
            tempList = $filter('filter')(tempList, $scope.searchString);

          //order the items if it's not async
          tempList = orderItems(tempList);

          if(includeNullOption)
            tempList.unshift(null);

          $scope.filteredItems = tempList;
        }

        var initialFilter = true;
        /*
         * Filter the item list based on the search string
         * This method is the only place showResults(true) should be called
         * onlyOrder: boolean; only order the list, do not filter
         */
        $scope.filterItems = function(onlyOrder){

          var searchObject = {};
          if( itemAttributeName != null )
            searchObject[itemAttributeName] = $scope.searchString;
          else
            searchObject = $scope.searchString;

          if( !isAsync )
            updateItems(onlyOrder);

          //Do not show results if the search string is set to null and
          //we're not only ordering
          if( $scope.searchString == null && !onlyOrder ){
            $scope.showResults(false);
          } else {
            if( onlyOrder){
              $scope.showResults(true);
            //If it's the initial filter, do not show items.
            //This prevents the results from being shown when the component
            //is initilized
            } else if( $scope.searchString.length > 0
                && !$scope.resultsVisible.value && !initialFilter ) {
              $scope.showResults(true);
            } else if( $scope.searchString.length == 0 &&
                       $scope.resultsVisible.value ){
              $scope.showResults(false);
            }
            initialFilter = false;
          }
        };

        var searchStringChanged = false;

        $scope.$watch('searchString', function(){
          searchStringChanged = true;
          $scope.filterItems();
          $scope.selectedRowIndex = 0;
          if( !valueWasSelected )
            $scope.selectedValue = null;
          else
            valueWasSelected = false;
          $scope.updateSourceValue();
        }, true);

        $scope.$watch('selectedRowIndex', function(){
          if($scope.selectedRowIndex < 0 ||
            $scope.selectedRowIndex > ($scope.filteredItems.length - 1))
            $scope.selectedRowIndex = 0;
        }, true);

        $scope.$on('$destroy', function(){
          $interval.cancel(refreshPromise);
        });

        function callRefreshFunction(searchString){
          refreshFunction($scope)(searchString);
        };

        // code to run once setup is finished
        function initComponent(){
          if(isAsync){
            refreshPromise = $interval(function(){
              if(searchStringChanged)
                callRefreshFunction($scope.searchString);
              searchStringChanged = false;
              $scope.filteredItems = getItems();
            }, refreshRate);

          }
        }
        initComponent();
      }
    }
  }
])
<|endoftext|>


<commit_before>var __$0, __$1, __$2, __$3, __$4, __$5, __$6, __$7, __$8, __$9, __$10, __$11, __$12, __$13, __$14, __$15, __$16, __$17, __$18, __$19, __$20, __$21, __$22, __$23, __$24, __$25, __$26, __$28; (__$0 = foo, a = (__$1 = _esdown.arrayd(__$0), __$1.at(1, 0)), b = __$1.at(1, 1), __$0);
(__$2 = foo, a = (__$3 = _esdown.arrayd(__$2), __$3.at(1, 0)), __$2);
((__$4 = foo, a = (__$5 = _esdown.arrayd(__$4), __$5.at(1, 0)), __$4));
(__$6 = foo, a = (__$7 = _esdown.arrayd(__$6), __$7.at(1, 0)), b = __$7.at(2, 2), __$6);
(__$8 = foo, a = (__$9 = _esdown.arrayd(__$8), __$9.at(1, 0)), b = __$9.rest(1, 1), __$8);
(__$10 = foo, a = (__$11 = _esdown.arrayd(__$10), __$11.at(2, 1)), __$10);

((__$12 = foo, a = (__$13 = _esdown.objd(__$12), __$13.a), c = __$13.b, __$12));
((__$14 = foo, b = (__$15 = _esdown.objd(__$14), __$16 = _esdown.arrayd(__$15.a), __$16.at(1, 0)), c = __$16.at(1, 1), __$14));
((__$17 = foo, a = (__$18 = _esdown.objd(__$17), __$18["a"]), b = __$18[0], __$17));

((__$19 = foo, y = (__$20 = _esdown.objd(__$19), __$21 = __$20[x], __$21 === void 0 ? 1 : __$21), __$19));

var __$_;
var __$_;

var a = (__$25 = _esdown.arrayd(foo), __$25.at(1, 0)), b = __$25.at(1, 1),
    c = (__$26 = _esdown.objd(foo), __$26.c), d = __$26.c;

function f(__$0) { var __$1; if (__$0 === void 0) __$0 = c; var a = (__$1 = _esdown.arrayd(__$0), __$1.at(1, 0)), b = __$1.at(1, 1); }
function f(__$0) { var __$1; if (__$0 === void 0) __$0 = d; var a = (__$1 = _esdown.objd(__$0), __$1.a), c = __$1.b; }

(function(__$0) { var __$1; var a = (__$1 = _esdown.arrayd(__$0), __$1.at(1, 0)), b = __$1.at(1, 1); });
(function(__$0) { var __$2; for (var args = [], __$1 = 1; __$1 < arguments.length; ++__$1) args.push(arguments[__$1]); var a = (__$2 = _esdown.arrayd(__$0), __$2.at(1, 0)), b = __$2.at(1, 1); return foo; });

try { x() }
catch (__$27) { let m = (__$28 = _esdown.arrayd(__$27), __$28.at(1, 0));  }
<commit_msg>Fix an outdated translation test.<commit_after>var __$0, __$1, __$2, __$3, __$4, __$5, __$6, __$7, __$8, __$9, __$10, __$11, __$12, __$13, __$14, __$15, __$16, __$17, __$18, __$19, __$20, __$21, __$22, __$23, __$24, __$25, __$26, __$28; (__$0 = foo, a = (__$1 = _esdown.arrayd(__$0), __$1.at(1, 0)), b = __$1.at(1, 1), __$0);
(__$2 = foo, a = (__$3 = _esdown.arrayd(__$2), __$3.at(1, 0)), __$2);
((__$4 = foo, a = (__$5 = _esdown.arrayd(__$4), __$5.at(1, 0)), __$4));
(__$6 = foo, a = (__$7 = _esdown.arrayd(__$6), __$7.at(1, 0)), b = __$7.at(2, 2), __$6);
(__$8 = foo, a = (__$9 = _esdown.arrayd(__$8), __$9.at(1, 0)), b = __$9.rest(1, 1), __$8);
(__$10 = foo, a = (__$11 = _esdown.arrayd(__$10), __$11.at(2, 1)), __$10);

((__$12 = foo, a = (__$13 = _esdown.objd(__$12), __$13.a), c = __$13.b, __$12));
((__$14 = foo, b = (__$15 = _esdown.objd(__$14), __$16 = _esdown.arrayd(__$15.a), __$16.at(1, 0)), c = __$16.at(1, 1), __$14));
((__$17 = foo, a = (__$18 = _esdown.objd(__$17), __$18["a"]), b = __$18[0], __$17));

((__$19 = foo, y = (__$20 = _esdown.objd(__$19), __$21 = __$20[x], __$21 === void 0 ? 1 : __$21), __$19));

var __$_;
var __$_;

var a = (__$25 = _esdown.arrayd(foo), __$25.at(1, 0)), b = __$25.at(1, 1),
    c = (__$26 = _esdown.objd(foo), __$26.c), d = __$26.c;

function f(__$0) { var __$1; if (__$0 === void 0) __$0 = c; var a = (__$1 = _esdown.arrayd(__$0), __$1.at(1, 0)), b = __$1.at(1, 1); }
function f(__$0) { var __$1; if (__$0 === void 0) __$0 = d; var a = (__$1 = _esdown.objd(__$0), __$1.a), c = __$1.b; }

(function(__$0) { var __$1; var a = (__$1 = _esdown.arrayd(__$0), __$1.at(1, 0)), b = __$1.at(1, 1); });
(function(__$0) { var __$2; for (var args = [], __$1 = 1; __$1 < arguments.length; ++__$1) args.push(arguments[__$1]); var a = (__$2 = _esdown.arrayd(__$0), __$2.at(1, 0)), b = __$2.at(1, 1); return foo; });

try { x() }
catch (__$27) { var m$0 = (__$28 = _esdown.arrayd(__$27), __$28.at(1, 0));  }
<|endoftext|>


<commit_before>import '../../../src/index';

describe('webcomponents/initialisation', function () {

  it('web components are initialised with the polyfill', function () {
    if (document.registerElement) {
      var x = document.registerElement('x-wc', {
        prototype: {
          hasPrototype: true,
          createdCallback: function () {
            this.created = true;
          }
        }
      });

      var div = document.createElement('div');
      div.innerHTML += '<x-wc></x-wc>';

      var el = div.querySelector('x-wc');
      expect(el.hasPrototype).to.equal(true);
      expect(el.created).to.equal(true);
    }
  });
});
<commit_msg>Remove unused variable<commit_after>import '../../../src/index';

describe('webcomponents/initialisation', function () {

  it('web components are initialised with the polyfill', function () {
    if (document.registerElement) {
      document.registerElement('x-wc', {
        prototype: {
          hasPrototype: true,
          createdCallback: function () {
            this.created = true;
          }
        }
      });

      var div = document.createElement('div');
      div.innerHTML += '<x-wc></x-wc>';

      var el = div.querySelector('x-wc');
      expect(el.hasPrototype).to.equal(true);
      expect(el.created).to.equal(true);
    }
  });
});
<|endoftext|>


<commit_before>import {frameworks, url, setOptions, initSurvey, getSurveyResult} from "../settings";
import {Selector, ClientFunction} from 'testcafe';
const assert = require('assert');
const title = `standardValidators`;

const json = {
    questions: [
        { type: "text", name: "email", title: "Please enter your e-mail", isRequired: true, validators: [{type:"email"}]},
        { type: "multipletext", name: "pricelimit", title: "What is the... ", isRequired: true, colCount: 2,
            items: [{ name: "leastamount", title: "The least amount you have ever paid for a computer",
                validators: [{ type: "numeric", minValue: 10, maxValue: 10000 }]
            },
                {  name: "mostamount", title: "The most amount you have ever paid for a computer",
                    validators: [{ type: "numeric", minValue: 10, maxValue: 10000 }]
                }]
        },
        { type: "comment", name: "firstcomputer", title: "Please tell us about your first computer", isRequired: true,
            validators: [{type:"text", minLength:20}]}
    ]
};

frameworks.forEach( (framework) => {
    fixture `${framework} ${title}`

        .page `${url}${framework}`

        .beforeEach( async t => {
            await initSurvey(framework, json);
        });

    test(`check validation`, async t => {
        const getError = Selector((text, index) => {
            var nodes = [];
            document.querySelectorAll("*").forEach(function(node) {
                if (node.innerHTML === text) nodes.push(node);
            });

            return nodes[index]
        });

        const getTextInputByIndex = Selector((index) =>
            document.querySelectorAll('div input[type=text]')[index]);
        const getTextarea = Selector(() =>
            document.querySelector('textarea'));
        let surveyResult;

        await t
            .click(`input[value="Complete"]`)
            .hover(getError(`Please answer the question.`, 0))
            .hover(getError(`Please answer the question.`, 1))
            .hover(getError(`Please answer the question.`, 2));

        await t
            .typeText(await getTextInputByIndex(0), `wombat`)
            .click(`input[value="Complete"]`)
            .hover(getError(`Please enter a valid e-mail address.`, 0))
            .hover(getError(`Please answer the question.`, 0))
            .hover(getError(`Please answer the question.`, 1));

        await t
            .typeText(await getTextInputByIndex(0), `wombat@mail.mail`, {replace: true})
            .typeText(await getTextInputByIndex(1), `wombat`)
            .click(`input[value="Complete"]`)
            .hover(getError(`The value should be numeric.`, 0))
            .hover(getError(`Please answer the question.`, 0));

        await t
            .typeText(await getTextInputByIndex(1), `0`, {replace: true})
            .typeText(await getTextInputByIndex(2), `10000`)
            .click(`input[value="Complete"]`)
            .hover(getError(`The 'The least amount you have ever paid for a computer' should be equal or more than 10 and equal or less than 10000`, 0))
            .hover(getError(`Please answer the question.`, 0));

        await t
            .typeText(await getTextInputByIndex(1), `10`, {replace: true})
            .typeText(await getTextarea(), `0123456789`)
            .click(`input[value="Complete"]`)
            .hover(getError(`Please enter at least 20 symbols.`, 0));

        await t
            .typeText(await getTextarea(), `01234567890123456789`, {replace: true})
            .click(`input[value="Complete"]`);

        surveyResult = await getSurveyResult();
        assert.deepEqual(surveyResult, {
            "email":"wombat@mail.mail",
            "firstcomputer":"01234567890123456789",
            "pricelimit":{
                "leastamount":10,
                "mostamount":10000
            }
        });
    });
});<commit_msg>testcafe<commit_after>import {frameworks, url, setOptions, initSurvey, getSurveyResult} from "../settings";
import {Selector, ClientFunction} from 'testcafe';
const assert = require('assert');
const title = `standardValidators`;

const json = {
    questions: [
        { type: "text", name: "email", title: "Please enter your e-mail", isRequired: true, validators: [{type:"email"}]},
        { type: "multipletext", name: "pricelimit", title: "What is the... ", isRequired: true, colCount: 2,
            items: [{ name: "leastamount", title: "The least amount you have ever paid for a computer",
                validators: [{ type: "numeric", minValue: 10, maxValue: 10000 }]
            },
                {  name: "mostamount", title: "The most amount you have ever paid for a computer",
                    validators: [{ type: "numeric", minValue: 10, maxValue: 10000 }]
                }]
        },
        { type: "comment", name: "firstcomputer", title: "Please tell us about your first computer", isRequired: true,
            validators: [{type:"text", minLength:20}]}
    ]
};

frameworks.forEach( (framework) => {
    fixture `${framework} ${title}`

        .page `${url}${framework}`

        .beforeEach( async t => {
            await initSurvey(framework, json);
        });

    test(`check validation`, async t => {
        const getError = Selector((text, index) => {
            var nodes = [];
            document.querySelectorAll("*").forEach(function(node) {
                if (node.innerHTML === text) nodes.push(node);
            });

            return nodes[index]
        });

        const getTextInputByIndex = Selector((index) =>
            document.querySelectorAll('div input[type=text]')[index]);
        const getTextarea = Selector(() =>
            document.querySelector('#sq_102 textarea'));
        let surveyResult;

        await t
            .click(`input[value="Complete"]`)
            .hover(getError(`Please answer the question.`, 0))
            .hover(getError(`Please answer the question.`, 1))
            .hover(getError(`Please answer the question.`, 2));

        await t
            .typeText(await getTextInputByIndex(0), `wombat`)
            .click(`input[value="Complete"]`)
            .hover(getError(`Please enter a valid e-mail address.`, 0))
            .hover(getError(`Please answer the question.`, 0))
            .hover(getError(`Please answer the question.`, 1));

        await t
            .typeText(await getTextInputByIndex(0), `wombat@mail.mail`, {replace: true})
            .typeText(await getTextInputByIndex(1), `wombat`)
            .click(`input[value="Complete"]`)
            .hover(getError(`The value should be numeric.`, 0))
            .hover(getError(`Please answer the question.`, 0));

        await t
            .typeText(await getTextInputByIndex(1), `0`, {replace: true})
            .typeText(await getTextInputByIndex(2), `10000`)
            .click(`input[value="Complete"]`)
            .hover(getError(`The 'The least amount you have ever paid for a computer' should be equal or more than 10 and equal or less than 10000`, 0))
            .hover(getError(`Please answer the question.`, 0));

        await t
            .typeText(await getTextInputByIndex(1), `10`, {replace: true})
            .typeText(await getTextarea(), `0123456789`)
            .click(`input[value="Complete"]`)
            .hover(getError(`Please enter at least 20 symbols.`, 0));

        await t
            .typeText(await getTextarea(), `01234567890123456789`, {replace: true})
            .click(`input[value="Complete"]`);

        surveyResult = await getSurveyResult();
        assert.deepEqual(surveyResult, {
            "email":"wombat@mail.mail",
            "firstcomputer":"01234567890123456789",
            "pricelimit":{
                "leastamount":10,
                "mostamount":10000
            }
        });
    });
});<|endoftext|>


<commit_before>/*===
TypeError
TypeError
TypeError
===*/

/* TypeError is required for cyclic structures. */

obj1 = { 'foo': 1 };
obj1.cycle = obj1;

obj2a = { 'foo': 1 };
obj2b = { 'bar': 2 };
obj2a.cycle = obj2b;
obj2b.cycle = obj2a;

obj3a = { 'foo': 1 };
obj3b = { 'bar': 2 };
obj3c = { 'quux': 3 };
obj3a.cycle = obj3b;
obj3b.cycle = obj3c;
obj3c.cycle = obj3a;

try {
    print(JSON.stringify(obj1));
} catch (e) {
    print(e.name);
}

try {
    print(JSON.stringify(obj2a));
} catch (e) {
    print(e.name);
}

try {
    print(JSON.stringify(obj3a));
} catch (e) {
    print(e.name);
}

<commit_msg>clean up json cyclic structure test; add wide non-cyclic test<commit_after>/*===
TypeError
TypeError
TypeError
===*/

/* TypeError is required for cyclic structures. */

function testCycle1() {
    var obj = { foo: 1 };
    obj.cycle = obj;
    print(JSON.stringify(obj));
}

function testCycle2() {
    var obj1 = { foo: 1 };
    var obj2 = { bar: 2 };
    obj1.cycle = obj2;
    obj2.cycle = obj1;
    print(JSON.stringify(obj1));
}

function testCycle3() {
    var obj1 = { foo: 1 };
    var obj2 = { bar: 2 };
    var obj3 = { quux: 3 };
    obj1.cycle = obj2;
    obj2.cycle = obj3;
    obj3.cycle = obj1;
    print(JSON.stringify(obj1));
}

try {
    testCycle1();
} catch (e) {
    print(e.name);
}

try {
    testCycle2();
} catch (e) {
    print(e.name);
}

try {
    testCycle3();
} catch (e) {
    print(e.name);
}

/*===
{"foo":1,"bar":2,"ref1":{"quux":3,"baz":4,"ref1":{"quuux":5},"ref2":{"quuux":5}},"ref2":{"quux":3,"baz":4,"ref1":{"quuux":5},"ref2":{"quuux":5}}}
===*/

/* The following visits the same object multiple times, but not in a cycle.
 * This test ensures that any loop stack or hash map is unwound correctly.
 */

function testNoCycle1() {
    var obj1 = { foo: 1, bar: 2 };
    var obj2 = { quux: 3, baz: 4 };
    var obj3 = { quuux: 5 };
    obj1.ref1 = obj2;
    obj1.ref2 = obj2;
    obj2.ref1 = obj3;
    obj2.ref2 = obj3;
    print(JSON.stringify(obj1));
}

try {
    testNoCycle1();
} catch (e) {
    print(e.name);
}

<|endoftext|>


<commit_before>import 'babel-polyfill';

import _ from 'lodash';
import path from 'path';
import del from 'delete';
import { Client } from 'node-rest-client';
import { Generator as SpriteGenerator } from 'league-sprites';
import { promisifyNodeClient, saveFile, zipItems } from './utils';
import { outputLog } from './log';
import { findAndUpdateMongoDocument, saveMongoDocument } from './db';
import ItemSetDocument from './models/item_set';
import ChampionDocument from './models/champion';
import ItemDocument from './models/item';
import PatchVersionDocument from './models/patch_version';
import config from './config';

const PROD = config.env === 'production';

const DATA_GETTERS = {
  'riot': require('./sources/riot.js').default,
  'championgg': require('./sources/championgg.js').default,
  'probuilds': require('./sources/probuilds.js').default,
  // Disable ProBuilds because X-ray doesn't execute JS, so the crawler is broken
};
const getDatas = (source) => { return DATA_GETTERS[source]; };

const formatSkills = (skills) => {
  let skillStr = '';
  const ults = [6, 12, 16];
  for (let ultIndex in ults) {
    // 0 => slice 0 to 6
    // 1 => slice 7 to 12
    // 2 => slice 13 to 16
    const group = _.slice(skills, ults[ultIndex-1] || 0, ults[ultIndex]);
    const skill = _.chain(group).countBy().toPairs().sortBy(1).reverse().map(0).value()[0];
    skillStr += skill;
    if (ultIndex < ults.length - 1) {
      skillStr += ' > ';
    }
  }
  return skillStr;
};
const formatItemsFromId = (items) => {
  return items.map((i) => {
    return {
      count: 1,
      id: i
    };
  });
};

const run = () => new Promise(async (resolve, reject) => {

  const version = require('../package.json').version;
  console.log(`Version : ${version}.`);

  // == REQUESTS : Start.

  let datas = {};
  const sources = Object.keys(DATA_GETTERS);
  for (let source of sources) {
    outputLog(`Getting ${source} datas ...`);
    try {
      let getDatasPromise = getDatas(source);
      datas[source] = await getDatasPromise();
    } catch (e) {
      reject(e);
      return;
    }
    outputLog(`Getting ${source} datas : done !`);
  }

  // == REQUESTS : Done.

  if (!PROD) {
    outputLog(`Deleting last tmp folder ...`);
  }
  try {
    del.sync(path.join(config.path.sets.outputFolder, config.path.sets.saveFolderTmp));
  } catch (e) {
    reject(e);
    return;
  }
  if (!PROD) {
    outputLog(`Deleting last tmp folder : done !`);
  }

  const riotPatch = datas['riot'].patch;
  const championGGPatch = datas['championgg'].patch;
  const PATCH = datas['riot'].patch;
  // Only save the datas in the database if the Riot patch and the ChampionGG patch are equal
  // It prevents datas conflicts
  if (riotPatch.startsWith(championGGPatch)) {
    if (!PROD) {
      outputLog(`Riot patch equals ChampionGG patch !`);
    }
    // Saving the champions, items and patch version in the database
    const champions = datas['riot'].champions;
    if (!PROD) {
      outputLog(`Saving the champions in the database ...`);
    }
    for (const champion of champions) {
      try {
        await findAndUpdateMongoDocument(ChampionDocument, { id: champion.id }, champion);
      } catch (e) {
        reject(e);
        return;
      }
    }
    if (!PROD) {
      outputLog(`Saving the champions in the database : done !`);
    }
    const items = datas['riot'].items;
    if (!PROD) {
      outputLog(`Saving the items in the database ...`);
    }
    for (const item of items) {
      try {
        await findAndUpdateMongoDocument(ItemDocument, { id: item.id }, item);
      } catch (e) {
        reject(e);
        return;
      }
    }
    if (!PROD) {
      outputLog(`Saving the items in the database : done !`);
    }
    if (!PROD) {
      outputLog(`Saving the patch version in the database ...`);
    }
    try {
      const patchVersionDoc = {
        patchVersion: PATCH,
        importDate: Date.now()
      };
      await findAndUpdateMongoDocument(PatchVersionDocument, { patchVersion: PATCH }, patchVersionDoc);
    } catch (e) {
      reject(e);
      return;
    }
    if (!PROD) {
      outputLog(`Saving the patch version in the database : done !`);
    }
  } else {
    if (!PROD) {
      outputLog(`Riot patch : ${riotPatch}, ChampionGG patch ; ${championGGPatch} : not saving the champions/items`);
    }
  }

  // Temp list of SetSchema (./models/item_sets.js)
  let itemSetsList = [];

  // Saving item sets
  outputLog('Saving the sets ...');
  for (let champData of datas['championgg'].sets) {
    if (!PROD) {
      outputLog(`Saving ${champData.name}/${champData.role} ...`);
    }
    const trinketItems = [
      '3340', // Warding Totem
      '3341', // Sweeping Lens
      '3363', // Farsight Alteration
    ];
    const consumeItems = [
      '2003', // Health Potion
      '2055', // Control Ward
      '2031', // Refillable Potion
      '2032', // Hunter's Potion
      '2033', // Corrupting Potion
      '2138', // Elixir of Iron
      '2139', // Elixir of Sorcery
      '2140', // Elixir of Wrath
    ];
    try {
      let skills = formatSkills(champData.skills.mostGames.order) + ` (${champData.skills.mostGames.winPercent}% win - ${champData.skills.mostGames.games} games)`;
      if (formatSkills(champData.skills.mostGames.order) !== formatSkills(champData.skills.highestWinPercent.order)) {
         skills += ' - ' + formatSkills(champData.skills.highestWinPercent.order) + ` (${champData.skills.highestWinPercent.winPercent}% win - ${champData.skills.highestWinPercent.games} games)`;
      }
      const fileData = {
        title: `${PATCH} ${champData.role} (LISG)`,
        champion: champData.key,
        role: champData.role,
        blocks: [{
          items: formatItemsFromId([...champData.firstItems.mostGames.items.map(i => i.id.toString()), ...trinketItems]),
          type: `Most frequent starters (${champData.firstItems.mostGames.winPercent}% win - ${champData.firstItems.mostGames.games} games)`
        }, {
          items: formatItemsFromId([...champData.firstItems.highestWinPercent.items.map(i => i.id.toString()), ...trinketItems]),
          type: `Highest win rate starters (${champData.firstItems.highestWinPercent.winPercent}% win - ${champData.firstItems.highestWinPercent.games} games)`
        }, {
          items: formatItemsFromId(champData.items.mostGames.items.map(i => i.id.toString())),
          type: `Most frequent build (${champData.items.mostGames.winPercent}% win - ${champData.items.mostGames.games} games)`
        }, {
          items: formatItemsFromId(champData.items.highestWinPercent.items.map(i => i.id.toString())),
          type: `Highest win rate build (${champData.items.highestWinPercent.winPercent}% win - ${champData.items.highestWinPercent.games} games)`
        }, {
          items: formatItemsFromId([...champData.trinkets.map(t => t.item.id.toString()), ...consumeItems]),
          type: 'Consumables | ' + _.maxBy(champData.trinkets, t => t.games).item.name + ' : ' + _.maxBy(champData.trinkets, t => t.games).winPercent + '% win - ' + _.maxBy(champData.trinkets, t => t.games).games + ' games'
        }, {
          // TODO: Combine the items appearing twice or thrice in a row
          items: (datas['probuilds']) ? formatItemsFromId(_.without(_.dropWhile(datas['probuilds'].builds[champData.key].build, item => item), undefined)) : formatItemsFromId(consumeItems),
          type: (datas['probuilds']) ? 'ProBuilds build order | ' + skills : 'ProBuilds items unavailable | ' + skills
        }]
      };
      const fileContent = {
        title: fileData.title,
        type: 'custom',
        map: 'any',
        mode: 'any',
        priority: false,
        sortrank: 1,
        champion: fileData.champion,
        blocks: fileData.blocks
      };
      await saveFile(path.join(config.path.sets.saveFolderTmp, config.path.sets.saveFolder, champData.key, 'Recommended', `${PATCH} ${champData.role}.json`), JSON.stringify(fileContent, null, '  '));
      itemSetsList.push({
        title: fileData.title,
        champion: fileData.champion,
        role: fileData.role,
        isCustom: false,
        author: null,
        itemBlocks: fileData.blocks
      });
    } catch (e) {
      reject(e);
      return;
    }
    if (!PROD) {
      outputLog(`Saving ${champData.name}/${champData.role} : done !`);
    }
  }

  if (!PROD) {
    outputLog(`Saving the sets in the database ...`);
  }
  const itemSet = new ItemSetDocument({
    generationDate: Date.now(),
    patchVersion: PATCH,
    sets: itemSetsList
  });
  await saveMongoDocument(itemSet);
  if (!PROD) {
    outputLog(`Saving the sets in the database : done !`);
  }

  outputLog('Saving the sets : done !');

  outputLog('Zipping the sets ...');
  await zipItems();
  outputLog('Zipping the sets : done !');

  outputLog('Generating the sprites ...');

  const sprites = ['champions', 'items'];

  for (const spriteType of sprites) {
    let dataType = '';
    switch (spriteType) {
      case 'champions':
        dataType = 'ChampionIcon';
        break;
      case 'items':
        dataType = 'ItemIcon';
        break;
      default:
        reject(e);
        return;
    }
    const generatorOpts = {
      dataType: dataType,
      apiKey: config.key.riot,
      region: 'euw',
      patch: PATCH,
      stylesheetFormat: 'css',
      stylesheetLayout: 'horizontal',
      downloadFolder: path.join(config.path.sprites.outputFolder, config.path.sprites.downloadFolder),
      spritePath: path.join(config.path.sprites.outputFolder, config.path.sprites.spritesheetFolderTmp, config.path.sprites.spritesheetName[spriteType]),
      spriteLink: config.path.sprites.spritesheetLink[spriteType],
      stylesheetPath: path.join(config.path.sprites.outputFolder, config.path.sprites.spritesheetFolder, config.path.sprites.stylesheetName[spriteType]),
      finalSpritesheetFolder: path.join(config.path.sprites.outputFolder, config.path.sprites.spritesheetFolder)
    };

    try {
      outputLog(`Generating the ${dataType} sprites ...`);
      const spritesGenerator = new SpriteGenerator(generatorOpts);
      await spritesGenerator.generate();
      outputLog(`Generating the ${dataType} sprites : done !`);
    } catch (e) {
      reject(e);
      return;
    }
  }

  outputLog('Generation : done !');

  resolve();
});

export default run;
<commit_msg>Remove useless comment<commit_after>import 'babel-polyfill';

import _ from 'lodash';
import path from 'path';
import del from 'delete';
import { Client } from 'node-rest-client';
import { Generator as SpriteGenerator } from 'league-sprites';
import { promisifyNodeClient, saveFile, zipItems } from './utils';
import { outputLog } from './log';
import { findAndUpdateMongoDocument, saveMongoDocument } from './db';
import ItemSetDocument from './models/item_set';
import ChampionDocument from './models/champion';
import ItemDocument from './models/item';
import PatchVersionDocument from './models/patch_version';
import config from './config';

const PROD = config.env === 'production';

const DATA_GETTERS = {
  'riot': require('./sources/riot.js').default,
  'championgg': require('./sources/championgg.js').default,
  'probuilds': require('./sources/probuilds.js').default
};
const getDatas = (source) => { return DATA_GETTERS[source]; };

const formatSkills = (skills) => {
  let skillStr = '';
  const ults = [6, 12, 16];
  for (let ultIndex in ults) {
    // 0 => slice 0 to 6
    // 1 => slice 7 to 12
    // 2 => slice 13 to 16
    const group = _.slice(skills, ults[ultIndex-1] || 0, ults[ultIndex]);
    const skill = _.chain(group).countBy().toPairs().sortBy(1).reverse().map(0).value()[0];
    skillStr += skill;
    if (ultIndex < ults.length - 1) {
      skillStr += ' > ';
    }
  }
  return skillStr;
};
const formatItemsFromId = (items) => {
  return items.map((i) => {
    return {
      count: 1,
      id: i
    };
  });
};

const run = () => new Promise(async (resolve, reject) => {

  const version = require('../package.json').version;
  console.log(`Version : ${version}.`);

  // == REQUESTS : Start.

  let datas = {};
  const sources = Object.keys(DATA_GETTERS);
  for (let source of sources) {
    outputLog(`Getting ${source} datas ...`);
    try {
      let getDatasPromise = getDatas(source);
      datas[source] = await getDatasPromise();
    } catch (e) {
      reject(e);
      return;
    }
    outputLog(`Getting ${source} datas : done !`);
  }

  // == REQUESTS : Done.

  if (!PROD) {
    outputLog(`Deleting last tmp folder ...`);
  }
  try {
    del.sync(path.join(config.path.sets.outputFolder, config.path.sets.saveFolderTmp));
  } catch (e) {
    reject(e);
    return;
  }
  if (!PROD) {
    outputLog(`Deleting last tmp folder : done !`);
  }

  const riotPatch = datas['riot'].patch;
  const championGGPatch = datas['championgg'].patch;
  const PATCH = datas['riot'].patch;
  // Only save the datas in the database if the Riot patch and the ChampionGG patch are equal
  // It prevents datas conflicts
  if (riotPatch.startsWith(championGGPatch)) {
    if (!PROD) {
      outputLog(`Riot patch equals ChampionGG patch !`);
    }
    // Saving the champions, items and patch version in the database
    const champions = datas['riot'].champions;
    if (!PROD) {
      outputLog(`Saving the champions in the database ...`);
    }
    for (const champion of champions) {
      try {
        await findAndUpdateMongoDocument(ChampionDocument, { id: champion.id }, champion);
      } catch (e) {
        reject(e);
        return;
      }
    }
    if (!PROD) {
      outputLog(`Saving the champions in the database : done !`);
    }
    const items = datas['riot'].items;
    if (!PROD) {
      outputLog(`Saving the items in the database ...`);
    }
    for (const item of items) {
      try {
        await findAndUpdateMongoDocument(ItemDocument, { id: item.id }, item);
      } catch (e) {
        reject(e);
        return;
      }
    }
    if (!PROD) {
      outputLog(`Saving the items in the database : done !`);
    }
    if (!PROD) {
      outputLog(`Saving the patch version in the database ...`);
    }
    try {
      const patchVersionDoc = {
        patchVersion: PATCH,
        importDate: Date.now()
      };
      await findAndUpdateMongoDocument(PatchVersionDocument, { patchVersion: PATCH }, patchVersionDoc);
    } catch (e) {
      reject(e);
      return;
    }
    if (!PROD) {
      outputLog(`Saving the patch version in the database : done !`);
    }
  } else {
    if (!PROD) {
      outputLog(`Riot patch : ${riotPatch}, ChampionGG patch ; ${championGGPatch} : not saving the champions/items`);
    }
  }

  // Temp list of SetSchema (./models/item_sets.js)
  let itemSetsList = [];

  // Saving item sets
  outputLog('Saving the sets ...');
  for (let champData of datas['championgg'].sets) {
    if (!PROD) {
      outputLog(`Saving ${champData.name}/${champData.role} ...`);
    }
    const trinketItems = [
      '3340', // Warding Totem
      '3341', // Sweeping Lens
      '3363', // Farsight Alteration
    ];
    const consumeItems = [
      '2003', // Health Potion
      '2055', // Control Ward
      '2031', // Refillable Potion
      '2032', // Hunter's Potion
      '2033', // Corrupting Potion
      '2138', // Elixir of Iron
      '2139', // Elixir of Sorcery
      '2140', // Elixir of Wrath
    ];
    try {
      let skills = formatSkills(champData.skills.mostGames.order) + ` (${champData.skills.mostGames.winPercent}% win - ${champData.skills.mostGames.games} games)`;
      if (formatSkills(champData.skills.mostGames.order) !== formatSkills(champData.skills.highestWinPercent.order)) {
         skills += ' - ' + formatSkills(champData.skills.highestWinPercent.order) + ` (${champData.skills.highestWinPercent.winPercent}% win - ${champData.skills.highestWinPercent.games} games)`;
      }
      const fileData = {
        title: `${PATCH} ${champData.role} (LISG)`,
        champion: champData.key,
        role: champData.role,
        blocks: [{
          items: formatItemsFromId([...champData.firstItems.mostGames.items.map(i => i.id.toString()), ...trinketItems]),
          type: `Most frequent starters (${champData.firstItems.mostGames.winPercent}% win - ${champData.firstItems.mostGames.games} games)`
        }, {
          items: formatItemsFromId([...champData.firstItems.highestWinPercent.items.map(i => i.id.toString()), ...trinketItems]),
          type: `Highest win rate starters (${champData.firstItems.highestWinPercent.winPercent}% win - ${champData.firstItems.highestWinPercent.games} games)`
        }, {
          items: formatItemsFromId(champData.items.mostGames.items.map(i => i.id.toString())),
          type: `Most frequent build (${champData.items.mostGames.winPercent}% win - ${champData.items.mostGames.games} games)`
        }, {
          items: formatItemsFromId(champData.items.highestWinPercent.items.map(i => i.id.toString())),
          type: `Highest win rate build (${champData.items.highestWinPercent.winPercent}% win - ${champData.items.highestWinPercent.games} games)`
        }, {
          items: formatItemsFromId([...champData.trinkets.map(t => t.item.id.toString()), ...consumeItems]),
          type: 'Consumables | ' + _.maxBy(champData.trinkets, t => t.games).item.name + ' : ' + _.maxBy(champData.trinkets, t => t.games).winPercent + '% win - ' + _.maxBy(champData.trinkets, t => t.games).games + ' games'
        }, {
          // TODO: Combine the items appearing twice or thrice in a row
          items: (datas['probuilds']) ? formatItemsFromId(_.without(_.dropWhile(datas['probuilds'].builds[champData.key].build, item => item), undefined)) : formatItemsFromId(consumeItems),
          type: (datas['probuilds']) ? 'ProBuilds build order | ' + skills : 'ProBuilds items unavailable | ' + skills
        }]
      };
      const fileContent = {
        title: fileData.title,
        type: 'custom',
        map: 'any',
        mode: 'any',
        priority: false,
        sortrank: 1,
        champion: fileData.champion,
        blocks: fileData.blocks
      };
      await saveFile(path.join(config.path.sets.saveFolderTmp, config.path.sets.saveFolder, champData.key, 'Recommended', `${PATCH} ${champData.role}.json`), JSON.stringify(fileContent, null, '  '));
      itemSetsList.push({
        title: fileData.title,
        champion: fileData.champion,
        role: fileData.role,
        isCustom: false,
        author: null,
        itemBlocks: fileData.blocks
      });
    } catch (e) {
      reject(e);
      return;
    }
    if (!PROD) {
      outputLog(`Saving ${champData.name}/${champData.role} : done !`);
    }
  }

  if (!PROD) {
    outputLog(`Saving the sets in the database ...`);
  }
  const itemSet = new ItemSetDocument({
    generationDate: Date.now(),
    patchVersion: PATCH,
    sets: itemSetsList
  });
  await saveMongoDocument(itemSet);
  if (!PROD) {
    outputLog(`Saving the sets in the database : done !`);
  }

  outputLog('Saving the sets : done !');

  outputLog('Zipping the sets ...');
  await zipItems();
  outputLog('Zipping the sets : done !');

  outputLog('Generating the sprites ...');

  const sprites = ['champions', 'items'];

  for (const spriteType of sprites) {
    let dataType = '';
    switch (spriteType) {
      case 'champions':
        dataType = 'ChampionIcon';
        break;
      case 'items':
        dataType = 'ItemIcon';
        break;
      default:
        reject(e);
        return;
    }
    const generatorOpts = {
      dataType: dataType,
      apiKey: config.key.riot,
      region: 'euw',
      patch: PATCH,
      stylesheetFormat: 'css',
      stylesheetLayout: 'horizontal',
      downloadFolder: path.join(config.path.sprites.outputFolder, config.path.sprites.downloadFolder),
      spritePath: path.join(config.path.sprites.outputFolder, config.path.sprites.spritesheetFolderTmp, config.path.sprites.spritesheetName[spriteType]),
      spriteLink: config.path.sprites.spritesheetLink[spriteType],
      stylesheetPath: path.join(config.path.sprites.outputFolder, config.path.sprites.spritesheetFolder, config.path.sprites.stylesheetName[spriteType]),
      finalSpritesheetFolder: path.join(config.path.sprites.outputFolder, config.path.sprites.spritesheetFolder)
    };

    try {
      outputLog(`Generating the ${dataType} sprites ...`);
      const spritesGenerator = new SpriteGenerator(generatorOpts);
      await spritesGenerator.generate();
      outputLog(`Generating the ${dataType} sprites : done !`);
    } catch (e) {
      reject(e);
      return;
    }
  }

  outputLog('Generation : done !');

  resolve();
});

export default run;
<|endoftext|>