_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3700
|
toggleColor
|
train
|
async function toggleColor(store) {
await store.update(state => {
if (state.color === "blue") {
|
javascript
|
{
"resource": ""
}
|
q3701
|
ErrorMessage
|
train
|
function ErrorMessage({ state, error, clearError }) {
return (
<>
<h1 style={{ color: "red" }}>{error.message}</h1>
<button onClick={()
|
javascript
|
{
"resource": ""
}
|
q3702
|
CurrentQuote
|
train
|
function CurrentQuote() {
const [quoteId] = useStore("quoteId")
const [quoteLength] = useStore("quoteLengths", quoteId)
return (
<>
<p>The
|
javascript
|
{
"resource": ""
}
|
q3703
|
fileToObject
|
train
|
function fileToObject(file) {
return {
lastModified: file.lastModified,
lastModifiedDate: file.lastModifiedDate,
name: file.filename || file.name,
size: file.size,
type: file.type,
|
javascript
|
{
"resource": ""
}
|
q3704
|
train
|
function(route) {
// Save the previous route value
this._previousRoute = this._currentRoute;
// Fetch Resources
document.body.classList.add("loading");
|
javascript
|
{
"resource": ""
}
|
|
q3705
|
train
|
function(fragment, options={}) {
// Default trigger to true unless otherwise specified
(options.trigger === undefined) && (options.trigger = true);
// Stringify any data passed in the options hash
var query = options.data ? (~fragment.indexOf('?') ? '&' : '?') + $.url.query.stringify(options.data) : '';
// Un-Mark any `active` links in the page container
var $container = $(this.config.containers).unMarkLinks();
|
javascript
|
{
"resource": ""
}
|
|
q3706
|
train
|
function(route, name, callback) {
if (_.isFunction(name)) {
callback = name;
name = '';
}
if (!_.isRegExp(route)){
route = this._routeToRegExp(route);
}
if (!callback){ callback = this[name]; }
Backbone.history.route(route, (fragment) => {
// If this route was defined as a regular expression, we don't capture
// query params. Only parse the actual path.
fragment = fragment.split('?')[0];
// Extract the arguments we care about from the fragment
var args = this._extractParameters(route, fragment);
// Get the query params string
var search = (Backbone.history.getSearch() || '').slice(1);
// If this route was created from a string (not a regexp), remove the auto-captured
// search params.
if(route._isString){ args.pop(); }
// If the route is not user prodided, if the history object has
|
javascript
|
{
"resource": ""
}
|
|
q3707
|
train
|
function(options={}, callback=function(){}) {
// Let all of our components always have referance to our router
Component.prototype.router = this;
// Save our config referance
this.config = options;
this.config.handlers = [];
this.config.containers = [];
// Normalize our url configs
this.config.root = normalizeUrl(this.config.root);
this.config.assetRoot = this.config.assetRoot ? normalizeUrl(this.config.assetRoot) : this.config.root;
this.config.jsPath = normalizeUrl(this.config.assetRoot, this.config.jsPath);
this.config.cssPath = normalizeUrl(this.config.assetRoot, this.config.cssPath);
// Get a unique instance id for this router
this.uid = $.uniqueId('router');
// Allow user to override error route
this.config.errorRoute && (ERROR_ROUTE_NAME = this.config.errorRoute);
// Convert our routeMappings to regexps and push to our handlers
_.each(this.config.routeMapping, function(value, route){
var regex = this._routeToRegExp(route);
this.config.handlers.unshift({ route: route, regex: regex, app: value });
}, this);
// Use the user provided container, or default to the closest `<main>` tag
|
javascript
|
{
"resource": ""
}
|
|
q3708
|
train
|
function(container){
// Navigate to route for any link with a relative href
$(container).on('click', 'a', (e) => {
var path = e.target.getAttribute('href');
// If the path is a remote URL, allow the browser to navigate normally.
// Otherwise, prevent default so we can handle the route event.
if(IS_REMOTE_URL.test(path) || path === '#'){ return void 0; }
|
javascript
|
{
"resource": ""
}
|
|
q3709
|
train
|
function(){
var routes = this.current ? (this.current.data.routes || {}) : {};
routes[this._previousRoute] = '';
// Unset Previous Application's Routes. For each route in the page app, remove
// the handler from our route object and delete our referance to the route's callback
_.each(routes, (value, key) => {
var regExp = this._routeToRegExp(key).toString();
Backbone.history.handlers = _.filter(Backbone.history.handlers, function(obj){
return obj.route.toString() !== regExp;
});
});
if(!this.current){ return void 0;
|
javascript
|
{
"resource": ""
}
|
|
q3710
|
train
|
function(PageApp, appName, container) {
var oldPageName, pageInstance, routes = [];
var isService = (container !== this.config.container);
var name = (isService) ? appName : 'page';
// If no container exists, throw an error
if(!container) throw 'No container found on the page! Please specify a container that exists in your Rebound config.';
// Add page level loading class
container.classList.remove('error', 'loading');
// Uninstall any old resource we have loaded
if(!isService && this.current){ this._uninstallResource(); }
// Load New PageApp, give it it's name so we know what css to remove when it deinitializes
pageInstance = ComponentFactory(PageApp).el;
if(SERVICES[name].isLazyComponent){ SERVICES[name].hydrate(pageInstance.data); }
else{ SERVICES[name] = pageInstance.data; }
pageInstance.__pageId = this.uid + '-' + appName;
// Add to our page
$(container).empty();
container.appendChild(pageInstance);
//
|
javascript
|
{
"resource": ""
}
|
|
q3711
|
train
|
function(route, container) {
var appName, routeName,
isService = (container !== this.config.container),
isError = (route === ERROR_ROUTE_NAME);
// Normalize Route
route || (route = '');
// Get the app name from this route
appName = routeName = (route.split('/')[0] || 'index');
// If this isn't the error route, Find Any Custom Route Mappings
if(!isService && !isError){
this._currentRoute = route.split('/')[0];
_.any(this.config.handlers, (handler) => {
if (handler.regex.test(route)){
appName = handler.app;
this._currentRoute = handler.route;
return true;
}
});
}
// Wrap these async resource fetches in a promise and return it.
// This promise resolves when both css and js resources are loaded
// It rejects if either of the css or js resources fails to load.
return new Promise((resolve, reject) => {
var throwError = (err) => {
// If we are already in an error state, this means we were unable to load
// a custom error page. Uninstall anything we have and insert our default 404 page.
if(this.status === ERROR){
if(isService) return resolve(err);
this._uninstallResource();
container.innerHTML = DEFAULT_404_PAGE;
return resolve(err);
}
// Set our status to error and attempt to load a custom error page.
console.error('Could not ' + ((isService) ? 'load the ' + appName + ' service:' : 'find the ' + (appName || 'index') + ' app.'), 'at', ('/' + route));
this.status = ERROR;
|
javascript
|
{
"resource": ""
}
|
|
q3712
|
clone
|
train
|
function clone(object) {
// check if the object is an object and isn't empty
if (is(object) && !empty(object)) {
// create a new object for the result
const result = {};
// for each key in the specified object add it
// to the new result with the value from the
// original object
Object.keys(object).forEach((key) => {
result[key]
|
javascript
|
{
"resource": ""
}
|
q3713
|
endListener
|
train
|
function endListener(state) {
// Note: If incremental is conclusive for 'end' event, this will be called
// with isDone === true, since removeListener doesn't affect listeners for
// an event which is already in-progress.
if (state.ended || isDone) {
return;
}
state.ended = true;
ended += 1;
debug(`${streamName(this)} has ended.`);
if (options.incremental) {
if (doCompare(options.incremental, CompareType.incremental)) {
return;
}
}
if (ended === 2) {
const postEndCompare = function() {
doCompare(options.compare, CompareType.last);
};
if (options.delay) {
|
javascript
|
{
"resource": ""
}
|
q3714
|
addData
|
train
|
function addData(data) {
if (options.objectMode) {
if (!this.data) {
this.data = [data];
} else {
this.data.push(data);
}
this.totalDataLen += 1;
} else if (typeof data !== 'string' && !(data instanceof Buffer)) {
throw new TypeError(`expected string or Buffer, got ${
Object.prototype.toString.call(data)}. Need objectMode?`);
} else if (this.data === null || this.data === undefined) {
this.data = data;
this.totalDataLen += data.length;
} else if (typeof this.data === 'string' && typeof data === 'string') {
// perf: Avoid unnecessary string concatenation
if
|
javascript
|
{
"resource": ""
}
|
q3715
|
handleData
|
train
|
function handleData(state, data) {
debug('Read data from ', streamName(this));
try {
addData.call(state, data);
} catch (err) {
|
javascript
|
{
"resource": ""
}
|
q3716
|
readNext
|
train
|
function readNext() {
let stream, state;
while (!isDone) {
if (!state1.ended
&& (state2.ended || state1.totalDataLen <= state2.totalDataLen)) {
stream = stream1;
state = state1;
} else if (!state2.ended) {
stream = stream2;
state = state2;
} else {
debug('All streams have ended. No further reads.');
return;
}
const data = stream.read();
if (data
|
javascript
|
{
"resource": ""
}
|
q3717
|
train
|
function(operation, parameters) {
var req;
req = getXmlReqHeader.call(this);
req.push('<Operation><Name>', operation, '</Name>', '<Params>');
if (parameters) {
// don't send raw '&', but don't change '&', '<', etc.
req.push(
parameters.replace(/&/g, "&")
|
javascript
|
{
"resource": ""
}
|
|
q3718
|
evenly
|
train
|
function evenly(iterables) {
const iterators = iterables.map(iterable => createIterator(iterable, { strict: false }));
const empties = new Set();
const count = iterators.length;
let index = -1;
/**
* Returns next iterator.
*
* Returns the first iterator after the last one.
*
* @returns {Iterator}
*/
function step() {
// Back to the first iterator.
if (index === count - 1) {
index = -1;
}
// Go to the next iterator.
index++;
// Ignore empty iterators.
while(empties.has(index)) {
if (index === count - 1) {
index = -1;
}
index++;
}
return iterators[index];
}
/**
* Returns next value.
*
* @returns {{done: boolean, value: *}}
|
javascript
|
{
"resource": ""
}
|
q3719
|
step
|
train
|
function step() {
// Back to the first iterator.
if (index === count - 1) {
index = -1;
}
// Go to the next iterator.
index++;
// Ignore empty iterators.
while(empties.has(index)) {
|
javascript
|
{
"resource": ""
}
|
q3720
|
next
|
train
|
function next() {
// Exit if all iterators are traversed.
if (empties.size === count) {
return done;
}
// Go to the next iterator.
const iter = step();
const res = iter.next();
//
|
javascript
|
{
"resource": ""
}
|
q3721
|
series
|
train
|
function series(iterables) {
if (iterables.length === 0) {
return createIterator();
}
let iter = createIterator(iterables.shift(), { strict: false });
return {
[Symbol.iterator]() { return this; },
next() {
let next = iter.next();
// If iterator is ended go to the next.
// If next iterator is empty (is ended) go to the next,
// until you get not empty iterator, or all iterators are ended.
while (next.done) {
|
javascript
|
{
"resource": ""
}
|
q3722
|
transformMessageToRequestMessage
|
train
|
function transformMessageToRequestMessage(message) {
const newMessage = {
info: message.info,
hops: message.hops
};
let payload;
if (message.payload === 'string') {
payload = message.payload;
} else if (message.payload instanceof stream.Stream) {
payload = message.payload;
} else {
// expect that it is JSON
payload = JSON.stringify(message.payload);
}
// make the message a form
|
javascript
|
{
"resource": ""
}
|
q3723
|
unpackToMessage
|
train
|
function unpackToMessage(request, forwardFunction) {
const busboy = new Busboy({
headers: request.headers
});
return new Promise((resolve, reject) => {
// the message which will be forwarded
const newMessage = {};
let resultPromise;
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
if (fieldname === 'payload') {
// This is a stream payload
newMessage.payload = file;
if (forwardFunction) {
resolve(forwardFunction(newMessage));
} else {
resolve(newMessage);
|
javascript
|
{
"resource": ""
}
|
q3724
|
train
|
function(arr){
var i, len = arr.length;
this.added || (this.added = {});
arr.forEach((item) => {
|
javascript
|
{
"resource": ""
}
|
|
q3725
|
onReset
|
train
|
function onReset(data, options){
trigger.call(this, 'reset',
|
javascript
|
{
"resource": ""
}
|
q3726
|
train
|
function(attributes, options={}){
var self = this;
if(attributes === null || attributes === undefined){ attributes = {}; }
attributes.isModel && (attributes = attributes.attributes);
this.helpers = {};
this.defaults
|
javascript
|
{
"resource": ""
}
|
|
q3727
|
train
|
function(attr, options) {
options = options ? _.clone(options) : {};
var val = this.get(attr);
if(!_.isBoolean(val)) console.error('Tried to toggle non-boolean
|
javascript
|
{
"resource": ""
}
|
|
q3728
|
train
|
function(obj, options){
var changed = {}, key, value;
options || (options = {});
options.reset = true;
obj = (obj && obj.isModel && obj.attributes) || obj || {};
options.previousAttributes = _.clone(this.attributes);
// Any unset previously existing values will be set back to default
_.each(this.defaults, function(val, key){
if(!obj.hasOwnProperty(key)){ obj[key] = val; }
}, this);
// Iterate over the Model's attributes:
// - If the property is the `idAttribute`, skip.
// - If the properties are already the same, skip
// - If the property is currently undefined and being changed, assign
// - If the property is a `Model`, `Collection`, or `ComputedProperty`, reset it.
// - If the passed object has the property, set it to the new value.
// - If the Model has a default value for this property, set it back to default.
|
javascript
|
{
"resource": ""
}
|
|
q3729
|
train
|
function() {
if (this._isSerializing){ return this.id || this.cid; }
this._isSerializing = true;
var json = _.clone(this.attributes);
_.each(json, function(value, name) {
if( _.isNull(value) || _.isUndefined(value) ){ return void
|
javascript
|
{
"resource": ""
}
|
|
q3730
|
getCoverageReport
|
train
|
function getCoverageReport (folder) {
var reports = grunt.file.expand(folder + '*/index.html');
if (reports && reports.length > 0) {
|
javascript
|
{
"resource": ""
}
|
q3731
|
getAuthConfigs
|
train
|
function getAuthConfigs(modelName) {
return _.filter(internals.authConfig, function hasSameModelName(c) {
|
javascript
|
{
"resource": ""
}
|
q3732
|
setModel
|
train
|
function setModel(Model, modelName) {
let authConfigs;
if (!internals.acl) {
throw new Error('Attempt to shield model before setting acl');
}
if (!internals.authConfig.length) {
throw new Error('Attempt to shield model before seting configs');
}
// raise shield around Model
new Shield(Model,
|
javascript
|
{
"resource": ""
}
|
q3733
|
validate
|
train
|
function validate(options) {
const schema = joi.object().keys({
config: joi.array().min(_.keys(options.models).length).required(),
acl: joi.object().required(),
|
javascript
|
{
"resource": ""
}
|
q3734
|
init
|
train
|
function init(options) {
validate(options);
setAuthConfig(options.config);
|
javascript
|
{
"resource": ""
}
|
q3735
|
Radio
|
train
|
function Radio (url) {
var self = this;
Block.apply(self, arguments);
self.audio = document.createElement('audio');
self.audio.autoplay = true;
self.audio.src = self.url;
self.node = self.app.context.createMediaElementSource(self.audio);
|
javascript
|
{
"resource": ""
}
|
q3736
|
keys
|
train
|
function keys(object, follow = false) {
// check if the object is an object and it's not empty
if (is(object) && !empty(object)) {
// create an empty array for the result
let result = [];
// if follow is enabled
if (follow) {
// create a new function which gets the keys and
// adds them with dot notation to the results array
const followKeys = (obj, currentPath) => {
// get all the keys for the inner object
Object.keys(obj).forEach((key) => {
// parse the dot notation path
const followPath = `${currentPath}.${key}`;
// if the result is an object run the function again
// for that object
if (is(obj[key]) && !empty(obj[key])) {
// the value is an object so run the function again
// for that object but with the new path
followKeys(obj[key], followPath);
}
// add the new parsed path to the result object
result.push(followPath);
});
};
// for each key in the specified object
Object.keys(object).forEach((key) => {
|
javascript
|
{
"resource": ""
}
|
q3737
|
hierarchy
|
train
|
function hierarchy (config) {
const templates = _.mapValues(config.templates, augmentSingleFile)
const partials = _.mapValues(config.partials, augmentSingleFile)
return {
children: Object.keys(templates).map((name) => {
let template = templates[name]
return {
name: name,
type: 'template',
path: template.path,
comments: template.comments,
children: template.callsPartial
.map((callee) => callee.name)
|
javascript
|
{
"resource": ""
}
|
q3738
|
partialForCallTree
|
train
|
function partialForCallTree (name, partials, visitedNodes) {
const cycleFound = visitedNodes[name]
try {
visitedNodes[name] = true
const partial = partials[name]
if (!partial) {
throw new Error(`Missing partial "${name}"`)
}
let children
if (!cycleFound) {
children = partial.callsPartial
.map((callee) => callee.name)
// Remove redundant names (only take the first one)
|
javascript
|
{
"resource": ""
}
|
q3739
|
keyOf
|
train
|
function keyOf(object, value, follow = false) {
// if the object is an object and is not empty
if (is(object) && !empty(object)) {
// create a found boolean so we can skip
// over keys once we have found the correct
// key
let found = false;
// create an result variable as false
let result = '';
// for each key/value in the object
// follow is passed into each therefore the
// each function works out whether to follow
// the objects
|
javascript
|
{
"resource": ""
}
|
q3740
|
every
|
train
|
function every(object, iterator, follow = false) {
// if the object is an object and is not empty
if (is(object) && !empty(object) && typeof iterator === 'function') {
// set the result to true so we can change it
// to false if the iterator fails
let result = true;
// for each over the object keys and values
// follow is passed into each therefore the
// each function works out whether to follow
// the objects
each(object, (key, value) => {
// run the iterator function on the key and
// value and if it evaluates to false set
// the result to false
|
javascript
|
{
"resource": ""
}
|
q3741
|
parseStaticRoutes
|
train
|
function parseStaticRoutes(config) {
Object.keys(config).map((key) => {
StaticRoutes.push({
method: 'get',
route: key,
controller: config[key].target,
action: '*',
|
javascript
|
{
"resource": ""
}
|
q3742
|
extractErrorHandler
|
train
|
function extractErrorHandler(target, name) {
if(name.indexOf('#') !== -1) {
const [controller, action] = name.split('#');
|
javascript
|
{
"resource": ""
}
|
q3743
|
generate
|
train
|
function generate() {
for(const i in Routes) {
if(!Routes[i].generated) {
Routes[i] = generateController(path.controllers, Routes[i]);
}
}
for(const i in MiddleWares) {
MiddleWares[i] = generateController(path.middlewares, MiddleWares[i]);
}
for(const i in GlobalMiddleWares) {
GlobalMiddleWares[i] =
|
javascript
|
{
"resource": ""
}
|
q3744
|
train
|
function(prop){
var props = {},
len, i = 0, item;
prop = Array.from(prop);
len = prop.length;
while(len--){
props[prop[i++]] = void 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q3745
|
loadBinary
|
train
|
function loadBinary (file, callback) {
if (isPlask) {
|
javascript
|
{
"resource": ""
}
|
q3746
|
map
|
train
|
function map(object, iterator, follow = false) {
// if the object is an object and is not empty
if (is(object) && !empty(object) && typeof iterator === 'function') {
// create an empty object for the result
let result = {};
// for each key/value in the object
// follow is passed into each therefore the
|
javascript
|
{
"resource": ""
}
|
q3747
|
trending
|
train
|
function trending () {
var language;
var timespan;
var callback;
if (arguments.length === 3) {
language = arguments[0];
timespan = arguments[1];
callback = arguments[2];
}
else if (arguments.length === 2) {
language = arguments[0];
callback = arguments[1];
}
else {
callback = arguments[0];
}
language = (language || 'all').toLowerCase();
timespan = timespan || 'daily';
function onResponse (err, html) {
var repositories;
if (err) {
return callback(new VError(err, 'failed to fetch trending
|
javascript
|
{
"resource": ""
}
|
q3748
|
find
|
train
|
function find(object, iterator, follow) {
// if the object is an object and is not empty
if (is(object) && !empty(object) && typeof iterator === 'function') {
// create an result variable as undefined
let found = false;
let result = '';
// for each key/value in the object
// follow is passed into each therefore the
// each function works out whether to follow
// the objects
each(object, (key, value) => {
// if the value hasn't already been found
if (!found) {
// check if the iterator is false if it
// is false then delete that key from the object
if
|
javascript
|
{
"resource": ""
}
|
q3749
|
loadImage
|
train
|
function loadImage (file, callback, crossOrigin) {
if (isPlask) {
|
javascript
|
{
"resource": ""
}
|
q3750
|
slice
|
train
|
function slice(object, start, end = Object.keys(object).length) {
// if the object is an object and is not empty
if (is(object) && !empty(object)) {
// get the keys from the object
const objKeys = keys(object);
// create an empty object for the result
const result = {};
// slice the object keys to the specified start and end
// and for each key returned
objKeys.slice(start, end).forEach((key) => {
|
javascript
|
{
"resource": ""
}
|
q3751
|
get
|
train
|
function get(object, path, defaultValue = undefined) {
// check if the object is an object and is not empty
// and it has the path specified
if (is(object) && !empty(object) && has(object, path)) {
// set the currentValue to the object so its easier to
// iterate over the objects
let currentValue = object;
// for each path parts from the parsed path
getPathParts(path).forEach((key) => {
|
javascript
|
{
"resource": ""
}
|
q3752
|
has
|
train
|
function has(object, ...paths) {
// check if object is an object
if (is(object) && !empty(object)) {
// set the result to true by default
let hasPaths = true;
// for each path specified
paths.forEach((path) => {
// get the parsed path parts
const parts = getPathParts(path);
// set the current value so its easier to iterate over
let currentValue = object;
// for each part in the path
parts.forEach((key) => {
if (is(currentValue) && !empty(currentValue)) {
currentValue = currentValue[key];
} else {
currentValue = undefined;
}
});
// check if the currentValue is undefined meaning that
|
javascript
|
{
"resource": ""
}
|
q3753
|
train
|
function(stat)
{
if(stat)
{
if(stat.isDirectory)
{
return stat.isDirectory()
}
if(stat.type)
{
|
javascript
|
{
"resource": ""
}
|
|
q3754
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.LOOKS_CHANGESIZEBY,
"args0": [
{
"type": "field_dropdown",
"name": "TYPE",
"options": [
[Blockly.Msg.LOOKS_SETSIZETO_SIZE, 'size'],
|
javascript
|
{
"resource": ""
}
|
|
q3755
|
startsWith
|
train
|
function startsWith(str, test){
if(str === test){ return true; }
|
javascript
|
{
"resource": ""
}
|
q3756
|
push
|
train
|
function push(arr){
var i, len = arr.length;
this.added || (this.added = {});
for(i=0;i<len;i++){
arr[i].markDirty();
|
javascript
|
{
"resource": ""
}
|
q3757
|
recomputeCallback
|
train
|
function recomputeCallback(){
var len = TO_CALL.length;
CALL_TIMEOUT = null;
while(len--){
|
javascript
|
{
"resource": ""
}
|
q3758
|
train
|
function(){
var root = this.__root__;
var context = this.__parent__;
root.__computedDeps || (root.__computedDeps = {});
_.each(this.deps, function(path){
// For each dependancy, mark ourselves as dirty if they become dirty
var dep = root.get(path, {raw: true, isPath: true});
if(dep && dep.isComputedProperty){ dep.on('dirty', this.markDirty); }
// Find actual context and path from relative paths
var split = $.splitPath(path);
while(split[0] === '@parent'){
context = context.__parent__;
split.shift();
}
path = context.__path().replace(/\.?\[.*\]/ig, '.@each');
path = path + (path
|
javascript
|
{
"resource": ""
}
|
|
q3759
|
train
|
function(object){
var target = this.value();
if(!object || !target || !target.isData || !object.isData){ return void 0; }
target._cid || (target._cid = target.cid);
object._cid ||
|
javascript
|
{
"resource": ""
}
|
|
q3760
|
train
|
function(key, options={}){
if(this.returnType === 'value'){ return console.error('Called get on the `'+ this.name +'` computed property which
|
javascript
|
{
"resource": ""
}
|
|
q3761
|
train
|
function(key, val, options={}){
if(this.returnType === null){ return void 0; }
var attrs = key;
var value = this.value();
// Noralize the data passed in
if(this.returnType === 'model'){
if (typeof key === 'object') {
attrs = (key.isModel) ? key.attributes : key;
options = val || {};
} else {
(attrs = {})[key] = val;
}
}
if(this.returnType !== 'model'){ options = val || {}; }
attrs = (attrs && attrs.isComputedProperty) ? attrs.value() : attrs;
// If a new value, set it and trigger events
this.setter && this.setter.call(this.__root__, attrs);
if(this.returnType === 'value' && this.cache.value !== attrs) {
this.cache.value = attrs;
if(!options.quiet){
// If set was called not through computedProperty.call(), this is a fresh new event burst.
if(!this.isDirty && !this.isChanging) this.__parent__.changed = {};
|
javascript
|
{
"resource": ""
}
|
|
q3762
|
train
|
function(obj, options={}){
if(_.isNull(this.returnType)){ return void 0; }
options.reset
|
javascript
|
{
"resource": ""
}
|
|
q3763
|
train
|
function() {
if (this._isSerializing){ return this.cid; }
var val = this.value();
this._isSerializing = true;
var json =
|
javascript
|
{
"resource": ""
}
|
|
q3764
|
fromEventCapture
|
train
|
function fromEventCapture(element, name) {
return Observable.create((subj) => {
const handler = function (...args) {
if (args.length > 1) {
subj.next(args);
} else {
subj.next(args[0] || true);
}
|
javascript
|
{
"resource": ""
}
|
q3765
|
train
|
function(obj){
var validators = Object.clone(this._validators),
// Store the global validator
global = validators[asterisk], keys;
// If global validator exists, test the object against it
if (global) {
// remove '*' validator from validators obj otherwise comparing keys will not pass
delete validators[asterisk];
// retrieve keys of obj for comparison;
keys = Object.keys(obj);
|
javascript
|
{
"resource": ""
}
|
|
q3766
|
respond
|
train
|
function respond(ctx) {
// allow bypassing koa
if (false === ctx.respond) return;
const res = ctx.res;
if (!ctx.writable) return;
let body = ctx.body;
const code = ctx.status;
// ignore body
if (statuses.empty[code]) {
// strip headers
ctx.body = null;
return res.end();
}
if ("HEAD" == ctx.method) {
if (!res.headersSent && isJSON(body)) {
ctx.length = Buffer.byteLength(JSON.stringify(body));
}
return res.end();
}
// status body
if (null == body) {
body = ctx.message || String(code);
if (!res.headersSent) {
ctx.type = "text";
ctx.length = Buffer.byteLength(body);
}
return res.end(body);
|
javascript
|
{
"resource": ""
}
|
q3767
|
getHexValue
|
train
|
function getHexValue(rune) {
if ("0" <= rune && rune <= "9") {
return rune.charCodeAt(0) - 48;
}
if ("a" <= rune && rune <= "f") {
return rune.charCodeAt(0) - 87;
|
javascript
|
{
"resource": ""
}
|
q3768
|
flip
|
train
|
function flip(object, follow = false, useToString = false) {
// if the object is an object and is not empty
if (is(object) && !empty(object)) {
// create an empty object for the result
const result = {};
// for each key/value in the object
each(object, (key, value) => {
// if the value is a string it can be used as
// the new key
if (typeof value === 'string') {
// set the new key/value to the result
result[value] = key;
} else if (typeof value !== 'string' && useToString) {
|
javascript
|
{
"resource": ""
}
|
q3769
|
traverse
|
train
|
function traverse(segments, tree, trail, iteration) {
if (iteration === undefined) {
iteration = 0;
}
iteration += 1;
var last = segments.pop();
if (last) {
if (tree[last] !== undefined) {
trail.unshift(last);
return traverse(segments, tree[last], trail);
}
if (tree["*"] !== undefined) {
if (tree["!" + last] !== undefined) {
return last;
}
trail.unshift(last);
return traverse(segments, tree["*"], trail);
}
if (tree[true]) {
return last;
|
javascript
|
{
"resource": ""
}
|
q3770
|
reverse
|
train
|
function reverse(iterable) {
assert(
arguments.length < 2,
'The `resolve()` method not support more than one argument. Use `series() or `evenly()` to combine iterators.'
);
if (arguments.length === 0) {
return createIterator();
}
const iter = createIterator(iterable);
const arr = Array.from(iter);
let index = arr.length - 1;
|
javascript
|
{
"resource": ""
}
|
q3771
|
forEachValue
|
train
|
function forEachValue (obj, iteratee) {
Object.keys(obj).forEach((key)
|
javascript
|
{
"resource": ""
}
|
q3772
|
train
|
function(){
if(this.cache === NIL){ return void 0; }
this.cache = NIL;
for (var i
|
javascript
|
{
"resource": ""
}
|
|
q3773
|
train
|
function() {
this.makeDirty();
for (var i = 0, l = this.subscribers.length; i < l; i++) {
if(!this.subscribers[i]){ continue; }
|
javascript
|
{
"resource": ""
}
|
|
q3774
|
set
|
train
|
function set(object, path, value) {
// check if the object is an object
if (is(object)) {
// clone the object
let cloned = clone(object);
// set a new value for the cloned object so we
// can manipulate it
const result = cloned;
// get the path parts
const pathParts = getPathParts(path);
// loop over all the path parts
for (let index = 0; index < pathParts.length; index += 1) {
// get the current key
const key = pathParts[index];
// check if the value is an object
if (!is(cloned[key])) {
// if it isn't an object set it to an empty object
cloned[key] = {};
|
javascript
|
{
"resource": ""
}
|
q3775
|
Microphone
|
train
|
function Microphone (options) {
var self = this;
Block.apply(self, arguments);
//get access to the microphone
getUserMedia({video: false, audio: true}, function (err, stream) {
if (err) {
console.log('failed to get microphone');
|
javascript
|
{
"resource": ""
}
|
q3776
|
moduleIfString
|
train
|
function moduleIfString (pathOrObject, type) {
// If this is a string, treat if as module to be required
try {
if (_.isString(pathOrObject)) {
// Attempt to find module without resolving the contents
// If there is an error, the module does not exist (which
// is ignored at the moment)
// If there is no error, the module should be loaded and error while loading
// the module should be reported
require.resolve(path.resolve(pathOrObject))
}
|
javascript
|
{
"resource": ""
}
|
q3777
|
train
|
function(fm, extraObj) {
// `init` event callback function
fm.bind('init', function() {
// Optional for Japanese decoder "encoding-japanese"
if (fm.lang === 'ja') {
require(
[ 'encoding-japanese' ],
function(Encoding) {
|
javascript
|
{
"resource": ""
}
|
|
q3778
|
createCmdButton
|
train
|
function createCmdButton(cmd, label, forceCheckbox, className) {
var button;
button = document.createElement('button');
button.className = className || 'btn';
button.innerHTML = label;
button.onclick = function() {
var cl;
var clients, doLogic;
cl = node.game.clientList;
// Get selected clients.
clients = cl.getSelectedClients();
if (!clients || clients.length === 0) return;
// If the room's logic client is selected, handle it specially.
if (node.game.roomLogicId) {
doLogic = J.removeElement(cl.roomLogicId, clients);
|
javascript
|
{
"resource": ""
}
|
q3779
|
train
|
function() {
var e = this.originalEvent;
this.defaultPrevented = true;
this.isDefaultPrevented = returnTrue;
|
javascript
|
{
"resource": ""
}
|
|
q3780
|
getCallbacks
|
train
|
function getCallbacks(target, delegate, eventType){
var callbacks = [];
if(target.delegateGroup && EVENT_CACHE[target.delegateGroup][eventType]){
_.each(EVENT_CACHE[target.delegateGroup][eventType], function(callbacksList,
|
javascript
|
{
"resource": ""
}
|
q3781
|
enumerateFunctions
|
train
|
function enumerateFunctions(relations) {
const blacklist = [
'use',
'tearDown',
'define'
];
return _.reduce(relations, function(functions,
|
javascript
|
{
"resource": ""
}
|
q3782
|
each
|
train
|
function each(object, iterator, follow = false) {
// check if the object is an object and isn't empty
// if it is it would be pointless running the forEach
if (is(object) && !empty(object) && typeof iterator === 'function') {
// if follow is true flatten the object keys so
// its easy to get the path and values if follow
// is false it will just be the base object
// therefore it will only use the base keys
const flattenedObject = follow
? deflate(object)
: object;
// loop over the keys of the object
Object.keys(flattenedObject).forEach((key) => {
// get the value of the current
|
javascript
|
{
"resource": ""
}
|
q3783
|
includes
|
train
|
function includes(object, value, follow = false) {
// if the object is an object and is not empty
if (is(object) && !empty(object)) {
// create an result variable as false
let result = false;
// for each key/value in the object
// follow is passed into each therefore the
// each function works out whether to follow
// the objects
each(object, (key, objValue) => {
// if the result isn't already true
if (!result) {
// check if the object value is equal to
// the specified value
if (objValue === value)
|
javascript
|
{
"resource": ""
}
|
q3784
|
_publish
|
train
|
function _publish(obj, callback) {
// Write the object to the separate file.
var shortname = prop + '.json';
var data = JSON.stringify(obj);
var hash = _checkNewHash(shortname, data);
if (!hash) {
// No need to publish if the data is the same.
return callback();
}
published[shortname] = true;
// Update new object
|
javascript
|
{
"resource": ""
}
|
q3785
|
close
|
train
|
function close() {
if (watcher && !closed) {
if (options.persistent) {
// Close handle only if watcher was created persistent.
watcher.close();
}
else {
// Stop handling change events.
watcher.removeAllListeners();
|
javascript
|
{
"resource": ""
}
|
q3786
|
_updateSingleton
|
train
|
function _updateSingleton() {
if (!options.singletons) {
return;
}
if (process.rebusinstances[folder]) {
|
javascript
|
{
"resource": ""
}
|
q3787
|
_startWatchdog
|
train
|
function _startWatchdog() {
if (!watcher) {
var watcherOptions = { persistent: !!options.persistent };
watcher = fs.watch(folder, watcherOptions, function (event, filename) {
if (event === 'change' && filename.charAt(0) != '.') {
// On every change load the changed
|
javascript
|
{
"resource": ""
}
|
q3788
|
_loadFile
|
train
|
function _loadFile(filename, callback) {
callback = callback || function () { };
if (filename.charAt(0) == '.') {
callback();
return;
}
var filepath = path.join(folder, filename);
fs.readFile(filepath, function (err, data) {
if (err) {
console.error('Failed to read file ' + filepath + ' err:', err);
callback(err);
return;
}
try {
_loadData(filename, data.toString());
}
catch (e) {
console.info('Object ' + filename + ' was not yet fully written, exception:', e);
// There will be another notification of change when the last write to file is completed.
// Meanwhile leave the previous value.
if (loader) {
// Store this error to wait until file will be successfully loaded for the 1st time.
loader.errors[filename] = e;
}
// Don't return error to continue asynchronous loading of other files. Errors are assembled on loader.
callback();
return;
}
console.log('Loaded ' + filename);
if (loader) {
|
javascript
|
{
"resource": ""
}
|
q3789
|
_traverse
|
train
|
function _traverse(props, obj, notification) {
var length = props.length;
var refobj = shared;
var refmeta = meta;
var handler = {};
var fns = [];
for (var i = 0; i < length; i++) {
var prop = props[i];
if (!refmeta[prop]) {
refmeta[prop] = {};
refmeta[prop][nfs] = {};
}
var currentmeta = refmeta[prop];
if (!refobj[prop]) {
refobj[prop] = {};
}
var currentobj = refobj[prop];
if (i === (length - 1)) {
// The end of the path.
if (obj) {
// Pin the object here.
refobj[prop] = obj;
// Since object changed, append all notifications in the subtree.
_traverseSubtree(currentmeta, obj, fns);
}
if (notification) {
// Pin notification at the end of the path.
var id = freeId++;
currentmeta[nfs][id] = notification;
// Return value indicates where the notification was pinned.
handler = { id: id, close: closeNotification };
handler[nfs] = currentmeta[nfs];
// Call the notification with initial value
|
javascript
|
{
"resource": ""
}
|
q3790
|
_traverseSubtree
|
train
|
function _traverseSubtree(meta, obj, fns) {
_pushNotifications(meta, obj, fns);
for (var key in meta) {
if (key === nfs) {
continue;
}
var subobj;
if
|
javascript
|
{
"resource": ""
}
|
q3791
|
_pushNotifications
|
train
|
function _pushNotifications(meta, obj, fns) {
for (var id in meta[nfs]) {
fns.push(function (i) {
return function () {
|
javascript
|
{
"resource": ""
}
|
q3792
|
children
|
train
|
function children(tree, query, options) {
var compiledQuery = query ? _.matches(query) : null;
var settings = _.defaults(options, {
childNode: ['children']
});
settings.childNode = _.castArray(settings.childNode);
var rootNode = query ? treeTools.find(tree, query) : tree;
|
javascript
|
{
"resource": ""
}
|
q3793
|
getPackageInfoFrom
|
train
|
function getPackageInfoFrom(string) {
if (string[0] === '@') {
const [scope, rawName] = string.split('/');
const { name, version } = getVersionFromString(rawName);
return {
|
javascript
|
{
"resource": ""
}
|
q3794
|
visProps
|
train
|
function visProps(props) {
const {
data,
height,
width,
} = props;
const padding = {
top: 20,
right: 20,
bottom: 40,
left: 50,
};
const plotAreaWidth = width - padding.left - padding.right;
const plotAreaHeight = height - padding.top - padding.bottom;
const xDomain = d3.extent(data, d => d.x);
const yDomain = d3.extent(data, d => d.y);
const xDomainPadding = 0.05 * xDomain[1];
const yDomainPadding = 0.02 * yDomain[1];
const xScale = d3.scaleLinear()
.domain([xDomain[0] - xDomainPadding, xDomain[1] + xDomainPadding])
.range([0, plotAreaWidth]);
const yScale = d3.scaleLinear()
|
javascript
|
{
"resource": ""
}
|
q3795
|
excludeIncludeKeys
|
train
|
function excludeIncludeKeys(objA, objB, excludeKeys, includeKeys) {
let keysA = Object.keys(objA);
let keysB = Object.keys(objB);
if (excludeKeys) {
keysA = keysA.filter(key => excludeKeys.indexOf(key) === -1);
keysB = keysB.filter(key => excludeKeys.indexOf(key) === -1);
} else if
|
javascript
|
{
"resource": ""
}
|
q3796
|
loadPlugin
|
train
|
function loadPlugin(descriptor, loader) {
const config = Array.isArray(descriptor) ? descriptor : [descriptor];
const [name, options = {}] = config;
const { error, module: plugin } = loader(name);
if (error) {
|
javascript
|
{
"resource": ""
}
|
q3797
|
loadPreset
|
train
|
function loadPreset(descriptor, loader) {
const config = Array.isArray(descriptor) ? descriptor : [descriptor];
const [name, options = {}] = config;
const { error: loaderError, module: getPreset } = loader(name);
if (loaderError) {
return {
error: loaderError,
name,
};
}
if (typeof getPreset !== 'function') {
return {
error: new Error(
`Expected the preset \`${name}\` to export a function, instead ` +
`recieved: ${typeof getPreset}`
),
name,
};
}
let preset;
try {
preset =
|
javascript
|
{
"resource": ""
}
|
q3798
|
create
|
train
|
async function create(name, options, api, env) {
// Grab the cwd and npmClient off of the environment. We can use these to
// create the folder for the project and for determining what client to use
// for npm-related commands
const { CLI_ENV, cwd, npmClient } = env;
// We support a couple of options for our `create` command, some only exist
// during development (like link and linkCli).
const { link, linkCli, plugins = [], presets = [], skip } = options;
const root = path.join(cwd, name);
logger.trace('Creating project:', name, 'at:', root);
if (await fs.exists(root)) {
throw new Error(`A folder already exists at \`${root}\``);
}
// Create the root directory for the new project
await fs.ensureDir(root);
const {
writePackageJson,
installDependencies,
linkDependencies,
} = await createClient(npmClient, root);
const packageJson = {
name,
private: true,
license: 'MIT',
scripts: {},
dependencies: {},
devDependencies: {},
toolkit:
|
javascript
|
{
"resource": ""
}
|
q3799
|
collect
|
train
|
function collect(str, type) {
if (!type) {
if (otherRE.test(str)) {
// base type, null|undefined etc.
type = 'base';
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.