_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q46700
|
truncate
|
train
|
function truncate(arr, len) {
if (arr.length > len) {
arr.length = len;
return true;
}
}
|
javascript
|
{
"resource": ""
}
|
q46701
|
writeReduceForLoop
|
train
|
function writeReduceForLoop(t, path, reducePath, reduceRight) {
const reduceCall = reducePath.node;
const array = defineIdIfNeeded(t, reducePath.get('callee.object'), path);
const func = extractDynamicFuncIfNeeded(t, reducePath, path);
const acc = path.scope.generateUidIdentifier('acc');
const i = path.scope.generateUidIdentifier('i');
// Initialize the accumulator.
// let acc = arguments[1] || (reduceRight ? arr[arr.length - 1] : arr[0]);
const initVal = reduceCall.arguments[1] || arrayMember(t, array, 0, reduceRight);
path.insertBefore(t.VariableDeclaration('let', [
t.VariableDeclarator(acc, initVal),
]));
// Write the for loop.
const newReduceCall = t.callExpression(func, [
acc,
t.memberExpression(array, i, true),
i,
array,
]);
const forBody = t.blockStatement([
t.expressionStatement(
t.assignmentExpression('=', acc, newReduceCall)
),
]);
let initI;
if (!reduceCall.arguments[1]) {
initI = reduceRight ? arrayIndex(t, array, 1, true) : t.numericLiteral(1);
}
path.insertBefore(basicArrayForLoop(t, i, array, forBody, reduceRight, initI));
return acc;
}
|
javascript
|
{
"resource": ""
}
|
q46702
|
randomArray
|
train
|
function randomArray(size) {
const cache = arrayCaches[size];
return cache[Math.floor(Math.random() * cache.length)];
}
|
javascript
|
{
"resource": ""
}
|
q46703
|
json2md
|
train
|
function json2md(data, prefix, _type) {
prefix = prefix || ""
if (typeof data === "string" || typeof data === "number") {
return indento(data, 1, prefix)
}
let content = []
// Handle arrays
if (Array.isArray(data)) {
for (let i = 0; i < data.length; ++i) {
content.push(indento(json2md(data[i], "", _type), 1, prefix))
}
return content.join("\n")
} else {
let type = Object.keys(data)[0]
, func = converters[_type || type]
if (typeof func === "function") {
return indento(func(_type ? data : data[type], json2md), 1, prefix) + "\n"
}
throw new Error("There is no such converter: " + type)
}
}
|
javascript
|
{
"resource": ""
}
|
q46704
|
train
|
function() {
var muteControl = this.options.muted ? 'fa-volume-off' : 'fa-volume-up';
var playPauseControl = this.options.autoplay ? 'fa-pause' : 'fa-play';
var controlsHTML = ' \
<div class="controlsWrapper">\
<div class="valiant-progress-bar">\
<div style="width: 0;"></div><div style="width: 100%;"></div>\
</div>\
<div class="controls"> \
<a href="#" class="playButton button fa '+ playPauseControl +'"></a> \
<div class="audioControl">\
<a href="#" class="muteButton button fa '+ muteControl +'"></a> \
<div class="volumeControl">\
<div class="volumeBar">\
<div class="volumeProgress"></div>\
<div class="volumeCursor"></div>\
</div>\
</div>\
</div>\
<span class="timeLabel"></span> \
<a href="#" class="fullscreenButton button fa fa-expand"></a> \
</div> \
</div>\
';
$(this.element).append(controlsHTML, true);
$(this.element).append('<div class="timeTooltip">00:00</div>', true);
// hide controls if option is set
if(this.options.hideControls) {
$(this.element).find('.controls').hide();
}
// wire up controller events to dom elements
this.attachControlEvents();
}
|
javascript
|
{
"resource": ""
}
|
|
q46705
|
cacheUniformLocations
|
train
|
function cacheUniformLocations ( program, identifiers ) {
var i, l, id;
for( i = 0, l = identifiers.length; i < l; i ++ ) {
id = identifiers[ i ];
program.uniforms[ id ] = _gl.getUniformLocation( program, id );
}
}
|
javascript
|
{
"resource": ""
}
|
q46706
|
train
|
function() {
var factConj = '';
for(var key in this.causes) {
factConj += ' ^ ' + this.causes[key].toString().substring(1).replace(/,/g, '');
}
for(var key in this.operatorCauses) {
factConj += ' ^ ' + this.operatorCauses[key].toString().substring(1).replace(/,/g, '');
}
return factConj.substr(3) + ' -> ' + this.consequences.toString().substring(1).replace(/,/g, '');
}
|
javascript
|
{
"resource": ""
}
|
|
q46707
|
train
|
function(FeAdd, FeDel, F, R) {
var FiAdd = [], FiAddNew = [], additions, deletions,
Fe = Logics.getOnlyExplicitFacts(F), FiAddNew = [];
// Deletion
if(FeDel && FeDel.length) {
Fe = Logics.minus(Fe, FeDel);
}
// Insertion
if(FeAdd && FeAdd.length) {
Fe = Utils.uniques(Fe, FeAdd);
}
// Recalculation
do {
FiAdd = Utils.uniques(FiAdd, FiAddNew);
FiAddNew = Solver.evaluateRuleSet(R, Utils.uniques(Fe, FiAdd));
} while (!Logics.containsFacts(FiAdd, FiAddNew));
additions = Utils.uniques(FeAdd, FiAdd);
deletions = Logics.minus(F, Utils.uniques(Fe, FiAdd));
F = Utils.uniques(Fe, FiAdd);
return {
additions: additions,
deletions: deletions,
updatedF: F
};
}
|
javascript
|
{
"resource": ""
}
|
|
q46708
|
train
|
function (FeAdd, FeDel, F, R) {
var Rdel = [], Rred = [], Rins = [],
FiDel = [], FiAdd = [],
FiDelNew = [], FiAddNew = [],
superSet = [],
additions, deletions,
Fe = Logics.getOnlyExplicitFacts(F),
Fi = Logics.getOnlyImplicitFacts(F),
deferred = q.defer(),
startAlgorithm = function() {
overDeletionEvaluationLoop();
},
overDeletionEvaluationLoop = function() {
FiDel = Utils.uniques(FiDel, FiDelNew);
Rdel = Logics.restrictRuleSet(R, Utils.uniques(FeDel, FiDel));
Solver.evaluateRuleSet(Rdel, Utils.uniques(Utils.uniques(Fi, Fe), FeDel))
.then(function(values) {
FiDelNew = values.cons;
if (Utils.uniques(FiDel, FiDelNew).length > FiDel.length) {
overDeletionEvaluationLoop();
} else {
Fe = Logics.minus(Fe, FeDel);
Fi = Logics.minus(Fi, FiDel);
rederivationEvaluationLoop();
}
});
},
rederivationEvaluationLoop = function() {
FiAdd = Utils.uniques(FiAdd, FiAddNew);
Rred = Logics.restrictRuleSet(R, FiDel);
Solver.evaluateRuleSet(Rred, Utils.uniques(Fe, Fi))
.then(function(values) {
FiAddNew = values.cons;
if (Utils.uniques(FiAdd, FiAddNew).length > FiAdd.length) {
rederivationEvaluationLoop();
} else {
insertionEvaluationLoop();
}
});
},
insertionEvaluationLoop = function() {
FiAdd = Utils.uniques(FiAdd, FiAddNew);
superSet = Utils.uniques(Utils.uniques(Utils.uniques(Fe, Fi), FeAdd), FiAdd);
Rins = Logics.restrictRuleSet(R, superSet);
Solver.evaluateRuleSet(Rins, superSet)
.then(function(values) {
FiAddNew = values.cons;
if (!Utils.containsSubset(FiAdd, FiAddNew)) {
insertionEvaluationLoop();
} else {
additions = Utils.uniques(FeAdd, FiAdd);
deletions = Utils.uniques(FeDel, FiDel);
deferred.resolve({
additions: additions,
deletions: deletions
});
}
}).fail(function(err) {
console.error(err);
});
};
startAlgorithm();
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q46709
|
train
|
function(F) {
var validSet = [];
for (var i = 0; i < F.length; i++) {
if (F[i].isValid()) {
validSet.push(F[i]);
}
}
return validSet;
}
|
javascript
|
{
"resource": ""
}
|
|
q46710
|
train
|
function(fs, subset) {
for (var i = 0; i < fs.length; i++) {
for (var j = 0; j < subset.length; j++) {
if ((subset[j] !== undefined) && (fs[i].equivalentTo(subset[j]))) {
fs[i].causedBy = this.uniquesCausedBy(fs[i].causedBy, subset[j].causedBy);
fs[i].consequences = fs[i].consequences.concat(subset[j].consequences);
subset[j].doPropagate(fs[i]);
delete subset[j];
}
}
}
for (i = 0; i < subset.length; i++) {
if (subset[i] !== undefined) fs.push(subset[i]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46711
|
train
|
function(fs) {
var fR = [];
for (var key in fs) {
var fact = fs[key];
if(!fact.explicit) {
fR.push(fact);
}
}
return fR;
}
|
javascript
|
{
"resource": ""
}
|
|
q46712
|
train
|
function(rs, fs) {
var restriction = [];
for (var i = 0; i < rs.length; i++) {
var rule = rs[i], matches = false;
for (var j = 0; j < rule.causes.length; j++) {
var cause = rule.causes[j];
for (var k = 0; k < fs.length; k++) {
var fact = fs[k];
if (this.causeMatchesFact(cause, fact)) {
matches = true;
break;
}
}
if (matches) {
restriction.push(rule);
break;
}
}
}
return restriction;
}
|
javascript
|
{
"resource": ""
}
|
|
q46713
|
train
|
function(cause, fact) {
return this.causeMemberMatchesFactMember(cause.predicate, fact.predicate)
&& this.causeMemberMatchesFactMember(cause.subject, fact.subject)
&& this.causeMemberMatchesFactMember(cause.object, fact.object);
}
|
javascript
|
{
"resource": ""
}
|
|
q46714
|
train
|
function(atom1, atom2) {
if (this.isVariable(atom1) && this.isVariable(atom2) ) {
return true;
} else if(atom1 == atom2) {
return true;
} else {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46715
|
train
|
function(fs1, fs2) {
if(!fs2 || (fs2.length > fs1.length)) return false;
for (var key in fs2) {
var fact = fs2[key];
if(!(fact.appearsIn(fs1))) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q46716
|
train
|
function(_set1, _set2) {
var flagEquals,
newSet = [];
for (var i = 0; i < _set1.length; i++) {
flagEquals = false;
for(var j = 0; j < _set2.length; j++) {
if (_set1[i].asString == _set2[j].asString) {
flagEquals = true;
break;
}
}
if (!flagEquals) {
newSet.push(_set1[i]);
}
}
return newSet;
}
|
javascript
|
{
"resource": ""
}
|
|
q46717
|
train
|
function(req, res, next) {
var initialTime = req.query.time,
receivedReqTime = new Date().getTime(),
filename = req.params.filename,
absolutePathToFile = ontoDir + '/' + filename,
extension = path.extname(absolutePathToFile),
contentType = mime.contentType(extension);
if(contentType) {
req.mimeType = contentType.replace(/;.*/g, '');
} else {
req.mimeType = contentType;
}
req.requestDelay = receivedReqTime - initialTime;
fs.readFile(absolutePathToFile, function(err, data) {
if(err) {
res.status(500).send(err.toString());
} else {
req.rawOntology = data.toString().replace(/(&)([a-z0-9]+)(;)/gi, '$2:');
next();
};
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46718
|
train
|
function(req, res) {
if (req.headers.accept == 'application/json') {
res.header('Content-Type', 'application/json');
res.status(200).json({
data: {
ontologyTxt: req.rawOntology,
mimeType: req.mimeType
},
requestDelay: req.requestDelay,
serverTime: new Date().getTime()
});
} else {
res.header('Content-Type', req.mimeType);
res.status(200).send(req.rawOntology);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46719
|
train
|
function(req, res, next) {
var initialTime = 0,
receivedReqTime = new Date().getTime();
req.requestDelay = receivedReqTime - initialTime;
var url = req.body.url;
request.get(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
req.rawOntology = body.toString().replace(/(&)([a-z0-9]+)(;)/gi, '$2:');
next();
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46720
|
train
|
function(rs, facts, doTagging, resolvedImplicitFactSet) {
var deferred = q.defer(), promises = [], cons = [], filteredFacts;
for (var key in rs) {
if (doTagging) {
promises.push(this.evaluateThroughRestrictionWithTagging(rs[key], facts, resolvedImplicitFactSet));
} else {
promises.push(this.evaluateThroughRestriction(rs[key], facts));
}
}
try {
q.all(promises).then(function (consTab) {
for (var i = 0; i < consTab.length; i++) {
cons = cons.concat(consTab[i]);
}
deferred.resolve({cons: cons});
});
} catch(e) {
deferred.reject(e);
}
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q46721
|
train
|
function(rule, facts) {
var mappingList = this.getMappings(rule, facts),
consequences = [], deferred = q.defer();
try {
this.checkOperators(rule, mappingList);
for (var i = 0; i < mappingList.length; i++) {
if (mappingList[i]) {
// Replace mappings on all consequences
for (var j = 0; j < rule.consequences.length; j++) {
consequences.push(this.substituteFactVariables(mappingList[i], rule.consequences[j], [], rule));
}
}
}
deferred.resolve(consequences);
} catch(e) {
deferred.reject(e);
}
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q46722
|
train
|
function(rule, kb) {
var mappingList = this.getMappings(rule, kb), deferred = q.defer(),
consequences = [], consequence, causes, iterationConsequences;
this.checkOperators(rule, mappingList);
try {
for (var i = 0; i < mappingList.length; i++) {
if (mappingList[i]) {
// Replace mappings on all consequences
causes = Logics.buildCauses(mappingList[i].__facts__);
iterationConsequences = [];
for (var j = 0; j < rule.consequences.length; j++) {
consequence = this.substituteFactVariables(mappingList[i], rule.consequences[j], causes, rule);
//if (Logics.filterKnownOrAlternativeImplicitFact(consequence, kb, resolvedImplicitFacts)) {
consequences.push(consequence);
iterationConsequences.push(consequence);
//}
}
try {
Logics.addConsequences(mappingList[i].__facts__, iterationConsequences);
} catch(e) {
throw "Error when trying to add consequences on the implicit fact.";
}
}
}
deferred.resolve(consequences);
} catch(e) {
deferred.reject(e);
}
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q46723
|
train
|
function(currentCauses, nextCause, facts, constants, rule) {
var substitutedNextCauses = [],
mappings = [];
for (var i = 0; i < currentCauses.length; i++) {
for (var j = 0; j < facts.length; j++) {
// Get the mapping of the current cause ...
var mapping = currentCauses[i].mapping,
substitutedNextCause,
newMapping;
// ... or build a fresh one if it does not exist
if (mapping === undefined) {
mapping = {};
mapping.__facts__ = [];
}
// Update the mapping using pattern matching
newMapping = this.factMatches(facts[j], currentCauses[i], mapping, constants, rule);
// If the current fact matches the current cause ...
if (newMapping) {
// If there are other causes to be checked...
if (nextCause) {
// Substitute the next cause's variable with the new mapping
substitutedNextCause = this.substituteFactVariables(newMapping, nextCause);
substitutedNextCause.mapping = newMapping;
substitutedNextCauses.push(substitutedNextCause);
} else {
// Otherwise, add the new mapping to the global mapping array
mappings.push(newMapping);
}
}
}
}
if(nextCause) {
return substitutedNextCauses;
} else {
return mappings;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46724
|
train
|
function(fact, ruleFact, mapping, constants, rule) {
var localMapping = {};
// Checks and update localMapping if matches
if (!this.factElemMatches(fact.predicate, ruleFact.predicate, mapping, localMapping)) {
return false;
}
if (!this.factElemMatches(fact.object, ruleFact.object, mapping, localMapping)) {
return false;
}
if (!this.factElemMatches(fact.subject, ruleFact.subject, mapping, localMapping)) {
return false;
}
emitter.emit('rule-fired', rule.name);
// If an already existing uri has been mapped...
for (var key in localMapping) {
if(constants.indexOf(localMapping[key]) !== -1) {
return false;
}
}
// Merges local and global mapping
for (var mapKey in mapping) {
if (mapKey == '__facts__') {
localMapping[mapKey] = Utils.uniques(mapping[mapKey], [fact]);
} else {
for (key in localMapping) {
if (mapping[mapKey] == localMapping[key]) {
if (mapKey != key) {
return false;
}
}
}
localMapping[mapKey] = mapping[mapKey];
}
}
// The new mapping is updated
return localMapping;
}
|
javascript
|
{
"resource": ""
}
|
|
q46725
|
train
|
function(elem, mapping) {
if(Logics.isBNode(elem)) {
return Logics.skolemize(mapping.__facts__, elem);
} else if(Logics.isVariable(elem)) {
if (mapping[elem] !== undefined) {
return mapping[elem]
}
}
return elem;
}
|
javascript
|
{
"resource": ""
}
|
|
q46726
|
train
|
function(t, explicit, notUsingValid) {
if(explicit === undefined) {
explicit = true;
}
return new Fact(t.predicate.toString(), t.subject.toString(), t.object.toString()/*.format()*/, [], explicit, [], [], notUsingValid, t.toString())
}
|
javascript
|
{
"resource": ""
}
|
|
q46727
|
train
|
function(fact) {
var subject, predicate, object;
/*if (fact.fromTriple !== undefined) {
return fact.fromTriple;
}*/
if(fact.falseFact) {
return '';
}
subject = this.parseStrEntityToTurtle(fact.subject);
predicate = this.parseStrEntityToTurtle(fact.predicate);
object = this.parseStrEntityToTurtle(fact.object);
if (subject && predicate && object) {
return subject + ' ' + predicate + ' ' + object + ' . ';
} else {
return '';
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46728
|
train
|
function(facts) {
var ttl = '', fact,
that = this;
for (var i = 0; i < facts.length; i++) {
fact = facts[i];
ttl += that.factToTurtle(fact);
}
return ttl;
}
|
javascript
|
{
"resource": ""
}
|
|
q46729
|
train
|
function() {
var e, spo;
if(this.falseFact) {
spo = 'FALSE';
} else {
spo = '(' + Utils.removeBeforeSharp(this.subject) + ', ' + Utils.removeBeforeSharp(this.predicate) + ', ' + Utils.removeBeforeSharp(this.object) + ')'
}
this.explicit ? e = 'E' : e = 'I';
return e + spo;
}
|
javascript
|
{
"resource": ""
}
|
|
q46730
|
train
|
function(fact) {
if ((this.explicit != fact.explicit) ||
(this.subject != fact.subject) ||
(this.predicate != fact.predicate) ||
(this.object != fact.object)) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q46731
|
train
|
function(factSet) {
var that = this;
for (var key in factSet) {
if(that.equivalentTo(factSet[key])){
return key;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q46732
|
train
|
function() {
if (this.explicit) {
return this.valid;
} else if (this.causedBy === undefined || this.causedBy.length == 0) {
return undefined;
} else {
var valid,
causes = this.causedBy,
explicitFact;
for (var i = 0; i < causes.length; i++) {
valid = true;
for (var j = 0; j < causes[i].length; j++) {
explicitFact = causes[i][j];
valid = valid && explicitFact.valid;
}
if (valid) {
return true;
}
}
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46733
|
train
|
function(_set1, _set2) {
var hash = {}, uniq = [],
fullSet = _set1.concat(_set2);
for (var i = 0; i < fullSet.length; i++) {
if (fullSet[i] !== undefined) hash[fullSet[i].toString()] = fullSet[i];
}
for (var key in hash) {
uniq.push(hash[key]);
}
return uniq;
}
|
javascript
|
{
"resource": ""
}
|
|
q46734
|
Channel
|
train
|
function Channel (id, socket) {
var log = debug('webrtc-tree-overlay:channel(' + id + ')')
this._log = log
var self = this
this.id = id
this._socket = socket
.on('data', function (data) {
log('received data:')
log(data.toString())
var message = JSON.parse(data)
if (message.type === 'DATA') {
log('data: ' + message.data)
self.emit('data', message.data)
} else if (message.type === 'JOIN-REQUEST') {
log('join-request: ' + JSON.stringify(message))
self.emit('join-request', message)
} else {
throw new Error('Invalid message type on channel(' + id + ')')
}
})
.on('connect', function () {
self.emit('connect', self)
})
.on('close', function () {
log('closing')
self.emit('close')
})
.on('error', function (err) {
log(err.message)
log(err.stack)
})
}
|
javascript
|
{
"resource": ""
}
|
q46735
|
_getErrorCorrectLevel
|
train
|
function _getErrorCorrectLevel(ecl) {
switch (ecl) {
case "L":
return QRErrorCorrectLevel.L;
case "M":
return QRErrorCorrectLevel.M;
case "Q":
return QRErrorCorrectLevel.Q;
case "H":
return QRErrorCorrectLevel.H;
default:
throw new Error("Unknown error correction level: " + ecl);
}
}
|
javascript
|
{
"resource": ""
}
|
q46736
|
_getTypeNumber
|
train
|
function _getTypeNumber(content, ecl) {
var length = _getUTF8Length(content);
var type = 1;
var limit = 0;
for (var i = 0, len = QRCodeLimitLength.length; i <= len; i++) {
var table = QRCodeLimitLength[i];
if (!table) {
throw new Error("Content too long: expected " + limit + " but got " + length);
}
switch (ecl) {
case "L":
limit = table[0];
break;
case "M":
limit = table[1];
break;
case "Q":
limit = table[2];
break;
case "H":
limit = table[3];
break;
default:
throw new Error("Unknwon error correction level: " + ecl);
}
if (length <= limit) {
break;
}
type++;
}
if (type > QRCodeLimitLength.length) {
throw new Error("Content too long");
}
return type;
}
|
javascript
|
{
"resource": ""
}
|
q46737
|
_getUTF8Length
|
train
|
function _getUTF8Length(content) {
var result = encodeURI(content).toString().replace(/\%[0-9a-fA-F]{2}/g, 'a');
return result.length + (result.length != content ? 3 : 0);
}
|
javascript
|
{
"resource": ""
}
|
q46738
|
getShapeZero
|
train
|
function getShapeZero(x,y,options,modules){
var EOL = '\r\n';
var width = options.width;
var height = options.height;
var length = modules.length;
var style = options.style;
var xsize = width / (length + 2 * options.padding);
var ysize = height / (length + 2 * options.padding);
var px = (x * xsize + options.padding * xsize);
var py = (y * ysize + options.padding * ysize);
switch(options.style){
case 'square':
return '<rect x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
case 'circle':
return '<rect rx="'+xsize+'" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
case 'sharp-edge':
return '<rect transform="rotate(45 '+(px+xsize/2)+' '+(py+ysize/2)+')" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
case 'ninja':
return '<g transform="translate('+px+','+py+') scale('+1+','+1+')"><g transform="" style="fill: rgb(255, 0, 0);"><path d="M0,14V0c0,0,9.15,4.38,14,0.55C14,0.55,14.24,14,0,14z"/></g></g>'
}
}
|
javascript
|
{
"resource": ""
}
|
q46739
|
setupReqCounter
|
train
|
function setupReqCounter() {
reqCounter = reqCounter || new ReqCounter();
process.monitor.getRequestCount = function () {
return reqCounter._requests;
};
process.monitor.getTotalRequestCount = function () {
return reqCounter._totalRequests;
};
process.monitor.getTransferred = function () {
return reqCounter._transferred;
};
process.monitor.getOpenConnections = function () {
return reqCounter._connections;
};
}
|
javascript
|
{
"resource": ""
}
|
q46740
|
startLuxometerNotifications
|
train
|
function startLuxometerNotifications()
{
showMessage('Scanning...')
bleat.requestDevice(
{
filters:[{ name: 'CC2650 SensorTag' }]
})
.then(function(device)
{
showMessage('Found device: ' + device.name)
return device.gatt.connect()
})
.then(function(server)
{
gattServer = server
showMessage('Connected')
return gattServer.getPrimaryService(LUXOMETER_SERVICE)
})
.then(function(service)
{
// Get config characteristic.
luxometerService = service
return luxometerService.getCharacteristic(LUXOMETER_CONFIG)
})
.then(function(characteristic)
{
// Turn luxometer config to ON.
return characteristic.writeValue(new Uint8Array([1]))
})
.then(function()
{
// Get data characteristic.
return luxometerService.getCharacteristic(LUXOMETER_DATA)
})
.then(function(characteristic)
{
// Start sensor notification.
showMessage('Starting notfications')
characteristic.addEventListener('characteristicvaluechanged', onLuxometerChanged)
return characteristic.startNotifications()
})
.catch(function(error)
{
showMessage(error)
})
}
|
javascript
|
{
"resource": ""
}
|
q46741
|
onLuxometerChanged
|
train
|
function onLuxometerChanged(event)
{
var characteristic = event.target
var lux = calculateLux(characteristic.value)
showMessage('Luxometer value: ' + lux)
}
|
javascript
|
{
"resource": ""
}
|
q46742
|
calculateLux
|
train
|
function calculateLux(data)
{
// Get 16 bit value from data buffer in little endian format.
var value = data.getUint16(0, true)
// Extraction of luxometer value, based on sfloatExp2ToDouble
// from BLEUtility.m in Texas Instruments TI BLE SensorTag
// iOS app source code.
var mantissa = value & 0x0FFF
var exponent = value >> 12
var magnitude = Math.pow(2, exponent)
var output = (mantissa * magnitude)
var lux = output / 100.0
// Return result.
return lux
}
|
javascript
|
{
"resource": ""
}
|
q46743
|
findDevice
|
train
|
function findDevice()
{
disconnectDevice()
// Used for debugging/testing.
//scanForDevice()
//return
searchForBondedDevice({
name: 'HEXIWEAR',
serviceUUIDs: [INFO_SERVICE],
onFound: connectToDevice,
onNotFound: scanForDevice,
})
}
|
javascript
|
{
"resource": ""
}
|
q46744
|
searchForBondedDevice
|
train
|
function searchForBondedDevice(params)
{
console.log('Searching for bonded device')
evothings.ble.getBondedDevices(
// Success function.
function(devices)
{
for (var i in devices)
{
var device = devices[i]
if (device.name == params.name)
{
console.log('Found bonded device: ' + device.name)
params.onFound(device)
return // bonded device found
}
}
params.onNotFound()
},
// Error function.
function(error)
{
params.onNotFound()
},
{ serviceUUIDs: params.serviceUUIDs })
}
|
javascript
|
{
"resource": ""
}
|
q46745
|
getCanonicalUUIDArray
|
train
|
function getCanonicalUUIDArray(uuidArray)
{
var result = [];
for (var i in uuidArray)
{
result.push(exports.getCanonicalUUID(uuidArray[i]));
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q46746
|
littleEndianToUint32
|
train
|
function littleEndianToUint32(data, offset)
{
return (littleEndianToUint8(data, offset + 3) << 24) +
(littleEndianToUint8(data, offset + 2) << 16) +
(littleEndianToUint8(data, offset + 1) << 8) +
littleEndianToUint8(data, offset)
}
|
javascript
|
{
"resource": ""
}
|
q46747
|
littleEndianToInt8
|
train
|
function littleEndianToInt8(data, offset)
{
var x = littleEndianToUint8(data, offset)
if (x & 0x80) x = x - 256
return x
}
|
javascript
|
{
"resource": ""
}
|
q46748
|
gattServerCallbackHandler
|
train
|
function gattServerCallbackHandler(winFunc, settings) {
// collect read/write callbacks and add handles, so the native side can tell us which one to call.
var readCallbacks = {};
var writeCallbacks = {};
var nextHandle = 1;
function handleCallback(object, name, callbacks) {
if(!object[name]) {
throw name+" missing!";
}
callbacks[nextHandle] = object[name];
object[name+"Handle"] = nextHandle;
nextHandle += 1;
}
function handleReadWrite(object) {
/* // primitive version
if(!object.readRequestCallback) {
throw "readRequestCallback missing!");
}
readCallbacks[nextHandle] = object.readRequestCallback;
*/
handleCallback(object, "onReadRequest", readCallbacks);
handleCallback(object, "onWriteRequest", writeCallbacks);
}
for(var i=0; i<settings.services.length; i++) {
var service = settings.services[i];
for(var j=0; j<service.characteristics.length; j++) {
var characteristic = service.characteristics[j];
handleReadWrite(characteristic);
for(var k=0; k<characteristic.descriptors.length; k++) {
var descriptor = characteristic.descriptors[k];
handleReadWrite(descriptor);
}
}
}
settings.nextHandle = nextHandle;
return function(args) {
// primitive version
/*if(args.name == "win") {
winFunc();
return;
}*/
var funcs = {
win: winFunc,
connection: function() {
settings.onConnectionStateChange(args.deviceHandle, args.connected);
},
write: function() {
writeCallbacks[args.callbackHandle](args.deviceHandle, args.requestId, args.data);
},
read: function() {
readCallbacks[args.callbackHandle](args.deviceHandle, args.requestId);
},
};
funcs[args.name]();
};
}
|
javascript
|
{
"resource": ""
}
|
q46749
|
train
|
function (containerId) {
for (var property in winble.deviceManager.deviceList) {
if (winble.deviceManager.deviceList[property] && winble.deviceManager.deviceList[property].containerId == containerId)
return (winble.deviceManager.deviceList[property]);
}
return (null);
}
|
javascript
|
{
"resource": ""
}
|
|
q46750
|
train
|
function (deviceHandle, functionName, errorCallback) {
var device = winble.deviceManager.deviceList[deviceHandle];
if (device == null) {
var msg = "Could not find the requested device handle '" + deviceHandle + "'";
winble.logger.logError(functionName, msg);
errorCallback(winble.DEVICE_NOT_FOUND);
}
return (device);
}
|
javascript
|
{
"resource": ""
}
|
|
q46751
|
train
|
function (device, serviceHandle, functionName, errorCallback) {
var service = device.serviceList[serviceHandle];
if (service == null) {
var msg = "Could not find the requested service handle '" + serviceHandle + "'";
winble.logger.logError(functionName, msg);
errorCallback(msg);
}
return (service);
}
|
javascript
|
{
"resource": ""
}
|
|
q46752
|
train
|
function (device, charHandle, functionName, errorCallback) {
var characteristic = device.charList[charHandle];
if (characteristic == null) {
var msg = "Could not find the requested characteristic handle '" + charHandle + "'";
winble.logger.logError(functionName, msg);
errorCallback(msg);
}
return (characteristic);
}
|
javascript
|
{
"resource": ""
}
|
|
q46753
|
train
|
function (successCallback, errorCallback) {
if (!winble.deviceManager.isScanning) {
winble.deviceManager.scanSuccessCallback = successCallback;
winble.deviceManager.scanErrorCallback = errorCallback;
winble.deviceManager.isScanning = true;
setTimeout(function () {
winble.deviceManager.scanDevices(successCallback, errorCallback);
}, 500);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46754
|
train
|
function () {
if (winble.deviceManager.isScanning)
winble.deviceManager.isScanning = false;
if (winble.deviceManager.connectionWatcher !== null)
winble.deviceManager.stopConnectionWatcher();
}
|
javascript
|
{
"resource": ""
}
|
|
q46755
|
train
|
function (successCallback) {
// If the caller told us to stop scanning since our last scan, or all devices have been removed from the list, nothing to do
if (!winble.deviceManager.isScanning || (winble.deviceManager.reportList.length == 0)) {
winble.deviceManager.isReporting = false;
return;
}
// Report the next device in our list
var device = winble.deviceManager.getNextReportableDevice();
if (device != null) {
winble.logger.logDebug("reportNextDevice", "Reporting scan for " + device.gattDevice.name);
var deviceOut = {
"address": device.gattDevice.id,
"name": device.gattDevice.name,
"rssi": device.rssi,
"scanRecord": "" // Base64 string, iOS only
};
successCallback(deviceOut, { keepCallback: true });
}
// Set up the next report
setTimeout(function () {
winble.deviceManager.reportNextDevice(successCallback);
}, winble.deviceManager.REPORT_INTERVAL);
}
|
javascript
|
{
"resource": ""
}
|
|
q46756
|
train
|
function (successCallback, errorCallback, deviceId) {
// Find the requested device in our list of discovered devices
var device = winble.deviceManager.getDeviceFromId(deviceId, "connectToDevice", errorCallback);
if (device == null) {
errorCallback(winble.DEVICE_NOT_FOUND);
return;
}
// Save the success callback; we will need to call this whenever the connection status changes.
if (device.connectSuccessCallback == null)
device.connectSuccessCallback = successCallback;
// Call the success callback if the device is connected, error callback if not
if (device.isReachable && device.isConnected) {
winble.logger.logDebug("connectToDevice", "Connection successful");
var connectInfo = {
"deviceHandle": device.handle,
"state": 2 // 0 = Disconnected, 1 = Connecting, 2 = Connected, 3 = Disconnecting
};
device.connectSuccessCallback(connectInfo, { keepCallback: true });
} else {
winble.logger.logDebug("connectToDevice", "Connection failed");
errorCallback(winble.DEVICE_NOT_CONNECTED);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46757
|
train
|
function () {
winble.deviceManager.connectionWatcher = Windows.Devices.Enumeration.Pnp.PnpObject.createWatcher(
Windows.Devices.Enumeration.Pnp.PnpObjectType.deviceContainer,
["System.Devices.Connected"],
"");
winble.deviceManager.connectionWatcher.onupdated = winble.deviceManager.onDeviceConnectionUpdated;
winble.deviceManager.connectionWatcher.start();
}
|
javascript
|
{
"resource": ""
}
|
|
q46758
|
train
|
function (successCallback, errorCallback, deviceHandle) {
// Find the requested device in our list of discovered devices
var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "closeDevice", errorCallback);
if (device == null)
return;
// Remove the device from our list
winble.deviceManager.deviceList[deviceHandle] = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q46759
|
train
|
function (successCallback, errorCallback, deviceHandle) {
// Find the requested device in our list of discovered devices
var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "getDeviceRssi", errorCallback);
if (device == null)
return;
// Return the RSSI value
winble.logger.logDebug("getDeviceRssi", "Warning: Windows BLE does not currently provide RSSI");
successCallback(device.rssi);
}
|
javascript
|
{
"resource": ""
}
|
|
q46760
|
train
|
function (successCallback, errorCallback, deviceHandle) {
// Find the requested device in our list of discovered devices
var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "getDeviceServices", errorCallback);
if (device == null)
return;
// Enumerate the services
winble.bleDevice.fromIdAsync(device.gattDevice.id).done(
function (bleDevice) {
winble.logger.logDebug("getDeviceServices", "BluetoothLEDevice.fromIdAsync completed with success");
// Store the services and return an API-specified list to the caller
var serviceListOut = [];
for (var i = 0; i < bleDevice.gattServices.length; i++) {
// Add service internally to the device so we can retrieve it later by its handle
winble.logger.logDebug("getDeviceServices", "Found " + device.gattDevice.name + " service '" + bleDevice.gattServices[i].uuid + "'");
var serviceStore = {
"gattService": bleDevice.gattServices[i],
"handle": winble.nextGattHandle++
};
device.serviceList[serviceStore.handle] = serviceStore;
// Add service to return list
var serviceOut = {
"handle": serviceStore.handle,
"uuid": serviceStore.gattService.uuid,
"type": 0 // 0 = Primary, 1 = Secondary (Windows only returns primary services in the ble.gattServices list)
};
serviceListOut.push(serviceOut);
}
// Report the list of services back to the caller
successCallback(serviceListOut);
},
function (error) {
var msg = "BluetoothLEDevice.fromIdAsync('" + device.gattDevice.id + "') failed: " + error;
winble.logger.logError("getDeviceServices", msg);
errorCallback(msg);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46761
|
train
|
function (successCallback, errorCallback, deviceHandle, serviceHandle) {
winble.logger.logDebug("getServiceCharacteristics", "deviceHandle='" + deviceHandle + ", serviceHandle='" + serviceHandle + "'");
// Find the requested device in our list of discovered devices
var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "getServiceCharacteristics", errorCallback);
if (device == null)
return;
// Find the requested service in the device's list of services
var service = winble.deviceManager.getServiceFromHandle(device, serviceHandle, "getServiceCharacteristics", errorCallback);
if (service == null)
return;
// Enumerate the characteristics on this service
var charList = service.gattService.getAllCharacteristics();
// Store the characteristics and return an API-specified list to the caller
var charListOut = [];
for (var i = 0; i < charList.length; i++) {
// Add characteristic internally to the device so we can retrieve it later by its handle
winble.logger.logDebug("getServiceCharacteristics", "Found " + service.gattService.uuid + " characteristic '" + charList[i].uuid + "'");
var charStore = {
"gattChar": charList[i],
"handle": winble.nextGattHandle++
};
device.charList[charStore.handle] = charStore;
// Add characteristic to return list
var charOut = {
"handle": charStore.handle,
"uuid": charStore.gattChar.uuid,
// TODO: Not at all sure if this is right as Microsoft has 1 of 4 values in this field and iOS/Android
// TODO: have a bitfield, but see code in winble.deviceManager.permissionsFromProtectionLevel
// TODO: as I try to map Microsoft's number to a bitfield.
"permissions": winble.deviceManager.permissionsFromProtectionLevel(charStore.gattChar.protectionLevel),
"properties": charStore.gattChar.characteristicProperties, // Microsoft's bitfield matches the BLE 4.2 spec
"writeType": 3 // So (1+2), where 1: WRITE_TYPE_NO_RESPONSE, 2: WRITE_TYPE_DEFAULT, 4: WRITE_TYPE_SIGNED
};
charListOut.push(charOut);
}
// Report the list of characteristics back to the caller
successCallback(charListOut);
}
|
javascript
|
{
"resource": ""
}
|
|
q46762
|
train
|
function (successCallback, errorCallback, deviceHandle, charHandle) {
winble.logger.logDebug("getCharacteristicDescriptors", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'");
// Find the requested device in our list of discovered devices
var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "getCharacteristicDescriptors", errorCallback);
if (device == null)
return;
// Find the requested characteristic in the device's list of characteristics
var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "getCharacteristicDescriptors", errorCallback);
if (characteristic == null)
return;
// Enumerate the descriptors on this characteristic
var descList = characteristic.gattChar.getAllDescriptors();
// Store the descriptors and return an API-specified list to the caller
var descListOut = [];
for (var i = 0; i < descList.length; i++) {
// Add descriptor internally to the device so we can retrieve it later by its handle
winble.logger.logDebug("getCharacteristicDescriptors", "Found " + characteristic.gattChar.uuid + " descriptor '" + descList[i].uuid + "'");
var descStore = {
"gattDesc": descList[i],
"handle": winble.nextGattHandle++
};
device.descList[descStore.handle] = descStore;
// Add characteristic to return list
var charOut = {
"handle": descStore.handle,
"uuid": descStore.gattDesc.uuid,
// TODO: Not at all sure if this is right as Microsoft has 1 of 4 values in this field and iOS/Android
// TODO: have a bitfield, but see code in winble.deviceManager.permissionsFromProtectionLevel
// TODO: as I try to map Microsoft's number to a bitfield.
"permissions": winble.deviceManager.permissionsFromProtectionLevel(descStore.gattDesc.protectionLevel)
};
descListOut.push(charOut);
}
// Report the list of descriptors back to the caller
successCallback(descListOut);
}
|
javascript
|
{
"resource": ""
}
|
|
q46763
|
train
|
function (successCallback, errorCallback, deviceHandle, charHandle) {
winble.logger.logDebug("readCharacteristic", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'");
// Find the requested device in our list of discovered devices
var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "readCharacteristic", errorCallback);
if (device == null)
return;
// Find the requested characteristic in the device's list of characteristics
var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "readCharacteristic", errorCallback);
if (characteristic == null)
return;
// Read and return the data
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.bluetooth.genericattributeprofile.gattcharacteristic.readvalueasync.aspx
//characteristic.gattChar.readValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.uncached).done(
characteristic.gattChar.readValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.cached).done(
function (readResult) {
if (readResult.status == winble.gatt.GattCommunicationStatus.success) {
var dataOut = new Uint8Array(readResult.value.length);
var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(readResult.value);
dataReader.readBytes(dataOut);
winble.logger.logDebug("readCharacteristic", "gattChar.readValueAsync completed with success, returning '" + dataOut + "'");
successCallback(dataOut);
} else {
winble.logger.logDebug("readCharacteristic", "gattChar.readValueAsync completed with error");
var msg = "Read failed or device unreachable, GattCommunicationStatus = " + readResult.status;
winble.logger.logError("readCharacteristic", msg);
errorCallback(msg);
}
},
function (error) {
var msg = "gattChar.readValueAsync() failed: " + error;
winble.logger.logError("readCharacteristic", msg);
errorCallback(msg);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46764
|
train
|
function (successCallback, errorCallback, deviceHandle, charHandle, dataBuffer) {
winble.logger.logDebug("writeCharacteristic", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'");
// Find the requested device in our list of discovered devices
var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "writeCharacteristic", errorCallback);
if (device == null)
return;
// Find the requested characteristic in the device's list of characteristics
var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "writeCharacteristic", errorCallback);
if (characteristic == null)
return;
// Write the data. The incoming buffer is and ArrayBuffer, and the writeValueAsync() function takes an iBuffer as its
// parameter, so we need to do some conversion here.
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.cryptographicbuffer.createfrombytearray
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.bluetooth.genericattributeprofile.gattcharacteristic.readvalueasync.aspx
var data = new Uint8Array(dataBuffer);
var dataOut = Windows.Security.Cryptography.CryptographicBuffer.createFromByteArray(data);
var writeOption;
if (characteristic.gattChar.characteristicProperties & winble.gatt.GattCharacteristicProperties.writeWithoutResponse)
writeOption = winble.gatt.GattWriteOption.writeWithoutResponse;
else
writeOption = winble.gatt.GattWriteOption.writeWithResponse;
characteristic.gattChar.writeValueAsync(dataOut, writeOption).done(
function (commStatus) {
if (commStatus == winble.gatt.GattCommunicationStatus.success) {
winble.logger.logDebug("writeCharacteristic", "gattChar.writeValueAsync completed with success");
successCallback();
} else {
winble.logger.logDebug("writeCharacteristic", "gattChar.writeValueAsync completed with error");
var msg = "Write failed or device unreachable, GattCommunicationStatus = " + commStatus;
winble.logger.logError("writeCharacteristic", msg);
errorCallback(msg);
}
},
function (error) {
var msg = "gattChar.writeValueAsync() failed: " + error;
winble.logger.logError("writeCharacteristic", msg);
errorCallback(msg);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46765
|
train
|
function (successCallback, errorCallback, deviceHandle, descHandle, dataBuffer) {
winble.logger.logDebug("writeDescriptor", "deviceHandle='" + deviceHandle + ", descHandle='" + descHandle + "'");
// Find the requested device in our list of discovered devices
var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "writeDescriptor", errorCallback);
if (device == null)
return;
// Find the requested descriptor in the device's list of descriptors
var descriptor = winble.deviceManager.getDescriptorFromHandle(device, descHandle, "writeDescriptor", errorCallback);
if (descriptor == null)
return;
// Write the data. The incoming buffer is and ArrayBuffer, and the writeValueAsync() function takes an iBuffer as its
// parameter, so we need to do some conversion here.
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.cryptographicbuffer.createfrombytearray
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.bluetooth.genericattributeprofile.gattdescriptor.writevalueasync.aspx
var data = new Uint8Array(dataBuffer);
var dataOut = Windows.Security.Cryptography.CryptographicBuffer.createFromByteArray(data);
descriptor.gattDesc.writeValueAsync(dataOut).done(
function (commStatus) {
if (commStatus == winble.gatt.GattCommunicationStatus.success) {
winble.logger.logDebug("writeDescriptor", "gattDesc.writeValueAsync completed with success");
successCallback();
} else {
winble.logger.logDebug("writeDescriptor", "gattDesc.writeValueAsync completed with error");
var msg = "Write failed or device unreachable, GattCommunicationStatus = " + commStatus;
winble.logger.logError("writeDescriptor", msg);
errorCallback(msg);
}
},
function (error) {
var msg = "gattDesc.writeValueAsync() failed: " + error;
winble.logger.logError("writeDescriptor", msg);
errorCallback(msg);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46766
|
train
|
function (successCallback, errorCallback, deviceHandle, charHandle) {
winble.logger.logDebug("enableCharacteristicNotification", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'");
// Find the requested device in our list of discovered devices
var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "enableCharacteristicNotification", errorCallback);
if (device == null)
return;
// Find the requested characteristic in the device's list of characteristics
var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "enableCharacteristicNotification", errorCallback);
if (characteristic == null)
return;
// Make sure this characteristic supports sending of notifications, notify caller if not.
if (!(characteristic.gattChar.characteristicProperties & winble.gatt.GattCharacteristicProperties.notify)) {
var msg = "This characteristic does not support notifications";
winble.logger.logDebug("enableCharacteristicNotification", msg);
errorCallback(msg);
return;
}
// Create callback to handle notifications; here we will get the new value into a UTF8 buffer and send it to the caller
characteristic.onValueChanged = function (args) {
winble.logger.logDebug("enableCharacteristicNotification", "** Windows called our callback! **");
var data = Uint8Array(args.characteristicValue.length);
Windows.Storage.Streams.DataReader.fromBuffer(args.characteristicValue).readBytes(data);
successCallback(data, { keepCallback: true });
};
// Register the callback
try {
characteristic.gattChar.addEventListener("valuechanged", characteristic.onValueChanged, false);
} catch (e) {
var msg = "Could not add event listener:" + e;
winble.logger.logError("enableCharacteristicNotification", msg);
errorCallback(msg);
return;
}
// Tell the characteristic to start sending us notifications.
// In order to avoid unnecessary communication with the device, first determine if the device is already
// correctly configured to send notifications. By default ReadClientCharacteristicConfigurationDescriptorAsync
// will attempt to get the current value from the system cache, so physical communication with the device
// is not typically required.
characteristic.gattChar.readClientCharacteristicConfigurationDescriptorAsync().then(
function (currentDescriptorValue) {
// No need to configure characteristic to send notifications if it's already configured
if ((currentDescriptorValue.status !== winble.gatt.GattCommunicationStatus.success) ||
(currentDescriptorValue.clientCharacteristicConfigurationDescriptor !==
winble.gatt.GattClientCharacteristicConfigurationDescriptorValue.notify)) {
// Set the Client Characteristic Configuration Descriptor to enable the device to send
// notifications when the Characteristic value changes.
winble.logger.logDebug("enableCharacteristicNotification", "Configuring characteristic for notifications");
characteristic.gattChar.writeClientCharacteristicConfigurationDescriptorAsync(
winble.gatt.GattClientCharacteristicConfigurationDescriptorValue.notify).then(
function (commStatus) {
if (commStatus == winble.gatt.GattCommunicationStatus.success) {
winble.logger.logDebug("enableCharacteristicNotification", "gattChar.writeClientCharacteristicConfigurationDescriptorAsync completed with success");
} else {
var msg = "Could not configure characteristic for notifications, device unreachable. GattCommunicationStatus = " + commStatus;
winble.logger.logError("enableCharacteristicNotification", "enableCharacteristicNotification", msg);
errorCallback(msg);
}
});
} else {
winble.logger.logDebug("enableCharacteristicNotification", "Characteristic is already configured for notifications");
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q46767
|
train
|
function (successCallback, errorCallback, deviceHandle, charHandle) {
winble.logger.logDebug("disableCharacteristicNotification", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'");
// Find the requested device in our list of discovered devices
var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "disableCharacteristicNotification", errorCallback);
if (device == null)
return;
// Find the requested characteristic in the device's list of characteristics
var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "disableCharacteristicNotification", errorCallback);
if (characteristic == null)
return;
// Unregister the callback
try {
characteristic.gattChar.removeEventListener("valuechanged", characteristic.onValueChanged, false);
} catch (e) {
var msg = "Could not remove event listener:" + e;
winble.logger.logError("disableCharacteristicNotification", msg);
errorCallback(msg);
return;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46768
|
arrayToUUID
|
train
|
function arrayToUUID(array, offset)
{
var k=0;
var string = '';
var UUID_format = [4, 2, 2, 2, 6];
for (var l=0; l<UUID_format.length; l++)
{
if (l != 0)
{
string += '-';
}
for (var j=0; j<UUID_format[l]; j++, k++)
{
string += evothings.util.toHexString(array[offset+k], 1);
}
}
return string;
}
|
javascript
|
{
"resource": ""
}
|
q46769
|
train
|
function(connectInfo)
{
// DEBUG LOG
console.log('BLE connect state: ' + connectInfo.state);
if (connectInfo.state == 2) // connected
{
device.deviceHandle = connectInfo.deviceHandle;
device.__uuidMap = {};
device.__serviceMap = {};
device.__isConnected = true;
internal.connectedDevices[device.address] = device;
success(device);
}
else if (connectInfo.state == 0) // disconnected
{
device.__isConnected = false;
internal.connectedDevices[device.address] = null;
// TODO: Perhaps this should be redesigned, as disconnect is
// more of a status change than an error? What do you think?
fail && fail(evothings.easyble.error.DISCONNECTED);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q46770
|
train
|
function(errorCode)
{
// DEBUG LOG
console.log('BLE connect error: ' + errorCode);
// Set isConnected to false on error.
device.__isConnected = false;
internal.connectedDevices[device.address] = null;
fail(errorCode);
}
|
javascript
|
{
"resource": ""
}
|
|
q46771
|
draggable
|
train
|
function draggable(e) {
e.preventDefault();
previousEvent = e;
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', removeDrag);
}
|
javascript
|
{
"resource": ""
}
|
q46772
|
buildPreviewUrl
|
train
|
function buildPreviewUrl (pose, scale, gender, style, rotation, traits, outfit) {
// use string templating to build the url
let url = `${basePreviewUrl}${pose}?scale=${scale}&gender=${gender}&style=${style}`
url += `&rotation=${rotation}${mapTraits(traits).join("")}&outfit=${outfit}`
return url;
}
|
javascript
|
{
"resource": ""
}
|
q46773
|
buildFriendmojiUrl
|
train
|
function buildFriendmojiUrl (comicId, avatarId1, avatarId2, transparent, scale) {
return `${baseCpanelUrl}${comicId}-${avatarId1}-${avatarId2}-v3.png?transparent=${transparent}&scale=${scale}`;
}
|
javascript
|
{
"resource": ""
}
|
q46774
|
structureResolve
|
train
|
function structureResolve(resolve, sPathStartWith) {
var aToResolve = [];
var aResolved = [];
if (typeof resolve === 'object' && resolve instanceof Array) {
aToResolve = resolve;
} else if (typeof resolve === 'string') {
aToResolve.push(resolve);
} else {
return null;
}
// resolve
aToResolve.forEach(function (item) {
var aSplit = item.split('/');
for (var i = 0; i < aSplit.length; i++) {
var aConc = aSplit.slice(0, i + 1);
var sConc = (aConc.length > 1) ? aConc.join('/') : aConc[0];
if (sConc.length > 0) {
aResolved.push({
type: (i < (aSplit.length - 1)) ? OBJECT_TYPE.folder : OBJECT_TYPE.file,
id: (sConc.charAt(0) !== sPathStartWith) ? sPathStartWith + sConc : sConc
});
}
}
});
// remove dups
aResolved = aResolved.sort(function (sVal1, sVal2) {
var sA = JSON.stringify(sVal1);
var sB = JSON.stringify(sVal2);
if (sA === sB) {
return 0;
} else if (sA <= sB) {
return -1;
} else {
return 1;
}
})
.filter(function (oItem, iPos) {
if (iPos > 0) {
return JSON.stringify(aResolved[iPos - 1]) !== JSON.stringify(oItem);
} else {
return true;
}
});
return aResolved;
}
|
javascript
|
{
"resource": ""
}
|
q46775
|
splitIntoPathAndObject
|
train
|
function splitIntoPathAndObject(sValue) {
var aValues = sValue.split('/');
var sObject = aValues.pop();
var sPath = aValues.join('/');
if (sPath.length > 0 && sPath.charAt(0) !== '/') {
sPath = '/' + sPath;
}
return {
path: sPath,
obj: sObject
};
}
|
javascript
|
{
"resource": ""
}
|
q46776
|
Transports
|
train
|
function Transports(oOptions, oLogger) {
this._client = new AdtClient(oOptions.conn, oOptions.auth, undefined, oLogger);
}
|
javascript
|
{
"resource": ""
}
|
q46777
|
stringToFlockFlags
|
train
|
function stringToFlockFlags(flag) {
// Only mess with strings
if (typeof flag !== 'string') {
return flag;
}
switch (flag) {
case 'sh':
return binding.LOCK_SH;
case 'ex':
return binding.LOCK_EX;
case 'shnb':
return binding.LOCK_SH | binding.LOCK_NB;
case 'exnb':
return binding.LOCK_EX | binding.LOCK_NB;
case 'un':
return binding.LOCK_UN;
default:
throw new Error('Unknown flock flag: ' + flag);
}
}
|
javascript
|
{
"resource": ""
}
|
q46778
|
stringToFcntlFlags
|
train
|
function stringToFcntlFlags(flag) {
if (typeof flag !== 'string') {
return flag;
}
switch (flag) {
case 'getfd':
return binding.F_GETFD;
case 'setfd':
return binding.F_SETFD;
case 'setlk':
return binding.F_SETLK;
case 'setlkw':
return binding.F_SETLKW;
case 'getlk':
return binding.F_GETLK;
default:
throw new Error('Unknown fcntl flag: ' + flag);
}
}
|
javascript
|
{
"resource": ""
}
|
q46779
|
getCurrentFileSize
|
train
|
function getCurrentFileSize(counter, timeout, cb) {
var fd = fs.openSync(__filename, 'r');
console.log("Trying to aquire lock for the %s time", counter);
fs.flock(fd, 'exnb', function(err) {
if (err) {
return console.log("Couldn't lock file", counter);
}
console.log('Aquired lock', counter);
// unlock after `timeout`
setTimeout(function() {
fs.flock(fd, 'un', function(err) {
if (err) {
return console.log("Couldn't unlock file", counter);
}
if (cb) { cb(); }
});
}, timeout);
});
}
|
javascript
|
{
"resource": ""
}
|
q46780
|
createClusters
|
train
|
function createClusters(units, distanceApart = 15.0) {
const squaredDistanceApart = distanceApart * distanceApart;
return units.reduce((clusters, u) => {
const isGeyser = vespeneGeyserTypes.includes(u.unitType);
/**
* @type {{ distance: number, target: Cluster }}
*/
const { distance, target } = clusters.reduce((acc, b) => {
const d = distanceSquared(u.pos, b.centroid);
if (d < acc.distance) {
return { distance: d, target: b };
} else {
return acc;
}
}, { distance: Infinity, target: null });
if (distance > squaredDistanceApart) {
return clusters.concat([{
centroid: u.pos,
mineralFields: isGeyser ? [] : [u],
vespeneGeysers: isGeyser ? [u] : [],
}]);
} else {
if (isGeyser) {
target.vespeneGeysers = [...target.vespeneGeysers, u];
} else {
target.mineralFields = [...target.mineralFields, u];
}
const size = target.mineralFields.length + target.vespeneGeysers.length;
target.centroid = divide(add(multiply(target.centroid, (size - 1)), u.pos), size);
return clusters;
}
}, []);
}
|
javascript
|
{
"resource": ""
}
|
q46781
|
clusterByNeighbor
|
train
|
function clusterByNeighbor(points) {
const sorted = points.slice().sort((a, b) => {
if (a.y < b.y) {
return -1;
} else if (a.y > b.y) {
return 1;
} else {
if (a.x < b.x) {
return -1;
} else if (a.x > b.x) {
return 1;
} else {
return 0;
}
}
});
const cluster = sorted.reduce((sets, point) => {
const setContainingNeighbors = sets.find(set => set.some((setPoint) => {
return getNeighbors(setPoint).some(spn => areEqual(spn, point));
}));
if (setContainingNeighbors) {
setContainingNeighbors.push(point);
} else {
sets.push([point]);
}
return sets;
}, []);
return cluster;
}
|
javascript
|
{
"resource": ""
}
|
q46782
|
distanceAAShapes
|
train
|
function distanceAAShapes(shapeA, shapeB) {
const dx = Math.max(Math.abs(shapeA.pos.x - shapeB.pos.x) - ((shapeA.w / 2) + (shapeB.w / 2)), 0);
const dy = Math.max(Math.abs(shapeA.pos.y - shapeB.pos.y) - ((shapeA.h / 2) + (shapeB.h / 2)), 0);
return Math.sqrt(dx * dx + dy * dy);
}
|
javascript
|
{
"resource": ""
}
|
q46783
|
distanceAAShapeAndPoint
|
train
|
function distanceAAShapeAndPoint(shape, point) {
const dx = Math.max(Math.abs(shape.pos.x - point.x) - (shape.w / 2), 0);
const dy = Math.max(Math.abs(shape.pos.y - point.y) - (shape.h / 2), 0);
return Math.sqrt(dx * dx + dy * dy);
}
|
javascript
|
{
"resource": ""
}
|
q46784
|
subtract
|
train
|
function subtract(point, rhs) {
if (typeof rhs === 'number') {
return {
x: point.x - rhs,
y: point.y - rhs,
};
} else {
return {
x: point.x - rhs.x,
y: point.y - rhs.y,
};
}
}
|
javascript
|
{
"resource": ""
}
|
q46785
|
multiply
|
train
|
function multiply(point, rhs) {
if (typeof rhs === 'number') {
return {
x: point.x * rhs,
y: point.y * rhs,
};
} else {
return {
x: point.x * rhs.x,
y: point.y * rhs.y,
};
}
}
|
javascript
|
{
"resource": ""
}
|
q46786
|
divide
|
train
|
function divide(point, rhs) {
if (typeof rhs === 'number') {
return {
x: point.x / rhs,
y: point.y / rhs,
};
} else {
return {
x: point.x / rhs.x,
y: point.y / rhs.y,
};
}
}
|
javascript
|
{
"resource": ""
}
|
q46787
|
proxyRecursive
|
train
|
function proxyRecursive(replicant, value, path) {
if (typeof value === 'object' && value !== null) {
let p;
assertSingleOwner(replicant, value);
// If "value" is already a Proxy, don't re-proxy it.
if (proxySet.has(value)) {
p = value;
const metadata = proxyMetadataMap.get(value);
metadata.path = path; // Update the path, as it may have changed.
} else if (metadataMap.has(value)) {
const metadata = metadataMap.get(value);
p = metadata.proxy;
metadata.path = path; // Update the path, as it may have changed.
} else {
const handler = Array.isArray(value) ? CHILD_ARRAY_HANDLER : CHILD_OBJECT_HANDLER;
p = new Proxy(value, handler);
proxySet.add(p);
const metadata = {
replicant,
path,
proxy: p
};
metadataMap.set(value, metadata);
proxyMetadataMap.set(p, metadata);
}
for (const key in value) {
/* istanbul ignore if */
if (!{}.hasOwnProperty.call(value, key)) {
continue;
}
const escapedKey = key.replace(/\//g, '~1');
if (path) {
const joinedPath = joinPathParts(path, escapedKey);
value[key] = proxyRecursive(replicant, value[key], joinedPath);
} else {
value[key] = proxyRecursive(replicant, value[key], escapedKey);
}
}
return p;
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q46788
|
assertSingleOwner
|
train
|
function assertSingleOwner(replicant, value) {
let metadata;
if (proxySet.has(value)) {
metadata = proxyMetadataMap.get(value);
} else if (metadataMap.has(value)) {
metadata = metadataMap.get(value);
} else {
// If there's no metadata for this value, then it doesn't belong to any Replicants yet,
// and we're okay to continue.
return;
}
if (metadata.replicant !== replicant) {
/* eslint-disable function-paren-newline */
throw new Error(
`This object belongs to another Replicant, ${metadata.replicant.namespace}::${metadata.replicant.name}.` +
`\nA given object cannot belong to multiple Replicants. Object value:\n${JSON.stringify(value, null, 2)}`
);
/* eslint-enable function-paren-newline */
}
}
|
javascript
|
{
"resource": ""
}
|
q46789
|
waitFor
|
train
|
function waitFor(stream) {
return new Promise((resolve, reject) => {
stream.on('end', resolve);
stream.on('error', reject);
});
}
|
javascript
|
{
"resource": ""
}
|
q46790
|
declare
|
train
|
function declare(name, namespace, opts) {
// Delay requiring the Replicant class until here, otherwise cryptic errors are thrown. Not sure why!
const Replicant = require('./replicant');
return new Replicant(name, namespace, opts);
}
|
javascript
|
{
"resource": ""
}
|
q46791
|
assign
|
train
|
function assign(replicant, value) {
const oldValue = replicant.value;
replicant._ignoreProxy = true;
replicant.__value = shared._proxyRecursive(replicant, value, '/');
replicant._ignoreProxy = false;
replicant.revision++;
replicant.emit('change', value, oldValue);
replicant.log.replicants('Assigned:', value);
emitToClients(replicant.namespace, 'replicant:assignment', {
name: replicant.name,
namespace: replicant.namespace,
newValue: value,
revision: replicant.revision
});
saveReplicant(replicant);
}
|
javascript
|
{
"resource": ""
}
|
q46792
|
applyOperations
|
train
|
function applyOperations(replicant, operations) {
const oldValue = clone(replicant.value);
operations.forEach(operation => shared.applyOperation(replicant, operation));
replicant.revision++;
replicant.emit('change', replicant.value, oldValue, operations);
emitToClients(replicant.namespace, 'replicant:operations', {
name: replicant.name,
namespace: replicant.namespace,
revision: replicant.revision,
operations
});
saveReplicant(replicant);
}
|
javascript
|
{
"resource": ""
}
|
q46793
|
find
|
train
|
function find(name, namespace) {
// If there are no replicants for that namespace, return undefined
if (!{}.hasOwnProperty.call(declaredReplicants, namespace)) {
return undefined;
}
// If that replicant doesn't exist for that namespace, return undefined
if (!{}.hasOwnProperty.call(declaredReplicants[namespace], name)) {
return undefined;
}
// Return the replicant.
return declaredReplicants[namespace][name];
}
|
javascript
|
{
"resource": ""
}
|
q46794
|
findOrDeclare
|
train
|
function findOrDeclare(name, namespace, opts) {
const existingReplicant = find(name, namespace);
if (typeof existingReplicant !== 'undefined') {
return existingReplicant;
}
return declare(name, namespace, opts);
}
|
javascript
|
{
"resource": ""
}
|
q46795
|
emitToClients
|
train
|
function emitToClients(namespace, eventName, data) {
// Emit to clients (in the given namespace's room) using Socket.IO
log.replicants('emitting %s to %s:', eventName, namespace, data);
io.to(`replicant:${namespace}`).emit(eventName, data);
}
|
javascript
|
{
"resource": ""
}
|
q46796
|
resetBackoffTimer
|
train
|
function resetBackoffTimer() {
clearTimeout(backoffTimer);
backoffTimer = setTimeout(() => {
backoffTimer = null;
for (const bundleName in hasChanged) {
/* istanbul ignore if: Standard hasOwnProperty check, doesn't need to be tested */
if (!{}.hasOwnProperty.call(hasChanged, bundleName)) {
continue;
}
log.debug('Backoff finished, emitting change event for', bundleName);
handleChange(bundleName);
}
hasChanged = {};
}, 500);
}
|
javascript
|
{
"resource": ""
}
|
q46797
|
isPanelHTMLFile
|
train
|
function isPanelHTMLFile(bundleName, filePath) {
const bundle = module.exports.find(bundleName);
if (bundle) {
return bundle.dashboard.panels.some(panel => {
return panel.path.endsWith(filePath);
});
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q46798
|
isManifest
|
train
|
function isManifest(bundleName, filePath) {
return path.dirname(filePath).endsWith(bundleName) && path.basename(filePath) === 'package.json';
}
|
javascript
|
{
"resource": ""
}
|
q46799
|
_wrapAcknowledgement
|
train
|
function _wrapAcknowledgement(ack) {
let handled = false;
const wrappedAck = function (firstArg, ...restArgs) {
if (handled) {
throw new Error('Acknowledgement already handled');
}
handled = true;
if (isError(firstArg)) {
firstArg = serializeError(firstArg);
}
ack(firstArg, ...restArgs);
};
Object.defineProperty(wrappedAck, 'handled', {
get() {
return handled;
}
});
return wrappedAck;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.