_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q44800
|
approveWallet
|
train
|
function approveWallet(wallet, xPubKey, account, arrWalletDefinitionTemplate, arrOtherCosigners, onDone){
var arrDeviceAddresses = getDeviceAddresses(arrWalletDefinitionTemplate);
device.addIndirectCorrespondents(arrOtherCosigners, function(){
addWallet(wallet, xPubKey, account, arrWalletDefinitionTemplate, function(){
arrDeviceAddresses.forEach(function(device_address){
if (device_address !== device.getMyDeviceAddress())
sendMyXPubKey(device_address, wallet, xPubKey);
});
if (onDone)
onDone();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q44801
|
deleteWallet
|
train
|
function deleteWallet(wallet, rejector_device_address, onDone){
db.query("SELECT approval_date FROM extended_pubkeys WHERE wallet=? AND device_address=?", [wallet, rejector_device_address], function(rows){
if (rows.length === 0) // you are not a member device
return onDone();
if (rows[0].approval_date) // you've already approved this wallet, you can't change your mind
return onDone();
db.query("SELECT device_address FROM extended_pubkeys WHERE wallet=?", [wallet], function(rows){
var arrMemberAddresses = rows.map(function(row){ return row.device_address; });
var arrQueries = [];
db.addQuery(arrQueries, "DELETE FROM extended_pubkeys WHERE wallet=?", [wallet]);
db.addQuery(arrQueries, "DELETE FROM wallet_signing_paths WHERE wallet=?", [wallet]);
db.addQuery(arrQueries, "DELETE FROM wallets WHERE wallet=?", [wallet]);
// delete unused indirect correspondents
db.addQuery(
arrQueries,
"DELETE FROM correspondent_devices WHERE is_indirect=1 AND device_address IN(?) AND NOT EXISTS ( \n\
SELECT * FROM extended_pubkeys WHERE extended_pubkeys.device_address=correspondent_devices.device_address \n\
)",
[arrMemberAddresses]
);
async.series(arrQueries, function(){
eventBus.emit('wallet_declined', wallet, rejector_device_address);
onDone();
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q44802
|
addNewAddress
|
train
|
function addNewAddress(wallet, is_change, address_index, address, handleError){
breadcrumbs.add('addNewAddress is_change='+is_change+', index='+address_index+', address='+address);
db.query("SELECT 1 FROM wallets WHERE wallet=?", [wallet], function(rows){
if (rows.length === 0)
return handleError("wallet "+wallet+" does not exist");
deriveAddress(wallet, is_change, address_index, function(new_address, arrDefinition){
if (new_address !== address)
return handleError("I derived address "+new_address+", your address "+address);
recordAddress(wallet, is_change, address_index, address, arrDefinition, function(){
eventBus.emit("new_wallet_address", address);
handleError();
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q44803
|
issueOrSelectNextAddress
|
train
|
function issueOrSelectNextAddress(wallet, is_change, handleAddress){
readNextAddressIndex(wallet, is_change, function(next_index){
if (next_index < MAX_BIP44_GAP)
return issueAddress(wallet, is_change, next_index, handleAddress);
readLastUsedAddressIndex(wallet, is_change, function(last_used_index){
if (last_used_index === null || next_index - last_used_index >= MAX_BIP44_GAP)
selectRandomAddress(wallet, is_change, last_used_index, handleAddress);
else
issueAddress(wallet, is_change, next_index, handleAddress);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q44804
|
readAddressInfo
|
train
|
function readAddressInfo(address, handleAddress){
db.query("SELECT address_index, is_change FROM my_addresses WHERE address=?", [address], function(rows){
if (rows.length === 0)
return handleAddress("address "+address+" not found");
handleAddress(null, rows[0]);
});
}
|
javascript
|
{
"resource": ""
}
|
q44805
|
sendPrivatePayments
|
train
|
function sendPrivatePayments(device_address, arrChains, bForwarded, conn, onSaved){
var body = {chains: arrChains};
if (bForwarded)
body.forwarded = true;
device.sendMessageToDevice(device_address, "private_payments", body, {
ifOk: function(){},
ifError: function(){},
onSaved: onSaved
}, conn);
}
|
javascript
|
{
"resource": ""
}
|
q44806
|
fixIsSpentFlag
|
train
|
function fixIsSpentFlag(onDone){
db.query(
"SELECT outputs.unit, outputs.message_index, outputs.output_index \n\
FROM outputs \n\
CROSS JOIN inputs ON outputs.unit=inputs.src_unit AND outputs.message_index=inputs.src_message_index AND outputs.output_index=inputs.src_output_index \n\
WHERE is_spent=0 AND type='transfer'",
function(rows){
console.log(rows.length+" previous outputs appear to be spent");
if (rows.length === 0)
return onDone();
var arrQueries = [];
rows.forEach(function(row){
console.log('fixing is_spent for output', row);
db.addQuery(arrQueries,
"UPDATE outputs SET is_spent=1 WHERE unit=? AND message_index=? AND output_index=?", [row.unit, row.message_index, row.output_index]);
});
async.series(arrQueries, onDone);
}
);
}
|
javascript
|
{
"resource": ""
}
|
q44807
|
createLinkProof
|
train
|
function createLinkProof(later_unit, earlier_unit, arrChain, cb){
storage.readJoint(db, later_unit, {
ifNotFound: function(){
cb("later unit not found");
},
ifFound: function(objLaterJoint){
var later_mci = objLaterJoint.unit.main_chain_index;
arrChain.push(objLaterJoint);
storage.readUnitProps(db, objLaterJoint.unit.last_ball_unit, function(objLaterLastBallUnitProps){
var later_lb_mci = objLaterLastBallUnitProps.main_chain_index;
storage.readJoint(db, earlier_unit, {
ifNotFound: function(){
cb("earlier unit not found");
},
ifFound: function(objEarlierJoint){
var earlier_mci = objEarlierJoint.unit.main_chain_index;
var earlier_unit = objEarlierJoint.unit.unit;
if (later_mci < earlier_mci && later_mci !== null && earlier_mci !== null)
return cb("not included");
if (later_lb_mci >= earlier_mci && earlier_mci !== null){ // was spent when confirmed
// includes the ball of earlier unit
proofChain.buildProofChain(later_lb_mci + 1, earlier_mci, earlier_unit, arrChain, function(){
cb();
});
}
else{ // the output was unconfirmed when spent
graph.determineIfIncluded(db, earlier_unit, [later_unit], function(bIncluded){
if (!bIncluded)
return cb("not included");
buildPath(objLaterJoint, objEarlierJoint, arrChain, function(){
cb();
});
});
}
}
});
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q44808
|
getAppsDataDir
|
train
|
function getAppsDataDir(){
switch(process.platform){
case 'win32': return process.env.LOCALAPPDATA;
case 'linux': return process.env.HOME + '/.config';
case 'darwin': return process.env.HOME + '/Library/Application Support';
default: throw Error("unknown platform "+process.platform);
}
}
|
javascript
|
{
"resource": ""
}
|
q44809
|
replaceWitness
|
train
|
function replaceWitness(old_witness, new_witness, handleResult){
if (!ValidationUtils.isValidAddress(new_witness))
return handleResult("new witness address is invalid");
readMyWitnesses(function(arrWitnesses){
if (arrWitnesses.indexOf(old_witness) === -1)
return handleResult("old witness not known");
if (arrWitnesses.indexOf(new_witness) >= 0)
return handleResult("new witness already present");
var doReplace = function(){
db.query("UPDATE my_witnesses SET address=? WHERE address=?", [new_witness, old_witness], function(){
handleResult();
});
};
if (conf.bLight) // absent the full database, there is nothing else to check
return doReplace();
db.query(
"SELECT 1 FROM unit_authors CROSS JOIN units USING(unit) WHERE address=? AND sequence='good' AND is_stable=1 LIMIT 1",
[new_witness],
function(rows){
if (rows.length === 0)
return handleResult("no stable messages from the new witness yet");
storage.determineIfWitnessAddressDefinitionsHaveReferences(db, [new_witness], function(bHasReferences){
if (bHasReferences)
return handleResult("address definition of the new witness has or had references");
doReplace();
});
}
);
});
}
|
javascript
|
{
"resource": ""
}
|
q44810
|
sendSignature
|
train
|
function sendSignature(device_address, signed_text, signature, signing_path, address){
device.sendMessageToDevice(device_address, "signature", {signed_text: signed_text, signature: signature, signing_path: signing_path, address: address});
}
|
javascript
|
{
"resource": ""
}
|
q44811
|
train
|
function(){
console.log("handleOnlinePrivatePayment queued, will wait for "+key);
eventBus.once(key, function(bValid){
if (!bValid)
return cancelAllKeys();
assocValidatedByKey[key] = true;
if (bParsingComplete)
checkIfAllValidated();
else
console.log('parsing incomplete yet');
});
cb();
}
|
javascript
|
{
"resource": ""
}
|
|
q44812
|
readFundedAndSigningAddresses
|
train
|
function readFundedAndSigningAddresses(
asset, wallet, estimated_amount, spend_unconfirmed, fee_paying_wallet,
arrSigningAddresses, arrSigningDeviceAddresses, handleFundedAndSigningAddresses)
{
readFundedAddresses(asset, wallet, estimated_amount, spend_unconfirmed, function(arrFundedAddresses){
if (arrFundedAddresses.length === 0)
return handleFundedAndSigningAddresses([], [], []);
var arrBaseFundedAddresses = [];
var addSigningAddressesAndReturn = function(){
var arrPayingAddresses = _.union(arrFundedAddresses, arrBaseFundedAddresses);
readAdditionalSigningAddresses(arrPayingAddresses, arrSigningAddresses, arrSigningDeviceAddresses, function(arrAdditionalAddresses){
handleFundedAndSigningAddresses(arrFundedAddresses, arrBaseFundedAddresses, arrSigningAddresses.concat(arrAdditionalAddresses));
});
};
if (!asset)
return addSigningAddressesAndReturn();
readFundedAddresses(null, wallet, TYPICAL_FEE, spend_unconfirmed, function(_arrBaseFundedAddresses){
// fees will be paid from the same addresses as the asset
if (_arrBaseFundedAddresses.length > 0 || !fee_paying_wallet || fee_paying_wallet === wallet){
arrBaseFundedAddresses = _arrBaseFundedAddresses;
return addSigningAddressesAndReturn();
}
readFundedAddresses(null, fee_paying_wallet, TYPICAL_FEE, spend_unconfirmed, function(_arrBaseFundedAddresses){
arrBaseFundedAddresses = _arrBaseFundedAddresses;
addSigningAddressesAndReturn();
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q44813
|
checkStability
|
train
|
function checkStability() {
db.query(
"SELECT is_stable, asset, SUM(amount) AS `amount` \n\
FROM outputs JOIN units USING(unit) WHERE address=? AND sequence='good' AND is_spent=0 GROUP BY asset ORDER BY asset DESC LIMIT 1",
[addrInfo.address],
function(rows){
if (rows.length === 0) {
cb("This textcoin either was already claimed or never existed in the network");
} else {
var row = rows[0];
if (false && !row.is_stable) {
cb("This payment is not confirmed yet, try again later");
} else {
if (row.asset) { // claiming asset
opts.asset = row.asset;
opts.amount = row.amount;
opts.fee_paying_addresses = [addrInfo.address];
storage.readAsset(db, row.asset, null, function(err, objAsset){
if (err && err.indexOf("not found" !== -1)) {
if (!conf.bLight) // full wallets must have this asset
throw Error("textcoin asset "+row.asset+" not found");
return network.requestHistoryFor([opts.asset], [], checkStability);
}
asset = opts.asset;
opts.to_address = addressTo;
if (objAsset.fixed_denominations){ // indivisible
opts.tolerance_plus = 0;
opts.tolerance_minus = 0;
indivisibleAsset.composeAndSaveIndivisibleAssetPaymentJoint(opts);
}
else{ // divisible
divisibleAsset.composeAndSaveDivisibleAssetPaymentJoint(opts);
}
});
} else {// claiming bytes
opts.send_all = true;
opts.outputs = [{address: addressTo, amount: 0}];
opts.callbacks = composer.getSavingCallbacks(opts.callbacks);
composer.composeJoint(opts);
}
}
}
}
);
}
|
javascript
|
{
"resource": ""
}
|
q44814
|
claimBackOldTextcoins
|
train
|
function claimBackOldTextcoins(to_address, days){
db.query(
"SELECT mnemonic FROM sent_mnemonics LEFT JOIN unit_authors USING(address) \n\
WHERE mnemonic!='' AND unit_authors.address IS NULL AND creation_date<"+db.addTime("-"+days+" DAYS"),
function(rows){
async.eachSeries(
rows,
function(row, cb){
receiveTextCoin(row.mnemonic, to_address, function(err, unit, asset){
if (err)
console.log("failed claiming back old textcoin "+row.mnemonic+": "+err);
else
console.log("claimed back mnemonic "+row.mnemonic+", unit "+unit+", asset "+asset);
cb();
});
}
);
}
);
}
|
javascript
|
{
"resource": ""
}
|
q44815
|
CreateProfileRequest
|
train
|
function CreateProfileRequest(properties) {
this.profileType = [];
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q44816
|
UpdateProfileRequest
|
train
|
function UpdateProfileRequest(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q44817
|
Deployment
|
train
|
function Deployment(properties) {
this.labels = {};
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q44818
|
ValueType
|
train
|
function ValueType(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q44819
|
Sample
|
train
|
function Sample(properties) {
this.locationId = [];
this.value = [];
this.label = [];
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q44820
|
Label
|
train
|
function Label(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q44821
|
Mapping
|
train
|
function Mapping(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q44822
|
Line
|
train
|
function Line(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q44823
|
Function
|
train
|
function Function(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q44824
|
onTimeout
|
train
|
function onTimeout() {
const listenerCount = socket.listeners('timeout').length;
debug('%s(requests: %s, finished: %s) timeout after %sms, listeners %s',
socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
getSocketTimeout(socket), listenerCount);
agent.timeoutSocketCount++;
const name = agent.getName(options);
if (agent.freeSockets[name] && agent.freeSockets[name].indexOf(socket) !== -1) {
// free socket timeout, destroy quietly
socket.destroy();
// Remove it from freeSockets list immediately to prevent new requests
// from being sent through this socket.
agent.removeSocket(socket, options);
debug('%s is free, destroy quietly', socket[SOCKET_NAME]);
} else {
// if there is no any request socket timeout handler,
// agent need to handle socket timeout itself.
//
// custom request socket timeout handle logic must follow these rules:
// 1. Destroy socket first
// 2. Must emit socket 'agentRemove' event tell agent remove socket
// from freeSockets list immediately.
// Otherise you may be get 'socket hang up' error when reuse
// free socket and timeout happen in the same time.
if (listenerCount === 1) {
const error = new Error('Socket timeout');
error.code = 'ERR_SOCKET_TIMEOUT';
error.timeout = getSocketTimeout(socket);
// must manually call socket.end() or socket.destroy() to end the connection.
// https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_settimeout_timeout_callback
socket.destroy(error);
agent.removeSocket(socket, options);
debug('%s destroy with timeout error', socket[SOCKET_NAME]);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q44825
|
runWithProgress
|
train
|
function runWithProgress(maybeTaskFn, inSuite)
{
return Task.asyncFunction(function(callback) {
var bjsSuite = new Benchmark.Suite;
var benchArray;
var retData = [];
var finalString = "";
var numCompleted = 0;
var numToRun;
switch (inSuite.ctor)
{
case "Suite":
benchArray = List.toArray(inSuite._1);
break;
case "SingleBenchmark":
benchArray = [inSuite._0 ];
break;
}
numToRun = benchArray.length;
Task.perform(maybeTaskFn("Running benchmark 1 of " + numToRun));
//Initialize each benchmark in the suite
for (i = 0; i < benchArray.length; i++)
{
var ourThunk = function (){
//Run the thing we're timing, then mark the asynch benchmark as done
benchArray[i].thunk();
deferred.resolve();
}
bjsSuite.add(benchArray[i].name, benchArray[i].thunk );
}
//Every time a benchmark finishes, we store its results
//and update our progress string
bjsSuite.on('cycle', function(event) {
numCompleted += 1;
retData.push(
{ name : event.target.options.name
, hz : event.target.hz
, marginOfError : event.target.stats.moe
, moePercent : event.target.stats.rme
}
);
finalString += String(event.target) + "\n";
var intermedString =
"Running benchmark "
+ (numCompleted + 1)
+ " of " + numToRun
+ "\nLast result: " + String(event.target);
Task.perform(maybeTaskFn(intermedString));
//retString += String(event.target) + "\n";
});
//When the last benchmark finishes, we show all results collected
bjsSuite.on('complete', function(event) {
Task.perform(maybeTaskFn("Final results:\n\n" + finalString) );
return callback(Task.succeed(Utils.Tuple2(finalString, List.fromArray(retData))));
});
//Finally: actually run the suite
Task.perform(
Task.asyncFunction(function(otherCallback){
bjsSuite.run({ 'async': true });
}));
});
}
|
javascript
|
{
"resource": ""
}
|
q44826
|
getOverallBarChart
|
train
|
function getOverallBarChart(){
var contextMenuActions = [{
name: 'Explore windmill',
action: function(ae, splitBy, timestamp) {
explore(splitBy);
}
}]
var endDate = new Date(Math.floor((new Date()).valueOf()/(1000*60*60*24))*(1000*60*60*24));
var startDate = new Date(endDate.valueOf() - 1000*60*60*24*7);
var aggregateExpressions = [];
aggregateExpressions.push(new tsiClient.ux.AggregateExpression({predicateString: "DSCR HAS 'Grid Power'"}, {property: 'VALUE', type: "Double"}, ['sum'],
{ from: startDate, to: endDate, bucketSize: '1d' }, {property: 'UNIT', type: 'String'}, 'teal', 'GridPower', contextMenuActions));
authContext.getTsiToken().then(function(token){
tsiClient.server.getAggregates(token, environmentFqdn, aggregateExpressions.map(function(ae){return ae.toTsx()})).then(function(result){
var barChart = new tsiClient.ux.BarChart(document.getElementById('chart0'));
var transformedResult = tsiClient.ux.transformAggregatesForVisualization(result, aggregateExpressions);
barChart.render(transformedResult, {legend: 'hidden', zeroYAxis: true, keepSplitByColor: true, tooltip: true}, aggregateExpressions);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q44827
|
train
|
function (response) {
document.getElementById("windmillWeather").innerHTML = "<div>Current conditions</div>" + '<img class="icon" src="https://openweathermap.org/img/w/' + response.weather[0].icon + '.png' + '"><span>' + response.weather[0].main + ", Temp: " + response.main.temp + "'c, Wind: " + response.wind.speed + " (m/s)</span>";
}
|
javascript
|
{
"resource": ""
}
|
|
q44828
|
getUpdatedEmittedFiles
|
train
|
function getUpdatedEmittedFiles(emittedFiles, webpackRuntimeFiles) {
let fallbackFiles = [];
let hotHash;
if (emittedFiles.some(x => x.endsWith('.hot-update.json'))) {
let result = emittedFiles.slice();
const hotUpdateScripts = emittedFiles.filter(x => x.endsWith('.hot-update.js'));
hotUpdateScripts.forEach(hotUpdateScript => {
const { name, hash } = parseHotUpdateChunkName(hotUpdateScript);
hotHash = hash;
// remove bundle/vendor.js files if there's a bundle.XXX.hot-update.js or vendor.XXX.hot-update.js
result = result.filter(file => file !== `${name}.js`);
if (webpackRuntimeFiles && webpackRuntimeFiles.length) {
// remove files containing only the Webpack runtime (e.g. runtime.js)
result = result.filter(file => webpackRuntimeFiles.indexOf(file) === -1);
}
});
//if applying of hot update fails, we must fallback to the full files
fallbackFiles = emittedFiles.filter(file => result.indexOf(file) === -1);
return { emittedFiles: result, fallbackFiles, hash: hotHash };
}
else {
return { emittedFiles, fallbackFiles };
}
}
|
javascript
|
{
"resource": ""
}
|
q44829
|
parseHotUpdateChunkName
|
train
|
function parseHotUpdateChunkName(name) {
const matcher = /^(.+)\.(.+)\.hot-update/gm;
const matches = matcher.exec(name);
return {
name: matches[1] || "",
hash: matches[2] || "",
};
}
|
javascript
|
{
"resource": ""
}
|
q44830
|
remove
|
train
|
function remove(id, callback) {
repo.contents(id).fetch({
ref: options.branch
}, function(err, info) {
if (err) return callback(err);
repo.contents(id).remove({
branch: options.branch,
sha: info.sha,
message: '-'
}, function(err, res) {
callback(err, res, id);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q44831
|
get
|
train
|
function get(id, callback) {
_getSHA(id, function(err, sha) {
if (err) return callback(err);
repo.git.blobs(sha).fetch(function(err, res) {
if (err) return callback(err);
callback(err, JSON.parse(atob(res.content)));
});
});
}
|
javascript
|
{
"resource": ""
}
|
q44832
|
_getSHA
|
train
|
function _getSHA(id, callback) {
repo.contents("").fetch({
ref: options.branch
}, function(err, res) {
if (err) return callback(err);
var sha = res.reduce(function(previousValue, item) {
return item.name === id ? item.sha : previousValue;
}, "");
callback(err, sha);
});
}
|
javascript
|
{
"resource": ""
}
|
q44833
|
processInput
|
train
|
function processInput(buffer, cb) {
if (buffer.length == 0) return buffer;
var split_char = '\n';
var lines = buffer.split(split_char);
// If there are any line splits, the below logic always works, but if there are none we need to detect this and skip
// any processing.
if (lines[0].length == buffer.length) return buffer;
// Note last item is ignored since it is the remainder (or empty)
for(var i = 0; i < lines.length-1; i++) {
var line = lines[i];
if (format == "binary") {
target.produce(line, handleProduceResponse.bind(undefined, cb));
} else if (format == "avro") {
// Avro data should be passed in its JSON-serialized form
try {
var avro = JSON.parse(line);
} catch (e) {
console.log("Couldn't parse '" + line + "' as JSON");
continue;
}
target.produce(valueSchema, avro, handleProduceResponse.bind(undefined, cb));
}
// OR with key or partition:
//target.produce({'partition': 0, 'value': line}, handleProduceResponse.bind(undefined, cb));
//target.produce({'key': 'console', 'value': line}, handleProduceResponse.bind(undefined, cb));
num_messages += 1;
num_bytes += line.length;
}
return lines[lines.length-1];
}
|
javascript
|
{
"resource": ""
}
|
q44834
|
handleProduceResponse
|
train
|
function handleProduceResponse(cb, err, res) {
num_responses += 1;
if (err) {
console.log("Error producing message: " + err);
} else {
num_messages_acked += 1;
}
// We can only indicate were done if stdin was closed and we have no outstanding messages.
checkSendingComplete(cb);
}
|
javascript
|
{
"resource": ""
}
|
q44835
|
getParts
|
train
|
function getParts (component, options) {
let {
modules = [],
package: pack,
path: packPath = COMPONENTS_DIRNAME,
transform,
fileName,
locale,
global = []
} = options
if (pack && fileName) {
modules.push({ package: pack, path: packPath, transform, fileName })
}
if (locale !== false) {
if (!locale) {
locale = 'zh-Hans'
}
if (!Array.isArray(locale)) {
locale = [locale]
}
locale = locale.filter(l => typeof l === 'string')
modules = locale
.map(l => {
return {
package: 'veui',
path: `locale/${l}`,
transform: false,
fileName: '{module}.js'
}
})
.concat(modules)
global = locale
.map(l => {
return { path: `veui/locale/${l}/common.js` }
})
.concat(global)
}
return modules.reduce(
(
acc,
{
package: pack,
path: packPath = COMPONENTS_DIRNAME,
transform,
fileName
}
) => {
let peerComponent = getPeerFilename(component, {
transform,
template: fileName
})
let peerPath = slash(path.join(pack, packPath, peerComponent))
pushPart(acc, { path: peerPath })
return acc
},
{
script: [...global],
style: []
}
)
}
|
javascript
|
{
"resource": ""
}
|
q44836
|
patchContent
|
train
|
function patchContent (content, parts) {
return Object.keys(parts).reduce((content, type) => {
let paths = parts[type].filter(({ valid }) => valid).map(({ path }) => path)
return patchType(content, type, paths)
}, content)
}
|
javascript
|
{
"resource": ""
}
|
q44837
|
pushPart
|
train
|
function pushPart (parts, file) {
let ext = getExtname(file.path)
let type = Object.keys(EXT_TYPES).find(key => {
return EXT_TYPES[key].includes(ext)
})
parts[type.toLowerCase()].push(file)
}
|
javascript
|
{
"resource": ""
}
|
q44838
|
patchType
|
train
|
function patchType (content, type, peerPaths) {
let normalizedPaths = peerPaths.map(path => slash(normalize(path)))
switch (type) {
case 'script':
let scriptImports = normalizedPaths.map(path => `import '${path}'\n`)
content = content.replace(RE_SCRIPT, match => {
return `${match}\n${scriptImports.join('')}`
})
break
case 'style':
let styleImports = normalizedPaths.map(path => {
let langStr = ''
let ext = getExtname(path)
if (ext !== 'css') {
langStr = `lang="${ext}" `
}
return `<style ${langStr}src="${path}"></style>\n`
})
content += styleImports.join('')
break
default:
break
}
return content
}
|
javascript
|
{
"resource": ""
}
|
q44839
|
assurePath
|
train
|
async function assurePath (modulePath, resolve) {
if (resolveCache[modulePath] === false) {
return false
} else if (!(modulePath in resolveCache)) {
if (typeof resolve === 'function') {
try {
resolveCache[modulePath] = !!(await resolve(modulePath))
} catch (e) {
resolveCache[modulePath] = false
}
}
}
return resolveCache[modulePath]
}
|
javascript
|
{
"resource": ""
}
|
q44840
|
assurePathSync
|
train
|
function assurePathSync (modulePath, resolveSync) {
if (resolveCache[modulePath] === false) {
return false
} else if (!(modulePath in resolveCache)) {
if (typeof resolveSync === 'function') {
try {
resolveCache[modulePath] = !!resolveSync(modulePath)
} catch (e) {
resolveCache[modulePath] = false
}
}
}
return resolveCache[modulePath]
}
|
javascript
|
{
"resource": ""
}
|
q44841
|
getPeerFilename
|
train
|
function getPeerFilename (
name,
{ transform = 'kebab-case', template = '{module}.css' }
) {
if (!name) {
return null
}
switch (transform) {
case 'kebab-case':
name = kebabCase(name)
break
case 'camelCase':
name = camelCase(name)
break
case 'PascalCase':
name = pascalCase(name)
break
case false:
default:
break
}
return template.replace(/\$?\{module\}/g, name)
}
|
javascript
|
{
"resource": ""
}
|
q44842
|
GeoComplete
|
train
|
function GeoComplete(input, options) {
this.options = $.extend(true, {}, defaults, options);
// This is a fix to allow types:[] not to be overridden by defaults
// so search results includes everything
if (options && options.types) {
this.options.types = options.types;
}
this.input = input;
this.$input = $(input);
this._defaults = defaults;
this._name = 'geocomplete';
this.init();
}
|
javascript
|
{
"resource": ""
}
|
q44843
|
train
|
function(){
if (!this.options.map){ return; }
if (typeof this.options.map.setCenter == "function"){
this.map = this.options.map;
return;
}
this.map = new google.maps.Map(
$(this.options.map)[0],
this.options.mapOptions
);
// add click event listener on the map
google.maps.event.addListener(
this.map,
'click',
$.proxy(this.mapClicked, this)
);
// add dragend even listener on the map
google.maps.event.addListener(
this.map,
'dragend',
$.proxy(this.mapDragged, this)
);
// add idle even listener on the map
google.maps.event.addListener(
this.map,
'idle',
$.proxy(this.mapIdle, this)
);
google.maps.event.addListener(
this.map,
'zoom_changed',
$.proxy(this.mapZoomed, this)
);
}
|
javascript
|
{
"resource": ""
}
|
|
q44844
|
train
|
function(){
if (!this.map){ return; }
var options = $.extend(this.options.markerOptions, { map: this.map });
if (options.disabled){ return; }
this.marker = new google.maps.Marker(options);
google.maps.event.addListener(
this.marker,
'dragend',
$.proxy(this.markerDragged, this)
);
}
|
javascript
|
{
"resource": ""
}
|
|
q44845
|
train
|
function(){
// Indicates is user did select a result from the dropdown.
var selected = false;
var options = {
types: this.options.types,
bounds: this.options.bounds === true ? null : this.options.bounds,
componentRestrictions: this.options.componentRestrictions,
strictBounds: this.options.strictBounds
};
if (this.options.country){
options.componentRestrictions = {country: this.options.country};
}
this.autocomplete = new google.maps.places.Autocomplete(
this.input, options
);
this.geocoder = new google.maps.Geocoder();
// Bind autocomplete to map bounds but only if there is a map
// and `options.bindToMap` is set to true.
if (this.map && this.options.bounds === true){
this.autocomplete.bindTo('bounds', this.map);
}
// Watch `place_changed` events on the autocomplete input field.
google.maps.event.addListener(
this.autocomplete,
'place_changed',
$.proxy(this.placeChanged, this)
);
// Prevent parent form from being submitted if user hit enter.
this.$input.on('keypress.' + this._name, function(event){
if (event.keyCode === 13){ return false; }
});
// Assume that if user types anything after having selected a result,
// the selected location is not valid any more.
if (this.options.geocodeAfterResult === true){
this.$input.bind('keypress.' + this._name, $.proxy(function(){
if (event.keyCode != 9 && this.selected === true){
this.selected = false;
}
}, this));
}
// Listen for "geocode" events and trigger find action.
this.$input.bind('geocode.' + this._name, $.proxy(function(){
this.find();
}, this));
// Saves the previous input value
this.$input.bind('geocode:result.' + this._name, $.proxy(function(){
this.lastInputVal = this.$input.val();
}, this));
// Trigger find action when input element is blurred out and user has
// not explicitly selected a result.
// (Useful for typing partial location and tabbing to the next field
// or clicking somewhere else.)
if (this.options.blur === true){
this.$input.on('blur.' + this._name, $.proxy(function(){
if (this.options.geocodeAfterResult === true && this.selected === true) { return; }
if (this.options.restoreValueAfterBlur === true && this.selected === true) {
setTimeout($.proxy(this.restoreLastValue, this), 0);
} else {
this.find();
}
}, this));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44846
|
train
|
function(){
if (!this.options.details){ return; }
if(this.options.detailsScope) {
var $details = $(this.input).parents(this.options.detailsScope).find(this.options.details);
} else {
var $details = $(this.options.details);
}
var attribute = this.options.detailsAttribute,
details = {};
function setDetail(value){
details[value] = $details.find("[" + attribute + "=" + value + "]");
}
$.each(componentTypes, function(index, key){
setDetail(key);
setDetail(key + "_short");
});
$.each(placesDetails, function(index, key){
setDetail(key);
});
this.$details = $details;
this.details = details;
}
|
javascript
|
{
"resource": ""
}
|
|
q44847
|
train
|
function() {
var location = this.options.location, latLng;
if (!location) { return; }
if (typeof location == 'string') {
this.find(location);
return;
}
if (location instanceof Array) {
latLng = new google.maps.LatLng(location[0], location[1]);
}
if (location instanceof google.maps.LatLng){
latLng = location;
}
if (latLng){
if (this.map){ this.map.setCenter(latLng); }
if (this.marker){ this.marker.setPosition(latLng); }
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44848
|
train
|
function(request){
// Don't geocode if the requested address is empty
if (!request.address) {
return;
}
if (this.options.bounds && !request.bounds){
if (this.options.bounds === true){
request.bounds = this.map && this.map.getBounds();
} else {
request.bounds = this.options.bounds;
}
}
if (this.options.country){
request.region = this.options.country;
}
this.geocoder.geocode(request, $.proxy(this.handleGeocode, this));
}
|
javascript
|
{
"resource": ""
}
|
|
q44849
|
train
|
function() {
//$(".pac-container").hide();
var selected = '';
// Check if any result is selected.
if ($(".pac-item-selected")[0]) {
selected = '-selected';
}
// Get the first suggestion's text.
var $span1 = $(".pac-container:visible .pac-item" + selected + ":first span:nth-child(2)").text();
var $span2 = $(".pac-container:visible .pac-item" + selected + ":first span:nth-child(3)").text();
// Adds the additional information, if available.
var firstResult = $span1;
if ($span2) {
firstResult += " - " + $span2;
}
this.$input.val(firstResult);
return firstResult;
}
|
javascript
|
{
"resource": ""
}
|
|
q44850
|
train
|
function(geometry){
if (geometry.viewport){
this.map.fitBounds(geometry.viewport);
if (this.map.getZoom() > this.options.maxZoom){
this.map.setZoom(this.options.maxZoom);
}
} else {
this.map.setZoom(this.options.maxZoom);
this.map.setCenter(geometry.location);
}
if (this.marker){
this.marker.setPosition(geometry.location);
this.marker.setAnimation(this.options.markerOptions.animation);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44851
|
train
|
function(result){
var data = {},
geometry = result.geometry,
viewport = geometry.viewport,
bounds = geometry.bounds;
// Create a simplified version of the address components.
$.each(result.address_components, function(index, object){
var name = object.types[0];
$.each(object.types, function(index, name){
data[name] = object.long_name;
data[name + "_short"] = object.short_name;
});
});
// Add properties of the places details.
$.each(placesDetails, function(index, key){
data[key] = result[key];
});
// Add infos about the address and geometry.
$.extend(data, {
formatted_address: result.formatted_address,
location_type: geometry.location_type || "PLACES",
viewport: viewport,
bounds: bounds,
location: geometry.location,
lat: geometry.location.lat(),
lng: geometry.location.lng()
});
// Set the values for all details.
$.each(this.details, $.proxy(function(key, $detail){
var value = data[key];
this.setDetail($detail, value);
}, this));
this.data = data;
}
|
javascript
|
{
"resource": ""
}
|
|
q44852
|
train
|
function(){
this.marker.setPosition(this.data.location);
this.setDetail(this.details.lat, this.data.location.lat());
this.setDetail(this.details.lng, this.data.location.lng());
}
|
javascript
|
{
"resource": ""
}
|
|
q44853
|
train
|
function(){
var place = this.autocomplete.getPlace();
this.selected = true;
if (!place.geometry){
if (this.options.autoselect) {
// Automatically selects the highlighted item or the first item from the
// suggestions list.
var autoSelection = this.selectFirstResult();
this.find(autoSelection);
}
} else {
// Use the input text if it already gives geometry.
this.update(place);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44854
|
train
|
function(req, res) {
if (!searchIdx) return res();
var results = searchIdx.search(req.term)
.map(function(result) {
return {
label: files[result.ref].title,
value: files[result.ref]
};
});
res(results);
}
|
javascript
|
{
"resource": ""
}
|
|
q44855
|
train
|
function(event, ui) {
search.val('');
window.location = ui.item.value.url.replace('_gh_pages', '');
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q44856
|
plugin
|
train
|
function plugin(name) {
return function(app) {
var files = app.getViews(name);
for (var file in files) {
if (files[file].data.draft) delete files[file];
}
};
}
|
javascript
|
{
"resource": ""
}
|
q44857
|
handleError
|
train
|
function handleError(err) {
if (typeof err === 'string' && errors[err]) {
console.error(errors[err]);
} else {
if (argv.verbose) {
console.error(err.stack);
} else {
console.error(err.message);
}
}
process.exit(1);
}
|
javascript
|
{
"resource": ""
}
|
q44858
|
concat
|
train
|
function concat(app) {
var files = app.views.files;
var css = '';
for (var file in files) {
if ('.css' != path.extname(file)) continue;
css += files[file].contents.toString();
delete files[file];
}
css = myth(css);
app.files.addView('index.css', {
contents: new Buffer(css)
});
}
|
javascript
|
{
"resource": ""
}
|
q44859
|
rename
|
train
|
function rename(files) {
return function(file) {
var base = path.relative(path.resolve(file.cwd), file.base);
var destBase = files.options.destBase;
file.dirname = path.resolve(path.join(destBase, base));
return file.base;
};
}
|
javascript
|
{
"resource": ""
}
|
q44860
|
Assemble
|
train
|
function Assemble(options) {
if (!(this instanceof Assemble)) {
return new Assemble(options);
}
Core.call(this, options);
this.is('assemble');
this.initAssemble();
}
|
javascript
|
{
"resource": ""
}
|
q44861
|
ask
|
train
|
function ask(cb) {
return function(app) {
app.use(store('smithy'))
.use(questions())
.ask(function(err, answers) {
if (err) return cb(err);
cb.call(app, null, answers);
});
app.asyncHelper('ask', function(key, options, cb) {
app.questions.options.force = true;
app.ask(key, function(err, res) {
if (err) return cb(err);
cb(null, res[key]);
});
});
};
}
|
javascript
|
{
"resource": ""
}
|
q44862
|
throwEqualError
|
train
|
function throwEqualError( F, a, b ) {
if ( (F[a] || F[b]) && (F[a] === F[b]) ) {
throw new Error(a);
}
}
|
javascript
|
{
"resource": ""
}
|
q44863
|
toFixed
|
train
|
function toFixed ( value, decimals ) {
var scale = Math.pow(10, decimals);
return ( Math.round(value * scale) / scale).toFixed( decimals );
}
|
javascript
|
{
"resource": ""
}
|
q44864
|
formatTo
|
train
|
function formatTo ( decimals, thousand, mark, prefix, postfix, encoder, decoder, negativeBefore, negative, edit, undo, input ) {
var originalInput = input, inputIsNegative, inputPieces, inputBase, inputDecimals = '', output = '';
// Apply user encoder to the input.
// Expected outcome: number.
if ( encoder ) {
input = encoder(input);
}
// Stop if no valid number was provided, the number is infinite or NaN.
if ( !isValidNumber(input) ) {
return false;
}
// Rounding away decimals might cause a value of -0
// when using very small ranges. Remove those cases.
if ( decimals !== false && parseFloat(input.toFixed(decimals)) === 0 ) {
input = 0;
}
// Formatting is done on absolute numbers,
// decorated by an optional negative symbol.
if ( input < 0 ) {
inputIsNegative = true;
input = Math.abs(input);
}
// Reduce the number of decimals to the specified option.
if ( decimals !== false ) {
input = toFixed( input, decimals );
}
// Transform the number into a string, so it can be split.
input = input.toString();
// Break the number on the decimal separator.
if ( input.indexOf('.') !== -1 ) {
inputPieces = input.split('.');
inputBase = inputPieces[0];
if ( mark ) {
inputDecimals = mark + inputPieces[1];
}
} else {
// If it isn't split, the entire number will do.
inputBase = input;
}
// Group numbers in sets of three.
if ( thousand ) {
inputBase = strReverse(inputBase).match(/.{1,3}/g);
inputBase = strReverse(inputBase.join( strReverse( thousand ) ));
}
// If the number is negative, prefix with negation symbol.
if ( inputIsNegative && negativeBefore ) {
output += negativeBefore;
}
// Prefix the number
if ( prefix ) {
output += prefix;
}
// Normal negative option comes after the prefix. Defaults to '-'.
if ( inputIsNegative && negative ) {
output += negative;
}
// Append the actual number.
output += inputBase;
output += inputDecimals;
// Apply the postfix.
if ( postfix ) {
output += postfix;
}
// Run the output through a user-specified post-formatter.
if ( edit ) {
output = edit ( output, originalInput );
}
// All done.
return output;
}
|
javascript
|
{
"resource": ""
}
|
q44865
|
formatFrom
|
train
|
function formatFrom ( decimals, thousand, mark, prefix, postfix, encoder, decoder, negativeBefore, negative, edit, undo, input ) {
var originalInput = input, inputIsNegative, output = '';
// User defined pre-decoder. Result must be a non empty string.
if ( undo ) {
input = undo(input);
}
// Test the input. Can't be empty.
if ( !input || typeof input !== 'string' ) {
return false;
}
// If the string starts with the negativeBefore value: remove it.
// Remember is was there, the number is negative.
if ( negativeBefore && strStartsWith(input, negativeBefore) ) {
input = input.replace(negativeBefore, '');
inputIsNegative = true;
}
// Repeat the same procedure for the prefix.
if ( prefix && strStartsWith(input, prefix) ) {
input = input.replace(prefix, '');
}
// And again for negative.
if ( negative && strStartsWith(input, negative) ) {
input = input.replace(negative, '');
inputIsNegative = true;
}
// Remove the postfix.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice
if ( postfix && strEndsWith(input, postfix) ) {
input = input.slice(0, -1 * postfix.length);
}
// Remove the thousand grouping.
if ( thousand ) {
input = input.split(thousand).join('');
}
// Set the decimal separator back to period.
if ( mark ) {
input = input.replace(mark, '.');
}
// Prepend the negative symbol.
if ( inputIsNegative ) {
output += '-';
}
// Add the number
output += input;
// Trim all non-numeric characters (allow '.' and '-');
output = output.replace(/[^0-9\.\-.]/g, '');
// The value contains no parse-able number.
if ( output === '' ) {
return false;
}
// Covert to number.
output = Number(output);
// Run the user-specified post-decoder.
if ( decoder ) {
output = decoder(output);
}
// Check is the output is valid, otherwise: return false.
if ( !isValidNumber(output) ) {
return false;
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
q44866
|
validate
|
train
|
function validate ( inputOptions ) {
var i, optionName, optionValue,
filteredOptions = {};
for ( i = 0; i < FormatOptions.length; i+=1 ) {
optionName = FormatOptions[i];
optionValue = inputOptions[optionName];
if ( optionValue === undefined ) {
// Only default if negativeBefore isn't set.
if ( optionName === 'negative' && !filteredOptions.negativeBefore ) {
filteredOptions[optionName] = '-';
// Don't set a default for mark when 'thousand' is set.
} else if ( optionName === 'mark' && filteredOptions.thousand !== '.' ) {
filteredOptions[optionName] = '.';
} else {
filteredOptions[optionName] = false;
}
// Floating points in JS are stable up to 7 decimals.
} else if ( optionName === 'decimals' ) {
if ( optionValue >= 0 && optionValue < 8 ) {
filteredOptions[optionName] = optionValue;
} else {
throw new Error(optionName);
}
// These options, when provided, must be functions.
} else if ( optionName === 'encoder' || optionName === 'decoder' || optionName === 'edit' || optionName === 'undo' ) {
if ( typeof optionValue === 'function' ) {
filteredOptions[optionName] = optionValue;
} else {
throw new Error(optionName);
}
// Other options are strings.
} else {
if ( typeof optionValue === 'string' ) {
filteredOptions[optionName] = optionValue;
} else {
throw new Error(optionName);
}
}
}
// Some values can't be extracted from a
// string if certain combinations are present.
throwEqualError(filteredOptions, 'mark', 'thousand');
throwEqualError(filteredOptions, 'prefix', 'negative');
throwEqualError(filteredOptions, 'prefix', 'negativeBefore');
return filteredOptions;
}
|
javascript
|
{
"resource": ""
}
|
q44867
|
passAll
|
train
|
function passAll ( options, method, input ) {
var i, args = [];
// Add all options in order of FormatOptions
for ( i = 0; i < FormatOptions.length; i+=1 ) {
args.push(options[FormatOptions[i]]);
}
// Append the input, then call the method, presenting all
// options as arguments.
args.push(input);
return method.apply('', args);
}
|
javascript
|
{
"resource": ""
}
|
q44868
|
formatDate
|
train
|
function formatDate ( date ) {
return weekdays[date.getDay()] + ", " +
date.getDate() + nth(date.getDate()) + " " +
months[date.getMonth()] + " " +
date.getFullYear();
}
|
javascript
|
{
"resource": ""
}
|
q44869
|
train
|
function () {
function commons() {}
commons.attachParentSelector = function (parentSelector, defaultSelector) {
var customSelector = defaultSelector;
if (parentSelector !== '' && parentSelector.length > 0) {
if (parentSelector === defaultSelector) {
customSelector = defaultSelector;
} else if ($(parentSelector).hasClass(defaultSelector)) {
customSelector = parentSelector + "" + defaultSelector;
} else {
customSelector = parentSelector + " " + defaultSelector;
}
}
return customSelector;
};
return commons;
}
|
javascript
|
{
"resource": ""
}
|
|
q44870
|
_inherits
|
train
|
function _inherits(SubClass, SuperClass) {
if (typeof SuperClass !== "function" && SuperClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof SuperClass);
}
SubClass.prototype = new SuperClass();
}
|
javascript
|
{
"resource": ""
}
|
q44871
|
onNavBarToggle
|
train
|
function onNavBarToggle() {
$(Selector.NAVBAR_SIDEBAR).toggleClass(ClassName.OPEN);
if (($(Selector.NAVBAR_SIDEBAR).hasClass(ClassName.NAVBAR_SIDEBAR)) && $(Selector.NAVBAR_SIDEBAR).hasClass(ClassName.OPEN)) {
$(Selector.OVERLAY).addClass(ClassName.OVERLAY_ACTIVE);
$(Selector.BODY).addClass(ClassName.BODY_OPEN);
} else {
$(Selector.OVERLAY).removeClass(ClassName.OVERLAY_ACTIVE);
$(Selector.BODY).addClass(ClassName.BODY_OPEN);
}
}
|
javascript
|
{
"resource": ""
}
|
q44872
|
onResizeWindow
|
train
|
function onResizeWindow(e) {
var options = e.data.param1;
var sideBarSelector=Selector.SIDEBAR;
$(sideBarSelector).each(function () {
var $this = $(this);
var sideBarId = $this.attr("id");
var isOpenWidth=$("a[data-target="+sideBarId+"]").attr("is-open-width");
if($(window).width()<isOpenWidth) {
if ($("#"+sideBarId).hasClass(ClassName.LEFT && ClassName.SLIDE_PUSH)) {
$("#"+sideBarId).removeClass(ClassName.OPEN + ' ' + ClassName.SLIDE_PUSH);
$("#"+sideBarId).addClass(ClassName.LEFT_FIXED + ' ' + ClassName.IS_SLIDEPUSH);
} else {
$("#"+sideBarId).removeClass(ClassName.OPEN);
}
}else{
if ($("#"+sideBarId).hasClass(ClassName.IS_SLIDEPUSH)) {
$("#"+sideBarId).addClass(ClassName.OPEN + ' ' + ClassName.SLIDE_PUSH);
$("#"+sideBarId).removeClass(ClassName.LEFT_FIXED);
} else {
$("#"+sideBarId).addClass(ClassName.OPEN);
}
}
});
$(pmdSidebar.prototype.attachParentSelector(Selector.PARENT_SELECTOR, Selector.OVERLAY)).removeClass(ClassName.OVERLAY_ACTIVE);
$(Selector.BODY).removeClass(ClassName.BODY_OPEN);
}
|
javascript
|
{
"resource": ""
}
|
q44873
|
localMiddleware
|
train
|
function localMiddleware (req, res, next) {
// Tell the client what Socket.IO namespace to use,
// trim the leading slash because the cookie will turn it into a %2F
res.setHeader('uibuilder-namespace', node.ioNamespace)
res.cookie('uibuilder-namespace', tilib.trimSlashes(node.ioNamespace), {path: node.url, sameSite: true})
next()
}
|
javascript
|
{
"resource": ""
}
|
q44874
|
train
|
function(msg, node, RED, io, ioNs, log) {
node.rcvMsgCount++
log.verbose(`[${node.url}] msg received via FLOW. ${node.rcvMsgCount} messages received`, msg)
// If the input msg is a uibuilder control msg, then drop it to prevent loops
if ( msg.hasOwnProperty('uibuilderCtrl') ) return null
//setNodeStatus({fill: 'yellow', shape: 'dot', text: 'Message Received #' + node.rcvMsgCount}, node)
// Remove script/style content if admin settings don't allow
if ( node.allowScripts !== true ) {
if ( msg.hasOwnProperty('script') ) delete msg.script
}
if ( node.allowStyles !== true ) {
if ( msg.hasOwnProperty('style') ) delete msg.style
}
// pass the complete msg object to the uibuilder client
// TODO: This should have some safety validation on it!
if (msg._socketId) {
log.debug(`[${node.url}] msg sent on to client ${msg._socketId}. Channel: ${node.ioChannels.server}`, msg)
ioNs.to(msg._socketId).emit(node.ioChannels.server, msg)
} else {
log.debug(`[${node.url}] msg sent on to ALL clients. Channel: ${node.ioChannels.server}`, msg)
ioNs.emit(node.ioChannels.server, msg)
}
if (node.fwdInMessages) {
// Send on the input msg to output
node.send(msg)
log.debug(`[${node.url}] msg passed downstream to next node`, msg)
}
return msg
}
|
javascript
|
{
"resource": ""
}
|
|
q44875
|
validateChoices
|
train
|
function validateChoices(props, propName, componentName) {
const propValue = props[propName];
if (!propValue) {
return undefined;
}
if (!Array.isArray(propValue) || propValue.length !== 2) {
return new Error(`Invalid ${propName} supplied to \`${componentName}\`, expected exactly two Choice components.`);
}
for (let i = 0; i < propValue.length; ++i) {
const item = propValue[i];
if (!item || !isComponentOfType(Choice, item)) {
return new Error(`Invalid ${propName}[${i}] supplied to \`${componentName}\`, expected a Choice component from Belle.`);
}
}
if (first(propValue).props.value === last(propValue).props.value) {
return new Error(`Invalid ${propName} supplied to \`${componentName}\`, expected different value properties for the provided Choice components.`);
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q44876
|
updatePseudoClassStyle
|
train
|
function updatePseudoClassStyle(styleId, properties, preventFocusStyleForTouchAndClick) {
let focusStyle;
if (preventFocusStyleForTouchAndClick) {
focusStyle = { outline: 0 };
} else {
focusStyle = {
...style.focusStyle,
...properties.focusStyle,
};
}
const styles = [
{
id: styleId,
style: focusStyle,
pseudoClass: 'focus',
},
];
injectStyles(styles);
}
|
javascript
|
{
"resource": ""
}
|
q44877
|
updatePseudoClassStyle
|
train
|
function updatePseudoClassStyle(styleId, properties, preventFocusStyleForTouchAndClick) {
const baseStyle = properties.primary ? buttonStyle.primaryStyle : buttonStyle.style;
const baseDisabledStyle = properties.primary ? buttonStyle.primaryDisabledStyle : buttonStyle.disabledStyle;
const disabledStyle = {
...baseStyle,
...properties.style,
...baseDisabledStyle,
...properties.disabledStyle,
};
const baseActiveStyle = properties.primary ? buttonStyle.primaryActiveStyle : buttonStyle.activeStyle;
const activeStyle = {
...baseActiveStyle,
...properties.activeStyle,
};
let focusStyle;
if (preventFocusStyleForTouchAndClick) {
focusStyle = { outline: 0 };
} else {
const baseFocusStyle = properties.primary ? buttonStyle.primaryFocusStyle : buttonStyle.focusStyle;
focusStyle = {
...baseFocusStyle,
...properties.focusStyle,
};
}
const styles = [
{
id: styleId,
style: activeStyle,
pseudoClass: 'active',
},
{
id: styleId,
style: disabledStyle,
pseudoClass: 'active',
disabled: true,
},
{
id: styleId,
style: focusStyle,
pseudoClass: 'focus',
},
];
injectStyles(styles);
}
|
javascript
|
{
"resource": ""
}
|
q44878
|
validateChildrenAreOptionsAndMaximumOnePlaceholder
|
train
|
function validateChildrenAreOptionsAndMaximumOnePlaceholder(props, propName, componentName) {
const validChildren = filterReactChildren(props[propName], (node) => (
(isOption(node) || isSeparator(node) || isPlaceholder(node))
));
if (React.Children.count(props[propName]) !== React.Children.count(validChildren)) {
return new Error(`Invalid children supplied to \`${componentName}\`, expected an Option, Separator or Placeholder component from Belle.`);
}
const placeholders = filterReactChildren(props[propName], (node) => isPlaceholder(node));
if (React.Children.count(placeholders) > 1) {
return new Error(`Invalid children supplied to \`${componentName}\`, expected only one Placeholder component.`);
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q44879
|
updatePseudoClassStyle
|
train
|
function updatePseudoClassStyle(styleId, properties) {
const hoverStyle = {
...style.hoverStyle,
...properties.hoverStyle,
};
const disabledHoverStyle = {
...style.disabledHoverStyle,
...properties.disabledHoverStyle,
};
const styles = [
{
id: styleId,
style: hoverStyle,
pseudoClass: 'hover',
},
{
id: styleId,
style: disabledHoverStyle,
pseudoClass: 'hover',
disabled: true,
},
];
injectStyles(styles);
}
|
javascript
|
{
"resource": ""
}
|
q44880
|
updateStructure
|
train
|
function updateStructure(targetObject, object) {
for (const componentName in object) {
if (object.hasOwnProperty(componentName)) {
for (const styleName in object[componentName]) {
if (object[componentName].hasOwnProperty(styleName)) {
targetObject[componentName][styleName] = object[componentName][styleName]; // eslint-disable-line no-param-reassign
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q44881
|
flattenInternal
|
train
|
function flattenInternal(output, element) {
if (element) {
element.forEach((obj) => {
if (Array.isArray(obj)) {
flattenInternal(output, obj);
} else {
output.push(obj);
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q44882
|
createMarkupOnPseudoClass
|
train
|
function createMarkupOnPseudoClass(pseudoClasses, id, disabled) {
return mapObject(pseudoClasses, (style, pseudoClass) => {
if (style && Object.keys(style).length > 0) {
const styleString = CSSPropertyOperations.createMarkupForStyles(style);
const styleWithImportant = styleString.replace(/;/g, ' !important;');
return disabled ?
`.${id}[disabled]:${pseudoClass} {${styleWithImportant}}` :
`.${id}:${pseudoClass} {${styleWithImportant}}`;
}
return undefined;
});
}
|
javascript
|
{
"resource": ""
}
|
q44883
|
filterFunc
|
train
|
function filterFunc(inputValue, optionValue) {
if (inputValue && optionValue) {
return optionValue.toLowerCase().indexOf(inputValue.toLowerCase()) > -1;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q44884
|
calculateStyling
|
train
|
function calculateStyling(node) {
const reactId = node.getAttribute('data-reactid');
// calculate the computed style only once it's not in the cache
if (!computedStyleCache[reactId]) {
// In order to work with legacy browsers the second paramter for pseudoClass
// has to be provided http://caniuse.com/#feat=getcomputedstyle
const computedStyle = window.getComputedStyle(node, null);
const boxSizing = (
computedStyle.getPropertyValue('box-sizing') ||
computedStyle.getPropertyValue('-moz-box-sizing') ||
computedStyle.getPropertyValue('-webkit-box-sizing')
);
let verticalPaddingSize = 0;
verticalPaddingSize = (
parseFloat(computedStyle.getPropertyValue('padding-bottom')) +
parseFloat(computedStyle.getPropertyValue('padding-top'))
);
let verticalBorderSize = 0;
verticalBorderSize = (
parseFloat(computedStyle.getPropertyValue('border-bottom-width')) +
parseFloat(computedStyle.getPropertyValue('border-top-width'))
);
const sizingStyle = stylesToCopy
.map(styleName => `${styleName}:${computedStyle.getPropertyValue(styleName)} !important`)
.join(';');
// store the style, vertical padding size, vertical border size and
// boxSizing inside the cache
computedStyleCache[reactId] = {
style: sizingStyle,
verticalPaddingSize,
verticalBorderSize,
boxSizing,
};
}
return computedStyleCache[reactId];
}
|
javascript
|
{
"resource": ""
}
|
q44885
|
sanitizeChildProps
|
train
|
function sanitizeChildProps(properties) {
const childProps = omit(properties, Object.keys(textInputPropTypes));
if (typeof properties.valueLink === 'object') {
childProps.value = properties.valueLink.value;
}
return childProps;
}
|
javascript
|
{
"resource": ""
}
|
q44886
|
isBuffer
|
train
|
function isBuffer(obj) {
return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
}
|
javascript
|
{
"resource": ""
}
|
q44887
|
copyFromBuffer
|
train
|
function copyFromBuffer(n, list) {
var ret = Buffer.allocUnsafe(n);
var p = list.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q44888
|
Hash
|
train
|
function Hash (blockSize, finalSize) {
this._block = Buffer$4.alloc(blockSize);
this._finalSize = finalSize;
this._blockSize = blockSize;
this._len = 0;
}
|
javascript
|
{
"resource": ""
}
|
q44889
|
write
|
train
|
function write(buffer, offs) {
for (var i = 2; i < arguments.length; i++) {
for (var j = 0; j < arguments[i].length; j++) {
buffer[offs++] = arguments[i].charAt(j);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q44890
|
crc32
|
train
|
function crc32(png, offs, size) {
var crc = -1;
for (var i = 4; i < size-4; i += 1) {
crc = _crc32[(crc ^ png[offs+i].charCodeAt(0)) & 0xff] ^ ((crc >> 8) & 0x00ffffff);
}
write(png, offs+size-4, byte4(crc ^ -1));
}
|
javascript
|
{
"resource": ""
}
|
q44891
|
searchText
|
train
|
async function searchText(node, callback, query, limit) {
var cursor = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '';
var desc = arguments[5];
var seen = {};
console.log('cursor', cursor, 'query', query, 'desc', desc);
var q = desc ? { '<': cursor, '-': desc } : { '>': cursor, '-': desc };
node.get({ '.': q, '%': 20 * 1000 }).once().map().on(function (value, key) {
console.log('searchText', value, key);
if (key.indexOf(query) === 0) {
if (typeof limit === 'number' && _Object$keys(seen).length >= limit) {
return;
}
if (seen.hasOwnProperty(key)) {
return;
}
if (value && _Object$keys(value).length > 1) {
seen[key] = true;
callback({ value: value, key: key });
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q44892
|
MediumClient
|
train
|
function MediumClient(options) {
this._enforce(options, ['clientId', 'clientSecret'])
this._clientId = options.clientId
this._clientSecret = options.clientSecret
this._accessToken = ""
}
|
javascript
|
{
"resource": ""
}
|
q44893
|
getResults
|
train
|
function getResults () {
return getHtmls(URLS).then(htmls => {
return getScrapersResults(SCRAPERS, URLS, htmls).then(results => results)
})
}
|
javascript
|
{
"resource": ""
}
|
q44894
|
getScrapersResults
|
train
|
function getScrapersResults (SCRAPERS, urls, htmls) {
return Promise.all(
SCRAPERS.map(SCRAPER => {
return getScraperResults(SCRAPER, urls, htmls).then(results => {
return {
name: SCRAPER.name,
results: results
}
})
})
)
}
|
javascript
|
{
"resource": ""
}
|
q44895
|
getScraperResults
|
train
|
function getScraperResults (SCRAPER, urls, htmls) {
return Promise.all(
urls.map((url, i) => {
const html = htmls[i]
const name = SCRAPER.name
const Module = require(name)
return SCRAPER.scrape(Module, url, html).then(metadata => {
return SCRAPER.normalize(metadata)
})
})
)
}
|
javascript
|
{
"resource": ""
}
|
q44896
|
getHtmls
|
train
|
function getHtmls (urls) {
return Promise.all(urls.map(url => got(url).then(res => res.body)))
}
|
javascript
|
{
"resource": ""
}
|
q44897
|
union
|
train
|
function union(xs, ys) {
var obj = {};
for (var i = 0; i < xs.length; i++) {
obj[xs[i]] = true;
}
for (var j = 0; j < ys.length; j++) {
obj[ys[j]] = true;
}
var keys = [];
for (var k in obj) {
if ({}.hasOwnProperty.call(obj, k)) {
keys.push(k);
}
}
keys.sort();
return keys;
}
|
javascript
|
{
"resource": ""
}
|
q44898
|
rangeFromIndexAndOffsets
|
train
|
function rangeFromIndexAndOffsets(i, before, after, length) {
return {
// Guard against the negative upper bound for lines included in the output.
from: i - before > 0 ? i - before : 0,
to: i + after > length ? length : i + after
};
}
|
javascript
|
{
"resource": ""
}
|
q44899
|
PREFIX
|
train
|
function PREFIX(operatorsParser, nextParser) {
let parser = P.lazy(() => {
return P.seq(operatorsParser, parser).or(nextParser);
});
return parser;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.