_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q53600
|
train
|
function (selector) {
var target = _emberViewsSystemJquery.default(selector);
_emberMetalDebug.assert('You tried to replace in (' + selector + ') but that isn\'t in the DOM', target.length > 0);
_emberMetalDebug.assert('You cannot replace an existing Ember.View.', !target.is('.ember-view') && !target.parents().is('.ember-view'));
this.renderer.replaceIn(this, target[0]);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q53601
|
normalizeComponentAttributes
|
train
|
function normalizeComponentAttributes(component, isAngleBracket, attrs) {
var normalized = {};
var attributeBindings = component.attributeBindings;
var streamBasePath = component.isComponent ? '' : 'view.';
var i, l;
if (attrs.id && _emberHtmlbarsHooksGetValue.default(attrs.id)) {
// Do not allow binding to the `id`
normalized.id = _emberHtmlbarsHooksGetValue.default(attrs.id);
component.elementId = normalized.id;
} else {
normalized.id = component.elementId;
}
if (attributeBindings) {
for (i = 0, l = attributeBindings.length; i < l; i++) {
var attr = attributeBindings[i];
var colonIndex = attr.indexOf(':');
var attrName, expression;
if (colonIndex !== -1) {
var attrProperty = attr.substring(0, colonIndex);
attrName = attr.substring(colonIndex + 1);
expression = ['get', '' + streamBasePath + attrProperty];
} else if (attrs[attr]) {
// TODO: For compatibility with 1.x, we probably need to `set`
// the component's attribute here if it is a CP, but we also
// probably want to suspend observers and allow the
// willUpdateAttrs logic to trigger observers at the correct time.
attrName = attr;
expression = ['value', attrs[attr]];
} else {
attrName = attr;
expression = ['get', '' + streamBasePath + attr];
}
_emberMetalDebug.assert('You cannot use class as an attributeBinding, use classNameBindings instead.', attrName !== 'class');
normalized[attrName] = expression;
}
}
if (isAngleBracket) {
for (var prop in attrs) {
var val = attrs[prop];
if (!val) {
continue;
}
if (typeof val === 'string' || val.isConcat) {
normalized[prop] = ['value', val];
}
}
}
if (attrs.tagName) {
component.tagName = attrs.tagName;
}
var normalizedClass = normalizeClass(component, attrs, streamBasePath);
if (normalizedClass) {
normalized.class = normalizedClass;
}
if (_emberMetalProperty_get.get(component, 'isVisible') === false) {
var hiddenStyle = ['subexpr', '-html-safe', ['display: none;'], []];
var existingStyle = normalized.style;
if (existingStyle) {
normalized.style = ['subexpr', 'concat', [existingStyle, ' ', hiddenStyle], []];
} else {
normalized.style = hiddenStyle;
}
}
return normalized;
}
|
javascript
|
{
"resource": ""
}
|
q53602
|
train
|
function (addedEvents, rootElement) {
var event;
var events = this._finalEvents = _emberMetalAssign.default({}, _emberMetalProperty_get.get(this, 'events'), addedEvents);
if (!_emberMetalIs_none.default(rootElement)) {
_emberMetalProperty_set.set(this, 'rootElement', rootElement);
}
rootElement = _emberViewsSystemJquery.default(_emberMetalProperty_get.get(this, 'rootElement'));
_emberMetalDebug.assert('You cannot use the same root element (' + (rootElement.selector || rootElement[0].tagName) + ') multiple times in an Ember.Application', !rootElement.is(ROOT_ELEMENT_SELECTOR));
_emberMetalDebug.assert('You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application', !rootElement.closest(ROOT_ELEMENT_SELECTOR).length);
_emberMetalDebug.assert('You cannot make a new Ember.Application using a root element that is an ancestor of an existing Ember.Application', !rootElement.find(ROOT_ELEMENT_SELECTOR).length);
rootElement.addClass(ROOT_ELEMENT_CLASS);
_emberMetalDebug.assert('Unable to add \'' + ROOT_ELEMENT_CLASS + '\' class to rootElement. Make sure you set rootElement to the body or an element in the body.', rootElement.is(ROOT_ELEMENT_SELECTOR));
for (event in events) {
if (events.hasOwnProperty(event)) {
this.setupHandler(rootElement, event, events[event]);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q53603
|
train
|
function (rootElement, event, eventName) {
var self = this;
var owner = _containerOwner.getOwner(this);
var viewRegistry = owner && owner.lookup('-view-registry:main') || _emberViewsViewsView.default.views;
if (eventName === null) {
return;
}
rootElement.on(event + '.ember', '.ember-view', function (evt, triggeringManager) {
var view = viewRegistry[this.id];
var result = true;
var manager = self.canDispatchToEventManager ? self._findNearestEventManager(view, eventName) : null;
if (manager && manager !== triggeringManager) {
result = self._dispatchEvent(manager, evt, eventName, view);
} else if (view) {
result = self._bubbleEvent(view, evt, eventName);
}
return result;
});
rootElement.on(event + '.ember', '[data-ember-action]', function (evt) {
var actionId = _emberViewsSystemJquery.default(evt.currentTarget).attr('data-ember-action');
var actions = _emberViewsSystemAction_manager.default.registeredActions[actionId];
// We have to check for actions here since in some cases, jQuery will trigger
// an event on `removeChild` (i.e. focusout) after we've already torn down the
// action handlers for the view.
if (!actions) {
return;
}
for (var index = 0, _length = actions.length; index < _length; index++) {
var action = actions[index];
if (action && action.eventName === eventName) {
return action.handler(evt);
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53604
|
train
|
function () {
this._super.apply(this, arguments);
var name = arguments[0];
var method = this[name];
if (method) {
var length = arguments.length;
var args = new Array(length - 1);
for (var i = 1; i < length; i++) {
args[i - 1] = arguments[i];
}
return method.apply(this, args);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q53605
|
train
|
function (view, eventName, event) {
if (view.has(eventName)) {
// Handler should be able to re-dispatch events, so we don't
// preventDefault or stopPropagation.
return _emberMetalInstrumentation.flaggedInstrument('interaction.' + eventName, { event: event, view: view }, function () {
return _emberMetalRun_loop.default.join(view, view.trigger, eventName, event);
});
} else {
return true; // continue event propagation
}
}
|
javascript
|
{
"resource": ""
}
|
|
q53606
|
train
|
function (parsedPath) {
return View._classStringForValue(parsedPath.path, parsedPath.stream.value(), parsedPath.className, parsedPath.falsyClassName);
}
|
javascript
|
{
"resource": ""
}
|
|
q53607
|
wrap
|
train
|
function wrap(template) {
if (template === null) {
return null;
}
return {
meta: template.meta,
arity: template.arity,
raw: template,
render: function (self, env, options, blockArguments) {
var scope = env.hooks.createFreshScope();
var contextualElement = options && options.contextualElement;
var renderOptions = new _htmlbarsRuntimeRender.RenderOptions(null, self, blockArguments, contextualElement);
return _htmlbarsRuntimeRender.default(template, env, scope, renderOptions);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q53608
|
advanceToKey
|
train
|
function advanceToKey(key) {
var seek = currentMorph;
while (seek.key !== key) {
candidates[seek.key] = seek;
seek = seek.nextMorph;
}
currentMorph = seek.nextMorph;
return seek;
}
|
javascript
|
{
"resource": ""
}
|
q53609
|
Morph
|
train
|
function Morph(domHelper, contextualElement) {
this.domHelper = domHelper;
// context if content if current content is detached
this.contextualElement = contextualElement;
// inclusive range of morph
// these should be nodeType 1, 3, or 8
this.firstNode = null;
this.lastNode = null;
// flag to force text to setContent to be treated as html
this.parseTextAsHTML = false;
// morph list graph
this.parentMorphList = null;
this.previousMorph = null;
this.nextMorph = null;
}
|
javascript
|
{
"resource": ""
}
|
q53610
|
ReferenceIterator
|
train
|
function ReferenceIterator(iterable) {
_classCallCheck(this, ReferenceIterator);
this.iterator = null;
var artifacts = new IterationArtifacts(iterable);
this.artifacts = artifacts;
}
|
javascript
|
{
"resource": ""
}
|
q53611
|
train
|
function (ch) {
// DEBUG "Processing `" + ch + "`:"
var nextStates = this.nextStates,
child,
charSpec,
chars;
// DEBUG " " + debugState(this)
var returned = [];
for (var i = 0, l = nextStates.length; i < l; i++) {
child = nextStates[i];
charSpec = child.charSpec;
if (typeof (chars = charSpec.validChars) !== 'undefined') {
if (chars.indexOf(ch) !== -1) {
returned.push(child);
}
} else if (typeof (chars = charSpec.invalidChars) !== 'undefined') {
if (chars.indexOf(ch) === -1) {
returned.push(child);
}
}
}
return returned;
}
|
javascript
|
{
"resource": ""
}
|
|
q53612
|
train
|
function (handlerName) {
var partitionedArgs = _routerUtils.extractQueryParams(_routerUtils.slice.call(arguments, 1)),
suppliedParams = partitionedArgs[0],
queryParams = partitionedArgs[1];
// Construct a TransitionIntent with the provided params
// and apply it to the present state of the router.
var intent = new _routerTransitionIntentNamedTransitionIntent.default({ name: handlerName, contexts: suppliedParams });
var state = intent.applyToState(this.state, this.recognizer, this.getHandler);
var params = {};
for (var i = 0, len = state.handlerInfos.length; i < len; ++i) {
var handlerInfo = state.handlerInfos[i];
var handlerParams = handlerInfo.serialize();
_routerUtils.merge(params, handlerParams);
}
params.queryParams = queryParams;
return this.recognizer.generate(handlerName, params);
}
|
javascript
|
{
"resource": ""
}
|
|
q53613
|
train
|
function () {
if (this.isAborted) {
return this;
}
_routerUtils.log(this.router, this.sequence, this.targetName + ": transition was aborted");
this.intent.preTransitionState = this.router.state;
this.isAborted = true;
this.isActive = false;
this.router.activeTransition = null;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q53614
|
race
|
train
|
function race(entries, label) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(_rsvpInternal.noop, label);
if (!_rsvpUtils.isArray(entries)) {
_rsvpInternal.reject(promise, new TypeError('You must pass an array to race.'));
return promise;
}
var length = entries.length;
function onFulfillment(value) {
_rsvpInternal.resolve(promise, value);
}
function onRejection(reason) {
_rsvpInternal.reject(promise, reason);
}
for (var i = 0; promise._state === _rsvpInternal.PENDING && i < length; i++) {
_rsvpInternal.subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
}
return promise;
}
|
javascript
|
{
"resource": ""
}
|
q53615
|
fsOperationFailed
|
train
|
function fsOperationFailed(stream, sourceFile, err) {
if (err.code !== 'ENOENT') {
stream.emit('error', new PluginError('gulp-changed', err, {
fileName: sourceFile.path
}));
}
stream.push(sourceFile);
}
|
javascript
|
{
"resource": ""
}
|
q53616
|
compareLastModifiedTime
|
train
|
function compareLastModifiedTime(stream, sourceFile, targetPath) {
return stat(targetPath)
.then(targetStat => {
if (sourceFile.stat && sourceFile.stat.mtime > targetStat.mtime) {
stream.push(sourceFile);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q53617
|
compareContents
|
train
|
function compareContents(stream, sourceFile, targetPath) {
return readFile(targetPath)
.then(targetData => {
if (sourceFile.isNull() || !sourceFile.contents.equals(targetData)) {
stream.push(sourceFile);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q53618
|
train
|
function (layers) {
var layersArray = this._toArray(layers),
separated = this._checkInGetSeparated(layersArray),
groups = separated.groups,
i, group, id;
// Batch add all single layers.
this._originalAddLayers(separated.singles);
// Add Layer Groups to the map so that they are registered there and
// the map fires 'layeradd' events for them as well.
for (i = 0; i < groups.length; i++) {
group = groups[i];
id = L.stamp(group);
this._proxyLayerGroups[id] = group;
delete this._proxyLayerGroupsNeedRemoving[id];
if (this._map) {
this._map._originalAddLayer(group);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q53619
|
train
|
function (layers) {
var layersArray = this._toArray(layers),
separated = this._separateSingleFromGroupLayers(layersArray, {
groups: [],
singles: []
}),
groups = separated.groups,
singles = separated.singles,
i = 0,
group, id;
// Batch remove single layers from MCG.
this._originalRemoveLayers(singles);
// Remove Layer Groups from the map so that they are un-registered
// there and the map fires 'layerremove' events for them as well.
for (; i < groups.length; i++) {
group = groups[i];
id = L.stamp(group);
delete this._proxyLayerGroups[id];
if (this._map) {
this._map._originalRemoveLayer(group);
} else {
this._proxyLayerGroupsNeedRemoving[id] = group;
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q53620
|
train
|
function (layer, operationType) {
var duration = this.options.singleAddRemoveBufferDuration,
fn;
if (duration > 0) {
this._singleAddRemoveBuffer.push({
type: operationType,
layer: layer
});
if (!this._singleAddRemoveBufferTimeout) {
fn = L.bind(this._processSingleAddRemoveBuffer, this);
this._singleAddRemoveBufferTimeout = setTimeout(fn, duration);
}
} else { // If duration <= 0, process synchronously.
this[operationType](layer);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q53621
|
train
|
function (layerGroup) {
if (layerGroup._proxyMcgLayerSupportGroup === undefined ||
layerGroup._proxyMcgLayerSupportGroup !== this) {
return;
}
delete layerGroup._proxyMcgLayerSupportGroup;
layerGroup.addLayer = layerGroup._originalAddLayer;
layerGroup.removeLayer = layerGroup._originalRemoveLayer;
layerGroup.onAdd = layerGroup._originalOnAdd;
layerGroup.onRemove = layerGroup._originalOnRemove;
var id = L.stamp(layerGroup);
delete this._proxyLayerGroups[id];
delete this._proxyLayerGroupsNeedRemoving[id];
this._removeFromOwnMap(layerGroup);
}
|
javascript
|
{
"resource": ""
}
|
|
q53622
|
train
|
function (map) {
var layers = this._layers,
toBeReAdded = [],
layer;
for (var id in layers) {
layer = layers[id];
if (layer._map) {
toBeReAdded.push(layer);
map._originalRemoveLayer(layer);
}
}
return toBeReAdded;
}
|
javascript
|
{
"resource": ""
}
|
|
q53623
|
train
|
function (layer) {
var id = this.getLayerId(layer);
this._layers[id] = layer;
if (this._map) {
this._proxyMcgLayerSupportGroup.addLayer(layer);
} else {
this._proxyMcgLayerSupportGroup.checkIn(layer);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q53624
|
train
|
function (layer) {
var id = layer in this._layers ? layer : this.getLayerId(layer);
this._proxyMcgLayerSupportGroup.removeLayer(layer);
delete this._layers[id];
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q53625
|
wrapRegistrationFunction
|
train
|
function wrapRegistrationFunction(object, property, callbackArg) {
if (typeof object[property] !== "function") {
console.error("(long-stack-traces) Object", object, "does not contain function", property);
return;
}
if (!has.call(object, property)) {
console.warn("(long-stack-traces) Object", object, "does not directly contain function", property);
}
// TODO: better source position detection
var sourcePosition = (object.constructor.name || Object.prototype.toString.call(object)) + "." + property;
// capture the original registration function
var fn = object[property];
// overwrite it with a wrapped registration function that modifies the supplied callback argument
object[property] = function() {
// replace the callback argument with a wrapped version that captured the current stack trace
arguments[callbackArg] = makeWrappedCallback(arguments[callbackArg], sourcePosition);
// call the original registration function with the modified arguments
return fn.apply(this, arguments);
}
// check that the registration function was indeed overwritten
if (object[property] === fn)
console.warn("(long-stack-traces) Couldn't replace ", property, "on", object);
}
|
javascript
|
{
"resource": ""
}
|
q53626
|
makeWrappedCallback
|
train
|
function makeWrappedCallback(callback, frameLocation) {
// add a fake stack frame. we can't get a real one since we aren't inside the original function
var traceError = new Error();
traceError.__location = frameLocation;
traceError.__previous = currentTraceError;
return function() {
// if (currentTraceError) {
// FIXME: This shouldn't normally happen, but it often does. Do we actually need a stack instead?
// console.warn("(long-stack-traces) Internal Error: currentTrace already set.");
// }
// restore the trace
currentTraceError = traceError;
try {
return callback.apply(this, arguments);
} catch (e) {
console.error("Uncaught " + e.stack);
if (LST.rethrow)
throw ""; // TODO: throw the original error, or undefined?
} finally {
// clear the trace so we can check that none is set above.
// TODO: could we remove this for slightly better performace?
currentTraceError = null;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q53627
|
_parserFirefox
|
train
|
function _parserFirefox(error){
// start parse the error stack string
var lines = error.stack.split("\n").slice(0, -1);
var stacktrace = [];
lines.forEach(function(line){
var matches = line.match(/^(.*)@(.+):(\d+)$/);
stacktrace.push(new Stacktrace.Frame({
fct : matches[1] === '' ? '<anonymous>' : matches[1],
url : matches[2],
line : parseInt(matches[3], 10),
column : 1
}));
});
return stacktrace;
}
|
javascript
|
{
"resource": ""
}
|
q53628
|
_parserPhantomJS
|
train
|
function _parserPhantomJS(error){
// start parse the error stack string
var lines = error.stack.split("\n").slice(1);
var stacktrace = [];
lines.forEach(function(line){
if( line.match(/\(native\)$/) ){
var matches = line.match(/^\s*at (.+) \(native\)/);
stacktrace.push(new Stacktrace.Frame({
fct : matches[1],
url : 'native',
line : 1,
column : 1
}));
}else if( line.match(/\)$/) ){
var matches = line.match(/^\s*at (.+) \((.+):(\d+)\)/);
stacktrace.push(new Stacktrace.Frame({
fct : matches[1],
url : matches[2],
line : parseInt(matches[3], 10),
column : 1
}));
}else{
var matches = line.match(/^\s*at (.+):(\d+)/);
stacktrace.push(new Stacktrace.Frame({
url : matches[1],
fct : '<anonymous>',
line : parseInt(matches[2], 10),
column : 1
}));
}
});
return stacktrace;
}
|
javascript
|
{
"resource": ""
}
|
q53629
|
typeToString
|
train
|
function typeToString(allowedType){
if( allowedType === Number ) return 'Number'
if( allowedType === String ) return 'String'
if( allowedType === Object ) return 'Object'
if( allowedType === undefined ) return 'undefined'
return allowedType.toString()
}
|
javascript
|
{
"resource": ""
}
|
q53630
|
merge
|
train
|
function merge(target, source) {
// Check if font name is changed
if (source['font-name']) {
target['font-name'] = source['font-name'];
}
// Check if root dir is changed
if (source['root-dir']) {
target['root-dir'] = source['root-dir'];
}
// Check for icon changes
if (source.icons) {
for (let icon of source['icons']) {
let index = iconsIndex.indexOf(icon.name);
// Icon is replaced
if (index !== -1) {
target.icons[index] = icon;
}
// New icon is added
else {
target.icons.push(icon);
iconsIndex.push(icon.name);
}
}
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
q53631
|
train
|
function(grunt, script, sources, params) {
var flag;
var cmd = script;
var args =[];
// Compute JSDoc options
for (flag in params) {
if (params.hasOwnProperty(flag)) {
if (params[flag] !== false) {
args.push('--' + flag);
}
if (typeof params[flag] === 'string') {
args.push(params[flag]);
}
}
}
if (!Array.isArray(sources)) {
sources = [sources];
}
args = args.concat(sources);
grunt.log.debug('Running : ' + cmd + ' ' + args.join(' '));
return spawn(cmd, args);
}
|
javascript
|
{
"resource": ""
}
|
|
q53632
|
train
|
function(grunt) {
var i, binPath, paths;
var nodePath = process.env.NODE_PATH || '';
//check first the base path into the cwd
paths = [
__dirname + '/../../node_modules/.bin/jsdoc',
__dirname + '/../../node_modules/jsdoc/jsdoc.js',
__dirname + '/../../../jsdoc/jsdoc.js'
];
//fall back on global if not found at the usual location
nodePath.split(path.delimiter).forEach(function(p) {
if (!/\/$/.test(p)) {
p += '/';
}
paths.push(p + '/jsdoc/jsdoc.js');
});
for (i in paths) {
binPath = path.resolve(paths[i]);
if (grunt.file.exists(binPath) && grunt.file.isFile(binPath)) {
return binPath;
}
}
return;
}
|
javascript
|
{
"resource": ""
}
|
|
q53633
|
compileTemplates
|
train
|
function compileTemplates() {
const mainHtml = fs.readFileSync(path.resolve(docsDir, 'src/template.html'), {
encoding: 'utf8',
});
const mainTemplate = Handlebars.compile(mainHtml);
function createPage(fileName, tab, content) {
const html = mainTemplate({
tabs: [{
title: 'Get started',
url: 'get-started.html',
selected: tab === 'get-started',
}, {
title: 'Components',
url: 'components.html',
selected: tab === 'components',
}],
content,
luiVersion: LUI_VERSION,
});
fileUtil.writeFile(path.resolve(docsDir, 'dist', fileName), html);
}
function createIndexPage() {
const content = fs.readFileSync(path.resolve(docsDir, 'src/pages/index.html'), {
encoding: 'utf8',
});
const template = Handlebars.compile(content);
const html = template();
return createPage('index.html', 'index', html);
}
function createGetStartedPage() {
const content = fs.readFileSync(path.resolve(docsDir, 'src/pages/get-started.html'), {
encoding: 'utf8',
});
const template = Handlebars.compile(content);
const html = template({
luiVersion: LUI_VERSION,
});
return createPage('get-started.html', 'get-started', html);
}
function createComponentPage(templateName, template, tab, content) {
return createPage(templateName, tab, template({
content,
sections: sections.map(section => ({
name: section.name,
pages: section.pages.map(page => ({
name: page.name,
template: page.template,
selected: page.template === templateName,
})),
})),
}));
}
function createComponentPages() {
const componentHtml = fs.readFileSync(path.resolve(docsDir, 'src/component-template.html'), {
encoding: 'utf8',
});
const componentTemplate = Handlebars.compile(componentHtml);
sections.forEach((section) => {
section.pages.forEach((page) => {
const file = `src/pages/${page.template}`;
const fileContent = fs.readFileSync(path.resolve(docsDir, file), {
encoding: 'utf8',
});
const template = Handlebars.compile(fileContent);
const html = template();
createComponentPage(page.template, componentTemplate, 'components', html);
});
});
const file = 'src/pages/components.html';
const fileContent = fs.readFileSync(path.resolve(docsDir, file), {
encoding: 'utf8',
});
createComponentPage('components.html', componentTemplate, 'components', fileContent);
}
createIndexPage();
createGetStartedPage();
createComponentPages();
}
|
javascript
|
{
"resource": ""
}
|
q53634
|
copyResources
|
train
|
function copyResources() {
// Source code deps
fileUtil.copyFile(path.resolve(docsDir, '../dist/leonardo-ui.js'), path.resolve(docsDir, 'dist/leonardo-ui/leonardo-ui.js'));
fileUtil.copyFile(path.resolve(docsDir, '../dist/leonardo-ui.js.map'), path.resolve(docsDir, 'dist/leonardo-ui/leonardo-ui.js.map'));
fileUtil.copyFile(path.resolve(docsDir, '../dist/leonardo-ui.css'), path.resolve(docsDir, 'dist/leonardo-ui/leonardo-ui.css'));
fileUtil.copyFile(path.resolve(docsDir, '../dist/leonardo-ui.css.map'), path.resolve(docsDir, 'dist/leonardo-ui/leonardo-ui.css.map'));
fileUtil.copyFile(path.resolve(docsDir, '../dist/lui-icons.ttf'), path.resolve(docsDir, 'dist/leonardo-ui/lui-icons.ttf'));
fileUtil.copyFile(path.resolve(docsDir, '../dist/lui-icons.woff'), path.resolve(docsDir, 'dist/leonardo-ui/lui-icons.woff'));
// Doc files
glob.sync(`${path.resolve(docsDir, 'src/img')}/**.*`).forEach((file) => {
const folder = path.resolve(docsDir, 'src/img/').replace(/\\/g, '/'); // Because glob uses forward slashes on all paths
const fileName = file.replace(folder, '');
fileUtil.copyFile(file, path.resolve(docsDir, `dist/resources/${fileName}`));
});
}
|
javascript
|
{
"resource": ""
}
|
q53635
|
getCanonicalNamePlain
|
train
|
function getCanonicalNamePlain(loader, normalized, isPlugin) {
// now just reverse apply paths rules to get canonical name
var pathMatch;
// first check exact path matches
for (var p in loader.paths) {
if (loader.paths[p].indexOf('*') != -1)
continue;
var curPath = normalizePath(loader, loader.paths[p], isPlugin);
// always stop on first exact match
if (normalized === curPath)
return p;
// support trailing / in paths rules
else if (curPath[curPath.length - 1] == '/' &&
normalized.substr(0, curPath.length - 1) == curPath.substr(0, curPath.length - 1) &&
(normalized.length < curPath.length || normalized[curPath.length - 1] == curPath[curPath.length - 1])) {
// first case is that canonicalize('src') = 'app' for 'app/': 'src/'
return normalized.length < curPath.length ? p.substr(0, p.length - 1) : p + normalized.substr(curPath.length);
}
}
// then wildcard matches
var pathMatchLength = 0;
var curMatchLength;
if (!pathMatch)
for (var p in loader.paths) {
if (loader.paths[p].indexOf('*') == -1)
continue;
// normalize the output path
var curPath = normalizePath(loader, loader.paths[p], true);
// do reverse match
var wIndex = curPath.indexOf('*');
if (normalized.substr(0, wIndex) === curPath.substr(0, wIndex)
&& normalized.substr(normalized.length - curPath.length + wIndex + 1) === curPath.substr(wIndex + 1)) {
curMatchLength = curPath.split('/').length;
if (curMatchLength >= pathMatchLength) {
pathMatch = p.replace('*', normalized.substr(wIndex, normalized.length - curPath.length + 1));
pathMatchLength = curMatchLength;
}
}
}
// when no path was matched, act like the standard rule is *: baseURL/*
if (!pathMatch) {
if (normalized.substr(0, loader.baseURL.length) == loader.baseURL)
pathMatch = normalized.substr(loader.baseURL.length);
else if (normalized.match(absURLRegEx))
throw new Error('Unable to calculate canonical name to bundle ' + normalized + '. Ensure that this module sits within the baseURL or a wildcard path config.');
else
pathMatch = normalized;
}
return pathMatch;
}
|
javascript
|
{
"resource": ""
}
|
q53636
|
createPkgConfigPathObj
|
train
|
function createPkgConfigPathObj(path) {
var lastWildcard = path.lastIndexOf('*');
var length = Math.max(lastWildcard + 1, path.lastIndexOf('/'));
return {
length: length,
regEx: new RegExp('^(' + path.substr(0, length).replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^\\/]+') + ')(\\/|$)'),
wildcard: lastWildcard != -1
};
}
|
javascript
|
{
"resource": ""
}
|
q53637
|
booleanEnvTrace
|
train
|
function booleanEnvTrace(condition) {
var conditionObj = parseCondition(condition);
if (conditionObj.negate)
return traceCondition(conditionalComplement(condition), false);
else
return traceCondition(condition, true);
}
|
javascript
|
{
"resource": ""
}
|
q53638
|
optimizePackageConfig
|
train
|
function optimizePackageConfig(json) {
if (json.systemjs)
json = json.systemjs;
// remove non SystemJS package config properties
var loaderConfigProperties = ['baseDir', 'defaultExtension', 'format', 'meta', 'map', 'main'];
for (var p in json)
if (loaderConfigProperties.indexOf(p) == -1)
delete json[p];
if (json.map && !json.map['@env']) {
Object.keys(json.map).forEach(function(target) {
var mapped = json.map[target];
if (typeof mapped == 'string' && mapped.substr(0, 6) == '@node/')
delete json.map[target];
if (typeof mapped == 'object') {
Object.keys(mapped).forEach(function(condition) {
if (condition == 'node')
delete mapped[condition];
});
if (!hasProperties(mapped))
delete json.map[target];
}
});
if (!hasProperties(json.map))
delete json.map;
}
return json;
}
|
javascript
|
{
"resource": ""
}
|
q53639
|
getCompileHash
|
train
|
function getCompileHash(load, compileOpts) {
return createHash('md5')
.update(JSON.stringify({
source: load.source,
metadata: load.metadata,
path: compileOpts.sourceMaps && load.path,
normalize: compileOpts.normalize,
anonymous: compileOpts.anonymous,
systemGlobal: compileOpts.systemGlobal,
static: compileOpts.static,
encodeNames: compileOpts.encodeNames,
sourceMaps: compileOpts.sourceMaps,
lowResSourceMaps: compileOpts.lowResSourceMaps
}))
.digest('hex');
}
|
javascript
|
{
"resource": ""
}
|
q53640
|
remapLoadRecord
|
train
|
function remapLoadRecord(load, mapFunction) {
load = extend({}, load);
load.name = mapFunction(load.name, load.name);
var depMap = {};
Object.keys(load.depMap).forEach(function(dep) {
depMap[dep] = mapFunction(load.depMap[dep], dep);
});
load.depMap = depMap;
return load;
}
|
javascript
|
{
"resource": ""
}
|
q53641
|
train
|
function(element, htSettings) {
var container = document.createElement('div'),
hot;
container.className = this.containerClassName;
if (htSettings.hotId) {
container.id = htSettings.hotId;
}
element[0].appendChild(container);
hot = new Handsontable(container, htSettings);
if (htSettings.hotId) {
hotRegisterer.registerInstance(htSettings.hotId, hot);
}
return hot;
}
|
javascript
|
{
"resource": ""
}
|
|
q53642
|
train
|
function(settings, scope) {
var
scopeOptions = angular.extend({}, scope),
htOptions, i, length;
settings = settings || {};
angular.extend(scopeOptions, scope.settings || {});
htOptions = this.getAvailableSettings();
for (i = 0, length = htOptions.length; i < length; i++) {
if (typeof scopeOptions[htOptions[i]] !== 'undefined') {
settings[htOptions[i]] = scopeOptions[htOptions[i]];
}
}
return settings;
}
|
javascript
|
{
"resource": ""
}
|
|
q53643
|
train
|
function(settings, scope) {
var
scopeOptions = angular.extend({}, scope),
htHooks, i, length, attribute;
settings = settings || {};
angular.extend(scopeOptions, scope.settings || {});
htHooks = this.getAvailableHooks();
for (i = 0, length = htHooks.length; i < length; i++) {
attribute = 'on' + ucFirst(htHooks[i]);
if (typeof scopeOptions[htHooks[i]] === 'function' || typeof scopeOptions[attribute] === 'function') {
settings[htHooks[i]] = scopeOptions[htHooks[i]] || scopeOptions[attribute];
}
}
return settings;
}
|
javascript
|
{
"resource": ""
}
|
|
q53644
|
train
|
function(scopeDefinition, attrs) {
for (var i in scopeDefinition) {
if (scopeDefinition.hasOwnProperty(i) && attrs[i] === void 0 &&
attrs[scopeDefinition[i].substr(1, scopeDefinition[i].length)] === void 0) {
delete scopeDefinition[i];
}
}
return scopeDefinition;
}
|
javascript
|
{
"resource": ""
}
|
|
q53645
|
train
|
function() {
var scopeDefinition = {};
this.applyAvailableSettingsScopeDef(scopeDefinition);
this.applyAvailableHooksScopeDef(scopeDefinition);
scopeDefinition.datarows = '=';
scopeDefinition.dataschema = '=';
scopeDefinition.observeDomVisibility = '=';
//scopeDefinition.settings = '=';
return scopeDefinition;
}
|
javascript
|
{
"resource": ""
}
|
|
q53646
|
train
|
function(scopeDefinition) {
var options, i, length;
options = this.getAvailableSettings();
for (i = 0, length = options.length; i < length; i++) {
scopeDefinition[options[i]] = '=';
}
return scopeDefinition;
}
|
javascript
|
{
"resource": ""
}
|
|
q53647
|
train
|
function(scopeDefinition) {
var options, i, length;
options = this.getAvailableHooks();
for (i = 0, length = options.length; i < length; i++) {
scopeDefinition[options[i]] = '=on' + ucFirst(options[i]);
}
return scopeDefinition;
}
|
javascript
|
{
"resource": ""
}
|
|
q53648
|
train
|
function(hyphenateStyle) {
var settings = Object.keys(Handsontable.DefaultSettings.prototype);
if (settings.indexOf('contextMenuCopyPaste') === -1) {
settings.push('contextMenuCopyPaste');
}
if (settings.indexOf('handsontable') === -1) {
settings.push('handsontable');
}
if (settings.indexOf('settings') >= 0) {
settings.splice(settings.indexOf('settings'), 1);
}
if (hyphenateStyle) {
settings = settings.map(hyphenate);
}
return settings;
}
|
javascript
|
{
"resource": ""
}
|
|
q53649
|
train
|
function(hyphenateStyle) {
var settings = Handsontable.hooks.getRegistered();
if (hyphenateStyle) {
settings = settings.map(function(hook) {
return 'on-' + hyphenate(hook);
});
}
return settings;
}
|
javascript
|
{
"resource": ""
}
|
|
q53650
|
autoClosePopups
|
train
|
function autoClosePopups(clear) {
if (clear) {
clearTimeout(modalTimerID);
modalTimerID = undefined;
} else {
modalTimerID = setTimeout(function() {
bootbox.hideAll();
}, 30000);
}
}
|
javascript
|
{
"resource": ""
}
|
q53651
|
buildUserHtml
|
train
|
function buildUserHtml(userLogin, userId, isNew) {
var userHtml = "<a href='#' id='" + userId;
if(isNew){
userHtml += "_new'";
}else{
userHtml += "'";
}
userHtml += " class='col-md-12 col-sm-12 col-xs-12 users_form' onclick='";
userHtml += "clickToAdd";
userHtml += "(\"";
userHtml += userId;
if(isNew){
userHtml += "_new";
}
userHtml += "\")'>";
userHtml += userLogin;
userHtml +="</a>";
return userHtml;
}
|
javascript
|
{
"resource": ""
}
|
q53652
|
cleanLaunchStoryboardImages
|
train
|
function cleanLaunchStoryboardImages(projectRoot, projectConfig, locations) {
var splashScreens = projectConfig.getSplashScreens('ios');
var platformProjDir = locations.xcodeCordovaProj;
var launchStoryboardImagesDir = getLaunchStoryboardImagesDir(projectRoot, platformProjDir);
if (launchStoryboardImagesDir) {
var resourceMap = mapLaunchStoryboardResources(splashScreens, launchStoryboardImagesDir);
var contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, launchStoryboardImagesDir);
Object.keys(resourceMap).forEach(function (targetPath) {
resourceMap[targetPath] = null;
});
events.emit('verbose', 'Cleaning storyboard image set at ' + launchStoryboardImagesDir);
// Source paths are removed from the map, so updatePaths() will delete the target files.
FileUpdater.updatePaths(
resourceMap, { rootDir: projectRoot, all: true }, logFileOp);
// delete filename from contents.json
contentsJSON.images.forEach(function(image) {
image.filename = undefined;
});
events.emit('verbose', 'Updating Storyboard image set contents.json');
fs.writeFileSync(path.join(launchStoryboardImagesDir, 'contents.json'),
JSON.stringify(contentsJSON, null, 2));
}
}
|
javascript
|
{
"resource": ""
}
|
q53653
|
train
|
function(callback, isInitialConnect) {
Utils.QBLog('[QBChat]', 'Status.CONNECTED at ' + chatUtils.getLocalTime());
var self = this,
xmppClient = Utils.getEnv().browser ? self.connection : self.Client,
presence = Utils.getEnv().browser ? $pres() : chatUtils.createStanza(XMPP.Stanza, null, 'presence');
if (config.streamManagement.enable && config.chatProtocol.active === 2) {
self.streamManagement.enable(self.connection, null);
self.streamManagement.sentMessageCallback = self._sentMessageCallback;
}
self.helpers.setUserCurrentJid(self.helpers.userCurrentJid(xmppClient));
self.isConnected = true;
self._isConnecting = false;
self._enableCarbons();
if (isInitialConnect) {
self.roster.get(function(contacts) {
xmppClient.send(presence);
self.roster.contacts = contacts;
callback(self.roster.contacts);
});
} else {
var rooms = Object.keys(self.muc.joinedRooms);
xmppClient.send(presence);
Utils.QBLog('[QBChat]', 'Re-joining ' + rooms.length + " rooms...");
for (var i = 0, len = rooms.length; i < len; i++) {
self.muc.join(rooms[i]);
}
if (typeof self.onReconnectListener === 'function') {
Utils.safeCallbackCall(self.onReconnectListener);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q53654
|
train
|
function(listWithUpdates, callback) {
/**
* Callback for QB.chat.privacylist.update().
* @param {Object} error - The error object
* @param {Object} response - The privacy list object
* @callback updatePrivacylistCallback
* */
var self = this;
self.getList(listWithUpdates.name, function(error, existentList) {
if (error) {
callback(error, null);
} else {
var updatedList = {};
updatedList.items = Utils.MergeArrayOfObjects(existentList.items, listWithUpdates.items);
updatedList.name = listWithUpdates.name;
self.create(updatedList, function(err, result) {
if (error) {
callback(err, null);
}else{
callback(null, result);
}
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53655
|
train
|
function(jid_or_user_id) {
var jid;
if (typeof jid_or_user_id === 'string') {
jid = jid_or_user_id;
} else if (typeof jid_or_user_id === 'number') {
jid = jid_or_user_id + '-' + config.creds.appId + '@' + config.endpoints.chat;
} else {
throw new Error('The method "jidOrUserId" may take jid or id');
}
return jid;
}
|
javascript
|
{
"resource": ""
}
|
|
q53656
|
train
|
function(jid_or_user_id) {
var chatType;
if (typeof jid_or_user_id === 'string') {
chatType = jid_or_user_id.indexOf("muc") > -1 ? 'groupchat' : 'chat';
} else if (typeof jid_or_user_id === 'number') {
chatType = 'chat';
} else {
throw new Error(unsupportedError);
}
return chatType;
}
|
javascript
|
{
"resource": ""
}
|
|
q53657
|
train
|
function(occupantsIds, UserId) {
var recipient = null;
occupantsIds.forEach(function(item) {
if(item != UserId){
recipient = item;
}
});
return recipient;
}
|
javascript
|
{
"resource": ""
}
|
|
q53658
|
train
|
function(userId, appId) {
if(!appId){
return userId + '-' + config.creds.appId + '@' + config.endpoints.chat;
}
return userId + '-' + appId + '@' + config.endpoints.chat;
}
|
javascript
|
{
"resource": ""
}
|
|
q53659
|
train
|
function(jid) {
var s = jid.split('/');
if (s.length < 2) return null;
s.splice(0, 1);
return parseInt(s.join('/'));
}
|
javascript
|
{
"resource": ""
}
|
|
q53660
|
train
|
function(jid) {
var arrayElements = jid.toString().split('/');
if(arrayElements.length === 0){
return null;
}
return arrayElements[arrayElements.length-1];
}
|
javascript
|
{
"resource": ""
}
|
|
q53661
|
filterSupportedArgs
|
train
|
function filterSupportedArgs(args) {
var filtered = [];
var sargs = ['--device', '--emulator', '--nobuild', '--list', '--target', '--debug', '--release'];
var re = new RegExp(sargs.join('|'));
args.forEach(function(element) {
// supported args not found, we add
// we do a regex search because --target can be "--target=XXX"
if (element.search(re) == -1) {
filtered.push(element);
}
}, this);
return filtered;
}
|
javascript
|
{
"resource": ""
}
|
q53662
|
clickSendMessage
|
train
|
function clickSendMessage() {
var currentText = $('#message_text').val().trim();
if (!currentText.length) {
return;
}
$('#message_text').val('').focus();
sendMessage(currentText, null);
}
|
javascript
|
{
"resource": ""
}
|
q53663
|
showMessage
|
train
|
function showMessage(userId, msg, attachmentFileId) {
var userLogin = getUserLoginById(userId);
var messageHtml = buildMessageHTML(msg.body, userLogin, new Date(), attachmentFileId, msg.id);
$('#messages-list').append(messageHtml);
// scroll to bottom
var mydiv = $('#messages-list');
mydiv.scrollTop(mydiv.prop('scrollHeight'));
}
|
javascript
|
{
"resource": ""
}
|
q53664
|
sendTypingStatus
|
train
|
function sendTypingStatus() {
if (currentDialog.type == 3) {
QB.chat.sendIsTypingStatus(opponentId);
} else if (currentDialog && currentDialog.xmpp_room_jid) {
QB.chat.sendIsTypingStatus(currentDialog.xmpp_room_jid);
}
}
|
javascript
|
{
"resource": ""
}
|
q53665
|
sendStopTypinStatus
|
train
|
function sendStopTypinStatus() {
if (currentDialog.type == 3) {
QB.chat.sendIsStopTypingStatus(opponentId);
} else {
QB.chat.sendIsStopTypingStatus(currentDialog.xmpp_room_jid);
}
}
|
javascript
|
{
"resource": ""
}
|
q53666
|
showUserIsTypingView
|
train
|
function showUserIsTypingView(isTyping, userId, dialogId) {
if (isMessageForCurrentDialog(userId, dialogId)) {
if (!isTyping) {
$('#' + userId + '_typing').remove();
} else if (userId != currentUser.id) {
var userLogin = getUserLoginById(userId);
var typingUserHtml = buildTypingUserHtml(userId, userLogin);
$('#messages-list').append(typingUserHtml);
}
// scroll to bottom
var mydiv = $('#messages-list');
mydiv.scrollTop(mydiv.prop('scrollHeight'));
}
}
|
javascript
|
{
"resource": ""
}
|
q53667
|
isMessageForCurrentDialog
|
train
|
function isMessageForCurrentDialog(userId, dialogId) {
var result = false;
if (dialogId == currentDialog._id || (dialogId === null && currentDialog.type == 3 && opponentId == userId)) {
result = true;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q53668
|
checkTool
|
train
|
function checkTool (tool, minVersion, message, toolFriendlyName) {
toolFriendlyName = toolFriendlyName || tool;
// Check whether tool command is available at all
var tool_command = shell.which(tool);
if (!tool_command) {
return Q.reject(toolFriendlyName + ' was not found. ' + (message || ''));
}
// check if tool version is greater than specified one
return versions.get_tool_version(tool).then(function (version) {
version = version.trim();
return versions.compareVersions(version, minVersion) >= 0 ?
Q.resolve(version) :
Q.reject('Cordova needs ' + toolFriendlyName + ' version ' + minVersion +
' or greater, you have version ' + version + '. ' + (message || ''));
});
}
|
javascript
|
{
"resource": ""
}
|
q53669
|
SoundMeter
|
train
|
function SoundMeter(context) {
this.context = context;
this.instant = 0.0;
this.slow = 0.0;
this.clip = 0.0;
this.script = context.createScriptProcessor(2048, 1, 1);
var that = this;
this.script.onaudioprocess = function(event) {
var input = event.inputBuffer.getChannelData(0);
var i;
var sum = 0.0;
var clipcount = 0;
for (i = 0; i < input.length; ++i) {
sum += input[i] * input[i];
if (Math.abs(input[i]) > 0.99) {
clipcount += 1;
}
}
that.instant = Math.sqrt(sum / input.length);
that.slow = 0.95 * that.slow + 0.05 * that.instant;
that.clip = clipcount / input.length;
};
}
|
javascript
|
{
"resource": ""
}
|
q53670
|
Device
|
train
|
function Device() {
this.available = false;
this.platform = null;
this.version = null;
this.uuid = null;
this.cordova = null;
this.model = null;
this.manufacturer = null;
this.isVirtual = null;
this.serial = null;
var me = this;
channel.onCordovaReady.subscribe(function() {
me.getInfo(function(info) {
//ignoring info.cordova returning from native, we should use value from cordova.version defined in cordova.js
//TODO: CB-5105 native implementations should not return info.cordova
var buildLabel = cordova.version;
me.available = true;
me.platform = info.platform;
me.version = info.version;
me.uuid = info.uuid;
me.cordova = buildLabel;
me.model = info.model;
me.isVirtual = info.isVirtual;
me.manufacturer = info.manufacturer || 'unknown';
me.serial = info.serial || 'unknown';
channel.onCordovaInfoReady.fire();
},function(e) {
me.available = false;
utils.alert("[ERROR] Error initializing Cordova: " + e);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q53671
|
train
|
function(isCompactOrCallback, callback) {
var self = this;
var isCompact, cb;
if(isFunction(isCompactOrCallback)) {
cb = isCompactOrCallback;
} else {
isCompact = isCompactOrCallback;
cb = callback;
}
if(!isFunction(cb)) {
throw new Error('The QB.addressbook.get accept callback function is required.');
}
var ajaxParams = {
'type': 'GET',
'url': Utils.getUrl(config.urls.addressbookRegistered),
'contentType': 'application/json; charset=utf-8'
};
if(isCompact) {
ajaxParams.data = {'compact': 1};
}
this.service.ajax(ajaxParams, function(err, res) {
if (err) {
// Don't ask me why.
// Thanks to backend developers for this
var isFakeErrorEmptyAddressBook = self._isFakeErrorEmptyAddressBook(err);
if(isFakeErrorEmptyAddressBook) {
cb(null, []);
} else {
cb(err, null);
}
} else {
cb(null, res);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53672
|
WebRTCSession
|
train
|
function WebRTCSession(params) {
this.ID = params.sessionID ? params.sessionID : generateUUID();
this.state = WebRTCSession.State.NEW;
this.initiatorID = parseInt(params.initiatorID);
this.opponentsIDs = params.opIDs;
this.callType = parseInt(params.callType);
this.peerConnections = {};
this.localStream = null;
this.mediaParams = null;
this.signalingProvider = params.signalingProvider;
this.currentUserID = params.currentUserID;
this.bandwidth = params.bandwidth;
/**
* We use this timeout to fix next issue:
* "From Android/iOS make a call to Web and kill the Android/iOS app instantly. Web accept/reject popup will be still visible.
* We need a way to hide it if sach situation happened."
*/
this.answerTimer = null;
this.startCallTime = 0;
this.acceptCallTime = 0;
}
|
javascript
|
{
"resource": ""
}
|
q53673
|
_prepareExtension
|
train
|
function _prepareExtension(extension) {
var ext = {};
try {
if ( ({}).toString.call(extension) === '[object Object]' ) {
ext.userInfo = extension;
ext = JSON.parse( JSON.stringify(ext).replace(/null/g, "\"\"") );
} else {
throw new Error('Invalid type of "extension" object.');
}
} catch (err) {
Helpers.traceWarning(err.message);
}
return ext;
}
|
javascript
|
{
"resource": ""
}
|
q53674
|
defaultImageSrcGenerator
|
train
|
function defaultImageSrcGenerator(icon, options) {
return ''.concat(options.base, options.size, '/', icon, options.ext);
}
|
javascript
|
{
"resource": ""
}
|
q53675
|
grabTheRightIcon
|
train
|
function grabTheRightIcon(icon, variant) {
// if variant is present as \uFE0F
return toCodePoint(
variant === '\uFE0F' ?
// the icon should not contain it
icon.slice(0, -1) :
// fix non standard OSX behavior
(icon.length === 3 && icon.charAt(1) === '\uFE0F' ?
icon.charAt(0) + icon.charAt(2) : icon)
);
}
|
javascript
|
{
"resource": ""
}
|
q53676
|
sendMessage
|
train
|
function sendMessage(text, attachmentFileId) {
stickerpipe.onUserMessageSent(stickerpipe.isSticker(text));
var msg = {
type: currentDialog.type === 3 ? 'chat' : 'groupchat',
body: text,
extension: {
save_to_history: 1,
},
markable: 1
};
if(attachmentFileId !== null){
msg['extension']['attachments'] = [{id: attachmentFileId, type: 'photo'}];
}
if (currentDialog.type === 3) {
opponentId = QB.chat.helpers.getRecipientId(currentDialog.occupants_ids, currentUser.id);
QB.chat.send(opponentId, msg);
$('.list-group-item.active .list-group-item-text')
.text(stickerpipe.isSticker(msg.body) ? 'Sticker' : msg.body);
if(attachmentFileId === null){
showMessage(currentUser.id, msg);
} else {
showMessage(currentUser.id, msg, attachmentFileId);
}
} else {
QB.chat.send(currentDialog.xmpp_room_jid, msg);
}
// claer timer and send 'stop typing' status
clearTimeout(isTypingTimerId);
isTypingTimeoutCallback();
dialogsMessages.push(msg);
}
|
javascript
|
{
"resource": ""
}
|
q53677
|
createNewDialog
|
train
|
function createNewDialog() {
var usersIds = [];
var usersNames = [];
$('#users_list .users_form.active').each(function(index) {
usersIds[index] = $(this).attr('id');
usersNames[index] = $(this).text();
});
$("#add_new_dialog").modal("hide");
$('#add_new_dialog .progress').show();
var dialogName;
var dialogOccupants;
var dialogType;
if (usersIds.length > 1) {
if (usersNames.indexOf(currentUser.login) > -1) {
dialogName = usersNames.join(', ');
}else{
dialogName = currentUser.login + ', ' + usersNames.join(', ');
}
dialogOccupants = usersIds;
dialogType = 2;
} else {
dialogOccupants = usersIds;
dialogType = 3;
}
var params = {
type: dialogType,
occupants_ids: dialogOccupants,
name: dialogName
};
// create a dialog
//
console.log("Creating a dialog with params: " + JSON.stringify(params));
QB.chat.dialog.create(params, function(err, createdDialog) {
if (err) {
console.log(err);
} else {
console.log("Dialog " + createdDialog._id + " created with users: " + dialogOccupants);
// save dialog to local storage
var dialogId = createdDialog._id;
dialogs[dialogId] = createdDialog;
currentDialog = createdDialog;
joinToNewDialogAndShow(createdDialog);
notifyOccupants(createdDialog.occupants_ids, createdDialog._id, 1);
triggerDialog(createdDialog._id);
$('a.users_form').removeClass('active');
}
});
}
|
javascript
|
{
"resource": ""
}
|
q53678
|
showDialogInfoPopup
|
train
|
function showDialogInfoPopup() {
if(Object.keys(currentDialog).length !== 0) {
$('#update_dialog').modal('show');
$('#update_dialog .progress').hide();
setupDialogInfoPopup(currentDialog.occupants_ids, currentDialog.name);
}
}
|
javascript
|
{
"resource": ""
}
|
q53679
|
parseAndroidPreferences
|
train
|
function parseAndroidPreferences(preferences, configData){
var type = 'preference';
_.each(preferences, function (preference) {
// Extract pre-defined preferences (deprecated)
var target,
prefData;
if(preference.attrib.name.match(/^android-manifest\//)){
// Extract manifest Xpath preferences
var parts = preference.attrib.name.split("/"),
destination = parts.pop();
parts.shift();
prefData = {
parent: parts.join("/") || "./",
type: type,
destination: destination,
data: preference
};
target = "AndroidManifest.xml";
}
if(prefData){
if(!configData[target]) {
configData[target] = [];
}
configData[target].push(prefData);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q53680
|
updateWp8Manifest
|
train
|
function updateWp8Manifest(targetFilePath, configItems) {
var tempManifest = fileUtils.parseElementtreeSync(targetFilePath),
root = tempManifest.getroot();
_.each(configItems, function (item) {
// if parent is not found on the root, child/grandchild nodes are searched
var parentEl = root.find(item.parent) || root.find('*/' + item.parent),
parentSelector,
data = item.data,
childSelector = item.destination,
childEl;
if(!parentEl) {
return;
}
_.each(data.attrib, function (prop, propName) {
childSelector += '[@'+propName+'="'+prop+'"]';
});
childEl = parentEl.find(childSelector);
// if child element doesnt exist, create new element
if(!childEl) {
childEl = new et.Element(item.destination);
parentEl.append(childEl);
}
// copy all config.xml data except for the generated _id property
_.each(data, function (prop, propName) {
if(propName !== '_id') {
childEl[propName] = prop;
}
});
});
fs.writeFileSync(targetFilePath, tempManifest.write({indent: 4}), 'utf-8');
}
|
javascript
|
{
"resource": ""
}
|
q53681
|
updateIosPbxProj
|
train
|
function updateIosPbxProj(xcodeProjectPath, configItems) {
var xcodeProject = xcode.project(xcodeProjectPath);
xcodeProject.parse(function(err){
if(err){
// shell is undefined if android platform has been removed and added with a new package id but ios stayed the same.
var msg = 'An error occurred during parsing of [' + xcodeProjectPath + ']: ' + JSON.stringify(err);
if(typeof shell !== "undefined" && shell !== null){
shell.echo(msg);
} else{
logger.error(msg + ' - Maybe you forgot to remove/add the ios platform?');
}
}else{
_.each(configItems, function (item) {
switch(item.type){
case "XCBuildConfiguration":
var buildConfig = xcodeProject.pbxXCBuildConfigurationSection();
var replaced = updateXCBuildConfiguration(item, buildConfig, "replace");
if(!replaced){
updateXCBuildConfiguration(item, buildConfig, "add");
}
break;
}
});
fs.writeFileSync(xcodeProjectPath, xcodeProject.writeSync(), 'utf-8');
}
});
}
|
javascript
|
{
"resource": ""
}
|
q53682
|
updateXCBuildConfiguration
|
train
|
function updateXCBuildConfiguration(item, buildConfig, mode){
var modified = false;
for(var blockName in buildConfig){
var block = buildConfig[blockName];
if(typeof(block) !== "object" || !(block["buildSettings"])) continue;
var literalMatch = !!block["buildSettings"][item.name],
quotedMatch = !!block["buildSettings"][quoteEscape(item.name)],
match = literalMatch || quotedMatch;
if((match || mode === "add") &&
(!item.buildType || item.buildType.toLowerCase() === block['name'].toLowerCase())){
var name;
if(match){
name = literalMatch ? item.name : quoteEscape(item.name);
}else{
// adding
name = (item.quote && (item.quote === "none" || item.quote === "value")) ? item.name : quoteEscape(item.name);
}
var value = (item.quote && (item.quote === "none" || item.quote === "key")) ? item.value : quoteEscape(item.value);
block["buildSettings"][name] = value;
modified = true;
logger.verbose(mode+" XCBuildConfiguration key={ "+name+" } to value={ "+value+" } for build type='"+block['name']+"' in block='"+blockName+"'");
}
}
return modified;
}
|
javascript
|
{
"resource": ""
}
|
q53683
|
train
|
function(className, params) {
var result = Utils.getUrl(config.urls.data, className + '/' + params.id + '/file');
result += '?field_name=' + params.field_name + '&token=' + this.service.getSession().token;
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q53684
|
train
|
function(params, callback) {
/**
* Callback for QB.content.createAndUpload(params, callback).
* @callback createAndUploadFileCallback
* @param {object} error - The error object
* @param {object} response - The file object (blob-object-access)
*/
var _this = this,
createParams= {},
file,
name,
type,
size,
fileId;
var clonedParams = JSON.parse(JSON.stringify(params));
clonedParams.file.data = "...";
file = params.file;
name = params.name || file.name;
type = params.type || file.type;
size = params.size || file.size;
createParams.name = name;
createParams.content_type = type;
if (params.public) {
createParams.public = params.public;
}
if (params.tag_list) {
createParams.tag_list = params.tag_list;
}
// Create a file object
this.create(createParams, function(err, createResult){
if (err) {
callback(err, null);
} else {
var uri = parseUri(createResult.blob_object_access.params),
uploadUrl = uri.protocol + "://" + uri.authority + uri.path,
uploadParams = {url: uploadUrl},
data = {};
fileId = createResult.id;
createResult.size = size;
Object.keys(uri.queryKey).forEach(function(val) {
data[val] = decodeURIComponent(uri.queryKey[val]);
});
data.file = file;
uploadParams.data = data;
// Upload the file to Amazon S3
_this.upload(uploadParams, function(err, result) {
if (err) {
callback(err, null);
} else {
// Mark file as uploaded
_this.markUploaded({
id: fileId,
size: size
}, function(err, result){
if (err) {
callback(err, null);
} else {
callback(null, createResult);
}
});
}
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53685
|
train
|
function (id, callback) {
/**
* Callback for QB.content.getInfo(id, callback)
* @callback getFileInfoByIdCallback
* @param {object} error - The error object
* @param {object} response - The file object (blob-object-access)
*/
this.service.ajax({url: Utils.getUrl(config.urls.blobs, id)}, function (err, res) {
if (err) {
callback (err, null);
} else {
callback (null, res);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53686
|
blockNavigation
|
train
|
function blockNavigation($scope, mainBlockUI, blockUIConfig) {
if (blockUIConfig.blockBrowserNavigation) {
function registerLocationChange() {
$scope.$on('$locationChangeStart', function (event) {
// console.log('$locationChangeStart', mainBlockUI.$_blockLocationChange + ' ' + mainBlockUI.state().blockCount);
if (mainBlockUI.$_blockLocationChange && mainBlockUI.state().blockCount > 0) {
event.preventDefault();
}
});
$scope.$on('$locationChangeSuccess', function () {
mainBlockUI.$_blockLocationChange = blockUIConfig.blockBrowserNavigation;
// console.log('$locationChangeSuccess', mainBlockUI.$_blockLocationChange + ' ' + mainBlockUI.state().blockCount);
});
}
if (moduleLoaded('ngRoute')) {
// After the initial content has been loaded we'll spy on any location
// changes and discard them when needed.
var fn = $scope.$on('$viewContentLoaded', function () {
// Unhook the view loaded and hook a function that will prevent
// location changes while the block is active.
fn();
registerLocationChange();
});
} else {
registerLocationChange();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q53687
|
unsubscribe
|
train
|
function unsubscribe(handler) {
for (var i = handlers.length - 1; i >= 0; --i) {
if (handlers[i] === handler) {
handlers.splice(i, 1);
}
}
if (handlers.length === 0) {
window.onerror = _oldOnerrorHandler;
_onErrorHandlerInstalled = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q53688
|
installGlobalHandler
|
train
|
function installGlobalHandler() {
if (_onErrorHandlerInstalled === true) {
return;
}
_oldOnerrorHandler = window.onerror;
window.onerror = traceKitWindowOnError;
_onErrorHandlerInstalled = true;
}
|
javascript
|
{
"resource": ""
}
|
q53689
|
processLastException
|
train
|
function processLastException() {
var _lastExceptionStack = lastExceptionStack,
_lastException = lastException;
lastExceptionStack = null;
lastException = null;
notifyHandlers(_lastExceptionStack, false, _lastException);
}
|
javascript
|
{
"resource": ""
}
|
q53690
|
loadSource
|
train
|
function loadSource(url) {
if (!TraceKit.remoteFetching) { //Only attempt request if remoteFetching is on.
return '';
}
try {
var getXHR = function() {
try {
return new window.XMLHttpRequest();
} catch (e) {
// explicitly bubble up the exception if not found
return new window.ActiveXObject('Microsoft.XMLHTTP');
}
};
var request = getXHR();
request.open('GET', url, false);
request.send('');
return request.responseText;
} catch (e) {
return '';
}
}
|
javascript
|
{
"resource": ""
}
|
q53691
|
findSourceInUrls
|
train
|
function findSourceInUrls(re, urls) {
var source, m;
for (var i = 0, j = urls.length; i < j; ++i) {
if ((source = getSource(urls[i])).length) {
source = source.join('\n');
if ((m = re.exec(source))) {
return {
'url': urls[i],
'line': source.substring(0, m.index).split('\n').length,
'column': m.index - source.lastIndexOf('\n', m.index) - 1
};
}
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q53692
|
findSourceByFunctionBody
|
train
|
function findSourceByFunctionBody(func) {
if (_isUndefined(window && window.document)) {
return;
}
var urls = [window.location.href],
scripts = window.document.getElementsByTagName('script'),
body,
code = '' + func,
codeRE = /^function(?:\s+([\w$]+))?\s*\(([\w\s,]*)\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/,
eventRE = /^function on([\w$]+)\s*\(event\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/,
re,
parts,
result;
for (var i = 0; i < scripts.length; ++i) {
var script = scripts[i];
if (script.src) {
urls.push(script.src);
}
}
if (!(parts = codeRE.exec(code))) {
re = new RegExp(escapeRegExp(code).replace(/\s+/g, '\\s+'));
}
// not sure if this is really necessary, but I don’t have a test
// corpus large enough to confirm that and it was in the original.
else {
var name = parts[1] ? '\\s+' + parts[1] : '',
args = parts[2].split(',').join('\\s*,\\s*');
body = escapeRegExp(parts[3]).replace(/;$/, ';?'); // semicolon is inserted if the function ends with a comment.replace(/\s+/g, '\\s+');
re = new RegExp('function' + name + '\\s*\\(\\s*' + args + '\\s*\\)\\s*{\\s*' + body + '\\s*}');
}
// look for a normal function definition
if ((result = findSourceInUrls(re, urls))) {
return result;
}
// look for an old-school event handler function
if ((parts = eventRE.exec(code))) {
var event = parts[1];
body = escapeCodeAsRegExpForMatchingInsideHTML(parts[2]);
// look for a function defined in HTML as an onXXX handler
re = new RegExp('on' + event + '=[\\\'"]\\s*' + body + '\\s*[\\\'"]', 'i');
if ((result = findSourceInUrls(re, urls[0]))) {
return result;
}
// look for ???
re = new RegExp(body);
if ((result = findSourceInUrls(re, urls))) {
return result;
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q53693
|
computeStackTraceFromStacktraceProp
|
train
|
function computeStackTraceFromStacktraceProp(ex) {
// Access and store the stacktrace property before doing ANYTHING
// else to it because Opera is not very good at providing it
// reliably in other circumstances.
var stacktrace = ex.stacktrace;
if (!stacktrace) {
return;
}
var opera10Regex = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,
opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^\)]+))\((.*)\))? in (.*):\s*$/i,
lines = stacktrace.split('\n'),
stack = [],
parts;
for (var line = 0; line < lines.length; line += 2) {
var element = null;
if ((parts = opera10Regex.exec(lines[line]))) {
element = {
'url': parts[2],
'line': +parts[1],
'column': null,
'func': parts[3],
'args':[]
};
} else if ((parts = opera11Regex.exec(lines[line]))) {
element = {
'url': parts[6],
'line': +parts[1],
'column': +parts[2],
'func': parts[3] || parts[4],
'args': parts[5] ? parts[5].split(',') : []
};
}
if (element) {
if (!element.func && element.line) {
element.func = guessFunctionName(element.url, element.line);
}
if (element.line) {
try {
element.context = gatherContext(element.url, element.line);
} catch (exc) {}
}
if (!element.context) {
element.context = [lines[line + 1]];
}
stack.push(element);
}
}
if (!stack.length) {
return null;
}
return {
'mode': 'stacktrace',
'name': ex.name,
'message': ex.message,
'stack': stack
};
}
|
javascript
|
{
"resource": ""
}
|
q53694
|
callHandler
|
train
|
function callHandler(callback, context, args) {
switch (args.length) {
case 0: return callback.call(context);
case 1: return callback.call(context, args[0]);
case 2: return callback.call(context, args[0], args[1]);
case 3: return callback.call(context, args[0], args[1], args[2]);
default: return callback.apply(context, args);
}
}
|
javascript
|
{
"resource": ""
}
|
q53695
|
removeHandler
|
train
|
function removeHandler(store, name, callback, context) {
var event = store[name];
if (
(!callback || (callback === event.callback || callback === event.callback._callback)) &&
(!context || (context === event.context))
) {
delete store[name];
return true;
}
}
|
javascript
|
{
"resource": ""
}
|
q53696
|
_partial
|
train
|
function _partial(channelName) {
return _logs[channelName] || (_logs[channelName] = Radio.log.bind(Radio, channelName));
}
|
javascript
|
{
"resource": ""
}
|
q53697
|
train
|
function(channelName, eventName) {
if (typeof console === 'undefined') { return; }
var args = _.toArray(arguments).slice(2);
console.log('[' + channelName + '] "' + eventName + '"', args);
}
|
javascript
|
{
"resource": ""
}
|
|
q53698
|
train
|
function(channelName) {
var channel = Radio.channel(channelName);
channel._tunedIn = true;
channel.on('all', _partial(channelName));
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q53699
|
train
|
function(channelName) {
var channel = Radio.channel(channelName);
channel._tunedIn = false;
channel.off('all', _partial(channelName));
delete _logs[channelName];
return this;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.