file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
command-handlers.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.status = undefined;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done)... |
function reconfig() {
log('exec => mup reconfig');
}
function restart() {
log('exec => mup restart');
}
function setup(api) {
process.on('exit', function (code) {
if (code > 0) {
return;
}
console.log('');
console.log('Next, you should run:');
console.log(' mup deploy');
});
... | {
log('exec => mup logs');
} | identifier_body |
command-handlers.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.status = undefined;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done)... | () {
log('exec => mup stop');
}
function ssh(api) {
var servers = api.getConfig().servers;
var serverOption = api.getArgs()[1];
if (!(serverOption in servers)) {
if (Object.keys(servers).length === 1) {
serverOption = Object.keys(servers)[0];
} else {
console.log('mup ssh <server>');
... | stop | identifier_name |
widget.draw.spec.js | import DrawWidget from '../../src/widget/draw/draw-widget';
import { runAllCommonWidgetTests } from '../helpers/test-widget';
const FORM1 =
`<form class="or">
<label class="question or-appearance-draw">
<input name="/data/d" type="file" data-type-xml="binary" accept="image/*" />
</label... | <label class="question or-appearance-annotate">
<input name="/data/a" type="file" data-type-xml="binary" accept="image/*" />
</label>
<input />
</form>`;
[ FORM1, FORM2, FORM3 ].forEach( form => {
runAllCommonWidgetTests( DrawWidget, form, '' );
} );
describe( 'draw widget'... | random_line_split | |
Utils.py | # $HeadURL: $
'''
:mod: Utils
Module that collects utility functions.
'''
import fnmatch
from DIRAC import gConfig, S_OK
from DIRAC.Core.Utilities import List
from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations
__... |
cParameter = candidateParams[ key ]
if not isinstance( cParameter, list ):
cParameter = [ cParameter ]
# We allow using UNIX-like regular expression ( wild-cards ) on the CS
_matches = False
for configItem in configParams[ key ]:
if fnmatch.filter( set( cParameter ), ... | continue | conditional_block |
Utils.py | # $HeadURL: $
'''
:mod: Utils
Module that collects utility functions.
'''
import fnmatch
from DIRAC import gConfig, S_OK
from DIRAC.Core.Utilities import List
from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations
__... |
def getCSTree( csPath = '' ):
'''
Gives the configuration rooted at path in a Python dict. The
result is a Python dictionary that reflects the structure of the
configuration file.
'''
opHelper = Operations()
def getCSTreeAsDict( treePath ):
'''
Function to recursively iterate over a CS... | '''
Function to import from extensions, if not found, tries from DIRAC.
'''
# FIXME: A.T.: Use Core.Utilities.ObjectLoader
for ext in gConfig.getValue( 'DIRAC/Extensions', [] ):
try:
return __import__( ext + base_mod, globals(), locals(), ['*'] )
except ImportError:
continue
#... | identifier_body |
Utils.py | # $HeadURL: $
'''
:mod: Utils
Module that collects utility functions.
'''
import fnmatch
from DIRAC import gConfig, S_OK
from DIRAC.Core.Utilities import List
from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations
__... | ( treePath ):
'''
Function to recursively iterate over a CS tree
'''
csTreeDict = {}
opts = opHelper.getOptionsDict( treePath )
if opts[ 'OK' ]:
opts = opts[ 'Value' ]
for optKey, optValue in opts.items():
if optValue.find( ',' ) > -1:
optVal... | getCSTreeAsDict | identifier_name |
Utils.py | # $HeadURL: $
'''
:mod: Utils
Module that collects utility functions.
'''
import fnmatch
from DIRAC import gConfig, S_OK
from DIRAC.Core.Utilities import List
from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations
__... | - if a param of the candidate does not match the config params
- if a candidate param is None, is considered as wildcard
'''
for key in candidateParams:
if not key in configParams:
# The candidateParams is missing one of the parameters required
# return False
continue
... | def configMatch( candidateParams, configParams ):
'''
For a given configuration, the candidate will be rejected if:
- it is missing at least one of the params in the config | random_line_split |
actions.spec.js | import test from 'tape'
import { forEach, get, isArray, isMatch, isNumber, omit } from 'lodash'
import {
entityDel, ENTITY_DEL, entityPut, ENTITY_PUT, entityPutAll, ENTITY_PUTALL,
entityUpdate, ENTITY_UPDATE, pickTypeId, tripleDel, TRIPLE_DEL, triplePut, TRIPLE_PUT,
} from '../src'
import { agent, creator, item, ma... |
test('entityPutAll', (t) => {
const act = entityPutAll([ agent, creator, item, mainEntity ])
t.equal(act.type, ENTITY_PUTALL)
t.ok(isArray(act.payload))
t.equal(act.payload.length, 4)
t.ok(isNumber(act.payload[0].dateCreated), '0 dateCreated number')
t.ok(isMatch(act.payload[0], agent))
t.ok(isNumber(act... | {
forEach(prototype, (val, key) => {
t.equal(get(object, key), val, str + key)
})
} | identifier_body |
actions.spec.js | import test from 'tape'
import { forEach, get, isArray, isMatch, isNumber, omit } from 'lodash'
import {
entityDel, ENTITY_DEL, entityPut, ENTITY_PUT, entityPutAll, ENTITY_PUTALL,
entityUpdate, ENTITY_UPDATE, pickTypeId, tripleDel, TRIPLE_DEL, triplePut, TRIPLE_PUT,
} from '../src'
import { agent, creator, item, ma... | (t, object, prototype, str) {
forEach(prototype, (val, key) => {
t.equal(get(object, key), val, str + key)
})
}
test('entityPutAll', (t) => {
const act = entityPutAll([ agent, creator, item, mainEntity ])
t.equal(act.type, ENTITY_PUTALL)
t.ok(isArray(act.payload))
t.equal(act.payload.length, 4)
t.ok(i... | testIsMatch | identifier_name |
actions.spec.js | import test from 'tape'
import { forEach, get, isArray, isMatch, isNumber, omit } from 'lodash'
import {
entityDel, ENTITY_DEL, entityPut, ENTITY_PUT, entityPutAll, ENTITY_PUTALL,
entityUpdate, ENTITY_UPDATE, pickTypeId, tripleDel, TRIPLE_DEL, triplePut, TRIPLE_PUT,
} from '../src'
import { agent, creator, item, ma... | })
t.end()
}) | const act2 = tripleDel({ subject: creator, predicate: 'item', object: item })
t.deepEqual(act2.payload, {
predicate: 'item', subject: pickTypeId(creator), object: pickTypeId(item), | random_line_split |
make_sdk_tools.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Create the base (auto)updater for the Native Client SDK"""
import py_compile
import optparse
import os
import shutil
import sys... |
def WriteTarFile(outname, in_dir, tar_dir=''):
'''Create a new compressed tarball from a given directory
Args:
outname: path and filename of the gzipped tar file
in_dir: source directory that will be tar'd and gzipped
tar_dir: root directory within the tarball'''
tar_file = None
try:
tar_fil... | zip.close() | conditional_block |
make_sdk_tools.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Create the base (auto)updater for the Native Client SDK"""
import py_compile
import optparse
import os
import shutil
import sys... | parser = optparse.OptionParser()
parser.add_option(
'-n', '--nacl-sdk', dest='nacl_sdk', default='nacl_sdk.zip',
help='name of the resulting nacl_sdk zipfile')
parser.add_option(
'-s', '--sdk-tools', dest='sdk_tools', default='sdk_tools.tgz',
help='name of the resulting sdk_tools tarball')... |
def main(argv): | random_line_split |
make_sdk_tools.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Create the base (auto)updater for the Native Client SDK"""
import py_compile
import optparse
import os
import shutil
import sys... | (outname, in_dir, tar_dir=''):
'''Create a new compressed tarball from a given directory
Args:
outname: path and filename of the gzipped tar file
in_dir: source directory that will be tar'd and gzipped
tar_dir: root directory within the tarball'''
tar_file = None
try:
tar_file = tarfile.open(ou... | WriteTarFile | identifier_name |
make_sdk_tools.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Create the base (auto)updater for the Native Client SDK"""
import py_compile
import optparse
import os
import shutil
import sys... | if zip:
zip.close()
def WriteTarFile(outname, in_dir, tar_dir=''):
'''Create a new compressed tarball from a given directory
Args:
outname: path and filename of the gzipped tar file
in_dir: source directory that will be tar'd and gzipped
tar_dir: root directory within the tarball'''
tar_... | '''Create a zipfile from the contents of a given directory.
The path of the resulting contents in the zipfile will match that of the
last directory name in dirpath.
Args:
dirpath: Path to directory to add to zipfile
zippath: filename of resulting zipfile
'''
zip = None
try:
zip = zipfile.ZipFi... | identifier_body |
mobileweb.py | import datetime
import re
from django.http import HttpResponse
from django.utils.http import urlencode
import smsgateway
from smsgateway.models import SMS
from smsgateway.backends.base import SMSBackend
from smsgateway.utils import check_cell_phone_number
class MobileWebBackend(SMSBackend):
def get_send_url(self... |
querystring = urlencode({
'login': account_dict['username'],
'pass': account_dict['password'],
'gsmnr': sms_request.to[0][1:],
'sid': account_dict['sid'],
'msgcontent': msg,
})
return u'http://gateway.mobileweb.be/smsin.asp?%s' % query... | pass | random_line_split |
mobileweb.py | import datetime
import re
from django.http import HttpResponse
from django.utils.http import urlencode
import smsgateway
from smsgateway.models import SMS
from smsgateway.backends.base import SMSBackend
from smsgateway.utils import check_cell_phone_number
class MobileWebBackend(SMSBackend):
def get_send_url(self... |
# Parse and process message
year, month, day, hour, minute, second, ms = map(int, re.findall(r'(\d+)', request_dict['SendDateTime']))
sms_dict = {
'sent': datetime.datetime(year, month, day, hour, minute, second),
'content': request_dict['MsgeContent'],
'sen... | return HttpResponse('OK') | conditional_block |
mobileweb.py | import datetime
import re
from django.http import HttpResponse
from django.utils.http import urlencode
import smsgateway
from smsgateway.models import SMS
from smsgateway.backends.base import SMSBackend
from smsgateway.utils import check_cell_phone_number
class MobileWebBackend(SMSBackend):
def get_send_url(self... | }
sms = SMS(**sms_dict)
response = self.process_incoming(request, sms)
# If necessary, send response SMS
if response is not None:
signature = smsgateway.get_account(reply_using)['reply_signature']
success = smsgateway.send([sms.sender], response, signatur... | request_dict = request.POST if request.method == 'POST' else request.GET
# Check whether we've gotten a SendDateTime
if not 'SendDateTime' in request_dict:
return HttpResponse('')
# Check whether we've already received this message
if SMS.objects.filter(gateway_ref=request_... | identifier_body |
mobileweb.py | import datetime
import re
from django.http import HttpResponse
from django.utils.http import urlencode
import smsgateway
from smsgateway.models import SMS
from smsgateway.backends.base import SMSBackend
from smsgateway.utils import check_cell_phone_number
class MobileWebBackend(SMSBackend):
def get_send_url(self... | (self, request, reply_using=None):
request_dict = request.POST if request.method == 'POST' else request.GET
# Check whether we've gotten a SendDateTime
if not 'SendDateTime' in request_dict:
return HttpResponse('')
# Check whether we've already received this message
... | handle_incoming | identifier_name |
rules.ts | import assert from 'assert'
import { Given, When, Then } from '../../../src'
Given(
'there are {int} {float} coins inside',
function (count: number, denomination: number) {
// TODO: implement this
assert(count)
assert(denomination)
}
)
Given('there are no chocolates inside', function () {
// TODO:... | assert(count)
assert(denomination)
}
) | "the customer's change should be {int} {float} coin(s)",
function (count: number, denomination: number) {
// TODO: implement this | random_line_split |
exceptions.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... | (&self) -> MessageType {
match self {
ResultType::Return | ResultType::Error => MessageType::Reply,
ResultType::Exception => MessageType::Exception,
}
}
}
| message_type | identifier_name |
exceptions.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... | Return,
/// A declared exception
Error,
/// Some other exception (eg ApplicationException)
Exception,
}
impl ResultType {
pub fn message_type(&self) -> MessageType {
match self {
ResultType::Return | ResultType::Error => MessageType::Reply,
ResultType::Exception ... | #[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ResultType {
/// A successful return | random_line_split |
realTimeAudio.py | import ui_plot
import sys
import numpy
from PyQt4 import QtCore, QtGui
import PyQt4.Qwt5 as Qwt
from recorder import *
def plotSomething():
if SR.newAudio==False:
return
xs,ys=SR.fft()
c.setData(xs,ys)
uiplot.qwtPlot.replot()
SR.newAudio=False
if __name__ == "__main__":... | SR.setup()
SR.continuousStart()
### DISPLAY WINDOWS
win_plot.show()
code=app.exec_()
SR.close()
sys.exit(code)
| app = QtGui.QApplication(sys.argv)
win_plot = ui_plot.QtGui.QMainWindow()
uiplot = ui_plot.Ui_win_plot()
uiplot.setupUi(win_plot)
uiplot.btnA.clicked.connect(plotSomething)
#uiplot.btnB.clicked.connect(lambda: uiplot.timer.setInterval(100.0))
#uiplot.btnC.clicked.connect(lambda: uipl... | conditional_block |
realTimeAudio.py | import ui_plot
import sys
import numpy
from PyQt4 import QtCore, QtGui
import PyQt4.Qwt5 as Qwt
from recorder import *
def plotSomething():
|
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
win_plot = ui_plot.QtGui.QMainWindow()
uiplot = ui_plot.Ui_win_plot()
uiplot.setupUi(win_plot)
uiplot.btnA.clicked.connect(plotSomething)
#uiplot.btnB.clicked.connect(lambda: uiplot.timer.setInterval(100.0))
#uipl... | if SR.newAudio==False:
return
xs,ys=SR.fft()
c.setData(xs,ys)
uiplot.qwtPlot.replot()
SR.newAudio=False | identifier_body |
realTimeAudio.py | import ui_plot
import sys
import numpy
from PyQt4 import QtCore, QtGui
import PyQt4.Qwt5 as Qwt
from recorder import *
def plotSomething():
if SR.newAudio==False:
return
xs,ys=SR.fft()
c.setData(xs,ys)
uiplot.qwtPlot.replot()
SR.newAudio=False
if __name__ == "__main__":... | code=app.exec_()
SR.close()
sys.exit(code) | random_line_split | |
realTimeAudio.py | import ui_plot
import sys
import numpy
from PyQt4 import QtCore, QtGui
import PyQt4.Qwt5 as Qwt
from recorder import *
def | ():
if SR.newAudio==False:
return
xs,ys=SR.fft()
c.setData(xs,ys)
uiplot.qwtPlot.replot()
SR.newAudio=False
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
win_plot = ui_plot.QtGui.QMainWindow()
uiplot = ui_plot.Ui_win_plot()
uiplot.setupUi(w... | plotSomething | identifier_name |
WeatherForecasts.ts | import { fetch, addTask } from 'domain-task';
import { Action, Reducer, ActionCreator } from 'redux';
import { AppThunkAction } from './';
// -----------------
// STATE - This defines the type of data maintained in the Redux store.
export interface WeatherForecastsState {
isLoading: boolean;
startDateIndex?: ... |
export const reducer: Reducer<WeatherForecastsState> = (state: WeatherForecastsState, incomingAction: Action) => {
const action = incomingAction as KnownAction;
switch (action.type) {
case 'REQUEST_WEATHER_FORECASTS':
return {
startDateIndex: action.startDateIndex,
... | // REDUCER - For a given state and action, returns the new state. To support time travel, this must not mutate the old state.
const unloadedState: WeatherForecastsState = { forecasts: [], isLoading: false }; | random_line_split |
index.js | import {inject, renderCss, space, face} from '../lib';
inject({
styles: {
heading: {
phone: {
family: 'serif',
fontWeight: 600,
fontSize: 22,
lineHeight: 30, | default: {
family: 'serif',
fontWeight: 600,
fontSize: 20,
lineHeight: 24,
fontSmoothing: 'antialiased',
letterSpacing: '0.5px'
}
},
paragraph: {
phone: {
family: 'sans',
fontWeight: 400,
fontSize: 17,
lineHeight: ... | fontSmoothing: 'antialiased',
letterSpacing: '0.5px'
}, | random_line_split |
server.js | import Express from 'express';
import compression from 'compression';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import path from 'path';
import morgan from 'morgan';
//import jwt from 'jsonwebtoken';
import IntlWrapper from '../client/modules/Intl/IntlWrapper';
// Webpack Requirements
imp... |
// feed some dummy data in DB.
dummyData();
});
// Apply body Parser and server public assets and routes
app.use(compression());
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }));
app.use(morgan('dev'));
app.use(Express.static(path.resolve(__dirname, ... | {
console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console
throw error;
} | conditional_block |
server.js | import Express from 'express';
import compression from 'compression';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import path from 'path';
import morgan from 'morgan';
//import jwt from 'jsonwebtoken';
import IntlWrapper from '../client/modules/Intl/IntlWrapper';
// Webpack Requirements
imp... | <IntlWrapper>
<RouterContext {...renderProps} />
</IntlWrapper>
</Provider>
);
const finalState = store.getState();
res
.set('Content-Type', 'text/html')
.status(200)
.end(renderFullPage(initialView, finalState));
... | <Provider store={store}> | random_line_split |
res_lang.py | # -*- coding: utf-8 -*-
# Copyright 2017 LasLabs Inc.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class ResLang(models.Model):
_inherit = 'res.lang'
default_uom_ids = fields.Many2many(
string='De... | (self):
for record in self:
categories = set(record.default_uom_ids.mapped('category_id'))
if len(categories) != len(record.default_uom_ids):
raise ValidationError(_(
'Only one default unit of measure per category may '
'be selected... | _check_default_uom_ids | identifier_name |
res_lang.py | # -*- coding: utf-8 -*-
# Copyright 2017 LasLabs Inc.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class ResLang(models.Model):
_inherit = 'res.lang'
default_uom_ids = fields.Many2many(
string='De... | )
results = lang.default_uom_ids.filtered(
lambda r: r.category_id.name == category_name,
)
return results[:1]
| """Return the default UoM for language for the input UoM Category.
Args:
category_name (str): Name of the UoM category to get the default
for.
lang (ResLang or str, optional): Recordset or code of the language
to get the default for. Will use the current user lan... | identifier_body |
res_lang.py | # -*- coding: utf-8 -*-
# Copyright 2017 LasLabs Inc.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class ResLang(models.Model):
_inherit = 'res.lang'
default_uom_ids = fields.Many2many(
string='De... |
results = lang.default_uom_ids.filtered(
lambda r: r.category_id.name == category_name,
)
return results[:1]
| lang = self.env['res.lang'].search([
('code', '=', lang),
],
limit=1,
) | conditional_block |
res_lang.py | # -*- coding: utf-8 -*-
# Copyright 2017 LasLabs Inc.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class ResLang(models.Model):
_inherit = 'res.lang'
default_uom_ids = fields.Many2many(
string='De... |
Args:
category_name (str): Name of the UoM category to get the default
for.
lang (ResLang or str, optional): Recordset or code of the language
to get the default for. Will use the current user language if
omitted.
Returns:
Product... |
@api.model
def default_uom_by_category(self, category_name, lang=None):
"""Return the default UoM for language for the input UoM Category. | random_line_split |
AzeriteArmor.ts | import { OvaleDebug } from "./Debug";
import { Ovale } from "./Ovale";
import aceEvent from "@wowts/ace_event-3.0";
import { LuaObj, LuaArray, wipe, pairs, tostring, lualength, ipairs } from "@wowts/lua";
import { sort, insert, concat } from "@wowts/table";
import { C_Item, ItemLocation, C_AzeriteEmpoweredItem, GetSpel... | };
}
break
}
}
}
}
}
}
HasTrait(spellId: number) {
return (this.self_traits[spellId]) && true || false;
... | {
this.self_traits = {}
for(const [slotId,] of pairs(azeriteSlots)){
let itemSlot = itemLocation.CreateFromEquipmentSlot(slotId)
if(item.DoesItemExist(itemSlot) && azeriteItem.IsAzeriteEmpoweredItem(itemSlot)){
let allTraits = azeriteItem.GetAllTierInfo(itemSlot)
... | identifier_body |
AzeriteArmor.ts | import { OvaleDebug } from "./Debug";
import { Ovale } from "./Ovale";
import aceEvent from "@wowts/ace_event-3.0";
import { LuaObj, LuaArray, wipe, pairs, tostring, lualength, ipairs } from "@wowts/lua";
import { sort, insert, concat } from "@wowts/table";
import { C_Item, ItemLocation, C_AzeriteEmpoweredItem, GetSpel... | this.UnregisterMessage("Ovale_EquipmentChanged")
this.UnregisterEvent("AZERITE_EMPOWERED_ITEM_SELECTION_UPDATED")
this.UnregisterEvent("PLAYER_ENTERING_WORLD")
}
ItemChanged(){
let slotId = OvaleEquipment.lastChangedSlot;
if(slotId != undefined && azeriteSlots[slotId]){
... | random_line_split | |
AzeriteArmor.ts | import { OvaleDebug } from "./Debug";
import { Ovale } from "./Ovale";
import aceEvent from "@wowts/ace_event-3.0";
import { LuaObj, LuaArray, wipe, pairs, tostring, lualength, ipairs } from "@wowts/lua";
import { sort, insert, concat } from "@wowts/table";
import { C_Item, ItemLocation, C_AzeriteEmpoweredItem, GetSpel... |
}
AZERITE_EMPOWERED_ITEM_SELECTION_UPDATED(event: string, itemSlot: ItemLocationMixin){
this.UpdateTraits()
}
PLAYER_ENTERING_WORLD(event:string){
this.UpdateTraits()
}
UpdateTraits() {
this.self_traits = {}
for(const [slotId,] of pairs(azeriteSlots)){
... | {
this.UpdateTraits()
} | conditional_block |
AzeriteArmor.ts | import { OvaleDebug } from "./Debug";
import { Ovale } from "./Ovale";
import aceEvent from "@wowts/ace_event-3.0";
import { LuaObj, LuaArray, wipe, pairs, tostring, lualength, ipairs } from "@wowts/lua";
import { sort, insert, concat } from "@wowts/table";
import { C_Item, ItemLocation, C_AzeriteEmpoweredItem, GetSpel... | () {
super();
for (const [k, v] of pairs(this.debugOptions)) {
OvaleDebug.options.args[k] = v;
}
}
OnInitialize() {
this.RegisterMessage("Ovale_EquipmentChanged", "ItemChanged")
this.RegisterEvent("AZERITE_EMPOWERED_ITEM_SELECTION_UPDATED")
this.R... | constructor | identifier_name |
wegame-api-tests.ts | �错
// 系统事件
const audioEnd = () => {
console.log("audio interrupted end");
};
wx.onAudioInterruptionEnd(audioEnd);
wx.offAudioInterruptionEnd(audioEnd);
const audioBegin = () => {
console.log("audio interrupted begin");
};
wx.onAudioInterruptionBegin(audioBegin);
wx.offAudioInterruptionBegin(audioBegin);
const... | });
// 转屏
wx.onDeviceOrientationChange(res => {
console.assert(res.value != null);
});
// 文件
let getFile = wx.getFileSystemManager();
console.assert(getFile != null);
// 位置
wx.getLocation({
success: res => {
res.altitude != null;
console.log("wx.getLocation success");
}
});
// 下载
let downLoa... | console.log("wx.vibrateLong success");
} | random_line_split |
home.component.ts | import { Component, OnInit, Optional } from '@angular/core';
import { MdDialog, MdDialogRef, MdSnackBar } from '@angular/material';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
isDarkTheme: boolea... |
}
@Component({
template: `
<p>This is a dialog</p>
<p>
<label>
This is a text box inside of a dialog.
<input #dialogInput>
</label>
</p>
<p> <button md-button (click)="dialogRef.close(dialogInput.value)">CLOSE</button> </p>
`,
})
export class DialogContent {
constr... | {
this._snackbar.open('YUM SNACKS', 'CHEW');
} | identifier_body |
home.component.ts | import { Component, OnInit, Optional } from '@angular/core';
import { MdDialog, MdDialogRef, MdSnackBar } from '@angular/material';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class | implements OnInit {
isDarkTheme: boolean = false;
lastDialogResult: string;
fullImagePath: string;
foods: any[] = [
{name: 'Pizza', rating: 'Excellent'},
{name: 'Burritos', rating: 'Great'},
{name: 'French fries', rating: 'Pretty good'},
];
progress: number = 0;
constructor(private _dialo... | HomeComponent | identifier_name |
home.component.ts | import { Component, OnInit, Optional } from '@angular/core';
import { MdDialog, MdDialogRef, MdSnackBar } from '@angular/material';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
isDarkTheme: boolea... | } | random_line_split | |
cargo_compile.rs | `rustc` can only be passed to \
one target, consider filtering\nthe package by \
passing e.g. `--lib` or `--bin NAME` to specify \
a single target"))
}
None => None,
};
let targets = target_with_args.as_r... | let key = format!("{}.{}", key, lib_name);
let table = try!(config.get_table(&key)).unwrap().0;
for (k, _) in table.into_iter() {
let key = format!("{}.{}", key, k);
match try!(config.get(&key)).unwrap() { | random_line_split | |
cargo_compile.rs | well as
// downloading and updating all remotes and such.
let resolve = try!(ops::resolve_pkg(&mut registry, package));
// Second, resolve with precisely what we're doing. Filter out
// transitive dependencies if necessary, specify features, handle
// overrides, etc.
le... | {
Some(n as u32)
} | conditional_block | |
cargo_compile.rs | /// Mode for this compile.
pub mode: CompileMode,
/// The specified target will be compiled with all the available arguments,
/// note that this only accounts for the *final* invocation of rustc
pub target_rustc_args: Option<&'a [String]>,
}
#[derive(Clone, Copy, PartialEq)]
pub enum CompileMode {
... | <'a> {
Everything,
Only {
lib: bool,
bins: &'a [String],
examples: &'a [String],
tests: &'a [String],
benches: &'a [String],
}
}
pub fn compile<'a>(manifest_path: &Path,
options: &CompileOptions<'a>)
-> CargoResult<ops::Compilati... | CompileFilter | identifier_name |
cargo_compile.rs | /// Mode for this compile.
pub mode: CompileMode,
/// The specified target will be compiled with all the available arguments,
/// note that this only accounts for the *final* invocation of rustc
pub target_rustc_args: Option<&'a [String]>,
}
#[derive(Clone, Copy, PartialEq)]
pub enum CompileMode {
... | t.tested()
}).map(|t| {
(t, if t.is_example() {build} else {profile})
}).collect::<Vec<_>>();
// Always compile the library if we're testing everything as
// it'll be needed for doctests
... | {
let profiles = pkg.manifest().profiles();
let build = if release {&profiles.release} else {&profiles.dev};
let test = if release {&profiles.bench} else {&profiles.test};
let profile = match mode {
CompileMode::Test => test,
CompileMode::Bench => &profiles.bench,
CompileMode::Bu... | identifier_body |
creation.py | from django.conf import settings
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation
from django.utils.functional import cached_property
class PostGISCreation(DatabaseCreation):
geom_index_type = 'GIST'
geom_index_ops = 'GIST_GEOMETRY_OPS'
geom_index_ops_nd = 'GIST_GEOMETRY_OPS_ND... | (self, verbosity, autoclobber):
test_database_name = super(PostGISCreation, self)._create_test_db(verbosity, autoclobber)
if self.template_postgis is None:
# Connect to the test database in order to create the postgis extension
self.connection.close()
self.connection.... | _create_test_db | identifier_name |
creation.py | from django.conf import settings
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation
from django.utils.functional import cached_property
class PostGISCreation(DatabaseCreation):
geom_index_type = 'GIST'
geom_index_ops = 'GIST_GEOMETRY_OPS'
geom_index_ops_nd = 'GIST_GEOMETRY_OPS_ND... | output.append(style.SQL_KEYWORD('CREATE INDEX ') +
style.SQL_TABLE(qn('%s_%s_id' % (db_table, f.column))) +
style.SQL_KEYWORD(' ON ') +
style.SQL_TABLE(qn(db_table)) +
style.SQL_KEYWOR... | random_line_split | |
creation.py | from django.conf import settings
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation
from django.utils.functional import cached_property
class PostGISCreation(DatabaseCreation):
| gqn = self.connection.ops.geo_quote_name
qn = self.connection.ops.quote_name
db_table = model._meta.db_table
if f.geography or self.connection.ops.geometry:
# Geography and Geometry (PostGIS 2.0+) columns are
# created normally.
... | geom_index_type = 'GIST'
geom_index_ops = 'GIST_GEOMETRY_OPS'
geom_index_ops_nd = 'GIST_GEOMETRY_OPS_ND'
@cached_property
def template_postgis(self):
template_postgis = getattr(settings, 'POSTGIS_TEMPLATE', 'template_postgis')
cursor = self.connection.cursor()
cursor.execute('SE... | identifier_body |
creation.py | from django.conf import settings
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation
from django.utils.functional import cached_property
class PostGISCreation(DatabaseCreation):
geom_index_type = 'GIST'
geom_index_ops = 'GIST_GEOMETRY_OPS'
geom_index_ops_nd = 'GIST_GEOMETRY_OPS_ND... |
return test_database_name
| self.connection.close()
self.connection.settings_dict["NAME"] = test_database_name
cursor = self.connection.cursor()
cursor.execute("CREATE EXTENSION postgis")
cursor.connection.commit() | conditional_block |
__init__.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2014 Alan Aguiar alanjas@hotmail.com
# Copyright (c) 2012-2014 Butiá Team butia@fing.edu.uy
# Butia is a free and open robotic platform
# www.fing.edu.uy/inco/proyectos/butia
# Facultad de Ingeniería - Universidad de la República - Uruguay
#
# This p... | # version = 0.turtlebots_version.secondary_number
__version__ = '0.27.0' | random_line_split | |
NetworkFirst.ts | /*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import {assert} from 'workbox-core/_private/assert.js';
import {logger} from 'workbox-core/_private/logger.js';
import {WorkboxError} fro... | private _getTimeoutPromise({
request,
logs,
handler,
}: {
request: Request;
logs: any[];
handler: StrategyHandler;
}): {promise: Promise<Response | undefined>; id?: number} {
let timeoutId;
const timeoutPromise: Promise<Response | undefined> = new Promise(
(resolve) => {
... | random_line_split | |
NetworkFirst.ts | /*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import {assert} from 'workbox-core/_private/assert.js';
import {logger} from 'workbox-core/_private/logger.js';
import {WorkboxError} fro... |
}
}
return response;
}
}
export {NetworkFirst};
| {
logs.push(`No response found in the '${this.cacheName}' cache.`);
} | conditional_block |
NetworkFirst.ts | /*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import {assert} from 'workbox-core/_private/assert.js';
import {logger} from 'workbox-core/_private/logger.js';
import {WorkboxError} fro... | ({
timeoutId,
request,
logs,
handler,
}: {
request: Request;
logs: any[];
timeoutId?: number;
handler: StrategyHandler;
}): Promise<Response | undefined> {
let error;
let response;
try {
response = await handler.fetchAndCachePut(request);
} catch (fetchError) {
... | _getNetworkPromise | identifier_name |
arm_Data_Lake_Store_Account_Firewall_Rules_create_command_should_work.nock.js | // This file has been autogenerated.
var profile = require('../../../lib/util/profile');
exports.getMockedProfile = function () {
var newProfile = new profile.Profile();
newProfile.addSubscription(new profile.Subscription({
id: '53d9063d-87ae-4ea8-be90-3686c3b8669f',
name: 'Visual Studio Ultimate with MS... | function (nock) {
var result =
nock('https://management.azure.com:443')
.filteringRequestBody(function (path) { return '*';})
.put('/subscriptions/53d9063d-87ae-4ea8-be90-3686c3b8669f/resourceGroups/xplattestadlsrg01/providers/Microsoft.DataLakeStore/accounts/xplattestadls3965/firewallRules/xplattestadls1573?api-ve... | return result; }, | random_line_split |
difference.rs | use super::Style;
/// When printing out one coloured string followed by another, use one of
/// these rules to figure out which *extra* control codes need to be sent.
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum Difference {
/// Print out the control codes specified by this style to end up looking
... |
if first.is_strikethrough && !next.is_strikethrough {
return Reset;
}
// Cannot go from foreground to no foreground, so must Reset.
if first.foreground.is_some() && next.foreground.is_none() {
return Reset;
}
// Cannot go from backgr... | {
return Reset;
} | conditional_block |
difference.rs | use super::Style;
/// When printing out one coloured string followed by another, use one of
/// these rules to figure out which *extra* control codes need to be sent.
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum Difference {
/// Print out the control codes specified by this style to end up looking
... | (first: &Style, next: &Style) -> Difference {
use self::Difference::*;
// XXX(Havvy): This algorithm is kind of hard to replicate without
// having the Plain/Foreground enum variants, so I'm just leaving
// it commented out for now, and defaulting to Reset.
if first == n... | between | identifier_name |
difference.rs | use super::Style;
/// When printing out one coloured string followed by another, use one of
/// these rules to figure out which *extra* control codes need to be sent.
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum Difference {
/// Print out the control codes specified by this style to end up looking
... | if first.is_italic && !next.is_italic {
return Reset;
}
// Cannot un-underline, so must Reset.
if first.is_underline && !next.is_underline {
return Reset;
}
if first.is_blink && !next.is_blink {
return Reset;
}
... | {
use self::Difference::*;
// XXX(Havvy): This algorithm is kind of hard to replicate without
// having the Plain/Foreground enum variants, so I'm just leaving
// it commented out for now, and defaulting to Reset.
if first == next {
return NoDifference;
... | identifier_body |
difference.rs | use super::Style;
/// When printing out one coloured string followed by another, use one of
/// these rules to figure out which *extra* control codes need to be sent.
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum Difference {
/// Print out the control codes specified by this style to end up looking
... | use style::Colour::*;
use style::Style;
fn style() -> Style {
Style::new()
}
macro_rules! test {
($name: ident: $first: expr; $next: expr => $result: expr) => {
#[test]
fn $name() {
assert_eq!($result, Difference::between(&$first, ... | random_line_split | |
patternModeHelpers.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree. |
import ansiEscapes = require('ansi-escapes');
import chalk = require('chalk');
import stringLength = require('string-length');
export const printPatternCaret = (
pattern: string,
pipe: NodeJS.WritableStream,
): void => {
const inputText = `${chalk.dim(' pattern \u203A')} ${pattern}`;
pipe.write(ansiEscapes.e... | */ | random_line_split |
__init__.py | # Copyright (C) 2013 Codethink Limited.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribute... |
def service_url(self, name):
"""Look up the service URL for a service name and return it.
Raises an UnknownServiceError if no service with this name is
registered.
"""
if name in self.services:
return self.services[name]
else:
raise Unknow... | """Look up the schema URL for a schema name and return it.
Raises an UnknownSchemaError if no schema with this name is registered.
"""
if name in self.schemas:
return self.schemas[name]
else:
raise UnknownSchemaError(name) | identifier_body |
__init__.py | # Copyright (C) 2013 Codethink Limited.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribute... |
self.services.update(services)
def _collect_config_dirs(self):
config_dirs = []
if os.environ.get('XDG_CONFIG_HOME'):
config_dirs.append(os.environ.get('XDG_CONFIG_HOME'))
else:
if os.environ.get('HOME'):
config_dirs.append(
... | if not isinstance(key, basestring):
phase.error(RegisterFormatError(
filename,
'Service name "%s" is not a string' % key))
if not expressions.service_name.match(key):
phase.error(RegisterFormatErr... | conditional_block |
__init__.py | # Copyright (C) 2013 Codethink Limited.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribute... | (cls, dumper, register): # pragma: no cover
"""Return a YAML representation of a Register."""
return dumper.represent_mapping(
u'tag:yaml.org,2002:map', {
'schemas': register.schemas,
'services': register.services,
})
| to_yaml | identifier_name |
__init__.py | # Copyright (C) 2013 Codethink Limited.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribute... | 'Services are not specified as a dictionary'))
for key, val in services.iteritems():
if not isinstance(key, basestring):
phase.error(RegisterFormatError(
filename,
'Service name "... | services = data.get('services', {})
if not isinstance(services, dict):
phase.error(RegisterFormatError(
filename, | random_line_split |
list_item.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Layout for elements with a CSS `display` property of `list-item`. These elements consist of a
//! block and an... |
fn bubble_inline_sizes(&mut self) {
// The marker contributes no intrinsic inline-size, so…
self.block_flow.bubble_inline_sizes()
}
fn assign_inline_sizes(&mut self, shared_context: &SharedStyleContext) {
self.block_flow.assign_inline_sizes(shared_context);
let mut marker... | {
&self.block_flow
} | identifier_body |
list_item.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Layout for elements with a CSS `display` property of `list-item`. These elements consist of a
//! block and an... | mut self, state: &mut DisplayListBuildState) {
self.build_display_list_for_list_item(state);
}
fn collect_stacking_contexts(&mut self,
parent_id: StackingContextId,
contexts: &mut Vec<Box<StackingContext>>)
... | ild_display_list(& | identifier_name |
list_item.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Layout for elements with a CSS `display` property of `list-item`. These elements consist of a
//! block and an... | let flow_size = self.block_flow.base.position.size.to_physical(self.block_flow.base.writing_mode);
let relative_containing_block_size =
&self.block_flow.base.early_absolute_position_info.relative_containing_block_size;
for fragment in &self.marker_fragments {
overflow.un... | }
fn compute_overflow(&self) -> Overflow {
let mut overflow = self.block_flow.compute_overflow(); | random_line_split |
error.rs | use std::error::Error as StdError;
use std::ffi::OsString;
use std::fmt;
use std::io::Error as IoError;
use std::io::ErrorKind as IoErrorKind;
use std::path::StripPrefixError;
/// A list specifying general categories of fs_extra error.
#[derive(Debug)]
pub enum ErrorKind {
/// An entity was not found.
NotFound... |
}
impl StdError for Error {
fn description(&self) -> &str {
self.kind.as_str()
}
}
impl From<StripPrefixError> for Error {
fn from(err: StripPrefixError) -> Error {
Error::new(
ErrorKind::StripPrefix(err),
"StripPrefixError. Look inside for more details",
)
... | {
write!(f, "{}", self.message)
} | identifier_body |
error.rs | use std::error::Error as StdError;
use std::ffi::OsString;
use std::fmt;
use std::io::Error as IoError;
use std::io::ErrorKind as IoErrorKind;
use std::path::StripPrefixError;
/// A list specifying general categories of fs_extra error.
#[derive(Debug)]
pub enum ErrorKind {
/// An entity was not found.
NotFound... | StripPrefix(StripPrefixError),
/// Any OsString error.
OsString(OsString),
/// Any fs_extra error not part of this list.
Other,
}
impl ErrorKind {
fn as_str(&self) -> &str {
match *self {
ErrorKind::NotFound => "entity not found",
ErrorKind::PermissionDenied => "... | random_line_split | |
error.rs | use std::error::Error as StdError;
use std::ffi::OsString;
use std::fmt;
use std::io::Error as IoError;
use std::io::ErrorKind as IoErrorKind;
use std::path::StripPrefixError;
/// A list specifying general categories of fs_extra error.
#[derive(Debug)]
pub enum ErrorKind {
/// An entity was not found.
NotFound... | (kind: ErrorKind, message: &str) -> Error {
Error {
kind,
message: message.to_string(),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.message)
}
}
impl StdError for Error {
fn description(... | new | identifier_name |
webpack.dev.conf.js | var utils = require('./utils')
var webpack = require('webpack') | var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
baseWebpackConfig.entry[name... | var config = require('../config')
var merge = require('webpack-merge') | random_line_split |
big-file-performance.js | var wows = require('vows');
var assert = require('assert');
var XMLSerializer = require('xmldom').XMLSerializer;
var DOMParser = require('xmldom').DOMParser;
var DomJS = require("dom-js").DomJS;
try{
var Libxml = require('libxmljs');
}catch(e){
}
function xmldom(data){
console.time('xmldom');
var doc = new DOMParse... |
// Create a Test Suite
wows.describe('XML Node Parse').addBatch({
"big file parse":function(){
var fs = require('fs');
var path = require('path')
var data = fs.readFileSync(path.resolve(__dirname,'./test.xml'), 'ascii');
//data = "<?xml version=\"1.0\"?><xml><child> ![CDATA[v]] d &</child>\n</xml>"
c... | {
var c =parseInt(Math.random()*maxRandomAttr);
while(c--){
el.setAttribute('dynamic-attr'+c,c+new Array(c).join('.'));
}
var child = el.firstChild;
while(child){
if(child.nodeType == 1){
addAttributes(child)
}else if(child.nodeType == 4){//cdata
el.insertBefore(el.ownerDocument.createTextNode(child.da... | identifier_body |
big-file-performance.js | var wows = require('vows');
var assert = require('assert');
var XMLSerializer = require('xmldom').XMLSerializer;
var DOMParser = require('xmldom').DOMParser;
var DomJS = require("dom-js").DomJS;
try{
var Libxml = require('libxmljs');
}catch(e){
}
function xmldom(data){
console.time('xmldom');
var doc = new DOMParse... | }
var maxRandomAttr =parseInt(Math.random()*60);
console.log('maxRandomAttr',maxRandomAttr)
function addAttributes(el){
var c =parseInt(Math.random()*maxRandomAttr);
while(c--){
el.setAttribute('dynamic-attr'+c,c+new Array(c).join('.'));
}
var child = el.firstChild;
while(child){
if(child.nodeType == 1){
ad... | return doc | random_line_split |
big-file-performance.js | var wows = require('vows');
var assert = require('assert');
var XMLSerializer = require('xmldom').XMLSerializer;
var DOMParser = require('xmldom').DOMParser;
var DomJS = require("dom-js").DomJS;
try{
var Libxml = require('libxmljs');
}catch(e){
}
function xmldom(data){
console.time('xmldom');
var doc = new DOMParse... |
var child = el.firstChild;
while(child){
if(child.nodeType == 1){
addAttributes(child)
}else if(child.nodeType == 4){//cdata
el.insertBefore(el.ownerDocument.createTextNode(child.data),child);
el.removeChild(child);
}
child = child.nextSibling;
}
}
// Create a Test Suite
wows.describe('XML Node Par... | {
el.setAttribute('dynamic-attr'+c,c+new Array(c).join('.'));
} | conditional_block |
big-file-performance.js | var wows = require('vows');
var assert = require('assert');
var XMLSerializer = require('xmldom').XMLSerializer;
var DOMParser = require('xmldom').DOMParser;
var DomJS = require("dom-js").DomJS;
try{
var Libxml = require('libxmljs');
}catch(e){
}
function xmldom(data){
console.time('xmldom');
var doc = new DOMParse... | (el){
var c =parseInt(Math.random()*maxRandomAttr);
while(c--){
el.setAttribute('dynamic-attr'+c,c+new Array(c).join('.'));
}
var child = el.firstChild;
while(child){
if(child.nodeType == 1){
addAttributes(child)
}else if(child.nodeType == 4){//cdata
el.insertBefore(el.ownerDocument.createTextNode(chil... | addAttributes | identifier_name |
SpellUsable.tsx | import SPELLS from 'common/SPELLS';
import CoreSpellUsable from 'parser/shared/modules/SpellUsable';
import { CastEvent } from 'parser/core/Events';
class SpellUsable extends CoreSpellUsable {
static dependencies = {
...CoreSpellUsable.dependencies,
};
lastPotentialTriggerForRapidFireReset: CastEvent | null... |
beginCooldown(spellId: number, cooldownTriggerEvent: Object) {
if (spellId === SPELLS.RAPID_FIRE.id && this.selectedCombatant.hasTrait(SPELLS.SURGING_SHOTS.id)) {
if (this.isOnCooldown(spellId)) {
this.rapidFireResets += 1;
this.endCooldown(spellId, undefined, this.lastPotentialTriggerForR... | {
super.on_byPlayer_cast?.(event);
const spellId = event.ability.guid;
if (this.selectedCombatant.hasTrait(SPELLS.SURGING_SHOTS.id)) {
if (spellId === SPELLS.AIMED_SHOT.id) {
this.lastPotentialTriggerForRapidFireReset = event;
} else if (spellId === SPELLS.RAPID_FIRE.id) {
this.... | identifier_body |
SpellUsable.tsx | import SPELLS from 'common/SPELLS';
import CoreSpellUsable from 'parser/shared/modules/SpellUsable';
import { CastEvent } from 'parser/core/Events';
class SpellUsable extends CoreSpellUsable { | };
lastPotentialTriggerForRapidFireReset: CastEvent | null = null;
rapidFireResets = 0;
on_byPlayer_cast(event: CastEvent) {
super.on_byPlayer_cast?.(event);
const spellId = event.ability.guid;
if (this.selectedCombatant.hasTrait(SPELLS.SURGING_SHOTS.id)) {
if (spellId === SPELLS.AIMED_SHOT... | static dependencies = {
...CoreSpellUsable.dependencies, | random_line_split |
SpellUsable.tsx | import SPELLS from 'common/SPELLS';
import CoreSpellUsable from 'parser/shared/modules/SpellUsable';
import { CastEvent } from 'parser/core/Events';
class SpellUsable extends CoreSpellUsable {
static dependencies = {
...CoreSpellUsable.dependencies,
};
lastPotentialTriggerForRapidFireReset: CastEvent | null... | (spellId: number, cooldownTriggerEvent: Object) {
if (spellId === SPELLS.RAPID_FIRE.id && this.selectedCombatant.hasTrait(SPELLS.SURGING_SHOTS.id)) {
if (this.isOnCooldown(spellId)) {
this.rapidFireResets += 1;
this.endCooldown(spellId, undefined, this.lastPotentialTriggerForRapidFireReset ? t... | beginCooldown | identifier_name |
build.rs | //! Generate a module with a custom `#[path=...]` for each of the files in our
//! libclang version-specific test expectations so that they get their layout
//! tests run. We need to do this because cargo doesn't automatically detect
//! tests subdirectories.
use std::env;
use std::fs;
use std::io::Write;
use std::pat... | }
println!("cargo:rerun-if-changed={}", path.display());
let module_name: String = path
.display()
.to_string()
.chars()
.map(|c| match c {
'a'..='z' | 'A'..='Z' | '0'..='9' => c,
... | {
println!("cargo:rerun-if-changed=build.rs");
let mut test_string = String::new();
for dir in LIBCLANG_VERSION_DIRS {
let dir = Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap())
.join("tests")
.join(dir);
println!("cargo:rerun-if-changed={}", dir.display());
... | identifier_body |
build.rs | //! Generate a module with a custom `#[path=...]` for each of the files in our
//! libclang version-specific test expectations so that they get their layout
//! tests run. We need to do this because cargo doesn't automatically detect
//! tests subdirectories.
use std::env;
use std::fs;
use std::io::Write;
use std::pat... |
test_string.push_str(&format!(
r###"
#[path = "{}"]
mod {};
"###,
path.display(),
module_name,
));
}
}
let out_path = Path::new(&env::var_os("OUT_DIR").unwrap())
.join("libclang_version_specific_generated_tests.rs");
l... | .collect(); | random_line_split |
build.rs | //! Generate a module with a custom `#[path=...]` for each of the files in our
//! libclang version-specific test expectations so that they get their layout
//! tests run. We need to do this because cargo doesn't automatically detect
//! tests subdirectories.
use std::env;
use std::fs;
use std::io::Write;
use std::pat... | () {
println!("cargo:rerun-if-changed=build.rs");
let mut test_string = String::new();
for dir in LIBCLANG_VERSION_DIRS {
let dir = Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap())
.join("tests")
.join(dir);
println!("cargo:rerun-if-changed={}", dir.display()... | main | identifier_name |
app.service.ts | import { Injectable } from '@angular/core';
export type InternalStateType = {
[key: string]: any
}; | @Injectable()
export class AppState {
public _state: InternalStateType = { };
constructor() {};
// already return a clone of the current state
get state() {
return this._state = this._clone(this._state);
}
// never allow mutation
set state(value) {
throw new Error('do not mutate the `.state` dir... | random_line_split | |
app.service.ts | import { Injectable } from '@angular/core';
export type InternalStateType = {
[key: string]: any
};
@Injectable()
export class AppState {
public _state: InternalStateType = { };
constructor() {};
// already return a clone of the current state
get state() {
return this._state = this._clone(this._state)... | (prop?: any) {
// use our state getter for the clone
const state = this.state;
return state.hasOwnProperty(prop) ? state[prop] : state;
}
public set(prop: string, value: any) {
// internally mutate our state
return this._state[prop] = value;
}
private _clone(object: InternalStateType) {
... | get | identifier_name |
post.js | import React from "react"
import { Grid, Container, Label, Segment, Header} from 'semantic-ui-react'
import ContactForm from '../components/form'
import SiteNav from '../components/site-nav'
export default ({ data }) => {
const post = data.markdownRemark
return (
<div>
<SiteNav></SiteNav>
<Segment ... | }
}
}
` | src
}
}
} | random_line_split |
glyph.rs | ---+ | s = simple
/// | | | | |
/// | | +---+-------+ |
/// | | | |
/// | +-V-+-V-+ |
/// | detail_store: | d | d | |
/// | +---+---+ ... | self.advance_for_byte_range_slow_path(range, extra_word_spacing)
} | random_line_split | |
glyph.rs | (&self, flag: u32) -> bool {
(self.value & flag) != 0
}
}
// Stores data for a detailed glyph, in the case that several glyphs
// correspond to one character, or the glyph's data couldn't be packed.
#[derive(Clone, Debug, Copy, Deserialize, Serialize)]
struct DetailedGlyph {
id: GlyphId,
// glyph's... | has_flag | identifier_name | |
glyph.rs | let key = DetailedGlyphRecord {
entry_offset: entry_offset,
detail_offset: 0, // unused
};
let i = self.detail_lookup.binary_search(&key)
.expect("Invalid index not found in detailed glyph lookup table!");
assert!(i + (count as usize) <= self.detail_buffer.... | {
let glyph_is_compressible = is_simple_glyph_id(data.id) &&
is_simple_advance(data.advance) &&
data.offset == Point2D::zero() &&
data.cluster_start; // others are stored in detail buffer
debug_assert!(data.ligature_start); // can't compress ligature continu... | identifier_body | |
glyph.rs | {
(self.value & flag) != 0
}
}
// Stores data for a detailed glyph, in the case that several glyphs
// correspond to one character, or the glyph's data couldn't be packed.
#[derive(Clone, Debug, Copy, Deserialize, Serialize)]
struct DetailedGlyph {
id: GlyphId,
// glyph's advance, in the text's di... |
});
let mut sorted_records = mut_records;
mem::swap(&mut self.detail_lookup, &mut sorted_records);
self.lookup_is_sorted = true;
}
}
// This struct is used by GlyphStore clients to provide new glyph data.
// It should be allocated on the stack and passed by reference to GlyphStore... | {
Ordering::Greater
} | conditional_block |
flashx.py | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para flashx
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# ------------------------------------------------------------
import re
from core import logger
from core import jsunpac... |
def get_video_url(page_url, premium=False, user="", password="", video_password=""):
logger.info("pelisalacarta.servers.flashx url=" + page_url)
# Lo pide una vez
data = scrapertools.cache_page(page_url, headers=headers)
# Si salta aviso, se carga la pagina de comprobacion y luego la inicial
if "Y... | return True, ""
| random_line_split |
flashx.py | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para flashx
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# ------------------------------------------------------------
import re
from core import logger
from core import jsunpac... | (page_url, premium=False, user="", password="", video_password=""):
logger.info("pelisalacarta.servers.flashx url=" + page_url)
# Lo pide una vez
data = scrapertools.cache_page(page_url, headers=headers)
# Si salta aviso, se carga la pagina de comprobacion y luego la inicial
if "You try to access t... | get_video_url | identifier_name |
flashx.py | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para flashx
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# ------------------------------------------------------------
import re
from core import logger
from core import jsunpac... |
match = scrapertools.find_single_match(data, "<script type='text/javascript'>(.*?)</script>")
if match.startswith("eval"):
match = jsunpack.unpack(match)
# Extrae la URL
# {file:"http://f11-play.flashx.tv/luq4gfc7gxixexzw6v4lhz4xqslgqmqku7gxjf4bk43u4qvwzsadrjsozxoa/video1.mp4"}
video_url... | url_reload = scrapertools.find_single_match(data, 'try to reload the page.*?href="([^"]+)"')
data = scrapertools.cache_page(url_reload, headers=headers)
data = scrapertools.cache_page(page_url, headers=headers) | conditional_block |
flashx.py | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para flashx
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# ------------------------------------------------------------
import re
from core import logger
from core import jsunpac... |
def get_video_url(page_url, premium=False, user="", password="", video_password=""):
logger.info("pelisalacarta.servers.flashx url=" + page_url)
# Lo pide una vez
data = scrapertools.cache_page(page_url, headers=headers)
# Si salta aviso, se carga la pagina de comprobacion y luego la inicial
if ... | logger.info("pelisalacarta.servers.flashx test_video_exists(page_url='%s')" % page_url)
data = scrapertools.cache_page(page_url, headers=headers)
if 'FILE NOT FOUND' in data:
return False, "[FlashX] El archivo no existe o ha sido borrado"
return True, "" | identifier_body |
plugin.py |
# fields" as defined by plugin.yaml. For plugins that don't define
# cacheable fields, there is no cache dir (it's set to /dev/null) and
# the cache lock is a no-op.
stack.enter_context((yield from _plugin_cache_lock(
plugin_context, definition, module_fields)))
# U... | pass | identifier_body | |
plugin.py | env, display_handle)
@asyncio.coroutine
def plugin_get_reup_fields(plugin_context, module_type, module_fields,
display_handle):
with tmp_dir(plugin_context) as output_file_dir:
output_path = os.path.join(output_file_dir, 'reup_output')
env = {'PERU_REUP_OUTPUT': output_... |
if not isinstance(value, str):
raise PluginModuleFieldError(
'reup field value must be a string: {}'.format(value))
return fields
@asyncio.coroutine
def _plugin_job(plugin_context, module_type, module_fields, command, env,
display_handle):
# We take severa... | raise PluginModuleFieldError(
'reup field name must be a string: {}'.format(key)) | conditional_block |
plugin.py | # lock (and the cache dir) are both keyed off the module's "cache
# fields" as defined by plugin.yaml. For plugins that don't define
# cacheable fields, there is no cache dir (it's set to /dev/null) and
# the cache lock is a no-op.
stack.enter_context((yield from _plugin_cache_lock(
... | PluginCandidateError | identifier_name | |
plugin.py | env, display_handle)
@asyncio.coroutine
def plugin_get_reup_fields(plugin_context, module_type, module_fields,
display_handle):
with tmp_dir(plugin_context) as output_file_dir:
output_path = os.path.join(output_file_dir, 'reup_output')
env = {'... | raise PluginCandidateError(
'No plugin found for `{}` module | for install_dir in _get_plugin_install_dirs():
candidate = os.path.join(install_dir, module_type)
if os.path.isdir(candidate):
return candidate
else: | random_line_split |
event.js | /*!
* @version 1.0.0
* @package Perfect Decorations For Occasions
* @copyright © 2015 Perfect Web sp. z o.o., All rights reserved. http://www.perfect-web.co
* @license GNU/GPL http://www.gnu.org/licenses/gpl-3.0.html
* @author Mateusz Podraza
*/
DFOEvent = (function ($) {
function Event() { | if(effect_count < 1){
return; //An event with no effects? Weird.
}
for (var i = 0; i < effect_count; i++) {
var effect = event_data.effects[i];
// switch (parseInt(effect.type)) {
// case 1:
// /... |
//Private
var _assetPath = '',
_isShown = false,
_isValid = false;
//Public
this.name = this.description = '';
this.effects = [];
this.parse = function (event_data) {
if (!event_data) {
return; //Guard case, no event
... | identifier_body |
event.js | /*!
* @version 1.0.0
* @package Perfect Decorations For Occasions
* @copyright © 2015 Perfect Web sp. z o.o., All rights reserved. http://www.perfect-web.co
* @license GNU/GPL http://www.gnu.org/licenses/gpl-3.0.html
* @author Mateusz Podraza
*/
DFOEvent = (function ($) {
function E | ) {
//Private
var _assetPath = '',
_isShown = false,
_isValid = false;
//Public
this.name = this.description = '';
this.effects = [];
this.parse = function (event_data) {
if (!event_data) {
return; //Guard case, no even... | vent( | identifier_name |
event.js | /*!
* @version 1.0.0
* @package Perfect Decorations For Occasions
* @copyright © 2015 Perfect Web sp. z o.o., All rights reserved. http://www.perfect-web.co
* @license GNU/GPL http://www.gnu.org/licenses/gpl-3.0.html
* @author Mateusz Podraza
*/
DFOEvent = (function ($) {
function Event() {
//Private
... | //A bit dumb, but oh well:
this.name = event_data.name;
this.description = event_data.description;
//Absolute URL to the feeds folder
_assetPath = event_data.path;
//Tmp variable
var effect_count = event_data.effects.length;
... |
return; //Guard case, no event
}
| conditional_block |
event.js | /*!
* @version 1.0.0
* @package Perfect Decorations For Occasions
* @copyright © 2015 Perfect Web sp. z o.o., All rights reserved. http://www.perfect-web.co
* @license GNU/GPL http://www.gnu.org/licenses/gpl-3.0.html
* @author Mateusz Podraza
*/
DFOEvent = (function ($) {
function Event() {
//Private
... | // case 4:
// //JS
// var item = new DFOCustomJSEffect();
// break;
// case 5:
// //CSS
// var item = new DFOCustomCSSEffect();
// break;
// ... | // break; | random_line_split |
recolor.rs | use {RendTri, Shape, Color};
/// `Recolor` represents a shape which has had its color set to a new one.
#[derive(Copy, Clone, Debug)]
pub struct Recolor<S> {
shape: S,
color: Color,
}
impl<S> Recolor<S> {
pub(crate) fn new(shape: S, color: Color) -> Self |
}
impl<S> IntoIterator for Recolor<S>
where
S: Shape,
{
type Item = RendTri;
type IntoIter = RecolorIter<S::IntoIter>;
fn into_iter(self) -> Self::IntoIter {
RecolorIter {
iter: self.shape.into_iter(),
color: self.color,
}
}
}
/// Iterator which is produce... | {
Recolor {
shape: shape,
color: color,
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.