file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
mongo_cache.py | # -*- encoding:utf8 -*-
"""
使用mongodb作为缓存器
测试本地缓存
"""
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import json
from pymongo import MongoClient
from datetime import datetime, timedelta
from bson.binary import Binary
import zlib
import time
class MongoCache:
def __init__(self, client=None, expires=timedelt... | except KeyError:
return False
else:
return True
def __getitem__(self, url):
result = self.db.webpage.find_one({'_id': url})
if result:
result['html'] = zlib.decompress(result['html'])
return result
else:
raise KeyError(ur... | [url]
| identifier_name |
mongo_cache.py | # -*- encoding:utf8 -*-
"""
使用mongodb作为缓存器
测试本地缓存
"""
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import json
from pymongo import MongoClient
from datetime import datetime, timedelta
from bson.binary import Binary
import zlib
import time
class MongoCache:
def __init__(self, client=None, expires=timedelt... | f.db.webpage.find_one({'_id': url})
if result:
result['html'] = zlib.decompress(result['html'])
return result
else:
raise KeyError(url + 'does not exists')
pass
def __setitem__(self, url, result):
result['html'] = Binary(zlib.compress(result['html... | return False
else:
return True
def __getitem__(self, url):
result = sel | identifier_body |
cellulant_sms.py | # -*- test-case-name: vumi.transports.cellulant.tests.test_cellulant_sms -*-
import json
from urllib import urlencode
from twisted.internet.defer import inlineCallbacks
from vumi.utils import http_request_full
from vumi import log
from vumi.config import ConfigDict, ConfigText
from vumi.transports.httprpc import Htt... |
@inlineCallbacks
def handle_raw_inbound_message(self, message_id, request):
values, errors = self.get_field_values(request, self.EXPECTED_FIELDS,
self.IGNORED_FIELDS)
if errors:
log.msg('Unhappy incoming message: %s' % (errors,))
... | creds = self._credentials.get(message['from_addr'], {})
username = creds.get('username', '')
password = creds.get('password', '')
params = {
'username': username,
'password': password,
'source': message['from_addr'],
'destination': message['to_addr... | identifier_body |
cellulant_sms.py | # -*- test-case-name: vumi.transports.cellulant.tests.test_cellulant_sms -*-
import json
from urllib import urlencode
from twisted.internet.defer import inlineCallbacks
from vumi.utils import http_request_full
from vumi import log
from vumi.config import ConfigDict, ConfigText
from vumi.transports.httprpc import Htt... |
else:
error = self.KNOWN_ERROR_RESPONSE_CODES.get(content,
'Unknown response code: %s' % (content,))
yield self.publish_nack(message['message_id'], error)
@inlineCallbacks
def handle_raw_inbound_message(self, message_id, request):
values, errors = self.g... | yield self.publish_ack(user_message_id=message['message_id'],
sent_message_id=message['message_id']) | conditional_block |
cellulant_sms.py | # -*- test-case-name: vumi.transports.cellulant.tests.test_cellulant_sms -*-
import json
from urllib import urlencode
from twisted.internet.defer import inlineCallbacks
from vumi.utils import http_request_full
from vumi import log
from vumi.config import ConfigDict, ConfigText
from vumi.transports.httprpc import Htt... | (self, message):
creds = self._credentials.get(message['from_addr'], {})
username = creds.get('username', '')
password = creds.get('password', '')
params = {
'username': username,
'password': password,
'source': message['from_addr'],
'desti... | handle_outbound_message | identifier_name |
cellulant_sms.py | # -*- test-case-name: vumi.transports.cellulant.tests.test_cellulant_sms -*-
import json
from urllib import urlencode
from twisted.internet.defer import inlineCallbacks
from vumi.utils import http_request_full
from vumi import log
from vumi.config import ConfigDict, ConfigText
from vumi.transports.httprpc import Htt... | transport_type=self.transport_type,
transport_metadata={'transport_message_id': values['ID']},
)
yield self.finish_request(
message_id, json.dumps({'message_id': message_id})) | to_addr=values['DESTADDR'],
from_addr=values['SOURCEADDR'],
provider='vumi', | random_line_split |
pac.wan.default.js | function | (url,host){
if (isPlainHostName(host))
return "DIRECT";
var r = /(^|\.)(local(\.)?|mydomain\.com|mydomain\.net|apple\.com|icloud\.com|mzstatic\.com|googlevideo\.com)$/i;
if (r.test(host))
return "DIRECT";
var ip = dnsResolve(host);
if (isInNet(ip,"10.0.0.0","255.0.0.0")||isInNet(ip,"127.0.0.0","255.0.0.0")||is... | FindProxyForURL | identifier_name |
pac.wan.default.js | function FindProxyForURL(url,host){
if (isPlainHostName(host))
return "DIRECT";
var r = /(^|\.)(local(\.)?|mydomain\.com|mydomain\.net|apple\.com|icloud\.com|mzstatic\.com|googlevideo\.com)$/i;
if (r.test(host))
return "DIRECT";
var ip = dnsResolve(host);
if (isInNet(ip,"10.0.0.0","255.0.0.0")||isInNet(ip,"127... |
return "PROXY proxy.mydomain.net:{PORT}";
} | {
return "DIRECT";
} | conditional_block |
pac.wan.default.js | function FindProxyForURL(url,host) | {
if (isPlainHostName(host))
return "DIRECT";
var r = /(^|\.)(local(\.)?|mydomain\.com|mydomain\.net|apple\.com|icloud\.com|mzstatic\.com|googlevideo\.com)$/i;
if (r.test(host))
return "DIRECT";
var ip = dnsResolve(host);
if (isInNet(ip,"10.0.0.0","255.0.0.0")||isInNet(ip,"127.0.0.0","255.0.0.0")||isInNet(ip,"... | identifier_body | |
formatparse.ts | import {FormulaTransform as VgFormulaTransform, SignalRef} from 'vega';
import {isNumber, isString} from 'vega-util';
import {AncestorParse} from '.';
import {isMinMaxOp} from '../../aggregate';
import {getMainRangeChannel, SingleDefChannel} from '../../channel';
import {
isFieldDef,
isFieldOrDatumDefForTimeFormat,... |
public assembleTransforms(onlyNested = false): VgFormulaTransform[] {
return keys(this._parse)
.filter(field => (onlyNested ? accessPathDepth(field) > 1 : true))
.map(field => {
const expr = parseExpression(field, this._parse[field]);
if (!expr) {
return null;
}
... | {
return new Set(keys(this._parse));
} | identifier_body |
formatparse.ts | import {FormulaTransform as VgFormulaTransform, SignalRef} from 'vega';
import {isNumber, isString} from 'vega-util';
import {AncestorParse} from '.';
import {isMinMaxOp} from '../../aggregate';
import {getMainRangeChannel, SingleDefChannel} from '../../channel';
import {
isFieldDef,
isFieldOrDatumDefForTimeFormat,... | // copy only non-null parses
const p: Dict<string> = {};
for (const key of keys(parse.combine())) {
const val = parse.get(key);
if (val !== null) {
p[key] = val;
}
}
if (keys(p).length === 0 || ancestorParse.parseNothing) {
return null;
}
return new ParseNod... | // add the format parse from this model so that children don't parse the same field again
ancestorParse.copyAll(parse);
| random_line_split |
formatparse.ts | import {FormulaTransform as VgFormulaTransform, SignalRef} from 'vega';
import {isNumber, isString} from 'vega-util';
import {AncestorParse} from '.';
import {isMinMaxOp} from '../../aggregate';
import {getMainRangeChannel, SingleDefChannel} from '../../channel';
import {
isFieldDef,
isFieldOrDatumDefForTimeFormat,... | (fieldDef: TypedFieldDef<string>) {
if (isFieldOrDatumDefForTimeFormat(fieldDef)) {
implicit[fieldDef.field] = 'date';
} else if (
fieldDef.type === 'quantitative' &&
isMinMaxOp(fieldDef.aggregate) // we need to parse numbers to support correct min and max
) {
implicit[fieldDef.field... | add | identifier_name |
mod.rs | use super::core::{
af_array, af_features, dim_t, AfError, Array, HasAfEnum, HomographyType, ImageFilterType,
MatchType, RealFloating, HANDLE_ERROR,
};
use libc::{c_float, c_int, c_uint};
use std::mem;
// af_sift and af_gloh uses patented algorithms, so didn't add them
// they are NOT built using installer bui... | thr: c_float,
arc_len: c_uint,
non_max: bool,
feature_ratio: c_float,
edge: c_uint,
) -> c_int;
fn af_harris(
out: *mut af_features,
input: af_array,
m: c_uint,
r: c_float,
s: c_float,
bs: c_uint,
k: c_float,
) ... | fn af_release_features(feat: af_features) -> c_int;
fn af_fast(
out: *mut af_features,
input: af_array, | random_line_split |
mod.rs | use super::core::{
af_array, af_features, dim_t, AfError, Array, HasAfEnum, HomographyType, ImageFilterType,
MatchType, RealFloating, HANDLE_ERROR,
};
use libc::{c_float, c_int, c_uint};
use std::mem;
// af_sift and af_gloh uses patented algorithms, so didn't add them
// they are NOT built using installer bui... |
/// SUSAN corner detector.
///
/// SUSAN is an acronym standing for Smallest Univalue Segment Assimilating Nucleus. This method
/// places a circular disc over the pixel to be tested (a.k.a nucleus) to compute the corner
/// measure of that corresponding pixel. The region covered by the circular disc is M, and a pixe... | {
unsafe {
let mut temp: af_array = std::ptr::null_mut();
let err_val = af_match_template(
&mut temp as *mut af_array,
search_img.get(),
template_img.get(),
mtype as c_uint,
);
HANDLE_ERROR(AfError::from(err_val));
temp.into()
... | identifier_body |
mod.rs | use super::core::{
af_array, af_features, dim_t, AfError, Array, HasAfEnum, HomographyType, ImageFilterType,
MatchType, RealFloating, HANDLE_ERROR,
};
use libc::{c_float, c_int, c_uint};
use std::mem;
// af_sift and af_gloh uses patented algorithms, so didn't add them
// they are NOT built using installer bui... | <T>(
input: &Array<T>,
thr: f32,
arc_len: u32,
non_max: bool,
feat_ratio: f32,
edge: u32,
) -> Features
where
T: HasAfEnum + ImageFilterType,
{
unsafe {
let mut temp: af_features = std::ptr::null_mut();
let err_val = af_fast(
&mut temp as *mut af_features,
... | fast | identifier_name |
decode_properties.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
//! Base types used by various rocks properties decoders
use std::collections::BTreeMap;
use std::io::Read;
use std::ops::{Deref, DerefMut};
use tikv_util::codec::number::{self, NumberEncoder};
use tikv_util::codec::Result;
#[derive(Clone, Debug, Def... | fn decode_handles(&self, k: &str) -> Result<IndexHandles> {
let buf = self.decode(k)?;
IndexHandles::decode(buf)
}
}
impl DecodeProperties for rocksdb::UserCollectedProperties {
fn decode(&self, k: &str) -> tikv_util::codec::Result<&[u8]> {
self.get(k.as_bytes())
.ok_or(... | random_line_split | |
decode_properties.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
//! Base types used by various rocks properties decoders
use std::collections::BTreeMap;
use std::io::Read;
use std::ops::{Deref, DerefMut};
use tikv_util::codec::number::{self, NumberEncoder};
use tikv_util::codec::Result;
#[derive(Clone, Debug, Def... | (&mut self) -> &mut BTreeMap<Vec<u8>, IndexHandle> {
&mut self.0
}
}
impl IndexHandles {
pub fn new() -> IndexHandles {
IndexHandles(BTreeMap::new())
}
pub fn into_map(self) -> BTreeMap<Vec<u8>, IndexHandle> {
self.0
}
pub fn add(&mut self, key: Vec<u8>, index_handle: ... | deref_mut | identifier_name |
MathML.js | /*
* /MathJax/localization/it/MathML.js
*
* Copyright (c) 2009-2015 The MathJax Consortium
*
* 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
* | * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Localization.addTranslation( "it", "MathML", {
ve... | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software | random_line_split |
UserEdit.js | import { connect } from 'react-redux'
import { compose } from 'redux'
import { reduxForm } from 'redux-form'
import schema from '@schemas/signUp'
import validator from '@helpers/validator'
import UserEditForm from '@routes/UserSettingsPage/components/UserEditForm'
import * as authActions from '@modules/auth/actions'
c... | reduxForm({
form: 'UserEditForm',
enableReinitialize: true,
validate,
}),
)(UserEditForm) | random_line_split | |
UserEdit.js | import { connect } from 'react-redux'
import { compose } from 'redux'
import { reduxForm } from 'redux-form'
import schema from '@schemas/signUp'
import validator from '@helpers/validator'
import UserEditForm from '@routes/UserSettingsPage/components/UserEditForm'
import * as authActions from '@modules/auth/actions'
c... | ,
})
const mapStateToProps = state => ({
authError: state.auth.get('error'),
initialValues: {
email: state.auth.get('user') ? state.auth.get('user').email : '',
username: state.auth.get('user') ? state.auth.get('user').username : '',
name: state.auth.get('user') ? state.auth.get('user').name : '',
... | {
dispatch(authActions.clearAuthErrors())
} | identifier_body |
UserEdit.js | import { connect } from 'react-redux'
import { compose } from 'redux'
import { reduxForm } from 'redux-form'
import schema from '@schemas/signUp'
import validator from '@helpers/validator'
import UserEditForm from '@routes/UserSettingsPage/components/UserEditForm'
import * as authActions from '@modules/auth/actions'
c... | () {
dispatch(authActions.clearAuthErrors())
},
})
const mapStateToProps = state => ({
authError: state.auth.get('error'),
initialValues: {
email: state.auth.get('user') ? state.auth.get('user').email : '',
username: state.auth.get('user') ? state.auth.get('user').username : '',
name: state.auth.... | clearError | identifier_name |
8.py | import random
CHOICES = {1: 'Rock', 2: 'Paper', 3: 'Scissors'}
RESULTS = [[0, -1, 1], [1, 0, -1], [-1, 1, 0]]
def ask():
while True:
s = input('Let\'s play the game:\n\t1. Rock\n\t2. Paper\n\t3. Scissors?\nWhat you choose?: ')
if s.isdigit():
c = int(s)
if not (1 <= c <= 3)... |
def another():
while True:
ans = input('Another round? y/n: ')
if ans == 'y':
return True
elif ans == 'n':
return False
else:
print('Invalid input, try again!')
continue
if __name__ == '__main__':
while True:
c = ask()
... | r = RESULTS[c-1][s-1]
if r == 0:
print('HaHa, no one wins!')
elif r == -1:
print('You\'re %s, I\'m %s, I win!' % (CHOICES[c], CHOICES[s]))
else:
print('You\'re %s, I\'m %s, You win!' % (CHOICES[c], CHOICES[s])) | identifier_body |
8.py | import random
CHOICES = {1: 'Rock', 2: 'Paper', 3: 'Scissors'}
RESULTS = [[0, -1, 1], [1, 0, -1], [-1, 1, 0]]
def ask():
while True:
s = input('Let\'s play the game:\n\t1. Rock\n\t2. Paper\n\t3. Scissors?\nWhat you choose?: ')
if s.isdigit():
c = int(s)
if not (1 <= c <= 3)... | print('HaHa, no one wins!')
elif r == -1:
print('You\'re %s, I\'m %s, I win!' % (CHOICES[c], CHOICES[s]))
else:
print('You\'re %s, I\'m %s, You win!' % (CHOICES[c], CHOICES[s]))
def another():
while True:
ans = input('Another round? y/n: ')
if ans == 'y':
... |
def compete(c, s):
r = RESULTS[c-1][s-1]
if r == 0: | random_line_split |
8.py | import random
CHOICES = {1: 'Rock', 2: 'Paper', 3: 'Scissors'}
RESULTS = [[0, -1, 1], [1, 0, -1], [-1, 1, 0]]
def | ():
while True:
s = input('Let\'s play the game:\n\t1. Rock\n\t2. Paper\n\t3. Scissors?\nWhat you choose?: ')
if s.isdigit():
c = int(s)
if not (1 <= c <= 3):
print('Invalid input, please re-select again!')
continue
else:
pr... | ask | identifier_name |
8.py | import random
CHOICES = {1: 'Rock', 2: 'Paper', 3: 'Scissors'}
RESULTS = [[0, -1, 1], [1, 0, -1], [-1, 1, 0]]
def ask():
while True:
s = input('Let\'s play the game:\n\t1. Rock\n\t2. Paper\n\t3. Scissors?\nWhat you choose?: ')
if s.isdigit():
c = int(s)
if not (1 <= c <= 3)... |
if __name__ == '__main__':
while True:
c = ask()
a = ai()
compete(c, a)
if not another():
break
| ans = input('Another round? y/n: ')
if ans == 'y':
return True
elif ans == 'n':
return False
else:
print('Invalid input, try again!')
continue | conditional_block |
knowledge.rs | use std::collections::BTreeMap;
use game::*;
use spatial_hash::*;
use coord::Coord;
use util::TwoDimensionalCons;
/// Trait implemented by representations of knowledge about a level
pub trait LevelKnowledge {
/// Updates a cell of the knowledge representation, returnig true iff the
/// knowledge of the cell c... | (&mut self, level_id: LevelId,
width: usize, height: usize) -> &mut K {
self.levels.entry(level_id).or_insert_with(|| K::new(width, height))
}
}
| level_mut_or_insert_size | identifier_name |
knowledge.rs | use std::collections::BTreeMap;
use game::*;
use spatial_hash::*;
use coord::Coord;
use util::TwoDimensionalCons;
/// Trait implemented by representations of knowledge about a level
pub trait LevelKnowledge {
/// Updates a cell of the knowledge representation, returnig true iff the
/// knowledge of the cell c... | self.levels.entry(level_id).or_insert_with(|| K::new(width, height))
}
} | impl<K: LevelKnowledge + TwoDimensionalCons> GameKnowledge<K> {
pub fn level_mut_or_insert_size(&mut self, level_id: LevelId,
width: usize, height: usize) -> &mut K { | random_line_split |
knowledge.rs | use std::collections::BTreeMap;
use game::*;
use spatial_hash::*;
use coord::Coord;
use util::TwoDimensionalCons;
/// Trait implemented by representations of knowledge about a level
pub trait LevelKnowledge {
/// Updates a cell of the knowledge representation, returnig true iff the
/// knowledge of the cell c... |
}
impl<K: LevelKnowledge + Default> Default for GameKnowledge<K> {
fn default() -> Self {
Self::new()
}
}
impl<K: LevelKnowledge + TwoDimensionalCons> GameKnowledge<K> {
pub fn level_mut_or_insert_size(&mut self, level_id: LevelId,
width: usize, height: usize) ... | {
self.levels.get_mut(&level_id).expect("No such level")
} | identifier_body |
johnny-cache.js | "use strict";
/*globals window, document, $, jQuery */
(function ($) {
var instance_store, refr, current, slctr;
function remove_group(el) {
return function () {
el.closest('tr').fadeOut().remove();
};
}
function remove_item(el) {
return function () {
... | keys.push($(this).attr('data-key'));
});
$.ajax({
url : elem.attr('href'),
type : 'post',
data : {
keys: keys
},
success : remove_group(elem)
})... | random_line_split | |
johnny-cache.js | "use strict";
/*globals window, document, $, jQuery */
(function ($) {
var instance_store, refr, current, slctr;
function remove_group(el) {
return function () {
el.closest('tr').fadeOut().remove();
};
}
function remove_item(el) {
return function () {
... |
$(document).ready(function () {
instance_store = $('#instance-store');
refr = $('#refresh-instance');
slctr = $('#instance-selector');
refr.click(function () {
slctr.trigger('change');
return false;
});
slctr.bind('change', ... | {
instance_store.html(data);
refr.show();
} | identifier_body |
johnny-cache.js | "use strict";
/*globals window, document, $, jQuery */
(function ($) {
var instance_store, refr, current, slctr;
function remove_group(el) {
return function () {
el.closest('tr').fadeOut().remove();
};
}
function remove_item(el) {
return function () {
... |
});
$('.jc-flush-group').live('click', function () {
var elem = $(this), keys = [];
elem.parents('td').next().find('p').each(function () {
keys.push($(this).attr('data-key'));
});
$.ajax({
... | {
var elem = $(this);
$.ajax({
url : '/wp-admin/admin-ajax.php',
data : {
action : 'jc-get-instance',
nonce : elem.attr('data-nonce'),
name : val
... | conditional_block |
johnny-cache.js | "use strict";
/*globals window, document, $, jQuery */
(function ($) {
var instance_store, refr, current, slctr;
function remove_group(el) {
return function () {
el.closest('tr').fadeOut().remove();
};
}
function remove_item(el) {
return function () {
... | (data) {
instance_store.html(data);
refr.show();
}
$(document).ready(function () {
instance_store = $('#instance-store');
refr = $('#refresh-instance');
slctr = $('#instance-selector');
refr.click(function () {
slctr.trigger('change');
... | add_instance | identifier_name |
user_routes_test.js | 'use strict';
var chai = require('chai');
var chaiHttp = require('chai-http');
chai.use(chaiHttp);
var expect = chai.expect;
process.env.MONGO_URL = 'mongodb://localhost/user_test';
require(__dirname + '/../server');
var mongoose = require('mongoose');
var User = require(__dirname + '/../models/user');
var host = 'loc... | }); | done();
});
}); | random_line_split |
ojrunnerlinux.py | import lorun
import os
import codecs
import random
import subprocess
import config
import sys
RESULT_MAP = [
2, 10, 5, 4, 3, 6, 11, 7, 12
]
class Runner:
def __init__(self):
return
def compile(self, judger, srcPath, outPath):
cmd = config.langCompile[judger.lang] % {'root': sys.path[0], '... |
return (RESULT_MAP[rst['result']], 0, 0)
| fans = open(ansFile, 'rU')
fout = open(fout_path, 'rU')
crst = lorun.check(fans.fileno(), fout.fileno())
fout.close()
fans.close()
return (RESULT_MAP[crst], int(rst['memoryused']), int(rst['timeused'])) | conditional_block |
ojrunnerlinux.py | import lorun
import os
import codecs
import random
import subprocess
import config
import sys
RESULT_MAP = [
2, 10, 5, 4, 3, 6, 11, 7, 12
]
class | :
def __init__(self):
return
def compile(self, judger, srcPath, outPath):
cmd = config.langCompile[judger.lang] % {'root': sys.path[0], 'src': srcPath, 'target': outPath}
p = subprocess.Popen(cmd, shell = True,
stdout = subprocess.PIPE, stdin = subprocess.PIPE, stderr = subpro... | Runner | identifier_name |
ojrunnerlinux.py | import lorun
import os
import codecs
import random
import subprocess
import config
import sys
RESULT_MAP = [
2, 10, 5, 4, 3, 6, 11, 7, 12
]
class Runner:
def __init__(self):
|
def compile(self, judger, srcPath, outPath):
cmd = config.langCompile[judger.lang] % {'root': sys.path[0], 'src': srcPath, 'target': outPath}
p = subprocess.Popen(cmd, shell = True,
stdout = subprocess.PIPE, stdin = subprocess.PIPE, stderr = subprocess.STDOUT)
retval = p.wait()
... | return | identifier_body |
ojrunnerlinux.py | import lorun
import os
import codecs
import random
import subprocess
import config
import sys
RESULT_MAP = [
2, 10, 5, 4, 3, 6, 11, 7, 12
]
class Runner:
def __init__(self):
return
def compile(self, judger, srcPath, outPath):
cmd = config.langCompile[judger.lang] % {'root': sys.path[0], '... | 'timelimit': int(timelimit),
'memorylimit': int(memlimit)
}
rst = lorun.run(runcfg)
fin.close()
fout.close()
if rst['result'] == 0:
fans = open(ansFile, 'rU')
fout = open(fout_path, 'rU')
crst = lorun.check(fans.fileno... | 'fd_in': fin.fileno(),
'fd_out': fout.fileno(), | random_line_split |
ad-unit-test.js | /*global describe before it*/ | var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
var expect = chai.expect;
var Dfp = require('../index');
var DFP_CREDS = require('../fixtures/setup/application-creds');
var config = require('../fixtures/setup/config');
var credentials;
// Override with local configs if recording
if (proc... |
'use strict';
var Replay = require('replay'); //eslint-disable-line no-unused-vars | random_line_split |
ad-unit-test.js | /*global describe before it*/
'use strict';
var Replay = require('replay'); //eslint-disable-line no-unused-vars
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
var expect = chai.expect;
var Dfp = require('../index');
var DFP_CREDS = require('../fixtures/setup/application-creds');
var c... |
credentials = {
clientId: DFP_CREDS.installed.client_id,
clientSecret: DFP_CREDS.installed.client_secret,
redirectUrl: DFP_CREDS.installed.redirect_uris[0]
};
chai.use(chaiAsPromised);
describe('Ad Unit Methods', function() {
var dfp;
before(function() {
dfp = new Dfp(credentials, config, config.ref... | { //eslint-disable-line no-process-env
DFP_CREDS = require('../local/application-creds');
config = require('../local/config');
} | conditional_block |
chimp-config.js | // import path from 'path';
// import {isCI} from '../lib/ci';
module.exports = {
// // - - - - CHIMP - - - -
// watch: false,
// watchTags: '@watch,@focus',
// domainSteps: null,
// e2eSteps: null,
// fullDomain: false,
// domainOnly: false,
// e2eTags: '@e2e',
// watchWithPolling: false,
// server: false,
... | // },
// // - - - - SELENIUM-STANDALONE
// seleniumStandaloneOptions: {
// // check for more recent versions of selenium here:
// // http://selenium-release.storage.googleapis.com/index.html
// version: '2.53.1',
// baseURL: 'https://selenium-release.storage.googleapis.com',
// drivers: {
// chrome: {
... | // baseUrl: null,
// coloredLogs: true,
// screenshotPath: null,
// waitforTimeout: 500,
// waitforInterval: 250, | random_line_split |
no_1109_corporate_flight_bookings.rs | pub fn corp_flight_bookings(bookings: Vec<Vec<i32>>, n: i32) -> Vec<i32> {
let mut answer = vec![0; n as usize];
for booking in bookings {
answer[booking[0] as usize - 1] += booking[2];
if booking[1] < n {
answer[booking[1] as usize] -= booking[2];
}
}
let mut sum =... |
answer
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_corp_flight_bookings() {
let answer = corp_flight_bookings(vec![vec![1, 2, 10], vec![2, 3, 20], vec![2, 5, 25]], 5);
assert_eq!(answer, vec![10, 55, 45, 25, 25]);
}
} | random_line_split | |
no_1109_corporate_flight_bookings.rs | pub fn corp_flight_bookings(bookings: Vec<Vec<i32>>, n: i32) -> Vec<i32> {
let mut answer = vec![0; n as usize];
for booking in bookings {
answer[booking[0] as usize - 1] += booking[2];
if booking[1] < n {
answer[booking[1] as usize] -= booking[2];
}
}
let mut sum =... | () {
let answer = corp_flight_bookings(vec![vec![1, 2, 10], vec![2, 3, 20], vec![2, 5, 25]], 5);
assert_eq!(answer, vec![10, 55, 45, 25, 25]);
}
}
| test_corp_flight_bookings | identifier_name |
no_1109_corporate_flight_bookings.rs | pub fn corp_flight_bookings(bookings: Vec<Vec<i32>>, n: i32) -> Vec<i32> {
let mut answer = vec![0; n as usize];
for booking in bookings {
answer[booking[0] as usize - 1] += booking[2];
if booking[1] < n |
}
let mut sum = 0;
for a in answer.iter_mut() {
sum += *a;
*a = sum;
}
answer
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_corp_flight_bookings() {
let answer = corp_flight_bookings(vec![vec![1, 2, 10], vec![2, 3, 20], vec![2, 5, 25]], 5);
... | {
answer[booking[1] as usize] -= booking[2];
} | conditional_block |
no_1109_corporate_flight_bookings.rs | pub fn corp_flight_bookings(bookings: Vec<Vec<i32>>, n: i32) -> Vec<i32> |
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_corp_flight_bookings() {
let answer = corp_flight_bookings(vec![vec![1, 2, 10], vec![2, 3, 20], vec![2, 5, 25]], 5);
assert_eq!(answer, vec![10, 55, 45, 25, 25]);
}
}
| {
let mut answer = vec![0; n as usize];
for booking in bookings {
answer[booking[0] as usize - 1] += booking[2];
if booking[1] < n {
answer[booking[1] as usize] -= booking[2];
}
}
let mut sum = 0;
for a in answer.iter_mut() {
sum += *a;
*a = sum;... | identifier_body |
ARCComputingElement.py | ########################################################################
# File : ARCComputingElement.py
# Author : A.T.
########################################################################
""" ARC Computing Element
"""
__RCSID__ = "58c42fc (2013-07-07 22:54:57 +0200) Andrei Tsaregorodtsev <atsareg@in2p3.fr>"
... | MANDATORY_PARAMETERS = [ 'Queue' ]
class ARCComputingElement( ComputingElement ):
#############################################################################
def __init__( self, ceUniqueID ):
""" Standard constructor.
"""
ComputingElement.__init__( self, ceUniqueID )
self.ceType = CE_NAME
s... | CE_NAME = 'ARC' | random_line_split |
ARCComputingElement.py | ########################################################################
# File : ARCComputingElement.py
# Author : A.T.
########################################################################
""" ARC Computing Element
"""
__RCSID__ = "58c42fc (2013-07-07 22:54:57 +0200) Andrei Tsaregorodtsev <atsareg@in2p3.fr>"
... |
running = 0
waiting = 0
for ref in resultDict:
status = resultDict[ref]
if status == 'Scheduled':
waiting += 1
if status == 'Running':
running += 1
result = S_OK()
result['RunningJobs'] = running
result['WaitingJobs'] = waiting
result['SubmittedJobs'] = 0... | resultDict = self.__parseJobStatus( result['Value'][1] ) | conditional_block |
ARCComputingElement.py | ########################################################################
# File : ARCComputingElement.py
# Author : A.T.
########################################################################
""" ARC Computing Element
"""
__RCSID__ = "58c42fc (2013-07-07 22:54:57 +0200) Andrei Tsaregorodtsev <atsareg@in2p3.fr>"
... |
def getJobStatus( self, jobIDList ):
""" Get the status information for the given list of jobs
"""
workingDirectory = self.ceParameters['WorkingDirectory']
fd, name = tempfile.mkstemp( suffix = '.list', prefix = 'StatJobs_', dir = workingDirectory )
jobListFile = os.fdope... | """
"""
resultDict = {}
lines = commandOutput.split('\n')
ln = 0
while ln < len( lines ):
if lines[ln].startswith( 'Job:' ):
jobRef = lines[ln].split()[1]
ln += 1
line = lines[ln].strip()
stateARC = ''
if line.startswith( 'State' ):
state... | identifier_body |
ARCComputingElement.py | ########################################################################
# File : ARCComputingElement.py
# Author : A.T.
########################################################################
""" ARC Computing Element
"""
__RCSID__ = "58c42fc (2013-07-07 22:54:57 +0200) Andrei Tsaregorodtsev <atsareg@in2p3.fr>"
... | ( self, jobID, localDir = None ):
""" Get the specified job standard output and error files. If the localDir is provided,
the output is returned as file in this directory. Otherwise, the output is returned
as strings.
"""
if jobID.find( ':::' ) != -1:
pilotRef, stamp = jobID.split( '... | getJobOutput | identifier_name |
client_json.rs | #![deny(warnings)]
extern crate hyper;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use hyper::Client;
use hyper::rt::{self, Future, Stream};
fn main() {
let url = "http://jsonplaceholder.typicode.com/users".parse().unwrap();
let fut = fetch_json(url)
// use th... | Json(serde_json::Error),
}
impl From<hyper::Error> for FetchError {
fn from(err: hyper::Error) -> FetchError {
FetchError::Http(err)
}
}
impl From<serde_json::Error> for FetchError {
fn from(err: serde_json::Error) -> FetchError {
FetchError::Json(err)
}
} | enum FetchError {
Http(hyper::Error), | random_line_split |
client_json.rs | #![deny(warnings)]
extern crate hyper;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use hyper::Client;
use hyper::rt::{self, Future, Stream};
fn | () {
let url = "http://jsonplaceholder.typicode.com/users".parse().unwrap();
let fut = fetch_json(url)
// use the parsed vector
.map(|users| {
// print users
println!("users: {:#?}", users);
// print the sum of ids
let sum = users.iter().fold(0, ... | main | identifier_name |
client_json.rs | #![deny(warnings)]
extern crate hyper;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use hyper::Client;
use hyper::rt::{self, Future, Stream};
fn main() {
let url = "http://jsonplaceholder.typicode.com/users".parse().unwrap();
let fut = fetch_json(url)
// use th... |
#[derive(Deserialize, Debug)]
struct User {
id: i32,
name: String,
}
// Define a type so we can return multiple types of errors
enum FetchError {
Http(hyper::Error),
Json(serde_json::Error),
}
impl From<hyper::Error> for FetchError {
fn from(err: hyper::Error) -> FetchError {
FetchError:... | {
let client = Client::new();
client
// Fetch the url...
.get(url)
// And then, if we get a response back...
.and_then(|res| {
// asynchronously concatenate chunks of the body
res.into_body().concat2()
})
.from_err::<FetchError>()
... | identifier_body |
Github.js | 'use strict';
//noinspection JSUnusedLocalSymbols
const { indent } = require('../utils');
const qs = require('querystring');
class GithubApi {
constructor(auth) {
this.rp = require('request-promise-native')
.defaults({
gzip : true,
jar : true,
auth ... |
}
//noinspection JSUnusedLocalSymbols
module.exports = (() => {
let { MatchlistProvider } = require('./Providers');
/**
* @property {QueryableProviderDefinition} def
*/
class GithubProvider extends MatchlistProvider {
/**
* Builds the matchlist according to what's queryable by the Github API
*
* @r... | {
if(query.substr(0, 1) === '/')
query = 'https://api.github.com' + query;
let res = await this.rp(query);
let nextPageURL = (res.headers.link || '')
.split(/,\s*/)
.reduce((acc, link) => {
if(link.indexOf('rel="next"') >= 0)
return link.match(/<(.+?)>/)[1];
return acc;
}, '');
if(nex... | identifier_body |
Github.js | 'use strict';
//noinspection JSUnusedLocalSymbols
const { indent } = require('../utils');
const qs = require('querystring');
class GithubApi {
constructor(auth) {
this.rp = require('request-promise-native') | json : true,
resolveWithFullResponse: true,
headers : {
'Accept' : 'application/vnd.github.v3+json',
'User-Agent': 'cpriest/hain-plugin-psl',
}
});
}
async get(query) {
if(query.substr(0, 1) === '/')
query = 'https://api.github.com' + query;
le... | .defaults({
gzip : true,
jar : true,
auth : auth, | random_line_split |
Github.js | 'use strict';
//noinspection JSUnusedLocalSymbols
const { indent } = require('../utils');
const qs = require('querystring');
class GithubApi {
| (auth) {
this.rp = require('request-promise-native')
.defaults({
gzip : true,
jar : true,
auth : auth,
json : true,
resolveWithFullResponse: true,
headers : {
'Accept' : 'application/vnd.github.v... | constructor | identifier_name |
test_routing.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nose.tools import raises, eq_, ok_
from werkzeug.test import Client
from werkzeug.wrappers import BaseResponse
from clastic import Application, render_basic
from clastic.application import BaseApplication
from clastic.route import BaseRoute, Route... |
def test_broken_routes():
for cur_mode in MODES:
for cur_patt in broken_routes:
try:
cur_rt = Route(cur_patt, NO_OP, slash_mode=cur_mode)
except InvalidPattern:
yield ok_, True
else:
yield ok_, False, cur_rt
def test_kn... | yield ok_, cur_rt | conditional_block |
test_routing.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nose.tools import raises, eq_, ok_
from werkzeug.test import Client
from werkzeug.wrappers import BaseResponse
from clastic import Application, render_basic
from clastic.application import BaseApplication
from clastic.route import BaseRoute, Route... | ():
# note default slashing behavior
rp = BaseRoute('/a/b/<t:int>/thing/<das+int>')
d = rp.match_path('/a/b/1/thing/1/2/3/4')
yield eq_, d, {u't': 1, u'das': [1, 2, 3, 4]}
d = rp.match_path('/a/b/1/thing/hi/')
yield eq_, d, None
d = rp.match_path('/a/b/1/thing/')
yield eq_, d, None
... | test_new_base_route | identifier_name |
test_routing.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nose.tools import raises, eq_, ok_
from werkzeug.test import Client
from werkzeug.wrappers import BaseResponse
from clastic import Application, render_basic
from clastic.application import BaseApplication
from clastic.route import BaseRoute, Route... |
def three_segments(one, two, three):
return 'three_segments: %s, %s, %s' % (one, two, three)
def test_create_route_order_list():
"tests route order when routes are added as a list"
routes = [('/api/<api_path+>', api, render_basic),
('/<one>/<two>', two_segments, render_basic),
... | return 'two_segments: %s, %s' % (one, two) | identifier_body |
test_routing.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nose.tools import raises, eq_, ok_
from werkzeug.test import Client
from werkzeug.wrappers import BaseResponse
from clastic import Application, render_basic
from clastic.application import BaseApplication
from clastic.route import BaseRoute, Route... | yield eq_, client.get('/api/a/b').data, 'api: a/b'
yield eq_, app.routes[-1].pattern, r[0]
return
"""
New routing testing strategy notes
==================================
* Successful endpoint
* Failing endpoint (i.e., raise a non-HTTPException exception)
* Raising endpoint (50x, 40x (breaking/n... | for r in routes:
app.add(r) | random_line_split |
TestNativeExp2.rs | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language gover... | * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* | random_line_split |
const.py | """Proides the constants needed for component."""
ATTR_APP_ID = "app_id"
ATTR_APP_NAME = "app_name"
ATTR_INPUT_SOURCE = "source"
ATTR_INPUT_SOURCE_LIST = "source_list"
ATTR_MEDIA_ALBUM_ARTIST = "media_album_artist"
ATTR_MEDIA_ALBUM_NAME = "media_album_name"
ATTR_MEDIA_ARTIST = "media_artist"
ATTR_MEDIA_CHANNEL = "medi... | ATTR_MEDIA_VOLUME_MUTED = "is_volume_muted"
ATTR_SOUND_MODE = "sound_mode"
ATTR_SOUND_MODE_LIST = "sound_mode_list"
DOMAIN = "media_player"
MEDIA_TYPE_MUSIC = "music"
MEDIA_TYPE_TVSHOW = "tvshow"
MEDIA_TYPE_MOVIE = "movie"
MEDIA_TYPE_VIDEO = "video"
MEDIA_TYPE_EPISODE = "episode"
MEDIA_TYPE_CHANNEL = "channel"
MEDIA_... | ATTR_MEDIA_SHUFFLE = "shuffle"
ATTR_MEDIA_TITLE = "media_title"
ATTR_MEDIA_TRACK = "media_track"
ATTR_MEDIA_VOLUME_LEVEL = "volume_level" | random_line_split |
urls.py | from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('webapp',
url(r'^/?$', 'views.home', name='home'),
url(r'^auth_redirect$', 'views.auth_redirect', name='auth_redirect'),
url(r'^nights$', 'views.night_index', name='night_index'),
| url(r'^song/(?P<key>[\w\d]+)/wait$', 'views.song_wait_finished', name='song_wait_finished'),
url(r'^sign_out$', 'views.sign_out', name='sign_out'),
) | url(r'^song$', 'views.song_index', name='song_index'),
url(r'^create_song$', 'views.song_create', name='song_create'),
url(r'^song/(?P<key>[\w\d]+)$', 'views.song', name='song'),
url(r'^song/(?P<key>[\w\d]+).mp3$', 'views.song_mp3', name='song_mp3'),
url(r'^song/(?P<key>[\w\d]+)/edit$', 'views.song_... | random_line_split |
test_column.py | import numpy as np
import pandas as pd
import pytest
ROWID_ZERO_INDEXED_BACKENDS = ('omniscidb',)
@pytest.mark.parametrize(
'column',
[
'string_col',
'double_col',
'date_string_col',
pytest.param('timestamp_col', marks=pytest.mark.skip(reason='hangs')),
],
)
@pytest.mark.x... | (con, backend):
t = con.table('functional_alltypes')
result = t[t.rowid().name('number')].execute()
first_value = 0 if backend.name() in ROWID_ZERO_INDEXED_BACKENDS else 1
expected = pd.Series(
range(first_value, first_value + len(result)),
dtype=np.int64,
name='number',
)
... | test_named_rowid | identifier_name |
test_column.py | import numpy as np
import pandas as pd
import pytest
ROWID_ZERO_INDEXED_BACKENDS = ('omniscidb',)
@pytest.mark.parametrize( | [
'string_col',
'double_col',
'date_string_col',
pytest.param('timestamp_col', marks=pytest.mark.skip(reason='hangs')),
],
)
@pytest.mark.xfail_unsupported
def test_distinct_column(backend, alltypes, df, column):
expr = alltypes[column].distinct()
result = expr.execute()
... | 'column', | random_line_split |
test_column.py | import numpy as np
import pandas as pd
import pytest
ROWID_ZERO_INDEXED_BACKENDS = ('omniscidb',)
@pytest.mark.parametrize(
'column',
[
'string_col',
'double_col',
'date_string_col',
pytest.param('timestamp_col', marks=pytest.mark.skip(reason='hangs')),
],
)
@pytest.mark.x... | t = con.table('functional_alltypes')
result = t[t.rowid().name('number')].execute()
first_value = 0 if backend.name() in ROWID_ZERO_INDEXED_BACKENDS else 1
expected = pd.Series(
range(first_value, first_value + len(result)),
dtype=np.int64,
name='number',
)
pd.testing.assert_... | identifier_body | |
lib.rs | //! A wrapper around the uchardet library. Detects character encodings.
//!
//! Note that the underlying implemention is written in C and C++, and I'm
//! not aware of any security audits which have been performed against it.
//!
//! ```
//! use uchardet::detect_encoding_name;
//!
//! assert_eq!("WINDOWS-1252",
//! ... |
/// We declare our `error_chain!` in a private submodule so that we can
/// `allow(missing_docs)`.
#[allow(missing_docs)]
mod errors {
error_chain! {
errors {
UnrecognizableCharset {
description("unrecognizable charset")
display("uchardet was unable to recognize ... | random_line_split | |
lib.rs | //! A wrapper around the uchardet library. Detects character encodings.
//!
//! Note that the underlying implemention is written in C and C++, and I'm
//! not aware of any security audits which have been performed against it.
//!
//! ```
//! use uchardet::detect_encoding_name;
//!
//! assert_eq!("WINDOWS-1252",
//! ... | unsafe { ffi::uchardet_delete(self.ptr) };
}
} | identifier_body | |
lib.rs | //! A wrapper around the uchardet library. Detects character encodings.
//!
//! Note that the underlying implemention is written in C and C++, and I'm
//! not aware of any security audits which have been performed against it.
//!
//! ```
//! use uchardet::detect_encoding_name;
//!
//! assert_eq!("WINDOWS-1252",
//! ... | mut self) {
unsafe { ffi::uchardet_data_end(self.ptr); }
}
/// Get the decoder's current best guess as to the encoding. May return
/// an error if uchardet was unable to detect an encoding.
fn charset(&self) -> Result<String> {
unsafe {
let internal_str = ffi::uchardet_get_c... | ta_end(& | identifier_name |
synonym.rs | use std::collections::HashMap;
use std::collections::hash_map::{Iter, Keys};
use std::fmt::Debug;
use std::hash::Hash;
use std::iter::{FromIterator, IntoIterator};
use std::mem;
#[derive(Clone)]
pub struct SynonymMap<K, V> {
vals: HashMap<K, V>,
syns: HashMap<K, K>,
}
impl<K: Eq + Hash, V> SynonymMap<K, V> {
... |
}
}
impl<K: Eq + Hash + Clone, V> SynonymMap<K, V> {
pub fn resolve(&self, k: &K) -> K {
self.with_key(k, |k| k.clone())
}
pub fn get<'a>(&'a self, k: &K) -> &'a V {
self.find(k).unwrap()
}
pub fn find_mut<'a>(&'a mut self, k: &K) -> Option<&'a mut V> {
if self.syns.c... | {
with(k)
} | conditional_block |
synonym.rs | use std::collections::HashMap;
use std::collections::hash_map::{Iter, Keys};
use std::fmt::Debug;
use std::hash::Hash;
use std::iter::{FromIterator, IntoIterator};
use std::mem;
#[derive(Clone)]
pub struct SynonymMap<K, V> {
vals: HashMap<K, V>,
syns: HashMap<K, K>,
}
impl<K: Eq + Hash, V> SynonymMap<K, V> {
... | write!(f, " (synomyns: {:?})", self.syns)
}
} | }
impl<K: Eq + Hash + Debug, V: Debug> Debug for SynonymMap<K, V> {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
try!(self.vals.fmt(f)); | random_line_split |
synonym.rs | use std::collections::HashMap;
use std::collections::hash_map::{Iter, Keys};
use std::fmt::Debug;
use std::hash::Hash;
use std::iter::{FromIterator, IntoIterator};
use std::mem;
#[derive(Clone)]
pub struct SynonymMap<K, V> {
vals: HashMap<K, V>,
syns: HashMap<K, K>,
}
impl<K: Eq + Hash, V> SynonymMap<K, V> {
... | () -> SynonymMap<K, V> {
SynonymMap {
vals: HashMap::new(),
syns: HashMap::new(),
}
}
pub fn insert_synonym(&mut self, from: K, to: K) -> bool {
assert!(self.vals.contains_key(&to));
self.syns.insert(from, to).is_none()
}
pub fn keys<'a>(&'a self... | new | identifier_name |
synonym.rs | use std::collections::HashMap;
use std::collections::hash_map::{Iter, Keys};
use std::fmt::Debug;
use std::hash::Hash;
use std::iter::{FromIterator, IntoIterator};
use std::mem;
#[derive(Clone)]
pub struct SynonymMap<K, V> {
vals: HashMap<K, V>,
syns: HashMap<K, K>,
}
impl<K: Eq + Hash, V> SynonymMap<K, V> {
... |
pub fn contains_key(&self, k: &K) -> bool {
self.with_key(k, |k| self.vals.contains_key(k))
}
pub fn len(&self) -> usize {
self.vals.len()
}
fn with_key<T, F>(&self, k: &K, with: F) -> T where F: FnOnce(&K) -> T {
if self.syns.contains_key(k) {
with(&self.syns... | {
self.with_key(k, |k| self.vals.get(k))
} | identifier_body |
find-map.js | /**
* shuji (周氏)
* https://github.com/paazmaya/shuji
*
* Reverse engineering JavaScript and CSS sources from sourcemaps
*
* Copyright (c) Juga Paazmaya <paazmaya@yahoo.com> (https://paazmaya.fi)
* Licensed under the MIT license
*/
const fs = require('fs'),
path = require('path');
const MATCH_MAP = /\.map$/i... | }
else if (input.match(FIND_SOURCE_FILE)) {
const sourceMappingMatch = FIND_SOURCE_FILE.exec(input);
if (sourceMappingMatch && sourceMappingMatch.length > 1) {
if (options.verbose) {
console.log(`Input file "${filepath}" points to "${sourceMappingMatch[1]}"`);
}
}
... | if (options.verbose) {
console.log(`Input file "${filepath}" contains URL encoded of ${sourceMappingMatch[2].length} length`);
}
const buf = Buffer.from(sourceMappingMatch[2], 'ascii');
return buf.toString('utf8');
}
| conditional_block |
find-map.js | /**
* shuji (周氏)
* https://github.com/paazmaya/shuji
*
* Reverse engineering JavaScript and CSS sources from sourcemaps
*
* Copyright (c) Juga Paazmaya <paazmaya@yahoo.com> (https://paazmaya.fi)
* Licensed under the MIT license
*/
const fs = require('fs'),
path = require('path');
const MATCH_MAP = /\.map$/i... | if (options.verbose) {
console.log(`Input file "${filepath}" points to "${sourceMappingMatch[1]}"`);
}
}
// Since the sourceMappingURL is relative, try to find it from the same folder
const mapFile = path.join(path.dirname(filepath), sourceMappingMatch[1]);
try {
... | random_line_split | |
default.py | """
URLResolver Addon for Kodi
Copyright (C) 2016 t0mm0, tknorris
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 3 of the License, or
(at your option) any late... |
mode = queries.get('mode', None)
url_dispatcher.dispatch(mode, queries)
if __name__ == '__main__':
sys.exit(main())
| return | conditional_block |
default.py | """
URLResolver Addon for Kodi
Copyright (C) 2016 t0mm0, tknorris
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 3 of the License, or
(at your option) any late... |
@url_dispatcher.register(MODES.RESET_RD)
def reset_rd():
kodi.close_all()
kodi.sleep(500) # sleep or reset won't work for some reason
from urlresolver.plugins import realdebrid
rd = realdebrid.RealDebridResolver()
rd.reset_authorization()
kodi.notify(msg=kodi.i18n('rd_auth_reset'), duration=5... | kodi.close_all()
kodi.sleep(500) # sleep or authorize won't work for some reason
from urlresolver.plugins import realdebrid
if realdebrid.RealDebridResolver().authorize_resolver():
kodi.notify(msg=kodi.i18n('rd_authorized'), duration=5000) | identifier_body |
default.py | """
URLResolver Addon for Kodi
Copyright (C) 2016 t0mm0, tknorris
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 3 of the License, or
(at your option) any late... | ():
if cache.reset_cache():
kodi.notify(msg=kodi.i18n('cache_reset'))
else:
kodi.notify(msg=kodi.i18n('cache_reset_failed'))
def main(argv=None):
if sys.argv: argv = sys.argv
queries = kodi.parse_query(sys.argv[2])
log_utils.log('Version: |%s| Queries: |%s|' % (kodi.get_version(... | reset_cache | identifier_name |
default.py | """
URLResolver Addon for Kodi
Copyright (C) 2016 t0mm0, tknorris
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 3 of the License, or
(at your option) any late... |
@url_dispatcher.register(MODES.AUTH_RD)
def auth_rd():
kodi.close_all()
kodi.sleep(500) # sleep or authorize won't work for some reason
from urlresolver.plugins import realdebrid
if realdebrid.RealDebridResolver().authorize_resolver():
kodi.notify(msg=kodi.i18n('rd_authorized'), duration=5000)... | return type('Enum', (), enums)
MODES = __enum(AUTH_RD='auth_rd', RESET_RD='reset_rd', RESET_CACHE='reset_cache') | random_line_split |
test-http-buffer-sanity.js | // Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modi... | });
server.listen(0, common.mustCall(() => {
const req = http.request({
port: server.address().port,
method: 'POST',
path: '/',
headers: { 'content-length': buffer.length }
}, common.mustCall((res) => {
res.setEncoding('utf8');
let data = '';
res.on('data', (chunk) => data += chunk);
... | random_line_split | |
test-http-buffer-sanity.js | // Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modi... |
const server = http.Server(function(req, res) {
server.close();
let i = 0;
req.on('data', (d) => {
measuredSize += d.length;
for (let j = 0; j < d.length; j++) {
assert.strictEqual(buffer[i], d[j]);
i++;
}
});
req.on('end', common.mustCall(() => {
assert.strictEqual(bufferSize... | {
buffer[i] = i % 256;
} | conditional_block |
guildMemberAdd.js | module.exports = {
Handle: (member) => {
let Guild = new Server.Server(member.guild.id);
Guild.modlog.then((ModLog) => {
Guild.channels.then((channels) => {
let Message = `${member.user.username} Joined the server.`;
if(channels !== null){
if(channels.joinLog !== null && channels.joinLog !== undefi... | }).catch((e) => {
});
}).catch((e) => {
});
}).catch((e) => {
})
}
}; | member.guild.channels.get(ModLog).sendMessage(Message);
}
} | random_line_split |
guildMemberAdd.js | module.exports = {
Handle: (member) => {
let Guild = new Server.Server(member.guild.id);
Guild.modlog.then((ModLog) => {
Guild.channels.then((channels) => {
let Message = `${member.user.username} Joined the server.`;
if(channels !== null){
if(channels.joinLog !== null && channels.joinLog !== undefi... |
}
}else{
if(ModLog !== null){
member.guild.channels.get(ModLog).sendMessage(Message);
}
}
}else{
if(ModLog !== null){
member.guild.channels.get(ModLog).sendMessage(Message);
}
}
}).catch((e) => {
});
}).catch((e) => {
});
}).catc... | {
Guild.userJoin.then((message) => {
member.sendMessage(message);
});
} | conditional_block |
CCArmature.js | /****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation... | if (parentBone)
this._parentBone = parentBone;
this.removeAllChildren();
this.animation = new ccs.ArmatureAnimation();
this.animation.init(this);
this._boneDic = {};
this._topBoneList.length = 0;
//this._name = name || "";
var armatureDataMan... | * @param {String} [name]
* @param {ccs.Bone} [parentBone]
* @return {Boolean}
*/
init: function (name, parentBone) { | random_line_split |
CCArmature.js | /****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation... |
cc.Node.prototype.addChild.call(this, child, localZOrder, tag);
},
/**
* create a bone with name
* @param {String} boneName
* @return {ccs.Bone}
*/
createBone: function (boneName) {
var existedBone = this.getBone(boneName);
if (existedBone)
return ex... | {
cc.log("Armature doesn't support to add Widget as its child, it will be fix soon.");
return;
} | conditional_block |
focus.ts | import { getDocument } from './getDocument';
import { elementContains } from './elementContains';
const IS_VISIBLE_ATTRIBUTE = 'data-is-visible';
const IS_FOCUSABLE_ATTRIBUTE = 'data-is-focusable';
const FOCUSZONE_ID_ATTRIBUTE = 'data-focuszone-id';
export function doesElementContainFocus(element: HTMLElement) {
le... |
export function isElementFocusZone(element?: HTMLElement): boolean {
return element && !!element.getAttribute(FOCUSZONE_ID_ATTRIBUTE);
}
| {
return (
!!element &&
(element.tagName === 'A' ||
(element.tagName === 'BUTTON' && !(element as HTMLButtonElement).disabled) ||
(element.tagName === 'INPUT' && !(element as HTMLInputElement).disabled) ||
(element.tagName === 'TEXTAREA' && !(element as HTMLTextAreaElement).disabled) ||
... | identifier_body |
focus.ts | import { elementContains } from './elementContains';
const IS_VISIBLE_ATTRIBUTE = 'data-is-visible';
const IS_FOCUSABLE_ATTRIBUTE = 'data-is-focusable';
const FOCUSZONE_ID_ATTRIBUTE = 'data-focuszone-id';
export function doesElementContainFocus(element: HTMLElement) {
let currentActiveElement: HTMLElement = getDocu... | import { getDocument } from './getDocument'; | random_line_split | |
focus.ts | import { getDocument } from './getDocument';
import { elementContains } from './elementContains';
const IS_VISIBLE_ATTRIBUTE = 'data-is-visible';
const IS_FOCUSABLE_ATTRIBUTE = 'data-is-focusable';
const FOCUSZONE_ID_ATTRIBUTE = 'data-focuszone-id';
export function doesElementContainFocus(element: HTMLElement) {
le... |
return (element.offsetHeight !== 0 ||
element.offsetParent !== null ||
(element as any).isVisible === true);
}
export function isElementTabbable(element: HTMLElement): boolean {
return (
!!element &&
(element.tagName === 'A' ||
(element.tagName === 'BUTTON' && !(element as HTMLButtonElement... | {
return visibilityAttribute === 'true';
} | conditional_block |
focus.ts | import { getDocument } from './getDocument';
import { elementContains } from './elementContains';
const IS_VISIBLE_ATTRIBUTE = 'data-is-visible';
const IS_FOCUSABLE_ATTRIBUTE = 'data-is-focusable';
const FOCUSZONE_ID_ATTRIBUTE = 'data-focuszone-id';
export function doesElementContainFocus(element: HTMLElement) {
le... | (element: HTMLElement): boolean {
return (
!!element &&
(element.tagName === 'A' ||
(element.tagName === 'BUTTON' && !(element as HTMLButtonElement).disabled) ||
(element.tagName === 'INPUT' && !(element as HTMLInputElement).disabled) ||
(element.tagName === 'TEXTAREA' && !(element as HTMLTe... | isElementTabbable | identifier_name |
HotspotViewerRenderer.tsx | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | onCommentButtonClick={props.onShowCommentForm}
onLocationSelect={props.onLocationClick}
selectedHotspotLocation={selectedHotspotLocation}
/>
}
hotspot={hotspot}
selectedHotspotLocation={selectedHotspotLocation}
/... | hotspot={hotspot} | random_line_split |
engineApi.js | /*
this is the API to be used by the underlying voice/messaging system
public functions throw exceptions when called in a wrong way.
*/
var uuid = require("uuid");
//var appConfig = require("./etc/app.json");
//var addressBook = require("./" + appConfig.addressBook);
var wss = require("./websocket");
var myLib = ... | }, ["telegraf"], ["inbox"], { message: { value: 1 }}, data.content);
}
};
exports.callUpdate = function(data) {
let required = ["number", "name", "timestamp", "filename"];
if (!myLib.checkObjectProperties(data, required)) {
myLib.consoleLog('panic', 'engineApi::callUpdate', "invalid input", data);
} else {
d... | random_line_split | |
explode.py | #!/Users/Drake/dev/LouderDev/louderdev/bin/python3
#
# The Python Imaging Library
# $Id$
#
# split an animation into a number of frame files
#
from __future__ import print_function
from PIL import Image
import os
import sys
class Interval(object):
def __init__(self, interval="0"):
self.setinterval(int... |
if html:
html.write("</body>\n</html>\n")
| if frames[ix]:
im.save(outfile % ix)
print(outfile % ix)
if html:
html.write("<img src='%s'><br>\n" % outfile % ix)
try:
im.seek(ix)
except EOFError:
break
ix += 1 | conditional_block |
explode.py | #!/Users/Drake/dev/LouderDev/louderdev/bin/python3
#
# The Python Imaging Library
# $Id$
#
# split an animation into a number of frame files
#
from __future__ import print_function
from PIL import Image
import os
import sys
class Interval(object):
def __init__(self, interval="0"):
self.setinterval(int... | (self, interval):
self.hilo = []
for s in interval.split(","):
if not s.strip():
continue
try:
v = int(s)
if v < 0:
lo, hi = 0, -v
else:
lo = hi = v
except ValueE... | setinterval | identifier_name |
explode.py | #!/Users/Drake/dev/LouderDev/louderdev/bin/python3
#
# The Python Imaging Library
# $Id$
#
# split an animation into a number of frame files
#
from __future__ import print_function
from PIL import Image
import os
import sys
class Interval(object):
def __init__(self, interval="0"):
self.setinterval(int... | print("Syntax: python explode.py infile template [range]")
print()
print("The template argument is used to construct the names of the")
print("individual frame files. The frames are numbered file001.ext,")
print("file002.ext, etc. You can insert %d to control the placement")
print("and syntax ... | del sys.argv[1]
if not sys.argv[2:]:
print() | random_line_split |
explode.py | #!/Users/Drake/dev/LouderDev/louderdev/bin/python3
#
# The Python Imaging Library
# $Id$
#
# split an animation into a number of frame files
#
from __future__ import print_function
from PIL import Image
import os
import sys
class Interval(object):
def __init__(self, interval="0"):
|
def setinterval(self, interval):
self.hilo = []
for s in interval.split(","):
if not s.strip():
continue
try:
v = int(s)
if v < 0:
lo, hi = 0, -v
else:
lo = hi = v
... | self.setinterval(interval) | identifier_body |
base.rs | use std::io::Write;
pub enum Color {
Reset,
Black,
White,
Grey,
}
// Shamelessly stolen from termios
// which doesn't compile on Win32
// which is why I'm doing all this nonsense in the first place
pub enum Event {
Key(Key),
Mouse(MouseEvent),
Unsupported(Vec<u32>),
}
// Derived from term... | F(u8),
Char(char),
Shift(Box<Key>),
Alt(Box<Key>),
Ctrl(Box<Key>),
Null,
Esc,
}
impl Key {
pub fn is_char(&self) -> bool {
match self {
&Key::Char(_) => true,
_ => false
}
}
pub fn is_navigation(&self) -> bool {
match self {
... | random_line_split | |
base.rs | use std::io::Write;
pub enum Color {
Reset,
Black,
White,
Grey,
}
// Shamelessly stolen from termios
// which doesn't compile on Win32
// which is why I'm doing all this nonsense in the first place
pub enum Event {
Key(Key),
Mouse(MouseEvent),
Unsupported(Vec<u32>),
}
// Derived from term... | (&self) -> bool {
match self {
&Key::Char(_) => true,
_ => false
}
}
pub fn is_navigation(&self) -> bool {
match self {
&Key::Left | &Key::Right | &Key::Up | &Key::Down |
&Key::Home | &Key::End | &Key::PageUp | &Key::PageDown => tr... | is_char | identifier_name |
deletePersona-test.js | import testId from 'api/routes/tests/utils/testId';
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import setup from 'api/routes/tests/utils/setup';
import * as routes from 'lib/constants/routes';
import createOrgToken from 'api/routes/tests/utils/tokens/createOrgToken'; | const apiApp = setup();
let token;
const personaService = getPersonaService();
beforeEach(async () => {
await personaService.clearService();
token = await createOrgToken();
});
after(async () => {
await personaService.clearService();
});
it('should delete a persona', async () => {
con... | import getPersonaService from 'lib/connections/personaService';
chai.use(chaiAsPromised);
describe('personaController deletePersona', () => { | random_line_split |
DateRangePicker.js | /*!
* ${copyright}
*/
// Provides control sap.ui.webc.main.DateRangePicker.
sap.ui.define([
"sap/ui/webc/common/WebComponent",
"./library",
"sap/ui/core/EnabledPropagator",
"sap/ui/core/library",
"./thirdparty/DateRangePicker",
"./thirdparty/features/InputElementsFormSupport"
], function(WebComponent, library,... | *
* @extends sap.ui.webc.common.WebComponent
* @class
*
* <h3>Overview</h3> The DateRangePicker enables the users to enter a localized date range using touch, mouse, keyboard input, or by selecting a date range in the calendar.
*
*
*
* <h3>Keyboard Handling</h3> The <code>sap.ui.webc.main.DateRangePic... | * @param {object} [mSettings] Initial settings for the new control | random_line_split |
run.py | import os, os.path
import subprocess
import shutil
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--make", help="run make clean && make on all files",
action="store_true")
parser.add_argument("-c", "--check", help="run ./check.sh on all files",
... |
tag = ''
if args.tag:
tag = args.tag + '_'
for n in benchmark:
m = n + dev
uniqueid = open('logs/.uniqueid.txt','r')
uid = uniqueid.readline()
uniqueid.close()
uniqueid = open('logs/.uniqueid.txt','w')
uniqueid.write(str(int(uid) + 1))
... | cmdlineopts = cmdlineoptsbasic | conditional_block |
run.py | import os, os.path
import subprocess
import shutil
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--make", help="run make clean && make on all files",
action="store_true")
parser.add_argument("-c", "--check", help="run ./check.sh on all files",
... | os.chdir(n)
for k in xrange(args.numberofiterations):
p1 = subprocess.Popen('./' + m +'.exe ' + cmdlineopts[n], shell=True,\
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
acc = '$Func ' + m + ', $Defines ' + cm... | uniqueid = open('logs/.uniqueid.txt','w')
uniqueid.write(str(int(uid) + 1))
log = open('logs/' + uid + '_' + tag + m + cmdlineopts[n].replace(" ", "_") \
.replace("-", "_") + '.txt','w') | random_line_split |
validate-header.hook.ts | // FoalTS
import { ValidateFunction } from 'ajv';
import {
ApiParameter,
ApiResponse,
Context,
Hook,
HookDecorator,
HttpResponseBadRequest,
IApiHeaderParameter,
OpenApi,
ServiceManager
} from '../../core';
import { getAjvInstance } from '../utils';
import { isFunction } from './is-function.util';
/**... | {
// tslint:disable-next-line
const required = options.required ?? true;
name = name.toLowerCase();
let validateSchema: ValidateFunction|undefined;
function validate(this: any, ctx: Context, services: ServiceManager) {
if (!validateSchema) {
const ajvSchema = isFunction(schema) ? schema(this) : sc... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.