_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q11500
|
isCompatible
|
train
|
function isCompatible(tdef, node) {
if (tdef && node) {
if (tdef.select('metaData[name=virtual]').array.length > 0) {
// tdef is virtual, so it is compatible
return true;
} else {
const nodePlatforms = getPlatforms(node.typeDefinition);
for (let i = 0; i < nodePlatforms.length; i++) {
if (tdef.select('deployUnits[name=*]/filters[name=platform,value=' + nodePlatforms[i] + ']').array.length > 0) {
return true;
}
}
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q11501
|
getFQN
|
train
|
function getFQN(tdef) {
const hasPreRelease = tdef.deployUnits.array.some((du) => {
return semver.prerelease(du.version) !== null;
});
const duTag = hasPreRelease ? '/LATEST' : '';
let fqn = tdef.name + '/' + tdef.version + duTag;
function walk(pkg) {
if (pkg.eContainer()) {
fqn = pkg.name + '.' + fqn;
walk(pkg.eContainer());
}
}
walk(tdef.eContainer());
return fqn;
}
|
javascript
|
{
"resource": ""
}
|
q11502
|
formatException
|
train
|
function formatException (ex) {
var stack = (ex.stack) ? String(ex.stack) : '',
message = ex.message || '';
return 'Error: ' + message + '\nStack: ' + stack;
}
|
javascript
|
{
"resource": ""
}
|
q11503
|
onError
|
train
|
function onError( error ) {
logger.error( error.stack || error );
process.exit( EXIT_FAILURE );
}
|
javascript
|
{
"resource": ""
}
|
q11504
|
baseIsMatch
|
train
|
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new _Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q11505
|
compareAscending
|
train
|
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol_1(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol_1(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
|
javascript
|
{
"resource": ""
}
|
q11506
|
customizeTimeAxis
|
train
|
function customizeTimeAxis(component, type) {
var axis = component.xAxis;
if (axis instanceof Plottable.Axes.Time) {
var customTimeAxisConfigs = getCustomTimeAxisConfigs(type);
axis.axisConfigurations(customTimeAxisConfigs);
if (type === 'year' || type === 'financial_year') {
axis.tierLabelPositions(customTimeAxisConfigs.map(function (v) {
return 'center';
}));
}
}
}
|
javascript
|
{
"resource": ""
}
|
q11507
|
removeInnerPadding
|
train
|
function removeInnerPadding(component) {
var _makeInnerScale = component.plot._makeInnerScale;
component.plot._makeInnerScale = function () {
return _makeInnerScale.call(this).innerPadding(0).outerPadding(0);
};
}
|
javascript
|
{
"resource": ""
}
|
q11508
|
prettyUrl
|
train
|
function prettyUrl(file) {
file.extname = ".html";
if (file.basename !== "index") {
file.dirname = path.join(file.dirname, file.basename);
file.basename = "index";
}
return file;
}
|
javascript
|
{
"resource": ""
}
|
q11509
|
train
|
function (name) {
if (name === undefined || name === 'stable') {
return 0;
}
else if (name === 'alpha') {
return Number.MAX_SAFE_INTEGER - 1;
}
else if (name == 'beta') {
return Number.MAX_SAFE_INTEGER - 2;
}
else {
// Possibly something like "RC", but for not officially supported
return Number.MAX_SAFE_INTEGER - 3;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q11510
|
train
|
function (constraint) {
let first = /((?:\d+(?:\.\d+){0,2}))\s+(\<=|\>=|\<|\>)\s+v/;
let second = /v\s+(\<=|\>=|\<|\>)\s+((?:\d+(?:\.\d+){0,2}))/;
let firstMatch = constraint.match(first);
let secondMatch = constraint.match(second);
;
let alwaysFail = (v) => false;
let firstOp = {
'<': (a) => (v) => a < v,
'<=': (a) => (v) => a <= v,
'>': (a) => (v) => a > v,
'>=': (a) => (v) => a >= v,
};
let secondOp = {
'<': (a) => (v) => v < a,
'<=': (a) => (v) => v <= a,
'>': (a) => (v) => v > a,
'>=': (a) => (v) => v >= a,
};
if (firstMatch && secondMatch) {
let firstVersion = parseVersionString(firstMatch[1]);
let secondVersion = parseVersionString(secondMatch[2]);
return [
firstVersion ? firstOp[firstMatch[2]](firstVersion) : alwaysFail,
secondVersion ? secondOp[secondMatch[1]](secondVersion) : alwaysFail
];
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q11511
|
train
|
function (dirname) {
return new Promise((resolve, reject) => {
fs.mkdir(dirname, (err) => {
if (err) {
reject(err);
}
else {
resolve(dirname);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q11512
|
train
|
function () {
let noop = function () { };
let log = {
error: npmlog.error,
warn: npmlog.warn,
info: noop,
verbose: noop,
silly: noop,
http: noop,
pause: noop,
resume: noop
};
return new RegClient({ log: log });
}
|
javascript
|
{
"resource": ""
}
|
|
q11513
|
train
|
function (version) {
return __awaiter(this, void 0, void 0, function* () {
let versions = yield ForestInternal.queryElmVersions();
let result = ForestInternal.findSuitable(version, versions);
if (result === null) {
throw new ForestError(Errors.NoMatchingVersion, `Unable to find an Elm version matching ${version} on NPM`);
}
return Promise.resolve(result);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q11514
|
train
|
function (path) {
return new Promise((resolve, reject) => {
fs.access(path, fs.constants.F_OK, (err) => {
if (err === null) {
resolve(true);
}
else if (err.code === 'ENOENT') {
resolve(false);
}
else {
reject(err);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q11515
|
train
|
function(){
this.manifest = {
apiEventType: '',
apiModelId: '', // this is the id for this module
routeBase: '', // this can be overwritten
routes: [
],
routeErrorMessages: {
conditions: 'No query conditions were specified',
query: 'Error querying for item(s): ',
notFound: 'No item was found.',
find: 'No item(s) matched your criteria.',
findOne: 'No item matched your criteria.',
update: 'No updates were specified.',
updateMatch: 'No items were updated based on your criteria.',
create: 'No data supplied for creating new item.',
createMatch: 'No item was created based on your criteria.',
remove: 'No data supplied for removing item.',
removeMatch: 'No item was removed based on your criteria.'
}
};
// return this object
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q11516
|
cleanPath
|
train
|
function cleanPath(p) {
p = JSON.stringify(p);
return p.slice(1, p.length - 1);
}
|
javascript
|
{
"resource": ""
}
|
q11517
|
isHelper
|
train
|
function isHelper(node) {
if (t.isMemberExpression(node)) {
return isHelper(node.object) || isHelper(node.property);
} else if (t.isIdentifier(node)) {
return node.name === "require" || node.name[0] === "_";
} else if (t.isCallExpression(node)) {
return isHelper(node.callee);
} else if (t.isBinary(node) || t.isAssignmentExpression(node)) {
return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right);
} else {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q11518
|
AssignmentExpression
|
train
|
function AssignmentExpression(node) {
var state = crawl(node.right);
if (state.hasCall && state.hasHelper || state.hasFunction) {
return {
before: state.hasFunction,
after: true
};
}
}
|
javascript
|
{
"resource": ""
}
|
q11519
|
CallExpression
|
train
|
function CallExpression(node) {
if (t.isFunction(node.callee) || isHelper(node)) {
return {
before: true,
after: true
};
}
}
|
javascript
|
{
"resource": ""
}
|
q11520
|
IfStatement
|
train
|
function IfStatement(node) {
if (t.isBlockStatement(node.consequent)) {
return {
before: true,
after: true
};
}
}
|
javascript
|
{
"resource": ""
}
|
q11521
|
encode
|
train
|
function encode(buffer, extra) {
if (!extra) extra = 0
var blen = buffer.length
var lenbytes = vencode(blen)
var mb = new Buffer(extra + blen + lenbytes.length)
for (var i = 0; i < lenbytes.length; i++) {
mb.writeUInt8(lenbytes[i], extra + i)
}
buffer.copy(mb, lenbytes.length + extra, 0, blen)
return mb
}
|
javascript
|
{
"resource": ""
}
|
q11522
|
pack
|
train
|
function pack(buffs, extra) {
var lengths = [],
lenbytes = [],
len = buffs.length,
extra = extra || 0,
sum = 0,
offset = 0,
mb,
i
for (i = 0; i < len; i++) {
lengths.push(buffs[i].length)
lenbytes.push(vencode(lengths[i]))
sum += lengths[i] + lenbytes[i].length + extra
}
mb = new Buffer(sum)
for (i = 0; i < len; i++) {
for (var j = 0; j < lenbytes[i].length; j++) {
mb.writeUInt8(lenbytes[i][j], offset + extra)
offset = offset + 1 + extra
}
buffs[i].copy(mb, offset, 0, lengths[i])
offset += lengths[i]
}
return mb
}
|
javascript
|
{
"resource": ""
}
|
q11523
|
unpack
|
train
|
function unpack(multibuffer) {
var buffs = []
var offset = 0
var length
while (offset < multibuffer.length) {
length = vdecode(multibuffer.slice(offset))
offset += vdecode.bytes
buffs.push(multibuffer.slice(offset, offset + length))
offset += length
}
return buffs
}
|
javascript
|
{
"resource": ""
}
|
q11524
|
readPartial
|
train
|
function readPartial(multibuffer) {
var dataLength = vdecode(multibuffer)
var read = vdecode.bytes
if (multibuffer.length < read + dataLength) return [null, multibuffer]
var first = multibuffer.slice(read, read + dataLength)
var rest = multibuffer.slice(read + dataLength)
if (rest.length === 0) rest = null
return [first, rest]
}
|
javascript
|
{
"resource": ""
}
|
q11525
|
determineKeyValueSpaces
|
train
|
function determineKeyValueSpaces(obj, tabSize) {
let lastDepth = 0;
let spacesIndex = 0;
let spaces = [];
//iterate over all lines
obj.forEach((line) => {
if (lastDepth !== line.depth) {
spacesIndex++;
}
//key found
if (line.key) {
//value found
if (line.value) {
//block line found
if (line.isBlockLine) {
line.keyValueSpaces = ' ';
} else {
if (!spaces[spacesIndex]) {
spaces[spacesIndex] = {
maxKeyLength: 1
};
}
//determine maxKeyLength
if (spaces[spacesIndex].maxKeyLength < line.key.length) {
if (spaces[spacesIndex].maxKeyLength < line.key.length) {
spaces[spacesIndex].maxKeyLength = line.key.length;
}
}
}
}
}
lastDepth = line.depth;
});
// reset the counters
lastDepth = 0;
spacesIndex = 0;
//iterate over all lines
obj.forEach((line) => {
if (lastDepth !== line.depth) {
spacesIndex++;
}
//key found
if (line.key) {
//value found
if (line.value) {
//block line found
if (!line.isBlockLine) {
if(spaces[spacesIndex]){
let numSpaces = spaces[spacesIndex].maxKeyLength - line.key.length + tabSize;
line.keyValueSpaces = '';
for (let i = 0; i < numSpaces; i++) {
line.keyValueSpaces += ' ';
}
}
}
}
}
lastDepth = line.depth;
});
console.log(obj);
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q11526
|
match_bitapScore_
|
train
|
function match_bitapScore_(e, x) {
var accuracy = e / pattern.length;
var proximity = Math.abs(loc - x);
if (!self.Match_Distance) {
// Dodge divide by zero error.
return proximity ? 1.0 : accuracy;
}
return accuracy + (proximity / self.Match_Distance);
}
|
javascript
|
{
"resource": ""
}
|
q11527
|
TpBuilderProcess
|
train
|
function TpBuilderProcess(str, options){
let init = str;
if (typeof str === 'object') {
init = init.map((item) => '{{@ ' + item + ' }}').join('\n');
}
return new TpBuilder(init, options).parse();
}
|
javascript
|
{
"resource": ""
}
|
q11528
|
train
|
function(options) {
options = options || {};
var optionsArray = [];
// Go through the available options,
// set either the passed option
// or the default
for (var i in apt.options) {
if (typeof options[i] !== 'undefined') {
addOption(optionsArray, i, options[i]);
} else {
addOption(optionsArray, i, apt.options[i]);
}
}
return optionsArray;
}
|
javascript
|
{
"resource": ""
}
|
|
q11529
|
train
|
function(optsArr, name, value) {
switch(typeof value) {
case 'boolean':
if (value) optsArr.push('--' + name);
break;
case 'string':
optsArr.push('--' + name);
optsArr.push(value);
break;
case 'function':
optsArr.push(value());
break;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q11530
|
train
|
function(command, options) {
options = options || [];
options.unshift(command);
return childProcess.spawn(apt.command, options, apt.spawnOptions);
}
|
javascript
|
{
"resource": ""
}
|
|
q11531
|
getOrdinal
|
train
|
function getOrdinal(value) {
const lastDigit = value % 10;
if (lastDigit === 1) {
return `${value}st`;
}
else if (lastDigit === 2) {
return `${value}nd`;
}
else if (lastDigit === 3) {
return `${value}rd`;
}
else {
return `${value}th`;
}
}
|
javascript
|
{
"resource": ""
}
|
q11532
|
getCallerLocation
|
train
|
function getCallerLocation() {
const error = new Error();
if (error.stack) {
const lines = error.stack.split("\n");
for (let i = 2; i < lines.length; i++) {
if (i > 0 && lines[i] === " at <anonymous>") {
const paren = lines[i - 1].indexOf("(");
if (paren >= 0) {
return lines[i - 1].slice(paren + 1, lines[i - 1].length - 1);
}
else {
return "";
}
}
else if (!lines[i].startsWith(" at CanaryTest.") &&
!lines[i].startsWith(" at new CanaryTest")) {
const paren = lines[i].indexOf("(");
if (paren >= 0) {
return lines[i].slice(paren + 1, lines[i].length - 1);
}
else {
return lines[i].slice(7, lines[i].length);
}
}
}
}
return "";
}
|
javascript
|
{
"resource": ""
}
|
q11533
|
normalizePath
|
train
|
function normalizePath(path) {
// Separate the path into parts (delimited by slashes)
let parts = [""];
for (let char of path) {
if (char === "/" || char === "\\") {
if (parts[parts.length - 1].length) {
parts.push("");
}
}
else {
parts[parts.length - 1] += char;
}
}
// Special case for when the entire path was "."
if (parts.length === 1 && parts[0] === ".") {
return ".";
}
// Resolve "." and ".."
let i = 0;
while (i < parts.length) {
if (parts[i] === ".") {
parts.splice(i, 1);
}
else if (i > 0 && parts[i] === "..") {
parts.splice(i - 1, 2);
i--;
}
else {
i++;
}
}
// Build the resulting path
let result = "";
for (let part of parts) {
if (part && part.length) {
if (result.length) {
result += "/";
}
result += part;
}
}
// Retain a slash at the beginning of the string
if (path[0] === "/" || path[0] === "\\") {
result = "/" + result;
}
// All done!
return result;
}
|
javascript
|
{
"resource": ""
}
|
q11534
|
maybeFireCallback
|
train
|
function maybeFireCallback() {
// This function is called in any place where we might have completed a task that allows us to fire
if (callbackFired) return;
// If everything is ready, we *should* fire the callback, and it hasn't already been fired, then do so
if (stdoutReady && stderrReady && wantCallback && !callbackFired) {
callbackFired = true;
callback(callbackErr, stdout);
}
}
|
javascript
|
{
"resource": ""
}
|
q11535
|
loadModulesConfig
|
train
|
async function loadModulesConfig()
{
if(!modulesLoaded)
{
for (let i = 0; i < modules.length; i++) {
await applyBotDataSource(modules[i]);
}
modulesLoaded = true;
}
}
|
javascript
|
{
"resource": ""
}
|
q11536
|
train
|
function (options, callback) {
var Deleter = {}
// Delete all docs with the IDs found in deleteBatch
Deleter.deleteBatch = function (deleteBatch, APICallback) {
tryDeleteBatch(options, deleteBatch, function (err) {
return APICallback(err)
})
}
// Flush the db (delete all entries)
Deleter.flush = function (APICallback) {
flush(options, function (err) {
return APICallback(err)
})
}
return callback(null, Deleter)
}
|
javascript
|
{
"resource": ""
}
|
|
q11537
|
bts2n
|
train
|
function bts2n(s) {
var n = 0;
for (var i = 0; i < s.length; ++i) {
var ch = s.charAt(i);
var digit = BT_DIGIT_TO_N[ch];
if (digit === undefined) throw new Error('bts2n('+s+'): invalid digit character: '+ch);
//console.log(i,digit,3**i,n,s,ch);
n += pow3(s.length - i - 1) * digit;
}
return n;
}
|
javascript
|
{
"resource": ""
}
|
q11538
|
n2bts
|
train
|
function n2bts(n_) {
var neg = n_ < 0;
var n = Math.abs(n_);
var s = '';
do {
var digit = n % 3;
// balance the ternary http://stackoverflow.com/questions/26456597/how-to-convert-from-unbalanced-to-balanced-ternary
if (digit === 2) {
digit = -1;
++n;
}
//console.log('digit',digit,n,n_,s);
// if number has negative sign, flip all digits
if (neg) {
digit = -digit;
}
s = N_TO_BT_DIGIT[digit] + s;
n = ~~(n / 3); // truncate, not floor! negatives
} while(n);
//console.log('n2bts',n_,s);
return s;
}
|
javascript
|
{
"resource": ""
}
|
q11539
|
startsWith
|
train
|
function startsWith(src, target) {
if (target && target.length > 0) {
return (src.substr(0, target.length) === target);
} else {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q11540
|
resolveScriptPaths
|
train
|
function resolveScriptPaths (filePath, m) {
const toParse = [ m ]
const lookup = {} // key is module name, value is path
while (toParse.length) {
let node = toParse.pop()
if (node.children)
for (let n of node.children)
toParse.push(n)
if (!node.scripts)
continue
for (let entry of node.scripts) {
let moduleName = camelcase(path.parse(entry.source).name)
lookup[moduleName] = entry.source
entry.module = moduleName
}
}
return lookup
}
|
javascript
|
{
"resource": ""
}
|
q11541
|
compileModel
|
train
|
async function compileModel (projectPath, model) {
await copyExternalScripts(projectPath, model)
deInlineScripts(projectPath, model)
const lookup = resolveScriptPaths(projectPath, model)
let imports = ''
for (let moduleName in lookup) {
let p = path.isAbsolute(lookup[moduleName]) ? lookup[moduleName] : `./${path.normalize(lookup[moduleName])}`
imports += `import ${moduleName} from '${p}'\n`
}
const pre = JSON.stringify(model, null, 2)
let post = pre
for (let moduleName in lookup)
post = replaceAll(post, moduleName)
return `import substrate from 'substrate'
// imports generated by the compiler
${imports}
const dom = document.createElement('div')
dom.id = 'myapp'
document.body.appendChild(dom)
const model = ${post}
const app = substrate({ dom, node: model.rootNode, registry: model.registry })`
}
|
javascript
|
{
"resource": ""
}
|
q11542
|
train
|
function () {
var s = null;
if (PFT.tester._suites.length > 0) {
s = PFT.tester._suites[PFT.tester._suites.length - 1];
}
return s;
}
|
javascript
|
{
"resource": ""
}
|
|
q11543
|
train
|
function () {
var t = null;
if (PFT.tester._tests.length > 0) {
t = PFT.tester._tests[PFT.tester._tests.length - 1];
}
return t;
}
|
javascript
|
{
"resource": ""
}
|
|
q11544
|
train
|
function (testObj) {
var duration = PFT.convertMsToHumanReadable(new Date().getTime() - testObj.startTime);
testObj.duration = duration;
var suite = "";
if (testObj.suite) {
if (testObj.suite.name) {
suite = testObj.suite.name + " - ";
}
}
var msg = "Completed: '" + suite + testObj.name + "' in " + duration + " with " + testObj.passes + " passes, " +
testObj.failures.length + " failures, " + testObj.errors.length + " errors.";
PFT.logger.log(PFT.logger.TEST, msg);
PFT.tester.onTestCompleted({ test: testObj });
try {
testObj.page.close();
} catch (e) {
PFT.warn(e);
}
PFT.tester.remainingCount--;
PFT.tester.exitIfDoneTesting();
}
|
javascript
|
{
"resource": ""
}
|
|
q11545
|
train
|
function (msg) {
// restart MutexJs in case exception caused fatal javascript halt
MutexJs.recover();
// unexpected exception so log in errors and move to next
var t = PFT.tester.currentTest();
t.errors.push(msg);
PFT.tester.onError({ test: t, message: msg });
PFT.tester.closeTest(t);
// move to next test
MutexJs.release(t.runUnlockId);
}
|
javascript
|
{
"resource": ""
}
|
|
q11546
|
uBrokersManager
|
train
|
function uBrokersManager(){
var listenClient = redis.createClient(config.redis[0].port, config.redis[0].server);
listenClient.on("error", function (err) {
console.log("Redis listen error " + err);
});
listenClient.on('message', function(channel, message) {
client.get('uBrokers', function(err, reply) {
uBrokers = JSON.parse(reply);
});
});
listenClient.subscribe('uBrokersChannel');
}
|
javascript
|
{
"resource": ""
}
|
q11547
|
selectService
|
train
|
function selectService (service){
if(typeof(uServices[service]) !== 'undefined'){
if (uServices[service].length !== 0 ) {
var uService = uServices[service], //array
activeuService = uService[0];
// the first service should be active but if is not, should look for an active one
if (activeuService.status == 0) {
var foundOne = false;
for ( var i = 0 ; i < uService.length ; i++ ){
if ( foundOne == false && uService[i].status == 1 ) {
activeuService = uService[i];
foundOne = true;
}
}
//if there is not active service just stay whith the first one
}
activeuService.status = 0; //change state to busy
uService.shift(); //take the service out of the list
uService.push(activeuService); // pushing the service at the end of the list
uService[0].status = 1; //activate other service
//save the new uServices
uServices[service] = uService;
// changing the variable on redis
client.set('uServices', JSON.stringify(uServices));
// Publish that it did an update
client.publish('uServicesChannel', 'UPDATE');
return activeuService;
} else {
//not services availables
console.log('Not services %s available', service);
//return error to broker
return 'Not services '+service+' available'
}
} else {
return "not services with name "+service;
// return an error cause there are no services with that name
}
}
|
javascript
|
{
"resource": ""
}
|
q11548
|
addService
|
train
|
function addService(service, serviceObject){
client.get('uServices', function(err, reply) {
if (reply == null){
//extend this object
//add a key with service name and value service channel
//this is the first service i should activate it
var newObjectToPush = JSON.parse('{"' + service + '": []}');//found a fancy way to make this
serviceObject.status = 1;
newObjectToPush[service].push(serviceObject);
extend(uServices, newObjectToPush);
setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE')
} else {
uServices = JSON.parse(reply);
if (typeof(uServices[service]) !== 'undefined') {
var uService = uServices[service];
uService.push(serviceObject);
//save the new uServices
uServices[service] = uService;
setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE')
} else {
//extend this object
//add a key with service name and value service channel
var stringObject = '{"' + service + '": []}'; //found a fancy way to make this
var objectToPush = JSON.parse(stringObject);
objectToPush[service].push(serviceObject);
extend(uServices, objectToPush);
setAndPublish('uServices',uServices,'uServicesChannel', 'UPDATE')
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q11549
|
setAndPublish
|
train
|
function setAndPublish(variableName, object, channel, option){
client.set(variableName, JSON.stringify(object));
// Publish that it did an update
client.publish(channel, option);
}
|
javascript
|
{
"resource": ""
}
|
q11550
|
pushOrPut
|
train
|
function pushOrPut (currentBin, index) {
var temp = currentBin;
if (Array.isArray(currentBin)) {
if (currentBin.indexOf(index) === -1) {
currentBin.push(index);//only add if this is a unique index to prevent dup'ing indexes, and associations
}
} else {
temp = [index];
}
return temp;
}
|
javascript
|
{
"resource": ""
}
|
q11551
|
buildHashTableIndices
|
train
|
function buildHashTableIndices (bin, leftValue, index, accessors, rightKeys) {
var i,
length = accessors.length,
lastBin,
val;
for (i = 0; i < length; i += 1) {
val = accessors[i](leftValue);
if (typeof val === "undefined") {
return;
}
if (i + 1 === length) {
if (Array.isArray(val)) {
//for each value in val, put that key in
val.forEach(function (subValue) {
var boot = putKeyInBin(bin, subValue);
bin[subValue] = pushOrPut(boot, index);
bin[subValue].$val = subValue;
});
} else {
bin[val] = pushOrPut(bin[val], index);
bin[val].$val = val;
}
} else if (Array.isArray(val)) {
lastBin = bin;
val.forEach(function (subDocumentValue) {//sub vals are for basically supposed to be payment ids
var rightKeySubset = rightKeys.slice(i + 1);
if (isNullOrUndefined(bin[subDocumentValue])) {
bin[subDocumentValue] = {$val: subDocumentValue};//Store $val to maintain the data type
}
buildHashTableIndices(bin[subDocumentValue], leftValue, index, accessors.slice(i + 1), rightKeySubset);
});
return;//don't go through the rest of the accessors, this recursion will take care of those
} else {
bin = putKeyInBin(bin, val);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q11552
|
buildQueriesFromHashBin
|
train
|
function buildQueriesFromHashBin (keyHashBin, rightKeys, level, valuePath, orQueries, inQueries) {
var keys = Object.getOwnPropertyNames(keyHashBin),
or;
valuePath = valuePath || [];
if (level === rightKeys.length) {
or = {};
rightKeys.forEach(function (key, i) {
inQueries[i].push(valuePath[i]);
or[key] = valuePath[i];
});
orQueries.push(or);
//start returning
//take the value path and begin making objects out of it
} else {
keys.forEach(function (key) {
if (key !== "$val") {
var newPath = valuePath.slice(),
value = keyHashBin[key].$val;
newPath.push(value);//now have a copied array
buildQueriesFromHashBin(keyHashBin[key], rightKeys, level + 1, newPath, orQueries, inQueries);
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q11553
|
arrayJoin
|
train
|
function arrayJoin (results, args) {
var srcDataArray = results,//use these results as the source of the join
joinCollection = args.joinCollection,//This is the mongoDB.Collection to use to join on
joinQuery = args.joinQuery,
joinType = args.joinType || 'left',
rightKeys = args.rightKeys || [args.rightKey],//Get the value of the key being joined upon
newKey = args.newKey,//The new field onto which the joined document will be mapped
callback = args.callback,//The callback to call at this level of the join
length,
i,
subqueries,
keyHashBin = {},
accessors = [],
joinLookups = [],
inQueries = [],
leftKeys = args.leftKeys || [args.leftKey];//place to put incoming join results
rightKeys.forEach(function () {
inQueries.push([]);
});
leftKeys.forEach(function (key) {//generate the accessors for each entry in the composite key
accessors.push(getKeyValueAccessorFromKey(key));
});
length = results.length;
//get the path first
for (i = 0; i < length; i += 1) {
buildHashTableIndices(keyHashBin, results[i], i, accessors, rightKeys, inQueries, joinLookups, {});
}//create the path
buildQueriesFromHashBin(keyHashBin, rightKeys, 0, [], joinLookups, inQueries);
if (!Array.isArray(srcDataArray)) {
srcDataArray = [srcDataArray];
}
subqueries = getSubqueries(inQueries, joinLookups, joinQuery, args.pageSize || 25, rightKeys);//example
runSubqueries(subqueries, function (items) {
var un;
performJoining(srcDataArray, items, {
rightKeyPropertyPaths: rightKeys,
newKey: newKey,
keyHashBin: keyHashBin
});
if (joinType === "inner") {
removeNonMatchesLeft(srcDataArray, newKey);
}
if (joinStack.length > 0) {
arrayJoin(srcDataArray, joinStack.shift());
} else {
callIfFunction(finalCallback, [un, srcDataArray]);
}
callIfFunction(callback, [un, srcDataArray]);
}, joinCollection);
}
|
javascript
|
{
"resource": ""
}
|
q11554
|
getSubqueries
|
train
|
function getSubqueries (inQueries, orQueries, otherQuery, pageSize, rightKeys) {
var subqueries = [],
numberOfChunks,
i,
inQuery,
orQuery,
queryArray,
from,
to;
// this is a stupid way to turn numbers into 1
numberOfChunks = (orQueries.length / pageSize) + (!!(orQueries.length % pageSize));
for (i = 0; i < numberOfChunks; i += 1) {
inQuery = {};
from = i * pageSize;
to = from + pageSize;
rightKeys.forEach(function (key, index) {
inQuery[rightKeys[index]] = {$in: inQueries[index].slice(from, to)};
});
orQuery = { $or: orQueries.slice(from, to)};
queryArray = [ { $match: inQuery }, { $match: orQuery } ];
if(otherQuery) {
queryArray.push({ $match: otherQuery });
//Push this to the end on the assumption that the join properties will be indexed, and the arbitrary
//filter properties won't be indexed.
}
subqueries.push(queryArray);
}
return subqueries;
}
|
javascript
|
{
"resource": ""
}
|
q11555
|
runSubqueries
|
train
|
function runSubqueries (subQueries, callback, collection) {
var i,
responsesReceived = 0,
length = subQueries.length,
joinedSet = [];//The array where the results are going to get stuffed
if (subQueries.length > 0) {
for (i = 0; i < subQueries.length; i += 1) {
collection.aggregate(subQueries[i], function (err, results) {
joinedSet = joinedSet.concat(results);
responsesReceived += 1;
if (responsesReceived === length) {
callback(joinedSet);
}
});
}
} else {
callback([]);
}
return joinedSet;
}
|
javascript
|
{
"resource": ""
}
|
q11556
|
getKeyValueAccessorFromKey
|
train
|
function getKeyValueAccessorFromKey (lookupValue) {
var accessorFunction;
if (typeof lookupValue === "string") {
accessorFunction = function (resultValue) {
var args = [resultValue];
args = args.concat(lookupValue.split("."));
return safeObjectAccess.apply(this, args);
};
} else if (typeof lookupValue === "function") {
accessorFunction = lookupValue;
}
return accessorFunction;
}
|
javascript
|
{
"resource": ""
}
|
q11557
|
performJoining
|
train
|
function performJoining (sourceData, joinSet, joinArgs) {
var length = joinSet.length,
i,
rightKeyAccessors = [];
joinArgs.rightKeyPropertyPaths.forEach(function (keyValue) {
rightKeyAccessors.push(getKeyValueAccessorFromKey(keyValue));
});
for (i = 0; i < length; i += 1) {
var rightRecord = joinSet[i],
currentBin = joinArgs.keyHashBin;
if (isNullOrUndefined(rightRecord)) {
continue;//move onto the next, can't join on records that don't exist
}
//for each entry in the join set add it to the source document at the correct index
rightKeyAccessors.forEach(function (accessor) {
currentBin = currentBin[accessor(rightRecord)];
});
currentBin.forEach(function (sourceDataIndex) {
var theObject = sourceData[sourceDataIndex][joinArgs.newKey];
if (isNullOrUndefined(theObject)) {//Handle adding multiple matches to the same sub document
sourceData[sourceDataIndex][joinArgs.newKey] = rightRecord;
} else if (Array.isArray(theObject)) {
theObject.push(rightRecord);
} else {
sourceData[sourceDataIndex][joinArgs.newKey] = [theObject, rightRecord];
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q11558
|
safeObjectAccess
|
train
|
function safeObjectAccess () {
var object = arguments[0],
length = arguments.length,
args = arguments,
i,
results,
temp;
if (!isNullOrUndefined(object)) {
for (i = 1; i < length; i += 1) {
if (Array.isArray(object)) {//if it's an array find the values from those results
results = [];
object.forEach(function (subDocument) {
temp = safeObjectAccess.apply(
safeObjectAccess,
[subDocument].concat(Array.prototype.slice.apply(args, [i, length]))
);
if (Array.isArray(temp)) {
results = results.concat(temp);
} else {
results.push(temp);
}
});
break;
}
if (typeof object !== "undefined") {
object = object[arguments[i]];
} else {
break;
}
}
}
return results || object
}
|
javascript
|
{
"resource": ""
}
|
q11559
|
takeCurve
|
train
|
function takeCurve(pred) {
for(var i=0, n=horizon.length; i<n; ++i) {
var c = horizon[i]
if(pred(c)) {
horizon[i] = horizon[n-1]
horizon.pop()
return c
}
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q11560
|
reflexLeft
|
train
|
function reflexLeft(left, p, i0, i1) {
for(var i=i1; i>i0; --i) {
var a = left[i-1]
var b = left[i]
if(orient(a, b, p) <= 0) {
cells.push([a[2], b[2], p[2]])
} else {
return i
}
}
return i0
}
|
javascript
|
{
"resource": ""
}
|
q11561
|
reflexRight
|
train
|
function reflexRight(right, p, i0, i1) {
for(var i=i0; i<i1; ++i) {
var a = right[i]
var b = right[i+1]
if(orient(p, a, b) <= 0) {
cells.push([p[2], a[2], b[2]])
} else {
return i
}
}
return i1
}
|
javascript
|
{
"resource": ""
}
|
q11562
|
mergeSegment
|
train
|
function mergeSegment(row, x0, x1) {
//Take left and right curves out of horizon
var left = takeCurve(function(c) {
return c[c.length-1][0] === x0
})
var right = takeCurve(function(c) {
return c[0][0] === x1
})
//Create new vertices
var p0 = [x0,row,vertices.length]
var p1 = [x1,row,vertices.length+1]
vertices.push([x0, row], [x1,row])
//Merge chains
var ncurve = []
if(left) {
var l1 = reflexLeft(left, p0, 0, left.length-1)
for(var i=0; i<=l1; ++i) {
ncurve.push(left[i])
}
}
ncurve.push(p0, p1)
if(right) {
var r0 = reflexRight(right, p1, 0, right.length-1)
for(var i=r0; i<right.length; ++i) {
ncurve.push(right[i])
}
}
//Append new chain to horizon
horizon.push(ncurve)
}
|
javascript
|
{
"resource": ""
}
|
q11563
|
_sendRequest
|
train
|
function _sendRequest (options) {
return new Promise((resolve, reject) => {
var query = querystring.stringify(options.query)
var bodyData = JSON.stringify(options.body)
request({
url: _baseUrl + `/${options.endpoint}?${query}`,
headers: headers,
method: options.method,
body: bodyData
}, (error, response, body) => {
if (error) {
reject(error)
}
resolve(body)
})
})
}
|
javascript
|
{
"resource": ""
}
|
q11564
|
getTypeAnnotation
|
train
|
function getTypeAnnotation() {
if (this.typeAnnotation) return this.typeAnnotation;
var type = this._getTypeAnnotation() || t.anyTypeAnnotation();
if (t.isTypeAnnotation(type)) type = type.typeAnnotation;
return this.typeAnnotation = type;
}
|
javascript
|
{
"resource": ""
}
|
q11565
|
getNormalizedTag
|
train
|
function getNormalizedTag(tag_buffer) {
var match = NORMALIZE_TAG_REGEX.exec(tag_buffer);
return match ? match[1].toLowerCase() : null;
}
|
javascript
|
{
"resource": ""
}
|
q11566
|
determineDepth
|
train
|
function determineDepth(obj){
let depth = 0;
obj.forEach((line)=>{
line.depth = depth;
if(line.isBlockKey){
depth++;
}else{
if(line.key){
if(line.key.toUpperCase() === 'END'){
depth--;
line.depth = depth;
}
}
}
});
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q11567
|
encode
|
train
|
function encode(hexString) {
// Convert to array of bytes
var bytes = Buffer.from(hexString, "hex");
var encoded = base32.stringify(bytes);
// strip padding & lowercase
return encoded.replace(/(=+)$/, '').toLowerCase();
}
|
javascript
|
{
"resource": ""
}
|
q11568
|
decode
|
train
|
function decode(base32String) {
// Decode to Buffer
var bytes = base32.parse(base32String, {
out: Buffer.alloc,
loose: true
});
return bytes.toString("hex");
}
|
javascript
|
{
"resource": ""
}
|
q11569
|
train
|
function(setArr, cb){
if(typeof setArr === "string")
var postData = querystring.stringify([setArr]);
else if(typeof setArr === "object" || typeof setArr === "array")
var postData = querystring.stringify(setArr);
var options = {
host: urlArr.hostname,
path: "/set",
port: urlArr.port,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var postRequest = protocol.request(options, function(res){
var result = "";
if(res.statusCode === 200){
res.on('error', function(error) {
if(typeof cb === "function")
cb(error);
});
res.on('data', function (chunk) {
result += chunk;
});
res.on('end', function (chunk) {
if(typeof cb === "function"){
var resultObj = JSON.parse(result);
var err = (resultObj.status === "error") ? resultObj["msg"] : null;
cb(err, resultObj);
}
});
}
else{
if(typeof cb === "function")
cb("Request return HTTP "+res.statusCode);
}
});
postRequest.write(postData);
postRequest.end();
}
|
javascript
|
{
"resource": ""
}
|
|
q11570
|
train
|
function(link, cb){
var options = {
host: urlArr.hostname,
port: urlArr.port,
path: urlArr.path+"?link="+encodeURIComponent(link),
method: 'GET'
};
var getRequest = protocol.request(options, function(res){
var result = "";
if(res.statusCode === 200){
res.on('error', function(error) {
if(typeof cb === "function")
cb(error);
});
res.on('data', function (chunk) {
result += chunk;
});
res.on('end', function (chunk) {
if(typeof cb === "function"){
var resultObj = JSON.parse(result);
var err = (resultObj.status === "error") ? resultObj["msg"] : null
cb(err, resultObj);
}
});
}
else{
if(typeof cb === "function")
cb("Request return HTTP "+res.statusCode);
}
});
getRequest.end();
}
|
javascript
|
{
"resource": ""
}
|
|
q11571
|
train
|
function(link, cb){
var id = Math.abs(crc32.str(md5(link)));
var options = {
host: urlArr.hostname,
port: urlArr.port,
path: "/delete/"+id,
method: 'DELETE',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
var deleteRequest = protocol.request(options, function(res){
var result = "";
if(res.statusCode === 200){
res.on('error', function(error){
if(typeof cb === "function")
cb(error);
});
res.on('data', function(chunk){
result += chunk;
});
res.on('end', function(chunk){
if(typeof cb === "function"){
var resultObj = JSON.parse(result);
var err = (resultObj.status === "error") ? resultObj["msg"] : null
cb(err, resultObj);
}
});
}
else{
if(typeof cb === "function")
cb("Request return HTTP "+res.statusCode);
}
});
deleteRequest.end();
}
|
javascript
|
{
"resource": ""
}
|
|
q11572
|
train
|
function (request) {
// This function is the default logging function.
return {
host: request.headers.host,
method: request.method,
timestamp: new Date(),
url: request.url
};
}
|
javascript
|
{
"resource": ""
}
|
|
q11573
|
train
|
function (newPaneOptions) {
var kb = UI.store
var newInstance = newPaneOptions.newInstance || kb.sym(newPaneOptions.newBase)
var u = newInstance.uri
if (u.endsWith('/')) {
u = u.slice(0, -1) // chop off trailer
}// { throw new Error('URI of new folder must end in "/" :' + u) }
newPaneOptions.newInstance = kb.sym(u + '/')
// @@@@ kludge until we can get the solid-client version working
// Force the folder by saving a dummy file inside it
return kb.fetcher.webOperation('PUT', newInstance.uri + '.dummy')
.then(function () {
console.log('New folder created: ' + newInstance.uri)
return kb.fetcher.delete(newInstance.uri + '.dummy')
})
.then(function () {
console.log('Dummy file deleted : ' + newInstance.uri + '.dummy')
/*
return kb.fetcher.createContainer(parentURI, folderName) // Not BOTH ways
})
.then(function () {
*/
console.log('New container created: ' + newInstance.uri)
return newPaneOptions
})
}
|
javascript
|
{
"resource": ""
}
|
|
q11574
|
train
|
function (obj) { // @@ This hiddenness should actually be server defined
var pathEnd = obj.uri.slice(obj.dir().uri.length)
return !(pathEnd.startsWith('.') || pathEnd.endsWith('.acl') || pathEnd.endsWith('~'))
}
|
javascript
|
{
"resource": ""
}
|
|
q11575
|
runScripts
|
train
|
function runScripts() {
var scripts = [];
var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"];
var index = 0;
/**
* Transform and execute script. Ensures correct load order.
*/
var exec = function exec() {
var param = scripts[index];
if (param instanceof Array) {
transform.run.apply(transform, param);
index++;
exec();
}
};
/**
* Load, transform, and execute all scripts.
*/
var run = function run(script, i) {
var opts = {};
if (script.src) {
transform.load(script.src, function (param) {
scripts[i] = param;
exec();
}, opts, true);
} else {
opts.filename = "embedded";
scripts[i] = [script.innerHTML, opts];
}
};
// Collect scripts with Babel `types`.
var _scripts = global.document.getElementsByTagName("script");
for (var i = 0; i < _scripts.length; ++i) {
var _script = _scripts[i];
if (types.indexOf(_script.type) >= 0) scripts.push(_script);
}
for (i in scripts) {
run(scripts[i], i);
}
exec();
}
|
javascript
|
{
"resource": ""
}
|
q11576
|
find
|
train
|
function find(obj, node, parent) {
if (!obj) return;
var result;
var types = Object.keys(obj);
for (var i = 0; i < types.length; i++) {
var type = types[i];
if (t.is(type, node)) {
var fn = obj[type];
result = fn(node, parent);
if (result != null) break;
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q11577
|
writeAndRunCodeBlocks
|
train
|
function writeAndRunCodeBlocks(codeBlocks) {
var dir = '.runnable-markdown-' + rand.generateKey(7);
return makeTempDir(dir)
.then(function() {
return new Promise(function(fulfill, reject) {
async.mapSeries(codeBlocks, function(codeBlock, callback) {
appendCodeBlockToFile(codeBlock, dir)
.then(runCodeBlock)
.then(function(codeBlock) {
callback(null, codeBlock);
})
.catch(function(err) {
callback(err, null);
});
}, convertAsyncResultToPromise(fulfill, reject));
});
})
.then(function(codeBlocks) {
return removeOldDir(dir)
.then(function() {
return codeBlocks;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q11578
|
runCodeBlock
|
train
|
function runCodeBlock(codeBlock) {
var dir = path.dirname(codeBlock.filename);
return new Promise(function(fulfill, reject) {
var filenameWithoutDir = codeBlock.filename.replace(dir + '/', '');
var command = runner(codeBlock, filenameWithoutDir);
if (command === null) {
fulfill(codeBlock);
return;
}
exec(command, {cwd: dir}, function(error, stdout, stderr) {
if (error) {
console.error(error);
reject(error);
} else {
if (stdout) {
console.log(stdout);
}
if (stderr) {
console.error(stderr);
}
fulfill(codeBlock);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q11579
|
countdownTimer
|
train
|
function countdownTimer() {
$(COUNTDOWN).html("0m 0s");
var end_t = COUNTDOWNTIME;
var start_t = (new Date()).getTime()/1000;
function countdown() {
var cur_t = (new Date()).getTime()/1000;
var timeleft = (end_t - (cur_t - start_t));
if (timeleft >= 0) {
var min = Math.floor(timeleft / 60);
var sec = Math.floor(timeleft % 60);
$(COUNTDOWN).html(min + "m " + sec + "s");
COUNTDOWNTID = setTimeout(countdown, 1000);
} else {
$.post("/games/" + enc($.cookie("game")) + "/players",
{end_turn: true}, function() {
getPlayers();
});
}
}
countdown();
}
|
javascript
|
{
"resource": ""
}
|
q11580
|
drawTurnInfo
|
train
|
function drawTurnInfo(pdata) {
var my_game = $.cookie("game");
var my_player = pdata[$.cookie("player")];
$(PIECES).empty();
$(ADDPIECE).show();
// allow player to end his turn
if (my_player.has_turn) {
$(ENDTURN).removeAttr('disabled');
$(TURN).html("It's your turn! You have " +
"<span id='countdown'>0m 0s</span> left.");
$(ENDTURN)[0].onclick = function() {
$.post("/games/" + enc(my_game) + "/players", {end_turn: true}, function() {
getPlayers();
/* Typically we let HAVETURN get updated from the server
* in onGetPlayers(), but if there is only one player this
* doesn't work very well (the player has to refresh manually).
* So we force it to false here in this special case.
*/
if (Object.keys(pdata).length === 1) {
HAVETURN = false;
clearTimeout(COUNTDOWNTID);
}
});
};
} else {
$(ENDTURN).attr('disabled', '');
$(TURN).html("It's not your turn.");
}
getPiecesLeft();
getBoard();
getMyPieces(my_player);
}
|
javascript
|
{
"resource": ""
}
|
q11581
|
getMyPieces
|
train
|
function getMyPieces(player) {
for (var i in player.pieces) {
var piece = player.pieces[i];
$(PIECES).append('<div class="piece" style="color:'+
pastels[piece.color]+'">'+ushapes[piece.shape]+'</div>');
$(PIECECLS+":last-child").data("piece", piece);
$(PIECES).append("<div style='float: left; margin: 3px'></div>");
}
function setDimensions() {
$(PIECECLS).width($(GRIDCLS).width());
$(PIECECLS).height($(GRIDCLS).height());
var fontsize = $(GRIDCLS).css("font-size");
$(PIECECLS).css("font-size", fontsize);
$(PIECECLS).css("line-height", fontsize);
}
/* Style switching is flaky here, we're depending on the width that was set
* in getBoard() and maybe that happens too fast sometimes. So we add a
* setTimeout to try setting dimensions again in a short while.
*/
setDimensions();
setTimeout(setDimensions, 250);
if (player.has_turn)
$(PIECECLS).draggable({
containment: "#board",
snap: ".snapgrid"
});
}
|
javascript
|
{
"resource": ""
}
|
q11582
|
getPiecesLeft
|
train
|
function getPiecesLeft() {
$.getJSON("/games/" + enc($.cookie("game")) +
"/pieces", function(data) {
$(GAMEPIECES).empty();
var npieces = 0;
for (var i in data)
npieces += data[i].count;
$(GAMEPIECES).html(npieces);
});
}
|
javascript
|
{
"resource": ""
}
|
q11583
|
onPieceDrop
|
train
|
function onPieceDrop(event, ui) {
var col = $(this).data().col;
var row = $(this).data().row;
var piece = $(ui.draggable).data().piece;
$.ajax({
type: 'POST',
url: "/games/" + enc($.cookie("game")) + "/board",
data: {
shape: piece.shape,
color: piece.color,
row: row,
column: col
},
success: function() {
$(ERRORS).empty();
},
error: function (jqXHR, textStatus, errorThrown) {
$(ERRORS).empty();
$(ERRORS).append("<div class='error'>⚠ "+jqXHR.responseText+"</div>");
},
complete: function() {
$.getJSON("/games/" + enc($.cookie("game")) +
"/players", drawTurnInfo);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q11584
|
drawChatIn
|
train
|
function drawChatIn() {
$(CHATIN).show();
function submit() {
var chatin = $(CHATIN+"> input")[0].value;
if (!CHATRE.test(chatin)) {
if(chatin) {
alert("Your input text is too long!");
}
return false;
}
var game = $.cookie("game");
var resource;
if (game) {
resource = "/games/" + enc(game) + "/chat";
} else {
resource = "/chat";
}
$.post(resource, {
input: chatin,
name: $.cookie("player")
}, function() {
$(CHATIN+"> input").val(''); // post was succesful, so clear input
drawChatLog();
});
}
$(CHATIN+"> button").click(submit);
$(CHATIN+"> input:visible").focus();
$(CHATIN+"> input").keydown(function(event) {
if (event.keyCode === 13) {
submit();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q11585
|
drawAddGuest
|
train
|
function drawAddGuest() {
$(ADDGUEST).show();
function submit() {
var name = $(ADDGUESTFRM+"> input")[0].value;
if (!NAMERE.test(name)) {
if(name) {
alert("Your input text is too long!");
}
return false;
}
$.cookie("player", name);
main();
}
$(ADDGUESTFRM+"> button").click(submit);
$(ADDGUESTFRM+"> input:visible").focus();
$(ADDGUESTFRM+"> input").keydown(function(event) {
if (event.keyCode === 13) {
submit();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q11586
|
drawLobby
|
train
|
function drawLobby(games) {
$(LOBBYCHAT).append($(CHATPNL)[0]);
$(CHATPNL).addClass('lobby_chat_panel');
drawGameList(games);
// setup future calls to get game list
function pollGames() {
$.getJSON("/games", drawGameList);
GETGAMESTID = setTimeout(pollGames, 2000);
}
GETGAMESTID = setTimeout(pollGames, 2000);
}
|
javascript
|
{
"resource": ""
}
|
q11587
|
drawGame
|
train
|
function drawGame() {
getPlayers();
getBoard();
getPiecesLeft();
$(SIDEBOARD).append("<hr/>");
$(SIDEBOARD).append($(CHATPNL));
$(CHATPNL).addClass('game_chat_panel');
$(LEAVEGAME)[0].onclick = function () {
clearTimeout(GETPLAYERSTID);
$.ajax({
type: 'DELETE',
url: "/games/" + enc($.cookie("game")) + "/players",
data: {name: $.cookie("player")},
success: function() {
$.removeCookie('game');
location.reload();
}
});
};
// setup future calls
function pollPlayers() {
getPlayers();
GETPLAYERSTID = setTimeout(pollPlayers, 2000);
}
GETPLAYERSTID = setTimeout(pollPlayers, 2000);
}
|
javascript
|
{
"resource": ""
}
|
q11588
|
gameOrLobby
|
train
|
function gameOrLobby(games) {
$(LOBBY).hide();
$(GAMEROOM).hide();
$(ADDGUEST).hide();
if (!$.cookie("player")) {
drawAddGuest();
return;
}
// hide the fork me banner from now on
$(FORKME).hide();
var my_game = $.cookie("game");
// User is not in a valid game
if (typeof games[my_game] === 'undefined') {
$.removeCookie('game');
$(LOBBY).show();
drawLobby(games);
} else {
$(GAMEROOM).show();
drawGame();
}
$(CHATPNL).show();
drawChatLog();
drawChatIn();
// setup future calls to get chat
function pollChat() {
drawChatLog();
DRAWCHATTID = setTimeout(pollChat, 2000);
}
DRAWCHATTID = setTimeout(pollChat, 2000);
}
|
javascript
|
{
"resource": ""
}
|
q11589
|
fmtconv
|
train
|
function fmtconv (input, output, compact = false) {
if (!input) {
throw new TypeError('"input" argument must be a file path')
} else if (!output) {
throw new TypeError('"output" argument must be a file path')
}
let extInput = path.extname(input).toLowerCase()
if (extInput !== '.yaml' && extInput !== '.yml' && extInput !== '.json') {
throw new TypeError('"input" file extension must be ".yaml" or ".yml" or ".json"')
}
let extOutput = path.extname(output).toLowerCase()
if (extOutput !== '.yaml' && extOutput !== '.yml' && extOutput !== '.json') {
throw new TypeError('"output" file extension must be ".yaml" or ".yml" or ".json"')
}
fs.accessSync(input, fs.R_OK)
let doc = '' + fs.readFileSync(input)
switch (extInput) {
case '.yaml':
case '.yml':
switch (extOutput) {
case '.json':
fs.writeFileSync(output, transcode.stringYAML2JSON(doc, compact), null)
break
default:
fs.writeFileSync(output, transcode.stringYAML2YAML(doc, compact), null)
break
}
break
case '.json':
switch (extOutput) {
case '.yaml':
case '.yml':
fs.writeFileSync(output, transcode.stringJSON2YAML(doc, compact), null)
break
default:
fs.writeFileSync(output, transcode.stringJSON2JSON(doc, compact), null)
break
}
break
}
}
|
javascript
|
{
"resource": ""
}
|
q11590
|
MssqlCrLayer
|
train
|
function MssqlCrLayer(config) {
if (!(this instanceof MssqlCrLayer)) {
return new MssqlCrLayer(config)
}
const mssqlConfig = toMssqlConfig(config)
connectionParams.set(this, mssqlConfig)
this.user = mssqlConfig.user
this.database = mssqlConfig.database
this.host = mssqlConfig.server
this.port = mssqlConfig.port
this.ISOLATION_LEVEL = (config && config.ISOLATION_LEVEL) || 'READ_COMMITTED'
}
|
javascript
|
{
"resource": ""
}
|
q11591
|
Graph
|
train
|
function Graph(directed) {
this.directed = (directed === undefined ? true : !!directed);
this.adjList = Object.create(null);
this.vertices = new HashSet();
}
|
javascript
|
{
"resource": ""
}
|
q11592
|
pick
|
train
|
function pick(propName, propValue) {
var possibleClassIds = Object.keys(storage[propName] || {}).filter(function (classId) {
return (0, _lodash2.default)(storage[propName][classId], propValue);
});
return possibleClassIds.length > 0 ? parseInt(possibleClassIds[0], 10) : null;
}
|
javascript
|
{
"resource": ""
}
|
q11593
|
put
|
train
|
function put(propName, propValue, classId) {
if (pick(propName, propValue)) return false;
if (!classId) {
nextClassId++;
classId = nextClassId;
}
nextClassId = nextClassId < classId ? classId : nextClassId;
storage[propName] = storage[propName] || {};
storage[propName][classId] = propValue;
return true;
}
|
javascript
|
{
"resource": ""
}
|
q11594
|
removeAfterKeyword
|
train
|
function removeAfterKeyword () {
var hasKeyword = false;
return function (family) {
if (~keywords.indexOf(family)) {
hasKeyword = true;
return true;
}
return !hasKeyword;
};
}
|
javascript
|
{
"resource": ""
}
|
q11595
|
urlStyleUriRegex
|
train
|
function urlStyleUriRegex() {
const protocol = '(?:[A-Za-z]{3,9}://)';
const auth = '(?:\\S+(?::\\S*)?@)?';
const ipv4 = '(?:\\[?([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\]?';
const host = '(?:(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)';
const domain = '(?:\\.(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)*';
const tld = '(?:\\.(?:[a-zA-Z]{2,}))\\.?';
const port = '(?::\\d{2,5})?';
const path = '(?:[/?#][\\x21-\\x7F]*)?'; // ascii no whitespaces
const regex = `(?:${protocol}|www\\.)${auth}(?:localhost|${ipv4}|${host}${domain}${tld})${port}${path}`;
return new RegExp(`^${regex}$`, 'i');
}
|
javascript
|
{
"resource": ""
}
|
q11596
|
train
|
function(destPath) {
var exists, stats;
var dirpath = path.dirname(destPath);
try{
stats = fs.lstatSync(dirpath);
exists = stats.isDirectory();
} catch(e) {
this.createDestDir = dirpath;
}
return !!exists;
}
|
javascript
|
{
"resource": ""
}
|
|
q11597
|
train
|
function(destPath) {
this.checkDestDir(destPath);
var exists = existsSync(destPath);
// we warn if
// if (exists) {
// this.ui.writeLine('The destination path: ' + destPath + ' already exists. Cannot overrwrite.', 'WARNING');
// }
return {
destExists: exists,
destDir: this.createDestDir
};
}
|
javascript
|
{
"resource": ""
}
|
|
q11598
|
hoist
|
train
|
function hoist() {
var scope = arguments.length <= 0 || arguments[0] === undefined ? this.scope : arguments[0];
var hoister = new _libHoister2["default"](this, scope);
return hoister.run();
}
|
javascript
|
{
"resource": ""
}
|
q11599
|
osmDateParser
|
train
|
function osmDateParser (value, options) {
var m, v, g
m = value.match(/^(.*)\.\.(.*)$/)
if (m) {
let s = osmDateParser(m[1])
let e = osmDateParser(m[2])
if (s === null || e === null) {
return null
}
if (s[0] > e[1]) {
return null
}
return [ s[0], e[1] ]
}
m = value.match(/^(\d*) BCE?$/i)
if (m) {
[ v, g ] = parseDate(value)
return [ v, v ]
}
m = value.match(/^before (.*)$/i)
if (m) {
[ v, g ] = parseDate(m[1])
return [ null, v - 1 ]
}
m = value.match(/^after (.*)$/i)
if (m) {
[ v, g ] = parseDate(m[1])
return [ v + g, null ]
}
m = value.match(/^early (.*)$/i)
if (m) {
[ v, g ] = parseDate(m[1])
return [ v, Math.round(v + g * 0.33) ]
}
m = value.match(/^mid (.*)$/i)
if (m) {
[ v, g ] = parseDate(m[1])
return [ Math.round(v + g * 0.33), Math.round(v + g * 0.67 - 1) ]
}
m = value.match(/^late (.*)$/i)
if (m) {
[ v, g ] = parseDate(m[1])
return [ Math.round(v + g * 0.67 - 1), v + g - 1 ]
}
m = parseDate(value)
if (m) {
[ v, g ] = m
return [ v, v + g - 1 ]
}
return null
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.