_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3100
|
_suspendBeforeObserver
|
train
|
function _suspendBeforeObserver(obj, path, target, method, callback) {
return suspendListener(obj, beforeEvent(path), target, method, callback);
}
|
javascript
|
{
"resource": ""
}
|
q3101
|
set
|
train
|
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) {
return setPath(obj, keyName, value, tolerant);
}
var meta = obj['__ember_meta__'];
var desc = meta && meta.descs[keyName];
var isUnknown, currentValue;
if (desc === undefined && isPath(keyName)) {
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);
if (desc !== undefined) {
desc.set(obj, keyName, value);
} else {
if (typeof obj === 'object' && obj !== null && value !== undefined && obj[keyName] === value) {
return value;
}
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 (hasPropertyAccessors) {
currentValue = meta.values[keyName];
} else {
currentValue = obj[keyName];
}
// only trigger a change if the value has changed
if (value !== currentValue) {
propertyWillChange(obj, keyName);
if (hasPropertyAccessors) {
if (
(currentValue === undefined && !(keyName in obj)) ||
!Object.prototype.propertyIsEnumerable.call(obj, keyName)
) {
defineProperty(obj, keyName, null, value); // setup mandatory setter
} else {
meta.values[keyName] = value;
}
} else {
obj[keyName] = value;
}
propertyDidChange(obj, keyName);
}
} else {
obj[keyName] = value;
}
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q3102
|
intern
|
train
|
function intern(str) {
var obj = {};
obj[str] = 1;
for (var key in obj) {
if (key === str) return key;
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q3103
|
makeArray
|
train
|
function makeArray(obj) {
if (obj === null || obj === undefined) { return []; }
return isArray(obj) ? obj : [obj];
}
|
javascript
|
{
"resource": ""
}
|
q3104
|
typeOf
|
train
|
function typeOf(item) {
var ret, modulePath;
// ES6TODO: Depends on Ember.Object which is defined in runtime.
if (typeof EmberObject === "undefined") {
modulePath = 'ember-runtime/system/object';
if (Ember.__loader.registry[modulePath]) {
EmberObject = Ember.__loader.require(modulePath)['default'];
}
}
ret = (item === null || item === undefined) ? String(item) : TYPE_MAP[toString.call(item)] || 'object';
if (ret === 'function') {
if (EmberObject && EmberObject.detect(item)) ret = 'class';
} else if (ret === 'object') {
if (item instanceof Error) ret = 'error';
else if (EmberObject && item instanceof EmberObject) ret = 'instance';
else if (item instanceof Date) ret = 'date';
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q3105
|
watchKey
|
train
|
function watchKey(obj, keyName, meta) {
// can't watch length on Array - it is special...
if (keyName === 'length' && typeOf(obj) === 'array') { return; }
var m = meta || metaFor(obj), watching = m.watching;
// activate watching first time
if (!watching[keyName]) {
watching[keyName] = 1;
var desc = m.descs[keyName];
if (desc && desc.willWatch) { desc.willWatch(obj, keyName); }
if ('function' === typeof obj.willWatchProperty) {
obj.willWatchProperty(keyName);
}
if (hasPropertyAccessors) {
handleMandatorySetter(m, obj, keyName);
}
} else {
watching[keyName] = (watching[keyName] || 0) + 1;
}
}
|
javascript
|
{
"resource": ""
}
|
q3106
|
train
|
function() {
this._super.apply(this, arguments);
Ember.deprecate('Using currentWhen with {{link-to}} is deprecated in favor of `current-when`.', !this.currentWhen);
// Map desired event name to invoke function
var eventName = get(this, 'eventName');
this.on(eventName, this, this._invoke);
}
|
javascript
|
{
"resource": ""
}
|
|
q3107
|
train
|
function(){
var helperParameters = this.parameters;
var linkTextPath = helperParameters.options.linkTextPath;
var paths = getResolvedPaths(helperParameters);
var length = paths.length;
var path, i, normalizedPath;
if (linkTextPath) {
normalizedPath = getNormalizedPath(linkTextPath, helperParameters);
this.registerObserver(normalizedPath.root, normalizedPath.path, this, this.rerender);
}
for(i=0; i < length; i++) {
path = paths[i];
if (null === path) {
// A literal value was provided, not a path, so nothing to observe.
continue;
}
normalizedPath = getNormalizedPath(path, helperParameters);
this.registerObserver(normalizedPath.root, normalizedPath.path, this, this._paramsChanged);
}
var queryParamsObject = this.queryParamsObject;
if (queryParamsObject) {
var values = queryParamsObject.values;
// Install observers for all of the hash options
// provided in the (query-params) subexpression.
for (var k in values) {
if (!values.hasOwnProperty(k)) { continue; }
if (queryParamsObject.types[k] === 'ID') {
normalizedPath = getNormalizedPath(values[k], helperParameters);
this.registerObserver(normalizedPath.root, normalizedPath.path, this, this._paramsChanged);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3108
|
train
|
function(params, transition) {
var match, name, sawParams, value;
var queryParams = get(this, '_qp.map');
for (var prop in params) {
if (prop === 'queryParams' || (queryParams && prop in queryParams)) {
continue;
}
if (match = prop.match(/^(.*)_id$/)) {
name = match[1];
value = params[prop];
}
sawParams = true;
}
if (!name && sawParams) { return copy(params); }
else if (!name) {
if (transition.resolveIndex < 1) { return; }
var parentModel = transition.state.handlerInfos[transition.resolveIndex-1].context;
return parentModel;
}
return this.findModel(name, value);
}
|
javascript
|
{
"resource": ""
}
|
|
q3109
|
train
|
function(name, model) {
var container = this.container;
model = model || this.modelFor(name);
return generateController(container, name, model);
}
|
javascript
|
{
"resource": ""
}
|
|
q3110
|
train
|
function(infos) {
updatePaths(this);
this._cancelLoadingEvent();
this.notifyPropertyChange('url');
// Put this in the runloop so url will be accurate. Seems
// less surprising than didTransition being out of sync.
run.once(this, this.trigger, 'didTransition');
if (get(this, 'namespace').LOG_TRANSITIONS) {
Ember.Logger.log("Transitioned into '" + EmberRouter._routePath(infos) + "'");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3111
|
train
|
function(routeName, models, queryParams) {
var router = this.router;
return router.isActive.apply(router, arguments);
}
|
javascript
|
{
"resource": ""
}
|
|
q3112
|
train
|
function(callback) {
var router = this.router;
if (!router) {
router = new Router();
router._triggerWillChangeContext = Ember.K;
router._triggerWillLeave = Ember.K;
router.callbacks = [];
router.triggerEvent = triggerEvent;
this.reopenClass({ router: router });
}
var dsl = EmberRouterDSL.map(function() {
this.resource('application', { path: "/" }, function() {
for (var i=0; i < router.callbacks.length; i++) {
router.callbacks[i].call(this);
}
callback.call(this);
});
});
router.callbacks.push(callback);
router.map(dsl.generate());
return router;
}
|
javascript
|
{
"resource": ""
}
|
|
q3113
|
map
|
train
|
function map(dependentKey, callback) {
var options = {
addedItem: function(array, item, changeMeta, instanceMeta) {
var mapped = callback.call(this, item, changeMeta.index);
array.insertAt(changeMeta.index, mapped);
return array;
},
removedItem: function(array, item, changeMeta, instanceMeta) {
array.removeAt(changeMeta.index, 1);
return array;
}
};
return arrayComputed(dependentKey, options);
}
|
javascript
|
{
"resource": ""
}
|
q3114
|
sort
|
train
|
function sort(itemsKey, sortDefinition) {
Ember.assert('Ember.computed.sort requires two arguments: an array key to sort and ' +
'either a sort properties key or sort function', arguments.length === 2);
if (typeof sortDefinition === 'function') {
return customSort(itemsKey, sortDefinition);
} else {
return propertySort(itemsKey, sortDefinition);
}
}
|
javascript
|
{
"resource": ""
}
|
q3115
|
train
|
function(actionName) {
var args = [].slice.call(arguments, 1);
var target;
if (this._actions && this._actions[actionName]) {
if (this._actions[actionName].apply(this, args) === true) {
// handler returned true, so this action will bubble
} else {
return;
}
}
if (target = get(this, 'target')) {
Ember.assert("The `target` for " + this + " (" + target + ") does not have a `send` method", typeof target.send === 'function');
target.send.apply(target, arguments);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3116
|
train
|
function(removing, adding) {
var removeCnt, addCnt, hasDelta;
if ('number' === typeof removing) removeCnt = removing;
else if (removing) removeCnt = get(removing, 'length');
else removeCnt = removing = -1;
if ('number' === typeof adding) addCnt = adding;
else if (adding) addCnt = get(adding,'length');
else addCnt = adding = -1;
hasDelta = addCnt<0 || removeCnt<0 || addCnt-removeCnt!==0;
if (removing === -1) removing = null;
if (adding === -1) adding = null;
propertyWillChange(this, '[]');
if (hasDelta) propertyWillChange(this, 'length');
sendEvent(this, '@enumerable:before', [this, removing, adding]);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q3117
|
train
|
function(name, target, method) {
if (!method) {
method = target;
target = null;
}
addListener(this, name, target, method, true);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q3118
|
train
|
function(name) {
var length = arguments.length;
var args = new Array(length - 1);
for (var i = 1; i < length; i++) {
args[i - 1] = arguments[i];
}
sendEvent(this, name, args);
}
|
javascript
|
{
"resource": ""
}
|
|
q3119
|
train
|
function(objects) {
if (!(Enumerable.detect(objects) || isArray(objects))) {
throw new TypeError("Must pass Ember.Enumerable to Ember.MutableArray#pushObjects");
}
this.replace(get(this, 'length'), 0, objects);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q3120
|
train
|
function(objects) {
beginPropertyChanges(this);
for (var i = objects.length - 1; i >= 0; i--) {
this.removeObject(objects[i]);
}
endPropertyChanges(this);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q3121
|
train
|
function() {
var C = this;
var l = arguments.length;
if (l > 0) {
var args = new Array(l);
for (var i = 0; i < l; i++) {
args[i] = arguments[i];
}
this._initProperties(args);
}
return new C();
}
|
javascript
|
{
"resource": ""
}
|
|
q3122
|
train
|
function(obj) {
// fail fast
if (!Enumerable.detect(obj)) return false;
var loc = get(this, 'length');
if (get(obj, 'length') !== loc) return false;
while(--loc >= 0) {
if (!obj.contains(this[loc])) return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q3123
|
train
|
function() {
if (get(this, 'isFrozen')) throw new EmberError(FROZEN_ERROR);
var obj = this.length > 0 ? this[this.length-1] : null;
this.remove(obj);
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q3124
|
train
|
function (index) {
var split = false;
var arrayOperationIndex, arrayOperation,
arrayOperationRangeStart, arrayOperationRangeEnd,
len;
// OPTIMIZE: we could search these faster if we kept a balanced tree.
// find leftmost arrayOperation to the right of `index`
for (arrayOperationIndex = arrayOperationRangeStart = 0, len = this._operations.length; arrayOperationIndex < len; ++arrayOperationIndex) {
arrayOperation = this._operations[arrayOperationIndex];
if (arrayOperation.type === DELETE) { continue; }
arrayOperationRangeEnd = arrayOperationRangeStart + arrayOperation.count - 1;
if (index === arrayOperationRangeStart) {
break;
} else if (index > arrayOperationRangeStart && index <= arrayOperationRangeEnd) {
split = true;
break;
} else {
arrayOperationRangeStart = arrayOperationRangeEnd + 1;
}
}
return new ArrayOperationMatch(arrayOperation, arrayOperationIndex, split, arrayOperationRangeStart);
}
|
javascript
|
{
"resource": ""
}
|
|
q3125
|
train
|
function(rootElement, event, eventName) {
var self = this;
rootElement.on(event + '.ember', '.ember-view', function(evt, triggeringManager) {
var view = View.views[this.id];
var result = true;
var manager = self.canDispatchToEventManager ? self._findNearestEventManager(view, eventName) : null;
if (manager && manager !== triggeringManager) {
result = self._dispatchEvent(manager, evt, eventName, view);
} else if (view) {
result = self._bubbleEvent(view, evt, eventName);
}
return result;
});
rootElement.on(event + '.ember', '[data-ember-action]', function(evt) {
var actionId = jQuery(evt.currentTarget).attr('data-ember-action');
var action = ActionManager.registeredActions[actionId];
// We have to check for action here since in some cases, jQuery will trigger
// an event on `removeChild` (i.e. focusout) after we've already torn down the
// action handlers for the view.
if (action && action.eventName === eventName) {
return action.handler(evt);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3126
|
train
|
function(content, start, removedCount) {
// If the contents were empty before and this template collection has an
// empty view remove it now.
var emptyView = get(this, 'emptyView');
if (emptyView && emptyView instanceof View) {
emptyView.removeFromParent();
}
// Loop through child views that correspond with the removed items.
// Note that we loop from the end of the array to the beginning because
// we are mutating it as we go.
var childViews = this._childViews;
var childView, idx;
for (idx = start + removedCount - 1; idx >= start; idx--) {
childView = childViews[idx];
childView.destroy();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3127
|
train
|
function(content, start, removed, added) {
var addedViews = [];
var view, item, idx, len, itemViewClass, emptyView;
len = content ? get(content, 'length') : 0;
if (len) {
itemViewClass = get(this, 'itemViewClass');
itemViewClass = handlebarsGetView(content, itemViewClass, this.container);
for (idx = start; idx < start+added; idx++) {
item = content.objectAt(idx);
view = this.createChildView(itemViewClass, {
content: item,
contentIndex: idx
});
addedViews.push(view);
}
} else {
emptyView = get(this, 'emptyView');
if (!emptyView) { return; }
if ('string' === typeof emptyView && isGlobalPath(emptyView)) {
emptyView = get(emptyView) || emptyView;
}
emptyView = this.createChildView(emptyView);
addedViews.push(emptyView);
set(this, 'emptyView', emptyView);
if (CoreView.detect(emptyView)) {
this._createdEmptyView = emptyView;
}
}
this.replace(start, 0, addedViews);
}
|
javascript
|
{
"resource": ""
}
|
|
q3128
|
train
|
function(classBindings) {
var classNames = this.classNames;
var elem, newClass, dasherizedClass;
// Loop through all of the configured bindings. These will be either
// property names ('isUrgent') or property paths relative to the view
// ('content.isUrgent')
forEach(classBindings, function(binding) {
Ember.assert("classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. ['foo', ':bar']", binding.indexOf(' ') === -1);
// Variable in which the old class value is saved. The observer function
// closes over this variable, so it knows which string to remove when
// the property changes.
var oldClass;
// Extract just the property name from bindings like 'foo:bar'
var parsedPath = View._parsePropertyPath(binding);
// Set up an observer on the context. If the property changes, toggle the
// class name.
var observer = function() {
// Get the current value of the property
newClass = this._classStringForProperty(binding);
elem = this.$();
// If we had previously added a class to the element, remove it.
if (oldClass) {
elem.removeClass(oldClass);
// Also remove from classNames so that if the view gets rerendered,
// the class doesn't get added back to the DOM.
classNames.removeObject(oldClass);
}
// If necessary, add a new class. Make sure we keep track of it so
// it can be removed in the future.
if (newClass) {
elem.addClass(newClass);
oldClass = newClass;
} else {
oldClass = null;
}
};
// Get the class name for the property at its current value
dasherizedClass = this._classStringForProperty(binding);
if (dasherizedClass) {
// Ensure that it gets into the classNames array
// so it is displayed when we render.
addObject(classNames, dasherizedClass);
// Save a reference to the class name so we can remove it
// if the observer fires. Remember that this variable has
// been closed over by the observer.
oldClass = dasherizedClass;
}
this.registerObserver(this, parsedPath.path, observer);
// Remove className so when the view is rerendered,
// the className is added based on binding reevaluation
this.one('willClearRender', function() {
if (oldClass) {
classNames.removeObject(oldClass);
oldClass = null;
}
});
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q3129
|
train
|
function(property) {
var parsedPath = View._parsePropertyPath(property);
var path = parsedPath.path;
var val = get(this, path);
if (val === undefined && isGlobalPath(path)) {
val = get(Ember.lookup, path);
}
return View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName);
}
|
javascript
|
{
"resource": ""
}
|
|
q3130
|
interiorNamespace
|
train
|
function interiorNamespace(element){
if (
element &&
element.namespaceURI === svgNamespace &&
!svgHTMLIntegrationPoints[element.tagName]
) {
return svgNamespace;
} else {
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
q3131
|
buildSafeDOM
|
train
|
function buildSafeDOM(html, contextualElement, dom) {
var childNodes = buildIESafeDOM(html, contextualElement, dom);
if (contextualElement.tagName === 'SELECT') {
// Walk child nodes
for (var i = 0; childNodes[i]; i++) {
// Find and process the first option child node
if (childNodes[i].tagName === 'OPTION') {
if (detectAutoSelectedOption(childNodes[i].parentNode, childNodes[i], html)) {
// If the first node is selected but does not have an attribute,
// presume it is not really selected.
childNodes[i].parentNode.selectedIndex = -1;
}
break;
}
}
}
return childNodes;
}
|
javascript
|
{
"resource": ""
}
|
q3132
|
filterArguments
|
train
|
function filterArguments(args, params, inject) {
var newArgs = ['node', '_mocha'].concat(inject || []),
param, i, len,
type;
for (i = 2, len = args.length; i < len; i++) {
if ((i < args.length - 1) && (args[i].length > 2) && (args[i].substr(0, 2) === '--')) {
// Get parameter without '--'
param = args[i].substr(2);
// Is parameter used?
if (params.hasOwnProperty(param)) {
// Remember what the type was
type = typeof params[param];
// Overwrite value with next value in arguments
if (type === 'boolean') {
params[param] = true;
} else {
params[param] = args[i + 1];
i++;
// Convert back to boolean if needed
if (type === 'number') {
params[param] = parseFloat(params[param]);
}
}
} else {
newArgs.push(args[i]);
}
} else {
newArgs.push(args[i]);
}
}
// Set test-path with last argument if none given
if (!params['test-path']) {
params['test-path'] = args.pop();
}
newArgs.push(path.join(__dirname, '..', 'resource', 'run.js'));
return newArgs;
}
|
javascript
|
{
"resource": ""
}
|
q3133
|
prepareEnvironment
|
train
|
function prepareEnvironment (argv) {
var params, args;
// Define default values
params = {
'approved-folder': 'approved',
'build-folder': 'build',
'highlight-folder': 'highlight',
'config-folder': 'config',
'fail-orphans': false,
'fail-additions': false,
'test-path': null,
'config': null
};
// Filter arguments
args = filterArguments(argv, params, [
'--slow', '5000',
'--no-timeouts'
]);
if (!fs.existsSync(params['test-path'])) {
throw new Error('Cannot find path to ' + params['test-path']);
} else {
params['test-path'] = path.resolve(params['test-path']);
}
// Load global config
if (typeof params['config'] === 'string') {
params['config'] = require(path.resolve(params['config']));
} else {
params['config'] = params['config'] || {};
}
// Set global variable for test-runner
global.koboldOptions = {
"verbose": false,
"failForOrphans": params['fail-orphans'],
"failOnAdditions": params['fail-additions'],
"build": params['build'],
"comparison": params['config'],
"storage": {
"type": 'File',
"options": {
"path": params['test-path'],
"approvedFolderName": params['approved-folder'],
"buildFolderName": params['build-folder'],
"highlightFolderName": params['highlight-folder'],
"configFolderName": params['config-folder']
}
}
};
return args;
}
|
javascript
|
{
"resource": ""
}
|
q3134
|
makeBarsChartPath
|
train
|
function makeBarsChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, paddingLeft, isRange) {
let heightScaler = (chartHeight-markerRadius)/maxValue;
let xSpacing = width / pointsOnScreen;
let barWidth = xSpacing - paddingLeft;
let fullWidth = paddingLeft/2 + (paddingLeft+barWidth) * (chart.data.length-1) + barWidth;
let pathStr = []
let barCords = [];
let x1, y1, y2;
chart.data.some((d, idx) => {
x1 = paddingLeft/2 + (paddingLeft+barWidth) * idx;
if (x1 > fullWidth * t && chart.drawChart) {
return true;
}
if (chart.stretchChart) {
x1 = x1 * t;
}
y1 = (chartHeight+chartHeightOffset) - d.value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1);
y2 = isRange ? (chartHeight+chartHeightOffset) - d.valueLow * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1) : (chartHeight+chartHeightOffset);
pathStr.push('M');
pathStr.push(x1);
pathStr.push(y2);
pathStr.push('H');
pathStr.push(x1 + barWidth);
pathStr.push('V');
pathStr.push(y1);
pathStr.push('H');
pathStr.push(x1);
pathStr.push('V');
pathStr.push(y2);
barCords.push({x1: x1, x2: x1+barWidth, y1: y1, y2: y2});
});
return {
path: pathStr.join(' '),
width: fullWidth,
maxScroll: fullWidth - width,
barCords: barCords
};
}
|
javascript
|
{
"resource": ""
}
|
q3135
|
makeStackedBarsChartPath
|
train
|
function makeStackedBarsChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, paddingLeft, yAxisWidth, isRange) {
let heightScaler = (chartHeight-markerRadius)/maxValue;
width = width - yAxisWidth;
let xSpacing = width / pointsOnScreen;
let barWidth = xSpacing - paddingLeft;
let fullWidth = paddingLeft/2 + (paddingLeft+barWidth) * (chart.data.length-1) + barWidth;
let paths = []
let barCords = [];
let x1, y1, y2;
chart.data.some((d, idx) => {
x1 = paddingLeft/2 + (paddingLeft+barWidth) * idx + yAxisWidth;
if (x1 > fullWidth * t && chart.drawChart) {
return true;
}
if (chart.stretchChart) {
x1 = x1 * t;
}
let prevY = 0;
d.forEach((stack) => {
y1 = (chartHeight+chartHeightOffset) - (stack.value+prevY) * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1);
//y2 = isRange ? (chartHeight+chartHeightOffset) - prevY * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1) : (chartHeight+chartHeightOffset);
y2 = isRange ? (chartHeight+chartHeightOffset) - prevY * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1) : (chartHeight+chartHeightOffset);
prevY += stack.value;
paths.push({path: makeBarPath(x1, y1, y2, barWidth), color: stack.color});
barCords.push({x1: x1, x2: x1+barWidth, y1: y1, y2: y2});
});
});
return {
//path: pathStr.join(' '),
path: paths,
width: fullWidth,
maxScroll: fullWidth - width,
barCords: barCords
};
}
|
javascript
|
{
"resource": ""
}
|
q3136
|
makeAreaChartPath
|
train
|
function makeAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen) {
return makeLineOrAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, true, false);
}
|
javascript
|
{
"resource": ""
}
|
q3137
|
makeLineChartPath
|
train
|
function makeLineChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen) {
return makeLineOrAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, false, false);
}
|
javascript
|
{
"resource": ""
}
|
q3138
|
makeLineOrAreaChartPath
|
train
|
function makeLineOrAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, makeArea, isRange) {
let heightScaler = (chartHeight-markerRadius)/maxValue;
let xSpacing = width / pointsOnScreen;
let centeriser = xSpacing / 2 - markerRadius;
let fullWidth = xSpacing*(chart.data.length-1) + markerRadius + centeriser;
let lineStrArray = makeArea && !isRange ? ['M' + markerRadius, chartHeight+chartHeightOffset] : [];
if (isRange) {
lineStrArray.push('M');
lineStrArray.push(makeXcord(chart, fullWidth, t, centeriser, markerRadius));
lineStrArray.push((chartHeight+chartHeightOffset) - chart.data[0].value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[0 % chart.timingFunctions.length](t) : 1));
}
let xCord;
let lowCords = [];
chart.data.some((d, idx) => {
let spacing = idx*xSpacing + centeriser;
if (spacing > fullWidth * t && chart.drawChart) {
return true;
}
xCord = makeXcord(chart, fullWidth, t, spacing, markerRadius);
// Move line to to next x-coordinate:
lineStrArray.push((idx > 0 || makeArea ? 'L' : 'M') + xCord);
// And y-cordinate:
let yCord = (chartHeight+chartHeightOffset) - d.value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1);
lineStrArray.push(yCord);
if (isRange) {
let yCordLow = (chartHeight+chartHeightOffset) - d.valueLow * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1);
lowCords.unshift({xCord, yCordLow});
}
});
if (makeArea) {
if (isRange) {
lowCords.forEach((d) => {
lineStrArray.push('L' + d.xCord);
lineStrArray.push(d.yCordLow);
});
// lineStrArray.push('L' + makeXcord(chart, fullWidth, t, xSpacing + centeriser, markerRadius));
// lineStrArray.push(d.yCordLow);
} else {
lineStrArray.push('L' + xCord);
lineStrArray.push(chartHeight + chartHeightOffset);
}
lineStrArray.push('Z');
}
return {
path: lineStrArray.join(' '),
width: xCord + markerRadius,
maxScroll: fullWidth - xSpacing + markerRadius
};
}
|
javascript
|
{
"resource": ""
}
|
q3139
|
makeSplineChartPath
|
train
|
function makeSplineChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, closePath) {
let heightScaler = (chartHeight-markerRadius)/maxValue;
let xSpacing = width / pointsOnScreen;
let centeriser = xSpacing / 2 - markerRadius;
let fullWidth = xSpacing*(chart.data.length-1) + markerRadius + centeriser;
let xCord;
let xCords = [];
let yCords = [];
chart.data.forEach((d, idx) => {
let spacing = idx*xSpacing + centeriser;
if (spacing > fullWidth * t && chart.drawChart) {
return true;
}
xCord = makeXcord(chart, fullWidth, t, spacing, markerRadius);
xCords.push(xCord);
yCords.push((chartHeight+chartHeightOffset) - d.value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1));
});
let px = computeSplineControlPoints(xCords);
let py = computeSplineControlPoints(yCords);
let splines = [`M ${xCords[0]} ${yCords[0]}`];
for (i=0;i<xCords.length-1;i++) {
splines.push(makeSpline(xCords[i],yCords[i],px.p1[i],py.p1[i],px.p2[i],py.p2[i],xCords[i+1],yCords[i+1]));
}
if (closePath) { // close for area spline graph
splines.push(`V ${chartHeight+chartHeightOffset} H ${xCords[0]} Z`);
}
return {
path: splines.join(','),
width: xCords.slice(-1) + markerRadius,
maxScroll: fullWidth - xSpacing + markerRadius
};
}
|
javascript
|
{
"resource": ""
}
|
q3140
|
rgbaToHsla
|
train
|
function rgbaToHsla(h, s, l, a) {
return [...rgbToHsl(h,s,l), a];
}
|
javascript
|
{
"resource": ""
}
|
q3141
|
inerpolateColorsFixedAlpha
|
train
|
function inerpolateColorsFixedAlpha(col1, col2, amount, alpha) {
let col1rgb = parseColor(col1);
let col2rgb = parseColor(col2);
return RGBobj2string({
r: Math.min(255, col1rgb.r * amount + col2rgb.r * Math.max(0,1-amount)),
g: Math.min(255, col1rgb.g * amount + col2rgb.g * Math.max(0,1-amount)),
b: Math.min(255, col1rgb.b * amount + col2rgb.b * Math.max(0,1-amount)),
a: alpha
});
}
|
javascript
|
{
"resource": ""
}
|
q3142
|
shadeColor
|
train
|
function shadeColor(col, amount) {
let col1rgb = parseColor(col);
return RGBobj2string({
r: Math.min(255, col1rgb.r * amount + 0 * Math.max(0,1-amount)),
g: Math.min(255, col1rgb.g * amount + 0 * Math.max(0,1-amount)),
b: Math.min(255, col1rgb.b * amount + 0 * Math.max(0,1-amount)),
a: col1rgb.a
});
}
|
javascript
|
{
"resource": ""
}
|
q3143
|
lightenColor
|
train
|
function lightenColor(col, amount) {
let colRgba = parseColor(col);
let colHsla = rgbaToHsla(colRgba.r, colRgba.g, colRgba.b, colRgba.a);
colRgba = hslaToRgba(colHsla[0],colHsla[1],Math.min(Math.max(colHsla[2]+amount, 0), 1),colHsla[3]);
return RGBobj2string({
r: colRgba[0],
g: colRgba[1],
b: colRgba[2],
a: colRgba[3]
});
}
|
javascript
|
{
"resource": ""
}
|
q3144
|
hueshiftColor
|
train
|
function hueshiftColor(col, amount) {
let colRgba = parseColor(col);
let colHsla = rgbaToHsla(colRgba.r, colRgba.g, colRgba.b, colRgba.a);
colRgba = hslaToRgba((hsl[0] + amount) % 1, colHsla[1], colHsla[2],colHsla[3]);
return RGBobj2string({
r: colRgba[0],
g: colRgba[1],
b: colRgba[2],
a: colRgba[3]
});
}
|
javascript
|
{
"resource": ""
}
|
q3145
|
getMaxSumStack
|
train
|
function getMaxSumStack(arr) { //here!!!
let maxValue = Number.MIN_VALUE;
arr
.forEach((d) => {
let stackSum = computeArrayValueSum(d);
if (stackSum > maxValue) {
maxValue = stackSum;
}
});
return maxValue;
}
|
javascript
|
{
"resource": ""
}
|
q3146
|
getMinMaxValuesXY
|
train
|
function getMinMaxValuesXY(arr) {
let maxValueX = Number.MIN_VALUE;
let maxValueY = Number.MIN_VALUE;
let minValueX = Number.MAX_VALUE;
let minValueY = Number.MAX_VALUE;
arr
.forEach((d) => {
if (d.x > maxValueX) {
maxValueX = d.x;
}
if (d.x < minValueX) {
minValueX = d.x;
}
if (d.y > maxValueY) {
maxValueY = d.y;
}
if (d.y < minValueY) {
minValueY = d.y;
}
});
return {maxValueX, minValueX, maxValueY, minValueY};
}
|
javascript
|
{
"resource": ""
}
|
q3147
|
getMinMaxValuesCandlestick
|
train
|
function getMinMaxValuesCandlestick(arr) {
let maxValue = Number.MIN_VALUE;
let minValue = Number.MAX_VALUE;
arr
.forEach((d) => {
if (d.high > maxValue) {
maxValue = d.high;
}
if (d.low < minValue) {
minValue = d.low;
}
});
return {maxValue, minValue};
}
|
javascript
|
{
"resource": ""
}
|
q3148
|
findRectangleIndexContainingPoint
|
train
|
function findRectangleIndexContainingPoint(rectangles, x, y) {
let closestIdx;
rectangles.some((d, idx) => {
if ((d.x1 <= x && x <= d.x2) && (d.y1 <= y && y <= d.y2)) {
closestIdx = idx;
return true;
}
return false;
});
return closestIdx;
}
|
javascript
|
{
"resource": ""
}
|
q3149
|
findClosestPointIndexWithinRadius
|
train
|
function findClosestPointIndexWithinRadius(points, x, y, radiusThreshold) {
let closestIdx;
let closestDist = Number.MAX_VALUE;
points.forEach((d, idx) => {
let distSqrd = Math.pow(d.x - x, 2) + Math.pow(d.y - y, 2); // changeto: (d.x - x)**2 + (d.y - y)**2;
if (distSqrd < closestDist && distSqrd < radiusThreshold) {
closestIdx = idx;
closestDist = distSqrd;
}
});
return closestIdx;
}
|
javascript
|
{
"resource": ""
}
|
q3150
|
train
|
function (fieldDefinition) {
let type = fieldDefinition.fieldType;
if (typeof type === 'object') {
type = fieldDefinition.fieldType.type;
}
return type;
}
|
javascript
|
{
"resource": ""
}
|
|
q3151
|
buildConfig
|
train
|
function buildConfig( wantedEnv )
{
const isValid = wantedEnv &&
wantedEnv.length > 0 && allowedEnvs.indexOf( wantedEnv ) !== -1;
const validEnv = isValid ? wantedEnv : 'dev';
return configs[ validEnv ];
}
|
javascript
|
{
"resource": ""
}
|
q3152
|
generate
|
train
|
function generate (projectPatch, source, done) {
shell.mkdir('-p', projectPatch)
shell.cp('-Rf', source, projectPatch)
done()
}
|
javascript
|
{
"resource": ""
}
|
q3153
|
getCacheRefreshInterval
|
train
|
function getCacheRefreshInterval() {
var value = parseInt(process.env[CACHE_REFRESH_KEY]);
// Should we 0 here to invalidate the cache immediately?
if (value && !isNaN(value) && value > 0) {
return value;
}
return DEFAULT_CACHE_REFRESH_SECONDS;
}
|
javascript
|
{
"resource": ""
}
|
q3154
|
createLocal
|
train
|
function createLocal(id) {
var nstr = prefix + id.replace(/\_/g, "__")
localVars.push(nstr)
return nstr
}
|
javascript
|
{
"resource": ""
}
|
q3155
|
createThisVar
|
train
|
function createThisVar(id) {
var nstr = "this_" + id.replace(/\_/g, "__")
thisVars.push(nstr)
return nstr
}
|
javascript
|
{
"resource": ""
}
|
q3156
|
rewrite
|
train
|
function rewrite(node, nstr) {
var lo = node.range[0], hi = node.range[1]
for(var i=lo+1; i<hi; ++i) {
exploded[i] = ""
}
exploded[lo] = nstr
}
|
javascript
|
{
"resource": ""
}
|
q3157
|
CacheClient
|
train
|
function CacheClient(store, config) {
EventEmitter.call(this);
this._store = store;
this._config = config || {};
util.propagateEvent(this._store, this, 'error');
this.on('error', unhandledErrorListener);
}
|
javascript
|
{
"resource": ""
}
|
q3158
|
timeit
|
train
|
async function timeit(fun, context={}, args=[]) {
const start = now();
await fun.call(context, ...args);
const end = now();
return end - start;
}
|
javascript
|
{
"resource": ""
}
|
q3159
|
getCache
|
train
|
function getCache() {
return new Promise(function(resolve, reject) {
// create and fetch the cache key
get(getKey(), function(err, data) {
if (err) {
return reject(err);
}
resolve(data);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q3160
|
putCache
|
train
|
function putCache() {
return new Promise(function(resolve, reject) {
// make the cache key
let key = getKey();
// adapt the image
adapt(function(err, stdout, stderr) {
if (err) {
return reject(err);
}
// convert the new image stream to buffer
stream2buffer(stdout, function(err, buffer) {
if (err) {
return reject(err);
}
if (!buffer || !buffer.length) {
return resolve(buffer);
}
// put the buffer in the cache
put(key, buffer, function(err, data) {
if (err) {
log(`Cache set failure: ${err instanceof Error ? err.message : err}`);
}
// return the buffer
resolve(buffer);
});
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q3161
|
getKey
|
train
|
function getKey() {
let paramString =
width + 'x' + height + '-'
+ path
+ (is2x ? '-@2x' : '')
+ (bg ? `_${bg}` : '')
+ (crop ? '_crop' : '')
+ (mode ? `_${mode}` : '')
+ (trim ? '_trim' : '');
return paramString + '-' + crypto.createHash('sha1').update(paramString).digest('hex');
}
|
javascript
|
{
"resource": ""
}
|
q3162
|
train
|
function(type, resStr, resArr, resObj) {
switch(type){
case 'css':
var css = resObj;
for (var res in resArr) {
//means that you will find options.
if (typeof(resArr[res]) == "object") {
//console.info('found object ', resArr[res]);
css.media = (resArr[res].options.media) ? resArr[res].options.media : css.media;
css.rel = (resArr[res].options.rel) ? resArr[res].options.rel : css.rel;
css.type = (resArr[res].options.type) ? resArr[res].options.type : css.type;
if (!css.content[resArr[res]._]) {
css.content[resArr[res]._] = '<link href="'+ resArr[res]._ +'" media="'+ css.media +'" rel="'+ css.rel +'" type="'+ css.type +'">';
resStr += '\n\t' + css.content[resArr[res]._]
}
} else {
css.content[resArr[res]] = '<link href="'+ resArr[res] +'" media="screen" rel="'+ css.rel +'" type="'+ css.type +'">';
resStr += '\n\t' + css.content[resArr[res]]
}
}
return { css : css, cssStr : resStr }
break;
case 'js':
var js = resObj;
for (var res in resArr) {
//means that you will find options
if ( typeof(resArr[res]) == "object" ) {
js.type = (resArr[res].options.type) ? resArr[res].options.type : js.type;
if (!js.content[resArr[res]._]) {
js.content[resArr[res]._] = '<script type="'+ js.type +'" src="'+ resArr[res]._ +'"></script>';
resStr += '\n' + js.content[resArr[res]._];
}
} else {
js.content[resArr[res]] = '<script type="'+ js.type +'" src="'+ resArr[res] +'"></script>';
resStr += '\n' + js.content[resArr[res]]
}
}
return { js : js, jsStr : resStr }
break;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3163
|
train
|
function (i, res, files, cb) {
if (!files.length || files.length == 0) {
cb(false)
} else {
if ( fs.existsSync(files[i].target) ) new _(files[i].target).rmSync();
var sourceStream = fs.createReadStream(files[i].source);
var destinationStream = fs.createWriteStream(files[i].target);
sourceStream
.pipe(destinationStream)
.on('error', function () {
var err = 'Error on SuperController::copyFile(...): Not found ' + files[i].source + ' or ' + files[i].target;
cb(err)
})
.on('close', function () {
try {
fs.unlinkSync(files[i].source);
files.splice(i, 1);
} catch (err) {
cb(err)
}
movefiles(i, res, files, cb)
})
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3164
|
train
|
function(req) {
req.getParams = function() {
// copy
var params = JSON.parse(JSON.stringify(req.params));
switch( req.method.toLowerCase() ) {
case 'get':
params = merge(params, req.get, true);
break;
case 'post':
params = merge(params, req.post, true);
break;
case 'put':
params = merge(params, req.put, true);
break;
case 'delete':
params = merge(params, req.delete, true);
break;
}
return params
}
req.getParam = function(name) {
// copy
var param = null, params = JSON.parse(JSON.stringify(req.params));
switch( req.method.toLowerCase() ) {
case 'get':
param = req.get[name];
break;
case 'post':
param = req.post[name];
break;
case 'put':
param= req.put[name];
break;
case 'delete':
param = req.delete[name];
break;
}
return param
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3165
|
train
|
function (code) {
var list = {}, cde = 'short', name = null;
if ( typeof(code) != 'undefined' && typeof(userLocales[0][code]) == 'string' ) {
cde = code
} else if ( typeof(code) != 'undefined' ) (
console.warn('`'+ code +'` not supported : sticking with `short` code')
)
for ( var i = 0, len = userLocales.length; i< len; ++i ) {
if (userLocales[i][cde]) {
name = userLocales[i].full || userLocales[i].officialName.short;
if ( name )
list[ userLocales[i][cde] ] = name;
}
}
return list
}
|
javascript
|
{
"resource": ""
}
|
|
q3166
|
train
|
function (arr){
var tmp = null,
curObj = {},
obj = {},
count = 0,
data = {},
last = null;
for (var r in arr) {
tmp = r.split(".");
//Creating structure - Adding sub levels
for (var o in tmp) {
count++;
if (last && typeof(obj[last]) == "undefined") {
curObj[last] = {};
if (count >= tmp.length) {
// assigning.
// !!! if null or undefined, it will be ignored while extending.
curObj[last][tmp[o]] = (arr[r]) ? arr[r] : "undefined";
last = null;
count = 0;
break
} else {
curObj[last][tmp[o]] = {}
}
} else if (tmp.length === 1) { //Just one root var
curObj[tmp[o]] = (arr[r]) ? arr[r] : "undefined";
obj = curObj;
break
}
obj = curObj;
last = tmp[o]
}
//data = merge(data, obj, true);
data = merge(obj, data);
obj = {};
curObj = {}
}
return data
}
|
javascript
|
{
"resource": ""
}
|
|
q3167
|
assertSameObjectIdArray
|
train
|
function assertSameObjectIdArray(actual, expected, msg) {
assert(Array.isArray(actual), 'assertSameObjectIdArray: First argument is not an Array.')
assert(Array.isArray(expected), 'assertSameObjectIdArray: Second argument is not an Array.')
assert(size(actual) > 0 || size(expected) > 0, 'assertSameObjectIdArray: Received two empty Arrays.')
assert.strictEqual(size(actual), size(expected), 'assertSameObjectIdArray: arrays different sizes')
const parseIds = flow(map(stringifyObjectId), sortBy(identity))
try { parseIds(actual) } catch (err) { throw Error(`assertSameObjectIdArray 1st argument: ${err.message}`) }
try { parseIds(expected) } catch (err) { throw Error(`assertSameObjectIdArray 2nd argument: ${err.message}`) }
assert.deepStrictEqual(parseIds(actual), parseIds(expected), msg)
}
|
javascript
|
{
"resource": ""
}
|
q3168
|
PreInstall
|
train
|
function PreInstall() {
var self = this;
var init = function() {
self.isWin32 = ( os.platform() == 'win32' ) ? true : false;
self.path = __dirname.substring(0, (__dirname.length - 'script'.length));
console.debug('paths -> '+ self.path);
if ( hasNodeModulesSync() ) { // cleaining old
var target = new _(self.path + '/node_modules');
console.debug('replacing: ', target.toString() );
var err = target.rmSync();
if (err instanceof Error) {
throw err;
process.exit(1)
}
fs.mkdirSync(_(self.path) + '/node_modules');
}
}
var hasNodeModulesSync = function() {
return fs.existsSync( _(self.path + '/node_modules') )
}
// compare with post_install.js if you want to use this
//var filename = _(self.path + '/SUCCESS');
//var installed = fs.existsSync( filename );
//if (installed && /node_modules\/gina/.test( new _(process.cwd()).toUnixStyle() ) ) {
// process.exit(0)
//} else {
// fs.writeFileSync(filename, true );
//}
// ...
init()
}
|
javascript
|
{
"resource": ""
}
|
q3169
|
train
|
function($form) {
var $form = $form, _id = null;
if ( typeof($form) == 'undefined' ) {
if ( typeof(this.target) != 'undefined' ) {
_id = this.target.getAttribute('id');
} else {
_id = this.getAttribute('id');
}
$form = instance.$forms[_id]
} else if ( typeof($form) == 'string' ) {
_id = $form;
_id = _id.replace(/\#/, '');
if ( typeof(instance.$forms[_id]) == 'undefined') {
throw new Error('[ FormValidator::resetErrorsDisplay([formId]) ] `'+$form+'` not found')
}
$form = instance.$forms[_id]
}
//reseting error display
handleErrorsDisplay($form['target'], []);
return $form
}
|
javascript
|
{
"resource": ""
}
|
|
q3170
|
train
|
function(rules, tmp) {
var _r = null;
for (var r in rules) {
if ( typeof(rules[r]) == 'object' && typeof(instance.rules[tmp + r]) == 'undefined' ) {
_r = r;
if (/\[|\]/.test(r) ) { // must be a real path
_r = r.replace(/\[/g, '.').replace(/\]/g, '');
}
instance.rules[tmp + _r] = rules[r];
//delete instance.rules[r];
parseRules(rules[r], tmp + _r +'.');
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3171
|
createSplitterForField
|
train
|
function createSplitterForField(multiFieldDefinitionPart, fieldName) {
if (multiFieldDefinitionPart === undefined) {
throw ("'multiFieldDefinitionPart' must not be undefined");
}
if (fieldName === undefined) {
throw ("'fieldName' must not be undefined");
}
const delimiter = multiFieldDefinitionPart.delimiter;
let escapeChar = multiFieldDefinitionPart.escapeChar;
let removeWhiteSpace = true;
let uniqueFields = true;
let sortFields = true;
let removeEmpty = true;
// set default values
if (multiFieldDefinitionPart.removeWhiteSpace !== undefined) {
// remove leading and trailing whitespaces
removeWhiteSpace = multiFieldDefinitionPart.removeWhiteSpace;
}
if (multiFieldDefinitionPart.uniqueFields !== undefined) {
// remove duplicates from the list
uniqueFields = multiFieldDefinitionPart.uniqueFields;
}
if (multiFieldDefinitionPart.sortFields !== undefined) {
// sort the fields
sortFields = multiFieldDefinitionPart.sortFields;
}
if (multiFieldDefinitionPart.removeEmpty !== undefined) {
// Empty fields will be deleted
removeEmpty = multiFieldDefinitionPart.removeEmpty;
}
return function (content) {
if (content.hasOwnProperty(fieldName)) {
// the field exists in the content record
let fieldValue = content[fieldName];
if (fieldValue) {
// ------------------------------------------------
// escape delimiter
// ------------------------------------------------
if (escapeChar) {
escapeChar = escapeChar.replace(/\\/, "\\\\");
escapeChar = escapeChar.replace(/\//, "\\/");
// The escaped delimiter will be replaced by the string '<--DIVIDER-->'
let re = new RegExp(escapeChar + delimiter, 'g');
fieldValue = fieldValue.replace(re, TMP_DEVIDER);
}
// ------------------------------------------------
// split the string
// ------------------------------------------------
let values = fieldValue.split(delimiter);
if (escapeChar) {
// remove the escape char
let re = new RegExp(TMP_DEVIDER, 'g');
for (let i = 0; i < values.length; i++) {
values[i] = values[i].replace(re, delimiter);
}
}
// ------------------------------------------------
// remove the leading and trailing whiteSpaces
// ------------------------------------------------
if (removeWhiteSpace) {
for (let i = 0; i < values.length; i++) {
values[i] = values[i].trim();
}
}
// ------------------------------------------------
// remove empty fields
// ------------------------------------------------
if (removeEmpty) {
let i = 0;
let j = 0;
for (i = 0; i < values.length; i++) {
if (values[i]) {
values[j] = values[i];
j++;
}
}
values.splice(j, i);
}
// ------------------------------------------------
// sort fields
// ------------------------------------------------
if (sortFields) {
values.sort();
}
// ------------------------------------------------
// remove duplicates
// ------------------------------------------------
if (uniqueFields) {
values = values.filter(function (elem, pos) {
return values.indexOf(elem) == pos;
});
}
// ------------------------------------------------
// store the splited fields back to the content
// ------------------------------------------------
content[fieldName] = values;
}
}
return null;
};
}
|
javascript
|
{
"resource": ""
}
|
q3172
|
findPrevNode
|
train
|
function findPrevNode(firstNode, item, comparer) {
let ret;
let prevNode = firstNode;
// while item > prevNode.value
while (prevNode != undefined && comparer(prevNode.value, item) > 0) {
ret = prevNode;
prevNode = prevNode.next;
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q3173
|
findNode
|
train
|
function findNode(firstNode, predicate) {
let curNode = firstNode;
while (curNode != null) {
if (predicate(curNode.value))
return curNode;
curNode = curNode.next;
}
}
|
javascript
|
{
"resource": ""
}
|
q3174
|
createCheckEmail
|
train
|
function createCheckEmail(fieldDefinition, fieldName) {
const severity = propertyHelper.getSeverity(fieldDefinition);
// return getIteratorFunction: function (fieldName, defaultValue, checkProperties, checkFunction, getErrorFunction,
// getValueIfErrorFunction, getValueIfOkFunction) {
let errorInfo = {
severity: severity,
errorCode: 'NOT_EMAIL'
};
return functionHelper.getParserCheck(errorInfo, getEmailIfValid, fieldName, undefined);
}
|
javascript
|
{
"resource": ""
}
|
q3175
|
createCheckDefaultValue
|
train
|
function createCheckDefaultValue(fieldDefinition, fieldName) {
const defaultValue = fieldDefinition.defaultValue;
// -----------------------------------------------------------------------
// Set default value
// -----------------------------------------------------------------------
return function (content) {
const valueToCheck = content[fieldName];
// If the value is defined, we need to check it
if (valueToCheck === undefined || valueToCheck === null) {
if (defaultValue !== undefined) {
content[fieldName] = defaultValue;
}
} else {
if (Array.isArray(valueToCheck)) {
valueToCheck.forEach(function (item, idx, arr) {
if (item === undefined || item === null) {
arr[idx] = defaultValue;
}
});
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q3176
|
train
|
function (format) {
var name = "default";
for (var f in self.masks) {
if ( self.masks[f] === format )
return f
}
return name
}
|
javascript
|
{
"resource": ""
}
|
|
q3177
|
train
|
function(date, dateTo) {
if ( dateTo instanceof Date) {
// The number of milliseconds in one day
var oneDay = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1Ms = date.getTime()
var date2Ms = dateTo.getTime()
// Calculate the difference in milliseconds
var count = Math.abs(date1Ms - date2Ms)
// Convert back to days and return
return Math.round(count/oneDay);
} else {
throw new Error('dateTo is not instance of Date() !')
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3178
|
train
|
function(date, dateTo, mask) {
if ( dateTo instanceof Date) {
var count = countDaysTo(date, dateTo)
, month = date.getMonth()
, year = date.getFullYear()
, day = date.getDate() + 1
, dateObj = new Date(year, month, day)
, days = []
, i = 0;
for (; i < count; ++i) {
if ( typeof(mask) != 'undefined' ) {
days.push(new Date(dateObj).format(mask));
} else {
days.push(new Date(dateObj));
}
dateObj.setDate(dateObj.getDate() + 1);
}
return days || [];
} else {
throw new Error('dateTo is not instance of Date() !')
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3179
|
BaseDecorator
|
train
|
function BaseDecorator(cache, config, configSchema) {
this._cache = cache;
if (config) {
this._configSchema = configSchema;
this._config = this._humanTimeIntervalToMs(config);
this._config = this._validateConfig(configSchema, this._config);
}
// substitute cb, for cases
// when you don't need a callback, but
// don't want to loose the error.
this._emitError = function (err) {
if (err) this.emit('error', err);
}.bind(this);
}
|
javascript
|
{
"resource": ""
}
|
q3180
|
train
|
function (obj) {
if (
!obj
|| {}.toString.call(obj) !== '[object Object]'
|| obj.nodeType
|| obj.setInterval
) {
return false
}
var hasOwn = {}.hasOwnProperty;
var hasOwnConstructor = hasOwn.call(obj, 'constructor');
// added test for node > v6
var hasMethodPrototyped = ( typeof(obj.constructor) != 'undefined' ) ? hasOwn.call(obj.constructor.prototype, 'isPrototypeOf') : false;
if (
obj.constructor && !hasOwnConstructor && !hasMethodPrototyped
) {
return false
}
//Own properties are enumerated firstly, so to speed up,
//if last one is own, then all properties are own.
var key;
return key === undefined || hasOwn.call(obj, key)
}
|
javascript
|
{
"resource": ""
}
|
|
q3181
|
doCallback
|
train
|
function doCallback(callback, reason, value) {
// Note: Could delay callback call until later, as When.js does, but this
// loses the stack (particularly for bluebird long traces) and causes
// unnecessary delay in the non-exception (common) case.
try {
// Match argument length to resolve/reject in case callback cares.
// Note: bluebird has argument length 1 if value === undefined due to
// https://github.com/petkaantonov/bluebird/issues/170
// If you are reading this and want similar behavior, I'll consider it.
if (reason) {
callback(reason);
} else {
callback(null, value);
}
} catch (err) {
later(() => { throw err; });
}
}
|
javascript
|
{
"resource": ""
}
|
q3182
|
promiseNodeify
|
train
|
function promiseNodeify(promise, callback) {
if (typeof callback !== 'function') {
return promise;
}
function onRejected(reason) {
// callback is unlikely to recognize or expect a falsey error.
// (we also rely on truthyness for arguments.length in doCallback)
// Convert it to something truthy
let truthyReason = reason;
if (!truthyReason) {
// Note: unthenify converts falsey rejections to TypeError:
// https://github.com/blakeembrey/unthenify/blob/v1.0.0/src/index.ts#L32
// We use bluebird convention for Error, message, and .cause property
truthyReason = new Error(String(reason));
truthyReason.cause = reason;
}
doCallback(callback, truthyReason);
}
function onResolved(value) {
doCallback(callback, null, value);
}
promise.then(onResolved, onRejected);
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q3183
|
getBinaryCase
|
train
|
function getBinaryCase (str, val) {
let res = '';
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
if (code >= 65 && code <= 90) {
res += val & 1 ? String.fromCharCode(code + 32) : String.fromCharCode(code);
val >>>= 1;
} else if (code >= 97 && code <= 122) {
res += val & 1 ? String.fromCharCode(code - 32) : String.fromCharCode(code);
val >>>= 1;
} else {
res += String.fromCharCode(code);
}
if (val === 0) {
return res + str.substr(i + 1);
}
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q3184
|
resolvePermission
|
train
|
function resolvePermission(params) {
var dbPermissions = mBaaS.permission_map.db;
if (params.act && dbPermissions && dbPermissions[params.act]) {
params.requestedPermission = dbPermissions[params.act].requires;
}
}
|
javascript
|
{
"resource": ""
}
|
q3185
|
getFilterMethods
|
train
|
function getFilterMethods(type, controller, action) {
// Get all filters for the action.
let filters = getFilters(type, controller, action)
// Get filter method names to be skipped.
type = `skip${type[0].toUpperCase() + type.slice(1)}`
let skipFilterMethods = _.map(getFilters(type, controller, action), 'action')
// Remove filters that should be skipped.
filters = _.filter(filters, f => {
for(let method of skipFilterMethods)
if(method === f.action)
return false
return true
})
// Return final list of filter methods.
return _.map(filters, f => {
let { action } = f
action = typeof action === 'string' ? controller[action] : action
return action.bind(controller)
})
}
|
javascript
|
{
"resource": ""
}
|
q3186
|
getFilters
|
train
|
function getFilters(type, controller, action) {
// User can set 'only' and 'except' rules on filters to be used on one
// or many action methods.
let useOptions = { only: true, except: false }
// Only return action filter methods that apply.
return _.filter(controller[`__${type}Filters`], filter => {
// An action must be defined in each filter.
if(!('action' in filter) || !filter.action)
throw new Error(`No action defined in filter for [${controller.constructor.name}.${type}: ${JSON.stringify(filter)}].`)
// Filter cannot contain both options.
let containsBoth = _.every(_.keys(useOptions), o => o in filter)
if(containsBoth)
throw new Error(`${type[0].toUpperCase() + type.slice(1)} filter cannot have both \'only\' and \'except\' keys.`)
let option = _.first(_.intersection(_.keys(useOptions), _.keys(filter)))
// If no option is defined, use for all actions.
if(!option)
return true
let useActions, use = useOptions[option]
useActions = typeof (useActions = filter[option]) === 'string' ? [useActions] : useActions
// Determine if filter can be used for this action.
for(let ua of useActions)
if(ua === action)
return use
return !use
})
}
|
javascript
|
{
"resource": ""
}
|
q3187
|
charlike
|
train
|
async function charlike(settings = {}) {
const proj = settings.project;
if (!proj || (proj && typeof proj !== 'object')) {
throw new TypeError('expect `settings.project` to be an object');
}
const options = await makeDefaults(settings);
const { project, templates } = options;
const cfgDir = path.join(os.homedir(), '.config', 'charlike');
const tplDir = path.join(cfgDir, 'templates');
const templatesDir = templates ? path.resolve(templates) : null;
if (templatesDir && fs.existsSync(templatesDir)) {
project.templates = templatesDir;
} else if (fs.existsSync(cfgDir) && fs.existsSync(tplDir)) {
project.templates = tplDir;
} else {
project.templates = path.join(path.dirname(__dirname), 'templates');
}
if (!fs.existsSync(project.templates)) {
throw new Error(`source templates folder not exist: ${project.templates}`);
}
const locals = objectAssign({}, options.locals, { project });
const stream = fastGlob.stream('**/*', {
cwd: project.templates,
ignore: arrayify(null),
});
return new Promise((resolve, reject) => {
stream.on('error', reject);
stream.on('end', () => {
// Note: Seems to be called before really write to the optionsination directory.
// Stream are still fucking shit even in Node v10.
// Feels like nothing happend since v0.10.
// For proof, `process.exit` from inside the `.then` in the CLI,
// it will end/close the program before even create the options folder.
// One more proof: put one console.log in stream.on('data')
// and you will see that it still outputs even after calling the resolve()
resolve({ locals, project, dest: options.dest, options });
});
stream.on('data', async (filepath) => {
try {
const tplFilepath = path.join(project.templates, filepath);
const { body } = await jstransformer.renderFileAsync(
tplFilepath,
{ engine: options.engine },
locals,
);
const newFilepath = path
.join(options.dest, filepath)
.replace('_circleci', '.circleci');
const basename = path
.basename(newFilepath)
.replace(/^__/, '')
.replace(/^\$/, '')
.replace(/^_/, '.');
const fp = path.join(path.dirname(newFilepath), basename);
const fpDirname = path.dirname(fp);
if (!fs.existsSync(fpDirname)) {
await util.promisify(fs.mkdir)(fpDirname);
}
await util.promisify(fs.writeFile)(fp, body);
} catch (err) {
reject(err);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q3188
|
train
|
function(request, params, route) {
var uRe = params.url.split(/\//)
, uRo = route.split(/\//)
, maxLen = uRo.length
, score = 0
, r = {}
, i = 0;
//attaching routing description for this request
request.routing = params; // can be retried in controller with: req.routing
if (uRe.length === uRo.length) {
for (; i<maxLen; ++i) {
if (uRe[i] === uRo[i]) {
++score
} else if (score == i && hasParams(uRo[i]) && fitsWithRequirements(request, uRo[i], uRe[i], params)) {
++score
}
}
}
r.past = (score === maxLen) ? true : false;
r.request = request;
return r
}
|
javascript
|
{
"resource": ""
}
|
|
q3189
|
wrapFn
|
train
|
function wrapFn (gen) {
if (!is.function(gen)) throw new Error('Middleware must be a function')
if (!is.generator(gen)) return gen
// wrap generator with raco
var fn = raco.wrap(gen)
return function (ctx, next) {
fn.call(this, ctx, next)
}
}
|
javascript
|
{
"resource": ""
}
|
q3190
|
use
|
train
|
function use () {
// init hooks
if (!this.hasOwnProperty('_hooks')) {
this._hooks = {}
}
var args = Array.prototype.slice.call(arguments)
var i, j, l, m
var name = null
if (is.array(args[0])) {
// use(['a','b','c'], ...)
var arr = args.shift()
for (i = 0, l = arr.length; i < l; i++) {
use.apply(this, [arr[i]].concat(args))
}
return this
} else if (is.object(args[0]) && args[0]._hooks) {
// use(ginga)
var key
// concat hooks
for (key in args[0]._hooks) {
use.call(this, key, args[0]._hooks[key])
}
return this
}
// method name
if (is.string(args[0])) name = args.shift()
if (!name) throw new Error('Method name is not defined.')
if (!this._hooks[name]) this._hooks[name] = []
for (i = 0, l = args.length; i < l; i++) {
if (is.function(args[i])) {
this._hooks[name].push(wrapFn(args[i]))
} else if (is.array(args[i])) {
// use('a', [fn1, fn2, fn3])
for (j = 0, m = args[i].length; j < m; j++) {
use.call(this, name, args[i][j])
}
return this
} else {
throw new Error('Middleware must be a function')
}
}
return this
}
|
javascript
|
{
"resource": ""
}
|
q3191
|
define
|
train
|
function define () {
var args = Array.prototype.slice.call(arguments)
var i, l
var name = args.shift()
if (is.array(name)) {
name = args.shift()
for (i = 0, l = name.length; i < l; i++) {
define.apply(this, [name[i]].concat(args))
}
return this
}
if (!is.string(name)) throw new Error('Method name is not defined')
var invoke = is.function(args[args.length - 1]) ? wrapFn(args.pop()) : null
var pre = args.map(wrapFn)
// define scope method
this[name] = function () {
var args = Array.prototype.slice.call(arguments)
var self = this
var callback
if (is.function(args[args.length - 1])) callback = args.pop()
// init pipeline
var pipe = []
var obj = this
// prototype chain
while (obj) {
if (obj.hasOwnProperty('_hooks') && obj._hooks[name]) {
pipe.unshift(obj._hooks[name])
}
obj = Object.getPrototypeOf(obj)
}
// pre middlewares
pipe.unshift(pre)
// invoke middleware
if (invoke) pipe.push(invoke)
pipe = flatten(pipe)
// context object and next triggerer
var ctx = new EventEmitter()
ctx.method = name
ctx.args = args
var index = 0
var size = pipe.length
function next (err, res) {
if (err || index === size) {
var args = Array.prototype.slice.call(arguments)
// callback when err or end of pipeline
if (callback) callback.apply(self, args)
args.unshift('end')
ctx.emit.apply(ctx, args)
} else if (index < size) {
var fn = pipe[index]
index++
var val = fn.call(self, ctx, next)
if (is.promise(val)) {
val.then(function (res) {
next(null, res)
}, function (err) {
next(err || new Error())
})
} else if (fn.length < 2) {
// args without next() & not promise, sync func
next(null, val)
}
}
}
if (callback) {
next()
} else {
// use promise if no callback
return new Promise(function (resolve, reject) {
callback = function (err, result) {
if (err) return reject(err)
resolve(result)
}
next()
})
}
}
return this
}
|
javascript
|
{
"resource": ""
}
|
q3192
|
train
|
function(callback) {
self.configureDatabases(function(err) {
if (err) {
process.exit(111);
return;
}
self.configureApplicationStack(
app, server, callback
);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3193
|
train
|
function (fieldDefinition, fieldName) {
const severity = propertyHelper.getSeverity(fieldDefinition, undefined, 'mandatory');
const isMandatoy = propertyHelper.getProperty(fieldDefinition, undefined, 'mandatory');
// const severity = fieldDefinition.severity;
// const isMandatoy = fieldDefinition.mandatory;
if (isMandatoy === true) {
/**
* Just check if for mandatory fields the value is given
* @param content the content hash to be validated.
*/
return function (content) {
// get the value from the content hash
const valueToCheck = content[fieldName];
// If the value is defined, we need to check it
if (valueToCheck === undefined || valueToCheck === null) {
return {
errorCode: 'MANDATORY_VALUE_MISSING',
severity: severity,
fieldName: fieldName
};
}
};
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3194
|
train
|
function (evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
if (
evt.type === "load" ||
readyRegExp.test((evt.currentTarget || evt.srcElement).readyState)
) {
//Reset interactive script so a script node is not held onto for
//to long.
interactiveScript = null;
//Pull out the name of the module and the context.
var data = getScriptData(evt);
context.completeLoad(data.id);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3195
|
train
|
function (attrName, oldVal, newVal) {
var property = vcomet.util.hyphenToCamelCase(attrName);
// The onAttributeChanged callback is triggered whether its observed or as a reflection of a property
if (el.__observeAttributes[attrName] || el.__reflectProperties[property]) {
vcomet.triggerAllCallbackEvents(el, config, "onAttributeChanged", [attrName, oldVal, newVal]);
}
// The onPropertyChanged callback is triggered when the attribute has changed and its reflect by a property
if (el.__reflectProperties[property]) {
el["__" + property] = newVal;
vcomet.triggerAllCallbackEvents(el, config, "onPropertyChanged", [property, oldVal, newVal]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3196
|
createAccessPolicy
|
train
|
function createAccessPolicy(thingId) {
const thingPolicy = {
id: thingId + "-" + thingId + "-cru-policy",
effect: "allow",
actions: ["dcd:actions:create", "dcd:actions:read", "dcd:actions:update"],
subjects: ["dcd:things:" + thingId],
resources: [
"dcd:things:" + thingId,
"dcd:things:" + thingId + ":properties",
"dcd:things:" + thingId + ":properties:<.*>"
]
};
logger.debug("Thing policy: " + JSON.stringify(thingPolicy));
return policies.create(thingPolicy);
}
|
javascript
|
{
"resource": ""
}
|
q3197
|
createOwnerAccessPolicy
|
train
|
function createOwnerAccessPolicy(thingId, subject) {
const thingOwnerPolicy = {
id: thingId + "-" + subject + "-clrud-policy",
effect: "allow",
actions: [
"dcd:actions:create",
"dcd:actions:list",
"dcd:actions:read",
"dcd:actions:update",
"dcd:actions:delete"
],
subjects: [subject],
resources: [
"dcd:things:" + thingId,
"dcd:things:" + thingId + ":properties",
"dcd:things:" + thingId + ":properties:<.*>"
]
};
return policies.create(thingOwnerPolicy);
}
|
javascript
|
{
"resource": ""
}
|
q3198
|
PopulateInDecorator
|
train
|
function PopulateInDecorator(cache, config) {
BaseDecorator.call(this, cache, config, joi.object().keys({
populateIn: joi.number().integer().min(500).required(),
populateInAttempts: joi.number().integer().default(5),
pausePopulateIn: joi.number().integer().required(),
accessedAtThrottle: joi.number().integer().default(1000)
}));
this._store = this._getStore();
this._timer = this._store.createTimer();
this._timer.on('error', this._emitError);
this._timer.on('timeout', this._onTimeout.bind(this));
this.on('set:after', this.setTimeout.bind(this));
this.on('get:after', throttle(this.setAccessedAt.bind(this),
this._config.accessedAtThrottle));
}
|
javascript
|
{
"resource": ""
}
|
q3199
|
concatenateFile
|
train
|
function concatenateFile(file, done) {
// Append the concat file itself to the end of the concatenation.
files[file].files.push(file)
// Make sure the output is defined.
if (!Object.prototype.hasOwnProperty.call(files[file], 'output')) {
// Output the file to the destination, without the ".concat".
const dir = path.dirname(file)
const filename = path.basename(file, opts.extname)
const final = path.join(dir, filename)
files[file].output = final
}
// Tell Metalsmith Concat plugin to concatinate the files.
metalsmithConcat(files[file])(files, metalsmith, done)
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.