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
tridentnet_r152v1bc4_c5_2x.py
3 train_scaleaware = True test_scaleaware = True branch_ids = range(num_branch) branch_dilates = [1, 2, 3] valid_ranges = [(0, 90), (30, 160), (90, -1)] valid_ranges_on_origin = True branch_bn_shared = True branch_conv_shared = True branch_deform =...
class BboxParam: fp16 = General.fp16 normalizer = NormalizeParam.normalizer num_class = 1 + 80 image_roi = 128 batch_image = General.batch_image * Trident.num_branch class regress_target: class_agnostic = True mean = (0.0, 0.0, ...
num_reg_class = 2 class_agnostic = True weight = (1.0, 1.0, 1.0, 1.0) mean = (0.0, 0.0, 0.0, 0.0) std = (0.1, 0.1, 0.2, 0.2)
identifier_body
newtype-struct-drop-run.rs
// Copyright 2013 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-MIT or ...
() { let y = @Cell::new(32); { let _x = Foo(y); } assert_eq!(y.get(), 23); }
main
identifier_name
newtype-struct-drop-run.rs
// Copyright 2013 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-MIT or ...
let y = @Cell::new(32); { let _x = Foo(y); } assert_eq!(y.get(), 23); }
pub fn main() {
random_line_split
newtype-struct-drop-run.rs
// Copyright 2013 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-MIT or ...
{ let y = @Cell::new(32); { let _x = Foo(y); } assert_eq!(y.get(), 23); }
identifier_body
ObjectBasedSet.spec.ts
namespace ZincDB { describe("Data structures:", () => { describe("ObjectBasedSet:", () => { it("Adds and checks for existence of a key", () => { const set = new ObjectBasedSet(); set.add("Key 1"); expect(set.size).toEqual(1); set.add("Key 2"); expect(set.size).toEqual(2); expect(set.has("K...
expect(set.has("Key 2")).toBe(false); }); it("Iterates all keys", () => { const set = new ObjectBasedSet(); set.add("Key 1"); set.add("Key 2"); set.delete("Key 2"); set.add("Key 3"); let i = 0; set.forEach((key) => { if (i === 0) expect(key).toEqual("Key 1"); els...
expect(set.has("Key 1")).toBe(true); expect(set.has("Key 2")).toBe(true); set.delete("Key 2"); expect(set.size).toEqual(1);
random_line_split
4-json-to-csv.py
# import the libraries that you need import requests import csv # make a GET request to the OneSearch X-Service API response = requests.get('http://onesearch.cuny.edu/PrimoWebServices'
'&query=any,contains,obama' '&query=facet_rtype,exact,books' '&loc=adaptor,primo_central_multiple_fe' '&loc=local,scope:(KB,AL,CUNY_BEPRESS)' '&json=true') # take the JSON from the response # and sto...
'/xservice/search/brief?' '&institution=KB'
random_line_split
4-json-to-csv.py
# import the libraries that you need import requests import csv # make a GET request to the OneSearch X-Service API response = requests.get('http://onesearch.cuny.edu/PrimoWebServices' '/xservice/search/brief?' '&institution=KB' '&query=any,contai...
writer.writerow([x['@KEY'], x['@VALUE']])
conditional_block
Instructions.js
var NN = NN || {}; NN.InstructionsState = NN.InstructionsState || {}; NN.InstructionsState.init = function(levelnum) { this.game.stage.backgroundColor = '#00f'; this.levelnum = levelnum; this.GAMEX = this.game.world.width; this.GAMEY = this.game.world.height; }; NN.InstructionsState.preload = functio...
if ( this.levelnum == 3 ) { words1.text = 'Enjoy your last'; words2.text = 'level without'; words3.text = 'enemies!'; } background.events.onInputDown.add(function() { this.startGameState(); }, this); }; NN.InstructionsState.startGameState = function(button) { this...
{ words1.text = 'The answers are'; words2.text = 'multiples of the'; words3.text = 'current level'; }
conditional_block
Instructions.js
var NN = NN || {}; NN.InstructionsState = NN.InstructionsState || {}; NN.InstructionsState.init = function(levelnum) { this.game.stage.backgroundColor = '#00f'; this.levelnum = levelnum; this.GAMEX = this.game.world.width; this.GAMEY = this.game.world.height; }; NN.InstructionsState.preload = functio...
var style = {font: 'bold 24pt Arial', fill: '#0f0'}; var words1 = this.game.add.text(this.GAMEX/2, this.GAMEY / 3, 'Text', style); var words2 = this.game.add.text(this.GAMEX/2, this.GAMEY / 2, 'Text', style); var words3 = this.game.add.text(this.GAMEX/2, this.GAMEY * 2 / 3, 'Text', style); w...
random_line_split
body.rs
use url::form_urlencoded; use hyper::Chunk; use mime; use controller::context::BodyContent; pub fn parse_body(content_type: Option<&mime::Mime>, body_data: Chunk) -> Option<BodyContent> { if body_data.is_empty() { None } else { let is_multipart_form_data = if let Some(ref content_mime) = conte...
} else { parse_form_urlencoded(body_data) }; Some(body_parsed) } } fn parse_form_urlencoded(body_data: Chunk) -> BodyContent { let vec: Vec<u8> = body_data.iter().cloned().collect(); form_urlencoded::parse(vec.as_ref()) .map(|(key, value)| (key.to_string(), valu...
let body_parsed = if is_multipart_form_data { parse_multipart_form_data(content_type, body_data)
random_line_split
body.rs
use url::form_urlencoded; use hyper::Chunk; use mime; use controller::context::BodyContent; pub fn parse_body(content_type: Option<&mime::Mime>, body_data: Chunk) -> Option<BodyContent> { if body_data.is_empty() { None } else { let is_multipart_form_data = if let Some(ref content_mime) = conte...
mime::Mime>, body_data: Chunk) -> BodyContent { if let Some(boundary) = get_boundary(content_type) { println!("multipart request received, boundary: {}", boundary); } parse_form_urlencoded(body_data) // TODO: this is stub } fn get_boundary(content_type: Option<&mime::Mime>) -> Option<String> { ...
ta(content_type: Option<&
identifier_name
body.rs
use url::form_urlencoded; use hyper::Chunk; use mime; use controller::context::BodyContent; pub fn parse_body(content_type: Option<&mime::Mime>, body_data: Chunk) -> Option<BodyContent> { if body_data.is_empty() { None } else { let is_multipart_form_data = if let Some(ref content_mime) = conte...
nt_type: Option<&mime::Mime>) -> Option<String> { content_type .and_then(|content_mime| { content_mime.get_param(mime::BOUNDARY).map(|boundary|boundary.as_ref().into()) }) }
ary) = get_boundary(content_type) { println!("multipart request received, boundary: {}", boundary); } parse_form_urlencoded(body_data) // TODO: this is stub } fn get_boundary(conte
identifier_body
body.rs
use url::form_urlencoded; use hyper::Chunk; use mime; use controller::context::BodyContent; pub fn parse_body(content_type: Option<&mime::Mime>, body_data: Chunk) -> Option<BodyContent> { if body_data.is_empty() { None } else { let is_multipart_form_data = if let Some(ref content_mime) = conte...
; Some(body_parsed) } } fn parse_form_urlencoded(body_data: Chunk) -> BodyContent { let vec: Vec<u8> = body_data.iter().cloned().collect(); form_urlencoded::parse(vec.as_ref()) .map(|(key, value)| (key.to_string(), value.to_string())) .collect() } // TODO: realize this function //...
{ parse_form_urlencoded(body_data) }
conditional_block
_OnDijitClickMixin.js.uncompressed.js
define("dijit/_OnDijitClickMixin", [ "dojo/on", "dojo/_base/array", // array.forEach "dojo/keys", // keys.ENTER keys.SPACE "dojo/_base/declare", // declare "dojo/has", // has("dom-addeventlistener") "dojo/_base/unload", // unload.addOnWindowUnload "dojo/_base/window", // win.doc.addEventListener win.doc.a...
return ret; });
ret.a11yclick = a11yclick; // back compat
random_line_split
isolate_service_test.py
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be
import base64 import json import os import shutil import tempfile import unittest import zlib import mock from core.services import isolate_service def ContentResponse(content): return [{'content': base64.b64encode(zlib.compress(content.encode('utf-8')))}] def UrlResponse(url, content): return [{'url': url},...
# found in the LICENSE file.
random_line_split
isolate_service_test.py
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import base64 import json import os import shutil import tempfile import unittest import zlib import mock from core.services import isolate_service def C...
def testRetrieveCompressed_fromUrl(self): self.mock_request.side_effect = UrlResponse('http://get/response', 'OK!') self.assertEqual(isolate_service.RetrieveCompressed('hash'), zlib.compress(b'OK!')) def testRetrieveCompressed_usesCache(self): self.mock_request.side_effect = Cont...
self.mock_request.side_effect = ContentResponse('OK!') self.assertEqual(isolate_service.RetrieveCompressed('hash'), zlib.compress(b'OK!'))
identifier_body
isolate_service_test.py
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import base64 import json import os import shutil import tempfile import unittest import zlib import mock from core.services import isolate_service def C...
(self): shutil.rmtree(self.temp_dir) mock.patch.stopall() def testRetrieve_content(self): self.mock_request.side_effect = ContentResponse('OK!') self.assertEqual(isolate_service.Retrieve('hash'), b'OK!') def testRetrieve_fromUrl(self): self.mock_request.side_effect = UrlResponse('http://get/re...
tearDown
identifier_name
dmui.js
){ target[ name ] = copy; } } else if ( deep && copy && ( isPlainObject(copy) || (copyIsArray = isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move origina...
return object; }()) ); util.browser = (function(){ "use strict"; var navigator = window.navigator; var browser = { versions: (function(){ var u = navigator.userAgent, app = navigator.appVersion; var vendor = navigator.vendor; return { u: u, app: app, vendor: vendor, windows: u.indexOf('Windows') >...
random_line_split
dmui.js
target[ name ] = copy; } } else if ( deep && copy && ( isPlainObject(copy) || (copyIsArray = isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original ...
tFullYear(); month = month || now.getMonth()+1; return getDurationStr('calendarMonth', paramToDate(year, month-1)); } function month(year, month){ var now = new Date(); year = year || now.getFullYear(); month = month || now.getMonth
r || now.ge
identifier_name
dmui.js
Date, paramToDate : paramToDate, strToDate : strToDate, timeToStr : timeToStr, durationToStr : durationToStr, durationToObj : durationToObj, typeToStr : typeToStr, weekdayToStr : weekdayToStr, zhDateToStr : zhDateToStr, zhDatetimeToStr : zhDatetimeToStr, fillZero : fillZero }; function getDate()...
fmt = fmt||'yyyy-MM-dd hh:mm
conditional_block
dmui.js
){ target[ name ] = copy; } } else if ( deep && copy && ( isPlainObject(copy) || (copyIsArray = isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move origina...
rationStr('month', new Date()); } function currentYear(){ return getDurationStr('year', new Date()); } function calendarMonth(year, month){ var now = new Date(); year = year || now.getFullYear(); month = month || now.getMonth()+1; return getDurationStr('calendarMonth', paramToDate(year, month-1))...
)); } function currentMonth(){ return getDu
identifier_body
composite_props.py
from typing import Any from typing import Tuple from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import select from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import composite Base = declarative_base() class Point: def
(self, x: int, y: int): self.x = x self.y = y def __composite_values__(self) -> Tuple[int, int]: return self.x, self.y def __repr__(self) -> str: return "Point(x=%r, y=%r)" % (self.x, self.y) def __eq__(self, other: Any) -> bool: return ( isinstance(oth...
__init__
identifier_name
composite_props.py
from typing import Any from typing import Tuple from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import select from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import composite Base = declarative_base() class Point: def __init__(self, x: int, y: int): ...
# inferred from right hand side start = composite(Point, x1, y1) # taken from left hand side end: Point = composite(Point, x2, y2) v1 = Vertex(start=Point(3, 4), end=Point(5, 6)) # I'm not even sure composites support this but it should work from a # typing perspective stmt = select(Vertex).where(V...
x1 = Column(Integer) y1 = Column(Integer) x2 = Column(Integer) y2 = Column(Integer)
random_line_split
composite_props.py
from typing import Any from typing import Tuple from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import select from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import composite Base = declarative_base() class Point: def __init__(self, x: int, y: int): ...
def __ne__(self, other: Any) -> bool: return not self.__eq__(other) class Vertex(Base): __tablename__ = "vertices" id = Column(Integer, primary_key=True) x1 = Column(Integer) y1 = Column(Integer) x2 = Column(Integer) y2 = Column(Integer) # inferred from right hand side ...
return ( isinstance(other, Point) and other.x == self.x and other.y == self.y )
identifier_body
random_points_on_a_circle.py
# -*- coding: utf-8 -*- import os from collections import defaultdict from random import choice world = defaultdict(int) possiblepoints = [(x, y) for x in range(-15, 16) for y in range(-15, 16) if 10 <= abs(x + y * 1j) <= 15] for i in range(100): world[choice(possiblepoints)] +...
world[choice(possiblepoints)] += 1 for x in range(-15, 16): print(''.join(str(min([9, world[(x, y)]])) if world[(x, y)] else ' ' for y in range(-15, 16))) os.system("pause")
for i in range(1000):
random_line_split
random_points_on_a_circle.py
# -*- coding: utf-8 -*- import os from collections import defaultdict from random import choice world = defaultdict(int) possiblepoints = [(x, y) for x in range(-15, 16) for y in range(-15, 16) if 10 <= abs(x + y * 1j) <= 15] for i in range(100): world[choice(possiblepoints)] +...
for x in range(-15, 16): print(''.join(str(min([9, world[(x, y)]])) if world[(x, y)] else ' ' for y in range(-15, 16))) os.system("pause")
world[choice(possiblepoints)] += 1
conditional_block
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read().replace('.. :changelog:', ...
package_dir={'kubestack': 'kubestack'}, include_package_data=True, install_requires=requirements, license="BSD", zip_safe=False, keywords='kubestack', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: ...
packages=[ 'kubestack', ],
random_line_split
query.py
def __eq__(self, other): return type(self) == type(other) def __hash__(self): return 0 class FieldQuery(Query): """An abstract query that searches in a specific field for a pattern. Subclasses must provide a `value_match` class method, which determines whether a certain pattern ...
return f"{self.__class__.__name__}()"
identifier_body
query.py
if not s: return None try: return int(s) except ValueError: try: return float(s) except ValueError: raise InvalidQueryArgumentValueError(s, "an int or a float") def __init__(self, field, pattern, fast=True): su...
raise ValueError(f'Invalid precision {precision}')
conditional_block
query.py
(FieldQuery): """A query that looks for exact matches in an item field.""" def col_clause(self): return self.field + " = ?", [self.pattern] @classmethod def value_match(cls, pattern, value): return pattern == value class NoneQuery(FieldQuery): """A query that checks whether a fie...
MatchQuery
identifier_name
query.py
: date = datetime.strptime(string, format_option) return date, ord except ValueError: # Parsing failed. pass return (None, None) if not string: return None # Chec...
field = '(CASE ' \ 'WHEN TYPEOF({0})="text" THEN LOWER({0}) ' \
random_line_split
globalize.culture.id.js
/* * Globalize Culture id * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file...
namesAbbr: ["Minggu","Sen","Sel","Rabu","Kamis","Jumat","Sabtu"], namesShort: ["M","S","S","R","K","J","S"] }, months: { names: ["Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","Nopember","Desember",""], namesAbbr: ["Jan","Feb","Mar","Apr","Mei","Jun",...
calendars: { standard: { firstDay: 1, days: { names: ["Minggu","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu"],
random_line_split
globalize.culture.id.js
/* * Globalize Culture id * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file...
Globalize.addCultureInfo( "id", "default", { name: "id", englishName: "Indonesian", nativeName: "Bahasa Indonesia", language: "id", numberFormat: { ",": ".", ".": ",", percent: { ",": ".", ".": "," }, currency: { decimals: 0, ",": ".", ".": ",", symbol: "Rp" } }...
{ // Global variable Globalize = window.Globalize; }
conditional_block
nerv35.py
#!/usr/local/bin/python ################################################### # Jeffrey Herbstman # nerv3.py # Goal: Named entity recognition script to pull names/place from text # called as python nerv3.py text_path_or_file # # Inputs: # path - text file or directory containing text files # output - output file name # O...
url = 'https://gateway-a.watsonplatform.net/calls/text/TextGetRankedNamedEntities' payload = { 'apikey': AlchemyApi_Key, 'outputMode': 'xml', 'text': text, 'max_items': '3' } r = requests.post(url,payload) root = ET.fromstring(r) place_list = ['City', 'Continent', 'Count...
tmpdir = "/tmp/pagekicker" #personal api key saved as api_key.txt parser = argparse.ArgumentParser() parser.add_argument('path', help = "target file or directory for NER") parser.add_argument('outfile', help = "target file for output") parser.add_argument('uuid', help = "uuid") args = parser.parse_args() in_fi...
identifier_body
nerv35.py
#!/usr/local/bin/python ################################################### # Jeffrey Herbstman # nerv3.py # Goal: Named entity recognition script to pull names/place from text # called as python nerv3.py text_path_or_file # # Inputs: # path - text file or directory containing text files # output - output file name # O...
else: Other[entity[3].text] = [entity[1].text, entity[2].text] #print lists ordered by relevance Places_s = sorted(Places, key = Places.get, reverse = True) People_s = sorted(People, key = People.get, reverse = True) Other_s = sorted(Other, key = Other.get, reverse = True) with codecs.open(out_file, mode =...
Places[entity[3].text] = [entity[1].text, entity[2].text]
conditional_block
nerv35.py
#!/usr/local/bin/python ################################################### # Jeffrey Herbstman # nerv3.py # Goal: Named entity recognition script to pull names/place from text # called as python nerv3.py text_path_or_file # # Inputs: # path - text file or directory containing text files # output - output file name # O...
from watson_developer_cloud import AlchemyLanguageV1 import argparse import xml.etree.ElementTree as ET import requests import codecs import os #================================================= def listwrite(output_file,thelist): for item in thelist: item.encode('utf-8') output_file.write("%s\n" % item) #======...
random_line_split
nerv35.py
#!/usr/local/bin/python ################################################### # Jeffrey Herbstman # nerv3.py # Goal: Named entity recognition script to pull names/place from text # called as python nerv3.py text_path_or_file # # Inputs: # path - text file or directory containing text files # output - output file name # O...
(output_file,thelist): for item in thelist: item.encode('utf-8') output_file.write("%s\n" % item) #================================================= def main(): tmpdir = "/tmp/pagekicker" #personal api key saved as api_key.txt parser = argparse.ArgumentParser() parser.add_argument('path', help = "target fi...
listwrite
identifier_name
mayberef.rs
use std::ops::Deref; use self::MaybeRef::*; pub enum MaybeRef<'a, T: 'a> { Ref(&'a T), Val(T), } impl<'a, T: Clone> MaybeRef<'a, T> { pub fn take(self) -> T { match self { Val(t) => t, Ref(t) => t.clone(), } } } impl<'a, T> Deref for MaybeRef<'a, T> { type ...
(&self) -> &T { match *self { Ref(t) => t, Val(ref t) => t, } } } #[cfg(test)] mod test { use super::MaybeRef::*; #[test] fn test() { let x = "foo"; let r = Ref(&x); let v = Val(x); assert_eq!(r.take(), v.take()); } }
deref
identifier_name
mayberef.rs
use std::ops::Deref; use self::MaybeRef::*; pub enum MaybeRef<'a, T: 'a> { Ref(&'a T), Val(T), } impl<'a, T: Clone> MaybeRef<'a, T> { pub fn take(self) -> T { match self { Val(t) => t, Ref(t) => t.clone(), } } } impl<'a, T> Deref for MaybeRef<'a, T> { type ...
}
{ let x = "foo"; let r = Ref(&x); let v = Val(x); assert_eq!(r.take(), v.take()); }
identifier_body
mayberef.rs
use std::ops::Deref; use self::MaybeRef::*; pub enum MaybeRef<'a, T: 'a> { Ref(&'a T), Val(T), } impl<'a, T: Clone> MaybeRef<'a, T> { pub fn take(self) -> T { match self { Val(t) => t, Ref(t) => t.clone(), } } } impl<'a, T> Deref for MaybeRef<'a, T> { type ...
} }
let r = Ref(&x); let v = Val(x); assert_eq!(r.take(), v.take());
random_line_split
cache.py
"""Caching Library using redis.""" import logging from functools import wraps from flask import current_app from walrus import Walrus import api import hashlib import pickle from api import PicoException log = logging.getLogger(__name__) __redis = { "walrus": None, "cache": None, "zsets": {"scores": No...
else: key = "%s:%s" % (f.__name__, _hash_key(args, kwargs)) value = f(*args, **kwargs) get_cache().set(key, value) return value def memoize(_f=None, **cached_kwargs): """walrus.Cache.cached wrapper that reuses shared cache.""" def decorator(f): @wraps(f) d...
raise PicoException("Error: Do not manually reset_cache get_score")
conditional_block
cache.py
"""Caching Library using redis.""" import logging from functools import wraps from flask import current_app from walrus import Walrus import api import hashlib import pickle from api import PicoException log = logging.getLogger(__name__) __redis = { "walrus": None, "cache": None, "zsets": {"scores": No...
global __redis if __redis["zsets"].get("scores") is None: __redis["zsets"]["scores"] = get_conn().ZSet("scores") return __redis["zsets"]["scores"] def get_scoreboard_cache(**kwargs): global __redis scoreboard_name = "scoreboard:{}".format(_hash_key((), kwargs)) if __redis["zsets"].get(...
def get_score_cache():
random_line_split
cache.py
"""Caching Library using redis.""" import logging from functools import wraps from flask import current_app from walrus import Walrus import api import hashlib import pickle from api import PicoException log = logging.getLogger(__name__) __redis = { "walrus": None, "cache": None, "zsets": {"scores": No...
(): """Get a walrus cache, reusing one if it exists.""" global __redis if __redis.get("cache") is None: __redis["cache"] = get_conn().cache(default_timeout=0) return __redis["cache"] def get_score_cache(): global __redis if __redis["zsets"].get("scores") is None: __redis["zsets...
get_cache
identifier_name
cache.py
"""Caching Library using redis.""" import logging from functools import wraps from flask import current_app from walrus import Walrus import api import hashlib import pickle from api import PicoException log = logging.getLogger(__name__) __redis = { "walrus": None, "cache": None, "zsets": {"scores": No...
def get_score_cache(): global __redis if __redis["zsets"].get("scores") is None: __redis["zsets"]["scores"] = get_conn().ZSet("scores") return __redis["zsets"]["scores"] def get_scoreboard_cache(**kwargs): global __redis scoreboard_name = "scoreboard:{}".format(_hash_key((), kwargs)) ...
"""Get a walrus cache, reusing one if it exists.""" global __redis if __redis.get("cache") is None: __redis["cache"] = get_conn().cache(default_timeout=0) return __redis["cache"]
identifier_body
__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2013 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # pu...
'license': 'AGPL-3', 'website': 'http://www.odoo-magento-connector.com', 'description': """ Magento Connector - Pricing =========================== Extension for **Magento Connector**. The prices of the products are managed in OpenERP using pricelists and are pushed to Magento. """, 'images': [], 'demo': [], 'd...
'author': "MagentoERPconnect Core Editors,Odoo Community Association (OCA)",
random_line_split
cashier.js
function
(){ var data = 'action=loadCashier'; data += '&' + $('#osForm').serialize(); $.ajax({ url: 'OverShortCashierPage.php', data: data, success: function(response){ $('#display').html(response); $('#countSCA').focus(); } }); $('#date').val(''); $('#empno').val(''); } function resumSheet(){ var cou...
loadCashier
identifier_name
cashier.js
function loadCashier(){ var data = 'action=loadCashier'; data += '&' + $('#osForm').serialize(); $.ajax({ url: 'OverShortCashierPage.php', data: data, success: function(response){ $('#display').html(response); $('#countSCA').focus(); } }); $('#date').val(''); $('#empno').val(''); } function re...
sum += Number(numbers[i]); } if (sum > 0) { $('#countCA').val(sum); } }
random_line_split
cashier.js
function loadCashier(){ var data = 'action=loadCashier'; data += '&' + $('#osForm').serialize(); $.ajax({ url: 'OverShortCashierPage.php', data: data, success: function(response){ $('#display').html(response); $('#countSCA').focus(); } }); $('#date').val(''); $('#empno').val(''); } function re...
{ var entry = $('#cash-counter').val(); var regexp = /[0-9\.]+/g; var numbers = entry.match(regexp); var sum = 0.0; for (var i=0; i<numbers.length; i++) { sum += Number(numbers[i]); } if (sum > 0) { $('#countCA').val(sum); } }
identifier_body
bitmap_glyph.rs
use std::ptr::null_mut; use { ffi, Bitmap }; pub struct BitmapGlyph { library_raw: ffi::FT_Library, raw: ffi::FT_BitmapGlyph } impl BitmapGlyph { pub unsafe fn from_raw(library_raw: ffi::FT_Library, raw: ffi::FT_BitmapGlyph) -> Self { ffi::FT_Reference_Library(library_raw); BitmapGlyph { l...
} #[inline(always)] pub fn top(&self) -> i32 { unsafe { (*self.raw).top } } #[inline(always)] pub fn bitmap(&self) -> Bitmap { unsafe { Bitmap::from_raw(&(*self.raw).bitmap) } } #[inline(always)] pub fn raw(&self) -> &ffi::FT_BitmapGlyphRec { ...
pub fn left(&self) -> i32 { unsafe { (*self.raw).left }
random_line_split
bitmap_glyph.rs
use std::ptr::null_mut; use { ffi, Bitmap }; pub struct BitmapGlyph { library_raw: ffi::FT_Library, raw: ffi::FT_BitmapGlyph } impl BitmapGlyph { pub unsafe fn from_raw(library_raw: ffi::FT_Library, raw: ffi::FT_BitmapGlyph) -> Self { ffi::FT_Reference_Library(library_raw); BitmapGlyph { l...
(&self) -> Self { let mut target = null_mut(); let err = unsafe { ffi::FT_Glyph_Copy(self.raw as ffi::FT_Glyph, &mut target) }; if err == ffi::FT_Err_Ok { unsafe { BitmapGlyph::from_raw(self.library_raw, target as ffi::FT_BitmapGlyph) } } else { ...
clone
identifier_name
bitmap_glyph.rs
use std::ptr::null_mut; use { ffi, Bitmap }; pub struct BitmapGlyph { library_raw: ffi::FT_Library, raw: ffi::FT_BitmapGlyph } impl BitmapGlyph { pub unsafe fn from_raw(library_raw: ffi::FT_Library, raw: ffi::FT_BitmapGlyph) -> Self { ffi::FT_Reference_Library(library_raw); BitmapGlyph { l...
#[inline(always)] pub fn top(&self) -> i32 { unsafe { (*self.raw).top } } #[inline(always)] pub fn bitmap(&self) -> Bitmap { unsafe { Bitmap::from_raw(&(*self.raw).bitmap) } } #[inline(always)] pub fn raw(&self) -> &ffi::FT_BitmapGlyphRec { ...
{ unsafe { (*self.raw).left } }
identifier_body
bitmap_glyph.rs
use std::ptr::null_mut; use { ffi, Bitmap }; pub struct BitmapGlyph { library_raw: ffi::FT_Library, raw: ffi::FT_BitmapGlyph } impl BitmapGlyph { pub unsafe fn from_raw(library_raw: ffi::FT_Library, raw: ffi::FT_BitmapGlyph) -> Self { ffi::FT_Reference_Library(library_raw); BitmapGlyph { l...
} }
{ panic!("Failed to drop library") }
conditional_block
VehicleHubConnectionManager.ts
/** * Manage signlar connections to the vehicleHub */ class VehicleHubConnectionManager { /** * If the hub is connectd */ connected: boolean; /** * Function to call when the connection state changes. Can be used for alerts. * @param state the current state of the connection * @re...
this.connected = connected; } }
this.connectionStateChangeFunction(connected); }
conditional_block
VehicleHubConnectionManager.ts
/** * Manage signlar connections to the vehicleHub */ class VehicleHubConnectionManager { /** * If the hub is connectd */ connected: boolean; /** * Function to call when the connection state changes. Can be used for alerts. * @param state the current state of the connection * @re...
this.setConnectedState(false); // try tor reconnect after 1 second setTimeout(() => { this.connectHub(() => { }); }, 1000); }); }); } else { th...
this.connected = false; this.connectionStateChangeFunction = connectionStateChangeFunction; this.hub = $.connection.vehicleHub; if (this.hub && this.hub.client) { this.hub.client.updateVehicle = updateFunction; this.connectHub(() => { // handle k...
identifier_body
VehicleHubConnectionManager.ts
/** * Manage signlar connections to the vehicleHub */ class Ve
/** * If the hub is connectd */ connected: boolean; /** * Function to call when the connection state changes. Can be used for alerts. * @param state the current state of the connection * @returns {} */ private connectionStateChangeFunction: (state: boolean) => void; /*...
hicleHubConnectionManager {
identifier_name
VehicleHubConnectionManager.ts
/** * Manage signlar connections to the vehicleHub */ class VehicleHubConnectionManager { /** * If the hub is connectd */ connected: boolean; /** * Function to call when the connection state changes. Can be used for alerts. * @param state the current state of the connection * @re...
private connectHub = (successCallback: () => void): void => { $.connection .hub .start() .done($.proxy(() => { console.log('connected'); this.setConnectedState(true); successCallback(); }, this)); } /** ...
* @param successCallback the function to call when the connection has be successfully made. */
random_line_split
utils.py
""" Utilities for instructor unit tests """ import datetime import json import random import six from pytz import UTC from util.date_utils import get_default_time_display class FakeInfo(object): """Parent class for faking objects used in tests""" FEATURES = [] def __init__(self): for feature ...
(FakeInfo): """ Fake task info needed for email content list """ FEATURES = [ 'task_input', 'task_output', 'requester', ] def __init__(self, email_id, num_sent, num_failed, sent_to): super(FakeContentTask, self).__init__() self.task_input = {'email_id': email_id}...
FakeContentTask
identifier_name
utils.py
""" Utilities for instructor unit tests """ import datetime import json import random import six from pytz import UTC from util.date_utils import get_default_time_display class FakeInfo(object): """Parent class for faking objects used in tests""" FEATURES = [] def __init__(self): for feature ...
'task_output', 'requester', ] def __init__(self, email_id, num_sent, num_failed, sent_to): super(FakeContentTask, self).__init__() self.task_input = {'email_id': email_id} self.task_input = json.dumps(self.task_input) self.task_output = {'succeeded': num_sent, 'f...
class FakeContentTask(FakeInfo): """ Fake task info needed for email content list """ FEATURES = [ 'task_input',
random_line_split
utils.py
""" Utilities for instructor unit tests """ import datetime import json import random import six from pytz import UTC from util.date_utils import get_default_time_display class FakeInfo(object): """Parent class for faking objects used in tests""" FEATURES = [] def __init__(self):
def to_dict(self): """ Returns a dict representation of the object """ return {key: getattr(self, key) for key in self.FEATURES} class FakeContentTask(FakeInfo): """ Fake task info needed for email content list """ FEATURES = [ 'task_input', 'task_output', 'reques...
for feature in self.FEATURES: setattr(self, feature, u'expected')
identifier_body
utils.py
""" Utilities for instructor unit tests """ import datetime import json import random import six from pytz import UTC from util.date_utils import get_default_time_display class FakeInfo(object): """Parent class for faking objects used in tests""" FEATURES = [] def __init__(self): for feature ...
self.number_sent = number_sent fake_email_dict = fake_email.to_dict() self.email = {feature: fake_email_dict[feature] for feature in self.EMAIL_FEATURES} self.requester = u'expected' self.sent_to = [u'expected']
number_sent += ', ' + str(num_failed) + " failed"
conditional_block
systemjs_component_resolver.ts
import {Type, global, isString} from '../facade/lang'; import {ComponentFactory} from './component_factory'; import {ComponentResolver} from './component_resolver'; const _SEPARATOR = '#'; /** * Component resolver that can load components lazily * @experimental */ export class SystemJsComponentResolver implements...
return (<any>global) .System.import(module) .then((module: any) => this._resolver.resolveComponent(module[component])); } return this._resolver.resolveComponent(componentType); } clearCache(): void {} } const FACTORY_MODULE_SUFFIX = '.ngfactory'; const FACTORY_CLASS_SUFFIX = '...
{ // Use the default export when no component is specified component = 'default'; }
conditional_block
systemjs_component_resolver.ts
import {Type, global, isString} from '../facade/lang'; import {ComponentFactory} from './component_factory'; import {ComponentResolver} from './component_resolver'; const _SEPARATOR = '#'; /** * Component resolver that can load components lazily * @experimental */ export class SystemJsComponentResolver implements...
clearCache(): void {} }
{ if (isString(componentType)) { let [module, factory] = componentType.split(_SEPARATOR); return (<any>global) .System.import(module + FACTORY_MODULE_SUFFIX) .then((module: any) => module[factory + FACTORY_CLASS_SUFFIX]); } return Promise.resolve(null); }
identifier_body
systemjs_component_resolver.ts
import {Type, global, isString} from '../facade/lang'; import {ComponentFactory} from './component_factory'; import {ComponentResolver} from './component_resolver'; const _SEPARATOR = '#'; /** * Component resolver that can load components lazily * @experimental */ export class
implements ComponentResolver { constructor(private _resolver: ComponentResolver) {} resolveComponent(componentType: string|Type): Promise<ComponentFactory<any>> { if (isString(componentType)) { let [module, component] = componentType.split(_SEPARATOR); if (component === void(0)) { // Use ...
SystemJsComponentResolver
identifier_name
systemjs_component_resolver.ts
import {Type, global, isString} from '../facade/lang'; import {ComponentFactory} from './component_factory'; import {ComponentResolver} from './component_resolver'; const _SEPARATOR = '#'; /** * Component resolver that can load components lazily * @experimental */ export class SystemJsComponentResolver implements...
/** * Component resolver that can load component factories lazily * @experimental */ export class SystemJsCmpFactoryResolver implements ComponentResolver { resolveComponent(componentType: string|Type): Promise<ComponentFactory<any>> { if (isString(componentType)) { let [module, factory] = componentType.s...
const FACTORY_MODULE_SUFFIX = '.ngfactory'; const FACTORY_CLASS_SUFFIX = 'NgFactory';
random_line_split
createSolid.js
/* * Copyright 2020 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
}); it('should convert with full opacity', () => { expect(createSolid(0, 255, 0, 1)).toStrictEqual({ color: { r: 0, g: 255, b: 0 }, }); }); it('should convert with less than full opacity', () => { expect(createSolid(0, 0, 255, 0.1)).toStrictEqual({ color: { r: 0, g: 0, b: 255, a: 0.1 }...
describe('createSolid', () => { it('should convert with specifying opacity', () => { expect(createSolid(255, 0, 0)).toStrictEqual({ color: { r: 255, g: 0, b: 0 }, });
random_line_split
dom.js
import Element from '../../../shared/Element'; import Elements from '../../../shared/Elements'; import link from '../../../shared/link'; import { isNormalElement } from '../../../shared/helper'; export function createElements(elements, parent) { elements.forEach( element => appendElement(element, parent) ...
{ Object.assign(node.style, styles); }
identifier_body
dom.js
import Element from '../../../shared/Element'; import Elements from '../../../shared/Elements'; import link from '../../../shared/link'; import { isNormalElement } from '../../../shared/helper'; export function createElements(elements, parent) { elements.forEach( element => appendElement(element, parent) ...
setProps(node, { tag, type: props.type , props }); // props } else if (Elements.isInstance(element)) { const node = document.createDocumentFragment(); // package createElements(element, node); } else { node = document.createTextNode(element); } ...
{ // only link normal nodes link(node, element); }
conditional_block
dom.js
import Element from '../../../shared/Element'; import Elements from '../../../shared/Elements'; import link from '../../../shared/link'; import { isNormalElement } from '../../../shared/helper'; export function createElements(elements, parent) { elements.forEach( element => appendElement(element, parent) ...
(node, styles) { Object.assign(node.style, styles); }
setStyle
identifier_name
dom.js
import Element from '../../../shared/Element'; import Elements from '../../../shared/Elements'; import link from '../../../shared/link'; import { isNormalElement } from '../../../shared/helper'; export function createElements(elements, parent) { elements.forEach( element => appendElement(element, parent) ...
} export function setStyle(node, styles) { Object.assign(node.style, styles); }
} else { node.setAttribute(name, props[name]); } });
random_line_split
blast_func.py
""" Copyright 2017 Ryan Wick (rrwick@gmail.com) https://github.com/rrwick/Unicycler This module contains functions relating to BLAST, which Unicycler uses to rotate completed circular replicons to a standard starting point. This file is part of Unicycler. Unicycler is free software: you can redistribute it and/or mod...
def find_start_gene(sequence, start_genes_fasta, identity_threshold, coverage_threshold, blast_dir, makeblastdb_path, tblastn_path): """ This function uses tblastn to look for start genes in the sequence. It returns the first gene (using the order in the file) which meets the identity...
pass
identifier_body
blast_func.py
""" Copyright 2017 Ryan Wick (rrwick@gmail.com) https://github.com/rrwick/Unicycler This module contains functions relating to BLAST, which Unicycler uses to rotate completed circular replicons to a standard starting point. This file is part of Unicycler. Unicycler is free software: you can redistribute it and/or mod...
(object): def __init__(self, blast_line, seq_len): self.qseqid = '' self.pident, self.qstart, self.bitscore, self.query_cov, self.start_pos = 0, 0, 0, 0, 0 self.flip = False parts = blast_line.strip().split('\t') if len(parts) > 7: self.qseqid = parts[0] ...
BlastHit
identifier_name
blast_func.py
""" Copyright 2017 Ryan Wick (rrwick@gmail.com) https://github.com/rrwick/Unicycler This module contains functions relating to BLAST, which Unicycler uses to rotate completed circular replicons to a standard starting point. This file is part of Unicycler. Unicycler is free software: you can redistribute it and/or mod...
raise CannotFindStart # Run the tblastn search. command = [tblastn_path, '-db', replicon_fasta_filename, '-query', start_genes_fasta, '-outfmt', '6 qseqid sstart send pident qlen qseq qstart bitscore', '-num_threads', '1'] log.log(' ' + ' '.join(command), 2) process = subprocess...
if err: log.log('\nmakeblastdb encountered an error:\n' + err.decode()) os.chdir(starting_dir)
random_line_split
blast_func.py
""" Copyright 2017 Ryan Wick (rrwick@gmail.com) https://github.com/rrwick/Unicycler This module contains functions relating to BLAST, which Unicycler uses to rotate completed circular replicons to a standard starting point. This file is part of Unicycler. Unicycler is free software: you can redistribute it and/or mod...
os.chdir(starting_dir) if best_bitscore: return best_hit else: raise CannotFindStart class BlastHit(object): def __init__(self, blast_line, seq_len): self.qseqid = '' self.pident, self.qstart, self.bitscore, self.query_cov, self.start_pos = 0, 0, 0, 0, 0 sel...
best_hit = hit best_bitscore = hit.bitscore
conditional_block
i18n_apply.ts
= mutableOpCodes[++i] as string; // This code is used for ICU expressions only, since we don't support // directives/components in ICUs, we don't need to worry about inputs here setElementAttribute( renderer, getNativeByIndex(elementNodeIndex, lView) as RElement, null, null,...
e for this ICU const caseIndex = getCaseIndex(tIcu, value); let activeCaseIndex = getCurrentICUCaseIndex(tIcu, lView); if (activeCaseIndex !== caseIndex) { applyIcuSwitchCaseRemove(tView, tIcu, lView); lView[tIcu.currentCaseLViewIndex] = caseIndex === null ? null : ~caseIndex; if (caseIndex !== null) ...
identifier_body
i18n_apply.ts
attrName, attrValue, null); break; default: if (ngDevMode) { throw new RuntimeError( RuntimeErrorCode.INVALID_I18N_STRUCTURE, `Unable to determine the type of mutate operation for "${opCode}"`); } } } else { ...
(tView: TView, tIcu: TIc
identifier_name
i18n_apply.ts
OpCode.SHIFT; let rNode = lView[index]; if (rNode === null) { // We only create new DOM nodes if they don't already exist: If ICU switches case back to a // case which was already instantiated, no need to create new DOM nodes. rNode = lView[index] = isComment ? renderer.createComment...
heck if we should apply the next update const checkBit = updateOpCodes[i] as number; // Number of opCodes to skip until next set of update codes const skipCodes = updateOpCodes[++i] as number; if (checkBit & changeMask) { // The value has been updated since last checked let value = ''; ...
conditional_block
i18n_apply.ts
as string; const attrValue = mutableOpCodes[++i] as string; // This code is used for ICU expressions only, since we don't support // directives/components in ICUs, we don't need to worry about inputs here setElementAttribute( renderer, getNativeByIndex(elementNodeI...
} }
random_line_split
refcounted.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/. */ //! A generic, safe mechanism by which DOM objects can be pinned and transferred //! between tasks (or intra-task ...
// hashtable entry. info!("attempt to cleanup an unrecognized reflector"); } } }) } } /// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES pub unsafe extern "C" fn trace_refcounted_objects(tracer: *mut JSTracer, ...
// there could be a cleanup message dispatched, then a new // pinned reference obtained and released before the message // is processed, at which point there would be no matching
random_line_split
refcounted.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/. */ //! A generic, safe mechanism by which DOM objects can be pinned and transferred //! between tasks (or intra-task ...
self) -> Root<T> { assert!(LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); self.owner_thread == (&*live_references) as *const _ as *const libc::c_void })); unsafe { Root::new(NonZero::new(self.ptr as *c...
ot(&
identifier_name
refcounted.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/. */ //! A generic, safe mechanism by which DOM objects can be pinned and transferred //! between tasks (or intra-task ...
} } /// Unpin the given DOM object if its refcount is 0. pub fn cleanup(raw_reflectable: TrustedReference) { let TrustedReference(raw_reflectable) = raw_reflectable; LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); ...
let refcount = Arc::new(Mutex::new(1)); entry.insert(refcount.clone()); refcount }
conditional_block
refcounted.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/. */ //! A generic, safe mechanism by which DOM objects can be pinned and transferred //! between tasks (or intra-task ...
info!("attempt to cleanup an unrecognized reflector"); } } }) } } /// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES pub unsafe extern "C" fn trace_refcounted_objects(tracer: *mut JSTracer, _d...
let TrustedReference(raw_reflectable) = raw_reflectable; LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); let mut table = live_references.table.borrow_mut(); match table.entry(raw_reflectable) { ...
identifier_body
Open_New_Plot_Demo.py
import matplotlib.pyplot as plt from matplotlib.widgets import RadioButtons t = np.arange(0.0, 2.0, 0.01) s0 = np.sin(2*np.pi*t) s1 = np.sin(4*np.pi*t) s2 = np.sin(8*np.pi*t) fig = plt.figure(1) rax = plt.subplot2grid((1,1), (0,0)) radio = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz', 'Clear')) def new_plot(Event): ...
import numpy as np
random_line_split
Open_New_Plot_Demo.py
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import RadioButtons t = np.arange(0.0, 2.0, 0.01) s0 = np.sin(2*np.pi*t) s1 = np.sin(4*np.pi*t) s2 = np.sin(8*np.pi*t) fig = plt.figure(1) rax = plt.subplot2grid((1,1), (0,0)) radio = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz', 'Clear')) def...
(Event): plt.figure(2) if Event == '2 Hz': plt.plot(t, s0) plt.show() if Event == 'Clear': plt.clf().figure(2) if Event == '8 Hz': plt.plot(t, s2) plt.show() if Event == '4 Hz': plt.plot(t,s1) plt.show() radio.on_clicked(new_plot) plt.show()
new_plot
identifier_name
Open_New_Plot_Demo.py
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import RadioButtons t = np.arange(0.0, 2.0, 0.01) s0 = np.sin(2*np.pi*t) s1 = np.sin(4*np.pi*t) s2 = np.sin(8*np.pi*t) fig = plt.figure(1) rax = plt.subplot2grid((1,1), (0,0)) radio = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz', 'Clear')) def...
radio.on_clicked(new_plot) plt.show()
plt.figure(2) if Event == '2 Hz': plt.plot(t, s0) plt.show() if Event == 'Clear': plt.clf().figure(2) if Event == '8 Hz': plt.plot(t, s2) plt.show() if Event == '4 Hz': plt.plot(t,s1) plt.show()
identifier_body
Open_New_Plot_Demo.py
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import RadioButtons t = np.arange(0.0, 2.0, 0.01) s0 = np.sin(2*np.pi*t) s1 = np.sin(4*np.pi*t) s2 = np.sin(8*np.pi*t) fig = plt.figure(1) rax = plt.subplot2grid((1,1), (0,0)) radio = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz', 'Clear')) def...
if Event == 'Clear': plt.clf().figure(2) if Event == '8 Hz': plt.plot(t, s2) plt.show() if Event == '4 Hz': plt.plot(t,s1) plt.show() radio.on_clicked(new_plot) plt.show()
plt.plot(t, s0) plt.show()
conditional_block
15.2.3.6-4-531-11.js
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this n...
}; var setFunc = function (value) { obj.verifySetFunction1 = value; }; Object.defineProperty(obj, "prop", { get: getFunc, set: setFunc }); verifyEqualTo(obj, "prop", getFunc()); verifyWritable(obj, "prop", "verifySetFunction1"); verifyNotEnumerable(obj, "prop"); verifyConfigurable(obj, "prop");
obj.verifySetFunction1 = "data1"; var getFunc = function () { return obj.verifySetFunction1;
random_line_split
Login.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2016-2017 University of Dundee & Open Microscopy Environment. # All Rights Reserved. # Use is subject to license terms supplied in LICENSE.txt # import requests from Parse_OMERO_Properties import USERNAME, PASSWORD, OMERO_WEB_HOST, \ ...
# Create a project: projType = schema_url + '#Project' # Need to specify target group url = save_url + '?group=' + str(groupId) r = session.post(url, json={'Name': 'API TEST foo', '@type': projType}) assert r.status_code == 201 project = r.json()['data'] project_id = project['@id'] print 'Created Project:', project_i...
print ' ', p['@id'], p['Name']
conditional_block
Login.py
#!/usr/bin/env python # -*- coding: utf-8 -*-
# import requests from Parse_OMERO_Properties import USERNAME, PASSWORD, OMERO_WEB_HOST, \ SERVER_NAME session = requests.Session() # Start by getting supported versions from the base url... api_url = '%s/api/' % OMERO_WEB_HOST print "Starting at:", api_url r = session.get(api_url) # we get a list of versions v...
# # Copyright (C) 2016-2017 University of Dundee & Open Microscopy Environment. # All Rights Reserved. # Use is subject to license terms supplied in LICENSE.txt
random_line_split
address.rs
//! Ethereum address use std::str::FromStr; use std::fmt; use utils::bigint::M256; use utils::{read_hex, ParseHexError}; use rlp::{Encodable, RlpStream}; #[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)] /// Represents an Ethereum address. This address is 20 bytes long. pub struct Address([u8; 20]); impl Address { ...
}
{ for i in 0..20 { write!(f, "{:02X}", self.0[i])?; } Ok(()) }
identifier_body
address.rs
//! Ethereum address use std::str::FromStr; use std::fmt; use utils::bigint::M256; use utils::{read_hex, ParseHexError}; use rlp::{Encodable, RlpStream}; #[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)] /// Represents an Ethereum address. This address is 20 bytes long. pub struct Address([u8; 20]); impl Address { ...
(self) -> [u8; 20] { self.0 } } impl FromStr for Address { type Err = ParseHexError; fn from_str(s: &str) -> Result<Address, ParseHexError> { read_hex(s).and_then(|v| { if v.len() > 20 { Err(ParseHexError::TooLong) } else if v.len() < 20 { ...
into
identifier_name
address.rs
//! Ethereum address use std::str::FromStr; use std::fmt; use utils::bigint::M256; use utils::{read_hex, ParseHexError}; use rlp::{Encodable, RlpStream}; #[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)] /// Represents an Ethereum address. This address is 20 bytes long. pub struct Address([u8; 20]); impl Address { ...
impl Into<[u8; 20]> for Address { fn into(self) -> [u8; 20] { self.0 } } impl FromStr for Address { type Err = ParseHexError; fn from_str(s: &str) -> Result<Address, ParseHexError> { read_hex(s).and_then(|v| { if v.len() > 20 { Err(ParseHexError::TooLong) ...
Address(a) } }
random_line_split
field.decorator.ts
import { SchemaFactoryError, SchemaFactoryErrorType } from '../type-factory'; import { FieldOption } from '../metadata'; import { PaginationMiddleware } from '../middleware'; import { getMetadataArgsStorage } from '../metadata-builder'; /** * GraphQL Schema field * See [GraphQL Documentation - Field]{@link http://g...
SchemaFactoryErrorType.INPUT_FIELD_SHOULD_NOT_BE_PAGINATED); } getMetadataArgsStorage().fields.push({ target: target, name: (option && option.name) ? option.name : propertyKey, description: option ? option.description : null, property: propertyKey, type: option ? option.typ...
throw new SchemaFactoryError(`Field '${propertyKey}' can't have pagination enabled`,
random_line_split
field.decorator.ts
import { SchemaFactoryError, SchemaFactoryErrorType } from '../type-factory'; import { FieldOption } from '../metadata'; import { PaginationMiddleware } from '../middleware'; import { getMetadataArgsStorage } from '../metadata-builder'; /** * GraphQL Schema field * See [GraphQL Documentation - Field]{@link http://g...
getMetadataArgsStorage().fields.push({ target: target, name: (option && option.name) ? option.name : propertyKey, description: option ? option.description : null, property: propertyKey, type: option ? option.type : null, nonNull: option ? option.nonNull : null, isList: opt...
{ throw new SchemaFactoryError(`Field '${propertyKey}' can't have pagination enabled`, SchemaFactoryErrorType.INPUT_FIELD_SHOULD_NOT_BE_PAGINATED); }
conditional_block
field.decorator.ts
import { SchemaFactoryError, SchemaFactoryErrorType } from '../type-factory'; import { FieldOption } from '../metadata'; import { PaginationMiddleware } from '../middleware'; import { getMetadataArgsStorage } from '../metadata-builder'; /** * GraphQL Schema field * See [GraphQL Documentation - Field]{@link http://g...
(option?: FieldOption) { return function (target: any, propertyKey: any, methodDescriptor?: any) { if (option && option.pagination && (!methodDescriptor || !methodDescriptor.value)) { throw new SchemaFactoryError(`Field '${propertyKey}' can't have pagination enabled`, SchemaFactoryErrorType.INPUT_FI...
Field
identifier_name
field.decorator.ts
import { SchemaFactoryError, SchemaFactoryErrorType } from '../type-factory'; import { FieldOption } from '../metadata'; import { PaginationMiddleware } from '../middleware'; import { getMetadataArgsStorage } from '../metadata-builder'; /** * GraphQL Schema field * See [GraphQL Documentation - Field]{@link http://g...
}
{ return function (target: any, propertyKey: any, methodDescriptor?: any) { if (option && option.pagination && (!methodDescriptor || !methodDescriptor.value)) { throw new SchemaFactoryError(`Field '${propertyKey}' can't have pagination enabled`, SchemaFactoryErrorType.INPUT_FIELD_SHOULD_NOT_BE_PAGIN...
identifier_body
index.js
const BaseStep = require('../step'); const EntryProxy = require('../../entry-proxy'); const analyze = require('../../helpers/analytics/analytics')('gst'); // TODO pull below out to (variation) helper function convertVariationalPath(variations, from, toVariationId) { const toDir = variations.find(variation => varia...
(entry) { this._processed.add(entry.id); if (this._processed.size >= this._cache.size()) { this._processed.clear(); if (++this._curGstIndex >= this._gsts.length) { this._cache.entries().forEach(({id}) => { this.emit('done', {entryId: id}); ...
gstDone
identifier_name
index.js
const BaseStep = require('../step'); const EntryProxy = require('../../entry-proxy'); const analyze = require('../../helpers/analytics/analytics')('gst'); // TODO pull below out to (variation) helper function convertVariationalPath(variations, from, toVariationId) { const toDir = variations.find(variation => varia...
return node.variation === this._baseVariationId || node.variation === false; }); }); // In case a new entry is introduced in variations without one // in the base folder, the main file won't exist. /...
{ const configVariations = new Set(); this._variations.forEach(variation => configVariations.add(variation.id)); // graph has array of arrays. First, make a pass and gather all variation info const variations = new Set(); graph.forEach(nodes => { nodes.forEach(node =...
identifier_body
index.js
const BaseStep = require('../step'); const EntryProxy = require('../../entry-proxy'); const analyze = require('../../helpers/analytics/analytics')('gst'); // TODO pull below out to (variation) helper function convertVariationalPath(variations, from, toVariationId) { const toDir = variations.find(variation => varia...
explorePermutation(graph, onPermutation) { const configVariations = new Set(); this._variations.forEach(variation => configVariations.add(variation.id)); // graph has array of arrays. First, make a pass and gather all variation info const variations = new Set(); graph.forEa...
return this.gstDone(entry); this.performHelper(entry); }
random_line_split
index.js
const BaseStep = require('../step'); const EntryProxy = require('../../entry-proxy'); const analyze = require('../../helpers/analytics/analytics')('gst'); // TODO pull below out to (variation) helper function convertVariationalPath(variations, from, toVariationId) { const toDir = variations.find(variation => varia...
} this.gstDone(main); }) .catch(error => { error.message = `Errored while transforming ${main.id}:\n` + error.message; this.emit('error', {error, id: main.id}); }); }); } } module.exports = GraphSourceTrans...
{ context.addVirtualEntry({ id: proxiedMain.filename, originatingEntry: entry, source: result.source, deps: result.deps, }); }
conditional_block
tests.py
from allauth.socialaccount.tests import OAuth2TestsMixin from allauth.tests import MockedResponse, TestCase from .provider import MicrosoftGraphProvider class
(OAuth2TestsMixin, TestCase): provider_id = MicrosoftGraphProvider.id def get_mocked_response(self): response_data = """ { "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity", "id": "16f5a7b6-5a15-4568-aa5a-31bb117e9967", "businessPho...
MicrosoftGraphTests
identifier_name