_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q28500 | resolveNative | train | function resolveNative(success, fail, path, fsType, options, size) {
window.webkitRequestFileSystem(
fsType,
size,
function (fs) {
if (path === '') {
//no path provided, call success with root file system
success(createEntryFromNative(fs.root));
} else {
//otherwise attempt to resolve as file
fs.root.getFile(
path,
options,
function (entry) {
success(createEntryFromNative(entry));
},
function (fileError) {
//file not found, attempt to resolve as directory
fs.root.getDirectory(
path,
options,
function (entry) {
success(createEntryFromNative(entry));
},
function (dirError) {
//path cannot be resolved
if (fileError.code === FileError.INVALID_MODIFICATION_ERR &&
options.exclusive) {
//mobile-spec expects this error code
fail(FileError.PATH_EXISTS_ERR);
} else {
fail(FileError.NOT_FOUND_ERR);
}
}
);
}
);
}
}
);
} | javascript | {
"resource": ""
} |
q28501 | train | function (pattern, repeat) {
repeat = (typeof repeat !== 'undefined') ? repeat : -1;
pattern = pattern.unshift(0); // add a 0 at beginning for backwards compatibility from w3c spec
exec(null, null, 'Vibration', 'vibrateWithPattern', [pattern, repeat]);
} | javascript | {
"resource": ""
} | |
q28502 | read | train | function read(context) {
const projectRoot = getProjectRoot(context);
const configXml = getConfigXml(projectRoot);
const branchXml = getBranchXml(configXml);
const branchPreferences = getBranchPreferences(
context,
configXml,
branchXml
);
validateBranchPreferences(branchPreferences);
return branchPreferences;
} | javascript | {
"resource": ""
} |
q28503 | getConfigXml | train | function getConfigXml(projectRoot) {
const pathToConfigXml = path.join(projectRoot, "config.xml");
const configXml = xmlHelper.readXmlAsJson(pathToConfigXml);
if (configXml == null) {
throw new Error(
"BRANCH SDK: A config.xml is not found in project's root directory. Docs https://goo.gl/GijGKP"
);
}
return configXml;
} | javascript | {
"resource": ""
} |
q28504 | getProjectName | train | function getProjectName(configXml) {
let output = null;
if (configXml.widget.hasOwnProperty("name")) {
const name = configXml.widget.name[0];
if (typeof name === "string") {
// handle <name>Branch Cordova</name>
output = configXml.widget.name[0];
} else {
// handle <name short="Branch">Branch Cordova</name>
output = configXml.widget.name[0]._;
}
}
return output;
} | javascript | {
"resource": ""
} |
q28505 | getProjectModule | train | function getProjectModule(context) {
const projectRoot = getProjectRoot(context);
const projectPath = path.join(projectRoot, "platforms", "ios");
try {
// pre 5.0 cordova structure
return context
.requireCordovaModule("cordova-lib/src/plugman/platforms")
.ios.parseProjectFile(projectPath);
} catch (e) {
try {
// pre 7.0 cordova structure
return context
.requireCordovaModule("cordova-lib/src/plugman/platforms/ios")
.parseProjectFile(projectPath);
} catch (e) {
// post 7.0 cordova structure
return getProjectModuleGlob(context);
}
}
} | javascript | {
"resource": ""
} |
q28506 | updateNpmVersion | train | function updateNpmVersion(pluginConfig, config, callback) {
const files = readFilePaths(FILES);
const version = config.nextRelease.version;
let git = "";
for (let i = 0; i < files.length; i++) {
// update
const file = files[i];
const content = readContent(file);
const updated = updateVersion(file, content, version);
// save
git += `git add ${file} && `;
saveContent(file, updated);
}
// publish
isChange && commitChanges(git, version);
} | javascript | {
"resource": ""
} |
q28507 | updateVersion | train | function updateVersion(file, content, version) {
const prev = /id="branch-cordova-sdk"[\s]*version="\d+\.\d+\.\d+"/gim;
const next = `id="branch-cordova-sdk"\n version="${version}"`;
try {
if (isFileXml(file)) {
content = content.replace(prev, next);
} else {
isChange = content.version !== version;
content.version = version;
}
} catch (e) {
throw new Error(
`BRANCH SDK: update to update npm version with file ${file}`
);
}
return content;
} | javascript | {
"resource": ""
} |
q28508 | readFilePaths | train | function readFilePaths(files) {
const locations = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
const location = path.join(__dirname, "../../../", file);
locations.push(location);
}
return locations;
} | javascript | {
"resource": ""
} |
q28509 | commitChanges | train | function commitChanges(git, version) {
git += `git commit -m "chore: updated npm version to ${version}" && git push`;
exec(git, (err, stdout, stderr) => {
if (err) {
throw new Error(
"BRANCH SDK: Failed to commit git changes for the npm version. Docs https://goo.gl/GijGKP"
);
}
});
} | javascript | {
"resource": ""
} |
q28510 | registerComponent | train | function registerComponent(Vue, name, definition) {
Vue._shards_vue_components_ = Vue._shards_vue_components_ || {};
var loaded = Vue._shards_vue_components_[name];
if (!loaded && definition && name) {
Vue._shards_vue_components_[name] = true;
Vue.component(name, definition);
}
return loaded
} | javascript | {
"resource": ""
} |
q28511 | registerComponents | train | function registerComponents(Vue, components) {
for (var component in components) {
registerComponent(Vue, component, components[component]);
}
} | javascript | {
"resource": ""
} |
q28512 | registerDirective | train | function registerDirective(Vue, name, definition) {
Vue._shards_vue_directives_ = Vue._shards_vue_directives_ || {};
var loaded = Vue._shards_vue_directives_[name];
if (!loaded && definition && name) {
Vue._shards_vue_directives_[name] = true;
Vue.directive(name, definition);
}
return loaded
} | javascript | {
"resource": ""
} |
q28513 | registerDirectives | train | function registerDirectives(Vue, directives) {
for (var directive in directives) {
registerDirective(Vue, directive, directives[directive]);
}
} | javascript | {
"resource": ""
} |
q28514 | train | function (el, className) {
if (className && isElement(el)) {
return el.classList.contains(className)
}
return false
} | javascript | {
"resource": ""
} | |
q28515 | train | function (el, attr, value) {
if (attr && isElement(el)) {
el.setAttribute(attr, value);
}
} | javascript | {
"resource": ""
} | |
q28516 | train | function (el) {
return !isElement(el)
|| el.disabled
|| el.classList.contains('disabled')
|| Boolean(el.getAttribute('disabled'))
} | javascript | {
"resource": ""
} | |
q28517 | train | function (el) {
return isElement(el)
&& document.body.contains(el)
&& el.getBoundingClientRect().height > 0
&& el.getBoundingClientRect().width > 0
} | javascript | {
"resource": ""
} | |
q28518 | train | function (selector, root) {
if (!isElement(root)) {
root = document;
}
return root.querySelector(selector) || null
} | javascript | {
"resource": ""
} | |
q28519 | train | function (selector, root) {
if (!isElement(root)) {
return null
}
var Closest = Element.prototype.closest ||
function (sel) {
var element = this;
if (!document.documentElement.contains(element)) {
return null
}
do {
if (element.matches(sel)) {
return element
}
element = element.parentElement;
} while (element !== null)
return null
};
var el = Closest.call(root, selector);
return el === root ? null : el
} | javascript | {
"resource": ""
} | |
q28520 | train | function (type, breakpoint, val) {
if (!!val === false) {
return false
}
var className = type;
if (breakpoint) {
className += "-" + (breakpoint.replace(type, '')); // -md ?
}
if (type === 'col' && (val === '' || val === true)) {
return className.toLowerCase() // .col-md
}
return (className + "-" + val).toLowerCase()
} | javascript | {
"resource": ""
} | |
q28521 | generateProp | train | function generateProp(type, defaultVal) {
if ( type === void 0 ) type = [Boolean, String, Number];
if ( defaultVal === void 0 ) defaultVal = null;
return {
default: defaultVal,
type: type
}
} | javascript | {
"resource": ""
} |
q28522 | createBreakpointMap | train | function createBreakpointMap(propGenArgs, defaultValue, breakpointWrapper) {
if ( propGenArgs === void 0 ) propGenArgs = null;
if ( breakpointWrapper === void 0 ) breakpointWrapper = null;
var breakpointWrapperArgs = [], len = arguments.length - 3;
while ( len-- > 0 ) breakpointWrapperArgs[ len ] = arguments[ len + 3 ];
breakpointWrapper = breakpointWrapper === null ? function (v) { return v; } : breakpointWrapper;
return BREAKPOINTS.reduce(function (map, breakpoint) {
map[breakpointWrapper.apply(void 0, [ breakpoint ].concat( breakpointWrapperArgs ))] = generateProp(propGenArgs, defaultValue);
return map
}, {})
} | javascript | {
"resource": ""
} |
q28523 | CancelableEvent | train | function CancelableEvent (type, eventInit) {
if ( eventInit === void 0 ) eventInit = {};
Object.assign(this, CancelableEvent.defaults(), eventInit, { type: type });
Object.defineProperties(this, {
type: _makeCancelableEventProps(),
cancelable: _makeCancelableEventProps(),
nativeEvent: _makeCancelableEventProps(),
target: _makeCancelableEventProps(),
relatedTarget: _makeCancelableEventProps(),
vueTarget: _makeCancelableEventProps()
});
var defaultPrevented = false;
this.preventDefault = function preventDefault() {
if (this.cancelable) {
defaultPrevented = true;
}
};
Object.defineProperty(this, 'defaultPrevented', {
enumerable: true,
get: function get() {
return defaultPrevented
}
});
} | javascript | {
"resource": ""
} |
q28524 | train | function () {
if (this$1._config.animation) {
var initConfigAnimation = this$1._config.animation || false;
if (getAttr(TPElement, 'x-placement') !== null) {
return
}
removeClass(TPElement, TP_STATE_CLASSES.FADE);
this$1._config.animation = false;
this$1.hide();
this$1.show();
this$1._config.animation = initConfigAnimation;
}
var prevHoverState = this$1._hoverState;
this$1._hoverState = null;
if (prevHoverState === TOOLTIP_HOVER_STATE_CLASSES.OUT) {
this$1._handleLeave(null);
}
var shownEvt = new CancelableEvent('shown', {
cancelable: false,
target: this$1._targetElement,
relatedTarget: TPElement
});
this$1._emitCustomEvent(shownEvt);
} | javascript | {
"resource": ""
} | |
q28525 | DOMObserver | train | function DOMObserver (el, callback, opts) {
if ( opts === void 0 ) opts = null;
if (opts === null) {
opts = {
subtree: true,
childList: true,
characterData: true,
attributes: true,
attributeFilter: ['class', 'style']
};
}
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var eventListenerSupported = window.addEventListener;
el = el ? (el.$el || el) : null;
if (!isElement(el)) {
return null
}
var obs = null;
if (MutationObserver) {
obs = new MutationObserver(function (mutations) {
var changed = false;
for (var i = 0; i < mutations.length && !changed; i++) {
var mutation = mutations[i];
var type = mutation.type;
var target = mutation.target;
if (type === 'characterData' && target.nodeType === Node.TEXT_NODE) {
changed = true;
} else if (type === 'attributes') {
changed = true;
} else if (type === 'childList' && (mutation.addedNodes.length > 0 || mutation.removedNodes.length > 0)) {
changed = true;
}
}
if (changed) {
callback();
}
});
obs.observe(el, Object.assign({}, { childList: true, subtree: true }, opts));
} else if (eventListenerSupported) {
el.addEventListener('DOMNodeInserted', callback, false);
el.addEventListener('DOMNodeRemoved', callback, false);
}
return obs
} | javascript | {
"resource": ""
} |
q28526 | getUpdatedConfig | train | function getUpdatedConfig() {
var updatedConfig = Object.assign({}, this.baseConfig);
// override title if slot is used
if (this.$refs.title) {
updatedConfig.title = this.$refs.title;
updatedConfig.html = true;
}
// override content if slot is used
if (this.$refs.content) {
updatedConfig.content = this.$refs.content;
updatedConfig.html = true;
}
return updatedConfig
} | javascript | {
"resource": ""
} |
q28527 | parseBindings | train | function parseBindings(bindings) {
var config = {};
switch (typeof bindings.value) {
case 'string':
case 'function':
config.title = bindings.value;
break
case 'object':
config = Object.assign({}, bindings.value);
}
// Parse args (eg: v-d-tooltip:my-container)
if (bindings.arg) {
config.container = "#" + (bindings.arg); // #my-container
}
// Parse modifiers. eg: v-d-tooltip.my-modifier
Object.keys(bindings.modifiers).forEach(function (mod) {
// Parse if the title allows HTML
if (/^html$/.test(mod)) {
config.html = true;
// Parse animation
} else if (/^nofade$/.test(mod)) {
config.animation = false;
// Parse placement
} else if (/^(auto|top(left|right)?|bottom(left|right)?|left(top|bottom)?|right(top|bottom)?)$/.test(mod)) {
config.placement = mod;
// Parse boundary
} else if (/^(window|viewport)$/.test(mod)) {
config.boundary = mod;
// Parse delay
} else if (/^d\d+$/.test(mod)) {
var delay = parseInt(mod.slice(1), 10) || 0;
if (delay) {
config.delay = delay;
}
// Parse offset
} else if (/^o-?\d+$/.test(mod)) {
var offset = parseInt(mod.slice(1), 10) || 0;
if (offset) {
config.offset = offset;
}
}
});
// Parse selected triggers.
var selectedTriggers = {};
var triggers = typeof config.trigger === 'string' ? config.trigger.trim().split(/\s+/) : [];
triggers.forEach(function (trigger) {
if (validTriggers[trigger]) {
selectedTriggers[trigger] = true;
}
});
// Parse trigger modifiers. eg: v-d-tooltip.click
Object.keys(validTriggers).forEach(function (trigger) {
if (bindings.modifiers[trigger]) {
selectedTriggers[trigger] = true;
}
});
config.trigger = Object.keys(selectedTriggers).join(' ');
// Convert `blur` to `focus`
if (config.trigger === 'blur') {
config.trigger = 'focus';
}
// If there's no trigger assigned, just delete the key.
if (!config.trigger) {
delete config.trigger;
}
return config
} | javascript | {
"resource": ""
} |
q28528 | mergeDefaultOptions | train | function mergeDefaultOptions(opts) {
const copy = {};
copyKeys(copy, _defaultOptions);
copyKeys(copy, opts);
Object.keys(_defaultOptions).forEach((key) => {
const obj = _defaultOptions[key];
if (typeof obj === 'object') {
const objCopy = {};
copyKeys(objCopy, obj);
copyKeys(objCopy, copy[key]);
copy[key] = objCopy;
}
});
return copy;
} | javascript | {
"resource": ""
} |
q28529 | parseAttribute | train | function parseAttribute(attribute, defaultValue) {
// 1em, 1.0em, 0.1em, .1em, 1. em
const re = /^(-{0,1}\.{0,1}\d+(\.\d+)?)[\s|\.]*(\w*)$/;
if (attribute && re.test(attribute)) {
const match = re.exec(attribute);
const number = match[1];
const units = match[3] || 'px';
return { value: number * 1, units, original: attribute };
}
if (defaultValue) {
return parseAttribute(defaultValue);
}
return { original: defaultValue };
} | javascript | {
"resource": ""
} |
q28530 | setHTML | train | function setHTML(container, content) {
if (container) {
// Clear out everything in the container
while (container.firstChild) {
container.removeChild(container.firstChild);
}
if (content) {
if (typeof content === 'string') {
container.innerHTML = content;
} else {
container.appendChild(content);
}
}
}
} | javascript | {
"resource": ""
} |
q28531 | toLatLng | train | function toLatLng(v) {
if (v !== undefined && v !== null) {
if (v instanceof google.maps.LatLng) {
return v;
} else if (v.lat !== undefined && v.lng !== undefined) {
return new google.maps.LatLng(v);
}
}
return null;
} | javascript | {
"resource": ""
} |
q28532 | applyCss | train | function applyCss(element, args) {
if (element && args) {
for (var i = 0; i < args.length; i++) {
var className = args[i];
if (className) {
if (element.className) {
element.className += ' ';
}
element.className += _classPrefix + className;
}
}
}
} | javascript | {
"resource": ""
} |
q28533 | blueRadiosAT | train | function blueRadiosAT(command){
if (! wsclient.listeners('notification').length) {
console.log('subscribe to RX notification');
//listen for notification response
wsclient.on('notification', function(peripheralId, serviceUuid, characteristicUuid, data) {
// console.log("NOTIFICATION: " + data.toString('hex') + ' : ' + data.toString('ascii').yellow);
console.log(data.toString('ascii').trim().yellow);
});
}
//convert command to hex, add CR (0x0d = \r) at the end
var hexCommand = new Buffer(command + '\r','ascii');
wsclient.notify(peripheralId, blueRadiosService,blueRadiosRxCharacteristic,true, function() {
wsclient.write(peripheralId, blueRadiosService,blueRadiosCmdCharacteristic, new Buffer('02','hex'), false, function(error) {
console.log('Switch to CMD mode');
wsclient.write(peripheralId, blueRadiosService, blueRadiosTxCharacteristic, hexCommand, false, function(){
console.log('sent CMD: ' + command.cyan);
})
})
});
} | javascript | {
"resource": ""
} |
q28534 | dumpLog | train | function dumpLog(type, peripheralId, serviceUuid, uuid, data ){
var dumpFile=dumpPath + '/' + peripheralId + '.log';
if (servicesLookup[serviceUuid]) {
var serviceName = servicesLookup[serviceUuid].name;
var characteristicName = servicesLookup[serviceUuid].characteristics[uuid].name;
}
var toSave = getDateTime() + ' | ' + type + ' | ' + serviceUuid;
if (serviceName) { toSave += ' (' + serviceName + ')'; };
toSave += ' | ' + uuid;
if (characteristicName) { toSave += ' (' + characteristicName + ')'; };
toSave += ' | ' + data.toString('hex') + ' (' + utils.hex2a(data.toString('hex'))+ ')\n';
fs.appendFile(dumpFile, toSave, function(err) {
if(err) {
return console.log(err);
}
})
} | javascript | {
"resource": ""
} |
q28535 | formatUuid | train | function formatUuid(Uuid) {
var formatted='';
//expand short service/characteristic UUID
if (Uuid.length == 4) {
formatted='0000' + Uuid + '-0000-1000-8000-00805f9b34fb';
}
else { //just add dashes
formatted = Uuid.slice(0,8)+'-'+Uuid.slice(8,12)+'-'+Uuid.slice(12,16)+'-'+Uuid.slice(16,20)+'-'+Uuid.slice(20,32);
}
return formatted;
} | javascript | {
"resource": ""
} |
q28536 | lockCrc | train | function lockCrc(inputStr){
res = 0xff;
inputHex = new Buffer(inputStr,'hex');
//start from the second byte
for (i = 1; i<= inputHex.length; i++) {
res = res ^ inputHex[i];
}
//add padding
reshex = (res+0x100).toString(16).substr(-2);
// console.log(reshex);
return(inputStr+reshex);
} | javascript | {
"resource": ""
} |
q28537 | checkFile | train | function checkFile(peripheralId, callback) {
if (overWriteServices) {
callback(false);
} else {
fs.stat(devicesPath + '/' + peripheralId + '.srv.json', function(err, stat) {
if(err == null) {
callback(true);
// console.log('File exists');
} else {
callback(false)
}
});
}
} | javascript | {
"resource": ""
} |
q28538 | readRaw | train | function readRaw(peripheralId, serviceUuid, uuid, callback){
//todo catch exceptions
var handle = servicesCache[peripheralId].services[serviceUuid].characteristics[uuid].handle;
var peripheral = peripherals[peripheralId];
//if not connected, connect
checkConnected(peripheral, function(){
peripheral.readHandle(handle, function(error, data){
if (error) {
debug('readHandle error : '.red + error)
}
debug('read handle data :' + data.toString('hex'));
sendEvent({
type: 'read',
peripheralId: peripheralId,
serviceUuid: serviceUuid,
characteristicUuid: uuid,
data: data.toString('hex'),
isNotification: false
});
if (callback) { callback(error, data); }
});
})
} | javascript | {
"resource": ""
} |
q28539 | writeRaw | train | function writeRaw(peripheralId, serviceUuid, uuid, data, withoutResponse, callback){
//todo catch exceptions
var handle = servicesCache[peripheralId].services[serviceUuid].characteristics[uuid].handle;
var peripheral = peripherals[peripheralId];
//if not connected, connect
checkConnected(peripheral, function(){
peripheral.writeHandle(handle, new Buffer(data,'hex'), withoutResponse, function(error){
if (error) {
debug('Write handle error! '. red + error);
}
debug('write handle sent ' + peripheralId + ' : ' + serviceUuid + ' : ' + uuid )
sendEvent({
type: 'write',
peripheralId: peripheralId,
serviceUuid: serviceUuid,
characteristicUuid: uuid
});
});
})
} | javascript | {
"resource": ""
} |
q28540 | checkConnected | train | function checkConnected(peripheral, callback){
if (peripheral.state === 'connected') {
debug(' - connected');
if (callback) { callback(); }
} else if (peripheral.state === 'connecting'){
debug(' - connecting....');
//wait until the connection completes, invoke callback
peripheral.once('connect', function(){
if (callback){
callback();
}
})
}
else { //not connected
debug(' - not connected');
//if peripheral is lost by noble
if (! noble._peripherals[peripheral.id]) {
console.log('No such peripheral! This should not happen, restart manually...');
return
}
peripheral.connect( function(error) {
if (error) {
debug('checkconnected -> reconnect error !'.red + error)
} else {
debug('checkconnected -> reconnect');
}
if (callback) { callback(error); };
});
}
} | javascript | {
"resource": ""
} |
q28541 | index | train | function index(a, fn) {
let i, l;
for (i = 0, l = a.length; i < l; i++) {
if (fn(a[i]))
return i;
}
return -1;
} | javascript | {
"resource": ""
} |
q28542 | slice | train | function slice(array) {
const newArray = new Array(array.length);
let i,
l;
for (i = 0, l = array.length; i < l; i++)
newArray[i] = array[i];
return newArray;
} | javascript | {
"resource": ""
} |
q28543 | cloneRegexp | train | function cloneRegexp(re) {
const pattern = re.source;
let flags = '';
if (re.global) flags += 'g';
if (re.multiline) flags += 'm';
if (re.ignoreCase) flags += 'i';
if (re.sticky) flags += 'y';
if (re.unicode) flags += 'u';
return new RegExp(pattern, flags);
} | javascript | {
"resource": ""
} |
q28544 | cloner | train | function cloner(deep, item) {
if (!item ||
typeof item !== 'object' ||
item instanceof Error ||
item instanceof MonkeyDefinition ||
item instanceof Monkey ||
('ArrayBuffer' in global && item instanceof ArrayBuffer))
return item;
// Array
if (type.array(item)) {
if (deep) {
const a = new Array(item.length);
for (let i = 0, l = item.length; i < l; i++)
a[i] = cloner(true, item[i]);
return a;
}
return slice(item);
}
// Date
if (item instanceof Date)
return new Date(item.getTime());
// RegExp
if (item instanceof RegExp)
return cloneRegexp(item);
// Object
if (type.object(item)) {
const o = {};
// NOTE: could be possible to erase computed properties through `null`.
const props = Object.getOwnPropertyNames(item);
for (let i = 0, l = props.length; i < l; i++) {
const name = props[i];
const k = Object.getOwnPropertyDescriptor(item, name);
if (k.enumerable === true) {
if (k.get && k.get.isLazyGetter) {
Object.defineProperty(o, name, {
get: k.get,
enumerable: true,
configurable: true
});
}
else {
o[name] = deep ? cloner(true, item[name]) : item[name];
}
}
else if (k.enumerable === false) {
Object.defineProperty(o, name, {
value: deep ? cloner(true, k.value) : k.value,
enumerable: false,
writable: true,
configurable: true
});
}
}
return o;
}
return item;
} | javascript | {
"resource": ""
} |
q28545 | compare | train | function compare(object, description) {
let ok = true,
k;
// If we reached here via a recursive call, object may be undefined because
// not all items in a collection will have the same deep nesting structure.
if (!object)
return false;
for (k in description) {
if (type.object(description[k])) {
ok = ok && compare(object[k], description[k]);
}
else if (type.array(description[k])) {
ok = ok && !!~description[k].indexOf(object[k]);
}
else {
if (object[k] !== description[k])
return false;
}
}
return ok;
} | javascript | {
"resource": ""
} |
q28546 | freezer | train | function freezer(deep, o) {
if (typeof o !== 'object' ||
o === null ||
o instanceof Monkey)
return;
Object.freeze(o);
if (!deep)
return;
if (Array.isArray(o)) {
// Iterating through the elements
let i,
l;
for (i = 0, l = o.length; i < l; i++)
deepFreeze(o[i]);
}
else {
let p,
k;
for (k in o) {
if (type.lazyGetter(o, k))
continue;
p = o[k];
if (!p ||
!hasOwnProp.call(o, k) ||
typeof p !== 'object' ||
Object.isFrozen(p))
continue;
deepFreeze(p);
}
}
} | javascript | {
"resource": ""
} |
q28547 | makeSetter | train | function makeSetter(name, typeChecker) {
/**
* Binding a setter method to the Cursor class and having the following
* definition.
*
* Note: this is not really possible to make those setters variadic because
* it would create an impossible polymorphism with path.
*
* @todo: perform value validation elsewhere so that tree.update can
* beneficiate from it.
*
* Arity (1):
* @param {mixed} value - New value to set at cursor's path.
*
* Arity (2):
* @param {path} path - Subpath to update starting from cursor's.
* @param {mixed} value - New value to set.
*
* @return {mixed} - Data at path.
*/
Cursor.prototype[name] = function(path, value) {
// We should warn the user if he applies to many arguments to the function
if (arguments.length > 2)
throw makeError(`Baobab.Cursor.${name}: too many arguments.`);
// Handling arities
if (arguments.length === 1 && !INTRANSITIVE_SETTERS[name]) {
value = path;
path = [];
}
// Coerce path
path = coercePath(path);
// Checking the path's validity
if (!type.path(path))
throw makeError(`Baobab.Cursor.${name}: invalid path.`, {path});
// Checking the value's validity
if (typeChecker && !typeChecker(value))
throw makeError(`Baobab.Cursor.${name}: invalid value.`, {path, value});
// Checking the solvability of the cursor's dynamic path
if (!this.solvedPath)
throw makeError(
`Baobab.Cursor.${name}: the dynamic path of the cursor cannot be solved.`,
{path: this.path}
);
const fullPath = this.solvedPath.concat(path);
// Filing the update to the tree
return this.tree.update(
fullPath,
{
type: name,
value
}
);
};
} | javascript | {
"resource": ""
} |
q28548 | extendData | train | function extendData({
data,
lengthAngle: totalAngle,
totalValue,
paddingAngle,
}) {
const total = totalValue || sumValues(data);
const normalizedTotalAngle = valueBetween(totalAngle, -360, 360);
const numberOfPaddings =
Math.abs(normalizedTotalAngle) === 360 ? data.length : data.length - 1;
const degreesTakenByPadding =
Math.abs(paddingAngle) * numberOfPaddings * Math.sign(normalizedTotalAngle);
const singlePaddingDegrees = degreesTakenByPadding / numberOfPaddings;
const degreesTakenByPaths = normalizedTotalAngle - degreesTakenByPadding;
let lastSegmentEnd = 0;
return data.map(dataEntry => {
const valueInPercentage = (dataEntry.value / total) * 100;
const degrees = extractPercentage(degreesTakenByPaths, valueInPercentage);
const startOffset = lastSegmentEnd;
lastSegmentEnd = lastSegmentEnd + degrees + singlePaddingDegrees;
return {
percentage: valueInPercentage,
degrees,
startOffset,
...dataEntry,
};
});
} | javascript | {
"resource": ""
} |
q28549 | train | function(req, res, next) {
if (req.headers.accept && req.headers.accept.startsWith('text/html')) {
req.url = '/index.html'; // eslint-disable-line no-param-reassign
}
next();
} | javascript | {
"resource": ""
} | |
q28550 | showPreset | train | function showPreset(name, pos){
console.log(_colors.magenta('Preset: ' + name));
// create a new progress bar with preset
var bar = new _progress.Bar({
align: pos
}, _progress.Presets[name] || _progress.Presets.legacy);
bar.start(200, 0);
// random value 1..200
bar.update(Math.floor((Math.random() * 200) + 1));
bar.stop();
console.log('');
} | javascript | {
"resource": ""
} |
q28551 | getDateTime | train | function getDateTime(obj) {
// get date, hour, minute, second, year, month and day
var date = new Date()
, hour = date.getHours()
, min = date.getMinutes()
, sec = date.getSeconds()
, year = date.getFullYear()
, month = date.getMonth() + 1
, day = date.getDate()
;
// add `0` if needed
hour = padWithZero(hour);
min = padWithZero(min);
sec = padWithZero(sec);
month = padWithZero(month);
day = padWithZero(day);
// obj is true, return an object
if (obj) {
return {
year: year,
month: parseInt(month),
day: parseInt(day),
cDay: date.getDay()
}
}
// return a string
return year + "-" + month + "-" + day;
} | javascript | {
"resource": ""
} |
q28552 | Openfile | train | function Openfile(i, path) {
// !Optimized: use child_process module to open local file with local path
(function() {
var cmdArr = [
'nautilus ' + path
, 'start "" "' + path + '"'
, 'konqueror ' + path
, 'open ' + path
]
;
if (i >= cmdArr.length) {
client.emit("complete", {
error: null
, output: path
, mannual: true
});
}
// recursive calling
exec(cmdArr[i], function (err, stdout, stderr) {
if (err == null) {
// Success
client.emit("complete", {
error: null
, output: path
, mannual: false
});
} else {
Openfile(++i, path);
}
});
})();
} | javascript | {
"resource": ""
} |
q28553 | parseGroupValue | train | function parseGroupValue(code, value) {
if(code <= 9) return value;
if(code >= 10 && code <= 59) return parseFloat(value);
if(code >= 60 && code <= 99) return parseInt(value);
if(code >= 100 && code <= 109) return value;
if(code >= 110 && code <= 149) return parseFloat(value);
if(code >= 160 && code <= 179) return parseInt(value);
if(code >= 210 && code <= 239) return parseFloat(value);
if(code >= 270 && code <= 289) return parseInt(value);
if(code >= 290 && code <= 299) return parseBoolean(value);
if(code >= 300 && code <= 369) return value;
if(code >= 370 && code <= 389) return parseInt(value);
if(code >= 390 && code <= 399) return value;
if(code >= 400 && code <= 409) return parseInt(value);
if(code >= 410 && code <= 419) return value;
if(code >= 420 && code <= 429) return parseInt(value);
if(code >= 430 && code <= 439) return value;
if(code >= 440 && code <= 459) return parseInt(value);
if(code >= 460 && code <= 469) return parseFloat(value);
if(code >= 470 && code <= 481) return value;
if(code === 999) return value;
if(code >= 1000 && code <= 1009) return value;
if(code >= 1010 && code <= 1059) return parseFloat(value);
if(code >= 1060 && code <= 1071) return parseInt(value);
console.log('WARNING: Group code does not have a defined type: %j', { code: code, value: value });
return value;
} | javascript | {
"resource": ""
} |
q28554 | getExtraTasks | train | async function getExtraTasks() {
config = config || (await getConfig());
switch (config.env) {
case 'pl':
extraTasks.patternLab = require('./pattern-lab-tasks');
break;
case 'static':
extraTasks.static = require('./static-tasks');
break;
case 'pwa':
delete require.cache[require.resolve('./api-tasks')];
extraTasks.api = require('./api-tasks');
extraTasks.patternLab = require('./pattern-lab-tasks');
extraTasks.static = require('./static-tasks');
break;
}
if (config.wwwDir) {
extraTasks.server = require('./server-tasks');
}
return extraTasks;
} | javascript | {
"resource": ""
} |
q28555 | getFileHash | train | function getFileHash(filePath, callback) {
var stream = fs.ReadStream(filePath);
var md5sum = crypto.createHash('md5');
stream.on('data', function(data) {
md5sum.update(data);
});
stream.on('end', function() {
callback(md5sum.digest('hex'));
});
} | javascript | {
"resource": ""
} |
q28556 | mkDirs | train | async function mkDirs() {
config = config || (await getConfig());
try {
return Promise.all([
config.wwwDir ? mkdirp(config.wwwDir) : null,
config.dataDir ? mkdirp(config.dataDir) : null,
config.buildDir ? mkdirp(config.buildDir) : null,
]);
} catch (error) {
log.errorAndExit('Could not make all directories necessary.', error);
}
} | javascript | {
"resource": ""
} |
q28557 | setupServer | train | async function setupServer() {
return new Promise(async (resolve, reject) => {
config = config || (await getConfig());
config.components.individual = [];
config.prod = true;
config.enableCache = true;
config.mode = 'server';
config.env = 'pwa';
config.sourceMaps = false;
config.copy = [];
config.webpackDevServer = false;
config.buildDir = path.join(config.wwwDir, 'build-ssr');
config.dataDir = path.join(config.wwwDir, 'build-ssr', 'data');
app.use(express.static(path.relative(process.cwd(), config.wwwDir)));
// generate a fresh webpack build + pass along asset data to dynamic HTML template rendered
server = await app.listen(port);
app.get('/ssr', function(req, res) {
res.send(template(html || '', port, webpackStatsGenerated || []));
});
// handle cleaning up + shutting down the server instance
process.on('SIGTERM', shutDownSSRServer);
process.on('SIGINT', shutDownSSRServer);
server.on('connection', connection => {
connections.push(connection);
connection.on(
'close',
// eslint-disable-next-line no-return-assign
() => (connections = connections.filter(curr => curr !== connection)),
);
});
resolve();
});
} | javascript | {
"resource": ""
} |
q28558 | receiveIframeMessage | train | function receiveIframeMessage(event) {
// does the origin sending the message match the current host? if not dev/null the request
if (
window.location.protocol !== 'file:' &&
event.origin !== window.location.protocol + '//' + window.location.host
) {
return;
}
let path;
let data = {};
try {
data = typeof event.data !== 'string' ? event.data : JSON.parse(event.data);
} catch (e) {
// @todo: how do we want to handle exceptions like these?
}
if (data.event !== undefined && data.event === 'patternLab.updatePath') {
if (window.patternData.patternPartial !== undefined) {
// handle patterns and the view all page
const re = /(patterns|snapshots)\/(.*)$/;
path =
window.location.protocol +
'//' +
window.location.host +
window.location.pathname.replace(re, '') +
data.path +
'?' +
Date.now();
window.location.replace(path);
} else {
// handle the style guide
path =
window.location.protocol +
'//' +
window.location.host +
window.location.pathname.replace(
'styleguide/html/styleguide.html',
''
) +
data.path +
'?' +
Date.now();
window.location.replace(path);
}
} else if (data.event !== undefined && data.event === 'patternLab.reload') {
// reload the location if there was a message to do so
window.location.reload();
}
} | javascript | {
"resource": ""
} |
q28559 | buildWebpackEntry | train | async function buildWebpackEntry() {
const { components } = await getBoltManifest();
const entry = {};
const globalEntryName = 'bolt-global';
if (components.global) {
entry[globalEntryName] = [];
components.global.forEach(component => {
if (component.assets.style) {
entry[globalEntryName].push(component.assets.style);
}
if (component.assets.main) {
entry[globalEntryName].push(component.assets.main);
}
});
const useHotMiddleware =
Array.isArray(fullBuildConfig.lang) && fullBuildConfig.lang.length > 1
? false
: true;
if (!config.prod && config.webpackDevServer && useHotMiddleware) {
entry[globalEntryName].push(
`webpack-hot-middleware/client?name=${
config.lang
}&noInfo=true&quiet=true&logLevel=silent&reload=true`,
);
}
}
if (components.individual) {
components.individual.forEach(component => {
const files = [];
if (component.assets.style) files.push(component.assets.style);
if (component.assets.main) files.push(component.assets.main);
if (files) {
entry[component.basicName] = files;
}
});
}
if (config.verbosity > 4) {
log.info('WebPack `entry`:');
console.log(entry);
}
return entry;
} | javascript | {
"resource": ""
} |
q28560 | readYamlFile | train | function readYamlFile(file) {
return new Promise((resolve, reject) => {
readFile(file, 'utf8')
.then(data => resolve(fromYaml(data)))
.catch(reject);
});
} | javascript | {
"resource": ""
} |
q28561 | writeYamlFile | train | function writeYamlFile(file, data) {
return new Promise((resolve, reject) => {
writeFile(file, toYaml(data))
.then(resolve)
.catch(reject);
});
} | javascript | {
"resource": ""
} |
q28562 | generatePackageData | train | async function generatePackageData() {
boltPackages.forEach(async pkg => {
if (pkg.version !== '0.0.0' && pkg.private !== true) {
const name = pkg.name;
try {
const pkgInfo = await packageJson(name, {
allVersions: true,
});
processedPackages.push(pkgInfo);
numberOfPackagesProcessed += 1;
} catch (err) {
console.log(err);
}
} else {
numberOfPackagesProcessed += 1;
}
if (numberOfPackagesProcessed === totalNumberOfPackages) {
const config = await getConfig();
const unformattedJSON = JSON.stringify(processedPackages);
const formattedJSON = prettier.format(unformattedJSON, {
parser: 'json',
});
fs.writeFile(
path.join(config.dataDir, 'bolt-pkg-versions.json'),
formattedJSON,
'utf8',
function(err) {
if (err) {
console.log('An error occured while writing JSON Object to File.');
return console.log(err);
}
console.log('Bolt NPM pkg Data has been saved.');
},
);
}
});
} | javascript | {
"resource": ""
} |
q28563 | getPage | train | async function getPage(file) {
config = config || (await asyncConfig());
if (config.verbosity > 3) {
log.dim(`Getting info for: ${file}`);
}
const url = path
.relative(config.srcDir, file)
.replace('.md', '.html')
.split('/')
.map(x => x.replace(/^[0-9]*-/, '')) // Removing number prefix `05-item` => `item`
.join('/');
const fileContents = await readFile(file, 'utf8');
// https://www.npmjs.com/package/front-matter
const { attributes, body, frontmatter } = fm(fileContents);
const dirTree = url.split('/');
let depth = url.split('/').filter(x => x !== 'index.html').length;
let parent = dirTree[depth - 2];
// Don't do it for homepage
if (url === 'index.html') depth = 1;
const page = {
srcPath: file,
url,
depth,
parent,
meta: attributes,
body: file.endsWith('.md') ? marked(body) : body,
};
return page;
} | javascript | {
"resource": ""
} |
q28564 | getPages | train | async function getPages(srcDir) {
config = config || (await asyncConfig());
/** @type Array<String> */
const allPaths = await globby([
path.join(srcDir, '**/*.{md,html}'),
'!**/_*/**/*.{md,html}',
'!**/pattern-lab/**/*',
'!**/_*.{md,html}',
]);
return Promise.all(allPaths.map(getPage)).then(pages => {
if (config.verbosity > 4) {
log.dim('All data for Static pages:');
console.log(pages);
log.dim('END: All data for Static pages.');
}
return pages;
});
} | javascript | {
"resource": ""
} |
q28565 | getSiteData | train | async function getSiteData(pages) {
config = config || (await asyncConfig());
const nestedPages = await getNestedPages(config.srcDir);
const site = {
nestedPages,
pages: pages.map(page => ({
url: page.url,
meta: page.meta,
// choosing not to have `page.body` in here on purpose
})),
};
return site;
} | javascript | {
"resource": ""
} |
q28566 | compile | train | async function compile(exitOnError = true) {
config = config || (await asyncConfig());
const startMessage = chalk.blue('Compiling Static Site...');
const startTime = timer.start();
let spinner;
if (config.verbosity > 2) {
console.log(startMessage);
} else {
spinner = ora(startMessage).start();
}
const pages = await getPages(config.srcDir);
const renderPages = pages.map(async page => {
const site = await getSiteData(pages);
const layout = page.meta.layout ? page.meta.layout : 'default';
const { ok, html, message } = await render(`@bolt/${layout}.twig`, {
page,
site,
});
if (!ok) {
if (exitOnError) {
log.errorAndExit(message);
} else {
log.error(message);
}
}
const htmlFilePath = path.join(config.wwwDir, page.url);
await mkdirp(path.dirname(htmlFilePath));
await writeFile(htmlFilePath, html);
if (config.verbosity > 3) {
log.dim(`Wrote: ${htmlFilePath}`);
}
return true;
});
Promise.all(renderPages)
.then(() => {
const endMessage = chalk.green(
`Compiled Static Site in ${timer.end(startTime)}`,
);
if (config.verbosity > 2) {
console.log(endMessage);
} else {
spinner.succeed(endMessage);
}
})
.catch(error => {
console.log(error);
const endMessage = chalk.red(
`Compiling Static Site failed in ${timer.end(startTime)}`,
);
spinner.fail(endMessage);
});
} | javascript | {
"resource": ""
} |
q28567 | init | train | async function init(keepAlive = false) {
state = STATES.STARTING;
const config = await getConfig();
const relativeFrom = path.dirname(config.configFileUsed);
// console.log({ config });
twigNamespaces = await getTwigNamespaceConfig(
relativeFrom,
config.extraTwigNamespaces,
);
twigRenderer = new TwigRenderer({
relativeFrom,
src: {
roots: [relativeFrom],
namespaces: TwigRenderer.convertLegacyNamespacesConfig(twigNamespaces),
},
debug: true,
alterTwigEnv: config.alterTwigEnv,
hasExtraInfoInResponses: false, // Will add `info` onto results with a lot of info about Twig Env
maxConcurrency: 50,
keepAlive, // only set this to be true when doing in-browser requests to avoid issues with this process not exiting when complete
});
state = STATES.READY;
} | javascript | {
"resource": ""
} |
q28568 | render | train | async function render(template, data = {}, keepAlive = false) {
await prep(keepAlive);
const results = await twigRenderer.render(template, data);
return results;
} | javascript | {
"resource": ""
} |
q28569 | renderString | train | async function renderString(templateString, data = {}, keepAlive = false) {
await prep(keepAlive);
const results = await twigRenderer.renderString(templateString, data);
// console.log({ results });
return results;
} | javascript | {
"resource": ""
} |
q28570 | uniqueArray | train | function uniqueArray(item) {
const u = {};
const newArray = [];
for (let i = 0, l = item.length; i < l; ++i) {
if (!{}.hasOwnProperty.call(u, item[i])) {
newArray.push(item[i]);
u[item[i]] = 1;
}
}
return newArray;
} | javascript | {
"resource": ""
} |
q28571 | ensureFileExists | train | function ensureFileExists(filePath) {
fs.access(filePath, err => {
if (err) {
log.errorAndExit(
'This file ^^^ does not exist and it was referenced in package.json for that component, please make sure the file path is correct.',
filePath,
);
}
});
} | javascript | {
"resource": ""
} |
q28572 | dirExists | train | async function dirExists(path) {
try {
const stats = await stat(path);
return stats.isDirectory() ? true : false;
} catch (err) {
return false;
}
} | javascript | {
"resource": ""
} |
q28573 | execAndReport | train | async function execAndReport({ cmd, name }) {
try {
const {
failed,
// code,
// timedOut,
stdout,
stderr,
// message,
} = await execa.shell(cmd);
process.stdout.write(stdout);
process.stderr.write(stderr);
await setCheckRun({
name,
status: 'completed',
conclusion: 'success',
output: {
title: name,
summary: `Ran ${cmd}`,
},
});
return failed;
} catch (err) {
const {
failed,
// code,
// timedOut,
stdout,
stderr,
message,
} = err;
process.stdout.write(stdout);
process.stderr.write(stderr);
await setCheckRun({
name,
status: 'completed',
conclusion: 'failure',
output: {
title: name,
summary: `Ran ${cmd}`,
text: `
<pre><code>
${message}
</code></pre>
`.trim(),
},
});
return failed;
}
} | javascript | {
"resource": ""
} |
q28574 | sh | train | async function sh(
cmd,
args,
exitOnError,
streamOutput,
showCmdOnError = true,
exitImmediately = false,
) {
return new Promise((resolve, reject) => {
const child = execa(cmd, args);
let output = '';
if (streamOutput) {
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
}
child.stdout.on('data', data => {
output += data;
if (streamOutput) {
process.stdout.write(data);
}
});
child.stderr.on('data', data => {
output += data;
if (streamOutput) {
process.stdout.write(data);
}
});
child.on('close', code => {
if (code > 0) {
const errorMsg = chalk.red(`
Error with code ${code}${
showCmdOnError ? ` after running: ${cmd}` : ''
}:
`);
if (exitOnError) {
if (exitImmediately) {
console.error(errorMsg + output);
process.exit(1);
}
process.exitCode = 1;
reject(new Error(errorMsg + output));
} else {
notifier.notify({
title: cmd,
message: output,
sound: true,
});
// eslint-disable-next-line prefer-promise-reject-errors
reject(errorMsg + output);
}
}
resolve(output);
});
});
} | javascript | {
"resource": ""
} |
q28575 | addNestedLevelProps | train | function addNestedLevelProps(childNode, level) {
let currentLevel = level;
if (childNode.tagName) {
childNode.level = currentLevel;
}
return currentLevel;
} | javascript | {
"resource": ""
} |
q28576 | updateConfig | train | async function updateConfig(options, programInstance) {
await configStore.updateConfig(config => {
originalConfig = config;
config.verbosity =
typeof program.verbosity === 'undefined'
? config.verbosity
: program.verbosity;
config.openServerAtStart =
typeof options.open === 'undefined'
? config.openServerAtStart
: options.open;
config.renderingService =
typeof options.renderingService === 'undefined'
? process.env.TRAVIS
? false
: config.renderingService
: options.renderingService;
config.env = process.env.NODE_ENV
? process.env.NODE_ENV
: typeof options.env === 'undefined'
? config.env
: options.env;
config.webpackStats =
typeof options.webpackStats === 'undefined'
? config.webpackStats
: options.webpackStats;
config.webpackDevServer =
typeof options.webpackDevServer === 'undefined'
? config.webpackDevServer
: options.webpackDevServer;
config.mode =
typeof options.mode === 'undefined' ? config.mode : options.mode;
config.quick =
typeof options.quick === 'undefined' ? config.quick : options.quick;
config.watch =
typeof options.watch === 'undefined' ? config.watch : options.watch;
config.prod =
typeof program.prod === 'undefined' ? config.prod : program.prod;
// automatically set enableSSR to true in prod mode and false in dev mode, unless manually set.
config.enableSSR = false;
config.i18n =
typeof options.i18n === 'undefined'
? config.prod
? true
: false
: options.i18n;
// If i18n is disabled, ignore and remove lang config settings
if (config.lang && config.i18n === false) {
// Remove any lang-specific settings for local dev to speed things up.
delete config['lang'];
}
return config;
});
const config = await configStore.getConfig();
log.dim(`Verbosity: ${config.verbosity}`);
log.dim(`Prod: ${config.prod}`);
log.dim(`i18n: ${config.i18n}`);
log.dim(
`enableSSR: ${config.enableSSR} ${
originalConfig.enableSSR ? '(manually set)' : '(auto set)'
}`,
);
log.dim(`Rendering Mode: ${config.mode}`);
if (config.verbosity > 2) {
log.dim(`Opening browser: ${config.openServerAtStart}`);
log.dim(`Quick mode: ${config.quick}`);
log.dim(`buildDir: ${config.buildDir}`);
log.dim(`dataDir: ${config.dataDir}`);
log.dim(`wwwDir: ${config.wwwDir}`);
}
// Basically at this point, the cli is bootstrapped and ready to go.
// Let's build the core bolt manifest
await buildBoltManifest();
return config;
} | javascript | {
"resource": ""
} |
q28577 | translateColor | train | function translateColor(colorArr, variationName, execMode) {
const [colorVar, alpha] = colorArr;
// returns the real color representation
if (!options.palette) {
options.palette = getColorPalette();
}
const underlineColor = options.palette[variationName][colorVar];
if (!underlineColor) {
// variable is not mandatory in non-default variations
if (variationName !== defaultVariation) {
return null;
}
throw new Error(
`The variable name '${colorVar}' doesn't exists in your palette.`,
);
}
switch (execMode) {
case ExecutionMode.CSS_COLOR:
// with default alpha - just returns the color
if (alpha === '1') {
return rgb2hex(underlineColor).hex;
}
// with custom alpha, convert it to rgba
const rgbaColor = hexToRgba(rgb2hex(underlineColor).hex, alpha);
return rgbaColor;
default:
if (alpha === 1) {
return `rgba(var(--bolt-theme-${colorVar}), ${alpha})`;
//return `var(--bolt-theme-${colorVar})`; // @todo: re-evaluate if hex values should ever get outputted here
} else {
return `rgba(var(--bolt-theme-${colorVar}), ${alpha})`;
}
}
} | javascript | {
"resource": ""
} |
q28578 | processRules | train | function processRules(root) {
root.walkRules(rule => {
if (!hasThemify(rule.toString())) {
return;
}
let aggragatedSelectorsMap = {};
let aggragatedSelectors = [];
let createdRules = [];
const variationRules = {
[defaultVariation]: rule,
};
rule.walkDecls(decl => {
const propertyValue = decl.value;
if (!hasThemify(propertyValue)) return;
const property = decl.prop;
const variationValueMap = getThemifyValue(
propertyValue,
ExecutionMode.CSS_VAR,
);
const defaultVariationValue = variationValueMap[defaultVariation];
decl.value = defaultVariationValue;
// indicate if we have a global rule, that cannot be nested
const createNonDefaultVariationRules = isAtRule(rule);
// don't create extra CSS for global rules
if (createNonDefaultVariationRules) {
return;
}
// create a new declaration and append it to each rule
nonDefaultVariations.forEach(variationName => {
const currentValue = variationValueMap[variationName];
// variable for non-default variation is optional
if (!currentValue || currentValue === 'null') {
return;
}
// when the declaration is the same as the default variation,
// we just need to concatenate our selector to the default rule
if (currentValue === defaultVariationValue) {
const selector = getSelectorName(rule, variationName);
// append the selector once
if (!aggragatedSelectorsMap[variationName]) {
aggragatedSelectorsMap[variationName] = true;
aggragatedSelectors.push(selector);
}
} else {
// creating the rule for the first time
if (!variationRules[variationName]) {
const clonedRule = createRuleWithVariation(rule, variationName);
variationRules[variationName] = clonedRule;
// append the new rule to the array, so we can append it later
createdRules.push(clonedRule);
}
const variationDecl = createDecl(
property,
variationValueMap[variationName],
);
variationRules[variationName].append(variationDecl);
}
});
});
if (aggragatedSelectors.length) {
rule.selectors = [...rule.selectors];
// Don't add extra redundant CSS selectors to every component using CSS vars
// rule.selectors = [...rule.selectors, ...aggragatedSelectors];
}
// append each created rule
if (createdRules.length) {
createdRules.forEach(r => root.append(r));
}
});
} | javascript | {
"resource": ""
} |
q28579 | createRuleWithVariation | train | function createRuleWithVariation(rule, variationName) {
const selector = getSelectorName(rule, variationName);
return postcss.rule({
selector,
});
} | javascript | {
"resource": ""
} |
q28580 | createFallbackRuleWithVariation | train | function createFallbackRuleWithVariation(rule, variationName) {
const selector = getSelectorName(rule, variationName, true);
return postcss.rule({
selector,
});
} | javascript | {
"resource": ""
} |
q28581 | getSelectorName | train | function getSelectorName(rule, variationName, isFallbackSelector = false) {
const selectorPrefix = `.${options.classPrefix || ''}${variationName}`;
// console.log(variationName);
if (isFallbackSelector) {
return rule.selectors
.map(selector => {
let selectors = [];
let initialSelector = `${selectorPrefix} ${selector}`;
if (variationName === 'xlight') {
selectors.push(selector);
}
selectors.push(initialSelector);
selectors.push(`[class*="t-bolt-"] ${initialSelector}`);
return selectors.join(',');
})
.join(',');
} else {
return rule.selectors
.map(selector => {
return `${selectorPrefix} ${selector}`;
})
.join(',');
}
} | javascript | {
"resource": ""
} |
q28582 | errorAndExit | train | function errorAndExit(msg, logMe) {
// @todo Only trigger if `verbosity > 1`
if (logMe) {
// Adding some empty lines before error message for readability
console.log();
console.log();
console.log(logMe);
}
error(`Error: ${msg}`);
// There's a few ways to handle exiting
// This is suggested and it's nice b/c it let's I/O finish up, but if an error happens on a watch task, it doesn't exit, b/c this will exit once the event loop is empty.
// process.exitCode = 1;
// This stops everything instantly and guarantees a killed program, but there's comments on the InterWebs about how it can be bad b/c I/O (like file writes) might not be done yet. I also have suspicions that this can lead to child processes never getting killed and running indefinitely - perhaps what leads to ports not being available
// process.exit(1);
// From docs for `process.nextTick` : "Once the current turn of the event loop turn runs to completion, all callbacks currently in the next tick queue will be called. This is not a simple alias to setTimeout(fn, 0). It is much more efficient. It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop."
// This exits during watches correctly, and I *think* it'll let the I/O finish, but I'm not 100%
process.nextTick(() => {
process.exit(1);
});
} | javascript | {
"resource": ""
} |
q28583 | activateGumshoeLink | train | function activateGumshoeLink() {
const originalTarget = nav.nav;
let originalTargetHref;
let normalizedTarget;
if (originalTarget) {
originalTargetHref = originalTarget.getAttribute('href');
} else {
originalTargetHref = nav.nav.getAttribute('href');
}
// Need to target via document vs this custom element reference since only one gumshoe instance is shared across every component instance to better optimize for performance
const matchedTargetLinks = document.querySelectorAll(
`bolt-navlink > [href*="${originalTargetHref}"]`,
);
for (var i = 0, len = matchedTargetLinks.length; i < len; i++) {
const linkInstance = matchedTargetLinks[i];
// Stop if normalizedTarget already set.
if (normalizedTarget) {
break;
}
// Prefer visible links over hidden links
if (isVisible(linkInstance)) {
normalizedTarget = linkInstance;
// Prefer dropdown links over non-dropdown links if the link is hidden
} else if (linkInstance.parentNode.isDropdownLink) {
normalizedTarget = linkInstance;
// otherwise default to what was originally selected.
} else if (i === len - 1) {
normalizedTarget = originalTarget;
}
}
const normalizedParent = normalizedTarget.parentNode;
normalizedParent.activate();
} | javascript | {
"resource": ""
} |
q28584 | flattenDeep | train | function flattenDeep(arr1) {
return arr1.reduce(
(acc, val) =>
Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val),
[],
);
} | javascript | {
"resource": ""
} |
q28585 | aggregateBoltDependencies | train | async function aggregateBoltDependencies(data) {
let componentDependencies = [];
let componentsWithoutDeps = data;
componentsWithoutDeps.forEach(item => {
if (item.deps) {
componentDependencies.push([...item.deps]);
}
});
componentDependencies = flattenDeep(componentDependencies);
componentDependencies = componentDependencies.filter(function(x, i, a) {
if (x !== '@bolt/build-tools' && a.indexOf(x) === i) {
return x;
}
});
let globalDepsSrc = await Promise.all(componentDependencies.map(getPkgInfo));
componentsWithoutDeps = componentsWithoutDeps.concat(globalDepsSrc);
var uniqueComponentsWithDeps = removeDuplicateObjectsFromArray(
componentsWithoutDeps,
'name',
);
return uniqueComponentsWithDeps;
} | javascript | {
"resource": ""
} |
q28586 | getAllDirs | train | async function getAllDirs(relativeFrom) {
const dirs = [];
const manifest = await getBoltManifest();
[manifest.components.global, manifest.components.individual].forEach(
componentList => {
componentList.forEach(component => {
dirs.push(
relativeFrom
? path.relative(relativeFrom, component.dir)
: component.dir,
);
});
},
);
return dirs;
} | javascript | {
"resource": ""
} |
q28587 | getTwigNamespaceConfig | train | async function getTwigNamespaceConfig(relativeFrom, extraNamespaces = {}) {
const config = await getConfig();
const namespaces = {};
const allDirs = [];
const manifest = await getBoltManifest();
const global = manifest.components.global;
const individual = manifest.components.individual;
[global, individual].forEach(componentList => {
componentList.forEach(component => {
if (!component.twigNamespace) {
return;
}
const dir = relativeFrom
? path.relative(relativeFrom, component.dir)
: component.dir;
namespaces[component.basicName] = {
recursive: true,
paths: [dir],
};
allDirs.push(dir);
});
});
const namespaceConfigFile = Object.assign(
{
// Can hit anything with `@bolt`
bolt: {
recursive: true,
paths: [...allDirs],
},
'bolt-data': {
recursive: true,
paths: [config.dataDir],
},
},
namespaces,
);
// `extraNamespaces` serves two purposes:
// 1. To add extra namespaces that have not been declared
// 2. To add extra paths to previously declared namespaces
// Assuming we've already declared the `foo` namespaces to look in `~/my-dir1`
// Then someone uses `extraNamespaces` to declare that `foo` will look in `~/my-dir2`
// This will not overwrite it, but *prepend* to the paths, resulting in a namespace setting like this:
// 'foo': {
// paths: ['~/my-dir2', '~/my-dir1']
// }
// This causes the folder declared in `extraNamespaces` to be looked in first for templates, before our default;
// allowing end user developers to selectively overwrite some templates.
if (extraNamespaces) {
Object.keys(extraNamespaces).forEach(namespace => {
const settings = extraNamespaces[namespace];
if (
namespaceConfigFile[namespace] &&
settings.paths !== undefined // make sure the paths config is defined before trying to merge
) {
// merging the two, making sure the paths from `extraNamespaces` go first
namespaceConfigFile[namespace].paths = [
...settings.paths,
...namespaceConfigFile[namespace].paths,
];
// don't add a new namespace key if the paths config option wasn't defined. prevents PHP errors if a namespace key was defined but no paths specified.
} else if (settings.paths !== undefined) {
namespaceConfigFile[namespace] = settings;
}
});
}
return namespaceConfigFile;
} | javascript | {
"resource": ""
} |
q28588 | Socket | train | function Socket(options) {
if (!(this instanceof Socket)) {
return new Socket(options);
}
var tty = process.binding('tty_wrap');
var guessHandleType = tty.guessHandleType;
tty.guessHandleType = function() {
return 'PIPE';
};
net.Socket.call(this, options);
tty.guessHandleType = guessHandleType;
} | javascript | {
"resource": ""
} |
q28589 | Agent | train | function Agent(file, args, env, cwd, cols, rows, debug) {
var self = this;
// Increment the number of pipes created.
pipeIncr++;
// Unique identifier per pipe created.
var timestamp = Date.now();
// The data pipe is the direct connection to the forked terminal.
this.dataPipe = '\\\\.\\pipe\\winpty-data-' + pipeIncr + '' + timestamp;
// Dummy socket for awaiting `ready` event.
this.ptySocket = new net.Socket();
// Create terminal pipe IPC channel and forward
// to a local unix socket.
this.ptyDataPipe = net.createServer(function (socket) {
// Default socket encoding.
socket.setEncoding('utf8');
// Pause until `ready` event is emitted.
socket.pause();
// Sanitize input variable.
file = file;
args = args.join(' ');
cwd = path.resolve(cwd);
// Start terminal session.
pty.startProcess(self.pid, file, args, env, cwd);
// Emit ready event.
self.ptySocket.emit('ready_datapipe', socket);
}).listen(this.dataPipe);
// Open pty session.
var term = pty.open(self.dataPipe, cols, rows, debug);
// Terminal pid.
this.pid = term.pid;
// Not available on windows.
this.fd = term.fd;
// Generated incremental number that has no real purpose besides
// using it as a terminal id.
this.pty = term.pty;
} | javascript | {
"resource": ""
} |
q28590 | isWildcardRange | train | function isWildcardRange(range, constraints) {
if (range instanceof Array && !range.length) {
return false;
}
if (constraints.length !== 2) {
return false;
}
return range.length === (constraints[1] - (constraints[0] < 1 ? - 1 : 0));
} | javascript | {
"resource": ""
} |
q28591 | CronExpression | train | function CronExpression (fields, options) {
this._options = options;
this._utc = options.utc || false;
this._tz = this._utc ? 'UTC' : options.tz;
this._currentDate = new CronDate(options.currentDate, this._tz);
this._startDate = options.startDate ? new CronDate(options.startDate, this._tz) : null;
this._endDate = options.endDate ? new CronDate(options.endDate, this._tz) : null;
this._fields = fields;
this._isIterator = options.iterator || false;
this._hasIterated = false;
this._nthDayOfWeek = options.nthDayOfWeek || 0;
} | javascript | {
"resource": ""
} |
q28592 | parseRepeat | train | function parseRepeat (val) {
var repeatInterval = 1;
var atoms = val.split('/');
if (atoms.length > 1) {
return parseRange(atoms[0], atoms[atoms.length - 1]);
}
return parseRange(val, repeatInterval);
} | javascript | {
"resource": ""
} |
q28593 | matchSchedule | train | function matchSchedule (value, sequence) {
for (var i = 0, c = sequence.length; i < c; i++) {
if (sequence[i] >= value) {
return sequence[i] === value;
}
}
return sequence[0] === value;
} | javascript | {
"resource": ""
} |
q28594 | isNthDayMatch | train | function isNthDayMatch(date, nthDayOfWeek) {
if (nthDayOfWeek < 6) {
if (
date.getDate() < 8 &&
nthDayOfWeek === 1 // First occurence has to happen in first 7 days of the month
) {
return true;
}
var offset = date.getDate() % 7 ? 1 : 0; // Math is off by 1 when dayOfWeek isn't divisible by 7
var adjustedDate = date.getDate() - (date.getDate() % 7); // find the first occurance
var occurrence = Math.floor(adjustedDate / 7) + offset;
return occurrence === nthDayOfWeek;
}
return false;
} | javascript | {
"resource": ""
} |
q28595 | train | function(){
// Update the next frame
updateId = requestAnimationFrame(update);
var now = Date.now();
if (emitter)
emitter.update((now - elapsed) * 0.001);
framerate.innerHTML = (1000 / (now - elapsed)).toFixed(2);
elapsed = now;
if(emitter && particleCount)
particleCount.innerHTML = emitter.particleCount;
// render the stage
renderer.render(stage);
} | javascript | {
"resource": ""
} | |
q28596 | train | function(a, b) {
a = a.trim().toLowerCase();
b = b.trim().toLowerCase();
if (a === b) return 0;
if (a < b) return 1;
return -1;
} | javascript | {
"resource": ""
} | |
q28597 | train | function(sort, antiStabilize) {
return function(a, b) {
var unstableResult = sort(a.td, b.td);
if (unstableResult === 0) {
if (antiStabilize) return b.index - a.index;
return a.index - b.index;
}
return unstableResult;
};
} | javascript | {
"resource": ""
} | |
q28598 | extendContext | train | function extendContext(context, opts) {
Object.defineProperties(context, {
[CONTEXT_SESSION]: {
get() {
if (this[_CONTEXT_SESSION]) return this[_CONTEXT_SESSION];
this[_CONTEXT_SESSION] = new ContextSession(this, opts);
return this[_CONTEXT_SESSION];
},
enumerable: true
},
session: {
get() {
return this[CONTEXT_SESSION].get();
},
set(val) {
this[CONTEXT_SESSION].set(val);
},
configurable: true,
enumerable: true
},
sessionOptions: {
get() {
return this[CONTEXT_SESSION].opts;
},
enumerable: true
},
});
} | javascript | {
"resource": ""
} |
q28599 | Router | train | function Router(opts) {
if (!(this instanceof Router)) {
return new Router(opts);
}
this.opts = opts || {};
this.methods = this.opts.methods || [
'HEAD',
'OPTIONS',
'GET',
'PUT',
'PATCH',
'POST',
'DELETE'
];
this.params = {};
this.stack = [];
this.MATCHS = {};
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.