_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q62900
|
bemNames
|
test
|
function bemNames(entitys, delimiters) {
var resultString = '';
var names = entitys || { mods: {}, mixin: '' };
var delims = _extends({
ns: '',
el: '__',
mod: '--',
modVal: '-'
}, delimiters);
var mixin = isString(names.mixin) ? ' ' + names.mixin : '';
if (!names.block) return '';
resultString = delims.ns ? delims.ns + names.block : names.block;
if (names.el) resultString += delims.el + names.el;
if (isPObject(names.mods)) {
resultString += Object.keys(names.mods).reduce(function (prev, name) {
var val = names.mods[name];
/* eslint-disable no-param-reassign */
if (val === true) {
prev += ' ' + resultString + delims.mod + name;
} else if (isString(val) || isNumber(val)) {
prev += ' ' + resultString + delims.mod + name + delims.modVal + names.mods[name];
}
/* eslint-enable no-param-reassign */
return prev;
}, '');
}
return resultString + mixin;
}
|
javascript
|
{
"resource": ""
}
|
q62901
|
deepMergeConfigs
|
test
|
function deepMergeConfigs(configs, options) {
return merge.all(configs.filter(config => config), options);
}
|
javascript
|
{
"resource": ""
}
|
q62902
|
loadYaml
|
test
|
async function loadYaml(context, params) {
try {
const response = await context.github.repos.getContents(params);
return parseConfig(response.data.content);
} catch (e) {
if (e.code === 404) {
return null;
}
throw e;
}
}
|
javascript
|
{
"resource": ""
}
|
q62903
|
getBaseParams
|
test
|
function getBaseParams(params, base) {
if (typeof base !== 'string') {
throw new Error(`Invalid repository name in key "${BASE_KEY}"`);
}
const match = base.match(BASE_REGEX);
if (match == null) {
throw new Error(`Invalid repository name in key "${BASE_KEY}": ${base}`);
}
return {
owner: match[1] || params.owner,
repo: match[2],
path: match[3] || params.path,
};
}
|
javascript
|
{
"resource": ""
}
|
q62904
|
getConfig
|
test
|
async function getConfig(context, fileName, defaultConfig, deepMergeOptions) {
const filePath = path.posix.join(CONFIG_PATH, fileName);
const params = context.repo({
path: filePath,
});
const config = await loadYaml(context, params);
let baseRepo;
if (config == null) {
baseRepo = DEFAULT_BASE;
} else if (config != null && BASE_KEY in config) {
baseRepo = config[BASE_KEY];
delete config[BASE_KEY];
}
let baseConfig;
if (baseRepo) {
const baseParams = getBaseParams(params, baseRepo);
baseConfig = await loadYaml(context, baseParams);
}
if (config == null && baseConfig == null && !defaultConfig) {
return null;
}
return deepMergeConfigs(
[defaultConfig, baseConfig, config],
deepMergeOptions
);
}
|
javascript
|
{
"resource": ""
}
|
q62905
|
defineProperty
|
test
|
function defineProperty (obj, name, value) {
var enumerable = !!obj[name] && obj.propertyIsEnumerable(name)
Object.defineProperty(obj, name, {
configurable: true,
enumerable: enumerable,
writable: true,
value: value
})
}
|
javascript
|
{
"resource": ""
}
|
q62906
|
shimmer
|
test
|
function shimmer (options) {
if (options && options.logger) {
if (!isFunction(options.logger)) logger("new logger isn't a function, not replacing")
else logger = options.logger
}
}
|
javascript
|
{
"resource": ""
}
|
q62907
|
injectManifest
|
test
|
function injectManifest(data) {
let manifestHtml = `<head><link rel=manifest href=${hexo.config.pwa.manifest.path}>`;
if (data.indexOf(manifestHtml) === -1) {
data = data.replace('<head>', manifestHtml);
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q62908
|
injectSWRegister
|
test
|
function injectSWRegister(data) {
let swHtml = `<script>${compiledSWRegTpl}</script></body>`;
if (data.indexOf(compiledSWRegTpl) === -1) {
data = data.replace('</body>', swHtml);
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q62909
|
injectAsyncLoadPageJS
|
test
|
function injectAsyncLoadPageJS(data) {
let injectHtml = `<script>${asyncLoadPageJSTpl}</script>`;
if (data.indexOf(injectHtml) === -1) {
data = data.replace('</head>', injectHtml);
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q62910
|
rehype2react
|
test
|
function rehype2react(options) {
var settings = options || {};
var createElement = settings.createElement;
var components = settings.components || {};
this.Compiler = compiler;
/* Compile HAST to React. */
function compiler(node) {
if (node.type === 'root') {
if (node.children.length === 1 && node.children[0].type === 'element') {
node = node.children[0];
} else {
node = {
type: 'element',
tagName: 'div',
properties: node.properties || {},
children: node.children
};
}
}
return toH(h, tableCellStyle(node), settings.prefix);
}
/* Wrap `createElement` to pass components in. */
function h(name, props, children) {
var component = has(components, name) ? components[name] : name;
return createElement(component, props, children);
}
}
|
javascript
|
{
"resource": ""
}
|
q62911
|
doExec
|
test
|
function doExec(method, args) {
var cp;
var cpPromise = new ChildProcessPromise();
var reject = cpPromise._cpReject;
var resolve = cpPromise._cpResolve;
var finalArgs = slice.call(args, 0);
finalArgs.push(callback);
cp = child_process[method].apply(child_process, finalArgs);
function callback(err, stdout, stderr) {
if (err) {
var commandStr = args[0] + (Array.isArray(args[1]) ? (' ' + args[1].join(' ')) : '');
err.message += ' `' + commandStr + '` (exited with error code ' + err.code + ')';
err.stdout = stdout;
err.stderr = stderr;
var cpError = new ChildProcessError(err.message, err.code, child_process, stdout, stderr);
reject(cpError);
} else {
resolve({
childProcess: cp,
stdout: stdout,
stderr: stderr
});
}
}
cpPromise.childProcess = cp;
return cpPromise;
}
|
javascript
|
{
"resource": ""
}
|
q62912
|
doSpawn
|
test
|
function doSpawn(method, command, args, options) {
var result = {};
var cp;
var cpPromise = new ChildProcessPromise();
var reject = cpPromise._cpReject;
var resolve = cpPromise._cpResolve;
var successfulExitCodes = (options && options.successfulExitCodes) || [0];
cp = method(command, args, options);
// Don't return the whole Buffered result by default.
var captureStdout = false;
var captureStderr = false;
var capture = options && options.capture;
if (capture) {
for (var i = 0, len = capture.length; i < len; i++) {
var cur = capture[i];
if (cur === 'stdout') {
captureStdout = true;
} else if (cur === 'stderr') {
captureStderr = true;
}
}
}
result.childProcess = cp;
if (captureStdout) {
result.stdout = '';
cp.stdout.on('data', function(data) {
result.stdout += data;
});
}
if (captureStderr) {
result.stderr = '';
cp.stderr.on('data', function(data) {
result.stderr += data;
});
}
cp.on('error', reject);
cp.on('close', function(code) {
if (successfulExitCodes.indexOf(code) === -1) {
var commandStr = command + (args.length ? (' ' + args.join(' ')) : '');
var message = '`' + commandStr + '` failed with code ' + code;
var err = new ChildProcessError(message, code, cp);
if (captureStderr) {
err.stderr = result.stderr.toString();
}
if (captureStdout) {
err.stdout = result.stdout.toString();
}
reject(err);
} else {
result.code = code;
resolve(result);
}
});
cpPromise.childProcess = cp;
return cpPromise;
}
|
javascript
|
{
"resource": ""
}
|
q62913
|
slope2
|
test
|
function slope2(that, t) {
var h = that._x1 - that._x0;
return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;
}
|
javascript
|
{
"resource": ""
}
|
q62914
|
shouldSetAttribute
|
test
|
function shouldSetAttribute(name, value) {
if (isReservedProp(name)) {
return false;
}
if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
return false;
}
if (value === null) {
return true;
}
switch (typeof value) {
case 'boolean':
return shouldAttributeAcceptBooleanValue(name);
case 'undefined':
case 'number':
case 'string':
case 'object':
return true;
default:
// function, symbol
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q62915
|
createMarkupForProperty
|
test
|
function createMarkupForProperty(name, value) {
var propertyInfo = getPropertyInfo(name);
if (propertyInfo) {
if (shouldIgnoreValue(propertyInfo, value)) {
return '';
}
var attributeName = propertyInfo.attributeName;
if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
return attributeName + '=""';
} else if (typeof value !== 'boolean' || shouldAttributeAcceptBooleanValue(name)) {
return attributeName + '=' + quoteAttributeValueForBrowser(value);
}
} else if (shouldSetAttribute(name, value)) {
if (value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q62916
|
trapBubbledEvent
|
test
|
function trapBubbledEvent(topLevelType, handlerBaseName, element) {
if (!element) {
return null;
}
return EventListener.listen(element, handlerBaseName, dispatchEvent.bind(null, topLevelType));
}
|
javascript
|
{
"resource": ""
}
|
q62917
|
createUpdateQueue
|
test
|
function createUpdateQueue(baseState) {
var queue = {
baseState: baseState,
expirationTime: NoWork,
first: null,
last: null,
callbackList: null,
hasForceUpdate: false,
isInitialized: false
};
{
queue.isProcessing = false;
}
return queue;
}
|
javascript
|
{
"resource": ""
}
|
q62918
|
mountClassInstance
|
test
|
function mountClassInstance(workInProgress, renderExpirationTime) {
var current = workInProgress.alternate;
{
checkClassInstance(workInProgress);
}
var instance = workInProgress.stateNode;
var state = instance.state || null;
var props = workInProgress.pendingProps;
!props ? invariant(false, 'There must be pending props for an initial mount. This error is likely caused by a bug in React. Please file an issue.') : void 0;
var unmaskedContext = getUnmaskedContext(workInProgress);
instance.props = props;
instance.state = workInProgress.memoizedState = state;
instance.refs = emptyObject;
instance.context = getMaskedContext(workInProgress, unmaskedContext);
if (enableAsyncSubtreeAPI && workInProgress.type != null && workInProgress.type.prototype != null && workInProgress.type.prototype.unstable_isAsyncReactComponent === true) {
workInProgress.internalContextTag |= AsyncUpdates;
}
if (typeof instance.componentWillMount === 'function') {
callComponentWillMount(workInProgress, instance);
// If we had additional state updates during this life-cycle, let's
// process them now.
var updateQueue = workInProgress.updateQueue;
if (updateQueue !== null) {
instance.state = processUpdateQueue(current, workInProgress, updateQueue, instance, props, renderExpirationTime);
}
}
if (typeof instance.componentDidMount === 'function') {
workInProgress.effectTag |= Update;
}
}
|
javascript
|
{
"resource": ""
}
|
q62919
|
requestWork
|
test
|
function requestWork(root, expirationTime) {
if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
invariant(false, 'Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.');
}
// Add the root to the schedule.
// Check if this root is already part of the schedule.
if (root.nextScheduledRoot === null) {
// This root is not already scheduled. Add it.
root.remainingExpirationTime = expirationTime;
if (lastScheduledRoot === null) {
firstScheduledRoot = lastScheduledRoot = root;
root.nextScheduledRoot = root;
} else {
lastScheduledRoot.nextScheduledRoot = root;
lastScheduledRoot = root;
lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
}
} else {
// This root is already scheduled, but its priority may have increased.
var remainingExpirationTime = root.remainingExpirationTime;
if (remainingExpirationTime === NoWork || expirationTime < remainingExpirationTime) {
// Update the priority.
root.remainingExpirationTime = expirationTime;
}
}
if (isRendering) {
// Prevent reentrancy. Remaining work will be scheduled at the end of
// the currently rendering batch.
return;
}
if (isBatchingUpdates) {
// Flush work at the end of the batch.
if (isUnbatchingUpdates) {
// ...unless we're inside unbatchedUpdates, in which case we should
// flush it now.
performWorkOnRoot(root, Sync);
}
return;
}
// TODO: Get rid of Sync and use current time?
if (expirationTime === Sync) {
performWork(Sync, null);
} else if (!isCallbackScheduled) {
isCallbackScheduled = true;
startRequestCallbackTimer();
scheduleDeferredCallback(performAsyncWork);
}
}
|
javascript
|
{
"resource": ""
}
|
q62920
|
shouldYield
|
test
|
function shouldYield() {
if (deadline === null) {
return false;
}
if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) {
return false;
}
deadlineDidExpire = true;
return true;
}
|
javascript
|
{
"resource": ""
}
|
q62921
|
deleteValueForProperty
|
test
|
function deleteValueForProperty(node, name) {
var propertyInfo = getPropertyInfo(name);
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, undefined);
} else if (propertyInfo.mustUseProperty) {
var propName = propertyInfo.propertyName;
if (propertyInfo.hasBooleanValue) {
node[propName] = false;
} else {
node[propName] = '';
}
} else {
node.removeAttribute(propertyInfo.attributeName);
}
} else {
node.removeAttribute(name);
}
}
|
javascript
|
{
"resource": ""
}
|
q62922
|
updateProperties$1
|
test
|
function updateProperties$1(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
// Apply the diff.
updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag);
// TODO: Ensure that an update gets scheduled if any of the special props
// changed.
switch (tag) {
case 'input':
// Update the wrapper around inputs *after* updating props. This has to
// happen after `updateDOMProperties`. Otherwise HTML5 input validations
// raise warnings and prevent the new value from being assigned.
updateWrapper(domElement, nextRawProps);
// We also check that we haven't missed a value update, such as a
// Radio group shifting the checked value to another named radio input.
updateValueIfChanged(domElement);
break;
case 'textarea':
updateWrapper$1(domElement, nextRawProps);
break;
case 'select':
// <select> value update needs to occur after <option> children
// reconciliation
postUpdateWrapper(domElement, nextRawProps);
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q62923
|
sympact
|
test
|
async function sympact(code, options) {
if (typeof code !== 'string') {
throw new TypeError("The 'code' paramater must a string'");
}
if (typeof options === 'undefined') {
options = {};
}
if (typeof options !== 'object') {
throw new TypeError("The 'options' paramater must an object'");
}
const interval = options.interval || 125;
const cwd = options.cwd || path.dirname(caller());
if (interval < 1) {
throw new TypeError("The 'interval' paramater must be greater than 0'");
}
return new Promise((resolve, reject) => {
const slave = new Worker(code, cwd);
const probe = new Profiler(slave.pid(), interval);
slave.on('ready', async () => {
await probe.watch();
slave.run();
});
slave.on('after', async (start, end) => {
await probe.unwatch();
slave.kill();
resolve(probe.report(start, end));
});
slave.on('error', async err => {
await probe.unwatch();
slave.kill();
reject(err);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q62924
|
ExponentialBackoffStrategy
|
test
|
function ExponentialBackoffStrategy(options) {
BackoffStrategy.call(this, options);
this.backoffDelay_ = 0;
this.nextBackoffDelay_ = this.getInitialDelay();
this.factor_ = ExponentialBackoffStrategy.DEFAULT_FACTOR;
if (options && options.factor !== undefined) {
precond.checkArgument(options.factor > 1,
'Exponential factor should be greater than 1 but got %s.',
options.factor);
this.factor_ = options.factor;
}
}
|
javascript
|
{
"resource": ""
}
|
q62925
|
Backoff
|
test
|
function Backoff(backoffStrategy) {
events.EventEmitter.call(this);
this.backoffStrategy_ = backoffStrategy;
this.maxNumberOfRetry_ = -1;
this.backoffNumber_ = 0;
this.backoffDelay_ = 0;
this.timeoutID_ = -1;
this.handlers = {
backoff: this.onBackoff_.bind(this)
};
}
|
javascript
|
{
"resource": ""
}
|
q62926
|
FunctionCall
|
test
|
function FunctionCall(fn, args, callback) {
events.EventEmitter.call(this);
precond.checkIsFunction(fn, 'Expected fn to be a function.');
precond.checkIsArray(args, 'Expected args to be an array.');
precond.checkIsFunction(callback, 'Expected callback to be a function.');
this.function_ = fn;
this.arguments_ = args;
this.callback_ = callback;
this.lastResult_ = [];
this.numRetries_ = 0;
this.backoff_ = null;
this.strategy_ = null;
this.failAfter_ = -1;
this.retryPredicate_ = FunctionCall.DEFAULT_RETRY_PREDICATE_;
this.state_ = FunctionCall.State_.PENDING;
}
|
javascript
|
{
"resource": ""
}
|
q62927
|
Channel
|
test
|
function Channel(connection, name, options) {
options || (options = {});
options.capped = true;
// In mongo v <= 2.2 index for _id is not done by default
options.autoIndexId = true;
options.size || (options.size = 1024 * 1024 * 5);
options.strict = false;
this.options = options;
this.connection = connection;
this.closed = false;
this.listening = null;
this.name = name || 'mubsub';
this.create().listen();
this.setMaxListeners(0);
}
|
javascript
|
{
"resource": ""
}
|
q62928
|
Connection
|
test
|
function Connection(uri, options) {
var self = this;
options || (options = {});
options.autoReconnect != null || (options.autoReconnect = true);
// It's a Db instance.
if (uri.collection) {
this.db = uri;
} else {
MongoClient.connect(uri, options, function (err, db) {
if (err) return self.emit('error', err);
self.db = db;
self.emit('connect', db);
db.on('error', function (err) {
self.emit('error', err);
});
});
}
this.destroyed = false;
this.channels = {};
}
|
javascript
|
{
"resource": ""
}
|
q62929
|
Draggable
|
test
|
function Draggable(target, options) {
if (!(this instanceof Draggable)) {
return new Draggable(target, options);
}
var that = this;
//ignore existing instance
var instance = draggableCache.get(target);
if (instance) {
instance.state = 'reset';
//take over options
extend(instance, options);
instance.update();
return instance;
}
else {
//get unique id for instance
//needed to track event binders
that.id = getUid();
that._ns = '.draggy_' + that.id;
//save element passed
that.element = target;
draggableCache.set(target, that);
}
//define state behaviour
defineState(that, 'state', that.state);
//preset handles
that.currentHandles = [];
//take over options
extend(that, options);
//define handle
if (that.handle === undefined) {
that.handle = that.element;
}
//setup droppable
if (that.droppable) {
that.initDroppable();
}
//try to calc out basic limits
that.update();
//go to initial state
that.state = 'idle';
}
|
javascript
|
{
"resource": ""
}
|
q62930
|
ConjunctionMap
|
test
|
function ConjunctionMap() {
let _conjunctions = [];
/**
* Add a mapping of a conjunction to a value to this map.
* @param {Array} conjunction The conjunction to map the value
* @param {any} value The value to be mapped
*/
this.add = function add(conjunction, value) {
if (value === undefined) {
return;
}
let map = new LiteralTreeMap();
conjunction.forEach((conjunct) => {
map.add(conjunct);
});
_conjunctions.push([map.size(), map, value]);
};
/**
* Get the value of a conjunction.
* @return {any} Return the value of the conjunction mapped if it exists. Otherwise if the
* conjunction is not mapped then undefined would be returned instead.
*/
this.get = function get(conjunction) {
let result;
for (let i = 0; i < _conjunctions.length; i += 1) {
let pair = _conjunctions[i];
let containMismatch = false;
if (conjunction.length !== pair[0]) {
continue;
}
for (let j = 0; j < conjunction.length; j += 1) {
let conjunct = conjunction[j];
if (!pair[1].contains(conjunct)) {
containMismatch = true;
break;
}
}
if (!containMismatch) {
result = pair[2];
break;
}
}
return result;
};
}
|
javascript
|
{
"resource": ""
}
|
q62931
|
sortTimables
|
test
|
function sortTimables(conjunction, forTime) {
let earlyConjuncts = [];
let laterConjuncts = [];
let dependentTimeVariables = {};
// determine the time dependent variables
for (let k = 0; k < conjunction.length; k += 1) {
let conjunct = conjunction[k];
if (!(conjunct instanceof Timable)) {
// skip over non-Timables
if (conjunct instanceof Functor
&& comparisonTerms.indexOf(conjunct.getId()) !== -1) {
conjunct.getVariables()
.forEach((v) => {
dependentTimeVariables[v] = true;
});
}
continue;
}
let conjunctStartTime = conjunct.getStartTime();
let conjunctEndTime = conjunct.getEndTime();
if (conjunctEndTime instanceof Variable) {
let endTimeName = conjunctEndTime.evaluate();
if (conjunctStartTime instanceof Value
|| (conjunctStartTime instanceof Variable
&& conjunctStartTime.evaluate() !== endTimeName)) {
// different start/end times
dependentTimeVariables[endTimeName] = true;
}
}
}
// sort between early and later
for (let k = 0; k < conjunction.length; k += 1) {
let conjunct = conjunction[k];
if (!(conjunct instanceof Timable)) {
if (laterConjuncts.length > 0) {
laterConjuncts.push(conjunct);
continue;
}
earlyConjuncts.push(conjunct);
continue;
}
if (!conjunct.isInRange(forTime)) {
laterConjuncts.push(conjunct);
continue;
}
let conjunctStartTime = conjunct.getStartTime();
if (conjunctStartTime instanceof Variable) {
if (dependentTimeVariables[conjunctStartTime.evaluate()] !== undefined) {
laterConjuncts.push(conjunct);
continue;
}
}
earlyConjuncts.push(conjunct);
}
return [
earlyConjuncts,
laterConjuncts
];
}
|
javascript
|
{
"resource": ""
}
|
q62932
|
test
|
function (programArgs) {
let _programArgs = programArgs;
if (programArgs === undefined) {
_programArgs = [];
}
// map to values
_programArgs = _programArgs.map(arg => new Value(arg));
let argsList = new List(_programArgs);
let theta = {
List: argsList
};
return programArgsPredicate.substitute(theta);
}
|
javascript
|
{
"resource": ""
}
|
|
q62933
|
createProgramArgsUpdaterFunc
|
test
|
function createProgramArgsUpdaterFunc(programArgs) {
return (program) => {
let programArgsFact = buildProgramArgsPredicate(programArgs);
program.getFacts().add(programArgsFact);
return Promise.resolve(program);
};
}
|
javascript
|
{
"resource": ""
}
|
q62934
|
processCycleObservations
|
test
|
function processCycleObservations() {
let activeObservations = new LiteralTreeMap();
if (_observations[_currentTime] === undefined) {
// no observations for current time
return activeObservations;
}
let cloneProgram = _program.clone();
cloneProgram.setExecutedActions(activeObservations);
const nextTime = _currentTime + 1;
// process observations for the current time
_observations[_currentTime].forEach((ob) => {
let action = ob.action;
let tempTreeMap = new LiteralTreeMap();
tempTreeMap.add(action);
activeObservations.add(action);
let postCloneProgram = cloneProgram.clone();
let postState = postCloneProgram.getState();
postCloneProgram.setExecutedActions(new LiteralTreeMap());
updateStateWithFluentActors(
this,
tempTreeMap,
postState
);
postCloneProgram.setState(postState);
// perform pre-check and post-check
if (!checkConstraintSatisfaction.call(this, cloneProgram)
|| !checkConstraintSatisfaction.call(this, postCloneProgram)) {
// reject the observed event
// to keep model true
activeObservations.remove(action);
// warning
_engineEventManager.notify('warning', {
type: 'observation.reject',
message: stringLiterals(
'engine.rejectObservationWarning',
action,
_currentTime,
nextTime
)
});
}
// if the given observation endTime has not ended
// propagate to the next cycle's
if (ob.endTime > nextTime) {
if (_observations[nextTime] === undefined) {
_observations[nextTime] = [];
}
_observations[nextTime].push(ob);
}
});
return activeObservations;
}
|
javascript
|
{
"resource": ""
}
|
q62935
|
actionsSelector
|
test
|
function actionsSelector(goalTrees) {
const recursiveActionsSelector = (actionsSoFar, programSoFar, l) => {
if (l >= goalTrees.length) {
let actions = new LiteralTreeMap();
actionsSoFar.forEach((map) => {
map.forEach((literal) => {
actions.add(literal);
});
});
return actions;
}
let goalTree = goalTrees[l];
let resultSet = null;
goalTree.forEachCandidateActions(_currentTime, (candidateActions) => {
let cloneProgram = programSoFar.clone();
let cloneExecutedActions = cloneProgram.getExecutedActions();
candidateActions.forEach((a) => {
cloneExecutedActions.add(a);
});
// pre-condition check
if (!checkConstraintSatisfaction.call(this, cloneProgram)) {
return false;
}
// post condition checks
let clonePostProgram = programSoFar.clone();
clonePostProgram.setExecutedActions(new LiteralTreeMap());
let postState = clonePostProgram.getState();
updateStateWithFluentActors(
this,
candidateActions,
postState
);
clonePostProgram.setState(postState);
if (!checkConstraintSatisfaction.call(this, clonePostProgram)) {
return false;
}
resultSet = recursiveActionsSelector(
actionsSoFar.concat([candidateActions]),
cloneProgram,
l + 1
);
return true;
});
if (resultSet !== null) {
return resultSet;
}
return recursiveActionsSelector(
actionsSoFar,
programSoFar,
l + 1
);
};
return recursiveActionsSelector([], _program, 0);
}
|
javascript
|
{
"resource": ""
}
|
q62936
|
performCycle
|
test
|
function performCycle() {
_currentTime += 1;
let selectedAndExecutedActions = new LiteralTreeMap();
let executedObservations = new LiteralTreeMap();
// Step 0 - Updating database
let updatedState = _program.getState().clone();
updateStateWithFluentActors(
this,
_program.getExecutedActions(),
updatedState
);
_program.setState(updatedState);
_nextCycleObservations.forEach((obs) => {
executedObservations.add(obs);
});
_nextCycleActions.forEach((act) => {
selectedAndExecutedActions.add(act);
});
// Step 1 - Processing rules
let newFiredGoals = processRules(this, _program, _currentTime, _profiler);
_goals = _goals.concat(newFiredGoals);
// Step 3 - Processing
return evaluateGoalTrees(_currentTime, _goals, _profiler)
.then((newGoals) => {
_goals = newGoals;
// Start preparation for next cycle
// reset the set of executed actions
_program.setExecutedActions(new LiteralTreeMap());
_goals.sort(goalTreeSorter(_currentTime));
// select actions from candidate actions
return actionsSelector.call(this, _goals);
})
.then((nextCycleActions) => {
_nextCycleActions = new LiteralTreeMap();
nextCycleActions.forEach((l) => {
_nextCycleActions.add(l);
});
_nextCycleObservations = new LiteralTreeMap();
let cycleObservations = processCycleObservations.call(this);
cycleObservations.forEach((observation) => {
nextCycleActions.add(observation);
_nextCycleObservations.add(observation);
});
_program.setExecutedActions(nextCycleActions);
_lastCycleActions = selectedAndExecutedActions;
_lastCycleObservations = executedObservations;
// done with cycle
return Promise.resolve();
});
}
|
javascript
|
{
"resource": ""
}
|
q62937
|
applyArgs
|
test
|
function applyArgs(func, thisObj, args) {
return func.apply(thisObj, Array.prototype.slice.call(args));
}
|
javascript
|
{
"resource": ""
}
|
q62938
|
define
|
test
|
function define() {
var thisFlow = function() {
applyArgs(thisFlow.exec, thisFlow, arguments);
}
thisFlow.blocks = arguments;
thisFlow.exec = function() {
// The flowState is the actual object each step in the flow is applied to. It acts as a
// callback to the next function. It also maintains the internal state of each execution
// and acts as a place for users to save values between steps of the flow.
var flowState = function() {
if (flowState.__frozen) return;
if (flowState.__timeoutId) {
clearTimeout(flowState.__timeoutId);
delete flowState.__timeoutId;
}
var blockIdx = flowState.__nextBlockIdx ++;
var block = thisFlow.blocks[blockIdx];
if (block === undefined) {
return;
}
else {
applyArgs(block, flowState, arguments);
}
}
// __nextBlockIdx specifies which function is the next step in the flow.
flowState.__nextBlockIdx = 0;
// __multiCount is incremented every time MULTI is used to createa a multiplexed callback
flowState.__multiCount = 0;
// __multiOutputs accumulates the arguments of each call to callbacks generated by MULTI
flowState.__multiOutputs = [];
// REWIND signals that the next call to thisFlow should repeat this step. It allows you
// to create serial loops.
flowState.REWIND = function() {
flowState.__nextBlockIdx -= 1;
}
// MULTI can be used to generate callbacks that must ALL be called before the next step
// in the flow is executed. Arguments to those callbacks are accumulated, and an array of
// of those arguments objects is sent as the one argument to the next step in the flow.
// @param {String} resultId An identifier to get the result of a multi call.
flowState.MULTI = function(resultId) {
flowState.__multiCount += 1;
return function() {
flowState.__multiCount -= 1;
flowState.__multiOutputs.push(arguments);
if (resultId) {
var result = arguments.length <= 1 ? arguments[0] : arguments
flowState.__multiOutputs[resultId] = result;
}
if (flowState.__multiCount === 0) {
var multiOutputs = flowState.__multiOutputs;
flowState.__multiOutputs = [];
flowState(multiOutputs);
}
}
}
// TIMEOUT sets a timeout that freezes a flow and calls the provided callback. This
// timeout is cleared if the next flow step happens first.
flowState.TIMEOUT = function(milliseconds, timeoutCallback) {
if (flowState.__timeoutId !== undefined) {
throw new Error("timeout already set for this flow step");
}
flowState.__timeoutId = setTimeout(function() {
flowState.__frozen = true;
timeoutCallback();
}, milliseconds);
}
applyArgs(flowState, this, arguments);
}
return thisFlow;
}
|
javascript
|
{
"resource": ""
}
|
q62939
|
test
|
function() {
if (flowState.__frozen) return;
if (flowState.__timeoutId) {
clearTimeout(flowState.__timeoutId);
delete flowState.__timeoutId;
}
var blockIdx = flowState.__nextBlockIdx ++;
var block = thisFlow.blocks[blockIdx];
if (block === undefined) {
return;
}
else {
applyArgs(block, flowState, arguments);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62940
|
exec
|
test
|
function exec() {
var flow = typeof exports != 'undefined' ? exports : window.flow;
applyArgs(flow.define, flow, arguments)();
}
|
javascript
|
{
"resource": ""
}
|
q62941
|
padStart
|
test
|
function padStart(str, length, padChar) {
if (str.length >= length) {
return str;
} else {
return padChar.repeat(length - str.length) + str;
}
}
|
javascript
|
{
"resource": ""
}
|
q62942
|
SM2Curve
|
test
|
function SM2Curve(params) {
if (!(this instanceof SM2Curve)) {
return new SM2Curve(params);
}
elliptic.curve.short.call(this, params);
}
|
javascript
|
{
"resource": ""
}
|
q62943
|
SM2KeyPair
|
test
|
function SM2KeyPair(pub, pri) {
if (!(this instanceof SM2KeyPair)) {
return new SM2KeyPair(pub, pri);
}
this.curve = SM2; // curve parameter
this.pub = null; // public key, should be a point on the curve
this.pri = null; // private key, should be a integer
var validPub = false;
var validPri = false;
if (pub != null) {
if (typeof pub === 'string') {
this._pubFromString(pub);
} else if (Array.isArray(pub)) {
this._pubFromBytes(pub);
} else if ('x' in pub && pub.x instanceof BN &&
'y' in pub && pub.y instanceof BN) {
// pub is already the Point object
this.pub = pub;
validPub = true;
} else {
throw 'invalid public key';
}
}
if (pri != null) {
if (typeof pri === 'string') {
this.pri = new BN(pri, 16);
} else if (pri instanceof BN) {
this.pri = pri;
validPri = true;
} else {
throw 'invalid private key';
}
// calculate public key
if (this.pub == null) {
this.pub = SM2.g.mul(this.pri);
}
}
if (!(validPub && validPri) && !this.validate()) {
throw 'invalid key';
}
}
|
javascript
|
{
"resource": ""
}
|
q62944
|
gulpStaticI18n
|
test
|
function gulpStaticI18n(options) {
return through.obj(function(target, encoding, cb) {
var stream = this;
var build = new StaticI18n(target, options, stream);
build.translate(cb);
});
}
|
javascript
|
{
"resource": ""
}
|
q62945
|
test
|
function (obj, type, fn, scope) {
scope = scope || obj;
var wrappedFn = function (e) { fn.call(scope, e); };
obj.addEventListener(type, wrappedFn, false);
cache.push([obj, type, fn, wrappedFn]);
}
|
javascript
|
{
"resource": ""
}
|
|
q62946
|
test
|
function (obj, type, fn) {
var wrappedFn, item, len = cache.length, i;
for (i = 0; i < len; i++) {
item = cache[i];
if (item[0] === obj && item[1] === type && item[2] === fn) {
wrappedFn = item[3];
if (wrappedFn) {
obj.removeEventListener(type, wrappedFn, false);
cache = cache.slice(i);
return true;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62947
|
View
|
test
|
function View(model) {
var wrapper;
this.el = wrapper = document.createElement('div');
this.model = model;
this.isShowing = false;
// HTML
wrapper.id = config.name;
config.parent.appendChild(wrapper);
// CSS
css.inject(document.getElementsByTagName('head')[0], config.styles);
// JavaScript
events.add(document, ('ontouchstart' in window) ? 'touchstart' : 'click', viewevents.click, this);
events.add(document, 'keyup', viewevents.keyup, this);
events.add(document, 'readystatechange', viewevents.readystatechange, this);
events.add(window, 'pageshow', viewevents.pageshow, this);
}
|
javascript
|
{
"resource": ""
}
|
q62948
|
Product
|
test
|
function Product(data) {
data.quantity = parser.quantity(data.quantity);
data.amount = parser.amount(data.amount);
data.href = parser.href(data.href);
this._data = data;
this._options = null;
this._discount = null;
this._amount = null;
this._total = null;
Pubsub.call(this);
}
|
javascript
|
{
"resource": ""
}
|
q62949
|
Cart
|
test
|
function Cart(name, duration) {
var data, items, settings, len, i;
this._items = [];
this._settings = { bn: constants.BN };
Pubsub.call(this);
Storage.call(this, name, duration);
if ((data = this.load())) {
items = data.items;
settings = data.settings;
if (settings) {
this._settings = settings;
}
if (items) {
for (i = 0, len = items.length; i < len; i++) {
this.add(items[i]);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62950
|
onRejected
|
test
|
function onRejected(error) {
attemts_left -= 1;
if (attemts_left < 1) {
throw error;
}
console.log("A retried call failed. Retrying " + attemts_left + " more time(s).");
// retry call self again with the same arguments, except attemts_left is now lower
var fullArguments = [attemts_left, promiseFunction].concat(promiseFunctionArguments);
return module.exports.retryPromise.apply(undefined, fullArguments);
}
|
javascript
|
{
"resource": ""
}
|
q62951
|
fixDate
|
test
|
function fixDate(type, value, hash) {
if (type !== "commit" && type !== "tag") return;
// Add up to 3 extra newlines and try all 30-minutes timezone offsets.
var clone = JSON.parse(JSON.stringify(value));
for (var x = 0; x < 3; x++) {
for (var i = -720; i < 720; i += 30) {
if (type === "commit") {
clone.author.date.offset = i;
clone.committer.date.offset = i;
}
else if (type === "tag") {
clone.tagger.date.offset = i;
}
if (hash !== hashAs(type, clone)) continue;
// Apply the changes and return.
value.message = clone.message;
if (type === "commit") {
value.author.date.offset = clone.author.date.offset;
value.committer.date.offset = clone.committer.date.offset;
}
else if (type === "tag") {
value.tagger.date.offset = clone.tagger.date.offset;
}
return true;
}
clone.message += "\n";
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q62952
|
test
|
function () {
var $this = this;
// remove all data set with .data()
$this.removeData();
// unbind the document as well
$(document)
.unbind('mousemove.nstSlider')
.unbind('mouseup.nstSlider');
// unbind events bound to the container element
$this.parent()
.unbind('mousedown.nstSlider')
.unbind('touchstart.nstSlider')
.unbind('touchmove.nstSlider')
.unbind('touchend.nstSlider');
// unbind events bound to the current element
$this.unbind('keydown.nstSlider')
.unbind('keyup.nstSlider');
return $this;
}
|
javascript
|
{
"resource": ""
}
|
|
q62953
|
test
|
function () {
var $this = this;
// re-set the slider step if specified
var lastStepHistogram = $this.data('last_step_histogram');
if (typeof lastStepHistogram !== 'undefined') {
methods.set_step_histogram.call($this, lastStepHistogram);
}
// re-center given values
_methods.set_position_from_val.call($this,
methods.get_current_min_value.call($this),
methods.get_current_max_value.call($this)
);
// re-highlight the range
var highlightRangeMin = $this.data('highlightedRangeMin');
if (typeof highlightRangeMin === 'number') {
// a highlight range is present, we must update it
var highlightRangeMax = $this.data('highlightedRangeMax');
methods.highlight_range.call($this, highlightRangeMin, highlightRangeMax);
}
_methods.notify_changed_implicit.call($this, 'refresh');
return $this;
}
|
javascript
|
{
"resource": ""
}
|
|
q62954
|
GoogleLogin
|
test
|
function GoogleLogin() {
if (!(this instanceof GoogleLogin)) {
return new GoogleLogin();
}
const self = this;
/**
* Based of https://github.com/tejado/pgoapi/blob/master/pgoapi/auth_google.py#L33
*/
const GOOGLE_LOGIN_ANDROID_ID = '9774d56d682e549c';
const GOOGLE_LOGIN_SERVICE =
'audience:server:client_id:848232511240-7so421jotr2609rmqakceuu1luuq0ptb.apps.googleusercontent.com';
const GOOGLE_LOGIN_APP = 'com.nianticlabs.pokemongo';
const GOOGLE_LOGIN_CLIENT_SIG = '321187995bc7cdc2b5fc91b11a96e2baa8602c62';
/**
* Sets a proxy address to use for logins.
* @param {string} proxy
*/
this.setProxy = function(proxy) {
google.setProxy(proxy);
};
/**
* Performs the Google Login using Android Device and returns a Promise that will be resolved
* with the auth token.
* @param {string} username
* @param {string} password
* @return {Promise}
*/
this.login = function(username, password) {
return self.getMasterToken(username, password)
.then(loginData => self.getToken(username, loginData))
.then(authData => authData.Auth);
};
/**
* Performs the Google login by skipping the password step and starting with the Master Token
* instead. Returns a Promise that will be resolved with the auth token.
* @param {string} username
* @param {string} token
* @return {Promise}
*/
this.loginWithToken = function(username, token) {
var loginData = {
androidId: GOOGLE_LOGIN_ANDROID_ID,
masterToken: token
};
return self.getToken(username, loginData).then(authData => authData.Auth);
};
/**
* Initialize Google Login
* @param {string} username
* @param {string} password
* @return {Promise}
*/
this.getMasterToken = function(username, password) {
return new Promise((resolve, reject) => {
google.login(username, password, GOOGLE_LOGIN_ANDROID_ID, (err, data) => {
if (err) {
if (err.response.statusCode === 403) {
reject(Error(
'Received code 403 from Google login. This could be because your account has ' +
'2-Step-Verification enabled. If that is the case, you need to generate an ' +
'App Password and use that instead of your regular password: ' +
'https://security.google.com/settings/security/apppasswords'
));
} else {
reject(Error(err.response.statusCode + ': ' + err.response.statusMessage));
}
return;
}
resolve(data);
});
});
};
/**
* Finalizes oAuth request using master token and resolved with the auth data
* @private
* @param {string} username
* @param {string} loginData
* @return {Promise}
*/
this.getToken = function(username, loginData) {
return new Promise((resolve, reject) => {
google.oauth(username, loginData.masterToken, loginData.androidId,
GOOGLE_LOGIN_SERVICE, GOOGLE_LOGIN_APP, GOOGLE_LOGIN_CLIENT_SIG, (err, data) => {
if (err) {
reject(Error(err.response.statusCode + ': ' + err.response.statusMessage));
return;
}
resolve(data);
});
});
};
}
|
javascript
|
{
"resource": ""
}
|
q62955
|
test
|
function(lat, lng, radius, level) {
if (typeof radius === 'undefined') radius = 3;
if (typeof level === 'undefined') level = 15;
/* eslint-disable new-cap */
var origin = s2.S2Cell.FromLatLng({
lat: lat,
lng: lng
}, level);
var cells = [];
cells.push(origin.toHilbertQuadkey()); // middle block
for (var i = 1; i < radius; i++) {
// cross in middle
cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0], origin.ij[1] - i], origin.level)
.toHilbertQuadkey());
cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0], origin.ij[1] + i], origin.level)
.toHilbertQuadkey());
cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0] - i, origin.ij[1]], origin.level)
.toHilbertQuadkey());
cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0] + i, origin.ij[1]], origin.level)
.toHilbertQuadkey());
for (var j = 1; j < radius; j++) {
cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0] - j, origin.ij[1] - i], origin.level)
.toHilbertQuadkey());
cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0] + j, origin.ij[1] - i], origin.level)
.toHilbertQuadkey());
cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0] - j, origin.ij[1] + i], origin.level)
.toHilbertQuadkey());
cells.push(s2.S2Cell.FromFaceIJ(origin.face, [origin.ij[0] + j, origin.ij[1] + i], origin.level)
.toHilbertQuadkey());
}
}
/* eslint-enable new-cap */
return cells.map(s2.toId);
}
|
javascript
|
{
"resource": ""
}
|
|
q62956
|
test
|
function(enumObj, val) {
for (var key of Object.keys(enumObj)) {
if (enumObj[key] === val) {
return key.split('_')
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q62957
|
test
|
function(object) {
if (!object || typeof object !== 'object') return object;
if (object instanceof ByteBuffer) return object;
if (Long.isLong(object)) {
return object.lessThanOrEqual(Number.MAX_SAFE_INTEGER)
&& object.greaterThanOrEqual(Number.MIN_SAFE_INTEGER)
? object.toNumber() : object.toString();
}
for (var i in object) {
if (object.hasOwnProperty(i)) {
if (Long.isLong(object[i])) {
object[i] = object[i].lessThanOrEqual(Number.MAX_SAFE_INTEGER) && object[i].greaterThanOrEqual(
Number.MIN_SAFE_INTEGER) ? object[i].toNumber() : object[i].toString();
} else if (typeof object[i] === 'object') {
object[i] = this.convertLongs(object[i]);
}
}
}
return object;
}
|
javascript
|
{
"resource": ""
}
|
|
q62958
|
Random
|
test
|
function Random(seed) {
this.multiplier = 16807;
this.modulus = 0x7fffffff;
this.seed = seed;
this.mq = Math.floor(this.modulus / this.multiplier);
this.mr = this.modulus % this.multiplier;
}
|
javascript
|
{
"resource": ""
}
|
q62959
|
prettyDate
|
test
|
function prettyDate(time){
/*var date = new Date((time || "")*/
var diff = (((new Date()).getTime() - time) / 1000),
day_diff = Math.floor(diff / 86400);
if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
return;
return day_diff == 0 && (
diff < 60 && "just now" ||
diff < 120 && "1 minute ago" ||
diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
diff < 7200 && "1 hour ago" ||
diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
day_diff == 1 && "Yesterday" ||
day_diff < 7 && day_diff + " days ago" ||
day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}
|
javascript
|
{
"resource": ""
}
|
q62960
|
LoggerFactory
|
test
|
function LoggerFactory(options) {
options = options || {
prefix: true
};
// If `console.log` is not accessible, `log` is a noop.
if (
typeof console !== 'object' ||
typeof console.log !== 'function' ||
typeof console.log.bind !== 'function'
) {
return function noop() {};
}
return function log() {
var args = Array.prototype.slice.call(arguments);
// All logs are disabled when `io.sails.environment = 'production'`.
if (io.sails.environment === 'production') return;
// Add prefix to log messages (unless disabled)
var PREFIX = '';
if (options.prefix) {
args.unshift(PREFIX);
}
// Call wrapped logger
console.log
.bind(console)
.apply(this, args);
};
}
|
javascript
|
{
"resource": ""
}
|
q62961
|
runRequestQueue
|
test
|
function runRequestQueue (socket) {
var queue = socket.requestQueue;
if (!queue) return;
for (var i in queue) {
// Double-check that `queue[i]` will not
// inadvertently discover extra properties attached to the Object
// and/or Array prototype by other libraries/frameworks/tools.
// (e.g. Ember does this. See https://github.com/balderdashy/sails.io.js/pull/5)
var isSafeToDereference = ({}).hasOwnProperty.call(queue, i);
if (isSafeToDereference) {
// Get the arguments that were originally made to the "request" method
var requestArgs = queue[i];
// Call the request method again in the context of the socket, with the original args
socket.request.apply(socket, requestArgs);
}
}
// Now empty the queue to remove it as a source of additional complexity.
socket.requestQueue = null;
}
|
javascript
|
{
"resource": ""
}
|
q62962
|
jsonp
|
test
|
function jsonp(opts, cb) {
opts = opts || {};
if (typeof window === 'undefined') {
// FUTURE: refactor node usage to live in here
return cb();
}
var scriptEl = document.createElement('script');
window._sailsIoJSConnect = function(response) {
// In rare circumstances our script may have been vaporised.
// Remove it, but only if it still exists
// https://github.com/balderdashy/sails.io.js/issues/92
if (scriptEl && scriptEl.parentNode) {
scriptEl.parentNode.removeChild(scriptEl);
}
cb(response);
};
scriptEl.src = opts.url;
document.getElementsByTagName('head')[0].appendChild(scriptEl);
}
|
javascript
|
{
"resource": ""
}
|
q62963
|
validateParameterValue
|
test
|
function validateParameterValue (parameter, type, format, value) {
if (type === 'integer') {
const parsedValue = Number.parseInt(value)
if (_.isNaN(parsedValue)) {
throw new Error(`Invalid "${parameter}" value: failed to parse "${value}" as integer`)
}
return parsedValue
} else if (type === 'number') {
const parsedValue = Number.parseFloat(value)
if (_.isNaN(parsedValue)) {
throw new Error(`Invalid "${parameter}" value: failed to parse "${value}" as number`)
}
return Number.isInteger(parsedValue) ? Number.parseInt(value) : parsedValue
} else if (type === 'string' && format) {
if (format === 'date-time' && !moment(value, moment.ISO_8601).isValid()) {
throw new Error(`Invalid "${parameter}" value: failed to parse "${value}" as date-time string`)
} else if (format === 'date' && !moment(value, 'YYYY-MM-DD').isValid()) {
throw new Error(`Invalid "${parameter}" value: failed to parse "${value}" as date string`)
}
return value
}
return value
}
|
javascript
|
{
"resource": ""
}
|
q62964
|
parameterDeclarationToYargs
|
test
|
function parameterDeclarationToYargs (yargs, parameter, declaration) {
const optionName = _.kebabCase(parameter)
let option = {}
if (declaration.description) {
option.describe = declaration.description
}
if (declaration.type) {
if (declaration.type === 'integer') {
option.type = 'number'
} else {
option.type = declaration.type
}
}
if (declaration.enum) {
option.choices = declaration.enum
}
if (declaration.default) {
option.default = declaration.default
}
if (declaration.required) {
option.demandOption = declaration.required
}
if (declaration.conflicts) {
option.conflicts = declaration.conflicts
}
yargs.option(optionName, option)
yargs.coerce(optionName, (value) => {
if (declaration.type === 'array') {
return _.map(value, (value) => {
return validateParameterValue(`${optionName}[]`, declaration.item, declaration.format, value)
})
}
return validateParameterValue(optionName, declaration.type, declaration.format, value)
})
}
|
javascript
|
{
"resource": ""
}
|
q62965
|
configDeclarationToYargs
|
test
|
function configDeclarationToYargs (yargs, configDeclaration) {
_.forOwn(configDeclaration, (parameter, parameterName) => {
parameterDeclarationToYargs(yargs, parameterName, parameter)
})
return yargs
}
|
javascript
|
{
"resource": ""
}
|
q62966
|
NGramParser
|
test
|
function NGramParser(theNgramList, theByteMap) {
var N_GRAM_MASK = 0xFFFFFF;
this.byteIndex = 0;
this.ngram = 0;
this.ngramList = theNgramList;
this.byteMap = theByteMap;
this.ngramCount = 0;
this.hitCount = 0;
this.spaceChar;
/*
* Binary search for value in table, which must have exactly 64 entries.
*/
this.search = function(table, value) {
var index = 0;
if (table[index + 32] <= value) index += 32;
if (table[index + 16] <= value) index += 16;
if (table[index + 8] <= value) index += 8;
if (table[index + 4] <= value) index += 4;
if (table[index + 2] <= value) index += 2;
if (table[index + 1] <= value) index += 1;
if (table[index] > value) index -= 1;
if (index < 0 || table[index] != value)
return -1;
return index;
};
this.lookup = function(thisNgram) {
this.ngramCount += 1;
if (this.search(this.ngramList, thisNgram) >= 0) {
this.hitCount += 1;
}
};
this.addByte = function(b) {
this.ngram = ((this.ngram << 8) + (b & 0xFF)) & N_GRAM_MASK;
this.lookup(this.ngram);
}
this.nextByte = function(det) {
if (this.byteIndex >= det.fInputLen)
return -1;
return det.fInputBytes[this.byteIndex++] & 0xFF;
}
this.parse = function(det, spaceCh) {
var b, ignoreSpace = false;
this.spaceChar = spaceCh;
while ((b = this.nextByte(det)) >= 0) {
var mb = this.byteMap[b];
// TODO: 0x20 might not be a space in all character sets...
if (mb != 0) {
if (!(mb == this.spaceChar && ignoreSpace)) {
this.addByte(mb);
}
ignoreSpace = (mb == this.spaceChar);
}
}
// TODO: Is this OK? The buffer could have ended in the middle of a word...
this.addByte(this.spaceChar);
var rawPercent = this.hitCount / this.ngramCount;
// TODO - This is a bit of a hack to take care of a case
// were we were getting a confidence of 135...
if (rawPercent > 0.33)
return 98;
return Math.floor(rawPercent * 300.0);
};
}
|
javascript
|
{
"resource": ""
}
|
q62967
|
collectScenariosFromElement
|
test
|
function collectScenariosFromElement(parentElement) {
var scenarios = [];
var templates = [];
var elements = parentElement.children();
var i = 0;
angular.forEach(elements, function(el) {
var elem = angular.element(el);
//if no source or no html, capture element itself
if (!elem.attr('src') || !elem.attr('src').match(/.html$/)) {
templates[i] = elem;
scenarios[i] = { media: elem.attr('media'), templ: i };
} else {
scenarios[i] = { media: elem.attr('media'), src: elem.attr('src') };
}
i++;
});
return {
scenarios: scenarios,
templates: templates
};
}
|
javascript
|
{
"resource": ""
}
|
q62968
|
changed
|
test
|
function changed (done) {
const files = [].slice.call(arguments);
if (typeof files[files.length - 1] === 'function') done = files.pop();
done = typeof done === 'function' ? done : () => {};
debug('Notifying %d servers - Files: ', servers.length, files);
servers.forEach(srv => {
const params = { params: { files: files } };
srv && srv.changed(params);
});
done();
}
|
javascript
|
{
"resource": ""
}
|
q62969
|
test
|
function(children, element) {
this.portalNode = document.createElement('div');
(element || document.body).appendChild(this.portalNode);
ReactDOM.render(children, this.portalNode);
}
|
javascript
|
{
"resource": ""
}
|
|
q62970
|
test
|
function() {
/* eslint-disable no-alert */
var close = typeof this.portalConfirmOnCloseMessage === 'string' ? confirm(this.portalConfirmOnCloseMessage) : true;
/* eslint-enable no-alert */
if (this.portalNode && this.portalNode.parentNode && close) {
ReactDOM.unmountComponentAtNode(this.portalNode);
this.portalNode.parentNode.removeChild(this.portalNode);
this.portalNode = null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62971
|
test
|
function(data) {
if (this.filterValue) {
data = this.quickFilterData(data, this.filterValue);
}
if (this.advancedFilters) {
data = this.advancedFilterData(data, this.advancedFilters);
}
this.dataCount = data.length;
return data;
}
|
javascript
|
{
"resource": ""
}
|
|
q62972
|
test
|
function(id, definition, dataFormatter) {
this.collection[id] = new Table(id, definition, dataFormatter);
return this.collection[id];
}
|
javascript
|
{
"resource": ""
}
|
|
q62973
|
test
|
function(payload) {
var action = payload.action;
if (!this.shouldHandleAction(action.component)) {
return;
}
switch (action.actionType) {
case ActionTypes.REQUEST_DATA:
this.handleRequestDataAction(action);
break;
case ActionTypes.TABLE_SORT:
this.collection[action.id].sortData(action.data.colIndex, action.data.direction);
this.emitChange(action.id);
break;
case ActionTypes.FILTER:
this.collection[action.id].setFilterValue(action.data.value);
this.emitChange(action.id);
break;
case ActionTypes.ADVANCED_FILTER:
this.collection[action.id].setAdvancedFilters(action.data.advancedFilters);
this.emitChange(action.id);
break;
case ActionTypes.PAGINATE:
this.collection[action.id].paginate(action.data.direction);
this.emitChange(action.id);
break;
case ActionTypes.TOGGLE_BULK_SELECT:
this.collection[action.id].updateBulkSelection(action.data.deselect);
this.emitChange(action.id);
break;
case ActionTypes.TOGGLE_ROW_SELECT:
this.collection[action.id].updateRowSelection(action.data.rowIndex);
this.emitChange(action.id);
break;
case ActionTypes.DESTROY_INSTANCE:
this.destroyInstance(action.id);
break;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62974
|
test
|
function(nextProps) {
if (this.props.filters !== nextProps.filters && JSON.stringify(this.props.filters) !== JSON.stringify(nextProps.filters)) {
setTimeout(function() {
this.requestData();
}.bind(this), 0);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62975
|
test
|
function(store) {
return {
/**
* Adds the listeners required when requesting data from the server.
*/
componentDidMount: function() {
store.on('change:' + this.props.componentId, this.onDataReceived);
store.on('fail:' + this.props.componentId, this.onError);
},
/**
* Removes the listeners required when requesting data from the server.
*/
componentWillUnmount: function() {
store.removeListener('change:' + this.props.componentId, this.onDataReceived);
store.removeListener('fail:' + this.props.componentId, this.onError);
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q62976
|
test
|
function() {
store.on('change:' + this.props.componentId, this.onDataReceived);
store.on('fail:' + this.props.componentId, this.onError);
}
|
javascript
|
{
"resource": ""
}
|
|
q62977
|
test
|
function() {
store.removeListener('change:' + this.props.componentId, this.onDataReceived);
store.removeListener('fail:' + this.props.componentId, this.onError);
}
|
javascript
|
{
"resource": ""
}
|
|
q62978
|
test
|
function(id, definition, dataFormatter, filters) {
AppDispatcher.dispatchAction({
actionType: this.actionTypes.REQUEST_DATA,
component: 'Table',
id: id,
data: {
definition: definition,
dataFormatter: dataFormatter,
filters: filters
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q62979
|
test
|
function(id, value) {
AppDispatcher.dispatchAction({
actionType: this.actionTypes.FILTER,
component: 'Table',
id: id,
data: {
value: value
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q62980
|
test
|
function(id, direction) {
AppDispatcher.dispatchAction({
actionType: this.actionTypes.PAGINATE,
component: 'Table',
id: id,
data: {
direction: direction
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q62981
|
test
|
function(id, deselect) {
AppDispatcher.dispatchAction({
actionType: this.actionTypes.TOGGLE_BULK_SELECT,
component: 'Table',
id: id,
data: {
deselect: deselect
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q62982
|
test
|
function(id, rowIndex) {
AppDispatcher.dispatchAction({
actionType: this.actionTypes.TOGGLE_ROW_SELECT,
component: 'Table',
id: id,
data: {
rowIndex: rowIndex
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q62983
|
extractValue
|
test
|
function extractValue(attr, node) {
if (attr === 'translate') {
return node.html() || getAttr(attr) || '';
}
return getAttr(attr) || node.html() || '';
}
|
javascript
|
{
"resource": ""
}
|
q62984
|
test
|
function(obj, callback, thisArg) {
return obj.map ? obj.map.call(obj, callback, thisArg) : map.call(obj, callback, thisArg);
}
|
javascript
|
{
"resource": ""
}
|
|
q62985
|
test
|
function(obj, callback, thisArg) {
return obj.filter ? obj.filter.call(obj, callback, thisArg) : filter.call(obj, callback, thisArg);
}
|
javascript
|
{
"resource": ""
}
|
|
q62986
|
test
|
function(obj, elements) {
return elements === undefined ? [] : utils.map(elements, function(item) {
return utils.indexOf(obj, item);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q62987
|
test
|
function(array, item) {
var index = utils.indexOf(array, item);
if (index === -1) { array.push(item); }
}
|
javascript
|
{
"resource": ""
}
|
|
q62988
|
test
|
function(array, idx, amt, objects) {
if (array.replace) {
return array.replace(idx, amt, objects);
} else {
return utils._replace(array, idx, amt, objects);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62989
|
test
|
function(array1, array2) {
var intersection = [];
utils.forEach(array1, function(element) {
if (utils.indexOf(array2, element) >= 0) {
intersection.push(element);
}
});
return intersection;
}
|
javascript
|
{
"resource": ""
}
|
|
q62990
|
removeListener
|
test
|
function removeListener(obj, eventName, target, method) {
Ember.assert("You must pass at least an object and event name to Ember.removeListener", !!obj && !!eventName);
if (!method && 'function' === typeof target) {
method = target;
target = null;
}
function _removeListener(target, method) {
var actions = actionsFor(obj, eventName),
actionIndex = indexOf(actions, target, method);
// action doesn't exist, give up silently
if (actionIndex === -1) { return; }
actions.splice(actionIndex, 3);
if ('function' === typeof obj.didRemoveListener) {
obj.didRemoveListener(eventName, target, method);
}
}
if (method) {
_removeListener(target, method);
} else {
var meta = obj[META_KEY],
actions = meta && meta.listeners && meta.listeners[eventName];
if (!actions) { return; }
for (var i = actions.length - 3; i >= 0; i -= 3) {
_removeListener(actions[i], actions[i+1]);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62991
|
suspendListener
|
test
|
function suspendListener(obj, eventName, target, method, callback) {
if (!method && 'function' === typeof target) {
method = target;
target = null;
}
var actions = actionsFor(obj, eventName),
actionIndex = indexOf(actions, target, method);
if (actionIndex !== -1) {
actions[actionIndex+2] |= SUSPENDED; // mark the action as suspended
}
function tryable() { return callback.call(target); }
function finalizer() { if (actionIndex !== -1) { actions[actionIndex+2] &= ~SUSPENDED; } }
return Ember.tryFinally(tryable, finalizer);
}
|
javascript
|
{
"resource": ""
}
|
q62992
|
dependentKeysDidChange
|
test
|
function dependentKeysDidChange(obj, depKey, meta) {
if (obj.isDestroying) { return; }
var seen = DID_SEEN, top = !seen;
if (top) { seen = DID_SEEN = {}; }
iterDeps(propertyDidChange, obj, depKey, seen, meta);
if (top) { DID_SEEN = null; }
}
|
javascript
|
{
"resource": ""
}
|
q62993
|
set
|
test
|
function set(obj, keyName, value, tolerant) {
if (typeof obj === 'string') {
Ember.assert("Path '" + obj + "' must be global if no obj is given.", IS_GLOBAL.test(obj));
value = keyName;
keyName = obj;
obj = null;
}
Ember.assert("Cannot call set with "+ keyName +" key.", !!keyName);
if (!obj || keyName.indexOf('.') !== -1) {
return setPath(obj, keyName, value, tolerant);
}
Ember.assert("You need to provide an object and key to `set`.", !!obj && keyName !== undefined);
Ember.assert('calling set on destroyed object', !obj.isDestroyed);
var meta = obj[META_KEY], desc = meta && meta.descs[keyName],
isUnknown, currentValue;
if (desc) {
desc.set(obj, keyName, value);
} else {
isUnknown = 'object' === typeof obj && !(keyName in obj);
// setUnknownProperty is called if `obj` is an object,
// the property does not already exist, and the
// `setUnknownProperty` method exists on the object
if (isUnknown && 'function' === typeof obj.setUnknownProperty) {
obj.setUnknownProperty(keyName, value);
} else if (meta && meta.watching[keyName] > 0) {
if (MANDATORY_SETTER) {
currentValue = meta.values[keyName];
} else {
currentValue = obj[keyName];
}
// only trigger a change if the value has changed
if (value !== currentValue) {
Ember.propertyWillChange(obj, keyName);
if (MANDATORY_SETTER) {
if ((currentValue === undefined && !(keyName in obj)) || !obj.propertyIsEnumerable(keyName)) {
Ember.defineProperty(obj, keyName, null, value); // setup mandatory setter
} else {
meta.values[keyName] = value;
}
} else {
obj[keyName] = value;
}
Ember.propertyDidChange(obj, keyName);
}
} else {
obj[keyName] = value;
}
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q62994
|
test
|
function(key, value) {
var keys = this.keys,
values = this.values,
guid = guidFor(key);
keys.add(key);
values[guid] = value;
set(this, 'length', keys.list.length);
}
|
javascript
|
{
"resource": ""
}
|
|
q62995
|
test
|
function(key) {
// don't use ES6 "delete" because it will be annoying
// to use in browsers that are not ES6 friendly;
var keys = this.keys,
values = this.values,
guid = guidFor(key);
if (values.hasOwnProperty(guid)) {
keys.remove(key);
delete values[guid];
set(this, 'length', keys.list.length);
return true;
} else {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62996
|
test
|
function(callback, self) {
var keys = this.keys,
values = this.values;
keys.forEach(function(key) {
var guid = guidFor(key);
callback.call(self, key, values[guid]);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q62997
|
test
|
function(obj) {
Ember.assert('Must pass a valid object to Ember.Binding.disconnect()', !!obj);
var twoWay = !this._oneWay;
// remove an observer on the object so we're no longer notified of
// changes that should update bindings.
Ember.removeObserver(obj, this._from, this, this.fromDidChange);
// if the binding is two-way, remove the observer from the target as well
if (twoWay) { Ember.removeObserver(obj, this._to, this, this.toDidChange); }
this._readyToSync = false; // disable scheduled syncs...
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q62998
|
filter
|
test
|
function filter(promises, filterFn, label) {
return all(promises, label).then(function(values){
if (!isArray(promises)) {
throw new TypeError('You must pass an array to filter.');
}
if (!isFunction(filterFn)){
throw new TypeError("You must pass a function to filter's second argument.");
}
return map(promises, filterFn, label).then(function(filterResults){
var i,
valuesLen = values.length,
filtered = [];
for (i = 0; i < valuesLen; i++){
if(filterResults[i]) filtered.push(values[i]);
}
return filtered;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q62999
|
Container
|
test
|
function Container(parent) {
this.parent = parent;
this.children = [];
this.resolver = parent && parent.resolver || function() {};
this.registry = new InheritingDict(parent && parent.registry);
this.cache = new InheritingDict(parent && parent.cache);
this.factoryCache = new InheritingDict(parent && parent.factoryCache);
this.resolveCache = new InheritingDict(parent && parent.resolveCache);
this.typeInjections = new InheritingDict(parent && parent.typeInjections);
this.injections = {};
this.factoryTypeInjections = new InheritingDict(parent && parent.factoryTypeInjections);
this.factoryInjections = {};
this._options = new InheritingDict(parent && parent._options);
this._typeOptions = new InheritingDict(parent && parent._typeOptions);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.