_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q51700
|
train
|
function(resp) {
if (resp.name) {
resp.details = "Speaks: " + resp.locale + ", Gender: " + resp.gender;
}
page.emit('profile', resp);
}
|
javascript
|
{
"resource": ""
}
|
|
q51701
|
train
|
function(payload, callback) {
var alice, bob, aliceChannel, bobChannel,
aliceCandidates = [],
aliceOffer;
alice = peercon();
bob = peercon();
bob.on('ondatachannel', function (msg) {
bobChannel = datachan(msg.channel);
bobChannel.setBinaryType('arraybuffer', function () {});
bobChannel.on('onmessage', function (msg) {
alice.close();
bob.close();
callback(msg);
});
});
bob.on('onicecandidate', function (msg) {
msg.candidate && alice.addIceCandidate(msg.candidate);
});
alice.on('onicecandidate', function (msg) {
// firefox needs ice candidates all sent before asking for an answer.
if (!msg.candidate) {
bob.setRemoteDescription(aliceOffer).then(function () {
var last;
while (aliceCandidates.length) {
last = bob.addIceCandidate(aliceCandidates.shift());
}
return last;
}).then(function () {
return bob.createAnswer();
}).then(function (answer) {
return bob.setLocalDescription(answer).then(function () {return answer; });
}).then(function (answer) {
return alice.setRemoteDescription(answer);
}, function (err) {
console.error('RTC failed: ', err);
});
} else {
aliceCandidates.push(msg.candidate);
}
});
alice.createDataChannel('channel').then(function (id) {
aliceChannel = datachan(id);
aliceChannel.on('onopen', function () {
if (payload instanceof ArrayBuffer) {
aliceChannel.sendBuffer(payload);
} else {
aliceChannel.send(payload);
}
});
aliceChannel.setBinaryType('arraybuffer').then(function () {
return alice.createOffer();
}).then(function (offer) {
alice.setLocalDescription(offer);
aliceOffer = offer;
});
}, function (err) {
console.error('RTC failed: ', err);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51702
|
makeEventTarget
|
train
|
function makeEventTarget(target) {
var listeners = {};
target.on = function(event, func) {
if (listeners[event]) {
listeners[event].push(func);
} else {
listeners[event] = [func];
}
};
target.fireEvent = function(event, data) {
expect(target.on).toHaveBeenCalledWith(event, jasmine.any(Function));
listeners[event].forEach(function(listener) {
listener(data);
});
};
target.removeListeners = function() {
listeners = {};
};
spyOn(target, "on").and.callThrough();
}
|
javascript
|
{
"resource": ""
}
|
q51703
|
train
|
function() {
var iface = testUtil.mockIface([
["setup", undefined],
["send", undefined],
["openDataChannel", undefined],
["close", undefined],
["getBufferedAmount", 0]
]);
peerconnection = iface();
makeEventTarget(peerconnection);
return peerconnection;
}
|
javascript
|
{
"resource": ""
}
|
|
q51704
|
train
|
function (interfaceCls, debug) {
this.id = Consumer.nextId();
this.interfaceCls = interfaceCls;
this.debug = debug;
util.handleEvents(this);
this.ifaces = {};
this.closeHandlers = {};
this.errorHandlers = {};
this.emits = {};
}
|
javascript
|
{
"resource": ""
}
|
|
q51705
|
Consign
|
train
|
function Consign(options) {
options = options || {};
this._options = {
cwd: process.cwd(),
locale: 'en-us',
logger: console,
verbose: true,
extensions: [],
loggingType: 'info'
};
this._files = [];
this._object = {};
this._extensions = this._options.extensions.concat(['.js', '.json', '.node']);
this._lastOperation = 'include';
if (options.extensions) {
this._extensions.concat(options.extensions);
}
for (var o in options) {
this._options[o] = options[o];
}
this._ = require(path.join(__dirname, '..', 'locale', this._options.locale));
this._log([pack.name, 'v' + pack.version, this._['Initialized in'], this._options.cwd]);
return this;
}
|
javascript
|
{
"resource": ""
}
|
q51706
|
extend
|
train
|
function extend(dest, source, callback) {
var index = -1,
props = Object.keys(source),
length = props.length,
ask = isFunction(callback);
while (++index < length) {
var key = props[index];
dest[key] = ask ?
callback(dest[key], source[key], key, dest, source) : source[key];
}
return dest;
}
|
javascript
|
{
"resource": ""
}
|
q51707
|
fromAppleTime
|
train
|
function fromAppleTime(ts) {
if (ts == 0) {
return null
}
// unpackTime returns 0 if the timestamp wasn't packed
// TODO: see `packTimeConditionally`'s comment
if (unpackTime(ts) != 0) {
ts = unpackTime(ts)
}
return new Date((ts + DATE_OFFSET) * 1000)
}
|
javascript
|
{
"resource": ""
}
|
q51708
|
handleForName
|
train
|
function handleForName(name) {
assert(typeof name == 'string', 'name must be a string')
return osa(name => {
const Messages = Application('Messages')
return Messages.buddies.whose({ name: name })[0].handle()
})(name)
}
|
javascript
|
{
"resource": ""
}
|
q51709
|
send
|
train
|
function send(handle, message) {
assert(typeof handle == 'string', 'handle must be a string')
assert(typeof message == 'string', 'message must be a string')
return osa((handle, message) => {
const Messages = Application('Messages')
let target
try {
target = Messages.buddies.whose({ handle: handle })[0]
} catch (e) {}
try {
target = Messages.textChats.byId('iMessage;+;' + handle)()
} catch (e) {}
try {
Messages.send(message, { to: target })
} catch (e) {
throw new Error(`no thread with handle '${handle}'`)
}
})(handle, message)
}
|
javascript
|
{
"resource": ""
}
|
q51710
|
train
|
function (table) {
table
.onBodyAdd(this.setWidth.bind(this))
.onColumnAdded(this.onColumnAdded.bind(this))
.onColumnPropertyChanged(this.onColumnPropertyChanged.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q51711
|
train
|
function (table) {
if (!table.pdf.page) {
return;
}
if (this.calculatedWidth === null) {
var self = this,
content_width = this.maxWidth,
width = lodash.sumBy(table.getColumns(), function (column) {
return column.id !== self.column ? column.width : 0;
});
if (!content_width) {
content_width = table.pdf.page.width
- table.pdf.page.margins.left
- table.pdf.page.margins.right;
}
this.calculatedWidth = content_width - width;
if (this.calculatedWidth < 0) {
this.calculatedWidth = 0;
}
}
table.setColumnWidth(this.column, this.calculatedWidth, true);
}
|
javascript
|
{
"resource": ""
}
|
|
q51712
|
createNodes
|
train
|
function createNodes(entityRanges, decoratorRanges = [], textArray, block) {
let lastIndex = 0;
const mergedRanges = [...entityRanges, ...decoratorRanges].sort((a, b) => a.offset - b.offset);
const nodes = [];
// if thers no entities will return just a single item
if (mergedRanges.length < 1) {
nodes.push(new ContentNode({ block, start: 0, end: textArray.length }));
return nodes;
}
mergedRanges.forEach((range) => {
// create an empty node for content between previous and this entity
if (range.offset > lastIndex) {
nodes.push(new ContentNode({ block, start: lastIndex, end: range.offset }));
}
// push the node for the entity
nodes.push(new ContentNode({
block,
entity: range.key,
decorator: range.component,
decoratorProps: range.decoratorProps,
decoratedText: range.component
? getString(textArray, range.offset, range.offset + range.length)
: undefined,
start: range.offset,
end: range.offset + range.length,
contentState: range.contentState,
}));
lastIndex = range.offset + range.length;
});
// finaly add a node for the remaining text if any
if (lastIndex < textArray.length) {
nodes.push(new ContentNode({
block,
start: lastIndex,
end: textArray.length,
}));
}
return nodes;
}
|
javascript
|
{
"resource": ""
}
|
q51713
|
getRelevantIndexes
|
train
|
function getRelevantIndexes(text, inlineRanges, entityRanges = [], decoratorRanges = []) {
let relevantIndexes = [];
// set indexes to corresponding keys to ensure uniquenes
relevantIndexes = addIndexes(relevantIndexes, inlineRanges);
relevantIndexes = addIndexes(relevantIndexes, entityRanges);
relevantIndexes = addIndexes(relevantIndexes, decoratorRanges);
// add text start and end to relevant indexes
relevantIndexes.push(0);
relevantIndexes.push(text.length);
const uniqueRelevantIndexes = relevantIndexes.filter(
(value, index, self) => self.indexOf(value) === index
);
// and sort it
return uniqueRelevantIndexes.sort((aa, bb) => (aa - bb));
}
|
javascript
|
{
"resource": ""
}
|
q51714
|
train
|
function ( type, css, obj, dom, id ) {
return Tools.dom( type, css, obj, dom, id );
}
|
javascript
|
{
"resource": ""
}
|
|
q51715
|
train
|
function ( n ) {
var i = this.uis.indexOf( n );
if ( i !== -1 ) {
this.inner.removeChild( this.uis[i].c[0] );
this.uis.splice( i, 1 );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51716
|
train
|
function( canvas, content, w, h ){
var ctx = canvas.getContext("2d");
var dcopy = null;
if( typeof content === 'string' ){
dcopy = Tools.dom( 'iframe', 'position:abolute; left:0; top:0; width:'+w+'px; height:'+h+'px;' );
dcopy.src = content;
}else{
dcopy = content.cloneNode(true);
dcopy.style.left = 0;
}
var svg = Tools.dom( 'foreignObject', 'position:abolute; left:0; top:0;', { width:w, height:h });
svg.childNodes[0].appendChild( dcopy );
svg.setAttribute("version", "1.1");
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg' );
svg.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
svg.setAttribute('width', w );
svg.setAttribute('height', h );
svg.childNodes[0].setAttribute('width', '100%' );
svg.childNodes[0].setAttribute('height', '100%' );
//console.log(svg)
var img = new Image();
var data = 'data:image/svg+xml;base64,'+ window.btoa((new XMLSerializer).serializeToString(svg));
dcopy = null;
img.onload = function() {
ctx.clearRect( 0, 0, w, h );
ctx.drawImage( img, 0, 0, w, h, 0, 0, w, h );
};
img.src = data;
/*setTimeout(function() {
ctx.clearRect( 0, 0, w, h );
ctx.drawImage( img, 0, 0, w, h, 0, 0, w, h );
}, 0);*/
// blob
/*var svgBlob = new Blob([(new XMLSerializer).serializeToString(svg)], {type: "image/svg+xml;charset=utf-8"});
var url = URL.createObjectURL(svgBlob);
img.onload = function() {
ctx.clearRect( 0, 0, w, h );
ctx.drawImage( img, 0, 0, w, h, 0, 0, w, h );
URL.revokeObjectURL(url);
};
img.src = url;*/
}
|
javascript
|
{
"resource": ""
}
|
|
q51717
|
resolveDate
|
train
|
function resolveDate (base_url, input, callback) {
var date = input;
// If provided a date string
if ((typeof input == "string" || typeof input == "number") && input !== "latest") {
date = new Date(input);
}
// If provided a date object
if (moment.isDate(date)) { return callback(null, date); }
// If provided "latest"
else if (input === "latest") {
var latest = base_url + '/latest.json';
request({
method: 'GET',
uri: latest,
timeout: 30000
}, function (err, res) {
if (err) return callback(err);
try { date = new Date(JSON.parse(res.body).date); }
catch (e) { date = new Date(); }
return callback(null, date);
});
}
// Invalid string provided, return new Date
else { return callback(null, new Date()); }
}
|
javascript
|
{
"resource": ""
}
|
q51718
|
recordProxy
|
train
|
function recordProxy( old, name ) {
return function() {
var tracked;
try {
tracked = JSON.parse(window.localStorage.getItem( shoestring.trackedMethodsKey ) || "{}");
} catch (e) {
if( e instanceof SyntaxError) {
tracked = {};
}
}
tracked[ name ] = true;
window.localStorage.setItem( shoestring.trackedMethodsKey, JSON.stringify(tracked) );
return old.apply(this, arguments);
};
}
|
javascript
|
{
"resource": ""
}
|
q51719
|
train
|
function( url, els, isHijax ) {
$.get( url, function( data, status, xhr ) {
els.trigger( "ajaxIncludeResponse", [ data, xhr ] );
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51720
|
queueOrRequest
|
train
|
function queueOrRequest( el ){
var url = el.data( "url" );
if( o.proxy && $.inArray( url, urllist ) === -1 ){
urllist.push( url );
elQueue = elQueue.add( el );
}
else{
AI.makeReq( url, el );
}
}
|
javascript
|
{
"resource": ""
}
|
q51721
|
runQueue
|
train
|
function runQueue(){
if( urllist.length ){
AI.makeReq( o.proxy + urllist.join( "," ), elQueue );
elQueue = $();
urllist = [];
}
}
|
javascript
|
{
"resource": ""
}
|
q51722
|
bindForLater
|
train
|
function bindForLater( el, media ){
var mm = win.matchMedia( media );
function cb(){
queueOrRequest( el );
runQueue();
mm.removeListener( cb );
}
if( mm.addListener ){
mm.addListener( cb );
}
}
|
javascript
|
{
"resource": ""
}
|
q51723
|
splitArgsIntoOptionsAndCallback
|
train
|
function splitArgsIntoOptionsAndCallback (args) {
let params;
let options;
let cb;
if (args.length > 1) {
const possibleCb = args[args.length - 1];
if ('function' === typeof possibleCb) {
cb = possibleCb;
options = args.length === 3 ? args[1] : undefined;
} else {
options = args[1];
}
params = args[0];
} else if ('object' === typeof args[0]) {
params = args[0];
} else if ('function' === typeof args[0]) {
cb = args[0];
}
return { params, options, cb };
}
|
javascript
|
{
"resource": ""
}
|
q51724
|
createUrlFromEndpointAndOptions
|
train
|
function createUrlFromEndpointAndOptions (endpoint, options) {
const query = qs.stringify(options);
const baseURL = `${host}${endpoint}`;
return query ? `${baseURL}?${query}` : baseURL;
}
|
javascript
|
{
"resource": ""
}
|
q51725
|
getDataFromWeb
|
train
|
function getDataFromWeb(url, options, apiKey, cb) {
let useCallback = 'function' === typeof cb;
const reqOptions = { headers: {} };
if (apiKey) {
reqOptions.headers['X-Api-Key'] = apiKey;
}
if (options && options.noCache === true) {
reqOptions.headers['X-No-Cache'] = 'true';
}
return fetch(url, reqOptions).then(res => Promise.all([res, res.json()])).then(([res, body]) => {
if (body.status === 'error') throw new NewsAPIError(body);
// 'showHeaders' option can be used for clients to debug response headers
// response will be in form of { headers, body }
if (options && options.showHeaders) {
if (useCallback) return cb(null, { headers: res.headers, body });
return { headers: res.headers, body };
}
if (useCallback) return cb(null, body);
return body;
}).catch(err => {
if (useCallback) return cb(err);
throw err;
});
}
|
javascript
|
{
"resource": ""
}
|
q51726
|
visitFragment
|
train
|
function visitFragment(fragment, fragments, fragmentsHash) {
if (fragment.marked) {
throw Error('Fragments cannot contain a cycle');
}
if (!fragment.visited) {
fragment.marked = true;
// Visit every spread in this fragment definition
visit(fragment, {
FragmentSpread(node) {
// Visit the corresponding fragment definition
visitFragment(fragmentsHash[node.name.value], fragments, fragmentsHash);
}
});
fragment.visited = true;
fragment.marked = false;
fragments.push(fragment);
}
}
|
javascript
|
{
"resource": ""
}
|
q51727
|
customCheck
|
train
|
function customCheck(req, mydevice) {
var useragent = req.headers['user-agent'];
if (!useragent || useragent === '') {
if (req.headers['cloudfront-is-mobile-viewer'] === 'true') return 'phone';
if (req.headers['cloudfront-is-tablet-viewer'] === 'true') return 'tablet';
if (req.headers['cloudfront-is-desktop-viewer'] === 'true') return 'desktop';
// No user agent.
return mydevice.parser.options.emptyUserAgentDeviceType;
}
return mydevice.type;
}
|
javascript
|
{
"resource": ""
}
|
q51728
|
writeText
|
train
|
function writeText(wasmModule, format, output, callback) {
if (format === "linear" || format === "stack") {
if (!assemblyscript.util.wabt) {
process.stderr.write("\nwabt.js not found\n");
return callback(EFAILURE);
}
var binary = wasmModule.ascCurrentBinary || (wasmModule.ascCurrentBinary = wasmModule.emitBinary()); // reuse
output.write(assemblyscript.util.wasmToWast(binary, { readDebugNames: true }), "utf8", end);
} else
output.write(wasmModule.emitText(), "utf8", end);
function end(err) {
if (err || output === process.stdout) return callback(err);
output.end(callback);
}
}
|
javascript
|
{
"resource": ""
}
|
q51729
|
writeBinary
|
train
|
function writeBinary(wasmModule, output, callback) {
output.write(Buffer.from(wasmModule.emitBinary()), end);
function end(err) {
if (err || output === process.stdout) return callback(err);
output.end(callback);
}
}
|
javascript
|
{
"resource": ""
}
|
q51730
|
writeAsmjs
|
train
|
function writeAsmjs(wasmModule, output, callback) {
output.write(Buffer.from(wasmModule.emitAsmjs()), end);
function end(err) {
if (err || output === process.stdout) return callback(err);
output.end(callback);
}
}
|
javascript
|
{
"resource": ""
}
|
q51731
|
createFromData
|
train
|
function createFromData(data, container) {
if (data === undefined) {
return Promise.resolve([])
}
if (!(isObject(data) || Array.isArray(data))) {
return Promise.reject(new Error('Invalid animation data'))
}
return Promise.resolve(create(data, container))
}
|
javascript
|
{
"resource": ""
}
|
q51732
|
loadFromPath
|
train
|
function loadFromPath(path, container) {
if (path && typeof path === 'string' && path.length > 0) {
return load(path, container)
}
return Promise.resolve([])
}
|
javascript
|
{
"resource": ""
}
|
q51733
|
groupsFactory
|
train
|
function groupsFactory() {
let list = []
const getGroupsByRoot = function(root) {
for (let i = 0; i < list.length; i++) {
let groups = list[i]
if (groups.rootEl === root) {
return groups
}
}
return null
}
return {
add: function(root, group) {
let groups = getGroupsByRoot(root)
if (!groups) {
groups = new Groups(root, [])
list.push(groups)
}
if (group) {
group._list = groups
group.resolve()
groups.add(group)
}
},
groups: function() {
return list.length === 1 ? list[0] : list
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51734
|
isUsed
|
train
|
function isUsed (name) {
if (module.isUsed(name)) {
return true
}
if (dupes.length > 0) {
return dupes.some((dupe) => {
const m = analyzer.modules.get(dupe.file)
return m && m.isUsed(name)
})
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q51735
|
train
|
function(options) {
var opts = options || {};
if (opts.cors !== false) {
this.cors = access(merge({
origins: [],
methods: ['GET', 'HEAD', 'OPTIONS'],
headers: ['Last-Event-ID']
}, opts.cors || {}));
}
var jsonEncode = (
typeof opts.jsonEncode === 'undefined' ?
false :
Boolean(opts.jsonEncode)
);
this.jsonEncode = jsonEncode;
this.historySize = opts.historySize || 500;
this.retryTimeout = opts.retryTimeout || null;
this.pingInterval = (opts.pingInterval | 0) || 20000;
// Populate history with the entries specified
this.history = ((opts.history || [])
.filter(hasId)
.slice(0 - this.historySize)
.reverse()
.map(function(msg) {
return {
id: msg.id,
msg: parseMessage(msg, jsonEncode)
};
})
);
this.connections = [];
this.connectionCount = 0;
// Start a timer that will ping all connected clients at a given interval
this.timer = setInterval(this.ping.bind(this), this.pingInterval);
}
|
javascript
|
{
"resource": ""
}
|
|
q51736
|
initializeConnection
|
train
|
function initializeConnection(opts) {
opts.request.socket.setTimeout(0);
opts.request.socket.setNoDelay(true);
opts.request.socket.setKeepAlive(true);
opts.response.writeHead(200, {
'Content-Type': 'text/event-stream;charset=UTF-8',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
opts.response.write(':ok\n\n');
// Only set retry if it has a sane value
var retry = opts.retry | 0;
if (retry) {
opts.response.write('retry: ' + retry + '\n');
}
// Should we delivar a "preamble" to the client? Required in some cases by Internet Explorer,
// see https://github.com/amvtek/EventSource/wiki/UserGuide for more information
if (opts.preamble) {
opts.response.write(':' + preambleData);
}
flush(opts.response);
}
|
javascript
|
{
"resource": ""
}
|
q51737
|
broadcast
|
train
|
function broadcast(connections, packet) {
var i = connections.length;
while (i--) {
connections[i].write(packet);
flush(connections[i]);
}
}
|
javascript
|
{
"resource": ""
}
|
q51738
|
parseTextData
|
train
|
function parseTextData(text) {
var data = String(text).replace(/(\r\n|\r|\n)/g, '\n');
var lines = data.split(/\n/), line;
var output = '';
for (var i = 0, l = lines.length; i < l; ++i) {
line = lines[i];
output += 'data: ' + line;
output += (i + 1) === l ? '\n\n' : '\n';
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
q51739
|
drawChart
|
train
|
function drawChart(canvas, data) {
var ctx = canvas.getContext('2d'),
color = 'rgba(0, 0, 0, 0.75)',
height = canvas.height - 2,
width = canvas.width,
total = data.length,
max = Math.max.apply(Math, data),
xstep = 1,
ystep = max / height,
x = 0,
y = height - data[0] / ystep;
ctx.clearRect(0, 0, width, height);
ctx.beginPath();
ctx.strokeStyle = color;
ctx.moveTo(x, y);
for (var i = 1; i < total; i++) {
x += xstep;
y = height - data[i] / ystep + 1;
ctx.moveTo(x, height);
ctx.lineTo(x, y);
}
ctx.stroke();
}
|
javascript
|
{
"resource": ""
}
|
q51740
|
triggerSlideEnd
|
train
|
function triggerSlideEnd(){
if(!slided){
if(options.transition == "fade"){
$(options.slidesContainer).find(options.slides).each(function(index){
if($(this).data('index') == obj.currentSlide){
$(this).show();
}
else{
$(this).hide();
}
});
}
// Reset to the first slide when neverEnding has been enabled and the 'faked' last slide is active
if(options.transition == "slide" && options.neverEnding){
// Check if it's the 'last' slide
if(obj.currentSlide == obj.totalSlides - 1 && prevSlide === 0){
if ($.support.transition && jQuery().transition)
$(movecontainer).stop().transition({x: -(obj.totalSlides) * 100 + "%"}, 1, 'linear');
else
$(movecontainer).css({left: -(obj.totalSlides) * 100 + "%"});
}
// Check if it's the 'first' slide
if(obj.currentSlide === 0 && prevSlide == obj.totalSlides - 1){
if ($.support.transition && jQuery().transition)
$(movecontainer).stop().transition({x: "-100%"}, 1, 'linear');
else
$(movecontainer).css({left: "-100%"});
}
}
// Trigger event
var afterSlidingEvent = jQuery.Event("afterSliding", {
prevSlide: prevSlide,
newSlide: obj.currentSlide
});
$(element).trigger(afterSlidingEvent);
slided = true;
}
}
|
javascript
|
{
"resource": ""
}
|
q51741
|
buildPathsObject
|
train
|
async function buildPathsObject(files) {
return Promise.all(
files.map(async filepath => {
const name = path.basename(filepath, '.svg');
const svg = fs.readFileSync(filepath, 'utf-8');
const pathStrings = await svgo.optimize(svg, { path: filepath })
.then(({ data }) => data.match(/ d="[^"]+"/g) || [])
.then(paths => paths.map(s => s.slice(3)));
return `"${name}": [${pathStrings.join(',\n')}]`;
}),
);
}
|
javascript
|
{
"resource": ""
}
|
q51742
|
mk_NodeSet
|
train
|
function mk_NodeSet(k_graph, a_terms, s_term_types) {
// prep to reduce nodes to a set
let h_nodes = {};
// nodes are all NamedNodes
if('NamedNode' === s_term_types) {
for(let i_term=0; i_term<a_terms.length; i_term++) {
let h_term = a_terms[i_term];
h_nodes[h_term.value] = h_term;
}
}
// nodes are all BlankNodes
else if('BlankNodes' === s_term_types) {
for(let i_term=0; i_term<a_terms.length; i_term++) {
let h_term = a_terms[i_term];
h_nodes['_:'+h_term.value] = h_term;
}
}
// nodes are mixed
else {
for(let i_term=0; i_term<a_terms.length; i_term++) {
let h_term = a_terms[i_term];
h_nodes[h_term.isBlankNode? '_:'+h_term.value: h_term.value] = h_term;
}
}
// reduce nodes to a set
let as_nodes = [];
for(let s_node_id in h_nodes) {
let k_node = k_graph.nodes[s_node_id]
|| k_graph.leafs[s_node_id]
|| (k_graph.leafs[s_node_id] = new Node(k_graph, [], h_nodes[s_node_id]));
// only add subject nodes that exist to the set
if(k_node) as_nodes.push(k_node);
}
// make instance
let h_methods = Object.assign(Object.create(NodeSet_prototype), {
graph: k_graph,
nodes: as_nodes,
areNodes: true,
});
// construct 'that'
let f_bound = NodeSet_operator.bind(h_methods);
// save to list so we can reuse it
a_terms.set = f_bound;
// make & return operator
Object.setPrototypeOf(f_bound, NodeSet_prototype);
return Object.assign(f_bound, h_methods);
}
|
javascript
|
{
"resource": ""
}
|
q51743
|
mk_LiteralBunch
|
train
|
function mk_LiteralBunch(k_graph, a_terms) {
// append local methods to hash
let h_methods = Object.assign(Object.create(LiteralBunch_prototype), {
graph: k_graph,
terms: a_terms,
// for returning a different sample each time
sample_counter: 0,
});
// construct 'that'
let f_bound = LiteralBunch_operator.bind(h_methods);
// make & return operator
Object.setPrototypeOf(f_bound, LiteralBunch_prototype);
return Object.assign(f_bound, h_methods);
}
|
javascript
|
{
"resource": ""
}
|
q51744
|
LiteralBunch_operator
|
train
|
function LiteralBunch_operator(z_literal_filter) {
// user wants to filter literal by language or datatype
if('string' === typeof z_literal_filter) {
// by language tag
if('@' === z_literal_filter[0]) {
// ref language tag
let s_language = z_literal_filter.slice(1).toLowerCase();
// apply filter
this.terms = this.terms.filter((h_term) => {
return s_language === h_term.language;
});
}
// by datatype
else {
// resolve datatype iri
let p_datatype = this.graph.resolve(z_literal_filter);
// apply filter
this.terms = this.terms.filter((h_term) => {
return p_datatype === h_term.datatype;
});
}
}
// user wants to filter literal by a function
else if('function' === typeof z_literal_filter) {
// apply filter
this.terms = this.terms.filter(z_literal_filter);
}
// results / no filtering
return this;
}
|
javascript
|
{
"resource": ""
}
|
q51745
|
asBitmap
|
train
|
function asBitmap(v, throwException) {
if (throwException === void 0) { throwException = true; }
var result = BitmapFactory.asBitmapObject(v);
if (throwException && (false === result)) {
throw "No valid value for a bitmap!";
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q51746
|
create
|
train
|
function create(width, height, opts) {
if (TypeUtils.isNullOrUndefined(height)) {
height = width;
}
if (arguments.length < 3) {
opts = getDefaultOptions();
}
if (TypeUtils.isNullOrUndefined(opts)) {
opts = {};
}
return BitmapFactory.createBitmap(width, height, opts);
}
|
javascript
|
{
"resource": ""
}
|
q51747
|
train
|
function (modes) {
var that = this;
return modes.sort(function (a, b) {
var a_idx, b_idx, i;
var user_prefixes = that.get('user_prefixes');
for (i = 0; i < user_prefixes.length; i++) {
if (user_prefixes[i].mode === a) {
a_idx = i;
}
}
for (i = 0; i < user_prefixes.length; i++) {
if (user_prefixes[i].mode === b) {
b_idx = i;
}
}
if (a_idx < b_idx) {
return -1;
} else if (a_idx > b_idx) {
return 1;
} else {
return 0;
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51748
|
train
|
function (modes) {
var prefix = '';
var user_prefixes = this.get('user_prefixes');
if (typeof modes[0] !== 'undefined') {
prefix = _.detect(user_prefixes, function (prefix) {
return prefix.mode === modes[0];
});
prefix = (prefix) ? prefix.symbol : '';
}
return prefix;
}
|
javascript
|
{
"resource": ""
}
|
|
q51749
|
train
|
function (nick) {
var tmp = nick, i, j, k, nick_char;
var user_prefixes = this.get('user_prefixes');
i = 0;
nick_character_loop:
for (j = 0; j < nick.length; j++) {
nick_char = nick.charAt(j);
for (k = 0; k < user_prefixes.length; k++) {
if (nick_char === user_prefixes[k].symbol) {
i++;
continue nick_character_loop;
}
}
break;
}
return tmp.substr(i);
}
|
javascript
|
{
"resource": ""
}
|
|
q51750
|
train
|
function () {
var user_prefixes = this.get('user_prefixes'),
modes = this.get('modes'),
o, max_mode;
if (modes.length > 0) {
o = _.indexOf(user_prefixes, _.find(user_prefixes, function (prefix) {
return prefix.mode === 'o';
}));
max_mode = _.indexOf(user_prefixes, _.find(user_prefixes, function (prefix) {
return prefix.mode === modes[0];
}));
if ((max_mode === -1) || (max_mode > o)) {
this.set({"is_op": false}, {silent: true});
} else {
this.set({"is_op": true}, {silent: true});
}
} else {
this.set({"is_op": false}, {silent: true});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51751
|
initialiseSocket
|
train
|
function initialiseSocket(socket, callback) {
var request = socket.request,
address = request.meta.remote_address,
revdns;
// Key/val data stored to the socket to be read later on
// May also be synced to a redis DB to lookup clients
socket.meta = socket.request.meta;
// If a forwarded-for header is found, switch the source address
if (request.headers[global.config.http_proxy_ip_header || 'x-forwarded-for']) {
// Check we're connecting from a whitelisted proxy
if (!global.config.http_proxies || !rangeCheck(address, global.config.http_proxies)) {
winston.info('Unlisted proxy: %s', address);
callback(null, false);
return;
}
// We're sent from a whitelisted proxy, replace the hosts
address = request.headers[global.config.http_proxy_ip_header || 'x-forwarded-for'];
// Multiple reverse proxies will have a comma delimited list of IPs. We only need the first
address = address.split(',')[0].trim();
// Some reverse proxies (IIS) may include the port, so lets remove that (if ipv4)
if (address.indexOf('.') > -1) {
address = (address || '').split(':')[0];
}
}
socket.meta.real_address = address;
// If enabled, don't go over the connection limit
if (global.config.max_client_conns && global.config.max_client_conns > 0) {
if (global.clients.numOnAddress(address) + 1 > global.config.max_client_conns) {
return callback(null, false);
}
}
try {
dns.reverse(address, function (err, domains) {
if (!err && domains.length > 0) {
revdns = _.first(domains);
}
if (!revdns) {
// No reverse DNS found, use the IP
socket.meta.revdns = address;
callback(null, true);
} else {
// Make sure the reverse DNS matches the A record to use the hostname..
dns.lookup(revdns, function (err, ip_address, family) {
if (!err && ip_address == address) {
// A record matches PTR, perfectly valid hostname
socket.meta.revdns = revdns;
} else {
// A record does not match the PTR, invalid hostname
socket.meta.revdns = address;
}
// We have all the info we need, proceed with the connection
callback(null, true);
});
}
});
} catch (err) {
socket.meta.revdns = address;
callback(null, true);
}
}
|
javascript
|
{
"resource": ""
}
|
q51752
|
train
|
function (ev) {
// If we're copying text, don't shift focus
if (ev.ctrlKey || ev.altKey || ev.metaKey) {
return;
}
// If we're typing into an input box somewhere, ignore
var elements = ['input', 'select', 'textarea', 'button', 'datalist', 'keygen'];
var do_not_refocus =
elements.indexOf(ev.target.tagName.toLowerCase()) > -1 ||
$(ev.target).attr('contenteditable');
if (do_not_refocus) {
return;
}
$('#kiwi .controlbox .inp').focus();
}
|
javascript
|
{
"resource": ""
}
|
|
q51753
|
train
|
function ( options ) {
// Some minimal defaults
this.defaults = {
"locale_data" : {
"messages" : {
"" : {
"domain" : "messages",
"lang" : "en",
"plural_forms" : "nplurals=2; plural=(n != 1);"
}
// There are no default keys, though
}
},
// The default domain if one is missing
"domain" : "messages",
// enable debug mode to log untranslated strings to the console
"debug" : false
};
// Mix in the sent options with the default options
this.options = _.extend( {}, this.defaults, options );
this.textdomain( this.options.domain );
if ( options.domain && ! this.options.locale_data[ this.options.domain ] ) {
throw new Error('Text domain set to non-existent domain: `' + options.domain + '`');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51754
|
train
|
function ( domain, context, singular_key, plural_key, val ) {
// Set some defaults
plural_key = plural_key || singular_key;
// Use the global domain default if one
// isn't explicitly passed in
domain = domain || this._textdomain;
var fallback;
// Handle special cases
// No options found
if ( ! this.options ) {
// There's likely something wrong, but we'll return the correct key for english
// We do this by instantiating a brand new Jed instance with the default set
// for everything that could be broken.
fallback = new Jed();
return fallback.dcnpgettext.call( fallback, undefined, undefined, singular_key, plural_key, val );
}
// No translation data provided
if ( ! this.options.locale_data ) {
throw new Error('No locale data provided.');
}
if ( ! this.options.locale_data[ domain ] ) {
throw new Error('Domain `' + domain + '` was not found.');
}
if ( ! this.options.locale_data[ domain ][ "" ] ) {
throw new Error('No locale meta information provided.');
}
// Make sure we have a truthy key. Otherwise we might start looking
// into the empty string key, which is the options for the locale
// data.
if ( ! singular_key ) {
throw new Error('No translation key found.');
}
var key = context ? context + Jed.context_delimiter + singular_key : singular_key,
locale_data = this.options.locale_data,
dict = locale_data[ domain ],
defaultConf = (locale_data.messages || this.defaults.locale_data.messages)[""],
pluralForms = dict[""].plural_forms || dict[""]["Plural-Forms"] || dict[""]["plural-forms"] || defaultConf.plural_forms || defaultConf["Plural-Forms"] || defaultConf["plural-forms"],
val_list,
res;
var val_idx;
if (val === undefined) {
// No value passed in; assume singular key lookup.
val_idx = 1;
} else {
// Value has been passed in; use plural-forms calculations.
// Handle invalid numbers, but try casting strings for good measure
if ( typeof val != 'number' ) {
val = parseInt( val, 10 );
if ( isNaN( val ) ) {
throw new Error('The number that was passed in is not a number.');
}
}
val_idx = getPluralFormFunc(pluralForms)(val) + 1;
}
// Throw an error if a domain isn't found
if ( ! dict ) {
throw new Error('No domain named `' + domain + '` could be found.');
}
val_list = dict[ key ];
// If there is no match, then revert back to
// english style singular/plural with the keys passed in.
if ( ! val_list || val_idx >= val_list.length ) {
if (this.options.missing_key_callback) {
this.options.missing_key_callback(key, domain);
}
res = [ null, singular_key, plural_key ];
// collect untranslated strings
if (this.options.debug===true) {
console.log(res[ getPluralFormFunc(pluralForms)( val ) + 1 ]);
}
return res[ getPluralFormFunc()( val ) + 1 ];
}
res = val_list[ val_idx ];
// This includes empty strings on purpose
if ( ! res ) {
res = [ null, singular_key, plural_key ];
return res[ getPluralFormFunc()( val ) + 1 ];
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
|
q51755
|
train
|
function (list) {
var batch_size = 100,
cutoff;
if (list.length >= batch_size) {
// If we have more clients than our batch size, call ourself with the next batch
setTimeout(function () {
sendCommandBatch(list.slice(batch_size));
}, 200);
cutoff = batch_size;
} else {
cutoff = list.length;
}
list.slice(0, cutoff).forEach(function (client) {
if (!client.disposed) {
client.sendKiwiCommand(command, data);
}
});
if (cutoff === list.length && typeof callback === 'function') {
callback();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51756
|
updateLocalesCache
|
train
|
function updateLocalesCache() {
cached_available_locales = [];
fs.readdir(global.config.public_http + '/assets/locales', function (err, files) {
if (err) {
if (err.code === 'ENOENT') {
winston.error('No locale files could be found at ' + err.path);
} else {
winston.error('Error reading locales.', err);
}
}
(files || []).forEach(function (file) {
if (file.substr(-5) === '.json') {
cached_available_locales.push(file.slice(0, -5));
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q51757
|
serveSettings
|
train
|
function serveSettings(request, response) {
var referrer_url,
debug = false;
// Check the referrer for a debug option
if (request.headers.referer) {
referrer_url = url.parse(request.headers.referer, true);
if (referrer_url.query && referrer_url.query.debug) {
debug = true;
}
}
SettingsGenerator.get(debug, function(err, settings) {
if (err) {
winston.error('Error generating settings', err);
response.writeHead(500, 'Internal Server Error');
return response.end();
}
if (request.headers['if-none-match'] && request.headers['if-none-match'] === settings.hash) {
response.writeHead(304, 'Not Modified');
return response.end();
}
response.writeHead(200, {
'ETag': settings.hash,
'Content-Type': 'application/json'
});
response.end(settings.settings);
});
}
|
javascript
|
{
"resource": ""
}
|
q51758
|
train
|
function (timeout) {
if (!this.closed) {
if (this.notification) {
this._closeTimeout = this._closeTimeout || setTimeout(_.bind(this.close, this), timeout);
} else {
this.once('show', _.bind(this.closeAfter, this, timeout));
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q51759
|
unknownCommand
|
train
|
function unknownCommand (ev) {
var raw_cmd = ev.command + ' ' + ev.params.join(' ');
this.app.connections.active_connection.gateway.raw(raw_cmd);
}
|
javascript
|
{
"resource": ""
}
|
q51760
|
train
|
function(rpc_method, fn) {
rpc.on(rpc_method, _.partial(moduleEventWrap, rpc_method, fn));
}
|
javascript
|
{
"resource": ""
}
|
|
q51761
|
truncateString
|
train
|
function truncateString(str, block_size) {
block_size = block_size || 350;
var blocks = [],
current_pos;
for (current_pos = 0; current_pos < str.length; current_pos = current_pos + block_size) {
blocks.push(str.substr(current_pos, block_size));
}
return blocks;
}
|
javascript
|
{
"resource": ""
}
|
q51762
|
train
|
function () {
var that = this,
connect_data;
// Build up data to be used for webirc/etc detection
connect_data = {
connection: this,
// Array of lines to be sent to the IRCd before anything else
prepend_data: []
};
// Let the webirc/etc detection modify any required parameters
connect_data = findWebIrc.call(this, connect_data);
global.modules.emit('irc authorize', connect_data).then(function ircAuthorizeCb() {
// Send any initial data for webirc/etc
if (connect_data.prepend_data) {
_.each(connect_data.prepend_data, function(data) {
that.write(data);
});
}
that.write('CAP LS');
if (that.password) {
that.write('PASS ' + that.password);
}
that.write('NICK ' + that.nick);
that.write('USER ' + that.username + ' 0 0 :' + that.gecos);
that.emit('connected');
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51763
|
findWebIrc
|
train
|
function findWebIrc(connect_data) {
var webirc_pass = global.config.webirc_pass,
found_webirc_pass, tmp;
// Do we have a single WEBIRC password?
if (typeof webirc_pass === 'string' && webirc_pass) {
found_webirc_pass = webirc_pass;
// Do we have a WEBIRC password for this hostname?
} else if (typeof webirc_pass === 'object' && webirc_pass[this.irc_host.hostname.toLowerCase()]) {
found_webirc_pass = webirc_pass[this.irc_host.hostname.toLowerCase()];
}
if (found_webirc_pass) {
// Build the WEBIRC line to be sent before IRC registration
tmp = 'WEBIRC ' + found_webirc_pass + ' KiwiIRC ';
tmp += this.user.hostname + ' ' + this.user.address;
connect_data.prepend_data = [tmp];
}
return connect_data;
}
|
javascript
|
{
"resource": ""
}
|
q51764
|
socketOnData
|
train
|
function socketOnData(data) {
var data_pos, // Current position within the data Buffer
line_start = 0,
lines = [],
i,
max_buffer_size = 1024; // 1024 bytes is the maximum length of two RFC1459 IRC messages.
// May need tweaking when IRCv3 message tags are more widespread
// Split data chunk into individual lines
for (data_pos = 0; data_pos < data.length; data_pos++) {
if (data[data_pos] === 0x0A) { // Check if byte is a line feed
lines.push(data.slice(line_start, data_pos));
line_start = data_pos + 1;
}
}
// No complete lines of data? Check to see if buffering the data would exceed the max buffer size
if (!lines[0]) {
if ((this.held_data ? this.held_data.length : 0 ) + data.length > max_buffer_size) {
// Buffering this data would exeed our max buffer size
this.emit('error', 'Message buffer too large');
this.socket.destroy();
} else {
// Append the incomplete line to our held_data and wait for more
if (this.held_data) {
this.held_data = Buffer.concat([this.held_data, data], this.held_data.length + data.length);
} else {
this.held_data = data;
}
}
// No complete lines to process..
return;
}
// If we have an incomplete line held from the previous chunk of data
// merge it with the first line from this chunk of data
if (this.hold_last && this.held_data !== null) {
lines[0] = Buffer.concat([this.held_data, lines[0]], this.held_data.length + lines[0].length);
this.hold_last = false;
this.held_data = null;
}
// If the last line of data in this chunk is not complete, hold it so
// it can be merged with the first line from the next chunk
if (line_start < data_pos) {
if ((data.length - line_start) > max_buffer_size) {
// Buffering this data would exeed our max buffer size
this.emit('error', 'Message buffer too large');
this.socket.destroy();
return;
}
this.hold_last = true;
this.held_data = new Buffer(data.length - line_start);
data.copy(this.held_data, 0, line_start);
}
this.read_buffer = this.read_buffer.concat(lines);
processIrcLines(this);
}
|
javascript
|
{
"resource": ""
}
|
q51765
|
processIrcLines
|
train
|
function processIrcLines(irc_con, continue_processing) {
if (irc_con.reading_buffer && !continue_processing) return;
irc_con.reading_buffer = true;
var lines_per_js_tick = 4,
processed_lines = 0;
while(processed_lines < lines_per_js_tick && irc_con.read_buffer.length > 0) {
parseIrcLine(irc_con, irc_con.read_buffer.shift());
processed_lines++;
Stats.incr('irc.connection.parsed_lines');
}
if (irc_con.read_buffer.length > 0) {
irc_con.setTimeout(processIrcLines, 1, irc_con, true);
} else {
irc_con.reading_buffer = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q51766
|
ProxySocket
|
train
|
function ProxySocket(proxy_port, proxy_addr, meta, proxy_opts) {
stream.Duplex.call(this);
this.connected_fn = null;
this.proxy_addr = proxy_addr;
this.proxy_port = proxy_port;
this.proxy_opts = proxy_opts || {};
this.setMeta(meta || {});
this.state = 'disconnected';
}
|
javascript
|
{
"resource": ""
}
|
q51767
|
isBlacklisted
|
train
|
function isBlacklisted(ip, callback) {
var host_lookup = reverseIp(ip) + bl_zones[current_bl];
dns.resolve4(host_lookup, function(err, domain) {
if (err) {
// Not blacklisted
callback(false);
} else {
// It is blacklisted
callback(true);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q51768
|
train
|
function() {
var network = typeof connection_id === 'undefined' ?
_kiwi.app.connections.active_connection :
_kiwi.app.connections.getByConnectionId(connection_id);
return network ?
network :
undefined;
}
|
javascript
|
{
"resource": ""
}
|
|
q51769
|
train
|
function (opts, callback) {
var locale_promise, theme_promise,
that = this;
opts = opts || {};
this.initUtils();
// Set up the settings datastore
_kiwi.global.settings = _kiwi.model.DataStore.instance('kiwi.settings');
_kiwi.global.settings.load();
// Set the window title
window.document.title = opts.server_settings.client.window_title || 'Kiwi IRC';
locale_promise = new Promise(function (resolve) {
// In order, find a locale from the users saved settings, the URL, default settings on the server, or auto detect
var locale = _kiwi.global.settings.get('locale') || opts.locale || opts.server_settings.client.settings.locale || 'magic';
$.getJSON(opts.base_path + '/assets/locales/' + locale + '.json', function (locale) {
if (locale) {
that.i18n = new Jed(locale);
} else {
that.i18n = new Jed();
}
resolve();
});
});
theme_promise = new Promise(function (resolve) {
var text_theme = opts.server_settings.client.settings.text_theme || 'default';
$.getJSON(opts.base_path + '/assets/text_themes/' + text_theme + '.json', function(text_theme) {
opts.text_theme = text_theme;
resolve();
});
});
Promise.all([locale_promise, theme_promise]).then(function () {
_kiwi.app = new _kiwi.model.Application(opts);
// Start the client up
_kiwi.app.initializeInterfaces();
// Event emitter to let plugins interface with parts of kiwi
_kiwi.global.events = new PluginInterface();
// Now everything has started up, load the plugin manager for third party plugins
_kiwi.global.plugins = new _kiwi.model.PluginManager();
callback();
}).then(null, function(err) {
console.error(err.stack);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51770
|
generateSettings
|
train
|
function generateSettings(debug) {
var vars = {
server_settings: {},
client_plugins: [],
translations: [],
scripts: [
[
'assets/libs/lodash.min.js'
],
['assets/libs/backbone.min.js', 'assets/libs/jed.js']
]
};
// Any restricted server mode set?
if (config.get().restrict_server) {
vars.server_settings = {
connection: {
server: config.get().restrict_server,
port: config.get().restrict_server_port || 6667,
ssl: config.get().restrict_server_ssl,
allow_change: false
}
};
}
// Any client default settings?
if (config.get().client) {
vars.server_settings.client = config.get().client;
}
// Client transport specified?
if (config.get().client_transports) {
vars.server_settings.transports = config.get().client_transports;
}
// Any client plugins?
if (config.get().client_plugins && config.get().client_plugins.length > 0) {
vars.client_plugins = config.get().client_plugins;
}
addScripts(vars, debug);
return Promise.all([addThemes().then(function (themes) {
vars.themes = themes;
}), addTranslations().then(function (translations) {
vars.translations = translations;
})]).then(function () {
var settings = JSON.stringify(vars);
return ({
settings: settings,
hash: crypto.createHash('md5').update(settings).digest('hex')
});
});
}
|
javascript
|
{
"resource": ""
}
|
q51771
|
train
|
function(word, colourise) {
var members, member, nick, nick_re, style = '';
if (!(members = this.model.get('members')) || !(member = members.getByNick(word))) {
return;
}
nick = member.get('nick');
if (colourise !== false) {
// Use the nick from the member object so the style matches the letter casing
style = this.getNickStyles(nick).asCssString();
}
nick_re = new RegExp('(.*)(' + _.escapeRegExp(nick) + ')(.*)', 'i');
return word.replace(nick_re, function (__, before, nick_in_orig_case, after) {
return _.escape(before)
+ '<span class="inline-nick" style="' + style + '; cursor:pointer" data-nick="' + _.escape(nick) + '">'
+ _.escape(nick_in_orig_case)
+ '</span>'
+ _.escape(after);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51772
|
train
|
function(word) {
var re,
parsed = false,
network = this.model.get('network');
if (!network) {
return;
}
re = new RegExp('(^|\\s)([' + _.escapeRegExp(network.get('channel_prefix')) + '][^ .,\\007]+)', 'g');
if (!word.match(re)) {
return parsed;
}
parsed = word.replace(re, function (m1, m2) {
return m2 + '<a class="chan" data-channel="' + _.escape(m1.trim()) + '">' + _.escape(m1.trim()) + '</a>';
});
return parsed;
}
|
javascript
|
{
"resource": ""
}
|
|
q51773
|
train
|
function(msg) {
var nick_hex, time_difference,
message_words,
sb = this.model.get('scrollback'),
network = this.model.get('network'),
nick,
regexpStr,
prev_msg = sb[sb.length-2],
hour, pm, am_pm_locale_key;
// Clone the msg object so we dont modify the original
msg = _.clone(msg);
// Defaults
msg.css_classes = '';
msg.nick_style = '';
msg.is_highlight = false;
msg.time_string = '';
// Nick + custom highlight detecting
nick = network ? network.get('nick') : '';
if (nick && msg.nick.localeCompare(nick) !== 0) {
// Build a list of all highlights and escape them for regex
regexpStr = _.chain((_kiwi.global.settings.get('custom_highlights') || '').split(/[\s,]+/))
.compact()
.concat(nick)
.map(_.escapeRegExp)
.join('|')
.value();
if (msg.msg.search(new RegExp('(\\b|\\W|^)(' + regexpStr + ')(\\b|\\W|$)', 'i')) > -1) {
msg.is_highlight = true;
msg.css_classes += ' highlight';
}
}
message_words = msg.msg.split(' ');
message_words = _.map(message_words, function(word) {
var parsed_word;
parsed_word = this.parseMessageUrls(word);
if (typeof parsed_word === 'string') return parsed_word;
parsed_word = this.parseMessageChannels(word);
if (typeof parsed_word === 'string') return parsed_word;
parsed_word = this.parseMessageNicks(word, (msg.type === 'privmsg'));
if (typeof parsed_word === 'string') return parsed_word;
parsed_word = _.escape(word);
// Replace text emoticons with images
if (_kiwi.global.settings.get('show_emoticons')) {
parsed_word = emoticonFromText(parsed_word);
}
return parsed_word;
}, this);
msg.unparsed_msg = msg.msg;
msg.msg = message_words.join(' ');
// Convert IRC formatting into HTML formatting
msg.msg = formatIRCMsg(msg.msg);
// Add some style to the nick
msg.nick_style = this.getNickStyles(msg.nick).asCssString();
// Generate a hex string from the nick to be used as a CSS class name
nick_hex = '';
if (msg.nick) {
_.map(msg.nick.split(''), function (char) {
nick_hex += char.charCodeAt(0).toString(16);
});
msg.css_classes += ' nick_' + nick_hex;
}
if (prev_msg) {
// Time difference between this message and the last (in minutes)
time_difference = (msg.time.getTime() - prev_msg.time.getTime())/1000/60;
if (prev_msg.nick === msg.nick && time_difference < 1) {
msg.css_classes += ' repeated_nick';
}
}
// Build up and add the line
if (_kiwi.global.settings.get('use_24_hour_timestamps')) {
msg.time_string = msg.time.getHours().toString().lpad(2, "0") + ":" + msg.time.getMinutes().toString().lpad(2, "0") + ":" + msg.time.getSeconds().toString().lpad(2, "0");
} else {
hour = msg.time.getHours();
pm = hour > 11;
hour = hour % 12;
if (hour === 0)
hour = 12;
am_pm_locale_key = pm ?
'client_views_panel_timestamp_pm' :
'client_views_panel_timestamp_am';
msg.time_string = translateText(am_pm_locale_key, hour + ":" + msg.time.getMinutes().toString().lpad(2, "0") + ":" + msg.time.getSeconds().toString().lpad(2, "0"));
}
return msg;
}
|
javascript
|
{
"resource": ""
}
|
|
q51774
|
train
|
function (event) {
var $target = $(event.currentTarget),
nick,
members = this.model.get('members'),
member;
event.stopPropagation();
// Check this current element for a nick before resorting to the main message
// (eg. inline nicks has the nick on its own element within the message)
nick = $target.data('nick');
if (!nick) {
nick = $target.parent('.msg').data('message').nick;
}
// Make sure this nick is still in the channel
member = members ? members.getByNick(nick) : null;
if (!member) {
return;
}
_kiwi.global.events.emit('nick:select', {
target: $target,
member: member,
network: this.model.get('network'),
source: 'message',
$event: event
})
.then(_.bind(this.openUserMenuForNick, this, $target, member));
}
|
javascript
|
{
"resource": ""
}
|
|
q51775
|
train
|
function (event) {
var nick_class;
// Find a valid class that this element has
_.each($(event.currentTarget).parent('.msg').attr('class').split(' '), function (css_class) {
if (css_class.match(/^nick_[a-z0-9]+/i)) {
nick_class = css_class;
}
});
// If no class was found..
if (!nick_class) return;
$('.'+nick_class).addClass('global_nick_highlight');
}
|
javascript
|
{
"resource": ""
}
|
|
q51776
|
statsTimer
|
train
|
function statsTimer(stat_name, data_start) {
var timer_started = new Date();
var timerStop = function timerStop(data_end) {
var time = (new Date()) - timer_started;
var data = shallowMergeObjects(data_start, data_end);
global.modules.emit('stat timer', {name: stat_name, time: time, data: data});
};
return {
stop: timerStop
};
}
|
javascript
|
{
"resource": ""
}
|
q51777
|
SocketClient
|
train
|
function SocketClient (socket) {
var that = this;
this.socket = socket;
this.socket_closing = false;
this.remoteAddress = this.socket.remoteAddress;
winston.info('Control connection from %s opened', this.socket.remoteAddress);
this.bindEvents();
socket.write("\nHello, you are connected to the Kiwi server :)\n\n");
this.control_interface = new ControlInterface(socket);
_.each(socket_commands, function(fn, command_name) {
that.control_interface.addCommand(command_name, fn.bind(that));
});
}
|
javascript
|
{
"resource": ""
}
|
q51778
|
train
|
function (applet_object, applet_name) {
if (typeof applet_object === 'object') {
// Make sure this is a valid Applet
if (applet_object.get || applet_object.extend) {
// Try find a title for the applet
this.set('title', applet_object.get('title') || _kiwi.global.i18n.translate('client_models_applet_unknown').fetch());
// Update the tabs title if the applet changes it
applet_object.bind('change:title', function (obj, new_value) {
this.set('title', new_value);
}, this);
// If this applet has a UI, add it now
this.view.$el.html('');
if (applet_object.view) {
this.view.$el.append(applet_object.view.$el);
}
// Keep a reference to this applet
this.loaded_applet = applet_object;
this.loaded_applet.trigger('applet_loaded');
}
} else if (typeof applet_object === 'string') {
// Treat this as a URL to an applet script and load it
this.loadFromUrl(applet_object, applet_name);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q51779
|
train
|
function (applet_name) {
// See if we have an instance loaded already
var applet = _.find(_kiwi.app.panels('applets'), function(panel) {
// Ignore if it's not an applet
if (!panel.isApplet()) return;
// Ignore if it doesn't have an applet loaded
if (!panel.loaded_applet) return;
if (panel.loaded_applet.get('_applet_name') === applet_name) {
return true;
}
});
if (applet) return applet;
// If we didn't find an instance, load a new one up
return this.load(applet_name);
}
|
javascript
|
{
"resource": ""
}
|
|
q51780
|
callListeners
|
train
|
function callListeners(listeners) {
var current_event_idx = -1;
// Make sure we have some data to pass to the listeners
event_data = event_data || undefined;
// If no bound listeners for this event, leave now
if (listeners.length === 0) {
emitComplete();
return;
}
// Call the next listener in our array
function nextListener() {
var listener, event_obj;
// We want the next listener
current_event_idx++;
// If we've ran out of listeners end this emit call
if (!listeners[current_event_idx]) {
emitComplete();
return;
}
// Object the listener ammends to tell us what it's going to do
event_obj = {
// If changed to true, expect this listener is going to callback
wait: false,
// If wait is true, this callback must be called to continue running listeners
callback: function () {
// Invalidate this callback incase a listener decides to call it again
event_obj.callback = undefined;
nextListener.apply(that);
},
// Prevents the default 'done' functions from executing
preventDefault: function () {
prevented = true;
}
};
listener = listeners[current_event_idx];
listener[1].call(listener[2] || that, event_obj, event_data);
// If the listener hasn't signalled it's going to wait, proceed to next listener
if (!event_obj.wait) {
// Invalidate the callback just incase a listener decides to call it anyway
event_obj.callback = undefined;
nextListener();
}
}
nextListener();
}
|
javascript
|
{
"resource": ""
}
|
q51781
|
train
|
function (channels) {
var that = this,
panels = [];
// Multiple channels may come as comma-delimited
if (typeof channels === 'string') {
channels = channels.split(',');
}
$.each(channels, function (index, channel_name_key) {
// We may have a channel key so split it off
var spli = channel_name_key.trim().split(' '),
channel_name = spli[0],
channel_key = spli[1] || '';
// Trim any whitespace off the name
channel_name = channel_name.trim();
// Add channel_prefix in front of the first channel if missing
if (that.get('channel_prefix').indexOf(channel_name[0]) === -1) {
// Could be many prefixes but '#' is highly likely the required one
channel_name = '#' + channel_name;
}
// Check if we have the panel already. If not, create it
channel = that.panels.getByName(channel_name);
if (!channel) {
channel = new _kiwi.model.Channel({name: channel_name, network: that, key: channel_key||undefined});
that.panels.add(channel);
}
panels.push(channel);
that.gateway.join(channel_name, channel_key);
});
return panels;
}
|
javascript
|
{
"resource": ""
}
|
|
q51782
|
train
|
function() {
var that = this;
this.panels.forEach(function(panel) {
if (!panel.isChannel())
return;
that.gateway.join(panel.get('name'), panel.get('key') || undefined);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51783
|
train
|
function (mask) {
var found_mask;
if (typeof mask === "object") {
mask = (mask.nick||'*')+'!'+(mask.ident||'*')+'@'+(mask.hostname||'*');
} else if (typeof mask === "string") {
mask = toUserMask(mask);
}
found_mask = this.ignore_list.find(function(entry) {
return entry.get('regex').test(mask);
});
return !!found_mask;
}
|
javascript
|
{
"resource": ""
}
|
|
q51784
|
train
|
function (nick) {
var that = this,
query;
// Check if we have the panel already. If not, create it
query = that.panels.getByName(nick);
if (!query) {
query = new _kiwi.model.Query({name: nick, network: this});
that.panels.add(query);
}
// In all cases, show the demanded query
query.view.show();
return query;
}
|
javascript
|
{
"resource": ""
}
|
|
q51785
|
friendlyModeString
|
train
|
function friendlyModeString (event_modes, alt_target) {
var modes = {}, return_string;
// If no default given, use the main event info
if (!event_modes) {
event_modes = event.modes;
alt_target = event.target;
}
// Reformat the mode object to make it easier to work with
_.each(event_modes, function (mode){
var param = mode.param || alt_target || '';
// Make sure we have some modes for this param
if (!modes[param]) {
modes[param] = {'+':'', '-':''};
}
modes[param][mode.mode[0]] += mode.mode.substr(1);
});
// Put the string together from each mode
return_string = [];
_.each(modes, function (modeset, param) {
var str = '';
if (modeset['+']) str += '+' + modeset['+'];
if (modeset['-']) str += '-' + modeset['-'];
return_string.push(str + ' ' + param);
});
return_string = return_string.join(', ');
return return_string;
}
|
javascript
|
{
"resource": ""
}
|
q51786
|
layouts
|
train
|
function layouts(handlebars) {
var helpers = {
/**
* @method extend
* @param {String} name
* @param {?Object} customContext
* @param {Object} options
* @param {Function(Object)} options.fn
* @param {Object} options.hash
* @return {String} Rendered partial.
*/
extend: function (name, customContext, options) {
// Make `customContext` optional
if (arguments.length < 3) {
options = customContext;
customContext = null;
}
options = options || {};
var fn = options.fn || noop,
context = mixin({}, this, customContext, options.hash),
data = handlebars.createFrame(options.data),
template = handlebars.partials[name];
// Partial template required
if (template == null) {
throw new Error('Missing partial: \'' + name + '\'');
}
// Compile partial, if needed
if (typeof template !== 'function') {
template = handlebars.compile(template);
}
// Add overrides to stack
getStack(context).push(fn);
// Render partial
return template(context, { data: data });
},
/**
* @method embed
* @param {String} name
* @param {?Object} customContext
* @param {Object} options
* @param {Function(Object)} options.fn
* @param {Object} options.hash
* @return {String} Rendered partial.
*/
embed: function () {
var context = mixin({}, this || {});
// Reset context
context.$$layoutStack = null;
context.$$layoutActions = null;
// Extend
return helpers.extend.apply(context, arguments);
},
/**
* @method block
* @param {String} name
* @param {Object} options
* @param {Function(Object)} options.fn
* @return {String} Modified block content.
*/
block: function (name, options) {
options = options || {};
var fn = options.fn || noop,
data = handlebars.createFrame(options.data),
context = this || {};
applyStack(context);
return getActionsByName(context, name).reduce(
applyAction.bind(context),
fn(context, { data: data })
);
},
/**
* @method content
* @param {String} name
* @param {Object} options
* @param {Function(Object)} options.fn
* @param {Object} options.hash
* @param {String} options.hash.mode
* @return {String} Always empty.
*/
content: function (name, options) {
options = options || {};
var fn = options.fn,
data = handlebars.createFrame(options.data),
hash = options.hash || {},
mode = hash.mode || 'replace',
context = this || {};
applyStack(context);
// Getter
if (!fn) {
return name in getActions(context);
}
// Setter
getActionsByName(context, name).push({
options: { data: data },
mode: mode.toLowerCase(),
fn: fn
});
}
};
return helpers;
}
|
javascript
|
{
"resource": ""
}
|
q51787
|
QueryInterface
|
train
|
function QueryInterface (options) {
this.options = _.extend({
stopPropagation: false,
createdDefault: true,
fallbackFn: undefined,
}, options || {});
this._results = [];
this._handlers = [];
}
|
javascript
|
{
"resource": ""
}
|
q51788
|
fakeModelInstance
|
train
|
function fakeModelInstance (values, options) {
this.options = options || {};
/**
* As with Sequelize, we include a `dataValues` property which contains the values for the
* instance. As with Sequelize, you should use other methods to edit the values for any
* code that will also interact with Sequelize.
*
* For test code, when possible, we also recommend you use other means to validate. But
* this object is also available if needed.
*
* @name dataValues
* @alias _values
* @member {Object}
**/
this.dataValues = this._values = _.clone(values || {});
this.hasPrimaryKeys = this.Model.options.hasPrimaryKeys;
if(this.hasPrimaryKeys) {
this.dataValues.id = this.dataValues.id || (++id);
}
if(this.Model.options.timestamps) {
this.dataValues.createdAt = this.dataValues.createdAt || new Date();
this.dataValues.updatedAt = this.dataValues.updatedAt || new Date();
}
// Double underscore for test specific internal variables
this.__validationErrors = [];
// Add the items from the dataValues to be accessible via a simple `instance.value` call
var self = this;
_.each(this.dataValues, function (val, key) {
Object.defineProperty(self, key, {
get: function () {
return fakeModelInstance.prototype.get.call(self, key);
},
set: function (value) {
fakeModelInstance.prototype.set.call(self, key, value);
},
});
});
}
|
javascript
|
{
"resource": ""
}
|
q51789
|
Sequelize
|
train
|
function Sequelize(database, username, password, options) {
if(typeof database == 'object') {
options = database;
} else if (typeof username == 'object') {
options = username;
} else if (typeof password == 'object') {
options = password;
}
this.queryInterface = new QueryInterface( _.pick(options || {}, ['stopPropagation']) );
/**
* Options passed into the Sequelize initialization
*
* @member Sequelize
* @property
**/
this.options = _.extend({
dialect: 'mock',
}, options || {});
/**
* Used to cache and override model imports for easy mock model importing
*
* @member Sequelize
* @property
**/
this.importCache = {};
/**
* Models that have been defined in this Sequelize Mock instances
*
* @member Sequelize
* @property
**/
this.models = {};
}
|
javascript
|
{
"resource": ""
}
|
q51790
|
convertToDate
|
train
|
function convertToDate(input)
{
if (input.constructor === Date) {
return input
}
if (typeof input === 'number') {
return new Date(input)
}
throw new Error(`Unsupported react-time-ago input: ${typeof input}, ${input}`)
}
|
javascript
|
{
"resource": ""
}
|
q51791
|
getPrefix
|
train
|
function getPrefix() {
var validPrefix = 'abcdef';
return validPrefix.charAt(Math.floor(Math.random() * validPrefix.length));
}
|
javascript
|
{
"resource": ""
}
|
q51792
|
train
|
function (num) {
var value, encoded = '';
while (num >= 0x20) {
value = (0x20 | (num & 0x1f)) + 63;
encoded += (String.fromCharCode(value));
num >>= 5;
}
value = num + 63;
encoded += (String.fromCharCode(value));
return encoded;
}
|
javascript
|
{
"resource": ""
}
|
|
q51793
|
train
|
function(x) {
var z = Math.abs(x);
var t = 1 / (1 + z / 2);
var r = t * Math.exp(-z * z - 1.26551223 + t * (1.00002368 +
t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 +
t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 +
t * (-0.82215223 + t * 0.17087277)))))))))
return x >= 0 ? r : 2 - r;
}
|
javascript
|
{
"resource": ""
}
|
|
q51794
|
train
|
function(x) {
if (x >= 2) { return -100; }
if (x <= 0) { return 100; }
var xx = (x < 1) ? x : 2 - x;
var t = Math.sqrt(-2 * Math.log(xx / 2));
var r = -0.70711 * ((2.30753 + t * 0.27061) /
(1 + t * (0.99229 + t * 0.04481)) - t);
for (var j = 0; j < 2; j++) {
var err = erfc(r) - xx;
r += err / (1.12837916709551257 * Math.exp(-(r * r)) - r * err);
}
return (x < 1) ? r : -r;
}
|
javascript
|
{
"resource": ""
}
|
|
q51795
|
train
|
function(mean, variance) {
if (variance <= 0) {
throw new Error('Variance must be > 0 (but was ' + variance + ')');
}
this.mean = mean;
this.variance = variance;
this.standardDeviation = Math.sqrt(variance);
}
|
javascript
|
{
"resource": ""
}
|
|
q51796
|
HeaderParser
|
train
|
function HeaderParser(cfg) {
EventEmitter.call(this);
var self = this;
this.nread = 0;
this.maxed = false;
this.npairs = 0;
this.maxHeaderPairs = (cfg && typeof cfg.maxHeaderPairs === 'number'
? cfg.maxHeaderPairs
: MAX_HEADER_PAIRS);
this.buffer = '';
this.header = {};
this.finished = false;
this.ss = new StreamSearch(B_DCRLF);
this.ss.on('info', function(isMatch, data, start, end) {
if (data && !self.maxed) {
if (self.nread + (end - start) > MAX_HEADER_SIZE) {
end = (MAX_HEADER_SIZE - self.nread);
self.nread = MAX_HEADER_SIZE;
} else
self.nread += (end - start);
if (self.nread === MAX_HEADER_SIZE)
self.maxed = true;
self.buffer += data.toString('binary', start, end);
}
if (isMatch)
self._finish();
});
}
|
javascript
|
{
"resource": ""
}
|
q51797
|
getToken
|
train
|
function getToken() {
tokenType = TOKENTYPE.NULL;
token = '';
// skip over whitespaces: space, tab, newline, and carriage return
while (c === ' ' || c === '\t' || c === '\n' || c === '\r') {
next();
}
// check for delimiters
if (DELIMITERS[c]) {
tokenType = TOKENTYPE.DELIMITER;
token = c;
next();
return;
}
// check for a number
if (isDigit(c) || c === '-') {
tokenType = TOKENTYPE.NUMBER;
if (c === '-') {
token += c;
next();
if (!isDigit(c)) {
throw createSyntaxError('Invalid number, digit expected', index);
}
}
else if (c === '0') {
token += c;
next();
}
else {
// digit 1-9, nothing extra to do
}
while (isDigit(c)) {
token += c;
next();
}
if (c === '.') {
token += c;
next();
if (!isDigit(c)) {
throw createSyntaxError('Invalid number, digit expected', index);
}
while (isDigit(c)) {
token += c;
next();
}
}
if (c === 'e' || c === 'E') {
token += c;
next();
if (c === '+' || c === '-') {
token += c;
next();
}
if (!isDigit(c)) {
throw createSyntaxError('Invalid number, digit expected', index);
}
while (isDigit(c)) {
token += c;
next();
}
}
return;
}
// check for a string
if (c === '"') {
tokenType = TOKENTYPE.STRING;
next();
while (c !== '' && c !== '"') {
if (c === '\\') {
// handle escape characters
next();
let unescaped = ESCAPE_CHARACTERS[c];
if (unescaped !== undefined) {
token += unescaped;
next();
}
else if (c === 'u') {
// parse escaped unicode character, like '\\u260E'
next();
let hex = '';
for (let u = 0; u < 4; u++) {
if (!isHex(c)) {
throw createSyntaxError('Invalid unicode character');
}
hex += c;
next();
}
token += String.fromCharCode(parseInt(hex, 16));
}
else {
throw createSyntaxError('Invalid escape character "\\' + c + '"', index);
}
}
else {
// a regular character
token += c;
next();
}
}
if (c !== '"') {
throw createSyntaxError('End of string expected');
}
next();
return;
}
// check for symbols (true, false, null)
if (isAlpha(c)) {
tokenType = TOKENTYPE.SYMBOL;
while (isAlpha(c)) {
token += c;
next();
}
return;
}
// something unknown is found, wrong characters -> a syntax error
tokenType = TOKENTYPE.UNKNOWN;
while (c !== '') {
token += c;
next();
}
throw createSyntaxError('Syntax error in part "' + token + '"');
}
|
javascript
|
{
"resource": ""
}
|
q51798
|
createSyntaxError
|
train
|
function createSyntaxError (message, c) {
if (c === undefined) {
c = index - token.length;
}
let error = new SyntaxError(message + ' (char ' + c + ')');
error['char'] = c;
return error;
}
|
javascript
|
{
"resource": ""
}
|
q51799
|
parseNumber
|
train
|
function parseNumber () {
if (tokenType === TOKENTYPE.NUMBER) {
let number = new LosslessNumber(token);
getToken();
return number;
}
return parseSymbol();
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.