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 |
|---|---|---|---|---|
setup.py | #!/usr/bin/env python3
import sys
import os
from distutils.core import run_setup
# build_ext is subclassed, so we import it with a _ to avoid a collision
from distutils.command.build_ext import build_ext as _build_ext
from setuptools import setup, Extension, find_packages
PKG_NAME = "piqueserver"
extra_args = sys.a... |
setup(
name=PKG_NAME,
packages=find_packages(exclude=("tests", "tests.*")),
version=version['__version__'],
description='Open-Source server implementation for Ace of Spades ',
author=('Originally MatPow2 and PySnip contributors,'
'now, StackOverflow and piqueserver authors'),
auth... | from Cython.Build import cythonize
if USE_ASAN:
from Cython.Compiler import Options
# make asan/valgrind's memory leak results better
Options.generate_cleanup_code = True
compiler_directives = {'language_level': 3, 'embedsignature': True}
if linetrace:
... | identifier_body |
euler024.py | def __init_break_indices__(num):
indices = [1]*num
for i in xrange(1, num):
indices[num-1-i] = indices[num-i]*i
return indices
def get_lex_permutation (N, base_string, break_indices):
stringPermutation = []
divident = []
base_string = list(base_string)
divident_prefix = 0
f... |
return ''.join(stringPermutation)
__STRING = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']
__BREAK_INDICES = __init_break_indices__(len(__STRING))
tests = int(raw_input())
for test in xrange(tests):
N = int(raw_input())
print get_lex_permutation(N, __STRING, __BREAK_INDICES) |
stringPermutation.append(base_string[temp_int])
base_string.pop(temp_int)
divident_prefix += temp_int*break_indices[i] | random_line_split |
euler024.py | def __init_break_indices__(num):
indices = [1]*num
for i in xrange(1, num):
|
return indices
def get_lex_permutation (N, base_string, break_indices):
stringPermutation = []
divident = []
base_string = list(base_string)
divident_prefix = 0
for i in xrange(len(base_string)):
if (i-1) >= 0:
temp = ( N - 1 - divident_prefix )/break_indices[i]
... | indices[num-1-i] = indices[num-i]*i | conditional_block |
euler024.py | def | (num):
indices = [1]*num
for i in xrange(1, num):
indices[num-1-i] = indices[num-i]*i
return indices
def get_lex_permutation (N, base_string, break_indices):
stringPermutation = []
divident = []
base_string = list(base_string)
divident_prefix = 0
for i in xrange(len(base_st... | __init_break_indices__ | identifier_name |
euler024.py | def __init_break_indices__(num):
indices = [1]*num
for i in xrange(1, num):
indices[num-1-i] = indices[num-i]*i
return indices
def get_lex_permutation (N, base_string, break_indices):
|
__STRING = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']
__BREAK_INDICES = __init_break_indices__(len(__STRING))
tests = int(raw_input())
for test in xrange(tests):
N = int(raw_input())
print get_lex_permutation(N, __STRING, __BREAK_INDICES) | stringPermutation = []
divident = []
base_string = list(base_string)
divident_prefix = 0
for i in xrange(len(base_string)):
if (i-1) >= 0:
temp = ( N - 1 - divident_prefix )/break_indices[i]
else:
temp = ( N - 1 )/break_indices[i]
temp_int = int(temp)
... | identifier_body |
arm64.rs | use execstate::ExecState;
use object::{Obj, Ref};
pub use self::param::*;
pub use self::reg::*;
pub mod asm;
pub mod param;
pub mod reg;
pub mod trap;
pub fn flush_icache(start: *const u8, len: usize) {
let start = start as usize;
let end = start + len;
let (icacheline_size, dcacheline_size) = cacheline... | (es: &ExecState) -> Ref<Obj> {
let obj: Ref<Obj> = es.regs[REG_RESULT.asm() as usize].into();
obj
}
pub fn ra_from_execstate(es: &ExecState) -> usize {
es.regs[REG_LR.asm() as usize]
}
| get_exception_object | identifier_name |
arm64.rs | use execstate::ExecState;
use object::{Obj, Ref};
pub use self::param::*;
pub use self::reg::*;
pub mod asm;
pub mod param;
pub mod reg;
pub mod trap;
pub fn flush_icache(start: *const u8, len: usize) {
let start = start as usize;
let end = start + len;
let (icacheline_size, dcacheline_size) = cacheline... | unsafe {
asm!("dc civac, $0":: "r"(ptr) : "memory" : "volatile");
}
ptr += dcacheline_size;
}
unsafe {
asm!("dsb ish" ::: "memory" : "volatile");
}
ptr = istart;
while ptr < end {
unsafe {
asm!("ic ivau, $0":: "r"(ptr) : "memory" : ... | while ptr < end { | random_line_split |
arm64.rs | use execstate::ExecState;
use object::{Obj, Ref};
pub use self::param::*;
pub use self::reg::*;
pub mod asm;
pub mod param;
pub mod reg;
pub mod trap;
pub fn flush_icache(start: *const u8, len: usize) {
let start = start as usize;
let end = start + len;
let (icacheline_size, dcacheline_size) = cacheline... |
pub fn ra_from_execstate(es: &ExecState) -> usize {
es.regs[REG_LR.asm() as usize]
}
| {
let obj: Ref<Obj> = es.regs[REG_RESULT.asm() as usize].into();
obj
} | identifier_body |
license_hopper.py | # (c) 2013, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
lookup: Select a random license k... | self.filename = kwargs.pop('filename', None)
self.remove = kwargs.pop('remove', False)
if self.filename is None:
raise AnsibleError("No 'filename' was specified")
lookupfile = self.find_file_in_search_path(variables, 'files', self.filename)
if lookupfile is None:
... | identifier_body | |
license_hopper.py | # (c) 2013, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
lookup: Select a random license k... |
def run(self, terms, variables=None, **kwargs):
self.filename = kwargs.pop('filename', None)
self.remove = kwargs.pop('remove', False)
if self.filename is None:
raise AnsibleError("No 'filename' was specified")
lookupfile = self.find_file_in_search_path(variables, 'files... | super(LookupModule, self).__init__(loader, templar, **kwargs)
self.filename = None
self.remove = False | random_line_split |
license_hopper.py | # (c) 2013, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
lookup: Select a random license k... | (LookupBase):
def __init__(self, loader=None, templar=None, **kwargs):
super(LookupModule, self).__init__(loader, templar, **kwargs)
self.filename = None
self.remove = False
def run(self, terms, variables=None, **kwargs):
self.filename = kwargs.pop('filename', None)
se... | LookupModule | identifier_name |
license_hopper.py | # (c) 2013, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
lookup: Select a random license k... |
return ret
| to_write = [x + "\n" for x in lines if x != ret[0]]
fh = open(lookupfile, 'w')
fh.writelines(to_write) | conditional_block |
datum_transform.js | var PJD_3PARAM = 1;
var PJD_7PARAM = 2;
var PJD_GRIDSHIFT = 3;
var PJD_NODATUM = 5; // WGS84 or equivalent
var SRS_WGS84_SEMIMAJOR = 6378137; // only used in grid shift transforms
var SRS_WGS84_ESQUARED = 0.006694379990141316; //DGR: 2012-07-29
module.exports = function(source, dest, point) {
var wp, i, l;
functio... |
// Short cut if the datums are identical.
if (source.compare_datums(dest)) {
return point; // in this case, zero is sucess,
// whereas cs_compare_datums returns 1 to indicate TRUE
// confusing, should fix this
}
// Explicitly skip datum transform by setting 'datum=none' as parameter for either sou... | {
return (fallback === PJD_3PARAM || fallback === PJD_7PARAM);
} | identifier_body |
datum_transform.js | var PJD_3PARAM = 1;
var PJD_7PARAM = 2;
var PJD_GRIDSHIFT = 3;
var PJD_NODATUM = 5; // WGS84 or equivalent
var SRS_WGS84_SEMIMAJOR = 6378137; // only used in grid shift transforms
var SRS_WGS84_ESQUARED = 0.006694379990141316; //DGR: 2012-07-29
module.exports = function(source, dest, point) {
var wp, i, l;
functio... |
if (checkParams(dest.datum_type)) {
dest.geocentric_from_wgs84(point);
// CHECK_RETURN;
}
// Convert back to geodetic coordinates
dest.geocentric_to_geodetic(point);
// CHECK_RETURN;
}
// Apply grid shift to destination if required
if (dest.datum_type === PJD_GRIDSHIFT) {
this... | {
source.geocentric_to_wgs84(point);
// CHECK_RETURN;
} | conditional_block |
datum_transform.js | var PJD_3PARAM = 1;
var PJD_7PARAM = 2;
var PJD_GRIDSHIFT = 3;
var PJD_NODATUM = 5; // WGS84 or equivalent
var SRS_WGS84_SEMIMAJOR = 6378137; // only used in grid shift transforms
var SRS_WGS84_ESQUARED = 0.006694379990141316; //DGR: 2012-07-29
module.exports = function(source, dest, point) {
var wp, i, l;
functio... | (fallback) {
return (fallback === PJD_3PARAM || fallback === PJD_7PARAM);
}
// Short cut if the datums are identical.
if (source.compare_datums(dest)) {
return point; // in this case, zero is sucess,
// whereas cs_compare_datums returns 1 to indicate TRUE
// confusing, should fix this
}
// Ex... | checkParams | identifier_name |
datum_transform.js | var PJD_3PARAM = 1;
var PJD_7PARAM = 2;
var PJD_GRIDSHIFT = 3;
var PJD_NODATUM = 5; // WGS84 or equivalent
var SRS_WGS84_SEMIMAJOR = 6378137; // only used in grid shift transforms
var SRS_WGS84_ESQUARED = 0.006694379990141316; //DGR: 2012-07-29
module.exports = function(source, dest, point) {
var wp, i, l;
functio... | if (this.apply_gridshift(source, 0, point) === 0) {
source.a = SRS_WGS84_SEMIMAJOR;
source.es = SRS_WGS84_ESQUARED;
}
else {
// try 3 or 7 params transformation or nothing ?
if (!source.datum_params) {
source.a = src_a;
source.es = source.es;
return point;
... |
var fallback = source.datum_type;
// If this datum requires grid shifts, then apply it to geodetic coordinates.
if (fallback === PJD_GRIDSHIFT) { | random_line_split |
htmlunknownelement.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/. */
use dom::bindings::codegen::Bindings::HTMLUnknownElementBinding;
use dom::bindings::js::Root;
use dom::bindings::s... | prefix: Option<DOMString>,
document: &Document) -> HTMLUnknownElement {
HTMLUnknownElement {
htmlelement:
HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom... | random_line_split | |
htmlunknownelement.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/. */
use dom::bindings::codegen::Bindings::HTMLUnknownElementBinding;
use dom::bindings::js::Root;
use dom::bindings::s... | {
htmlelement: HTMLElement
}
impl HTMLUnknownElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLUnknownElement {
HTMLUnknownElement {
htmlelement:
HTMLElement::new_inherited(localName,... | HTMLUnknownElement | identifier_name |
htmlunknownelement.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/. */
use dom::bindings::codegen::Bindings::HTMLUnknownElementBinding;
use dom::bindings::js::Root;
use dom::bindings::s... |
}
| {
Node::reflect_node(box HTMLUnknownElement::new_inherited(localName, prefix, document),
document,
HTMLUnknownElementBinding::Wrap)
} | identifier_body |
__init__.py | s at Line %s: %s' % (f_name, lineno, line))
f.close()
return lfreq, ltotal
def initialize(self, dictionary=None):
if dictionary:
abs_path = _get_abs_path(dictionary)
if self.dictionary == abs_path and self.initialized:
return
else:
... | try:
with open(cache_file, 'rb') as cf:
self.FREQ, self.total = marshal.load(cf)
load_from_cache_fail = False
except Exception:
load_from_cache_fail = True
if load_from_cache_fail:
... | random_line_split | |
__init__.py | s at Line %s: %s' % (f_name, lineno, line))
f.close()
return lfreq, ltotal
def initialize(self, dictionary=None):
if dictionary:
abs_path = _get_abs_path(dictionary)
if self.dictionary == abs_path and self.initialized:
return
else:
... | (self, sentence, HMM=True):
"""
Finer segmentation for search engines.
"""
words = self.cut(sentence, HMM=HMM)
for w in words:
if len(w) > 2:
for i in xrange(len(w) - 1):
gram2 = w[i:i + 2]
if self.FREQ.get(gram2... | cut_for_search | identifier_name |
__init__.py | segments an entire sentence that contains
Chinese characters into separated words.
Parameter:
- sentence: The str(unicode) to be segmented.
- cut_all: Model type. True for full pattern, False for accurate pattern.
- HMM: Whether to use the Hidden Markov Model.
... | parts = strdecode(sentence).splitlines(True)
if cut_all:
result = pool.map(_lcut_all, parts)
elif HMM:
result = pool.map(_lcut, parts)
else:
result = pool.map(_lcut_no_hmm, parts)
for r in result:
for w in r:
yield w | identifier_body | |
__init__.py | t1))
default_logger.debug("Prefix dict has been built successfully.")
def check_initialized(self):
if not self.initialized:
self.initialize()
def calc(self, sentence, DAG, route):
N = len(sentence)
route[N] = (0, 0)
logtotal = log(self.total)
fo... | self.add_word(word, freq) | conditional_block | |
linefinder.py | import cv2
import numpy as np
import time
image = cv2.imread('test.png')
image = cv2.flip(image,2)
rows, cols,_ = image.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),40,1)
image = cv2.warpAffine(image,M,(cols,rows)) | t0 = time.time()
size = np.size(mask)
skel = np.zeros(mask.shape,np.uint8)
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(20,20))
done = False
while( not done):
eroded = cv2.erode(mask,element)
temp = cv2.dilate(eroded,element)
temp = cv2.subtract(mask,temp)
skel = cv2.bitwise_or(skel,temp)
i... | mask=cv2.inRange(image, np.array([0, 180, 255],dtype='uint8'),np.array([0, 180, 255],dtype='uint8'))
_, cnts, _ = cv2.findContours(mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
| random_line_split |
linefinder.py | import cv2
import numpy as np
import time
image = cv2.imread('test.png')
image = cv2.flip(image,2)
rows, cols,_ = image.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),40,1)
image = cv2.warpAffine(image,M,(cols,rows))
mask=cv2.inRange(image, np.array([0, 180, 255],dtype='uint8'),np.array([0, 180, 255],dtype='uint8'... |
cv2.imshow("skel",image)
cv2.waitKey(0)
cv2.destroyAllWindows() | for rho,theta in lines[1]:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
print(x1,y1,x2,y2)
cv2.line(image,(x1,y1),(x2,y2),(0,0,255),2) | conditional_block |
keypage_prepare_fields.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013,2014 Rodolphe Quiédeville <rodolphe@quiedeville.org>
#
# 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 ver... |
log.stop = datetime.now()
log.save()
print key, log.stop - log.start, nb
| reak
| conditional_block |
keypage_prepare_fields.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013,2014 Rodolphe Quiédeville <rodolphe@quiedeville.org>
#
# 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 ver... | "SELECT keyid,nbpages FROM july_bigbook",
"WHERE serie= 3 AND keyid > $1",
"ORDER BY keyid ASC LIMIT 250"])
try:
cursor.execute(qry)
except:
pass
while True:
cursor.execute('EXECUTE prep... | ""
Use prepared query on july_bigbook
"""
key = 'keypage_prepare_fields'
log = Log.objects.create(name=key,
start=datetime.now(),
stop=datetime.now())
nb = 0
keyid = 0
cursor = connection.cursor(... | identifier_body |
keypage_prepare_fields.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013,2014 Rodolphe Quiédeville <rodolphe@quiedeville.org>
#
# 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 ver... | "WHERE serie= 3 AND keyid > $1",
"ORDER BY keyid ASC LIMIT 250"])
try:
cursor.execute(qry)
except:
pass
while True:
cursor.execute('EXECUTE preptwo (%s)' % (keyid))
books = cursor.fetchall()
... | random_line_split | |
keypage_prepare_fields.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013,2014 Rodolphe Quiédeville <rodolphe@quiedeville.org>
#
# 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 ver... | BaseCommand):
help = 'Import datas'
def handle(self, *args, **options):
"""
Use prepared query on july_bigbook
"""
key = 'keypage_prepare_fields'
log = Log.objects.create(name=key,
start=datetime.now(),
... | ommand( | identifier_name |
error.rs | use std::io;
use std::result;
use mqtt3;
use tokio_timer::TimerError;
pub type Result<T> = result::Result<T, Error>;
quick_error! {
#[derive(Debug)]
pub enum Error {
Io(err: io::Error) {
from()
description("io error")
display("I/O error: {}", err)
cause... | }
InvalidMqttPacket {
description("Invalid Mqtt Packet")
}
InvalidClientId {
description("Invalid Client ID")
}
DisconnectRequest {
description("Received Disconnect Request")
}
NotInQueue {
description("Could... | ClientIdExists {
description("Client with that ID already exists") | random_line_split |
PermaPower.js | /**
* Created by ralphy on 29/03/17.
*/
/**
* this spell will permanantly increase player fire power | * @class MANSION.SPELLS.PermaPower
*/
O2.createClass('MANSION.SPELLS.PermaPower', {
run: function(g) {
var ePerma = new Effect.PermaBonus('power');
var p = g.oLogic.getPlayerSoul();
ePerma.setSource(p);
ePerma.setTarget(p);
ePerma.setLevel(MANSION.CONST.SPELL_POWER_UP);
... | * by 10 points | random_line_split |
utils.js.uncompressed.js | instanceof g.Group){
arr.forEach(object.children, function(shape){
gu.forEach(shape, f, o);
});
}
},
serialize: function(object){
// summary:
// Takes a shape or a surface and returns a JSON-like object, which describes underlying shapes.
// object: dojox/gfx/shape.Surface|dojox/gfx/shap... | },
//iFrame document used for handling SVG serialization.
_gfxSvgProxy: null,
//Serializer loaded.
_initSvgSerializerDeferred: null,
_svgSerializerInitialized: function() {
// summary:
// Internal function to call when the serializer init completed.
// tags:
// private
gu._initSvgSeriali... | }
return deferred; //dojo.Deferred that will be called when serialization finishes. | random_line_split |
utils.js.uncompressed.js | instanceof g.Group){
arr.forEach(object.children, function(shape){
gu.forEach(shape, f, o);
});
}
},
serialize: function(object){
// summary:
// Takes a shape or a surface and returns a JSON-like object, which describes underlying shapes.
// object: dojox/gfx/shape.Surface|dojox/gfx/shap... |
return t; // Object
},
toJson: function(object, prettyPrint){
// summary:
// Works just like serialize() but returns a JSON string. If prettyPrint is true, the string is pretty-printed to make it more human-readable.
// object: dojox/gfx/shape.Surface|dojox/gfx/shape.Shape
// The container to ser... | {
v = object.getFont();
if(v){ t.font = v; }
} | conditional_block |
aria-valid-attr-value-test.js | /**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* 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 applicable law or a... | const artifacts = {
Accessibility: {
violations: [{
id: 'aria-valid-attr-value',
nodes: [],
help: 'http://example.com/',
}],
},
};
const output = Audit.audit(artifacts);
assert.equal(output.rawValue, false);
});
it('generates an audit outpu... | describe('Accessibility: aria-valid-attr-value audit', () => {
it('generates an audit output', () => { | random_line_split |
ramp.py | # Copyright 2015 TellApart, Inc.
#
# 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 applicable law or agreed to in writi... |
@property
def _end_time(self):
return self._start_time + timedelta(seconds=self._ramp_seconds)
@property
def auditable_share(self):
"""Return current share adjustment factor.
"""
as_of = datetime.now()
share = self._curve_fn(self._start_time,
self._end_time,
... | spawn_later(self._update_frequency, self._update) | conditional_block |
ramp.py | # Copyright 2015 TellApart, Inc.
#
# 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 applicable law or agreed to in writi... | (self):
"""Return current share adjustment factor.
"""
as_of = datetime.now()
share = self._curve_fn(self._start_time,
self._end_time,
as_of)
return share, AuditItem('ramp', str(share))
| auditable_share | identifier_name |
ramp.py | # Copyright 2015 TellApart, Inc.
#
# 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 applicable law or agreed to in writi... | def start(self):
"""Start maintaining share adjustment factor for endpoint.
"""
if not self._start_time:
self._start_time = datetime.now() + timedelta(seconds=self._ramp_delay)
spawn_later(self._update_frequency, self._update)
def stop(self):
"""Stop maintaining share adjustment factor fo... | self._stop_event = Event()
| random_line_split |
ramp.py | # Copyright 2015 TellApart, Inc.
#
# 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 applicable law or agreed to in writi... |
@property
def auditable_share(self):
"""Return current share adjustment factor.
"""
as_of = datetime.now()
share = self._curve_fn(self._start_time,
self._end_time,
as_of)
return share, AuditItem('ramp', str(share))
| return self._start_time + timedelta(seconds=self._ramp_seconds) | identifier_body |
docs.py | # Module: docs
# Date: 03rd April 2013
# Author: James Mills, j dot mills at griffith dot edu dot au
"""Documentation Tasks"""
from fabric.api import lcd, local, task
from .utils import pip, requires
PACKAGE = "mio"
@task()
@requires("make", "sphinx-apidoc")
def clean():
"""Delete Generated Documenta... |
@task()
@requires("open")
def view(**options):
"""View the Documentation"""
with lcd("docs"):
local("open build/html/index.html")
| """Build the Documentation"""
pip(requirements="docs/requirements.txt")
if PACKAGE is not None:
local("sphinx-apidoc -f -T -o docs/source/api {0:s}".format(PACKAGE))
with lcd("docs"):
local("make html") | identifier_body |
docs.py | # Module: docs | # Date: 03rd April 2013
# Author: James Mills, j dot mills at griffith dot edu dot au
"""Documentation Tasks"""
from fabric.api import lcd, local, task
from .utils import pip, requires
PACKAGE = "mio"
@task()
@requires("make", "sphinx-apidoc")
def clean():
"""Delete Generated Documentation"""
with... | random_line_split | |
docs.py | # Module: docs
# Date: 03rd April 2013
# Author: James Mills, j dot mills at griffith dot edu dot au
"""Documentation Tasks"""
from fabric.api import lcd, local, task
from .utils import pip, requires
PACKAGE = "mio"
@task()
@requires("make", "sphinx-apidoc")
def | ():
"""Delete Generated Documentation"""
with lcd("docs"):
local("make clean")
@task(default=True)
@requires("make")
def build(**options):
"""Build the Documentation"""
pip(requirements="docs/requirements.txt")
if PACKAGE is not None:
local("sphinx-apidoc -f -T -o docs/source/ap... | clean | identifier_name |
docs.py | # Module: docs
# Date: 03rd April 2013
# Author: James Mills, j dot mills at griffith dot edu dot au
"""Documentation Tasks"""
from fabric.api import lcd, local, task
from .utils import pip, requires
PACKAGE = "mio"
@task()
@requires("make", "sphinx-apidoc")
def clean():
"""Delete Generated Documenta... |
with lcd("docs"):
local("make html")
@task()
@requires("open")
def view(**options):
"""View the Documentation"""
with lcd("docs"):
local("open build/html/index.html")
| local("sphinx-apidoc -f -T -o docs/source/api {0:s}".format(PACKAGE)) | conditional_block |
regexbot.py | ][0] < datetime.now():
channel_timeouts.get()
timeout_arg = 3
found_item = False
for item in channel_timeouts.queue:
if channel != item[1]['channel']:
continue
found_item = True
timeout_arg = item[1]['timeout']
channel_timeouts.queue.remove(item)
... | global NICKSERV_PASS
# Compliance with most network's rules to set this mode on connect.
event.connection.usermode("+B")
if NICKSERV_PASS != None:
event.connection.todo(['NickServ', 'identify', NICKSERV_PASS]) | identifier_body | |
regexbot.py | new_item[1]['user'] = user
new_item[1]['timeout'] = timeout_arg
user_timeouts.put(new_item)
if found_item:
print "Ignoring message from %s because of a timeout, timeout now %d seconds" % (user, 2**timeout_arg)
return True
else:
return False
def handle_ctcp(event, match):
... | irc_conn | identifier_name | |
regexbot.py | message from %s because of a timeout, timeout now %d seconds" % (user, 2**timeout_arg)
return True
else:
return False
def handle_ctcp(event, match):
channel = event.channel.lower()
global message_buffer, MAX_MESSAGES, channel_list
if channel in channel_list:
if event.args[0] =... | IRC.handle_close = irc_conn
IRC.handle_error = irc_conn | conditional_block | |
regexbot.py | message_buffer, MAX_MESSAGES, channel_list
if channel in channel_list:
if event.args[0] == "ACTION":
message_buffer[channel].append([event.nick, event.text[:MAX_MESSAGE_SIZE], True])
message_buffer[channel] = message_buffer[channel][-MAX_MESSAGES:]
return
def handle_msg... | irc.bind(handle_ctcp, CTCP_REQUEST)
irc_conn(irc) | random_line_split | |
index.ts | /**
* Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
*/
import { PDBeStructureQualityReport } from '../../extensions/pdbe';
import { EmptyLoci } from '../../mol-model/loci';
import { StructureSelection } from '../../mol-mo... |
async init(target: string | HTMLElement) {
this.plugin = await createPluginUI(typeof target === 'string' ? document.getElementById(target)! : target, {
...DefaultPluginUISpec(),
layout: {
initial: {
isExpanded: false,
showContr... | plugin: PluginUIContext; | random_line_split |
index.ts | /**
* Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
*/
import { PDBeStructureQualityReport } from '../../extensions/pdbe';
import { EmptyLoci } from '../../mol-model/loci';
import { StructureSelection } from '../../mol-mo... | ({ url, format = 'mmcif', isBinary = false, assemblyId = '' }: LoadParams) {
await this.plugin.clear();
const data = await this.plugin.builders.data.download({ url: Asset.Url(url), isBinary }, { state: { isGhost: true } });
const trajectory = await this.plugin.builders.structure.parseTrajectory... | load | identifier_name |
index.ts | /**
* Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
*/
import { PDBeStructureQualityReport } from '../../extensions/pdbe';
import { EmptyLoci } from '../../mol-model/loci';
import { StructureSelection } from '../../mol-mo... |
toggleSpin() {
if (!this.plugin.canvas3d) return;
const trackball = this.plugin.canvas3d.props.trackball;
PluginCommands.Canvas3D.SetSettings(this.plugin, {
settings: {
trackball: {
...trackball,
animate: trackball.animat... | {
PluginCommands.Canvas3D.SetSettings(this.plugin, { settings: props => { props.renderer.backgroundColor = Color(color); } });
} | identifier_body |
setup.py | import sys
import EulerPy
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def readme():
with open('README.rst') as f:
return f.read()
def requirements():
install_requires = []
with open('requirements.txt') as f:
for line in f:
ins... | url='https://github.com/iKevinY/EulerPy',
author=EulerPy.__author__,
author_email='me@kevinyap.ca',
license=EulerPy.__license__,
packages=['EulerPy'],
entry_points={'console_scripts': ['euler = EulerPy.__main__:main']},
install_requires=requirements(),
classifiers=[
"License :: O... | version=EulerPy.__version__,
description=EulerPy.__doc__.strip(),
long_description=readme(), | random_line_split |
setup.py | import sys
import EulerPy
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def | ():
with open('README.rst') as f:
return f.read()
def requirements():
install_requires = []
with open('requirements.txt') as f:
for line in f:
install_requires.append(line.strip())
# Terminal colors for Windows
if 'win32' in str(sys.platform).lower():
install_re... | readme | identifier_name |
setup.py | import sys
import EulerPy
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def readme():
with open('README.rst') as f:
return f.read()
def requirements():
|
setup(
name='EulerPy',
version=EulerPy.__version__,
description=EulerPy.__doc__.strip(),
long_description=readme(),
url='https://github.com/iKevinY/EulerPy',
author=EulerPy.__author__,
author_email='me@kevinyap.ca',
license=EulerPy.__license__,
packages=['EulerPy'],
entry_point... | install_requires = []
with open('requirements.txt') as f:
for line in f:
install_requires.append(line.strip())
# Terminal colors for Windows
if 'win32' in str(sys.platform).lower():
install_requires.append('colorama>=0.2.4')
return install_requires | identifier_body |
setup.py | import sys
import EulerPy
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def readme():
with open('README.rst') as f:
return f.read()
def requirements():
install_requires = []
with open('requirements.txt') as f:
for line in f:
|
# Terminal colors for Windows
if 'win32' in str(sys.platform).lower():
install_requires.append('colorama>=0.2.4')
return install_requires
setup(
name='EulerPy',
version=EulerPy.__version__,
description=EulerPy.__doc__.strip(),
long_description=readme(),
url='https://github.co... | install_requires.append(line.strip()) | conditional_block |
LeadStatusEditController.js | app.controller('LeadStatusEditCtrl', ['$scope', 'Auth', 'Leadstatus', function ($scope, Auth, Leadstatus) {
$("ul.page-sidebar-menu li").removeClass("active");
$("#id_LeadStatus").addClass("active");
$scope.isSignedIn = false;
$scope.immediateFailed = false;
$scope.nbLoads = 0;
$scope.isLoading ... | else {
$scope.nbLoads -= 1;
if ($scope.nbLoads == 0) {
$scope.isLoading = false;
}
;
}
;
};
$scope.apply = function () {
if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
$scope.$appl... | {
$scope.nbLoads += 1;
if ($scope.nbLoads == 1) {
$scope.isLoading = true;
}
;
} | conditional_block |
LeadStatusEditController.js | app.controller('LeadStatusEditCtrl', ['$scope', 'Auth', 'Leadstatus', function ($scope, Auth, Leadstatus) {
$("ul.page-sidebar-menu li").removeClass("active");
$("#id_LeadStatus").addClass("active");
$scope.isSignedIn = false;
$scope.immediateFailed = false;
$scope.nbLoads = 0;
$scope.isLoading ... |
};
$scope.editleadstatus = function (leadStatus) {
$scope.leadstat = $scope.leadstat || {};
$scope.leadstat.status = leadStatus.status;
$scope.leadstat.id = leadStatus.id;
$('#EditLeadStatus').modal('show');
};
$scope.updateLeadstatus = function (stat) {
var p... | };
Leadstatus.insert($scope, params);
$('#addLeadsStatusModal').modal('hide');
$scope.lead.status = ''; | random_line_split |
searchbar-compiled.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("... | return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype =... | { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } | conditional_block |
searchbar-compiled.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("... | (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "obje... | _classCallCheck | identifier_name |
searchbar-compiled.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("... |
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enum... | { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } | identifier_body |
searchbar-compiled.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("... | //# sourceMappingURL=searchbar-compiled.js.map | {/*<button><i id="searchIcon" className="fa fa-search" /></button>*/}
| random_line_split |
apprunner.py | # This file is part of the Enkel web programming library.
#
# Copyright (C) 2007 Espen Angell Kristiansen (espen@wsgi.net)
#
# 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... |
def mixing_write_app(env, start_response):
""" WSGI app for tesing of mixing using the write function and iterator. """
write = start_response("200 OK", [("Content-type", "text/plain")])
write("Mixing write... ")
return [" ...and iterator."]
def double_response_error_app(env, start_response):
""" WSGI app for t... | """ WSGI app for testing of the write function. """
write = start_response("200 OK", [("Content-type", "text/plain")])
write("Using write")
return [] | identifier_body |
apprunner.py | # This file is part of the Enkel web programming library.
#
# Copyright (C) 2007 Espen Angell Kristiansen (espen@wsgi.net)
#
# 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... |
def noiter_app(env, start_response):
""" An app that does not return an iterator. This is an error,
and should raise AppError. """
start_response("200 OK", [("Content-type", "text/plain")])
return 10
def override_defaultheader(env, start_response):
""" An app that overrides the default HTTP header "server".
... | try:
yield str(int(d)) # will fail on "four"
except ValueError:
self.start_response("500 ERROR",
[("Content-type", "text/plain")],
exc_info()) | conditional_block |
apprunner.py | # This file is part of the Enkel web programming library.
#
# Copyright (C) 2007 Espen Angell Kristiansen (espen@wsgi.net)
#
# 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... | (self):
run_app(mixing_write_app, self.sr)
b = self.buf.getvalue()
self.assert_(b.startswith(HEAD))
self.assert_(b.endswith("Mixing write... ...and iterator."))
def test_double_response_error(self):
self.assertRaises(AppError, run_app,
double_response_error_app, self.sr)
def test_double_response_ok(s... | test_mixing_write | identifier_name |
apprunner.py | # This file is part of the Enkel web programming library.
#
# Copyright (C) 2007 Espen Angell Kristiansen (espen@wsgi.net)
#
# 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... |
def testDoubleResponseErrInResponse(self):
self.assertRaises(ValueError, run_app,
DoubleResponseErrInResponse, self.sr)
def test_noiter(self):
self.assertRaises(AppError, run_app,
noiter_app, self.sr)
def suite():
return unit_case_suite(TestApprunner)
if __name__ == '__main__':
run_suite(suite()) | run_app(double_response_ok_app, self.sr)
b = self.buf.getvalue()
self.assert_(b.startswith(ERRHEAD)) | random_line_split |
main.js | steelblue';
function segColor(c) { return { low: "#807dba", mid: "#e08214", high: "#41ab5d" }[c]; }
// compute total for each state.
fData.forEach(function (d) { d.total = d.freq.low + d.freq.mid + d.freq.high; });
// function to handle histogram.
function histoGram(fD) {
var hG = {}, hGDi... |
// Draw the pie slices.
piesvg.selectAll("path").data(pie(pD)).enter().append("path").attr("d", arc)
.each(function (d) { this._current = d; })
.style("fill", function (d) { return segColor(d.data.type); })
.on("mouseover", mouseover).on("mouseout", mouseout);
... |
// create a function to compute the pie slice angles.
var pie = d3.layout.pie().sort(null).value(function (d) { return d.freq; }); | random_line_split |
main.js | steelblue';
function segColor(c) { return { low: "#807dba", mid: "#e08214", high: "#41ab5d" }[c]; }
// compute total for each state.
fData.forEach(function (d) { d.total = d.freq.low + d.freq.mid + d.freq.high; });
// function to handle histogram.
function histoGram(fD) {
var hG = {}, hGDi... | the pie-slice requiring a custom function which specifies
// how the intermediate paths should be drawn.
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function (t) { return arc(i(t)); };
}
return pC;
... | the update function of histogram with all data.
hG.update(fData.map(function (v) {
return [v.State, v.total];
}), barColor);
}
// Animating | identifier_body |
main.js | ([0, d3.max(nD, function (d) { return d[1]; })]);
// Attach the new data to the bars.
var bars = hGsvg.selectAll(".bar").data(nD);
// transition the height and color of rectangles.
bars.select("rect").transition().duration(500)
.attr("y", function (d) { ... | key: 'Group ' + i,
values: []
});
for (j = 0; j < points; j++) {
data[i].values.push({
x: random()
, y: random()
, size: Math.random() //Configure the size of each scatter point
, shape: (Math.random() > 0.95) ? s... | conditional_block | |
main.js | steelblue';
function segColor(c) { return { low: "#807dba", mid: "#e08214", high: "#41ab5d" }[c]; }
// compute total for each state.
fData.forEach(function (d) { d.total = d.freq.low + d.freq.mid + d.freq.high; });
// function to handle histogram.
function histoGram(fD) {
var hG = {}, hGDi... | nction to be called on mouseout.
// reset the pie-chart and legend.
pC.update(tF);
leg.update(tF);
}
// create function to update the bars. This will be used by pie-chart.
hG.update = function (nD, color) {
// update the domain of the y-axis m... | ility fu | identifier_name |
test_hdf5_filters.py | # Copyright (c) 2013-2021, Freja Nordsiek
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions ... | f.create_dataset(name, data=data, chunks=True, **filts)
out = hdf5storage.read(path=name, filename=filename,
matlab_compatible=False)
# Compare
assert_equal(out, data)
@pytest.mark.parametrize(
'compression,shuffle,fletcher32,gzip_level',
[(compress... | filts = {'compression': compression,
'shuffle': shuffle,
'fletcher32': fletcher32}
if compression == 'gzip':
filts['compression_opts'] = gzip_level
# Make some random data.
dims = random.randint(1, 4)
data = random_numpy(shape=random_numpy_shape(dims,
... | identifier_body |
test_hdf5_filters.py | # Copyright (c) 2013-2021, Freja Nordsiek
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions ... |
@pytest.mark.parametrize(
'compression,shuffle,fletcher32,gzip_level',
[(compression, shuffle, fletcher32, level)
for compression in ('gzip', 'lzf')
for shuffle in (True, False)
for fletcher32 in (True, False)
for level in range(10)])
def test_write_filtered_data(compression, shuffle, flet... | # Compare
assert_equal(out, data) | random_line_split |
test_hdf5_filters.py | # Copyright (c) 2013-2021, Freja Nordsiek
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions ... |
# Write the data to the file with the given name with the provided
# filters and read it back.
with tempfile.TemporaryDirectory() as folder:
filename = os.path.join(folder, 'data.h5')
hdf5storage.write(data, path=name, filename=filename, \
store_python_metadata=False, matlab_co... | opts = {'compress': True,
'compress_size_threshold': data.nbytes + 1} | conditional_block |
test_hdf5_filters.py | # Copyright (c) 2013-2021, Freja Nordsiek
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions ... | (compression, shuffle, fletcher32,
gzip_level):
# Make the filters dict.
filts = {'compression': compression,
'shuffle': shuffle,
'fletcher32': fletcher32}
if compression == 'gzip':
filts['compression_opts'] = gzip_level
# Make some random d... | test_read_filtered_data | identifier_name |
main.rs | macro_rules! timeit {
($func:expr) => ({
let t1 = std::time::Instant::now();
println!("{:?}", $func);
let t2 = std::time::Instant::now().duration_since(t1);
println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00);
})
}
fn main() | {
fn fib(n: usize) -> usize {
match n <= 3 {
true => n,
false => return fib(n - 1) + fib(n - 2),
}
}
fn even_fibs(n: usize) -> usize {
(1..)
.map(|x| fib(x))
.take_while(|&x| x <= n as usize)
.filter(|&x| x % 2 == 0)
... | identifier_body | |
main.rs | macro_rules! timeit {
($func:expr) => ({
let t1 = std::time::Instant::now();
println!("{:?}", $func);
let t2 = std::time::Instant::now().duration_since(t1);
println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00);
})
}
fn main() {
fn fib(n: usize) -> ... | false => return fib(n - 1) + fib(n - 2),
}
}
fn even_fibs(n: usize) -> usize {
(1..)
.map(|x| fib(x))
.take_while(|&x| x <= n as usize)
.filter(|&x| x % 2 == 0)
.fold(0, |acc, item| acc + item)
}
timeit!(even_fibs(4000000))
} | true => n, | random_line_split |
main.rs | macro_rules! timeit {
($func:expr) => ({
let t1 = std::time::Instant::now();
println!("{:?}", $func);
let t2 = std::time::Instant::now().duration_since(t1);
println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00);
})
}
fn main() {
fn fib(n: usize) -> ... | (n: usize) -> usize {
(1..)
.map(|x| fib(x))
.take_while(|&x| x <= n as usize)
.filter(|&x| x % 2 == 0)
.fold(0, |acc, item| acc + item)
}
timeit!(even_fibs(4000000))
}
| even_fibs | identifier_name |
lexical-scope-in-match.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
match (235, 236) {
// with literal
(235, shadowed) => {
zzz();
sentinel();
}
_ => {}
}
match Struct { x: 237, y: 238 } {
Struct { x: shadowed, y: local_to_arm } => {
zzz();
sentinel();
}
}
mat... | {
zzz();
sentinel();
} | conditional_block |
lexical-scope-in-match.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
x: int,
y: int
}
fn main() {
let shadowed = 231;
let not_shadowed = 232;
zzz();
sentinel();
match (233, 234) {
(shadowed, local_to_arm) => {
zzz();
sentinel();
}
}
match (235, 236) {
// with literal
(235, shadowed) => {... | Struct | identifier_name |
lexical-scope-in-match.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
// compile-flags:-g
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print shadowed
// check:$1 = 231
// debugger:print not_shadowed
// check:$2 = 232
// debugger:continue
// debugger:finish
// debugger:print shadowed
// check:$3 = 233
// debugger:print not_shadowed
// check:$4 = 232
// debugger... | // ignore-android: FIXME(#10381) | random_line_split |
test_rule_300.py |
import os
import unittest
from vsg.rules import iteration_scheme
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_300_test_input.vhd'))
dIndentMap = utils.read_indent_file()
lExpected = []
lExpected.ap... |
def test_rule_300(self):
oRule = iteration_scheme.rule_300()
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'iteration_scheme')
self.assertEqual(oRule.identifier, '300')
lExpected = [13, 17]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.... | self.oFile = vhdlFile.vhdlFile(lFile)
self.assertIsNone(eError)
self.oFile.set_indent_map(dIndentMap) | identifier_body |
test_rule_300.py |
import os
import unittest
from vsg.rules import iteration_scheme
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_300_test_input.vhd'))
dIndentMap = utils.read_indent_file()
lExpected = []
lExpected.ap... | (self):
oRule = iteration_scheme.rule_300()
oRule.fix(self.oFile)
lActual = self.oFile.get_lines()
self.assertEqual(lExpected, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule.violations, [])
| test_fix_rule_300 | identifier_name |
test_rule_300.py | import os
import unittest
from vsg.rules import iteration_scheme
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_300_test_input.vhd'))
dIndentMap = utils.read_indent_file()
lExpected = []
lExpected.app... | self.oFile = vhdlFile.vhdlFile(lFile)
self.assertIsNone(eError)
self.oFile.set_indent_map(dIndentMap)
def test_rule_300(self):
oRule = iteration_scheme.rule_300()
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'iteration_scheme')
self.assertEqual(oRule.i... |
class test_iteration_scheme_rule(unittest.TestCase):
def setUp(self): | random_line_split |
board-games.js | import request from 'request';
import xml2js from 'xml2js';
import util from 'util';
import Promise from 'promise';
export default function boardGames(app) {
app.get('/api/board-games?', function(req, res) {
try {
let minDate = new Date(2015, 0, 1);
let maxDate = new Date(2018, 0, 1);
if(!req.... |
return fullCollection;
}
| {
for(var i = 0; i < collection.length; i++) {
if(collection[i].status[0].$.own === '1') {
let name = collection[i].name[0]._;
let image = collection[i].image[0];
fullCollection[name] = image;
}
}
} | conditional_block |
board-games.js | import request from 'request';
import xml2js from 'xml2js';
import util from 'util';
import Promise from 'promise';
export default function boardGames(app) {
app.get('/api/board-games?', function(req, res) {
try {
let minDate = new Date(2015, 0, 1);
let maxDate = new Date(2018, 0, 1);
if(!req.... | (username, minDate, maxDate) {
return new Promise(function(resolve, reject) {
let allPlays = [];
fetchPlaysByPage(username, minDate, maxDate, 1)
.then(function (result) {
allPlays = result.plays.play;
let totalPlays = result.plays.$.total;
if(totalPlays > 100) {
l... | fetchPlays | identifier_name |
board-games.js | import request from 'request';
import xml2js from 'xml2js';
import util from 'util';
import Promise from 'promise';
export default function boardGames(app) {
app.get('/api/board-games?', function(req, res) {
try {
let minDate = new Date(2015, 0, 1);
let maxDate = new Date(2018, 0, 1);
if(!req.... | ).done(function(results){
let allPlays = calculateAllPlays(results[0]);
let allCollection = results[1];
resolve({
'10x10': get10x10(allPlays),
'100x1': get100x1(allPlays),
'wallOfShame': getWallOfShame(allPlays, allCollection)
});
});
});
}
function getWallOfS... | [ fetchPlays(username, minDate, maxDate),
fetchCollection(username, minDate, maxDate) ] | random_line_split |
board-games.js | import request from 'request';
import xml2js from 'xml2js';
import util from 'util';
import Promise from 'promise';
export default function boardGames(app) {
app.get('/api/board-games?', function(req, res) {
try {
let minDate = new Date(2015, 0, 1);
let maxDate = new Date(2018, 0, 1);
if(!req.... |
function calculateAllPlays(plays) {
let allPlays = {};
if(!plays) {
return {};
}
for(var i = 0; i < plays.length; i++) {
let gameName = plays[i].item[0].$.name;
if(allPlays[gameName] === undefined || allPlays[gameName] === NaN) {
allPlays[gameName] = 1;
} else {
allPlays[gameNam... | {
if(play1.plays < play2.plays) { return 1; }
if(play1.plays > play2.plays) { return -1; }
return 0;
} | identifier_body |
test_term_consistency.py | # c: 19.05.2008, r: 19.05.2008
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/2d/special/circle_in_square.mesh'
dim = 2
field_1 = {
'name' : 'scalar_field',
'dtype' : 'real',
'shape' : 'scalar',
'region' : 'Omega',
'approx_order' : 1,
}
field_2 = {
'name' : 'vector_field',
... | ( self ):
from sfepy.fem import Function, Variables
ok = True
pb = self.problem
for aux in test_terms:
term_template, (prefix, par_name, d_vars, dw_vars, mat_mode) = aux
print term_template, prefix, par_name, d_vars, dw_vars, mat_mode
term1 = term_te... | test_consistency_d_dw | identifier_name |
test_term_consistency.py | # c: 19.05.2008, r: 19.05.2008
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/2d/special/circle_in_square.mesh'
dim = 2
field_1 = {
'name' : 'scalar_field',
'dtype' : 'real',
'shape' : 'scalar',
'region' : 'Omega',
'approx_order' : 1,
}
field_2 = {
'name' : 'vector_field',
... |
elif term == 'biot_m':
val = 1.0 / nm.array( [3.8], dtype = nm.float64 )
elif term == 'permeability':
val = nm.eye( dim, dtype = nm.float64 )
else:
raise ValueError
return {'val' : nm.tile(val, (coor.shape[0], 1, 1))}
functions = {
'get_pars' : ... | val = nm.zeros( (sym, 1), dtype = nm.float64 )
val[:dim] = 0.132
val[dim:sym] = 0.092 | conditional_block |
test_term_consistency.py | # c: 19.05.2008, r: 19.05.2008
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/2d/special/circle_in_square.mesh'
dim = 2
field_1 = {
'name' : 'scalar_field',
'dtype' : 'real',
'shape' : 'scalar',
'region' : 'Omega',
'approx_order' : 1,
}
field_2 = {
'name' : 'vector_field',
... | if prefix == 'd':
val1 = pb.evaluate(term1, var_dict=variables.as_dict())
else:
val1 = pb.evaluate(term1, call_mode='d_eval',
var_dict=variables.as_dict())
self.report( '%s: %s' % (term1, val1) )
term2 ... | from sfepy.fem import Function, Variables
ok = True
pb = self.problem
for aux in test_terms:
term_template, (prefix, par_name, d_vars, dw_vars, mat_mode) = aux
print term_template, prefix, par_name, d_vars, dw_vars, mat_mode
term1 = term_template % ((prefix,... | identifier_body |
test_term_consistency.py | # c: 19.05.2008, r: 19.05.2008
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/2d/special/circle_in_square.mesh'
dim = 2
field_1 = {
'name' : 'scalar_field',
'dtype' : 'real',
'shape' : 'scalar',
'region' : 'Omega',
'approx_order' : 1,
}
field_2 = {
'name' : 'vector_field',
... | # c: 19.05.2008
class Test( TestCommon ):
##
# c: 19.05.2008, r: 19.05.2008
def from_conf( conf, options ):
from sfepy.fem import ProblemDefinition
problem = ProblemDefinition.from_conf(conf, init_equations=False)
test = Test( problem = problem,
conf = conf, op... | ## | random_line_split |
si.js | /*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'liststyle', 'si', {
armenian: 'Armenian numbering', // MISSING
bulletedTitle: 'Bulleted List Properties', // MISSING
circle: 'Circle', // MISSING
... | start: 'Start', // MISSING
type: 'වර්ගය',
upperAlpha: 'Upper Alpha (A, B, C, D, E, etc.)', // MISSING
upperRoman: 'Upper Roman (I, II, III, IV, V, etc.)', // MISSING
validateStartNumber: 'List start number must be a whole number.' // MISSING
} ); | none: 'කිසිවක්ම නොවේ',
notset: '<යොදා >',
numberedTitle: 'Numbered List Properties', // MISSING
square: 'Square', // MISSING | random_line_split |
index.d.ts | // Type definitions for raw-body 2.1 | // Definitions by: Stefan Reichel <https://github.com/bomret>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { Readable } from "stream";
declare namespace getRawBody {
export interface Options {
length?: number;
limit?: number;
enco... | // Project: https://github.com/stream-utils/raw-body | random_line_split |
syslog_json.py | # (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
callback: syslog_json
callback_type: notification
... | (CallbackBase):
"""
logs ansible-playbook and ansible runs to a syslog server in json format
"""
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
CALLBACK_NAME = 'syslog_json'
CALLBACK_NEEDS_WHITELIST = True
def __init__(self):
super(CallbackModule, self).__init__()
... | CallbackModule | identifier_name |
syslog_json.py | # (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
callback: syslog_json
callback_type: notification
... | CALLBACK_NEEDS_WHITELIST = True
def __init__(self):
super(CallbackModule, self).__init__()
self.set_options()
syslog_host = self.get_option("server")
syslog_port = int(self.get_option("port"))
syslog_facility = self.get_option("facility")
self.logger = loggin... |
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
CALLBACK_NAME = 'syslog_json' | random_line_split |
syslog_json.py | # (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
callback: syslog_json
callback_type: notification
... | self.logger.info('%s ansible-command: playbook NOT IMPORTED; host: %s; message: missing file %s', self.hostname, host, missing_file) | identifier_body | |
stp.py | # $Id: stp.py 23 2006-11-08 15:45:33Z dugsong $
# -*- coding: utf-8 -*-
"""Spanning Tree Protocol."""
import dpkt
class STP(dpkt.Packet):
__hdr__ = (
('proto_id', 'H', 0),
('v', 'B', 0),
('type', 'B', 0),
('flags', 'B', 0),
('root_id', '8s', ''),
('root_path', 'I',... | test_stp()
print 'Tests Successful...' | conditional_block | |
stp.py | # $Id: stp.py 23 2006-11-08 15:45:33Z dugsong $
# -*- coding: utf-8 -*-
"""Spanning Tree Protocol."""
import dpkt
class STP(dpkt.Packet):
__hdr__ = (
('proto_id', 'H', 0),
('v', 'B', 0),
('type', 'B', 0),
('flags', 'B', 0),
('root_id', '8s', ''),
('root_path', 'I',... | def max_age(self, max_age):
self._max_age = max_age << 8
@property
def hello(self):
return self._hello >> 8
@hello.setter
def hello(self, hello):
self._hello = hello << 8
@property
def fd(self):
return self._fd >> 8
@fd.setter
def fd(self, fd):
... | @property
def max_age(self):
return self._max_age >> 8
@max_age.setter | random_line_split |
stp.py | # $Id: stp.py 23 2006-11-08 15:45:33Z dugsong $
# -*- coding: utf-8 -*-
"""Spanning Tree Protocol."""
import dpkt
class STP(dpkt.Packet):
| def age(self, age):
self._age = age << 8
@property
def max_age(self):
return self._max_age >> 8
@max_age.setter
def max_age(self, max_age):
self._max_age = max_age << 8
@property
def hello(self):
return self._hello >> 8
@hello.setter
def hello(self... | __hdr__ = (
('proto_id', 'H', 0),
('v', 'B', 0),
('type', 'B', 0),
('flags', 'B', 0),
('root_id', '8s', ''),
('root_path', 'I', 0),
('bridge_id', '8s', ''),
('port_id', 'H', 0),
('_age', 'H', 0),
('_max_age', 'H', 0),
('_hello', 'H'... | identifier_body |
stp.py | # $Id: stp.py 23 2006-11-08 15:45:33Z dugsong $
# -*- coding: utf-8 -*-
"""Spanning Tree Protocol."""
import dpkt
class STP(dpkt.Packet):
__hdr__ = (
('proto_id', 'H', 0),
('v', 'B', 0),
('type', 'B', 0),
('flags', 'B', 0),
('root_id', '8s', ''),
('root_path', 'I',... | (self):
return self._hello >> 8
@hello.setter
def hello(self, hello):
self._hello = hello << 8
@property
def fd(self):
return self._fd >> 8
@fd.setter
def fd(self, fd):
self._fd = fd << 8
def test_stp():
buf = '\x00\x00\x02\x02\x3e\x80\x00\x08\x00\x27\xad... | hello | identifier_name |
IBaseReader.ts | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi... | */
export interface IBaseReader extends IAdaptiveRP {
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/ | /**
@class Adaptive.IBaseReader | random_line_split |
test_init.py | #!/usr/bin/env python
"""This module has unit tests for the pvl __init__ functions."""
# Copyright 2019, Ross A. Beyer (rbeyer@seti.org)
#
# 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
#
# ... |
@patch("pvl.loads")
@patch("pvl.decode_by_char")
def test_loadu_args(self, m_decode, m_loads):
pvl.loadu(self.url, data=None)
pvl.loadu(self.url, noturlopen="should be passed to loads")
m_decode.assert_called()
self.assertNotIn("data", m_loads.call_args_list[0][1])
... | self.assertEqual(self.simplePVL, pvl.loadu(self.url))
self.assertEqual(
self.simplePVL, pvl.loadu(self.simple.resolve().as_uri())
) | identifier_body |
test_init.py | #!/usr/bin/env python
"""This module has unit tests for the pvl __init__ functions."""
# Copyright 2019, Ross A. Beyer (rbeyer@seti.org)
#
# 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
#
# ... | s, pvl.dumps(self.module, encoder=pvl.encoder.ODLEncoder())
)
class TestDump(unittest.TestCase):
def setUp(self):
self.module = pvl.PVLModule(
a="b",
staygroup=pvl.PVLGroup(c="d"),
obj=pvl.PVLGroup(d="e", f=pvl.PVLGroup(g="h")),
)
sel... | END\r\n"""
self.assertEqual( | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.