_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q40100 | reduceBundles | train | function reduceBundles(bundles, dependencies, maxBundles) {
while (anyMainExceedsMaxBundles(bundles, maxBundles)) {
var merge = findLeastCostMerge(bundles, dependencies, maxBundles);
mergeBundles(merge.bundle1Name, merge.bundle2Name, bundles);
}
return bundles;
} | javascript | {
"resource": ""
} |
q40101 | resolve | train | function resolve(files, opts) {
var fn = opts.filter || function(fp) {
return true;
};
if (opts.realpath === true) {
return files.filter(fn);
}
var len = files.length;
var idx = -1;
var res = [];
while (++idx < len) {
var fp = path.resolve(opts.cwd, files[idx]);
if (!fn(fp) || ~res.indexOf(fp)) continue;
res.push(fp);
}
return res;
} | javascript | {
"resource": ""
} |
q40102 | getPsInfo | train | function getPsInfo(param, callback) {
if (process.platform === 'windows') return;
var pid = param.pid;
var cmd = "ps auxw | grep " + pid + " | grep -v 'grep'";
//var cmd = "ps auxw | grep -E '.+?\\s+" + pid + "\\s+'" ;
exec(cmd, function(err, output) {
if (!!err) {
if (err.code === 1) {
console.log('the content is null!');
} else {
console.error('getPsInfo failed! ' + err.stack);
}
callback(err, null);
return;
}
format(param, output, callback);
});
} | javascript | {
"resource": ""
} |
q40103 | browserifyTransform | train | function browserifyTransform(file) {
var chunks = [];
var write = function(buffer) {
chunks.push(buffer);
};
var end = function() {
var content = Buffer.concat(chunks).toString('utf8');
// convention fileName == key for shim options
var fileName = file.match(/([^\/]+)(?=\.\w+$)/)[0];
this.queue(commonjsify(content, options[fileName]));
this.queue(null);
};
return through(write, end);
} | javascript | {
"resource": ""
} |
q40104 | train | function (cwd, filename, options, customizeEngine) {
var helpers = customizeEngine.engine.helpers
var code = helpers.example(path.join(cwd, filename), {
hash: {
snippet: true
}
})
var result = helpers.exec(`node ${filename}`, {
hash: {
cwd: cwd,
lang: 'raw'
}
})
return Q.all([code,result]).spread(function(code, result) {
console.log(result)
var output = result.split('\u0001')
return code.replace(/console\.log\-output/g, function() {
return output.shift().trim();
})
})
} | javascript | {
"resource": ""
} | |
q40105 | NetworkServer | train | function NetworkServer(server) {
this.server = server;
function connection(socket) {
server.connection(socket, this);
}
this.on('connection', connection);
} | javascript | {
"resource": ""
} |
q40106 | listen | train | function listen(file, perm) {
var args = [file]
, perm = perm || 0700
, server = this;
this.file = file;
this.name = path.basename(file);
if(this.name === file) {
file = path.join(process.cwd(), file);
}
function onListen() {
try {
fs.chmodSync(file, perm);
}catch(e){}
log.notice('accepting connections at %s', file);
}
args.push(onListen);
// jump through some hoops for stale sockets
server.on('error', function (e) {
if(e.code == 'EADDRINUSE') {
var client = new net.Socket();
// handle error trying to talk to server
client.on('error', function(e) {
// no other server listening
if(e.code == 'ECONNREFUSED') {
fs.unlinkSync(file);
TcpServer.prototype.listen.apply(server, args);
}
});
client.connect({path: file}, function() {
// exit with original EADDRINUSE
throw e;
});
}
});
Server.prototype.listen.apply(server, args);
} | javascript | {
"resource": ""
} |
q40107 | close | train | function close() {
log.notice('removing the unix socket file')
try {
fs.unlinkSync(file);
}catch(e){} // nothing to do at this point
Server.prototype.close.call(this);
} | javascript | {
"resource": ""
} |
q40108 | train | function (next) {
request(url, function (err, res, body) {
if (err) {
return next(err);
}
next(null, body);
});
} | javascript | {
"resource": ""
} | |
q40109 | train | function (body, next) {
fs.writeFile(out + "/" + path.basename(url), body, function (err) {
if (err) {
return next(err);
}
next(null, body);
});
} | javascript | {
"resource": ""
} | |
q40110 | train | function (body, next) {
parseString(body, function (err, json) {
if (err) {
return next(err);
}
next(null, json);
});
} | javascript | {
"resource": ""
} | |
q40111 | train | function(json, next) {
fs.writeFile(out + "/" + path.basename(url).replace('.xml', '.json'), JSON.stringify(json), function (err) {
if (err) {
return next(err);
}
next(null, json);
});
} | javascript | {
"resource": ""
} | |
q40112 | Knack | train | function Knack({ concurrency = 5, interval = 500, onDone = () => {} }={}) {
const q = new Queue(concurrency, interval, onDone)
/**
* @func knack
* @template T
* @param {function(...args): Promise<T>} func
* @returns {function(...args): Promise<T>}
*/
const knack = function(func, {
priority = 50,
onTimeout = timeouts.none,
timeout = 30e3,
repeats = 3 }={}) {
return (...args) => q.task(func, { priority, onTimeout, timeout, repeats }, ...args)
}
knack.once = ({
priority = 50,
onTimeout = timeouts.none,
timeout = 30e3,
repeats = 3 }={}) => (func, ...args) => q.task(func, { priority, onTimeout, timeout, repeats }, ...args)
knack.isHalt = false
knack.halt = () => {
q.tryNext = () => {}
q.task = () => {}
knack.isHalt = true
}
Object.defineProperty(knack, 'active', {
get: () => q.active
})
Object.defineProperty(knack, 'concurrency', {
get: () => q.concurrency
// set: parallel => q.concurrency = parallel
})
Object.defineProperty(knack, 'interval', {
get: () => q.interval
// set: delay => q.interval = delay
})
knack.timeouts = timeouts
return knack
} | javascript | {
"resource": ""
} |
q40113 | train | function(file) {
var filePath = path.resolve(file);
if (filePath && fs.existsSync(filePath)) {
return filePath;
}
return false;
} | javascript | {
"resource": ""
} | |
q40114 | train | function(file) {
var filePath = path.resolve(file);
if (filePath) {
if (!fs.existsSync(filePath)) {
fse.ensureFileSync(filePath);
}
return filePath;
}
return false;
} | javascript | {
"resource": ""
} | |
q40115 | Quad | train | function Quad(gl)
{
/*
* the current WebGL drawing context
*
* @member {WebGLRenderingContext}
*/
this.gl = gl;
// this.textures = new TextureUvs();
/**
* An array of vertices
*
* @member {Float32Array}
*/
this.vertices = new Float32Array([
0,0,
200,0,
200,200,
0,200
]);
/**
* The Uvs of the quad
*
* @member {Float32Array}
*/
this.uvs = new Float32Array([
0,0,
1,0,
1,1,
0,1
]);
// var white = (0xFFFFFF >> 16) + (0xFFFFFF & 0xff00) + ((0xFFFFFF & 0xff) << 16) + (1 * 255 << 24);
//TODO convert this to a 32 unsigned int array
/**
* The color components of the triangles
*
* @member {Float32Array}
*/
this.colors = new Float32Array([
1,1,1,1,
1,1,1,1,
1,1,1,1,
1,1,1,1
]);
/*
* @member {Uint16Array} An array containing the indices of the vertices
*/
this.indices = new Uint16Array([
0, 1, 2, 0, 3, 2
]);
/*
* @member {WebGLBuffer} The vertex buffer
*/
this.vertexBuffer = gl.createBuffer();
/*
* @member {WebGLBuffer} The index buffer
*/
this.indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, (8 + 8 + 16) * 4, gl.DYNAMIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
this.upload();
} | javascript | {
"resource": ""
} |
q40116 | train | function(moduleRegex) {
var self = this;
moduleRegex = moduleRegex || /^(.+)\.js$/;
return function(req, res, next) {
var match = req.url.match(moduleRegex);
if(!match) return next();
var module= match[1];
self.bundle(module, function(err, src) {
res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache');
// expose event to allow for custom headers
self.emit('pre-response', err, res, module, src);
res.send(src);
});
};
} | javascript | {
"resource": ""
} | |
q40117 | _same_set | train | function _same_set(set1, set2){
var h1 = {};
var h2 = {};
for( var h1i = 0; h1i < set1.length; h1i++ ){ h1[set1[h1i]] = 1; }
for( var h2i = 0; h2i < set2.length; h2i++ ){ h2[set2[h2i]] = 1; }
return _same_hash(h1, h2);
} | javascript | {
"resource": ""
} |
q40118 | _is_same | train | function _is_same(a, b){
//bark('typeof(a, b): ' + typeof(a) + ',' + typeof(b));
var ret = false;
if( a == b ){ // atoms, incl. null and 'string'
//bark('true on equal atoms: ' + a + '<>' + b);
ret = true;
}else{ // is list or obj (ignore func)
if( typeof(a) === 'object' && typeof(b) === 'object' ){
//bark('...are objects');
// Null is an object, but not like the others.
if( a == null || b == null ){
ret = false;
}else if( Array.isArray(a) && Array.isArray(b) ){ // array equiv
//bark('...are arrays');
// Recursively check array equiv.
if( a.length == b.length ){
if( a.length == 0 ){
//bark('true on 0 length array');
ret = true;
}else{
ret = true; // assume true until false here
for( var i = 0; i < a.length; i++ ){
if( ! _is_same(a[i], b[i]) ){
//bark('false on diff @ index: ' + i);
ret = false;
break;
}
}
}
}
}else{ // object equiv.
// Get unique set of keys.
var a_keys = Object.keys(a);
var b_keys = Object.keys(b);
var keys = a_keys.concat(b_keys.filter(function(it){
return a_keys.indexOf(it) < 0;
}));
// Assume true until false.
ret = true;
for( var j = 0; j < keys.length; j++ ){ // no forEach - break
var k = keys[j];
if( ! _is_same(a[k], b[k]) ){
//bark('false on key: ' + k);
ret = false;
break;
}
}
}
}else{
//bark('false by default');
}
}
return ret;
} | javascript | {
"resource": ""
} |
q40119 | _in_list | train | function _in_list(in_item, list, comparator){
var retval = false;
for(var li = 0; li < list.length; li++ ){
var list_item = list[li];
if( comparator ){
var comp_op = comparator(in_item, list_item);
if( comp_op && comp_op == true ){
retval = true;
}
}else{
if( in_item == list_item ){
retval = true;
}
}
}
return retval;
} | javascript | {
"resource": ""
} |
q40120 | _is_string_embedded | train | function _is_string_embedded(target_str, base_str, add_str){
// Walk through all of ways of splitting base_str and add
// add_str in there to see if we get the target_str.
var retval = false;
for(var si = 0; si <= base_str.length; si++ ){
var car = base_str.substr(0, si);
var cdr = base_str.substr(si, base_str.length);
//bark(car + "|" + add_str + "|" + cdr);
if( car + add_str + cdr == target_str){
retval = true;
break;
}
}
return retval;
} | javascript | {
"resource": ""
} |
q40121 | rec_up | train | function rec_up(nid){
//print('rec_up on: ' + nid);
var results = new Array();
var new_parent_edges = anchor.get_parent_edges(nid, pid);
// Capture edge list for later adding.
for( var e = 0; e < new_parent_edges.length; e++ ){
seen_edge_list.push(new_parent_edges[e]);
}
// Pull extant nodes from edges. NOTE: This is a retread
// of what happens in get_parent_nodes to avoid another
// call to get_parent_edges (as all this is now
// implemented).
var new_parents = new Array();
for( var n = 0; n < new_parent_edges.length; n++ ){
// Make sure that any found edges are in our
// world.
var obj_id = new_parent_edges[n].object_id();
var temp_node = anchor.get_node(obj_id);
if( temp_node ){
new_parents.push( temp_node );
}
}
// Make sure we're in there too.
var tmp_node = anchor.get_node(nid);
if( tmp_node ){
new_parents.push( tmp_node );
}
// Recur on unseen things and mark the current as seen.
if( new_parents.length != 0 ){
for( var i = 0; i < new_parents.length; i++ ){
// Only do things we haven't ever seen before.
var new_anc = new_parents[i];
var new_anc_id = new_anc.id();
if( ! seen_node_hash[ new_anc_id ] ){
seen_node_hash[ new_anc_id ] = new_anc;
rec_up(new_anc_id);
}
}
}
return results;
} | javascript | {
"resource": ""
} |
q40122 | order_cohort | train | function order_cohort(in_brackets){
// Push into global cohort list list.
for( var i = 0; i < in_brackets.length; i++ ){
var bracket_item = in_brackets[i];
//
//_kvetch(' order_cohort: i: ' + i);
//_kvetch(' order_cohort: lvl: ' + bracket_item.level);
cohort_list[bracket_item.level - 1].push(bracket_item);
// Drill down.
if( bracket_item.brackets.length > 0 ){
//_kvetch(' order_cohort: down: ' +
// bracket_item.brackets.length);
order_cohort(bracket_item.brackets);
}
}
} | javascript | {
"resource": ""
} |
q40123 | _new_node_at | train | function _new_node_at(bnode, level){
ll("adding " + bnode.id() + " at level " + level + "!");
// Create new vertex and add to set.
var new_vertex = new bbop.layout.sugiyama.simple_vertex(bnode.id());
new_vertex.level = level;
vertex_set[ new_vertex.id() ] = new_vertex;
// Check the node in to the 'seen' references.
first_seen_reference[ new_vertex.id() ] = level;
last_seen_reference[ new_vertex.id() ] = level;
} | javascript | {
"resource": ""
} |
q40124 | getSubjectBarycenter | train | function getSubjectBarycenter(subject){
var weighted_number_of_edges = 0;
var number_of_edges = 0;
for( var o = 1; o <= object_vector.length; o++ ){
if( relation_matrix[object_vector[o -1].id()] &&
relation_matrix[object_vector[o -1].id()][subject.id()]){
weighted_number_of_edges += o;
number_of_edges++;
}
}
// The '-1' is to offset the indexing.
return ( weighted_number_of_edges / number_of_edges ) -1;
} | javascript | {
"resource": ""
} |
q40125 | on_error | train | function on_error(e) {
console.log('problem with request: ' + e.message);
var response = new anchor._response_handler(null);
response.okay(false);
response.message(e.message);
response.message_type('error');
anchor.apply_callbacks('error', [response, anchor]);
} | javascript | {
"resource": ""
} |
q40126 | on_error | train | function on_error(xhr, status, error) {
var response = new anchor._response_handler(null);
response.okay(false);
response.message(error);
response.message_type(status);
anchor.apply_callbacks('error', [response, anchor]);
} | javascript | {
"resource": ""
} |
q40127 | _full_delete | train | function _full_delete(hash, key1, key2){
if( key1 && key2 && hash &&
hash[key1] && hash[key1][key2] ){
delete hash[key1][key2];
}
if( bbop.core.is_empty(hash[key1]) ){
delete hash[key1];
}
} | javascript | {
"resource": ""
} |
q40128 | _lock_map | train | function _lock_map(field, id_list){
var fixed_list = [];
bbop.core.each(id_list,
function(item){
fixed_list.push(bbop.core.ensure(item, '"'));
});
var base_id_list = '(' + fixed_list.join(' OR ') + ')';
var ret_query = field + ':' + base_id_list;
return ret_query;
} | javascript | {
"resource": ""
} |
q40129 | _create_select_box | train | function _create_select_box(val, id, name){
if( ! is_defined(name) ){
name = select_item_name;
}
var input_attrs = {
'value': val,
'name': name,
'type': 'checkbox'
};
if( is_defined(id) ){
input_attrs['id'] = id;
}
var input = new bbop.html.input(input_attrs);
return input;
} | javascript | {
"resource": ""
} |
q40130 | _ignorable_event | train | function _ignorable_event(event){
var retval = false;
if( event ){
var kc = event.keyCode;
if( kc ){
if( kc == 39 || // right
kc == 37 || // left
kc == 32 || // space
kc == 20 || // ctl?
kc == 17 || // ctl?
kc == 16 || // shift
//kc == 8 || // delete
kc == 0 ){ // super
ll('ignorable key event: ' + kc);
retval = true;
}
}
}
return retval;
} | javascript | {
"resource": ""
} |
q40131 | _nothing_to_see_here | train | function _nothing_to_see_here(in_field){
var section_id = filter_accordion_widget.get_section_id(in_field);
jQuery('#' + section_id).empty();
jQuery('#' + section_id).append('Nothing to filter.');
} | javascript | {
"resource": ""
} |
q40132 | draw_shield | train | function draw_shield(resp){
// ll("shield what: " + bbop.core.what_is(resp));
// ll("shield resp: " + bbop.core.dump(resp));
// First, extract the fields from the
// minimal response.
var fina = call_time_field_name;
var flist = resp.facet_field(call_time_field_name);
// Draw the proper contents of the shield.
filter_shield.draw(fina, flist, manager);
} | javascript | {
"resource": ""
} |
q40133 | train | function(layout_level){
loop(layout_level, // for every item at this level
function(level_item){
var nid = level_item[0];
var lbl = level_item[1];
var rel = level_item[2];
// For various sections, decide to run image
// (img) or text code depending on whether
// or not it looks like we have a real URL.
var use_img_p = true;
if( base_icon_url == null || base_icon_url == '' ){
use_img_p = false;
}
// Clickable acc span.
// No images, so the same either way. Ignore
// it if we're current.
var nav_b = null;
if(anchor._current_acc == nid){
var inact_attrs = {
'class': 'bbop-js-text-button-sim-inactive',
'title': 'Current term.'
};
nav_b = new bbop.html.span(nid, inact_attrs);
}else{
var tbs = bbop.widget.display.text_button_sim;
var bttn_title =
'Reorient neighborhood onto this node (' +
nid + ').';
nav_b = new tbs(nid, bttn_title);
nav_button_hash[nav_b.get_id()] = nid;
}
// Clickable info span. A little difference
// if we have images.
var info_b = null;
if( use_img_p ){
// Do the icon version.
var imgsrc = bbop.core.resourcify(base_icon_url,
info_icon,
image_type);
info_b =
new bbop.html.image({'alt': info_alt,
'title': info_alt,
'src': imgsrc,
'generate_id': true});
}else{
// Do a text-only version.
info_b =
new bbop.html.span('<b>[i]</b>',
{'generate_id': true});
}
info_button_hash[info_b.get_id()] = nid;
// "Icon". If base_icon_url is defined as
// something try for images, otherwise fall
// back to this text ick.
var icon = null;
if( use_img_p ){
// Do the icon version.
var ialt = '[' + rel + ']';
var isrc = null;
if(anchor._current_acc == nid){
isrc = bbop.core.resourcify(base_icon_url,
current_icon,
image_type);
}else{
isrc = bbop.core.resourcify(base_icon_url,
rel, image_type);
}
icon =
new bbop.html.image({'alt': ialt,
'title': rel,
'src': isrc,
'generate_id': true});
}else{
// Do a text-only version.
if(anchor._current_acc == nid){
icon = '[[->]]';
}else if( rel && rel.length && rel.length > 0 ){
icon = '[' + rel + ']';
}else{
icon = '[???]';
}
}
// Stack the info, with the additional
// spaces, into the div.
top_level.add_to(spaces,
icon,
nav_b.to_string(),
lbl,
info_b.to_string());
});
spaces = spaces + spacing;
} | javascript | {
"resource": ""
} | |
q40134 | train | function(request_data, response_hook) {
anchor.jq_vars['success'] = function(json_data){
var retlist = [];
var resp = new bbop.golr.response(json_data);
// Reset the last return; remember: tri-state.
result_count = null;
return_count = null;
if( resp.success() ){
// Get best shot at document counts.
result_count = resp.total_documents();
return_count = resp.documents().length;
loop(resp.documents(),
function(doc){
// First, try and pull what we can out of our
var lbl = label_tt.fill(doc);
// Now the same thing for the return/value.
var val = value_tt.fill(doc);
// Add the discovered items to the return
// save.
var item = {
'label': lbl,
'value': val,
'document': doc
};
retlist.push(item);
});
}
response_hook(retlist);
};
// Get the selected term into the manager and fire.
//anchor.set_query(request_data.term);
anchor.set_comfy_query(request_data.term);
anchor.JQ.ajax(anchor.get_query_url(), anchor.jq_vars);
} | javascript | {
"resource": ""
} | |
q40135 | train | function(event, ui){
// Prevent default selection input filling action (from
// jQuery UI) when non-default marked.
if( ! anchor._fill_p ){
event.preventDefault();
}
var doc_to_apply = null;
if( ui.item ){
doc_to_apply = ui.item.document;
}
// Only do the callback if it is defined.
if( doc_to_apply &&
bbop.core.is_defined(anchor._list_select_callback) ){
anchor._list_select_callback(doc_to_apply);
}
} | javascript | {
"resource": ""
} | |
q40136 | _draw_local_doc | train | function _draw_local_doc(doc){
//ll(doc['id']);
var personality = anchor.get_personality();
var cclass = golr_conf_obj.get_class(personality);
var txt = 'Nothing here...';
if( doc && cclass ){
var tbl = new bbop.html.table();
var results_order = cclass.field_order_by_weight('result');
var each = bbop.core.each; // convenience
each(results_order,
function(fid){
//
var field = cclass.get_field(fid);
var val = doc[fid];
// Determine if we have a list that we're working
// with or not.
if( field.is_multi() ){
if( val ){
val = val.join(', ');
}else{
val = 'n/a';
}
}else{
// When handling just the single value, see
// if we can link out the value.
var link = null;
if( val ){
//link = linker.anchor({id: val});
//link = linker.anchor({id: val}, 'term');
link = linker.anchor({id: val}, fid);
if( link ){ val = link; }
}else{
val = 'n/a';
}
}
tbl.add_to([field.display_name(), val]);
});
txt = tbl.to_string();
}
// Create div.
var div = new bbop.html.tag('div', {'generate_id': true});
var div_id = div.get_id();
// Append div to body.
jQuery('body').append(div.to_string());
// Add text to div.
jQuery('#' + div_id).append(txt);
// Modal dialogify div; include self-destruct.
var diargs = {
modal: true,
draggable: false,
width: width,
close:
function(){
// TODO: Could maybe use .dialog('destroy') instead?
jQuery('#' + div_id).remove();
}
};
var dia = jQuery('#' + div_id).dialog(diargs);
} | javascript | {
"resource": ""
} |
q40137 | _get_selected | train | function _get_selected(){
var ret_list = [];
var selected_strings =
jQuery('#'+ sul_id).sortable('toArray', {'attribute': 'value'});
each(selected_strings,
function(in_thing){
if( in_thing && in_thing != '' ){
ret_list.push(in_thing);
}
});
return ret_list;
} | javascript | {
"resource": ""
} |
q40138 | _button_wrapper | train | function _button_wrapper(str, title){
var b = new bbop.widget.display.text_button_sim(str, title, '');
return b.to_string();
} | javascript | {
"resource": ""
} |
q40139 | _initial_runner | train | function _initial_runner(response, manager){
// I can't just remove the callback from the register
// after the first run because it would be reconstituted
// every time it was reset (established).
if( anchor.initial_reset_p ){
anchor.initial_reset_p = false;
anchor.initial_reset_callback(response, manager);
//ll('unregister: ' + anchor.unregister('reset', 'first_run'));
}
} | javascript | {
"resource": ""
} |
q40140 | _draw_table_or_something | train | function _draw_table_or_something(resp, manager){
// Wipe interface.
jQuery('#' + interface_id).empty();
// Vary by what we got.
if( ! resp.success() || resp.total_documents() === 0 ){
jQuery('#' + interface_id).append('<em>No results given your input and search fields. Please refine and try again.</em>');
last_response = null;
}else{
last_response = resp;
// Render the buttons.
//console.log('user_buttons: ', user_buttons);
if( user_buttons && user_buttons.length && user_buttons.length > 0 ){
// Ensure we have somewhere to put our buttons. If not
// supplied with an injection id, make our own and use
// it.
var insert_div_id = user_buttons_div_id;
if( ! user_buttons_div_id ){
// Generate new dic and add it to the display.
var ubt_attrs = {
'generate_id': true
};
var ubt = new bbop.html.tag('div', ubt_attrs);
jQuery('#' + interface_id).append(ubt.to_string());
// Ensure the id.
insert_div_id = ubt.get_id();
}
// Add all of the defined buttons after the spacing.
_draw_user_buttons(user_buttons, insert_div_id);
}
// Display results.
var bwd = bbop.widget.display;
results_table =
new bwd.results_table_by_class_conf_b3(conf_class, resp, linker,
handler, interface_id,
selectable_p,
select_column_id,
select_item_name);
}
} | javascript | {
"resource": ""
} |
q40141 | read_cli | train | function read_cli(event){
var which = event.which;
var ctrl_p = event.ctrlKey;
//log('cli: ' + which + ', ' + ctrl_p);
if ( which == 13 ) { // return
// Stop events.
event.preventDefault();
// Get and ensure nice JS, wipe CLI clean.
var to_eval = jQuery('#' + command_line.get_id()).val();
if( to_eval != '' ){
jQuery('#' + command_line.get_id()).val('');
// Enter the new command into our history and bump the
// index to the last thing pushed on.
history_list.pop(); // pop the empty ''
history_list.push(to_eval);
history_list.push(''); // push new empty ''
history_pointer = history_list.length -1;
//log('// history: '+history_pointer+', '+history_list.length);
// Log, eval, log.
to_eval = bbop.core.ensure(to_eval, ';', 'back');
log(to_eval);
var evals = _evaluate(to_eval);
log('// ' + evals[1]);
_advance_log_to_bottom();
return false;
}
}else if( ctrl_p && which == 38 ){ // ctrl + up
// Stop stuff?
event.preventDefault();
if( history_pointer == 0 ){
_update_cli();
}else if( history_pointer > 0 ){
history_pointer--;
_update_cli();
}
return false;
}else if( ctrl_p && which == 40 ){ // ctrl + down
// Stop stuff?
event.preventDefault();
if( history_pointer < history_list.length -1 ){
history_pointer++;
_update_cli();
}
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q40142 | read_buffer | train | function read_buffer(){
var to_eval = jQuery('#' + command_buffer.get_id()).val();
if( to_eval != '' ){
log('// Evaluating buffer...');
var evals = _evaluate(to_eval);
log('// ' + evals[1]);
_advance_log_to_bottom();
}
} | javascript | {
"resource": ""
} |
q40143 | gather_list_from_hash | train | function gather_list_from_hash(nid, hash){
var retlist = new Array();
retlist.push(nid);
// Get all nodes cribbing from distances.
for( vt in hash[nid] ){
//ll("id: " + id + ", v: " + ct);
retlist.push(vt);
}
return retlist;
} | javascript | {
"resource": ""
} |
q40144 | get_connections | train | function get_connections(phynode_id, phynode_getter, conn_hash){
var retlist = new Array();
// Fish in the connection ancestor hash for edges.
var tmp_phynodes = phynode_getter(phynode_id);
for( var si = 0; si < tmp_phynodes.length; si++ ){
var tshp = tmp_phynodes[si];
var tnid = phynode_id_to_node_id[tshp.id];
if( tnid && conn_hash[tnid] ){
for( var anid in conn_hash[tnid] ){
var conn_index = conn_hash[tnid][anid];
var conn = connections[conn_index];
ll('get_conn: found: [' + conn_index +
'] ' + anid + ' <=> ' + tnid +
' ... ' + conn);
retlist.push(conn);
}
}
}
return retlist;
} | javascript | {
"resource": ""
} |
q40145 | train | function () {
var phynode_id = this.id;
// Fade boxes.
var assoc_phynodes = get_descendant_phynodes(phynode_id);
for( var si = 0; si < assoc_phynodes.length; si++ ){
var mshp = assoc_phynodes[si];
mshp.update();
}
// Update connections; bring them all back to normal.
for (var i = connections.length; i--;) {
connections[i].update();
}
paper.safari();
} | javascript | {
"resource": ""
} | |
q40146 | dblclick_event_handler | train | function dblclick_event_handler(event){
var phynode_id = this.id;
// If this is the first double click here...
var pn = get_pnode_from_phynode_id(phynode_id);
if( pn.open == true ){
// "Vanish" edges.
var subtree_edges = get_descendant_connections(phynode_id);
for( var se = 0; se < subtree_edges.length; se++ ){
var ste = subtree_edges[se];
ste.visible = false;
ste.update();
}
// "Vanish" nodes and text; not this node though...
var subtree_nodes = get_descendant_phynodes(phynode_id);
for( var sn = 0; sn < subtree_nodes.length; sn++ ){
var stn = subtree_nodes[sn];
if( stn.id != phynode_id ){
// Turn of visibilty for children.
stn.visible = false;
}else{
// Mark self as closed.
stn.open = false;
}
stn.update();
}
}else{ //Otherwise...
// Reestablish edges.
var subtree_edges = get_descendant_connections(phynode_id);
for( var se = 0; se < subtree_edges.length; se++ ){
var ste = subtree_edges[se];
ste.visible = true;
ste.update();
}
// Restablish pnodes; clear all history.
var subtree_nodes = get_descendant_phynodes(phynode_id);
for( var sn = 0; sn < subtree_nodes.length; sn++ ){
var stn = subtree_nodes[sn];
stn.open = true;
stn.visible = true;
stn.update();
}
}
} | javascript | {
"resource": ""
} |
q40147 | _generate_element | train | function _generate_element(ctype, str){
var message_classes = ['bbop-js-message',
'bbop-js-message-' + ctype];
var message_elt =
new bbop.html.tag('div',
{'generate_id': true,
'class': message_classes.join(' ')},
'<h2>' + str + '</h2>');
jQuery("body").append(jQuery(message_elt.to_string()).hide());
// jQuery-ify the element.
var elt = jQuery('#' + message_elt.get_id());
return elt;
} | javascript | {
"resource": ""
} |
q40148 | train | function(dirname) {
var result;
if (!fs.test('-d', dirname)) { return result; }
result = {};
_.each(sg.fs.ls(dirname), (name_) => {
const name = path.basename(name_, '.js');
const filename = path.join(dirname, name);
if (!fs.test('-f', `${filename}.js`)) { return; } // skip
if (name.startsWith('helper')) { return; } // skip helper(s).js
result[name] = result[name] || {};
_.extend(result[name], libRa.middlewareify(safeRequire(filename)));
});
return result;
} | javascript | {
"resource": ""
} | |
q40149 | make_query_maker | train | function make_query_maker(connection_string, connection_opts) {
connection_string = connection_string || "http://localhost:7474";
connection_opts = connection_opts || {};
var client_cache = null;
return {
query: query,
multi: multi
};
/**
* Makes a cypher query and resolves to the result
* @param {String} cypher_query The CQL code to execute
* @param {Object} [parameters] The parameters to pass to the query
* @return {Promise} Resolves to the result of the query
*/
function query(cypher_query, parameters) {
return get_client()
.then(rpar(query_with, cypher_query, parameters));
}
/**
* Make a new object for batching queries. Call multi.query multiple times,
* and then call multi.exec() to get a promise of whether everything succeeded
* or not.
* @return {Multi} Returns a multi object with `query` and `exec` methods
*/
function multi() {
var multi = get_client().then(function (client) {
return client.multi();
});
return {
query: query,
exec: exec
};
function query(cypher_query, parameters) {
return multi.then(function (multi) {
return query_with(multi, cypher_query, parameters);
});
}
function exec() {
return multi.then(function (multi) {
return make_promise(multi.exec.bind(multi));
});
}
}
// Makes a query with a given client and returns a promise
function query_with(client, cypher_query, parameters) {
parameters = parameters || {};
return make_promise(client.query.bind(client, cypher_query, parameters));
}
// Creates a new client or returns a cached one
function get_client() {
if (client_cache) return Promise.resolve(client_cache);
return make_promise(
cypher.createClient.bind(cypher, connection_string, connection_opts)
).then(cache_client);
}
// Caches a client for later use
function cache_client(client) {
client_cache = client;
return client;
}
} | javascript | {
"resource": ""
} |
q40150 | query_with | train | function query_with(client, cypher_query, parameters) {
parameters = parameters || {};
return make_promise(client.query.bind(client, cypher_query, parameters));
} | javascript | {
"resource": ""
} |
q40151 | get_client | train | function get_client() {
if (client_cache) return Promise.resolve(client_cache);
return make_promise(
cypher.createClient.bind(cypher, connection_string, connection_opts)
).then(cache_client);
} | javascript | {
"resource": ""
} |
q40152 | BlurYTintFilter | train | function BlurYTintFilter()
{
core.AbstractFilter.call(this,
// vertex shader
fs.readFileSync(__dirname + '/blurYTint.vert', 'utf8'),
// fragment shader
fs.readFileSync(__dirname + '/blurYTint.frag', 'utf8'),
// set the uniforms
{
blur: { type: '1f', value: 1 / 512 },
color: { type: 'c', value: [0,0,0]},
alpha: { type: '1f', value: 0.7 },
offset: { type: '2f', value:[5, 5]},
strength: { type: '1f', value:1}
}
);
this.passes = 1;
this.strength = 4;
} | javascript | {
"resource": ""
} |
q40153 | train | function ( src ) {
var cuts = src.split ( "/" );
var name = cuts.pop ();
var dots = src.split ( "." );
var type = dots.pop ();
new gui.Request(src).acceptText().get().then(function(status, data) {
this._output(name, type, data);
}, this);
} | javascript | {
"resource": ""
} | |
q40154 | train | function ( text, type ) {
switch ( type ) {
case "js" :
return new dox.JSDoc ({
title : document.title,
chapters : this._chapters ( text )
});
case "md" :
return new dox.MDDoc ({
title : document.title,
markup : this._markup ( text )
});
}
} | javascript | {
"resource": ""
} | |
q40155 | train | function ( source ) {
var comment = false;
var chapters = [];
var chapter = null;
var sections = [];
var section = null;
var marker = new Showdown.converter ();
function nextchapter ( title ) {
if ( chapter ) {
chapter.sections = sections.map ( function ( section, i ) {
section.desc = marker.makeHtml ( section.desc );
return section;
});
chapters.push ( chapter );
}
chapter = new dox.Chapter ({
title : title || null
});
sections = [];
}
function nextsection ( line ) {
if ( section && section.code ) {
sections.push ( section );
}
section = new dox.Block ({
line : line || 0,
tags : [],
desc : "",
code : ""
});
}
nextsection ();
nextchapter ();
source.split ( "\n" ).forEach ( function ( line, index ) {
var md, trim = line.trim ();
if ( comment ) {
if ( trim.startsWith ( "*/" )) {
comment = false;
} else {
if ( trim === "*" ) {
section.desc += "\n\n";
} else {
md = line.replace ( this._GUTTER, "" );
switch ( md [ 0 ]) {
case "@" :
section.tags.push ( new dox.Tag ({
text : this._encode ( md )
}));
break;
case "#" :
//chapter.title = md.replace ( this._HEADER, "" );
section.desc += "\n" + md + "\n\n";
break;
default :
if ( !md.match ( this._LETTER )) {
section.desc += "\n";
}
section.desc += this._encode ( md );
break;
}
}
}
} else {
if ( line.match ( this._CHAPTER )) {
var title = this._TITLE.exec ( line );
nextsection ( index );
nextchapter ( title ? title [ 0 ] : null );
section.code += this._HELLO.exec ( line );
} else {
if ( trim.startsWith ( "/**" )) {
comment = true;
nextsection ( index );
} else {
section.code += line + "\n";
}
}
}
}, this );
nextsection ();
nextchapter ();
return chapters;
} | javascript | {
"resource": ""
} | |
q40156 | indento | train | function indento(input, width, char) {
char = typeof char !== "string" ? " " : char;
return String(input).replace(/^/gm, char.repeat(width));
} | javascript | {
"resource": ""
} |
q40157 | request | train | function request (suppliedOptions,data,next)
{
var options = makeOptions(suppliedOptions);
switch (options.method ? options.method.toUpperCase() : "BADMETHOD") {
case "PUT":
case "POST":
var dataString = JSON.stringify(data);
options.headers['Content-Length'] = dataString.length;
var req = https.request(options,requestDone);
req.end(dataString);
break;
case "GET":
case "DELETE":
var req = https.request(options,requestDone);
req.end();
break;
case "BADMETHOD":
default:
var e = new Error('trakter: invalid method or not specified');
e.name = 'TrakterBadMethod';
e.code = 97;
next (e);
break;
}
function requestDone(res) {
res.setEncoding('utf8');
var responseString = '';
res.on('error', function(err) {
next (err,null);
});
res.on('data', function(data) {
responseString += data;
});
res.on('end', function() {
var err = checkError(options.method,res);
if ( err !== null) {
next (err);
} else {
next (null,JSON.parse(responseString));
}
});
}
} | javascript | {
"resource": ""
} |
q40158 | GENERATE_CLASSES | train | function GENERATE_CLASSES(classes) {
var docs = {};
_.each(classes, function(classSpec, parentClass) {
var constructor = classSpec.methods[parentClass];
_.extend(docs, GENERATE_METHOD(parentClass, constructor ? constructor : { params: {}, return: {}, description: '' } ));
if (_.has(docs, parentClass)) {
_.each(classSpec.enums, function(enumSpec, enumName) {
_.extend(docs[parentClass], GENERATE_ENUM(enumName, enumSpec));
});
docs[parentClass].prototype = {};
_.each(_.omit(classSpec.methods, parentClass), function(methodSpec, methodName) {
_.extend(docs[parentClass].prototype, GENERATE_METHOD(methodName, methodSpec));
});
_.each(classSpec.variables, function(variableSpec, variableName) {
_.extend(docs[parentClass].prototype, GENERATE_VARIABLE(variableName, variableSpec));
});
}
});
return docs;
} | javascript | {
"resource": ""
} |
q40159 | GENERATE_METHOD | train | function GENERATE_METHOD(name, spec) {
var doc = {};
doc[name] = {
'!type': 'fn(' + GENERATE_PARAMS(spec.params) + ')' + GENERATE_RETURN(spec.return),
'!doc': spec.description
}
return doc;
} | javascript | {
"resource": ""
} |
q40160 | GENERATE_PARAMS | train | function GENERATE_PARAMS(spec) {
return _.map(spec, function(paramSpec, paramName) {
return paramName + ': ' + paramSpec.type;
}).join(', ');
} | javascript | {
"resource": ""
} |
q40161 | extend_if_promise | train | function extend_if_promise(methods, ret) {
if(ret && ret.then) { // Check if return value is promise compatible
return extend.promise(methods, ret); // ..and if so, extend it, too.
}
return ret; // ..and if not, return the same value.
} | javascript | {
"resource": ""
} |
q40162 | train | function(filename, fileInfo) {
var projectName = path.relative(
app.config.paths.projects,
path.dirname(filename)
);
if (app.projects.get(projectName)) {
logger.log('Unload project: "' + projectName + '"');
app.projects.unload({name: projectName});
}
// on add or change (info is falsy on unlink)
if (fileInfo) {
logger.log('Load project "' + projectName + '" on change');
app.projects.load({name: projectName}, function(err) {
if (err) {
return logger.error(
'Error during load project "' + projectName + '": ',
err.stack || err
);
}
logger.log(
'Project "' + projectName + '" loaded:',
JSON.stringify(app.projects.get(projectName), null, 4)
);
});
}
} | javascript | {
"resource": ""
} | |
q40163 | splatND | train | function splatND(out, points, weights, radius) {
var n = points.shape[0]
var d = points.shape[1]
var lo = new Array(d)
var hi = new Array(d)
var bounds = out.shape
var coord = new Array(d+1)
var w = 1.0
function splatRec(k) {
if(k < 0) {
coord[d] = out.get.apply(out, coord) + w
out.set.apply(out, coord)
return
}
var wprev = w
var x = points.get(i, k)
for(coord[k]=lo[k]; coord[k]<hi[k]; ++coord[k]) {
w = wprev * dirichlet(bounds[k], coord[k] - x)
splatRec(k-1)
}
w = wprev
}
for(var i=0; i<=d; ++i) {
coord[i] = 0
}
for(var i=0; i<n; ++i) {
for(var j=0; j<d; ++j) {
var x = points.get(i,j)
lo[j] = Math.max(x-radius, 0)
hi[j] = Math.min(x+radius, bounds[j]-1)
}
w = weights.get(i)
splatRec(d-1)
}
} | javascript | {
"resource": ""
} |
q40164 | fireOnLoad | train | function fireOnLoad() {
var args = arguments, i;
for(i = 0, len = addOnLoadHandler.stack.length; i<len; i++) {
addOnLoadHandler.stack[i].apply(null, args);
}
} | javascript | {
"resource": ""
} |
q40165 | findHash | train | function findHash(path) {
var h, m, len;
for(h in config.map) {
var modules = config.map[h];
for(m = 0, len = modules.length; m < len; m++ ) {
if(modules[m] === path) return h
}
}
return null;
} | javascript | {
"resource": ""
} |
q40166 | scriptLoader | train | function scriptLoader(url, callback) {
var doc = document, s = doc.createElement("script")
, head = doc.getElementsByTagName("head")[0]
, node
, done = false;
;
// On success listener
function onScriptLoad() {
if ( !done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") )
{
done = true;
callback();
}
}
// On failure listener (callback receive an error false)
function onScriptError() {
callback(new Error("Packet loading error for " + url));
}
// Create the script tag
node = document.createElement('script')
node.type = config.scriptType || 'text/javascript';
node.charset = 'utf-8';
node.async = true;
// Listen to the onload event
if (node.attachEvent &&
!(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0)) {
node.attachEvent('onreadystatechange', onScriptLoad);
} else {
node.addEventListener('load', onScriptLoad, false);
node.addEventListener('error', onScriptError, false);
}
// Set the src value with the packed script url
node.src = url;
// Start loading by adding the script tag in the head
head.appendChild(node);
} | javascript | {
"resource": ""
} |
q40167 | _getMongoDbName | train | function _getMongoDbName(str) {
if (!/[/\. "*<>:|?@]/.test(str)) {
return str;
}
str = str.replace(/\//g, exports.constants.slash);
str = str.replace(/\\/g, exports.constants.backslash);
str = str.replace(/\./g, exports.constants.dot);
str = str.replace(/ /g, exports.constants.space);
str = str.replace(/"/g, exports.constants.doubleQuotes);
str = str.replace(/\*/g, exports.constants.star);
str = str.replace(/</g, exports.constants.lessThan);
str = str.replace(/>/g, exports.constants.greaterThan);
str = str.replace(/:/g, exports.constants.colon);
str = str.replace(/\|/g, exports.constants.pipe);
str = str.replace(/\?/g, exports.constants.questionMark);
str = str.replace(/@/g, exports.constants.at);
return str;
} | javascript | {
"resource": ""
} |
q40168 | _getSafeFileName | train | function _getSafeFileName(filename, directory) {
var deferred = q.defer();
fs.readdir(directory, function(err, files) {
if(err) {
// This means the directory doesn't exist
if (err.errno === 34 && err.code === 'ENOENT') {
deferred.resolve(filename);
}
else {
deferred.reject(err);
}
}
else {
var index = files.indexOf(filename);
if (index > -1) {
// Get filename and extension (if it has one)
var name, extension;
var splitString = filename.split('.');
// Has extension
if (splitString.length > 1) {
extension = splitString.pop();
name = splitString.join('.');
// Wait! Is this a hidden file?
if (!name) {
name = '.' + extension;
extension = '';
}
}
// No extension
else {
name = filename;
extension = '';
}
// Get the copy number appended to the name and increment, if any
var matches = name.match(/\((\d+)\)$/);
if (matches) {
var copyNumber = Number(matches[1]) + 1;
name = name.replace(/\((\d+)\)$/, '(' + copyNumber + ')');
}
else {
name += '(1)';
}
// Assemble new filename
if (extension) {
filename = name + '.' + extension;
}
else {
filename = name;
}
deferred.resolve(_getSafeFileName(filename, directory));
}
else {
deferred.resolve(filename);
}
}
});
return deferred.promise;
} | javascript | {
"resource": ""
} |
q40169 | _getOutputFileName | train | function _getOutputFileName(path, extension) {
var filename = path.split('/');
filename = filename[filename.length - 1];
filename = filename.split('.');
// No extension found
if (filename.length === 1) {
return filename[0] + '.' + extension;
}
// Hidden file
if (filename[0] === '') {
filename = filename.slice(1);
filename[0] = '.' + filename[0];
if (filename.length === 1) {
return filename[0] + '.' + extension;
}
}
filename = filename.slice(0, -1);
return filename + '.' + extension;
} | javascript | {
"resource": ""
} |
q40170 | _setTimeLimit | train | function _setTimeLimit(options, done) {
if (options && options.timeLimit && options.pidFile) {
var timeout = setTimeout(function() {
var kill = 'kill $(cat ' + options.pidFile + ')';
if (logLevel === 'trace') logger.warn('process', kill);
childProcess.exec(kill, function(err, stdout, stderr) {
if (err) {
if (logLevel === 'trace') logger.error('process', 'timeout', err);
}
if (stderr) {
if (logLevel === 'trace') logger.warn('process', 'timeout', stderr);
}
if (stdout) {
if (logLevel === 'trace') logger.info('process', 'timeout', stdout);
}
options.returnNow = 'Sorry, that file took too long to process';
});
}, options.timeLimit);
done(timeout);
}
else {
done(false);
}
} | javascript | {
"resource": ""
} |
q40171 | _stopTimer | train | function _stopTimer(timer, options) {
if (timer) {
options.timeLimit = _getTimeLeft(timer);
clearTimeout(timer);
}
} | javascript | {
"resource": ""
} |
q40172 | _echoPidToFile | train | function _echoPidToFile(options) {
var command = '';
if (options && options.pidFile) {
command = ' & echo $! > ' + options.pidFile;
}
return command;
} | javascript | {
"resource": ""
} |
q40173 | _getTimeLeft | train | function _getTimeLeft(timeout) {
return Math.ceil(timeout._idleStart + timeout._idleTimeout - Date.now());
} | javascript | {
"resource": ""
} |
q40174 | hide | train | function hide(element) {
if (!element || !element.style || typeof element.style.display !== 'string') {
return;
}
element.style.display = "";
} | javascript | {
"resource": ""
} |
q40175 | train | function(name, config) {
if (!config && typeof name === 'string' || utils.isObject(name)) {
return this.getScaffold(name);
}
this.setScaffold.apply(this, arguments);
if (typeof name === 'string') {
return this.getScaffold(name);
}
return this;
} | javascript | {
"resource": ""
} | |
q40176 | train | function(name, config) {
if (typeof name !== 'string') {
throw new TypeError('expected the first argument to be a string');
}
if (utils.isObject(config)) {
config.name = name;
}
this.emit('scaffold.set', name, config);
this.scaffolds[name] = config;
return this;
} | javascript | {
"resource": ""
} | |
q40177 | train | function(name, options) {
var opts = utils.merge({}, this.options, options);
var config;
switch (utils.typeOf(name)) {
case 'function':
config = name;
break;
case 'object':
config = name;
name = config.name;
break;
case 'string':
default: {
opts.name = name;
config = this.scaffolds[name];
if (typeof config === 'undefined') {
throw new Error(`scaffold "${name}" is not registered`);
}
break;
}
}
if (typeof config === 'function') {
config = config(opts);
}
if (!utils.isObject(config)) {
throw new TypeError('expected config to be an object');
}
// if `config` is not an instance of Scaffold, make it one
if (!this.isScaffold(config)) {
var Scaffold = this.get('Scaffold');
var scaffold = new Scaffold(opts);
scaffold.options = utils.merge({}, this.options, scaffold.options, options);
if (typeof name === 'string') {
scaffold.name = name;
}
if (typeof this.run === 'function') {
this.run(scaffold);
}
this.emit('scaffold', scaffold);
scaffold.on('target', this.emit.bind(this, 'target'));
config = scaffold.addTargets(config);
}
// otherwise, ensure options are merged onto the scaffold,
// and all targets are emitted
else {
config.options = utils.merge({}, this.options, config.options, options);
if (typeof name === 'string') {
config.name = name;
}
if (typeof this.run === 'function') {
this.run(config);
}
for (var key in config.targets) {
if (config.targets.hasOwnProperty(key)) {
this.emit('target', config.targets[key]);
}
}
config.on('target', this.emit.bind(this, 'target'));
this.emit('scaffold', config);
}
return config;
} | javascript | {
"resource": ""
} | |
q40178 | Preprocessor | train | function Preprocessor(source, baseDirOrIncludes, preserveLineNumbers) {
/**
* Source code to pre-process.
* @type {string}
* @expose
*/
this.source = '' + source;
/**
* Source base directory.
* @type {string}
* @expose
*/
this.baseDir = typeof baseDirOrIncludes === 'string' ? baseDirOrIncludes : '.';
/**
* Included sources by filename.
* @type {Object.<string, string>}
*/
this.includes = typeof baseDirOrIncludes === 'object' ? baseDirOrIncludes : {};
/**
* Preserve line numbers when removing blocks of code
* @type {boolean}
*/
this.preserveLineNumbers = typeof preserveLineNumbers === 'boolean' ? preserveLineNumbers : false;
/**
* Whether running inside of node.js or not.
* @type {boolean}
* @expose
*/
this.isNode = (typeof window === 'undefined' || !window.window) && typeof require === 'function';
/**
* Error reporting source ahead length.
* @type {number}
* @expose
*/
this.errorSourceAhead = 50;
/**
* Runtime defines.
* @type {Array.<string>}
*/
this.defines = [];
} | javascript | {
"resource": ""
} |
q40179 | train | function(mCons, vCons, k){
var nCons = {}; // the final nested constraints
// if there are per-key constraints for k, add them all
if(validate.isObject(mCons[k])){
nCons = validateParams.extendObject({}, mCons[k]);
}
// loop through each universal constraint and merge as appropraite
if(vCons){
Object.keys(vCons).forEach(function(vn){
// only add non-clashing universal constraints
if(!nCons[vn]){
nCons[vn] = vCons[vn];
}
});
}
// return the merged constraints
return nCons;
} | javascript | {
"resource": ""
} | |
q40180 | train | function(cName){
if(validate.isEmpty(cName)){
validateParams._warn('ignoring invalid coercion name: ' + cName);
}
if(validate.isFunction(validateParams.coercions[cName])){
return validateParams.coercions[cName];
}else{
validateParams._warn("no coercion named '" + cName + "' defined - ignoring");
}
return undefined;
} | javascript | {
"resource": ""
} | |
q40181 | train | function(value, options){
// make sure the default options object exists
if(typeof this.options !== 'object') this.options = {};
// build up a base config from the pre-defined defaults
var config = { rejectUndefined: true };
config.message = validateParams.extractValidatorMessage(this, options);
// interpret the passed value
if(typeof options === 'boolean'){
// false prevents the validator from being run, so must have be true
config.rejectUndefined = true;
}else if(validate.isObject(options)){
if(options.rejectUndefined) config.rejectUndefined = true;
if(validate.isString(options.message)) config.message = options.message;
}else{
throw new Error('invalid options passed - must be true or a plain object');
}
// do the actual validation
var errors = [];
if(config.rejectUndefined && typeof value === 'undefined'){
errors.push('cannot be undefined');
}
// return as appropriate
if(errors.length > 0){
return config.message ? config.message : errors;
}
return undefined;
} | javascript | {
"resource": ""
} | |
q40182 | train | function(value, options){
// implicitly pass undefined
var valType = typeof value;
if(valType === 'undefined') return undefined;
// make sure the default options object exists
if(typeof this.options !== 'object') this.options = {};
// build up a base config from the pre-defined defaults
var config = {};
config.types = validate.isArray(this.options.types) ? this.options.types : [];
config.inverseMatch = this.options.inverseMatch ? true : false;
config.message = validateParams.extractValidatorMessage(this, options);
// interpret the passed value
if(typeof options === 'string'){
config.types.push(options);
}else if(validate.isArray(options)){
config.types = config.types.concat(options);
}else if(validate.isObject(options)){
if(validate.isArray(options.types)){
config.types = config.types.concat(options.types);
}
if(options.inverseMatch) config.inverseMatch = true;
if(validate.isString(options.message)) config.message = options.message;
}else{
throw new Error('invalid options passed - must be a string, an array of strings, or a plain object');
}
// validate the passed types
var typeList = [];
config.types.forEach(function(t){
if(validateParams.isTypeofString(t) && t !== 'undefined'){
typeList.push(t);
}else{
validateParams._warn('ignoring invalid type: ' + String(t));
}
});
if(typeList.length === 0){
throw new Error('no valid types specified');
}
// do the actual validation
var errors = [];
if(config.inverseMatch){
// do a reverse match
typeList.forEach(function(t){
if(valType === t){
errors.push("can't have type '" + t + "'");
}
});
}else{
// do a regular forward match
var matched = false;
typeList.forEach(function(t){
if(valType === t){
matched = true;
}
});
if(!matched){
errors.push("must have one of the following types: " + humanJoin(typeList) + "'");
}
}
// return as appropriate
if(errors.length > 0){
return config.message ? config.message : errors;
}
return undefined;
} | javascript | {
"resource": ""
} | |
q40183 | train | function(value, options){
if(!validate.isObject(options)) options = {};
// deal with undefined
if(options.ignoreUndefined && typeof value === 'undefined'){
return undefined;
}
// cast to boolean as appropriate
if(options.nativeTruthinessOnly){
return Boolean(value);
}
return Boolean(value) && !validate.isEmpty(value) ? true : false;
} | javascript | {
"resource": ""
} | |
q40184 | train | function(value, options){
if(validate.isObject(options) && options.onlyCoercePrimitives && !validateParams.isPrimitive(value)){
return value;
}
if(validate.isEmpty(value)) return '';
return String(value);
} | javascript | {
"resource": ""
} | |
q40185 | train | function(value, options){
var typeVal = typeof value;
// if we already have a number that's not NaN, return it unaltered
if(typeVal === 'number' && !isNaN(value)) return value;
// otherwise, try do a conversion
var numVal = NaN;
if(typeVal === 'string' || typeVal === 'boolean'){
numVal = Number(value);
}
// return as appropriate, perhaps converting NaN to zero
if(validate.isObject(options) && options.NaNToZero && isNaN(numVal)){
return 0;
}
return numVal;
} | javascript | {
"resource": ""
} | |
q40186 | min | train | function min(array) {
var length = array.length;
if (length === 0) {
return 0;
}
var index = -1;
var result = array[++index];
while (++index < length) {
if (array[index] < result) {
result = array[index];
}
}
return result;
} | javascript | {
"resource": ""
} |
q40187 | isBooleanBinaryExpression | train | function isBooleanBinaryExpression(node) {
return node.kind === ts.SyntaxKind.BinaryExpression && binaryBooleanExpressionKind(node) !== undefined;
} | javascript | {
"resource": ""
} |
q40188 | prop | train | function prop(v, w) { return {
value: v, writable: w, enumerable: true, configurable: false
}} | javascript | {
"resource": ""
} |
q40189 | execute | train | function execute(req, res) {
ScriptManager.eval(req, res, '' + req.args[0], req.args.slice(1));
} | javascript | {
"resource": ""
} |
q40190 | Parser | train | function Parser (platform, projectPath) {
this.platform = platform || '';
this.path = projectPath || '';
// Extend with a ParserHelper instance
Object.defineProperty(this, 'helper', {
value: new ParserHelper(this.platform),
enumerable: true,
configurable: false,
writable: false
});
} | javascript | {
"resource": ""
} |
q40191 | authenticate | train | function authenticate(options) {
options = options || {};
var authenticators = [
passport.authenticate(['copress-oauth2-bearer', 'copress-oauth2-mac'],
options)];
if (options.scopes || options.scope) {
authenticators.push(scopeValidator(options));
}
authenticators.push(oauth2Provider.errorHandler());
return authenticators;
} | javascript | {
"resource": ""
} |
q40192 | train | function( string ){
if( string[ string.length -1 ] !== $this.slash.get()) string = string + $this.slash.get();
return string;
} | javascript | {
"resource": ""
} | |
q40193 | train | function( string ){
string = $this.slash.clean( string );
if( string[ 0 ] === $this.slash.get()) string = string.substr( 1 );
if( string[ string.length -1 ] === $this.slash.get()) string = string.substr( 0, string.length -1 );
return string;
} | javascript | {
"resource": ""
} | |
q40194 | to_map | train | function to_map(params) {
var map = {};
params.forEach(function (param, i) {
param.index = i;
map[param.name] = param;
});
map.length = params.length;
return map;
} | javascript | {
"resource": ""
} |
q40195 | train | function (selector, hash) {
this.actionQueue.push(this.webdriverClient.element.bind(this.webdriverClient, selector));
this.actionQueue.push(this._existsCb.bind(this, selector, hash));
return this;
} | javascript | {
"resource": ""
} | |
q40196 | train | function (selector, hash) {
this.actionQueue.push(this.webdriverClient.element.bind(this.webdriverClient, selector));
this.actionQueue.push(this.webdriverClient.displayed.bind(this.webdriverClient, selector));
this.actionQueue.push(this._visibleCb.bind(this, selector, hash));
return this;
} | javascript | {
"resource": ""
} | |
q40197 | train | function (selector, expected, hash) {
this.actionQueue.push(this.webdriverClient.element.bind(this.webdriverClient, selector));
this.actionQueue.push(this.webdriverClient.text.bind(this.webdriverClient, selector));
this.actionQueue.push(this._textCb.bind(this, selector, hash, expected));
return this;
} | javascript | {
"resource": ""
} | |
q40198 | train | function (selector, expected, hash) {
this.actionQueue.push(this.webdriverClient.element.bind(this.webdriverClient, selector));
this.actionQueue.push(this.webdriverClient.size.bind(this.webdriverClient));
this.actionQueue.push(this._widthCb.bind(this, selector, hash, expected));
return this;
} | javascript | {
"resource": ""
} | |
q40199 | train | function (selector, attribute, expected, hash) {
this.actionQueue.push(this.webdriverClient.element.bind(this.webdriverClient, selector));
this.actionQueue.push(this.webdriverClient.getAttribute.bind(this.webdriverClient, attribute));
this.actionQueue.push(this._attributeCb.bind(this, selector, hash, attribute, expected));
return this;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.