_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q62100
|
deltaRight
|
test
|
function deltaRight(left, top) {
let d = 0;
// If there is an edge, and no crossing edges, continue.
if(top[3] === 1 && left[1] !== 1 && left[3] !== 1) {
d += 1;
}
/* If an edge was previously found, there is another edge and there are no
crossing edges, continue. */
if(d === 1 && top[2] === 1 && left[0] !== 1 && left[2] !== 1) {
d += 1;
}
return d;
}
|
javascript
|
{
"resource": ""
}
|
q62101
|
bilinear
|
test
|
function bilinear(e) {
const a = lerp(e[0], e[1], 1.0 - 0.25);
const b = lerp(e[2], e[3], 1.0 - 0.25);
return lerp(a, b, 1.0 - 0.125);
}
|
javascript
|
{
"resource": ""
}
|
q62102
|
checkForm
|
test
|
function checkForm(that) {
var newValue = $(that).val()
var matches = newValue != '' ? newValue.match(timeRegEx) : ''
var error = $(that)
.closest('.time-spinner')
.find('.error_container')
var $closerTimeSpinner = $(that)
.closest('.time-spinner')
.find('.spinner-control')
if (matches) {
$(error).html('')
//$closerTimeSpinner.find('.spinner-hour input').val(timeRegEx.split(':')[0]);
//$closerTimeSpinner.find('.spinner-min input').val(timeRegEx.split(':')[1]);
return true
} else {
var errMsg = 'Formato data non valido'
$(error).html(errMsg)
//$(that).val('Formato data non valido')
return false
}
}
|
javascript
|
{
"resource": ""
}
|
q62103
|
resetToMove
|
test
|
function resetToMove(contextControl) {
var left = contextControl.find('.source .transfer-group')
var right = contextControl.find('.target .transfer-group')
var textLeft = contextControl.find('.source .transfer-header span.num')
var textRight = contextControl.find('.target .transfer-header span.num')
var header = contextControl.find('.transfer-header input')
$(left).html(elemLeft)
$(right).html(elemRight)
$(textLeft).text(elemLeftNum)
$(textRight).text(elemRightNum)
$(header).prop('disabled', false)
}
|
javascript
|
{
"resource": ""
}
|
q62104
|
checkIfActive
|
test
|
function checkIfActive(
targetControl,
targetHeaderControl,
containerTypeControl,
addButtonControl
) {
$(targetControl).each(function(el) {
if ($(this).prop('checked')) {
if (!$(targetHeaderControl).hasClass('semi-checked')) {
$(targetHeaderControl).addClass('semi-checked')
$(targetHeaderControl).prop('checked', false)
if (containerTypeControl.hasClass('source')) {
$(addButtonControl).addClass('active')
}
if (containerTypeControl.hasClass('target')) {
$(inverseButton).addClass('active')
}
}
return false
} else {
$(targetHeaderControl).removeClass('semi-checked')
if (containerTypeControl.hasClass('source')) {
$(addButtonControl).removeClass('active')
}
if (containerTypeControl.hasClass('target')) {
$(inverseButton).removeClass('active')
}
}
})
}
|
javascript
|
{
"resource": ""
}
|
q62105
|
sourceControl
|
test
|
function sourceControl(contextControl) {
var tocheck = contextControl.find('.transfer-scroll').find('input')
var checknum = tocheck.length
var targetText = contextControl
.find('.transfer-header')
.find('label span.num')
var header = contextControl.find('.transfer-header input')
$(header)
.prop('checked', false)
.removeClass('semi-checked')
if (checknum < 1) {
$(header).prop('disabled', true)
} else {
$(header).prop('disabled', false)
}
$(targetText).text(checknum)
}
|
javascript
|
{
"resource": ""
}
|
q62106
|
targetControl
|
test
|
function targetControl(targetControl) {
var tocheck = targetControl.find('input')
var checknum = tocheck.length
var targetText = tocheck
.closest('.it-transfer-wrapper')
.find('.transfer-header')
.find('label span.num')
var header = $(targetControl).find('.transfer-header input')
if (checknum < 1) {
$(header).prop('disabled', true)
} else {
$(header).prop('disabled', false)
}
$(targetText).text(checknum)
}
|
javascript
|
{
"resource": ""
}
|
q62107
|
checkToMove
|
test
|
function checkToMove(contextControl, targetControl) {
var elements = contextControl.find('.transfer-group').find('input:checked')
var sourceTag = $(elements).closest('.form-check')
$(elements).each(function() {
$(this).prop('checked', false)
$(sourceTag)
.detach()
.appendTo(targetControl)
.addClass('added')
})
}
|
javascript
|
{
"resource": ""
}
|
q62108
|
updateScrollPos
|
test
|
function updateScrollPos() {
if (!stickies.length) {
return
}
lastKnownScrollTop =
document.documentElement.scrollTop || document.body.scrollTop
// Only trigger a layout change if we’re not already waiting for one
if (!isAnimationRequested) {
isAnimationRequested = true
// Don’t update until next animation frame if we can, otherwise use a
// timeout - either will help avoid too many repaints
if (requestAnimationFrame) {
requestAnimationFrame(setPositions)
} else {
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(setPositions, 15)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62109
|
scoreText
|
test
|
function scoreText(score) {
if (score === -1) {
return options.shortPass
}
score = score < 0 ? 0 : score
if (score < 26) {
return options.shortPass
}
if (score < 51) {
return options.badPass
}
if (score < 76) {
return options.goodPass
}
return options.strongPass
}
|
javascript
|
{
"resource": ""
}
|
q62110
|
calculateScore
|
test
|
function calculateScore(password) {
var score = 0
// password < options.minimumLength
if (password.length < options.minimumLength) {
return -1
}
// password length
score += password.length * 4
score += checkRepetition(1, password).length - password.length
score += checkRepetition(2, password).length - password.length
score += checkRepetition(3, password).length - password.length
score += checkRepetition(4, password).length - password.length
// password has 3 numbers
if (password.match(/(.*[0-9].*[0-9].*[0-9])/)) {
score += 5
}
// password has at least 2 sybols
var symbols = '.*[!,@,#,$,%,^,&,*,?,_,~]'
symbols = new RegExp('(' + symbols + symbols + ')')
if (password.match(symbols)) {
score += 5
}
// password has Upper and Lower chars
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {
score += 10
}
// password has number and chars
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) {
score += 15
}
// password has number and symbol
if (
password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) &&
password.match(/([0-9])/)
) {
score += 15
}
// password has char and symbol
if (
password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) &&
password.match(/([a-zA-Z])/)
) {
score += 15
}
// password is just numbers or chars
if (password.match(/^\w+$/) || password.match(/^\d+$/)) {
score -= 10
}
if (score > 100) {
score = 100
}
if (score < 0) {
score = 0
}
return score
}
|
javascript
|
{
"resource": ""
}
|
q62111
|
checkRepetition
|
test
|
function checkRepetition(rLen, str) {
var res = '',
repeated = false
for (var i = 0; i < str.length; i++) {
repeated = true
for (var j = 0; j < rLen && j + i + rLen < str.length; j++) {
repeated = repeated && str.charAt(j + i) === str.charAt(j + i + rLen)
}
if (j < rLen) {
repeated = false
}
if (repeated) {
i += rLen - 1
repeated = false
} else {
res += str.charAt(i)
}
}
return res
}
|
javascript
|
{
"resource": ""
}
|
q62112
|
init
|
test
|
function init() {
var shown = true
var $text = options.showText
var $graybar = $('<div>').addClass(
'password-meter progress rounded-0 position-absolute'
)
$graybar.append(`<div class="row position-absolute w-100 m-0">
<div class="col-3 border-left border-right border-white"></div>
<div class="col-3 border-left border-right border-white"></div>
<div class="col-3 border-left border-right border-white"></div>
<div class="col-3 border-left border-right border-white"></div>
</div>`)
var $colorbar = $('<div>').attr({
class: 'progress-bar',
role: 'progressbar',
'aria-valuenow': '0',
'aria-valuemin': '0',
'aria-valuemax': '100',
})
var $insert = $('<div>').append($graybar.append($colorbar))
if (options.showText) {
$text = $('<small>')
.addClass('form-text text-muted')
.html(options.enterPass)
$insert.prepend($text)
}
$object.after($insert)
$object.keyup(function() {
var score = calculateScore($object.val())
$object.trigger('password.score', [score])
var perc = score < 0 ? 0 : score
$colorbar.removeClass(function(index, className) {
return (className.match(/(^|\s)bg-\S+/g) || []).join(' ')
})
$colorbar.addClass('bg-' + scoreColor(score))
$colorbar.css({
width: perc + '%',
})
$colorbar.attr('aria-valuenow', perc)
if (options.showText) {
var text = scoreText(score)
if (!$object.val().length && score <= 0) {
text = options.enterPass
}
if (
$text.html() !==
$('<div>')
.html(text)
.html()
) {
$text.html(text)
$text.removeClass(function(index, className) {
return (className.match(/(^|\s)text-\S+/g) || []).join(' ')
})
$text.addClass('text-' + scoreColor(score))
$object.trigger('password.text', [text, score])
}
}
})
return this
}
|
javascript
|
{
"resource": ""
}
|
q62113
|
LevelUpArrayAdapter
|
test
|
function LevelUpArrayAdapter(name, db, serializer) {
this.db = Sublevel(db);
this.db = this.db.sublevel(name);
this.name = name;
this.serializer = serializer || {
encode: function(val, callback) {
callback(null, val);
},
decode: function(val, callback) {
callback(null, val);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q62114
|
fixProps
|
test
|
function fixProps(tx, data) {
// ethereumjs-tx doesn't allow for a `0` value in fields, but we want it to
// in order to differentiate between a value that isn't set and a value
// that is set to 0 in a fake transaction.
// Once https://github.com/ethereumjs/ethereumjs-tx/issues/112 is figured
// out we can probably remove this fix/hack.
// We keep track of the original value and return that value when
// referenced by its property name. This lets us properly encode a `0` as
// an empty buffer while still being able to differentiate between a `0`
// and `null`/`undefined`.
tx._originals = [];
const fieldNames = ["nonce", "gasPrice", "gasLimit", "value"];
fieldNames.forEach((fieldName) => configZeroableField(tx, fieldName, 32));
// Ethereumjs-tx doesn't set the _chainId value whenever the v value is set,
// which causes transaction signing to fail on transactions that include a
// chain id in the v value (like ethers.js does).
// Whenever the v value changes we need to make sure the chainId is also set.
const vDescriptors = Object.getOwnPropertyDescriptor(tx, "v");
// eslint-disable-next-line accessor-pairs
Object.defineProperty(tx, "v", {
set: (v) => {
vDescriptors.set.call(tx, v);
// calculate chainId from signature
const sigV = ethUtil.bufferToInt(tx.v);
let chainId = Math.floor((sigV - 35) / 2);
if (chainId < 0) {
chainId = 0;
}
tx._chainId = chainId || 0;
}
});
if (tx.isFake()) {
/**
* @prop {Buffer} from (read/write) Set from address to bypass transaction
* signing on fake transactions.
*/
Object.defineProperty(tx, "from", {
enumerable: true,
configurable: true,
get: tx.getSenderAddress.bind(tx),
set: (val) => {
if (val) {
tx._from = ethUtil.toBuffer(val);
} else {
tx._from = null;
}
}
});
if (data && data.from) {
tx.from = data.from;
}
tx.hash = fakeHash;
}
}
|
javascript
|
{
"resource": ""
}
|
q62115
|
initData
|
test
|
function initData(tx, data) {
if (data) {
if (typeof data === "string") {
data = to.buffer(data);
}
if (Buffer.isBuffer(data)) {
data = rlp.decode(data);
}
const self = tx;
if (Array.isArray(data)) {
if (data.length > tx._fields.length) {
throw new Error("wrong number of fields in data");
}
// make sure all the items are buffers
data.forEach((d, i) => {
self[self._fields[i]] = ethUtil.toBuffer(d);
});
} else if ((typeof data === "undefined" ? "undefined" : typeof data) === "object") {
const keys = Object.keys(data);
tx._fields.forEach(function(field) {
if (keys.indexOf(field) !== -1) {
self[field] = data[field];
}
if (field === "gasLimit") {
if (keys.indexOf("gas") !== -1) {
self["gas"] = data["gas"];
}
} else if (field === "data") {
if (keys.indexOf("input") !== -1) {
self["input"] = data["input"];
}
}
});
// Set chainId value from the data, if it's there and the data didn't
// contain a `v` value with chainId in it already. If we do have a
// data.chainId value let's set the interval v value to it.
if (!tx._chainId && data && data.chainId != null) {
tx.raw[self._fields.indexOf("v")] = tx._chainId = data.chainId || 0;
}
} else {
throw new Error("invalid data");
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62116
|
TXRejectedError
|
test
|
function TXRejectedError(message) {
// Why not just Error.apply(this, [message])? See
// https://gist.github.com/justmoon/15511f92e5216fa2624b#anti-patterns
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
}
|
javascript
|
{
"resource": ""
}
|
q62117
|
RequestFunnel
|
test
|
function RequestFunnel() {
// We use an object here for O(1) lookups (speed).
this.methods = {
eth_call: true,
eth_getStorageAt: true,
eth_sendTransaction: true,
eth_sendRawTransaction: true,
// Ensure block filter and filter changes are process one at a time
// as well so filter requests that come in after a transaction get
// processed once that transaction has finished processing.
eth_newBlockFilter: true,
eth_getFilterChanges: true,
eth_getFilterLogs: true
};
this.queue = [];
this.isWorking = false;
}
|
javascript
|
{
"resource": ""
}
|
q62118
|
compileSass
|
test
|
function compileSass(_path, ext, data, callback) {
const compiledCss = sass.renderSync({
data: data,
outputStyle: 'expanded',
importer: function (url, prev, done) {
if (url.startsWith('~')) {
const newUrl = path.join(__dirname, 'node_modules', url.substr(1));
return { file: newUrl };
} else {
return { file: url };
}
}
});
callback(null, compiledCss.css);
}
|
javascript
|
{
"resource": ""
}
|
q62119
|
requireBrocfile
|
test
|
function requireBrocfile(brocfilePath) {
let brocfile;
if (brocfilePath.match(/\.ts$/)) {
try {
require.resolve('ts-node');
} catch (e) {
throw new Error(`Cannot find module 'ts-node', please install`);
}
try {
require.resolve('typescript');
} catch (e) {
throw new Error(`Cannot find module 'typescript', please install`);
}
// Register ts-node typescript compiler
require('ts-node').register(); // eslint-disable-line node/no-unpublished-require
// Load brocfile via ts-node
brocfile = require(brocfilePath);
} else {
// Load brocfile via esm shim
brocfile = esmRequire(brocfilePath);
}
// ESM `export default X` is represented as module.exports = { default: X }
if (brocfile !== null && typeof brocfile === 'object' && brocfile.hasOwnProperty('default')) {
brocfile = brocfile.default;
}
return brocfile;
}
|
javascript
|
{
"resource": ""
}
|
q62120
|
runmath
|
test
|
function runmath(s) {
var ans;
try {// We want to catch parse errors and die appropriately
// Make a parser and feed the input
ans = new nearley.Parser(grammar.ParserRules, grammar.ParserStart)
.feed(s);
// Check if there are any results
if (ans.results.length) {
return ans.results[0].toString();
} else {
// This means the input is incomplete.
var out = "Error: incomplete input, parse failed. :(";
return out;
}
} catch(e) {
// Panic in style, by graphically pointing out the error location.
var out = new Array(PROMPT.length + e.offset + 1).join("-") + "^ Error.";
// --------
// ^ This comes from nearley!
return out;
}
}
|
javascript
|
{
"resource": ""
}
|
q62121
|
test
|
function(arr, isSigned) {
if (this.type !== Pbf.Bytes) return arr.push(this.readVarint(isSigned));
var end = readPackedEnd(this);
arr = arr || [];
while (this.pos < end) arr.push(this.readVarint(isSigned));
return arr;
}
|
javascript
|
{
"resource": ""
}
|
|
q62122
|
handleUnionSelections
|
test
|
function handleUnionSelections(
sqlASTNode,
children,
selections,
gqlType,
namespace,
depth,
options,
context,
internalOptions = {}
) {
for (let selection of selections) {
// we need to figure out what kind of selection this is
switch (selection.kind) {
case 'Field':
// has this field been requested once already? GraphQL does not protect against duplicates so we have to check for it
const existingNode = children.find(child => child.fieldName === selection.name.value && child.type === 'table')
let newNode = new SQLASTNode(sqlASTNode)
if (existingNode) {
newNode = existingNode
} else {
children.push(newNode)
}
if (internalOptions.defferedFrom) {
newNode.defferedFrom = internalOptions.defferedFrom
}
populateASTNode.call(this, selection, gqlType, newNode, namespace, depth + 1, options, context)
break
// if its an inline fragment, it has some fields and we gotta recurse thru all them
case 'InlineFragment':
{
const selectionNameOfType = selection.typeCondition.name.value
// normally, we would scan for the extra join-monster data on the current gqlType.
// but the gqlType is the Union. The data isn't there, its on each of the types that make up the union
// lets find that type and handle the selections based on THAT type instead
const deferredType = this.schema._typeMap[selectionNameOfType]
const deferToObjectType = deferredType.constructor.name === 'GraphQLObjectType'
const handler = deferToObjectType ? handleSelections : handleUnionSelections
if (deferToObjectType) {
const typedChildren = sqlASTNode.typedChildren
children = typedChildren[deferredType.name] = typedChildren[deferredType.name] || []
internalOptions.defferedFrom = gqlType
}
handler.call(
this, sqlASTNode, children,
selection.selectionSet.selections, deferredType, namespace,
depth, options, context,
internalOptions
)
}
break
// if its a named fragment, we need to grab the fragment definition by its name and recurse over those fields
case 'FragmentSpread':
{
const fragmentName = selection.name.value
const fragment = this.fragments[fragmentName]
const fragmentNameOfType = fragment.typeCondition.name.value
const deferredType = this.schema._typeMap[fragmentNameOfType]
const deferToObjectType = deferredType.constructor.name === 'GraphQLObjectType'
const handler = deferToObjectType ? handleSelections : handleUnionSelections
if (deferToObjectType) {
const typedChildren = sqlASTNode.typedChildren
children = typedChildren[deferredType.name] = typedChildren[deferredType.name] || []
internalOptions.defferedFrom = gqlType
}
handler.call(
this, sqlASTNode, children,
fragment.selectionSet.selections, deferredType, namespace,
depth, options, context,
internalOptions
)
}
break
/* istanbul ignore next */
default:
throw new Error('Unknown selection kind: ' + selection.kind)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62123
|
handleSelections
|
test
|
function handleSelections(
sqlASTNode,
children,
selections,
gqlType,
namespace,
depth,
options,
context,
internalOptions = {},
) {
for (let selection of selections) {
// we need to figure out what kind of selection this is
switch (selection.kind) {
// if its another field, recurse through that
case 'Field':
// has this field been requested once already? GraphQL does not protect against duplicates so we have to check for it
const existingNode = children.find(child => child.fieldName === selection.name.value && child.type === 'table')
let newNode = new SQLASTNode(sqlASTNode)
if (existingNode) {
newNode = existingNode
} else {
children.push(newNode)
}
if (internalOptions.defferedFrom) {
newNode.defferedFrom = internalOptions.defferedFrom
}
populateASTNode.call(this, selection, gqlType, newNode, namespace, depth + 1, options, context)
break
// if its an inline fragment, it has some fields and we gotta recurse thru all them
case 'InlineFragment':
{
// check to make sure the type of this fragment (or one of the interfaces it implements) matches the type being queried
const selectionNameOfType = selection.typeCondition.name.value
const sameType = selectionNameOfType === gqlType.name
const interfaceType = (gqlType._interfaces || []).map(iface => iface.name).includes(selectionNameOfType)
if (sameType || interfaceType) {
handleSelections.call(
this, sqlASTNode, children,
selection.selectionSet.selections, gqlType, namespace,
depth, options, context,
internalOptions
)
}
}
break
// if its a named fragment, we need to grab the fragment definition by its name and recurse over those fields
case 'FragmentSpread':
{
const fragmentName = selection.name.value
const fragment = this.fragments[fragmentName]
// make sure fragment type (or one of the interfaces it implements) matches the type being queried
const fragmentNameOfType = fragment.typeCondition.name.value
const sameType = fragmentNameOfType === gqlType.name
const interfaceType = gqlType._interfaces.map(iface => iface.name).indexOf(fragmentNameOfType) >= 0
if (sameType || interfaceType) {
handleSelections.call(
this, sqlASTNode, children,
fragment.selectionSet.selections, gqlType, namespace,
depth, options, context,
internalOptions
)
}
}
break
/* istanbul ignore next */
default:
throw new Error('Unknown selection kind: ' + selection.kind)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62124
|
columnToASTChild
|
test
|
function columnToASTChild(columnName, namespace) {
return {
type: 'column',
name: columnName,
fieldName: columnName,
as: namespace.generate('column', columnName)
}
}
|
javascript
|
{
"resource": ""
}
|
q62125
|
keyToASTChild
|
test
|
function keyToASTChild(key, namespace) {
if (typeof key === 'string') {
return columnToASTChild(key, namespace)
}
if (Array.isArray(key)) {
const clumsyName = toClumsyName(key)
return {
type: 'composite',
name: key,
fieldName: clumsyName,
as: namespace.generate('column', clumsyName)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62126
|
stripRelayConnection
|
test
|
function stripRelayConnection(gqlType, queryASTNode, fragments) {
// get the GraphQL Type inside the list of edges inside the Node from the schema definition
const edgeType = stripNonNullType(gqlType._fields.edges.type)
const strippedType = stripNonNullType(stripNonNullType(edgeType.ofType)._fields.node.type)
// let's remember those arguments on the connection
const args = queryASTNode.arguments
// and then find the fields being selected on the underlying type, also buried within edges and Node
const edges = spreadFragments(queryASTNode.selectionSet.selections, fragments, gqlType.name)
.find(selection => selection.name.value === 'edges')
if (edges) {
queryASTNode = spreadFragments(edges.selectionSet.selections, fragments, gqlType.name)
.find(selection => selection.name.value === 'node') || {}
} else {
queryASTNode = {}
}
// place the arguments on this inner field, so our SQL AST picks it up later
queryASTNode.arguments = args
return { gqlType: strippedType, queryASTNode }
}
|
javascript
|
{
"resource": ""
}
|
q62127
|
spreadFragments
|
test
|
function spreadFragments(selections, fragments, typeName) {
return flatMap(selections, selection => {
switch (selection.kind) {
case 'FragmentSpread':
const fragmentName = selection.name.value
const fragment = fragments[fragmentName]
return spreadFragments(fragment.selectionSet.selections, fragments, typeName)
case 'InlineFragment':
if (selection.typeCondition.name.value === typeName) {
return spreadFragments(selection.selectionSet.selections, fragments, typeName)
}
return []
default:
return selection
}
})
}
|
javascript
|
{
"resource": ""
}
|
q62128
|
getNode
|
test
|
async function getNode(typeName, resolveInfo, context, condition, dbCall, options = {}) {
// get the GraphQL type from the schema using the name
const type = resolveInfo.schema._typeMap[typeName]
assert(type, `Type "${typeName}" not found in your schema.`)
assert(type._typeConfig.sqlTable, `joinMonster can't fetch a ${typeName} as a Node unless it has "sqlTable" tagged.`)
// we need to determine what the WHERE function should be
let where = buildWhereFunction(type, condition, options)
// our getGraphQLType expects every requested field to be in the schema definition. "node" isn't a parent of whatever type we're getting, so we'll just wrap that type in an object that LOOKS that same as a hypothetical Node type
const fakeParentNode = {
_fields: {
node: {
type,
name: type.name.toLowerCase(),
where
}
}
}
const namespace = new AliasNamespace(options.minify)
const sqlAST = {}
const fieldNodes = resolveInfo.fieldNodes || resolveInfo.fieldASTs
// uses the same underlying function as the main `joinMonster`
queryAST.populateASTNode.call(resolveInfo, fieldNodes[0], fakeParentNode, sqlAST, namespace, 0, options, context)
queryAST.pruneDuplicateSqlDeps(sqlAST, namespace)
const { sql, shapeDefinition } = await compileSqlAST(sqlAST, context, options)
const data = arrToConnection(await handleUserDbCall(dbCall, sql, sqlAST, shapeDefinition), sqlAST)
await nextBatch(sqlAST, data, dbCall, context, options)
if (!data) return data
data.__type__ = type
return data
}
|
javascript
|
{
"resource": ""
}
|
q62129
|
arrToConnection
|
test
|
function arrToConnection(data, sqlAST) {
// use "post-order" tree traversal
for (let astChild of sqlAST.children || []) {
if (Array.isArray(data)) {
for (let dataItem of data) {
recurseOnObjInData(dataItem, astChild)
}
} else if (data) {
recurseOnObjInData(data, astChild)
}
}
const pageInfo = {
hasNextPage: false,
hasPreviousPage: false
}
if (!data) {
if (sqlAST.paginate) {
return {
pageInfo,
edges: []
}
}
return null
}
// is cases where pagination was done, take the data and convert to the connection object
// if any two fields happen to become a reference to the same object (when their `uniqueKey`s are the same),
// we must prevent the recursive processing from visting the same object twice, because mutating the object the first
// time changes it everywhere. we'll set the `_paginated` property to true to prevent this
if (sqlAST.paginate && !data._paginated) {
if (sqlAST.sortKey || idx(sqlAST, _ => _.junction.sortKey)) {
if (idx(sqlAST, _ => _.args.first)) {
// we fetched an extra one in order to determine if there is a next page, if there is one, pop off that extra
if (data.length > sqlAST.args.first) {
pageInfo.hasNextPage = true
data.pop()
}
} else if (sqlAST.args && sqlAST.args.last) {
// if backward paging, do the same, but also reverse it
if (data.length > sqlAST.args.last) {
pageInfo.hasPreviousPage = true
data.pop()
}
data.reverse()
}
// convert nodes to edges and compute the cursor for each
// TODO: only compute all the cursor if asked for them
const sortKey = sqlAST.sortKey || sqlAST.junction.sortKey
const edges = data.map(obj => {
const cursor = {}
const key = sortKey.key
for (let column of wrap(key)) {
cursor[column] = obj[column]
}
return { cursor: objToCursor(cursor), node: obj }
})
if (data.length) {
pageInfo.startCursor = edges[0].cursor
pageInfo.endCursor = last(edges).cursor
}
return { edges, pageInfo, _paginated: true }
}
if (sqlAST.orderBy || (sqlAST.junction && sqlAST.junction.orderBy)) {
let offset = 0
if (idx(sqlAST, _ => _.args.after)) {
offset = cursorToOffset(sqlAST.args.after) + 1
}
// $total was a special column for determining the total number of items
const arrayLength = data[0] && parseInt(data[0].$total, 10)
const connection = connectionFromArraySlice(data, sqlAST.args || {}, { sliceStart: offset, arrayLength })
connection.total = arrayLength || 0
connection._paginated = true
return connection
}
}
return data
}
|
javascript
|
{
"resource": ""
}
|
q62130
|
validate
|
test
|
function validate(rows) {
// its supposed to be an array of objects
if (Array.isArray(rows)) return rows
// a check for the most common error. a lot of ORMs return an object with the desired data on the `rows` property
if (rows && rows.rows) return rows.rows
throw new Error(
`"dbCall" function must return/resolve an array of objects where each object is a row from the result set.
Instead got ${util.inspect(rows, { depth: 3 })}`
)
}
|
javascript
|
{
"resource": ""
}
|
q62131
|
sortKeyToWhereCondition
|
test
|
function sortKeyToWhereCondition(keyObj, descending, sortTable, dialect) {
const { name, quote: q } = dialect
const sortColumns = []
const sortValues = []
for (let key in keyObj) {
sortColumns.push(`${q(sortTable)}.${q(key)}`)
sortValues.push(maybeQuote(keyObj[key], name))
}
const operator = descending ? '<' : '>'
return name === 'oracle'
? recursiveWhereJoin(sortColumns, sortValues, operator)
: `(${sortColumns.join(', ')}) ${operator} (${sortValues.join(', ')})`
}
|
javascript
|
{
"resource": ""
}
|
q62132
|
clone
|
test
|
function clone(frm, to) {
if (frm === null || typeof frm !== "object") {
return frm;
}
if (frm.constructor !== Object && frm.constructor !== Array) {
return frm;
}
if (frm.constructor === Date || frm.constructor === RegExp || frm.constructor === Function ||
frm.constructor === String || frm.constructor === Number || frm.constructor === Boolean) {
return new frm.constructor(frm);
}
to = to || new frm.constructor();
for (var name in frm) {
to[name] = typeof to[name] === "undefined" ? clone(frm[name], null) : to[name];
}
return to;
}
|
javascript
|
{
"resource": ""
}
|
q62133
|
buildString
|
test
|
function buildString (length, str) {
return Array.apply(null, new Array(length)).map(String.prototype.valueOf, str).join('')
}
|
javascript
|
{
"resource": ""
}
|
q62134
|
concatArray
|
test
|
function concatArray (arr, pretty, indentation, indentLevel) {
var currentIndent = buildString(indentLevel, indentation)
var closingBraceIndent = buildString(indentLevel - 1, indentation)
var join = pretty ? ',\n' + currentIndent : ', '
if (pretty) {
return '[\n' + currentIndent + arr.join(join) + '\n' + closingBraceIndent + ']'
} else {
return '[' + arr.join(join) + ']'
}
}
|
javascript
|
{
"resource": ""
}
|
q62135
|
test
|
function (value, opts, indentLevel) {
indentLevel = indentLevel === undefined ? 1 : indentLevel + 1
switch (Object.prototype.toString.call(value)) {
case '[object Number]':
return value
case '[object Array]':
// Don't prettify arrays nto not take too much space
var pretty = false
var valuesRepresentation = value.map(function (v) {
// Switch to prettify if the value is a dictionary with multiple keys
if (Object.prototype.toString.call(v) === '[object Object]') {
pretty = Object.keys(v).length > 1
}
return this.literalRepresentation(v, opts, indentLevel)
}.bind(this))
return concatArray(valuesRepresentation, pretty, opts.indent, indentLevel)
case '[object Object]':
var keyValuePairs = []
for (var k in value) {
keyValuePairs.push(util.format('"%s": %s', k, this.literalRepresentation(value[k], opts, indentLevel)))
}
return concatArray(keyValuePairs, opts.pretty && keyValuePairs.length > 1, opts.indent, indentLevel)
case '[object Boolean]':
return value.toString()
default:
if (value === null || value === undefined) {
return ''
}
return '"' + value.toString().replace(/"/g, '\\"') + '"'
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62136
|
test
|
function(text, placeholders) {
if (text[text.length - 1] == "]" && text.lastIndexOf(" [") != -1) {
// Remove translation comments
text = text.substr(0, text.lastIndexOf(" ["));
}
var replaceAll = function(str, substr, replacement) {
return str.replace(
new RegExp(
substr.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), "g"),
replacement);
}
var localeReplace = function(text, placeholders) {
for (var key in placeholders) {
text = replaceAll(text, "%(" + key + ")s", placeholders[key]);
}
return text;
};
var reactLocaleReplace = function(text, placeholders) {
var start;
var expanded = [text];
for (var key in placeholders) {
start = expanded;
expanded = [];
for (var i = 0; i < start.length; i++) {
if (typeof start[i] == "string") {
var keyStr = "%(" + key + ")s";
var parts = start[i].split(keyStr);
var replaced = [];
for (var j = 0; j < parts.length - 1; j++) {
replaced.push(parts[j]);
replaced.push(placeholders[key]);
}
replaced.push(parts[parts.length - 1]);
replaced = replaced.filter(function (str) {
return str != "";
});
expanded.push.apply(expanded, replaced)
} else {
expanded.push(start[i]);
}
}
}
return expanded;
}
if (placeholders) {
var hasReactElements = false;
for (var key in placeholders) {
var val = placeholders[key];
if (typeof val !== "string" && React.isValidElement(val)) {
hasReactElements = true;
break;
}
}
return (hasReactElements ?
reactLocaleReplace(text, placeholders) :
localeReplace(text, placeholders));
}
return text;
}
|
javascript
|
{
"resource": ""
}
|
|
q62137
|
createNode
|
test
|
function createNode (media) {
var node = new Audio();
node.onplay = function () {
Media.onStatus(media.id, Media.MEDIA_STATE, Media.MEDIA_STARTING);
};
node.onplaying = function () {
Media.onStatus(media.id, Media.MEDIA_STATE, Media.MEDIA_RUNNING);
};
node.ondurationchange = function (e) {
Media.onStatus(media.id, Media.MEDIA_DURATION, e.target.duration || -1);
};
node.onerror = function (e) {
// Due to media.spec.15 It should return MediaError for bad filename
var err = e.target.error.code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED ?
{ code: MediaError.MEDIA_ERR_ABORTED } :
e.target.error;
Media.onStatus(media.id, Media.MEDIA_ERROR, err);
};
node.onended = function () {
Media.onStatus(media.id, Media.MEDIA_STATE, Media.MEDIA_STOPPED);
};
if (media.src) {
node.src = media.src;
}
return node;
}
|
javascript
|
{
"resource": ""
}
|
q62138
|
test
|
function(win, lose, args) {
var id = args[0];
var srcUri = processUri(args[1]);
var createAudioNode = !!args[2];
var thisM = Media.get(id);
Media.prototype.node = null;
var prefix = args[1].split(':').shift();
var extension = srcUri.extension;
if (thisM.node === null) {
if (SUPPORTED_EXTENSIONS.indexOf(extension) === -1 && SUPPORTED_PREFIXES.indexOf(prefix) === -1) {
if (lose) {
lose({ code: MediaError.MEDIA_ERR_ABORTED });
}
return false; // unable to create
}
// Don't create Audio object in case of record mode
if (createAudioNode === true) {
thisM.node = new Audio();
thisM.node.msAudioCategory = "BackgroundCapableMedia";
thisM.node.src = srcUri.absoluteCanonicalUri;
thisM.node.onloadstart = function () {
Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STARTING);
};
thisM.node.ontimeupdate = function (e) {
Media.onStatus(id, Media.MEDIA_POSITION, e.target.currentTime);
};
thisM.node.onplaying = function () {
Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_RUNNING);
};
thisM.node.ondurationchange = function (e) {
Media.onStatus(id, Media.MEDIA_DURATION, e.target.duration || -1);
};
thisM.node.onerror = function (e) {
// Due to media.spec.15 It should return MediaError for bad filename
var err = e.target.error.code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED ?
{ code: MediaError.MEDIA_ERR_ABORTED } :
e.target.error;
Media.onStatus(id, Media.MEDIA_ERROR, err);
};
thisM.node.onended = function () {
Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STOPPED);
};
}
}
return true; // successfully created
}
|
javascript
|
{
"resource": ""
}
|
|
q62139
|
test
|
function(win, lose, args) {
var id = args[0];
//var src = args[1];
//var options = args[2];
var thisM = Media.get(id);
// if Media was released, then node will be null and we need to create it again
if (!thisM.node) {
args[2] = true; // Setting createAudioNode to true
if (!module.exports.create(win, lose, args)) {
// there is no reason to continue if we can't create media
// corresponding callback has been invoked in create so we don't need to call it here
return;
}
}
try {
thisM.node.play();
} catch (err) {
if (lose) {
lose({code:MediaError.MEDIA_ERR_ABORTED});
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62140
|
test
|
function(win, lose, args) {
var id = args[0];
var milliseconds = args[1];
var thisM = Media.get(id);
try {
thisM.node.currentTime = milliseconds / 1000;
win(thisM.node.currentTime);
} catch (err) {
lose("Failed to seek: "+err);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62141
|
test
|
function(win, lose, args) {
var id = args[0];
var thisM = Media.get(id);
try {
thisM.node.pause();
Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_PAUSED);
} catch (err) {
lose("Failed to pause: "+err);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62142
|
test
|
function(win, lose, args) {
var id = args[0];
try {
var p = (Media.get(id)).node.currentTime;
win(p);
} catch (err) {
lose(err);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62143
|
test
|
function(win, lose, args) {
var id = args[0];
var srcUri = processUri(args[1]);
var dest = parseUriToPathAndFilename(srcUri);
var destFileName = dest.fileName;
var success = function () {
Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_RUNNING);
};
var error = function (reason) {
Media.onStatus(id, Media.MEDIA_ERROR, reason);
};
// Initialize device
Media.prototype.mediaCaptureMgr = null;
var thisM = (Media.get(id));
var captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
captureInitSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.audio;
thisM.mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
thisM.mediaCaptureMgr.addEventListener("failed", error);
thisM.mediaCaptureMgr.initializeAsync(captureInitSettings).done(function (result) {
thisM.mediaCaptureMgr.addEventListener("recordlimitationexceeded", error);
thisM.mediaCaptureMgr.addEventListener("failed", error);
// Start recording
Windows.Storage.ApplicationData.current.temporaryFolder.createFileAsync(destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(function (newFile) {
recordedFile = newFile;
var encodingProfile = null;
switch (newFile.fileType) {
case '.m4a':
encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createM4a(Windows.Media.MediaProperties.AudioEncodingQuality.auto);
break;
case '.mp3':
encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createMp3(Windows.Media.MediaProperties.AudioEncodingQuality.auto);
break;
case '.wma':
encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createWma(Windows.Media.MediaProperties.AudioEncodingQuality.auto);
break;
default:
error("Invalid file type for record");
break;
}
thisM.mediaCaptureMgr.startRecordToStorageFileAsync(encodingProfile, newFile).done(success, error);
}, error);
}, error);
}
|
javascript
|
{
"resource": ""
}
|
|
q62144
|
test
|
function(win, lose, args) {
var id = args[0];
var thisM = Media.get(id);
var srcUri = processUri(thisM.src);
var dest = parseUriToPathAndFilename(srcUri);
var destPath = dest.path;
var destFileName = dest.fileName;
var fsType = dest.fsType;
var success = function () {
Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STOPPED);
};
var error = function (reason) {
Media.onStatus(id, Media.MEDIA_ERROR, reason);
};
thisM.mediaCaptureMgr.stopRecordAsync().done(function () {
if (fsType === fsTypes.TEMPORARY) {
if (!destPath) {
// if path is not defined, we leave recorded file in temporary folder (similar to iOS)
success();
} else {
Windows.Storage.ApplicationData.current.temporaryFolder.getFolderAsync(destPath).done(function (destFolder) {
recordedFile.copyAsync(destFolder, destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(success, error);
}, error);
}
} else {
// Copying file to persistent storage
if (!destPath) {
recordedFile.copyAsync(Windows.Storage.ApplicationData.current.localFolder, destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(success, error);
} else {
Windows.Storage.ApplicationData.current.localFolder.getFolderAsync(destPath).done(function (destFolder) {
recordedFile.copyAsync(destFolder, destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(success, error);
}, error);
}
}
}, error);
}
|
javascript
|
{
"resource": ""
}
|
|
q62145
|
test
|
function(win, lose, args) {
var id = args[0];
var thisM = Media.get(id);
try {
if (thisM.node) {
thisM.node.onloadedmetadata = null;
// Unsubscribing as the media object is being released
thisM.node.onerror = null;
// Needed to avoid "0x80070005 - JavaScript runtime error: Access is denied." on copyAsync
thisM.node.src = null;
delete thisM.node;
}
} catch (err) {
lose("Failed to release: "+err);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q62146
|
fullPathToAppData
|
test
|
function fullPathToAppData(uri) {
if (uri.schemeName === 'file') {
if (uri.rawUri.indexOf(Windows.Storage.ApplicationData.current.localFolder.path) !== -1) {
// Also remove path' beginning slash to avoid losing folder name part
uri = new Windows.Foundation.Uri(localFolderAppDataBasePath, uri.rawUri.replace(localFolderFullPath, '').replace(/^[\\\/]{1,2}/, ''));
} else if (uri.rawUri.indexOf(Windows.Storage.ApplicationData.current.temporaryFolder.path) !== -1) {
uri = new Windows.Foundation.Uri(tempFolderAppDataBasePath, uri.rawUri.replace(tempFolderFullPath, '').replace(/^[\\\/]{1,2}/, ''));
} else {
throw new Error('Not supported file uri: ' + uri.rawUri);
}
}
return uri;
}
|
javascript
|
{
"resource": ""
}
|
q62147
|
cdvfileToAppData
|
test
|
function cdvfileToAppData(uri) {
var cdvFsRoot;
if (uri.schemeName === 'cdvfile') {
cdvFsRoot = uri.path.split('/')[1];
if (cdvFsRoot === 'temporary') {
return new Windows.Foundation.Uri(tempFolderAppDataBasePath, uri.path.split('/').slice(2).join('/'));
} else if (cdvFsRoot === 'persistent') {
return new Windows.Foundation.Uri(localFolderAppDataBasePath, uri.path.split('/').slice(2).join('/'));
} else {
throw new Error(cdvFsRoot + ' cdvfile root is not supported on Windows');
}
}
return uri;
}
|
javascript
|
{
"resource": ""
}
|
q62148
|
processUri
|
test
|
function processUri(src) {
// Collapse double slashes (File plugin issue): ms-appdata:///temp//recs/memos/media.m4a => ms-appdata:///temp/recs/memos/media.m4a
src = src.replace(/([^\/:])(\/\/)([^\/])/g, '$1/$3');
// Remove beginning slashes
src = src.replace(/^[\\\/]{1,2}/, '');
var uri = setTemporaryFsByDefault(src);
uri = fullPathToAppData(uri);
uri = cdvfileToAppData(uri);
return uri;
}
|
javascript
|
{
"resource": ""
}
|
q62149
|
parseUriToPathAndFilename
|
test
|
function parseUriToPathAndFilename(uri) {
// Removing scheme and location, using backslashes: ms-appdata:///local/path/to/file.m4a -> path\\to\\file.m4a
var normalizedSrc = uri.path.split('/').slice(2).join('\\');
var path = normalizedSrc.substr(0, normalizedSrc.lastIndexOf('\\'));
var fileName = normalizedSrc.replace(path + '\\', '');
var fsType;
if (uri.path.split('/')[1] === 'local') {
fsType = fsTypes.PERSISTENT;
} else if (uri.path.split('/')[1] === 'temp') {
fsType = fsTypes.TEMPORARY;
}
return {
path: path,
fileName: fileName,
fsType: fsType
};
}
|
javascript
|
{
"resource": ""
}
|
q62150
|
Context
|
test
|
function Context (hook, opts) {
this.hook = hook;
// create new object, to avoid affecting input opts in other places
// For example context.opts.plugin = Object is done, then it affects by reference
this.opts = Object.assign({}, opts);
this.cmdLine = process.argv.join(' ');
// Lazy-load cordova to avoid cyclical dependency
Object.defineProperty(this, 'cordova', {
get () { return this.requireCordovaModule('cordova-lib').cordova; }
});
}
|
javascript
|
{
"resource": ""
}
|
q62151
|
getUniqueCapabilities
|
test
|
function getUniqueCapabilities(capabilities) {
return capabilities.reduce(function(uniqueCaps, currCap) {
var isRepeated = uniqueCaps.some(function(cap) {
return getCapabilityName(cap) === getCapabilityName(currCap);
});
return isRepeated ? uniqueCaps : uniqueCaps.concat([currCap]);
}, []);
}
|
javascript
|
{
"resource": ""
}
|
q62152
|
compareCapabilities
|
test
|
function compareCapabilities(firstCap, secondCap) {
var firstCapName = getCapabilityName(firstCap);
var secondCapName = getCapabilityName(secondCap);
if (firstCapName < secondCapName) {
return -1;
}
if (firstCapName > secondCapName) {
return 1;
}
return 0;
}
|
javascript
|
{
"resource": ""
}
|
q62153
|
isCordova
|
test
|
function isCordova (dir) {
if (!dir) {
// Prefer PWD over cwd so that symlinked dirs within your PWD work correctly (CB-5687).
var pwd = process.env.PWD;
var cwd = process.cwd();
if (pwd && pwd !== cwd && pwd !== 'undefined') {
return this.isCordova(pwd) || this.isCordova(cwd);
}
return this.isCordova(cwd);
}
var bestReturnValueSoFar = false;
for (var i = 0; i < 1000; ++i) {
var result = isRootDir(dir);
if (result === 2) {
return dir;
}
if (result === 1) {
bestReturnValueSoFar = dir;
}
var parentDir = path.normalize(path.join(dir, '..'));
// Detect fs root.
if (parentDir === dir) {
return bestReturnValueSoFar;
}
dir = parentDir;
}
console.error('Hit an unhandled case in util.isCordova');
return false;
}
|
javascript
|
{
"resource": ""
}
|
q62154
|
cdProjectRoot
|
test
|
function cdProjectRoot () {
const projectRoot = this.getProjectRoot();
if (!origCwd) {
origCwd = process.env.PWD || process.cwd();
}
process.env.PWD = projectRoot;
process.chdir(projectRoot);
return projectRoot;
}
|
javascript
|
{
"resource": ""
}
|
q62155
|
deleteSvnFolders
|
test
|
function deleteSvnFolders (dir) {
var contents = fs.readdirSync(dir);
contents.forEach(function (entry) {
var fullpath = path.join(dir, entry);
if (isDirectory(fullpath)) {
if (entry === '.svn') {
fs.removeSync(fullpath);
} else module.exports.deleteSvnFolders(fullpath);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q62156
|
findPlugins
|
test
|
function findPlugins (pluginDir) {
var plugins = [];
if (fs.existsSync(pluginDir)) {
plugins = fs.readdirSync(pluginDir).filter(function (fileName) {
var pluginPath = path.join(pluginDir, fileName);
var isPlugin = isDirectory(pluginPath) || isSymbolicLink(pluginPath);
return fileName !== '.svn' && fileName !== 'CVS' && isPlugin;
});
}
return plugins;
}
|
javascript
|
{
"resource": ""
}
|
q62157
|
HooksRunner
|
test
|
function HooksRunner (projectRoot) {
var root = cordovaUtil.isCordova(projectRoot);
if (!root) throw new CordovaError('Not a Cordova project ("' + projectRoot + '"), can\'t use hooks.');
else this.projectRoot = root;
}
|
javascript
|
{
"resource": ""
}
|
q62158
|
extractSheBangInterpreter
|
test
|
function extractSheBangInterpreter (fullpath) {
// this is a modern cluster size. no need to read less
const chunkSize = 4096;
const fileData = readChunk.sync(fullpath, 0, chunkSize);
const fileChunk = fileData.toString();
const hookCmd = shebangCommand(fileChunk);
if (hookCmd && fileData.length === chunkSize && !fileChunk.match(/[\r\n]/)) {
events.emit('warn', 'shebang is too long for "' + fullpath + '"');
}
return hookCmd;
}
|
javascript
|
{
"resource": ""
}
|
q62159
|
isHookDisabled
|
test
|
function isHookDisabled (opts, hook) {
if (opts === undefined || opts.nohooks === undefined) {
return false;
}
var disabledHooks = opts.nohooks;
var length = disabledHooks.length;
for (var i = 0; i < length; i++) {
if (hook.match(disabledHooks[i]) !== null) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q62160
|
test
|
function() {
var modulemapper = require('cordova/modulemapper');
var channel = require('cordova/channel');
modulemapper.clobbers('cordova/exec/proxy', 'cordova.commandProxy');
channel.onNativeReady.fire();
document.addEventListener("visibilitychange", function(){
if(document.hidden) {
channel.onPause.fire();
}
else {
channel.onResume.fire();
}
});
// End of bootstrap
}
|
javascript
|
{
"resource": ""
}
|
|
q62161
|
test
|
function (hook, opts) {
// args check
if (!hook) {
throw new Error('hook type is not specified');
}
return getApplicationHookScripts(hook, opts)
.concat(getPluginsHookScripts(hook, opts));
}
|
javascript
|
{
"resource": ""
}
|
|
q62162
|
getPluginsHookScripts
|
test
|
function getPluginsHookScripts (hook, opts) {
// args check
if (!hook) {
throw new Error('hook type is not specified');
}
// In case before_plugin_install, after_plugin_install, before_plugin_uninstall hooks we receive opts.plugin and
// retrieve scripts exclusive for this plugin.
if (opts.plugin) {
events.emit('verbose', 'Finding scripts for "' + hook + '" hook from plugin ' + opts.plugin.id + ' on ' + opts.plugin.platform + ' platform only.');
// if plugin hook is not run for specific platform then use all available platforms
return getPluginScriptFiles(opts.plugin, hook, opts.plugin.platform ? [opts.plugin.platform] : opts.cordova.platforms);
}
return getAllPluginsHookScriptFiles(hook, opts);
}
|
javascript
|
{
"resource": ""
}
|
q62163
|
getApplicationHookScriptsFromDir
|
test
|
function getApplicationHookScriptsFromDir (dir) {
if (!(fs.existsSync(dir))) {
return [];
}
var compareNumbers = function (a, b) {
// TODO SG looks very complex, do we really need this?
return isNaN(parseInt(a, 10)) ? a.toLowerCase().localeCompare(b.toLowerCase ? b.toLowerCase() : b)
: parseInt(a, 10) > parseInt(b, 10) ? 1 : parseInt(a, 10) < parseInt(b, 10) ? -1 : 0;
};
var scripts = fs.readdirSync(dir).sort(compareNumbers).filter(function (s) {
return s[0] !== '.';
});
return scripts.map(function (scriptPath) {
// for old style hook files we don't use module loader for backward compatibility
return { path: scriptPath, fullPath: path.join(dir, scriptPath), useModuleLoader: false };
});
}
|
javascript
|
{
"resource": ""
}
|
q62164
|
getScriptsFromConfigXml
|
test
|
function getScriptsFromConfigXml (hook, opts) {
var configPath = cordovaUtil.projectConfig(opts.projectRoot);
var configXml = new ConfigParser(configPath);
return configXml.getHookScripts(hook, opts.cordova.platforms).map(function (scriptElement) {
return {
path: scriptElement.attrib.src,
fullPath: path.join(opts.projectRoot, scriptElement.attrib.src)
};
});
}
|
javascript
|
{
"resource": ""
}
|
q62165
|
getPluginScriptFiles
|
test
|
function getPluginScriptFiles (plugin, hook, platforms) {
var scriptElements = plugin.pluginInfo.getHookScripts(hook, platforms);
return scriptElements.map(function (scriptElement) {
return {
path: scriptElement.attrib.src,
fullPath: path.join(plugin.dir, scriptElement.attrib.src),
plugin: plugin
};
});
}
|
javascript
|
{
"resource": ""
}
|
q62166
|
getAllPluginsHookScriptFiles
|
test
|
function getAllPluginsHookScriptFiles (hook, opts) {
var scripts = [];
var currentPluginOptions;
var plugins = (new PluginInfoProvider()).getAllWithinSearchPath(path.join(opts.projectRoot, 'plugins'));
plugins.forEach(function (pluginInfo) {
currentPluginOptions = {
id: pluginInfo.id,
pluginInfo: pluginInfo,
dir: pluginInfo.dir
};
scripts = scripts.concat(getPluginScriptFiles(currentPluginOptions, hook, opts.cordova.platforms));
});
return scripts;
}
|
javascript
|
{
"resource": ""
}
|
q62167
|
ensureUniqueCapabilities
|
test
|
function ensureUniqueCapabilities(capabilities) {
var uniqueCapabilities = [];
capabilities.getchildren()
.forEach(function(el) {
var name = el.attrib.Name;
if (uniqueCapabilities.indexOf(name) !== -1) {
capabilities.remove(el);
} else {
uniqueCapabilities.push(name);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q62168
|
copyNewFile
|
test
|
function copyNewFile (plugin_dir, src, project_dir, dest, link) {
var target_path = path.resolve(project_dir, dest);
if (fs.existsSync(target_path))
throw new CordovaError('"' + target_path + '" already exists!');
copyFile(plugin_dir, src, project_dir, dest, !!link);
}
|
javascript
|
{
"resource": ""
}
|
q62169
|
PluginSpec
|
test
|
function PluginSpec (raw, scope, id, version) {
/** @member {String|null} The npm scope of the plugin spec or null if it does not have one */
this.scope = scope || null;
/** @member {String|null} The id of the plugin or the raw plugin spec if it is not an npm package */
this.id = id || raw;
/** @member {String|null} The specified version of the plugin or null if no version was specified */
this.version = version || null;
/** @member {String|null} The npm package of the plugin (with scope) or null if this is not a spec for an npm package */
this.package = (scope ? scope + id : id) || null;
}
|
javascript
|
{
"resource": ""
}
|
q62170
|
getPluginFilePath
|
test
|
function getPluginFilePath(plugin, pluginFile, targetDir) {
var src = path.resolve(plugin.dir, pluginFile);
return '$(ProjectDir)' + path.relative(targetDir, src);
}
|
javascript
|
{
"resource": ""
}
|
q62171
|
platform
|
test
|
function platform (command, targets, opts) {
// CB-10519 wrap function code into promise so throwing error
// would result in promise rejection instead of uncaught exception
return Promise.resolve().then(function () {
var msg;
var projectRoot = cordova_util.cdProjectRoot();
var hooksRunner = new HooksRunner(projectRoot);
if (arguments.length === 0) command = 'ls';
if (targets && !(targets instanceof Array)) targets = [targets];
// TODO: wouldn't update need a platform, too? what about save?
if ((command === 'add' || command === 'rm' || command === 'remove') && (!targets || (targets instanceof Array && targets.length === 0))) {
msg = 'You need to qualify `' + command + '` with one or more platforms!';
return Promise.reject(new CordovaError(msg));
}
opts = opts || {};
opts.platforms = targets;
switch (command) {
case 'add':
return module.exports.add(hooksRunner, projectRoot, targets, opts);
case 'rm':
case 'remove':
return module.exports.remove(hooksRunner, projectRoot, targets, opts);
case 'update':
case 'up':
return module.exports.update(hooksRunner, projectRoot, targets, opts);
case 'check':
return module.exports.check(hooksRunner, projectRoot);
default:
return module.exports.list(hooksRunner, projectRoot, opts);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q62172
|
getPlatforms
|
test
|
function getPlatforms (projectRoot) {
var xml = cordova_util.projectConfig(projectRoot);
var cfg = new ConfigParser(xml);
// If an engine's 'version' property is really its source, map that to the appropriate field.
var engines = cfg.getEngines().map(function (engine) {
var result = {
name: engine.name
};
if (semver.validRange(engine.spec, true)) {
result.version = engine.spec;
} else {
result.src = engine.spec;
}
return result;
});
return Promise.resolve(engines);
}
|
javascript
|
{
"resource": ""
}
|
q62173
|
getPlugins
|
test
|
function getPlugins (projectRoot) {
var xml = cordova_util.projectConfig(projectRoot);
var cfg = new ConfigParser(xml);
// Map variables object to an array
var plugins = cfg.getPlugins().map(function (plugin) {
var result = {
name: plugin.name
};
if (semver.validRange(plugin.spec, true)) {
result.version = plugin.spec;
} else {
result.src = plugin.spec;
}
var variablesObject = plugin.variables;
var variablesArray = [];
if (variablesObject) {
for (var variable in variablesObject) {
variablesArray.push({
name: variable,
value: variablesObject[variable]
});
}
}
result.variables = variablesArray;
return result;
});
return Promise.resolve(plugins);
}
|
javascript
|
{
"resource": ""
}
|
q62174
|
test
|
function (plugin_id, plugins_dir, platformJson, pluginInfoProvider) {
var depsInfo;
if (typeof plugins_dir === 'object') { depsInfo = plugins_dir; } else { depsInfo = pkg.generateDependencyInfo(platformJson, plugins_dir, pluginInfoProvider); }
var graph = depsInfo.graph;
var dependencies = graph.getChain(plugin_id);
var tlps = depsInfo.top_level_plugins;
var diff_arr = [];
tlps.forEach(function (tlp) {
if (tlp !== plugin_id) {
diff_arr.push(graph.getChain(tlp));
}
});
// if this plugin has dependencies, do a set difference to determine which dependencies are not required by other existing plugins
diff_arr.unshift(dependencies);
var danglers = underscore.difference.apply(null, diff_arr);
// Ensure no top-level plugins are tagged as danglers.
danglers = danglers && danglers.filter(function (x) { return tlps.indexOf(x) < 0; });
return danglers;
}
|
javascript
|
{
"resource": ""
}
|
|
q62175
|
createReplacement
|
test
|
function createReplacement(manifestFile, originalChange) {
var replacement = {
target: manifestFile,
parent: originalChange.parent,
after: originalChange.after,
xmls: originalChange.xmls,
versions: originalChange.versions,
deviceTarget: originalChange.deviceTarget
};
return replacement;
}
|
javascript
|
{
"resource": ""
}
|
q62176
|
checkID
|
test
|
function checkID (expectedIdAndVersion, pinfo) {
if (!expectedIdAndVersion) return;
var parsedSpec = pluginSpec.parse(expectedIdAndVersion);
if (parsedSpec.id !== pinfo.id) {
throw new Error('Expected plugin to have ID "' + parsedSpec.id + '" but got "' + pinfo.id + '".');
}
if (parsedSpec.version && !semver.satisfies(pinfo.version, parsedSpec.version)) {
throw new Error('Expected plugin ' + pinfo.id + ' to satisfy version "' + parsedSpec.version + '" but got "' + pinfo.version + '".');
}
}
|
javascript
|
{
"resource": ""
}
|
q62177
|
getPlatformDetailsFromDir
|
test
|
function getPlatformDetailsFromDir (dir, platformIfKnown) {
var libDir = path.resolve(dir);
var platform;
var version;
// console.log("getPlatformDetailsFromDir : ", dir, platformIfKnown, libDir);
try {
var pkgPath = path.join(libDir, 'package.json');
var pkg = cordova_util.requireNoCache(pkgPath);
platform = module.exports.platformFromName(pkg.name);
version = pkg.version;
} catch (e) {
return Promise.reject(new CordovaError('The provided path does not seem to contain a valid package.json or a valid Cordova platform: ' + libDir));
}
// platform does NOT have to exist in 'platforms', but it should have a name, and a version
if (!version || !platform) {
return Promise.reject(new CordovaError('The provided path does not seem to contain a ' +
'Cordova platform: ' + libDir));
}
return Promise.resolve({
libDir: libDir,
platform: platform,
version: version
});
}
|
javascript
|
{
"resource": ""
}
|
q62178
|
platformFromName
|
test
|
function platformFromName (name) {
var platName = name;
var platMatch = /^cordova-([a-z0-9-]+)$/.exec(name);
if (platMatch && (platMatch[1] in platforms)) {
platName = platMatch[1];
events.emit('verbose', 'Removing "cordova-" prefix from ' + name);
}
return platName;
}
|
javascript
|
{
"resource": ""
}
|
q62179
|
processMessage
|
test
|
function processMessage(message) {
var firstChar = message.charAt(0);
if (firstChar == 'J') {
// This is deprecated on the .java side. It doesn't work with CSP enabled.
eval(message.slice(1));
} else if (firstChar == 'S' || firstChar == 'F') {
var success = firstChar == 'S';
var keepCallback = message.charAt(1) == '1';
var spaceIdx = message.indexOf(' ', 2);
var status = +message.slice(2, spaceIdx);
var nextSpaceIdx = message.indexOf(' ', spaceIdx + 1);
var callbackId = message.slice(spaceIdx + 1, nextSpaceIdx);
var payloadMessage = message.slice(nextSpaceIdx + 1);
var payload = [];
buildPayload(payload, payloadMessage);
cordova.callbackFromNative(callbackId, success, status, payload, keepCallback);
} else {
console.log("processMessage failed: invalid message: " + JSON.stringify(message));
}
}
|
javascript
|
{
"resource": ""
}
|
q62180
|
callEngineScripts
|
test
|
function callEngineScripts (engines, project_dir) {
return Promise.all(
engines.map(function (engine) {
// CB-5192; on Windows scriptSrc doesn't have file extension so we shouldn't check whether the script exists
var scriptPath = engine.scriptSrc || null;
if (scriptPath && (isWindows || fs.existsSync(engine.scriptSrc))) {
if (!isWindows) { // not required on Windows
fs.chmodSync(engine.scriptSrc, '755');
}
return superspawn.spawn(scriptPath)
.then(stdout => {
engine.currentVersion = cleanVersionOutput(stdout, engine.name);
if (engine.currentVersion === '') {
events.emit('warn', engine.name + ' version check returned nothing (' + scriptPath + '), continuing anyways.');
engine.currentVersion = null;
}
}, () => {
events.emit('warn', engine.name + ' version check failed (' + scriptPath + '), continuing anyways.');
engine.currentVersion = null;
})
.then(_ => engine);
} else {
if (engine.currentVersion) {
engine.currentVersion = cleanVersionOutput(engine.currentVersion, engine.name);
} else {
events.emit('warn', engine.name + ' version not detected (lacks script ' + scriptPath + ' ), continuing.');
}
return Promise.resolve(engine);
}
})
);
}
|
javascript
|
{
"resource": ""
}
|
q62181
|
createPackageJson
|
test
|
function createPackageJson (plugin_path) {
var pluginInfo = new PluginInfo(plugin_path);
var defaults = {
id: pluginInfo.id,
version: pluginInfo.version,
description: pluginInfo.description,
license: pluginInfo.license,
keywords: pluginInfo.getKeywordsAndPlatforms(),
repository: pluginInfo.repo,
engines: pluginInfo.getEngines(),
platforms: pluginInfo.getPlatformsArray()
};
var initFile = require.resolve('./init-defaults');
return initPkgJson(plugin_path, initFile, defaults)
.then(_ => {
events.emit('verbose', 'Package.json successfully created');
});
}
|
javascript
|
{
"resource": ""
}
|
q62182
|
preparePlatforms
|
test
|
function preparePlatforms (platformList, projectRoot, options) {
return Promise.all(platformList.map(function (platform) {
// TODO: this need to be replaced by real projectInfo
// instance for current project.
var project = {
root: projectRoot,
projectConfig: new ConfigParser(cordova_util.projectConfig(projectRoot)),
locations: {
plugins: path.join(projectRoot, 'plugins'),
www: cordova_util.projectWww(projectRoot),
rootConfigXml: cordova_util.projectConfig(projectRoot)
}
};
// CB-9987 We need to reinstall the plugins for the platform it they were added by cordova@<5.4.0
return module.exports.restoreMissingPluginsForPlatform(platform, projectRoot, options)
.then(function () {
// platformApi prepare takes care of all functionality
// which previously had been executed by cordova.prepare:
// - reset config.xml and then merge changes from project's one,
// - update www directory from project's one and merge assets from platform_www,
// - reapply config changes, made by plugins,
// - update platform's project
// Please note that plugins' changes, such as installed js files, assets and
// config changes is not being reinstalled on each prepare.
var platformApi = platforms.getPlatformApi(platform);
return platformApi.prepare(project, _.clone(options))
.then(function () {
// Handle edit-config in config.xml
var platformRoot = path.join(projectRoot, 'platforms', platform);
var platformJson = PlatformJson.load(platformRoot, platform);
var munger = new PlatformMunger(platform, platformRoot, platformJson);
// the boolean argument below is "should_increment"
munger.add_config_changes(project.projectConfig, true).save_all();
});
});
}));
}
|
javascript
|
{
"resource": ""
}
|
q62183
|
test
|
function(icon, icon_size) {
// do I have a platform icon for that density already
var density = icon.density || sizeToDensityMap[icon_size];
if (!density) {
// invalid icon defition ( or unsupported size)
return;
}
var previous = android_icons[density];
if (previous && previous.platform) {
return;
}
android_icons[density] = icon;
}
|
javascript
|
{
"resource": ""
}
|
|
q62184
|
mapImageResources
|
test
|
function mapImageResources(rootDir, subDir, type, resourceName) {
var pathMap = {};
shell.ls(path.join(rootDir, subDir, type + '-*'))
.forEach(function (drawableFolder) {
var imagePath = path.join(subDir, path.basename(drawableFolder), resourceName);
pathMap[imagePath] = null;
});
return pathMap;
}
|
javascript
|
{
"resource": ""
}
|
q62185
|
findAndroidLaunchModePreference
|
test
|
function findAndroidLaunchModePreference(platformConfig) {
var launchMode = platformConfig.getPreference('AndroidLaunchMode');
if (!launchMode) {
// Return a default value
return 'singleTop';
}
var expectedValues = ['standard', 'singleTop', 'singleTask', 'singleInstance'];
var valid = expectedValues.indexOf(launchMode) >= 0;
if (!valid) {
// Note: warn, but leave the launch mode as developer wanted, in case the list of options changes in the future
events.emit('warn', 'Unrecognized value for AndroidLaunchMode preference: ' +
launchMode + '. Expected values are: ' + expectedValues.join(', '));
}
return launchMode;
}
|
javascript
|
{
"resource": ""
}
|
q62186
|
AndroidManifest
|
test
|
function AndroidManifest(path) {
this.path = path;
this.doc = xml.parseElementtreeSync(path);
if (this.doc.getroot().tag !== 'manifest') {
throw new Error('AndroidManifest at ' + path + ' has incorrect root node name (expected "manifest")');
}
}
|
javascript
|
{
"resource": ""
}
|
q62187
|
expectUnmetRequirements
|
test
|
function expectUnmetRequirements (expected) {
const actual = unmetRequirementsCollector.store;
expect(actual).toEqual(jasmine.arrayWithExactContents(expected));
}
|
javascript
|
{
"resource": ""
}
|
q62188
|
findVersion
|
test
|
function findVersion (versions, version) {
var cleanedVersion = semver.clean(version);
for (var i = 0; i < versions.length; i++) {
if (semver.clean(versions[i]) === cleanedVersion) {
return versions[i];
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q62189
|
listUnmetRequirements
|
test
|
function listUnmetRequirements (name, failedRequirements) {
events.emit('warn', 'Unmet project requirements for latest version of ' + name + ':');
failedRequirements.forEach(function (req) {
events.emit('warn', ' ' + req.dependency + ' (' + req.installed + ' in project, ' + req.required + ' required)');
});
}
|
javascript
|
{
"resource": ""
}
|
q62190
|
test
|
function(folderName, task) {
var defer = Q.defer();
var vn = (task.name || folderName);
if (!task.id || !check.isUUID(task.id)) {
defer.reject(createError(vn + ': id is a required guid'));
};
if (!task.name || !check.isAlphanumeric(task.name)) {
defer.reject(createError(vn + ': name is a required alphanumeric string'));
}
if (!task.friendlyName || !check.isLength(task.friendlyName, 1, 40)) {
defer.reject(createError(vn + ': friendlyName is a required string <= 40 chars'));
}
if (!task.instanceNameFormat) {
defer.reject(createError(vn + ': instanceNameFormat is required'));
}
// resolve if not already rejected
defer.resolve();
return defer.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q62191
|
test
|
function (travisYML, newVersion, newCodeName, existingVersions) {
// Should only add the new version if it is not present in any form
if (existingVersions.versions.length === 0) return travisYML
const nodeVersionIndex = getNodeVersionIndex(existingVersions.versions, newVersion, newCodeName)
const travisYMLLines = travisYML.split('\n')
// We only need to do something if the new version isn’t present
if (nodeVersionIndex === -1) {
let delimiter = ''
let leadingSpaces = ''
if (existingVersions.versions && existingVersions.versions.length > 0) {
if (existingVersions.versions[0].match(/"/)) {
delimiter = '"'
}
if (existingVersions.versions[0].match(/'/)) {
delimiter = "'"
}
leadingSpaces = existingVersions.versions[0].match(/^([ ]*)/)[1]
}
// splice the new version back onto the end of the node version list in the original travisYMLLines array,
// unless it wasn’t an array but an inline definition of a single version, eg: `node_js: 9`
if (existingVersions.versions.length === 1 && existingVersions.startIndex === existingVersions.endIndex) {
// A single node version was defined in inline format, now we want to define two versions in array format
travisYMLLines.splice(existingVersions.startIndex, 1, 'node_js:')
travisYMLLines.splice(existingVersions.startIndex + 1, 0, `${leadingSpaces}- ${existingVersions.versions[0]}`)
travisYMLLines.splice(existingVersions.startIndex + 2, 0, `${leadingSpaces}- ${delimiter}${newVersion}${delimiter}`)
} else {
// Multiple node versions were defined in array format
travisYMLLines.splice(existingVersions.endIndex + 1, 0, `${leadingSpaces}- ${delimiter}${newVersion}${delimiter}`)
}
}
return travisYMLLines.join('\n')
}
|
javascript
|
{
"resource": ""
}
|
|
q62192
|
test
|
function (travisYML, newVersion, newCodeName, existingVersions) {
// Should only remove the old version if it is actually present in any form
if (existingVersions.versions.length === 0) return travisYML
const nodeVersionIndex = getNodeVersionIndex(existingVersions.versions, newVersion, newCodeName, true)
let travisYMLLines = travisYML.split('\n')
// We only need to do something if the old version is present
if (nodeVersionIndex !== -1) {
// If it’s the only version we don’t want to remove it
if (existingVersions.versions.length !== 1) {
// Multiple node versions were defined in array format
// set lines we want to remove to undefined in existingVersion.versions and filter them out afterwards
const updatedVersionsArray = _.filter(existingVersions.versions.map((version) => {
return hasNodeVersion(version, newVersion, newCodeName, true) ? undefined : version
}), Boolean)
// splice the updated existingversions into travisymllines
travisYMLLines.splice(existingVersions.startIndex + 1, existingVersions.endIndex - existingVersions.startIndex, updatedVersionsArray)
// has an array in an array, needs to be flattened
travisYMLLines = _.flatten(travisYMLLines)
}
}
return travisYMLLines.join('\n')
}
|
javascript
|
{
"resource": ""
}
|
|
q62193
|
travisTransform
|
test
|
function travisTransform (travisYML) {
try {
var travisJSON = yaml.safeLoad(travisYML, {
schema: yaml.FAILSAFE_SCHEMA
})
} catch (e) {
// ignore .travis.yml if it can not be parsed
return
}
// No node versions specified in root level of travis YML
// There may be node versions defined in the matrix or jobs keys, but those can become
// far too complex for us to handle, so we don’t
if (!_.get(travisJSON, 'node_js')) return
const nodeVersionFromYaml = getNodeVersionsFromTravisYML(travisYML)
const hasNodeVersion = getNodeVersionIndex(nodeVersionFromYaml.versions, nodeVersion, codeName) !== -1
if (hasNodeVersion) return
const updatedTravisYaml = addNodeVersionToTravisYML(travisYML, nodeVersion, codeName, nodeVersionFromYaml)
return updatedTravisYaml
}
|
javascript
|
{
"resource": ""
}
|
q62194
|
isDependencyIgnoredInGroups
|
test
|
function isDependencyIgnoredInGroups (groups, packageFilePath, dependencyName) {
const groupName = getGroupForPackageFile(groups, packageFilePath)
return groupName && _.includes(groups[groupName].ignore, dependencyName)
}
|
javascript
|
{
"resource": ""
}
|
q62195
|
getDependencyURL
|
test
|
function getDependencyURL ({ repositoryURL, dependency }) {
// githubURL is an object!
const githubURL = url.parse(
githubFromGit(repositoryURL) || ''
)
if (dependency && !githubURL.href) {
return `https://www.npmjs.com/package/${dependency}`
}
return githubURL
}
|
javascript
|
{
"resource": ""
}
|
q62196
|
extractApis
|
test
|
function extractApis(services) {
var filterTypes = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
services = Array.isArray(services) ? services : [services];
var apis = services.reduce(function (total, service) {
var obj = service.constructor === Object ? service : Object.getPrototypeOf(service);
var keys = aggregateApisByType(obj, total, filterTypes);
total.push.apply(total, keys);
return total;
}, []);
return apis;
}
|
javascript
|
{
"resource": ""
}
|
q62197
|
extractNormalizedFacetValues
|
test
|
function extractNormalizedFacetValues(results, attribute) {
var predicate = {name: attribute};
if (results._state.isConjunctiveFacet(attribute)) {
var facet = find(results.facets, predicate);
if (!facet) return [];
return map(facet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isFacetRefined(attribute, k),
isExcluded: results._state.isExcludeRefined(attribute, k)
};
});
} else if (results._state.isDisjunctiveFacet(attribute)) {
var disjunctiveFacet = find(results.disjunctiveFacets, predicate);
if (!disjunctiveFacet) return [];
return map(disjunctiveFacet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isDisjunctiveFacetRefined(attribute, k)
};
});
} else if (results._state.isHierarchicalFacet(attribute)) {
return find(results.hierarchicalFacets, predicate);
}
}
|
javascript
|
{
"resource": ""
}
|
q62198
|
recSort
|
test
|
function recSort(sortFn, node) {
if (!node.data || node.data.length === 0) {
return node;
}
var children = map(node.data, partial(recSort, sortFn));
var sortedChildren = sortFn(children);
var newNode = merge({}, node, {data: sortedChildren});
return newNode;
}
|
javascript
|
{
"resource": ""
}
|
q62199
|
test
|
function(attribute, operator, v) {
var value = valToNumber(v);
if (this.isNumericRefined(attribute, operator, value)) return this;
var mod = merge({}, this.numericRefinements);
mod[attribute] = merge({}, mod[attribute]);
if (mod[attribute][operator]) {
// Array copy
mod[attribute][operator] = mod[attribute][operator].slice();
// Add the element. Concat can't be used here because value can be an array.
mod[attribute][operator].push(value);
} else {
mod[attribute][operator] = [value];
}
return this.setQueryParameters({
numericRefinements: mod
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.