_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q14700
|
subgen
|
train
|
function subgen (key, ...params) {
return random(createSeed([...seed, keygen(key), ...params], seed.length))
}
|
javascript
|
{
"resource": ""
}
|
q14701
|
logout
|
train
|
function logout(mongoClient, dbName, callback) {
mongoClient.topology.logout(dbName, err => {
if (err) return callback(err);
callback(null, true);
});
}
|
javascript
|
{
"resource": ""
}
|
q14702
|
validOptions
|
train
|
function validOptions(options) {
const _validOptions = validOptionNames.concat(legacyOptionNames);
for (const name in options) {
if (ignoreOptionNames.indexOf(name) !== -1) {
continue;
}
if (_validOptions.indexOf(name) === -1 && options.validateOptions) {
return new MongoError(`option ${name} is not supported`);
} else if (_validOptions.indexOf(name) === -1) {
console.warn(`the options [${name}] is not supported`);
}
if (legacyOptionNames.indexOf(name) !== -1) {
console.warn(
`the server/replset/mongos/db options are deprecated, ` +
`all their options are supported at the top level of the options object [${validOptionNames}]`
);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q14703
|
Converter
|
train
|
function Converter() {
// Validate arguments
if (arguments.length === 1) {
this._bl = 2;
if (typeof arguments[0] !== "function")
throw new TypeError("Converter requires at least a callback function");
else
this._fx = arguments[0];
} else if (arguments.length >= 2) {
this._bl = arguments[0];
if (this._bl !== 1 && this._bl !== 2 && this._bl !== 4)
throw new TypeError("Prefix length must be 1, 2 or 4");
if (typeof arguments[1] !== "function")
throw new TypeError("Converter requires a callback function");
else
this._fx = arguments[1];
} else {
throw new Error("cannot construct a converter without a callback");
}
this.flush();
}
|
javascript
|
{
"resource": ""
}
|
q14704
|
getCommonActions
|
train
|
function getCommonActions(device) {
const actions = []
actions.push(new BackAction(device))
actions.push(new HomeAction(device))
actions.push(new MenuAction(device))
actions.push()
return actions
}
|
javascript
|
{
"resource": ""
}
|
q14705
|
mutation
|
train
|
function mutation(target, handler) {
target.addEventListener("mutation", function(evt) {
handler.call(this, this, evt.mutations);
});
}
|
javascript
|
{
"resource": ""
}
|
q14706
|
Request
|
train
|
function Request(reqBytes){
var parsed;
var err
try {
parsed = types.Request.decode(reqBytes);
} catch (e) {
err = e;
}
//Check for request errors here
if(err){
this.BadRequest = true;
this.errCode = types.CodeType.EncodingError;
this.errMsg = "The request failed to be decoded"
} else if(!types.methodLookup[parsed.type]){
//Request type not recognized
//Make a request object for the error
this.BadRequest = true;
this.errCode = types.CodeType.UnknownRequest;
this.errMsg = "The request type was not understood"
} else {
this.BadRequest = false;
this.type = parsed.type;
this.method = types.methodLookup[this.type];
this.data = parsed.data.buffer.slice(parsed.data.offset);
this.dataLength = parsed.data.limit - parsed.data.offset;
this.dataLittle = parsed.data.littleEndian;
this.key = parsed.key;
this.value = parsed.value;
}
}
|
javascript
|
{
"resource": ""
}
|
q14707
|
fire
|
train
|
function fire (event, $el, evt) {
var handler = $el.data('dragon-opts')[event];
// Patch the proxied Event Object
evt.target = $el[0];
if (handler) {
handler(evt);
}
$el.trigger(event);
}
|
javascript
|
{
"resource": ""
}
|
q14708
|
ComponentModel
|
train
|
function ComponentModel(key, impl, cfg) {
this.key = key
/**
* @property {Any} impl The implementation to use for `resolve`
* */
this.impl =impl
this._cfg = cfg || {}
/**
* @property {Array} inject The {String} dependencies array a service may declare
* */
this.inject = (this.impl.inject || [])
/**
* @property {String} initializable The method to invoke on an resolved service just after resolution, but before returning
* injecting any dependencies found on that method
* */
this.initializable = (this.impl.initializable || false)
/**
* @property {String} startable The method to invoke on an resolved services when started. Usually during an app bootstrap.
* */
this.startable = (this.impl.startable || false)
}
|
javascript
|
{
"resource": ""
}
|
q14709
|
fetchLogs
|
train
|
function fetchLogs(root, msg, callback) {
const number = msg.number;
const logfile = msg.logfile;
const serverId = msg.serverId;
const filePath = path.join(root, getLogFileName(logfile, serverId));
const endLogs = [];
exec(`tail -n ${number} ${filePath}`, (error, output) => {
const endOut = [];
output = output.replace(/^\s+|\s+$/g, '').split(/\s+/);
for (let i = 5; i < output.length; i += 6) {
endOut.push(output[i]);
}
const endLength = endOut.length;
for (let j = 0; j < endLength; j++) {
const map = {};
let json;
try {
json = JSON.parse(endOut[j]);
} catch (e) {
logger.error(`the log cannot parsed to json, ${e}`);
continue; // eslint-disable-line
}
map.time = json.time;
map.route = json.route || json.service;
map.serverId = serverId;
map.timeUsed = json.timeUsed;
map.params = endOut[j];
endLogs.push(map);
}
callback({ logfile: logfile, dataArray: endLogs });
});
}
|
javascript
|
{
"resource": ""
}
|
q14710
|
train
|
function(parser) {
return highland.map(function(item) {
if (_.isFunction(parser)) {
return parser(item);
}
if (_.isObject(parser) && (parser.parse != null)) {
return parser.parse(item);
}
return item;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14711
|
train
|
function(done) {
var p, parser, stream, _i, _len;
parser = this.parser();
stream = highland(this.source());
if (_.isArray(parser)) {
for (_i = 0, _len = parser.length; _i < _len; _i++) {
p = parser[_i];
stream = this._mapWith(p)(stream).flatten().compact();
}
} else {
stream = this._mapWith(parser)(stream).flatten().compact();
}
stream = stream.reduce({}, _.merge);
if (done == null) {
return stream;
}
stream.pull(done);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q14712
|
mergeInto
|
train
|
function mergeInto(target, source) {
var a = target;
var b = source;
if (a && b) {
for (var key in b) {
if (!(key in a)) {
continue;
}
if (typeof b[key] === 'object' && !Array.isArray(b[key]) && b[key] !== null) {
mergeInto(a[key], b[key]);
} else {
a[key] = b[key];
}
}
}
return a;
}
|
javascript
|
{
"resource": ""
}
|
q14713
|
tryWatch
|
train
|
function tryWatch(target, callback) {
if (!target) {
return logger.halt('invalid watch target')
}
if (!callback || typeof callback !== 'function') {
return logger.halt('invalid watch callback')
}
return fs.watch(
target, { persistent: true, recursive: true},
function (e, file) {
// todo: exact watch
callback(e, file)
}
)
}
|
javascript
|
{
"resource": ""
}
|
q14714
|
getBabelConfig
|
train
|
function getBabelConfig(env) {
var babelrcPath = path.join(__dirname, '.babelrc')
var babelrc = JSON.parse(fs.readFileSync(babelrcPath))
babelrc.presets = resolve(
babelrc.presets.map(preset => 'babel-preset-' + preset)
)
if (!babelrc.plugins) babelrc.plugins = []
return babelrc
}
|
javascript
|
{
"resource": ""
}
|
q14715
|
isNested
|
train
|
function isNested(obj) {
if (getType(obj)==='object') {
for (let tag in obj) {
if (tag != TEXT && !ATTRTAG.test(tag)) {
return true;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q14716
|
getAttributes
|
train
|
function getAttributes(obj) {
let attrString = '';
let attrArray = Object.keys(obj);
for (let tag of attrArray) {
if (tag != ATTR && ATTRTAG.test(tag)) {
attrString += ` ${tag.replace('_', '')}="${obj[tag]}"`;
}
}
if (ATTR in obj) {
attrString += ' ' + obj[ATTR];
}
return attrString;
}
|
javascript
|
{
"resource": ""
}
|
q14717
|
getType
|
train
|
function getType(obj) {
let typeStr = typeof(obj);
if (obj) {
return Array.isArray(obj) ? 'array' : typeStr;
} else {
switch (typeStr) {
case 'number':
return obj === 0 ? 'number' : 'NaN';
case 'object':
return 'null';
default:
return typeStr;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q14718
|
injectWatcher
|
train
|
function injectWatcher(handler) {
return function(module, filename) {
fs.watchFile(filename, watcher);
handler(module, filename);
};
}
|
javascript
|
{
"resource": ""
}
|
q14719
|
loadNext
|
train
|
function loadNext() {
var script;
if ( ( script = pending[ 0 ] ) )
this.load( script.scriptUrl, script.callback, CKEDITOR, 0 );
}
|
javascript
|
{
"resource": ""
}
|
q14720
|
callbackWrapper
|
train
|
function callbackWrapper() {
callback && callback.apply( this, arguments );
// Removed the just loaded script from the queue.
pending.shift();
loadNext.call( that );
}
|
javascript
|
{
"resource": ""
}
|
q14721
|
Lexer
|
train
|
function Lexer(sourcetext, filename, options) {
options = options || {};
this.options = options || {};
this.dialects = []; // the "stack" dialects are pushed/popped from
if(filename) {
this.filename = filename;
this.fileext = utils.getFileExt(filename, "sugar");
}
this.set_source_text(sourcetext);
}
|
javascript
|
{
"resource": ""
}
|
q14722
|
regexes_for_category
|
train
|
function regexes_for_category(lexer, category) {
var REs = [];
var done = false;
for(var i = 0; !done && i < lexer.dialects.length; i++) {
var dialect = lexer.dialects[i];
if(dialect.lextab) {
var categoryentry = dialect.lextab.find(function(lextabentry) {
return lextabentry.category == category;
});
if(categoryentry) {
REs.push(categoryentry.match);
// if they've set entry.replace=true this dialect's
// entry replaces other dialects' entries:
done = categoryentry.replace;
}
}
}
return REs;
}
|
javascript
|
{
"resource": ""
}
|
q14723
|
oncharincategory
|
train
|
function oncharincategory(lexer, lookahead, categoryREs) {
var c = lexer.peek_char(lookahead);
return categoryREs.find(function(re) {
// because we're matching a single char...
re.lastIndex = 0; // make sure we start from the start
return re.test(c);
});
}
|
javascript
|
{
"resource": ""
}
|
q14724
|
next_lextab_token
|
train
|
function next_lextab_token(lexer) {
var token;
if(lexer.eos()) {
return undefined;
}
// skip leading whitespace or comments...
lexer.skip_filler();
var previouslyPeeked = lexer.getPeekedToken();
if(previouslyPeeked) {
return previouslyPeeked;
}
lexer.mark_token_start();
trace(lexer.message_src_loc("", lexer, {file:false}));
// try and match all token categories except punctuation (and
// the default handler). Note that single character punctuation
// should take a back seat to longer symbols e.g. '...' should
// match before '.'.
token = match_in_lextabs(lexer, {omit: ['punctuation','default']});
if(!token) {
// okay now try again matching punctuation characters.
token = match_in_lextabs(lexer, {include: ['punctuation']});
}
if(!token) {
// ok go ahead and try any default handler(s)
token = match_in_lextabs(lexer, {include: ['default']});
}
// we expect they will use an explicit default lextab entry, but JIC:
if(!token) {
trace('their lextab has no default handler - defaulting to next word');
token = lexer.next_word_token();
if(token) {
token.category = 'symbol';
}
}
return token;
}
|
javascript
|
{
"resource": ""
}
|
q14725
|
match_in_lextabs
|
train
|
function match_in_lextabs(lexer, options) {
options = options || {};
var token;
var replaced = {};
// for each dialect's lextab...
for(var d = 0; !token && d < lexer.dialects.length; d++) {
var dialect = lexer.dialects[d];
if(!dialect.lextab) {
continue; // no lextab for the dialect so move on
}
// check each entry in order...
// NOTE I AM IGNORING THE 'PRIORITY' PROPERTY RIGHT NOW - MAYBE I CAN DELETE THEM!?
debug('matching in ' + dialect.name + ' lextable');
for(var l = 0; !token && l < dialect.lextab.length; l++) {
var entry = dialect.lextab[l];
// we don't match tokens against "replaced" categories
if(!replaced[entry.category] &&
// and if they've specified categories to include...
(!options.include ||
// only consider those
(options.include.contains(entry.category) ||
(options.include.contains("default") && entry.default))) &&
// or if they've specified categories to omit...
(!options.omit ||
// make sure we skip over those
((!options.omit.contains(entry.category) &&
!(options.omit.contains("default") && entry.default)))))
{
// most functions "match" (with a regex)
// but they can also just "read" (with a function)
if(typeof entry.read !== 'function') {
// are we on a token matching this entry's pattern?
//trace('matching ' + entry.category + ' pattern');
var matchedText = lexer.on(entry.match);
if(matchedText) {
trace('matched ' + entry.category + ' pattern');
// advance the current position
lexer.next_char(matchedText.length);
// create and return the token object (including line/col info)
token = lexer.create_token(matchedText, entry.category);
}
}
else {
// note we use a "read" function for our default entry
// used when nothing else matches. Such entries can
// still set a token category, but they should set
// "default: true" (so we know to consider them last).
trace('invoking ' + entry.category + ' read function');
token = entry.read(lexer);
if(token) {
trace('read from ' + entry.category + ' read function');
token.category = entry.category;
}
}
}
if(entry.replace) {
// remember that this category has been replaced
replaced[entry.category] = true;
}
}
}
return token;
}
|
javascript
|
{
"resource": ""
}
|
q14726
|
formatTokenDump
|
train
|
function formatTokenDump(tokens, formatter, resultPrefix, resultSuffix) {
var tokensSexpStr = "";
var currentLine = -999;
tokens.forEach(function(token, index) {
// skip the wrapping () it's annoying in the dump
if(!((index === 0 && token.text === "(") ||
(index === tokens.length-1 && token.text === ")")))
{
// add a return if this starts a different line:
if(currentLine !== -999 && token.line !== currentLine) {
tokensSexpStr += '\n';
}
tokensSexpStr += formatter(token);
currentLine = token.line;
}
});
return (resultPrefix ? resultPrefix : "") +
tokensSexpStr +
(resultSuffix ? resultSuffix : "");
}
|
javascript
|
{
"resource": ""
}
|
q14727
|
Suite
|
train
|
function Suite(name, fn){
if (! (this instanceof Suite))
return new Suite(name, fn);
return this.initialize(name, fn);
}
|
javascript
|
{
"resource": ""
}
|
q14728
|
generateNamedFieldExtractors
|
train
|
function generateNamedFieldExtractors(input) {
var names = input.filter(function(matcher, index, array) {
// has a name?
return matcher.name;
});
// has duplicates?
names.forEach(function(matcher, index, array) {
var isDuplicate = array.slice(0, index).some(function(previousMatcher) {
return previousMatcher.name == matcher.name;
});
if (isDuplicate) {
throw new Error("duplicate named field '" + matcher.name + "'");
}
});
return names;
}
|
javascript
|
{
"resource": ""
}
|
q14729
|
extractNamedFields
|
train
|
function extractNamedFields(fields, input) {
var output = Object.create(null);
fields.forEach(function(field) {
var subObject = input;
for (var i = 0; i < field.path.length; i += 1) {
if (subObject == undefined) {
throw new Error("Unreachable: matched input will always have fields");
}
subObject = subObject[field.path[i]];
}
switch (field.typeShortcut) {
// type matcher:
case 1:
subObject = global[field.type](subObject);
break;
// literal matcher:
case 3:
subObject = field.object;
break;
}
output[field.name] = subObject;
});
return output;
}
|
javascript
|
{
"resource": ""
}
|
q14730
|
rawContent
|
train
|
function rawContent(tagName, string, templ, innerTemplate) {
var index = string.indexOf('</' + tagName + '>'),
raw;
if (index === -1)
throw new Error(tagName + ' tag badly closed.');
if (index) { // more than 0
raw = string.substring(0, index);
if (tagName === 'templ') // produce local api-like handler
{
innerTemplate.templFunc = new Function(raw);
} else
innerTemplate.raw(raw);
}
return string.substring(index + tagName.length + 3);
}
|
javascript
|
{
"resource": ""
}
|
q14731
|
train
|
function(markupList) {
("production" !== "development" ? invariant(
ExecutionEnvironment.canUseDOM,
'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' +
'thread. Make sure `window` and `document` are available globally ' +
'before requiring React when unit testing or use ' +
'React.renderToString for server rendering.'
) : invariant(ExecutionEnvironment.canUseDOM));
var nodeName;
var markupByNodeName = {};
// Group markup by `nodeName` if a wrap is necessary, else by '*'.
for (var i = 0; i < markupList.length; i++) {
("production" !== "development" ? invariant(
markupList[i],
'dangerouslyRenderMarkup(...): Missing markup.'
) : invariant(markupList[i]));
nodeName = getNodeName(markupList[i]);
nodeName = getMarkupWrap(nodeName) ? nodeName : '*';
markupByNodeName[nodeName] = markupByNodeName[nodeName] || [];
markupByNodeName[nodeName][i] = markupList[i];
}
var resultList = [];
var resultListAssignmentCount = 0;
for (nodeName in markupByNodeName) {
if (!markupByNodeName.hasOwnProperty(nodeName)) {
continue;
}
var markupListByNodeName = markupByNodeName[nodeName];
// This for-in loop skips the holes of the sparse array. The order of
// iteration should follow the order of assignment, which happens to match
// numerical index order, but we don't rely on that.
var resultIndex;
for (resultIndex in markupListByNodeName) {
if (markupListByNodeName.hasOwnProperty(resultIndex)) {
var markup = markupListByNodeName[resultIndex];
// Push the requested markup with an additional RESULT_INDEX_ATTR
// attribute. If the markup does not start with a < character, it
// will be discarded below (with an appropriate console.error).
markupListByNodeName[resultIndex] = markup.replace(
OPEN_TAG_NAME_EXP,
// This index will be parsed back out below.
'$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" '
);
}
}
// Render each group of markup with similar wrapping `nodeName`.
var renderNodes = createNodesFromMarkup(
markupListByNodeName.join(''),
emptyFunction // Do nothing special with <script> tags.
);
for (var j = 0; j < renderNodes.length; ++j) {
var renderNode = renderNodes[j];
if (renderNode.hasAttribute &&
renderNode.hasAttribute(RESULT_INDEX_ATTR)) {
resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR);
renderNode.removeAttribute(RESULT_INDEX_ATTR);
("production" !== "development" ? invariant(
!resultList.hasOwnProperty(resultIndex),
'Danger: Assigning to an already-occupied result index.'
) : invariant(!resultList.hasOwnProperty(resultIndex)));
resultList[resultIndex] = renderNode;
// This should match resultList.length and markupList.length when
// we're done.
resultListAssignmentCount += 1;
} else if ("production" !== "development") {
console.error(
'Danger: Discarding unexpected node:',
renderNode
);
}
}
}
// Although resultList was populated out of order, it should now be a dense
// array.
("production" !== "development" ? invariant(
resultListAssignmentCount === resultList.length,
'Danger: Did not assign to every index of resultList.'
) : invariant(resultListAssignmentCount === resultList.length));
("production" !== "development" ? invariant(
resultList.length === markupList.length,
'Danger: Expected markup to render %s nodes, but rendered %s.',
markupList.length,
resultList.length
) : invariant(resultList.length === markupList.length));
return resultList;
}
|
javascript
|
{
"resource": ""
}
|
|
q14732
|
recomputePluginOrdering
|
train
|
function recomputePluginOrdering() {
if (!EventPluginOrder) {
// Wait until an `EventPluginOrder` is injected.
return;
}
for (var pluginName in namesToPlugins) {
var PluginModule = namesToPlugins[pluginName];
var pluginIndex = EventPluginOrder.indexOf(pluginName);
("production" !== "development" ? invariant(
pluginIndex > -1,
'EventPluginRegistry: Cannot inject event plugins that do not exist in ' +
'the plugin ordering, `%s`.',
pluginName
) : invariant(pluginIndex > -1));
if (EventPluginRegistry.plugins[pluginIndex]) {
continue;
}
("production" !== "development" ? invariant(
PluginModule.extractEvents,
'EventPluginRegistry: Event plugins must implement an `extractEvents` ' +
'method, but `%s` does not.',
pluginName
) : invariant(PluginModule.extractEvents));
EventPluginRegistry.plugins[pluginIndex] = PluginModule;
var publishedEvents = PluginModule.eventTypes;
for (var eventName in publishedEvents) {
("production" !== "development" ? invariant(
publishEventForPlugin(
publishedEvents[eventName],
PluginModule,
eventName
),
'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.',
eventName,
pluginName
) : invariant(publishEventForPlugin(
publishedEvents[eventName],
PluginModule,
eventName
)));
}
}
}
|
javascript
|
{
"resource": ""
}
|
q14733
|
publishEventForPlugin
|
train
|
function publishEventForPlugin(dispatchConfig, PluginModule, eventName) {
("production" !== "development" ? invariant(
!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName),
'EventPluginHub: More than one plugin attempted to publish the same ' +
'event name, `%s`.',
eventName
) : invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName)));
EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig;
var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
if (phasedRegistrationNames) {
for (var phaseName in phasedRegistrationNames) {
if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
var phasedRegistrationName = phasedRegistrationNames[phaseName];
publishRegistrationName(
phasedRegistrationName,
PluginModule,
eventName
);
}
}
return true;
} else if (dispatchConfig.registrationName) {
publishRegistrationName(
dispatchConfig.registrationName,
PluginModule,
eventName
);
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q14734
|
train
|
function(spec) {
var Constructor = function(props, context) {
// This constructor is overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if ("production" !== "development") {
("production" !== "development" ? warning(
this instanceof Constructor,
'Something is calling a React component directly. Use a factory or ' +
'JSX instead. See: https://fb.me/react-legacyfactory'
) : null);
}
// Wire up auto-binding
if (this.__reactAutoBindMap) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if ("production" !== "development") {
// We allow auto-mocks to proceed as if they're returning null.
if (typeof initialState === 'undefined' &&
this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
("production" !== "development" ? invariant(
typeof initialState === 'object' && !Array.isArray(initialState),
'%s.getInitialState(): must return an object or null',
Constructor.displayName || 'ReactCompositeComponent'
) : invariant(typeof initialState === 'object' && !Array.isArray(initialState)));
this.state = initialState;
};
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
injectedMixins.forEach(
mixSpecIntoComponent.bind(null, Constructor)
);
mixSpecIntoComponent(Constructor, spec);
// Initialize the defaultProps property after all mixins have been merged
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
if ("production" !== "development") {
// This is a tag to indicate that the use of these method names is ok,
// since it's used with createClass. If it's not, then it's likely a
// mistake so we'll warn you to use the static property, property
// initializer or constructor respectively.
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps.isReactClassApproved = {};
}
if (Constructor.prototype.getInitialState) {
Constructor.prototype.getInitialState.isReactClassApproved = {};
}
}
("production" !== "development" ? invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
) : invariant(Constructor.prototype.render));
if ("production" !== "development") {
("production" !== "development" ? warning(
!Constructor.prototype.componentShouldUpdate,
'%s has a method called ' +
'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
'The name is phrased as a question because the function is ' +
'expected to return a value.',
spec.displayName || 'A component'
) : null);
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
// Legacy hook
Constructor.type = Constructor;
if ("production" !== "development") {
try {
Object.defineProperty(Constructor, 'type', typeDeprecationDescriptor);
} catch (x) {
// IE will fail on defineProperty (es5-shim/sham too)
}
}
return Constructor;
}
|
javascript
|
{
"resource": ""
}
|
|
q14735
|
train
|
function(propTypes, props, location) {
// TODO: Stop validating prop types here and only use the element
// validation.
var componentName = this.getName();
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error;
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
("production" !== "development" ? invariant(
typeof propTypes[propName] === 'function',
'%s: %s type `%s` is invalid; it must be a function, usually ' +
'from React.PropTypes.',
componentName || 'React class',
ReactPropTypeLocationNames[location],
propName
) : invariant(typeof propTypes[propName] === 'function'));
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
if (error instanceof Error) {
// We may want to extend this logic for similar errors in
// React.render calls, so I'm abstracting it away into
// a function to minimize refactoring in the future
var addendum = getDeclarationErrorAddendum(this);
if (location === ReactPropTypeLocations.prop) {
// Preface gives us something to blacklist in warning module
("production" !== "development" ? warning(
false,
'Failed Composite propType: %s%s',
error.message,
addendum
) : null);
} else {
("production" !== "development" ? warning(
false,
'Failed Context Types: %s%s',
error.message,
addendum
) : null);
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14736
|
warnForPropsMutation
|
train
|
function warnForPropsMutation(propName, element) {
var type = element.type;
var elementName = typeof type === 'string' ? type : type.displayName;
var ownerName = element._owner ?
element._owner.getPublicInstance().constructor.displayName : null;
var warningKey = propName + '|' + elementName + '|' + ownerName;
if (warnedPropsMutations.hasOwnProperty(warningKey)) {
return;
}
warnedPropsMutations[warningKey] = true;
var elementInfo = '';
if (elementName) {
elementInfo = ' <' + elementName + ' />';
}
var ownerInfo = '';
if (ownerName) {
ownerInfo = ' The element was created by ' + ownerName + '.';
}
("production" !== "development" ? warning(
false,
'Don\'t set .props.%s of the React component%s. Instead, specify the ' +
'correct value when initially creating the element or use ' +
'React.cloneElement to make a new element with updated props.%s',
propName,
elementInfo,
ownerInfo
) : null);
}
|
javascript
|
{
"resource": ""
}
|
q14737
|
train
|
function(object) {
if ("production" !== "development") {
if (typeof object !== 'object' || !object || Array.isArray(object)) {
("production" !== "development" ? warning(
false,
'React.addons.createFragment only accepts a single object.',
object
) : null);
return object;
}
if (ReactElement.isValidElement(object)) {
("production" !== "development" ? warning(
false,
'React.addons.createFragment does not accept a ReactElement ' +
'without a wrapper object.'
) : null);
return object;
}
if (canWarnForReactFragment) {
var proxy = {};
Object.defineProperty(proxy, fragmentKey, {
enumerable: false,
value: object
});
Object.defineProperty(proxy, didWarnKey, {
writable: true,
enumerable: false,
value: false
});
for (var key in object) {
proxyPropertyAccessWithWarning(proxy, key);
}
Object.preventExtensions(proxy);
return proxy;
}
}
return object;
}
|
javascript
|
{
"resource": ""
}
|
|
q14738
|
train
|
function(container) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (Strictly speaking, unmounting won't cause a
// render but we still don't expect to be in a render call here.)
("production" !== "development" ? warning(
ReactCurrentOwner.current == null,
'unmountComponentAtNode(): Render methods should be a pure function of ' +
'props and state; triggering nested component updates from render is ' +
'not allowed. If necessary, trigger nested updates in ' +
'componentDidUpdate.'
) : null);
("production" !== "development" ? invariant(
container && (
(container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE)
),
'unmountComponentAtNode(...): Target container is not a DOM element.'
) : invariant(container && (
(container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE)
)));
var reactRootID = getReactRootID(container);
var component = instancesByReactRootID[reactRootID];
if (!component) {
return false;
}
ReactMount.unmountComponentFromNode(component, container);
delete instancesByReactRootID[reactRootID];
delete containersByReactRootID[reactRootID];
if ("production" !== "development") {
delete rootElementsByReactRootID[reactRootID];
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q14739
|
train
|
function(objName, fnName, func) {
if ("production" !== "development") {
var measuredFunc = null;
var wrapper = function() {
if (ReactPerf.enableMeasure) {
if (!measuredFunc) {
measuredFunc = ReactPerf.storedMeasure(objName, fnName, func);
}
return measuredFunc.apply(this, arguments);
}
return func.apply(this, arguments);
};
wrapper.displayName = objName + '_' + fnName;
return wrapper;
}
return func;
}
|
javascript
|
{
"resource": ""
}
|
|
q14740
|
train
|
function() {
var acc = arguments.callee.caller;
var nom = ((acc ? acc.nom : "") || "(instance method)") + ":";
enyo.logging.log("log", [nom].concat(enyo.cloneArray(arguments)));
}
|
javascript
|
{
"resource": ""
}
|
|
q14741
|
mv
|
train
|
function mv (sourceURI, destURI, callback) {
if (!sourceURI) {
callback(new Error('source URI is required'))
}
if (!destURI) {
callback(new Error('dest URI is required'))
}
util.get(sourceURI, function (err, val, uri) {
util.put(destURI, val, function (err, ret, uri) {
if (!err) {
util.rm(sourceURI, function(err, ret) {
if (!err) {
callback(null, ret, uri)
} else {
callback(err)
}
})
} else {
callback(err)
}
})
})
}
|
javascript
|
{
"resource": ""
}
|
q14742
|
update
|
train
|
function update() {
connection = new Connection(room)
// set our funcitonal code on the ready event, so we are sure that the socket has been created and is connected to the server
connection.on('ready', _ => {
connection.on('snapshot-event', event => {
// get every listener including bots and lurkers
userList = event.data.listing.sort()
render(userList)
connection.close()
})
})
}
|
javascript
|
{
"resource": ""
}
|
q14743
|
render
|
train
|
function render(list) {
const blank = new Array(process.stdout.rows).fill('\n')
console.log(blank)
readline.cursorTo(process.stdout, 0, 0)
readline.clearScreenDown(process.stdout)
list.forEach( user => {
console.log(`${chalk.hsl(color(user.name),100,50)(user.name)}: ${user.id}`)
})
}
|
javascript
|
{
"resource": ""
}
|
q14744
|
getMeasureStations
|
train
|
function getMeasureStations(latitude, longitude, params, callback) {
if(!latitude || !longitude) {
callback(new Error("WaterFlow.getMeasureStations: latitude and longitude required"));
return;
}
params = params || {};
params.latitude = latitude;
params.longitude = longitude;
core.callApi('/waterflowservice/GetMeasureStations', params, callback);
}
|
javascript
|
{
"resource": ""
}
|
q14745
|
getWaterLevel
|
train
|
function getWaterLevel(stationId, startDate, endDate, params, callback) {
if(!stationId) {
callback(new Error("WaterFlow.getWaterLevel: stationId required"));
return;
}
params = params || {};
params.stationid = stationId;
if(!startDate && !endDate) {
startDate = new Date();
startDate.setHours(startDate.getHours() - 4);
startDate = formatDate(startDate);
endDate = new Date();
endDate = formatDate(endDate);
}
params.startdate = startDate;
params.endDate = endDate;
core.callApi('/waterflowservice/GetWaterLevel', params, callback);
}
|
javascript
|
{
"resource": ""
}
|
q14746
|
matches
|
train
|
function matches(url, command) {
var cap;
if (cap = commandReg.exec(url)) return cap[1] === command;
}
|
javascript
|
{
"resource": ""
}
|
q14747
|
Pending
|
train
|
function Pending(runner) {
runner.on('start', function(){
console.log('* ')
console.log('*********************');
console.log('*** Pending tests ***');
console.log('*********************');
console.log('* ')
});
var scope = [];
runner.on('pending', function(test){
var current = [test]
, parent = test.parent
;
// stack suites
while( !!parent ){
current.unshift(parent)
parent = parent.parent;
}
// print titles
current.forEach(function(val, key){
if( val != scope[key] ){
while( scope.length > key ){
scope.pop()
}
console.log( '* ' + Array(key).join(' ') + val.title );
scope.push(val);
}
})
})
}
|
javascript
|
{
"resource": ""
}
|
q14748
|
train
|
function (d, use_UTC) {
if (typeof d === "string") {
if (d.match(/[0-9][0-9][0-9][0-9][\s]*-[0-1][0-9]-[\s]*[0-3][0-9]/)) {
return d.replace(/\s+/, "");
}
d = new Date(d);
} else if (typeof d === "number") {
d = new Date(d);
} else if (typeof d !== "object" &&
typeof d.getFullYear !== "function") {
throw "Expecting type: " + String(d) + " --> " + typeof d;
}
if (!use_UTC) {
return [
d.getFullYear(),
String("0" + (d.getMonth() + 1)).substr(-2),
String("0" + d.getDate()).substr(-2)
].join("-");
}
return [
d.getUTCFullYear(),
String("0" + (d.getUTCMonth() + 1)).substr(-2),
String("0" + d.getUTCDate()).substr(-2)
].join("-");
}
|
javascript
|
{
"resource": ""
}
|
|
q14749
|
train
|
function (options) {
var ky,
default_keys = [
"normalize_date",
"hours",
"save_parse",
"tags",
"map"
],
defaults = {},
map = {};
default_keys.forEach(function (ky) {
defaults[ky] = true;
});
this.defaults = defaults;
this.map = false;
this.parse_tree = {};
this.msgs = [];
if (options !== undefined) {
for (ky in options) {
if (options.hasOwnProperty(ky)) {
if (default_keys.indexOf(ky) >= 0) {
this.defaults[ky] = options[ky];
} else {
map[ky] = options[ky];
}
}
}
if (Object.keys(map).length > 0) {
this.map = map;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14750
|
train
|
function (msg) {
var i = this.msgs.length;
this.msgs.push('ERROR: ' + msg);
if ((i + 1) !== this.msgs.length) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q14751
|
train
|
function (no_clear) {
var result;
if (this.msgs === undefined) {
this.msgs = [];
}
result = this.msgs.join("\n");
// set optional default i needed
if (no_clear !== undefined) {
no_clear = false;
}
if (no_clear === true) {
return result;
}
// Clear the messages
this.msgs = [];
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q14752
|
train
|
function () {
var self = this,
dates = Object.keys(this.parse_tree),
lines = [];
dates.sort();
dates.forEach(function (dy, i) {
var times = Object.keys(self.parse_tree[dy]);
lines.push(dy);
times.sort();
times.forEach(function (tm) {
var tags = "", maps = "", notes = "", rec;
rec = self.parse_tree[dy][tm];
if (typeof rec === "string") {
notes = rec;
} else {
if (typeof rec.map !== "undefined" &&
rec.map !== false) {
maps = [
rec.map.project_name,
rec.map.task
].join(", ") + "; ";
}
if (typeof rec.tags !== "undefined" &&
rec.tags !== false) {
tags = rec.tags.join(", ") + "; ";
}
if (typeof rec.notes !== "undefined") {
notes = rec.notes;
}
}
lines.push([
tm,
"; ",
tags,
maps,
notes
].join(""));
});
});
return lines.join("\n\n");
}
|
javascript
|
{
"resource": ""
}
|
|
q14753
|
addFiles
|
train
|
function addFiles(pattern, cb){
glob(pattern, function(err, files){
if(err) throw err;
async.each(files, readFile, function(err){
if(err) throw err;
if(cb) cb();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14754
|
find
|
train
|
function find(source, fn) {
glob('**', {cwd: source, dot: true}, function(err, files) {
fn(err, files);
});
}
|
javascript
|
{
"resource": ""
}
|
q14755
|
filterIgnored
|
train
|
function filterIgnored(files, ignore, fn) {
fn(null, files.filter(function(file) {
// TODO make more robust
return !~ignore.indexOf(file) && !~ignore.indexOf(file + '/');
}));
}
|
javascript
|
{
"resource": ""
}
|
q14756
|
statFiles
|
train
|
function statFiles(files, source, fn) {
var batch = new Batch();
files.forEach(function(file) {
batch.push(statFile(file, source));
});
batch.end(fn);
}
|
javascript
|
{
"resource": ""
}
|
q14757
|
statFile
|
train
|
function statFile(file, source) {
return function(cb) {
var abs = join(source, file);
stat(abs, function(err, stats) {
if (err) return cb(err);
var manifest = {
name: file,
abs: abs,
mtime: Math.floor(stats.mtime.getTime() / 1000),
mode: '' + parseInt(stats.mode.toString(8), 10),
size: '' + stats.size // do we need this?
};
if (stats.isDirectory()) return cb();
if (stats.isSymbolicLink()) return fs.readlink(abs, finish('link'));
calculateHash(abs, finish('hash'));
function finish(key) {
return function(err, val) {
if (err) return cb(err);
manifest[key] = val;
cb(null, manifest);
};
}
});
};
}
|
javascript
|
{
"resource": ""
}
|
q14758
|
calculateHash
|
train
|
function calculateHash(file, fn) {
read(file, function(err, bin) {
if (err) return fn(err);
fn(null, hash('sha256').update(bin).digest('hex'));
});
}
|
javascript
|
{
"resource": ""
}
|
q14759
|
normalizeManifest
|
train
|
function normalizeManifest(manifest, fn) {
var obj = {};
manifest.forEach(function(file) {
if (!file) return;
obj[file.name] = {
mtime: file.mtime,
mode: file.mode,
size: file.size,
hash: file.hash,
link: file.link
};
});
fn(null, obj);
}
|
javascript
|
{
"resource": ""
}
|
q14760
|
findMissing
|
train
|
function findMissing(manifest, request, host, fn) {
request
.post(host + '/manifest/diff')
.send({manifest: JSON.stringify(manifest)})
.end(function(err, res) {
if (err) return fn(err);
if (res.error) return fn(res.error);
fn(null, res.body);
});
}
|
javascript
|
{
"resource": ""
}
|
q14761
|
selectMissing
|
train
|
function selectMissing(missing, manifest, fn) {
fn(null, manifest.filter(function(file) {
return file && ~missing.indexOf(file.hash);
}));
}
|
javascript
|
{
"resource": ""
}
|
q14762
|
uploadMissing
|
train
|
function uploadMissing(missing, request, host, log, fn) {
var batch = new Batch();
missing.forEach(function(file) {
batch.push(uploadFile(file, request, host));
});
batch.on('progress', function() {
log('.');
});
batch.end(function(err, res) {
log(' done\n');
fn(err, res);
});
}
|
javascript
|
{
"resource": ""
}
|
q14763
|
uploadFile
|
train
|
function uploadFile(file, request, host) {
return function(cb) {
request
.post(host + '/file/' + file.hash)
.attach('data', file.abs)
.end(function(err, res) {
if (err) return cb(err);
if (res.error) return cb(res.error);
return cb();
});
};
}
|
javascript
|
{
"resource": ""
}
|
q14764
|
saveManifest
|
train
|
function saveManifest(manifest, request, host, fn) {
request
.post(host + '/manifest')
.send({manifest: JSON.stringify(manifest)})
.end(function(err, res) {
if (err) return fn(err);
if (res.error) return fn(res.error);
fn(null, res.headers.location);
});
}
|
javascript
|
{
"resource": ""
}
|
q14765
|
use
|
train
|
function use(type) {
// Convert args to array.
var args = Array.prototype.slice.call(arguments);
// Check if type not provided.
if ('string' !== typeof type && type instanceof Array === false) {
type = [];
} else {
if ('string' === typeof type) {
//wrap string in array to homogenize handling
type = [type];
}
args.shift();
}
args.forEach(function(arg){
stack.push({type: type, cb: arg});
});
return middlebot;
}
|
javascript
|
{
"resource": ""
}
|
q14766
|
handle
|
train
|
function handle(type, req, res, out) {
var index = 0;
var ended = false;
// When called stop middlewares execution.
res.end = end;
// Handle next middleware in stack.
function next(err) {
var middleware = stack[index++];
// No more middlewares or early end.
if (!middleware || ended) {
if (out) out(err, req, res);
return;
}
// Check if middleware type matches or if it has no type.
if (middleware.type.indexOf(type) === -1 && middleware.type.length > 0)
return next(err);
try {
var arity = middleware.cb.length;
//if err, only execute error middlewares
if (err) {
//error middlewares have an arity of 4, the first
//arg being the error
if (arity === 4) {
middleware.cb(err, req, res, next);
} else {
next(err);
}
} else if (arity < 4) {
middleware.cb(req, res, next);
} else {
next();
}
}
catch (e) {
next(e);
}
}
// Stop middlewares execution.
function end() {
ended = true;
}
// Start handling.
next();
}
|
javascript
|
{
"resource": ""
}
|
q14767
|
writeToConsoleOrStderr
|
train
|
function writeToConsoleOrStderr(message) {
if (typeof console == 'object' && typeof console.warn == 'function')
console.warn(message);
else if (typeof process == 'object' && typeof process.stderr == 'object' && typeof process.stderr.write == 'function')
process.stderr.write(message);
else
throw new Error(message);
}
|
javascript
|
{
"resource": ""
}
|
q14768
|
train
|
function(value) {
switch (typeof value) {
case 'undefined':
return this.undefined;
case 'string':
return this.string;
case 'number':
if (value % 1 === 0) {
return this.integer;
} else {
return this.double;
}
break;
case 'boolean':
return this.boolean;
case 'function':
return this["function"];
default:
if (value === null) {
return this["null"];
} else if (value instanceof Date) {
return this.datetime;
} else if (value instanceof Array) {
return this.array;
} else if (Buffer.isBuffer(value)) {
throw new TypeError("Value cannot be a buffer");
} else if (value instanceof Object) {
return this.object;
} else {
throw new TypeError('Value must either be a string, integer, double, boolean, date, array, object or function');
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14769
|
preamble
|
train
|
function preamble(opts) {
var str = '';
var index = opts.section || SECTION;
var date = opts.date || new Date().toISOString();
var version = opts.version || '1.0';
// section name
var sname = section(index);
var title = opts.title || opts.name;
if(!title) {
throw new TypeError('manual preamble requires a name or title');
}
// use comment
if(opts.comment) {
str += util.format(elements.comment, opts.comment);
}
//console.dir(title)
str += util.format(
elements.th,
strip(title.toUpperCase()),
index, date,
(strip(opts.name || title)).replace(/\s+.*$/, '') + ' ' + version, sname);
// add name section
if(opts.name) {
var name = strip(opts.name);
str += util.format(elements.sh, header(constants.NAME));
if(opts.description) {
str += util.format('%s \\- %s' + EOL, name, opts.description);
}else{
str += util.format('%s' + EOL, name);
}
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q14770
|
splitActionName
|
train
|
function splitActionName(actionName) {
if(actionName.indexOf('_') > 0) return actionName.split('_')
else return actionName.split(/(?=[A-Z])/).map(p => p.toLowerCase())
}
|
javascript
|
{
"resource": ""
}
|
q14771
|
parseMethodName
|
train
|
function parseMethodName(parts, argsNames) {
/**
* argsName could be in different case from that
* of function's name.
*/
const argsNamesLower = argsNames.map(arg => arg.toLowerCase())
/**
* Suppresses HTTP method if exists
*/
if(keysMethods.indexOf(parts[0].toLowerCase()) >= 0)
parts = parts.slice(1)
/**
* Converts each method part into route path
*/
return parts.reduce((prev, curr) => {
if(keywordsMaps[curr]) prev += keywordsMaps[curr]
else {
if(prev.slice(-1) != '/') prev += '/'
const index = argsNamesLower.indexOf(curr.toLowerCase())
if(index >= 0) {
prev += ':'
prev += argsNames[index] // Preserve argument Case
} else {
prev += curr
}
}
return prev
}, '')
}
|
javascript
|
{
"resource": ""
}
|
q14772
|
parseHttpMethod
|
train
|
function parseHttpMethod(parts) {
const prefix = parts[0].toLowerCase()
if(keysMethods.indexOf(prefix) >= 0)
return prefix
else
return GET
}
|
javascript
|
{
"resource": ""
}
|
q14773
|
lookupParameterOnReq
|
train
|
function lookupParameterOnReq(name, index, length) {
return (req, res) => {
if(req[name]) return req[name]
if(req.query && req.query[name]) return req.query[name]
if(req.body && req.body[name]) return req.body[name]
if(res.locals && res.locals[name]) return res.locals[name]
if(req.app.locals && req.app.locals[name]) return req.app.locals[name]
/**
* In this case there is not a matching property in Request object for
* the given parameter name.
* We just accept it, if that is the last parameter of the method, in which
* case it should correspond to a callback.
*/
if(index != (length - 1))
throw new Error('Parameter ' + name + ' not found in Request object!!!' )
return null
}
}
|
javascript
|
{
"resource": ""
}
|
q14774
|
appLoader
|
train
|
function appLoader(app, config) {
app.define('load', load('view', config));
var fn = app.view;
app.define('view', function() {
var view = fn.apply(this, arguments);
utils.contents.sync(view);
return view;
});
}
|
javascript
|
{
"resource": ""
}
|
q14775
|
createLoader
|
train
|
function createLoader(options, fn) {
var loader = new utils.Loader(options);
return function() {
if (!this.isApp) loader.cache = this.views;
loader.options.loaderFn = fn.bind(this);
loader.load.apply(loader, arguments);
return loader.cache;
};
}
|
javascript
|
{
"resource": ""
}
|
q14776
|
load
|
train
|
function load(method, config) {
return function(patterns, options) {
var opts = mergeOptions(this, config, options);
var loader = createLoader(opts, this[method]);
return loader.apply(this, arguments);
};
}
|
javascript
|
{
"resource": ""
}
|
q14777
|
train
|
function () {
waitForServers--;
if (waitForServers) return;
if (seminarjs.get('logger')) {
console.log(dashes + startupMessages.join('\n') + dashes);
}
events.onStart && events.onStart();
}
|
javascript
|
{
"resource": ""
}
|
|
q14778
|
randstr
|
train
|
function randstr(options) {
var opt = _validateOptions(options);
var from, to;
if (Array.isArray(opt.length)) {
_a = opt.length, from = _a[0], to = _a[1];
}
else {
from = to = opt.length;
}
var str = '';
if (0 === to) {
return str;
}
var charsIsString = 'string' === typeof opt.chars;
var charsLastIndex = charsIsString ? opt.chars.length - 1 : 0;
var includeControlChars = true === opt.includeControlChars;
var hasAcceptableFunc = 'function' === typeof opt.acceptable;
var hasReplacer = 'function' === typeof opt.replacer;
var max = _randomIntBetween(opt.random, from, to);
// console.log( 'max', max, 'from', from, 'to', to );
for (var i = 0, len = 0, charCode = void 0, chr = void 0; i < max && len < max; ++i) {
if (charsIsString) {
var index = _randomIntBetween(opt.random, 0, charsLastIndex);
charCode = opt.chars.charCodeAt(index);
}
else {
charCode = _randomIntBetween(opt.random, opt.chars[0], opt.chars[1]);
}
// Non printable?
if (!includeControlChars && _isControlChar(charCode)) {
// console.log( 'NOT PRINTABLE!');
--i; // back to try again
continue;
}
chr = String.fromCharCode(charCode);
// console.log( 'charCode', charCode, 'char', chr );
if (hasAcceptableFunc && !opt.acceptable.call(null, chr)) {
--i; // back to try again
continue;
}
if (hasReplacer) {
chr = opt.replacer.call(null, chr);
// console.log( 'char after', chr );
// Their combined length pass the limit?
if ((len + chr.length) > max) {
// console.log( 'greater than max!', 'i', i, 'max', max, 'str', len, 'chr', chr.length );
--i; // back to try again
continue;
}
}
str += chr;
len = str.length;
}
return str;
var _a;
}
|
javascript
|
{
"resource": ""
}
|
q14779
|
updateStatus
|
train
|
function updateStatus(evType, opts) {
var t2 = new Date()
var elapsed = (t2.getTime() - t1.getTime()) / 1000
var msg = {
timeElapsed:elapsed,
stdout: opts.stdout || "",
stderr: opts.stderr || "",
stdmerged: opts.stdmerged || "",
info: opts.info,
step: opts.step,
deployExitCode: null,
url: null || opts.url,
}
if (opts.deployExitCode !== undefined) {
msg.deployExitCode = opts.deployExitCode
}
emitter.emit(evType, msg)
}
|
javascript
|
{
"resource": ""
}
|
q14780
|
train
|
function(s_thing) {
if(H_SPARQL_CHARS[s_thing[0]]) return s_thing;
else if(s_thing.indexOf(':') != -1) return s_thing;
else if(s_thing == 'a') return s_thing;
else return ':'+s_thing;
}
|
javascript
|
{
"resource": ""
}
|
|
q14781
|
train
|
function(s_str) {
if(H_SPARQL_CHARS[s_str[0]]) return s_str;
else if(s_str.indexOf(':') != -1) return s_str;
else if(/^(?:[0-9]|(?:\-|\.|\-\.)[0-9])/.test(s_str)) return s_str;
else return JSON.stringify(s_str);
}
|
javascript
|
{
"resource": ""
}
|
|
q14782
|
train
|
function(sq_prefixes) {
var s_select = this.select || '*';
var sq_select = 'SELECT '+s_select+' WHERE {';
var sq_where = this.where;
var sq_tail = this.tail;
var sq_group = this.group? ' GROUP BY '+this.group: '';
var sq_order = this.order? ' ORDER BY '+this.order: '';
var sq_limit_offset = this.limit;
var sq_close = '\n}';
return ''
+sq_prefixes
+sq_select
+sq_where
+sq_tail
+sq_close
+sq_group
+sq_order
+sq_limit_offset;
}
|
javascript
|
{
"resource": ""
}
|
|
q14783
|
train
|
function(s_query, f_okay) {
$.ajax({
url: s_endpoint_url+'query',
method: 'GET',
data: {
query: s_query,
},
dataType: 'json',
success: function(h_res) {
f_okay && f_okay(h_res);
},
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14784
|
train
|
function(h_subjects, b_raw) {
// initiliaze output
var s_out = '';
// add slot for tail
var s_tail = '';
// newline + indent
var _ = '\n\t'+(b_raw? '\t':'');
// root nodes must be subjects
for(var s_rs in h_subjects) {
//
var z_predicates = h_subjects[s_rs];
// declaring optional block
if(s_rs == '?') {
// these are subjects actually
var h_write = query_hash(z_predicates, true);
s_out += _+'OPTIONAL {'+h_write.where+_+'}';
s_tail += h_write.tail;
}
// regular query hash
else {
var s_rsi = rdf_var(s_rs);
// this is subject
s_out += _+s_rsi;
// predicates are in hash
if(typeof z_predicates == 'object') {
// recurse
var a_write = build_from_ph(z_predicates, _);
s_out += a_write[0]+' .';
s_tail += a_write[1];
}
}
}
var h_raw = {
treated_vars: {subs:{},lists:{}},
select: '',
where: s_out,
tail: s_tail,
group: '',
order: '',
limit: '',
};
return (b_raw? h_raw: qb(h_raw));
}
|
javascript
|
{
"resource": ""
}
|
|
q14785
|
train
|
function(s_query) {
// execute function
var f_exec = function(f_okay) {
submit_query(s_query, f_okay);
};
var d_self = {
exec: f_exec,
results: function(f_okay) {
f_exec(function(h_res) {
f_okay && f_okay(h_res.results.bindings);
});
},
each: function(f_each, f_okay) {
f_exec(function(h_res) {
if(!f_each) return;
var a_rows = h_res.results.bindings;
for(var i=0,l=a_rows.length; i<l; i++) {
var h_row = a_rows[i];
var h_this = {};
for(var e in h_row) h_this[e] = h_row[e].value;
f_each.apply(h_this, [i, h_row]);
}
f_okay && f_okay();
});
},
};
return d_self;
}
|
javascript
|
{
"resource": ""
}
|
|
q14786
|
train
|
function(channel) {
return function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(__class+':');
console[channel].apply(console, args);
};
}
|
javascript
|
{
"resource": ""
}
|
|
q14787
|
into
|
train
|
function into(impl) {
/**
* @param {string} selector
* @param {Document|Element} [context]
*/
return function(selector, context) {
var callContext = this,
extra;
if (typeof selector === "string") {
if (context && context.querySelector) {
extra = Array.prototype.slice.call(arguments, 2);
} else {
extra = Array.prototype.slice.call(arguments, 1);
context = document;
}
select(selector, context, function(elem) {
impl.apply(callContext, [elem].concat(extra));
});
} else {
impl.apply(callContext, arguments);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q14788
|
select
|
train
|
function select(selector, context, fn) {
var nodes;
if (arguments.length === 2 && typeof context === "function") {
fn = context;
context = undefined;
}
nodes = (context || document).querySelectorAll(selector);
nodes = Array.prototype.slice.call(nodes);
if (fn) nodes.forEach(fn);
else return nodes;
}
|
javascript
|
{
"resource": ""
}
|
q14789
|
LooseInterval
|
train
|
function LooseInterval(fn, interval, callback) {
if (!(this instanceof LooseInterval)) return new LooseInterval(fn, interval, callback)
if (typeof fn != "function") throw new Error("LooseInterval requires a function")
if (typeof interval == "function") {
callback = interval
interval = null
}
this.fn = fn
this.interval = interval
this.callback = callback
EventEmitter.call(this)
this._running = false
if (interval != null) this.start(interval)
}
|
javascript
|
{
"resource": ""
}
|
q14790
|
process
|
train
|
function process(){
if (!conf.configured) that.configure();
var args = command.args.slice(0);
for(var i in args){
var arg = args[i];
if(conf.regexp.test(arg)){
var catchWord = RegExp.$2;
switch(RegExp.$1){
case '-':
processShortKey(catchWord, i, args);
break;
case '--':
processKey(catchWord, i, args);
break;
}
} else {
addArgument(arg);
}
}
conf.processed = true
}
|
javascript
|
{
"resource": ""
}
|
q14791
|
getPlatforms
|
train
|
function getPlatforms(options) {
return request('GET', 'https://saucelabs.com/rest/v1/info/platforms/webdriver')
.getBody('utf8').then(JSON.parse).then(function (platforms) {
var obj = {};
platforms.map(function (platform) {
return {
browserName: platform.api_name,
version: platform.short_version,
platform: platform.os
};
}).forEach(function (platform) {
if (platform.browserName === 'lynx') return;
if (!(options.filterPlatforms || defaultFilters.filterPlatforms)(platform, defaultFilters.filterPlatforms)) return;
obj[platform.browserName] = obj[platform.browserName] || {};
obj[platform.browserName][platform.version] = obj[platform.browserName][platform.version] || [];
obj[platform.browserName][platform.version].push(platform);
});
var result = {};
Object.keys(obj).forEach(function (browser) {
result[browser] = [];
Object.keys(obj[browser]).sort(function (versionA, versionB) {
if (isNaN(versionA) && isNaN(versionB)) return versionA < versionB ? -1 : 1;
if (isNaN(versionA)) return -1;
if (isNaN(versionB)) return 1;
return (+versionB) - (+versionA);
}).forEach(function (version, index) {
var platforms = obj[browser][version];
result[browser] = result[browser].concat((options.choosePlatforms || defaultFilters.choosePlatforms)(platforms));
});
});
return result;
});
}
|
javascript
|
{
"resource": ""
}
|
q14792
|
Blob
|
train
|
function Blob(source, parent, githubClient) {
this.gh = githubClient;
this.parent = parent;
this.sha = source.sha;
this.rawContent = source.content;
this.size = source.size;
this.contents = new Buffer(this.rawContent, 'base64').toString('utf-8');
}
|
javascript
|
{
"resource": ""
}
|
q14793
|
pJson
|
train
|
function pJson(events, top = '') {
Object.keys(events).forEach((i) => {
if (typeof events[i] === 'object' && events[i] != null) {
let rtn;
if (Object.prototype.toString.call(events) === '[object Array]') {
rtn = (`${top}[${i}]`);
} else { rtn = (`${top}.${i}`); }
pJson(events[i], rtn);
} else if (Object.prototype.toString.call(events) === '[object Array]') {
tmp += `{}${top}[${i}] = ${events[i]}\n`;
} else {
tmp += `{}${top}.${i} = ${events[i]}\n`;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q14794
|
jPretty
|
train
|
function jPretty(obj) {
// make sure data is a json obj
if(typeof obj === "string") {
obj = obj.replace(/\s/g,"");
obj = obj.replace(/'/g,'"');
}
let gl;
try {
const p = JSON.parse(obj);
gl = obj; // already stringified
} catch (e) { // not stringified
if(typeof obj === "string") {
obj = obj.replace(/([,|{|\s|])([a-zA-Z0-9]*?)([\s|]*\:)/g,'$1"$2"$3');
}
const s = JSON.stringify(obj);
const k = JSON.parse(JSON.stringify(obj));
if (k && typeof k === 'object') {
gl = s;
} else {
if(typeof obj === "string") {
//console.log("ERROR: " + );
obj = obj.replace(/"/g,"'");
obj = obj.replace(/'/g,'"');
gl = ((obj));
} else {
return new Error(`jpretty: input is not recognised json: ${typeof obj}- ${JSON.stringify(obj)}`);
}
}
}
return (() => {
let jp = prettyJson(gl);
if(typeof window !== 'undefined') {
console.log("jPretty loaded in browser");
jp = jp.replace(/\{\}/g,"<br/>{}");
}
return jp;
})()
}
|
javascript
|
{
"resource": ""
}
|
q14795
|
Client
|
train
|
function Client(options) {
options = options || { };
this._key = options.key || null;
this._secret = options.secret || null;
this._proxy = options.proxy || null;
return this;
}
|
javascript
|
{
"resource": ""
}
|
q14796
|
parallel
|
train
|
async function parallel(resolvers, limit=-1){
// set default limit
if (limit < 1){
limit = 1000;
}
// buffer
const results = [];
// calculate chunk size
// limit step size to input array size
const chunkSize = Math.min(limit, resolvers.length);
// process resolvers in chunks
for (let i=0;i<resolvers.length;i=i+chunkSize){
// extract current chunk
const chunk = resolvers.slice(i, Math.min(i+chunkSize, resolvers.length));
// resolve current chunk
const intermediateResults = await Promise.all(chunk.map((r) => r.resolve()));
// push results into buffer
results.push(...intermediateResults);
}
// return results
return results;
}
|
javascript
|
{
"resource": ""
}
|
q14797
|
train
|
function(error, newIndex) {
if (error) {
console.log('Data error for ' + dataurl + '\n' + error)
}
if (!error) {
index = newIndex
var timeStart = Date.now()
request(dataurl)
.pipe(JSONStream.parse())
.pipe(index.defaultPipeline())
.pipe(index.add())
.on('data', function(data) {
//console.dir(data) // What's going on in the indexing process
})
.on('end', () => {
var timeEnd = Date.now()
var timeUsed = Math.trunc((timeEnd - timeStart) / 1000)
console.log('Indexed in ' + timeUsed + ' seconds')
})
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14798
|
train
|
function(str, len, padChar) {
str = stringIt(str);
if (str.length >= len) {
return str;
}
var padStr = getPadding(padChar, len);
return str + padStr.substr(str.length - len);
}
|
javascript
|
{
"resource": ""
}
|
|
q14799
|
train
|
function(str, start) {
return (str.length >= start.length &&
str.substr(0, start.length) === start);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.