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
retiredminer.py
import parole from parole.colornames import colors from parole.display import interpolateRGB import pygame, random import sim_creatures, main, random from util import * description = \ """ This guy should really look into another line of work. """ nagLines = [ '*sigh*', "It's not been the same 'round...
(sim_creatures.NPC): def __init__(self): sim_creatures.NPC.__init__( self, 'retired miner', # name parole.map.AsciiTile('@', colors['Gray']), # symbol, color 11, # str 8, # dex 11, # con 11, # per 10, # spd ...
NPCClass
identifier_name
retiredminer.py
import parole from parole.colornames import colors from parole.display import interpolateRGB import pygame, random import sim_creatures, main, random from util import * description = \ """ This guy should really look into another line of work. """ nagLines = [ '*sigh*', "It's not been the same 'round...
if event.id == 'enter tile': eObj, ePos, eMap = event.args if eMap is self.parentTile.map and eObj is main.player: self.say(random.choice(nagLines)) #======================================== thingClass = NPCClass
return
conditional_block
retiredminer.py
import parole from parole.colornames import colors from parole.display import interpolateRGB import pygame, random import sim_creatures, main, random from util import *
nagLines = [ '*sigh*', "It's not been the same 'round 'ere.", "Ain't been no work since the mines... changed.", "We been in for some rough times.", "I pray they don't get to the wells.", ] class NPCClass(sim_creatures.NPC): def __init__(self): sim_creatures.NPC.__in...
description = \ """ This guy should really look into another line of work. """
random_line_split
forcetouchevent.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::ForceTouchEventBinding; use dom::bindings::codegen::Bindings::ForceTouchEven...
type_: DOMString, force: f32) -> Root<ForceTouchEvent> { let event = box ForceTouchEvent::new_inherited(force); let ev = reflect_dom_object(event, GlobalRef::Window(window), ForceTouchEventBinding::Wrap); ev.upcast::<UIEvent>().InitUIEvent(type_, true, true, Some(wi...
pub fn new(window: &Window,
random_line_split
forcetouchevent.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::ForceTouchEventBinding; use dom::bindings::codegen::Bindings::ForceTouchEven...
(force: f32) -> ForceTouchEvent { ForceTouchEvent { uievent: UIEvent::new_inherited(), force: force, } } pub fn new(window: &Window, type_: DOMString, force: f32) -> Root<ForceTouchEvent> { let event = box ForceTouchEvent::new_inheri...
new_inherited
identifier_name
forcetouchevent.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::ForceTouchEventBinding; use dom::bindings::codegen::Bindings::ForceTouchEven...
// https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.uievent.IsTrusted() } }
{ Finite::wrap(2.0) }
identifier_body
webvr_traits.rs
/* This Source Code Form is subject to the terms of the Mozilla Public
use webvr::*; pub type WebVRResult<T> = Result<T, String>; // Messages from Script thread to WebVR thread. #[derive(Deserialize, Serialize)] pub enum WebVRMsg { RegisterContext(PipelineId), UnregisterContext(PipelineId), PollEvents(IpcSender<bool>), GetDisplays(IpcSender<WebVRResult<Vec<VRDisplayData>...
* 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 ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId;
random_line_split
webvr_traits.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 ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use webvr::*; pub type WebVRResult<T> = ...
{ RegisterContext(PipelineId), UnregisterContext(PipelineId), PollEvents(IpcSender<bool>), GetDisplays(IpcSender<WebVRResult<Vec<VRDisplayData>>>), GetFrameData(PipelineId, u64, f64, f64, IpcSender<WebVRResult<VRFrameData>>), ResetPose(PipelineId, u64, IpcSender<WebVRResult<VRDisplayData>>), ...
WebVRMsg
identifier_name
core.py
from __future__ import absolute_import, division, print_function from itertools import chain from dynd import nd import datashape from datashape.internal_utils import IndexCallable from datashape import discover from functools import partial from ..dispatch import dispatch from blaze.expr import Projection, Field from...
(self): if self._schema: return datashape.dshape(self._schema) if isdimension(self.dshape[0]): return self.dshape.subarray(1) raise TypeError('Datashape is not indexable to schema\n%s' % self.dshape) @property def columns(self): re...
schema
identifier_name
core.py
from __future__ import absolute_import, division, print_function from itertools import chain from dynd import nd import datashape from datashape.internal_utils import IndexCallable from datashape import discover from functools import partial from ..dispatch import dispatch from blaze.expr import Projection, Field from...
def _iter(self): raise NotImplementedError() _dshape = None @property def dshape(self): return datashape.dshape(self._dshape or datashape.Var() * self.schema) _schema = None @property def schema(self): if self._schema: return datashape.dshape(self._s...
yield row
conditional_block
core.py
from __future__ import absolute_import, division, print_function from itertools import chain from dynd import nd import datashape from datashape.internal_utils import IndexCallable from datashape import discover from functools import partial from ..dispatch import dispatch from blaze.expr import Projection, Field from...
yield nd.array(chunk, type=dshape(chunk)) def _chunks(self, blen=100): return partition_all(blen, iter(self)) def as_dynd(self): return self.dynd[:] def as_py(self): if isdimension(self.dshape[0]): return tuple(self) else: return tuple(n...
def chunks(self, **kwargs): def dshape(chunk): return str(len(chunk) * self.dshape.subshape[0]) for chunk in self._chunks(**kwargs):
random_line_split
core.py
from __future__ import absolute_import, division, print_function from itertools import chain from dynd import nd import datashape from datashape.internal_utils import IndexCallable from datashape import discover from functools import partial from ..dispatch import dispatch from blaze.expr import Projection, Field from...
@dispatch(DataDescriptor) def discover(dd): return dd.dshape
return ddesc[:, t.fields[0]]
identifier_body
lastimport.py
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Rafael Bodill http://github.com/rafi # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including #...
def process_tracks(lib, tracks, log): total = len(tracks) total_found = 0 total_fails = 0 log.info('Received {0} tracks in this page, processing...', total) for num in xrange(0, total): song = '' trackid = tracks[num]['mbid'].strip() artist = tracks[num]['artist'].get('na...
return requests.get(API_URL, params={ 'method': 'library.gettracks', 'user': user, 'api_key': plugins.LASTFM_KEY, 'page': bytes(page), 'limit': bytes(limit), 'format': 'json', }).json()
identifier_body
lastimport.py
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Rafael Bodill http://github.com/rafi # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including #...
# If not, try just artist/title if not song: log.debug(u'no album match, trying by artist/title') query = dbcore.AndQuery([ dbcore.query.SubstringQuery('artist', artist), dbcore.query.SubstringQuery('title', title) ]) song...
log.debug(u'no match for mb_trackid {0}, trying by ' u'artist/title/album', trackid) query = dbcore.AndQuery([ dbcore.query.SubstringQuery('artist', artist), dbcore.query.SubstringQuery('title', title), dbcore.query.SubstringQuery('album'...
conditional_block
lastimport.py
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Rafael Bodill http://github.com/rafi # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including #...
(self): cmd = ui.Subcommand('lastimport', help='import last.fm play-count') def func(lib, opts, args): import_lastfm(lib, self._log) cmd.func = func return [cmd] def import_lastfm(lib, log): user = config['lastfm']['user'].get(unicode) per_page = config['lastimpor...
commands
identifier_name
lastimport.py
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Rafael Bodill http://github.com/rafi # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including #...
album = '' if 'album' in tracks[num]: album = tracks[num]['album'].get('name', '').strip() log.debug(u'query: {0} - {1} ({2})', artist, title, album) # First try to query by musicbrainz's trackid if trackid: song = lib.items( dbcore.query...
artist = tracks[num]['artist'].get('name', '').strip() title = tracks[num]['name'].strip()
random_line_split
init.py
import sys from gnucash import * from gnucash import _sw_app_utils from gnucash import _sw_core_utils from gnucash._sw_core_utils import gnc_prefs_is_extra_enabled, gnc_prefs_is_debugging_enabled from gi import require_version require_version('Gtk', '3.0') from gi.repository import Gtk import os sys.path.append(os.pat...
else: shelltypeName = "IPython" banner_style = 'title' # TRANSLATORS: %s is either Python or IPython banner = _("Welcome to GnuCash %s Shell") % shelltypeName console = Console(argv = [], shelltype = shelltype, banner = [[banner, banner_style]], size = 100) window = Gtk.Window(type = G...
shelltypeName = "Python"
conditional_block
init.py
import sys from gnucash import * from gnucash import _sw_app_utils from gnucash import _sw_core_utils from gnucash._sw_core_utils import gnc_prefs_is_extra_enabled, gnc_prefs_is_debugging_enabled from gi import require_version require_version('Gtk', '3.0') from gi.repository import Gtk import os sys.path.append(os.pat...
def scroll_event (self, widget, event): """ Scroll event """ if self.active_canvas: return True return False def button_press_event (self, widget, event): """ Button press event """ return self.refresh() def quit_event (self, widget, event): "...
""" Handle key press event """ if self.active_canvas: self.active_canvas.emit ('key-press-event', event) return True return cons.Console.key_press_event (self, widget, event)
identifier_body
init.py
import sys from gnucash import * from gnucash import _sw_app_utils from gnucash import _sw_core_utils from gnucash._sw_core_utils import gnc_prefs_is_extra_enabled, gnc_prefs_is_debugging_enabled from gi import require_version require_version('Gtk', '3.0') from gi.repository import Gtk import os sys.path.append(os.pat...
# output debug information if gnucash has been started with # gnucash --debug --extra if gnc_prefs_is_extra_enabled() and gnc_prefs_is_debugging_enabled(): print("Hello from python!\n") print("sys.modules.keys(): ", sys.modules.keys(), "\n") print("dir(_sw_app_utils): ", dir(_sw_app_utils), "\n") #ses...
import pycons.console as cons # Restore the SIGTTOU handler signal.signal(signal.SIGTTOU, old_sigttou)
random_line_split
init.py
import sys from gnucash import * from gnucash import _sw_app_utils from gnucash import _sw_core_utils from gnucash._sw_core_utils import gnc_prefs_is_extra_enabled, gnc_prefs_is_debugging_enabled from gi import require_version require_version('Gtk', '3.0') from gi.repository import Gtk import os sys.path.append(os.pat...
(cons.Console): """ GTK python console """ def __init__(self, argv=[], shelltype='python', banner=[], filename=None, size=100, user_local_ns=None, user_global_ns=None): cons.Console.__init__(self, argv, shelltype, banner, filename, size, user_local_ns=user_loca...
Console
identifier_name
run.rs
); let snapshot_path = db_dirs.snapshot_path(); // execute upgrades try!(execute_upgrades(&db_dirs, algorithm, cmd.compaction.compaction_profile(db_dirs.fork_path().as_path()))); // run in daemon mode if let Some(pid_file) = cmd.daemon { try!(daemonize(pid_file)); } // display info about used pruning algori...
wait_for_exit
identifier_name
run.rs
; use dapps::WebappServer; use io_handler::ClientIoHandler; use params::{ SpecType, Pruning, AccountsConfig, GasPricerConfig, MinerExtras, Switch, tracing_switch_to_bool, fatdb_switch_to_bool, }; use helpers::{to_client_config, execute_upgrades, passwords_from_files}; use dir::Directories; use cache::CacheConfig; use...
let miner = Miner::new(cmd.miner_options, cmd.gas_pricer.into(), &spec, Some(account_provider.clone())); miner.set_author(cmd.miner_extras.author); miner.set_gas_floor_target(cmd.miner_extras.gas_floor_target); miner.set_gas_ceil_target(cmd.miner_extras.gas_ceil_target); miner.set_extra_data(cmd.miner_extras.extra...
// create miner
random_line_split
run.rs
; use dapps::WebappServer; use io_handler::ClientIoHandler; use params::{ SpecType, Pruning, AccountsConfig, GasPricerConfig, MinerExtras, Switch, tracing_switch_to_bool, fatdb_switch_to_bool, }; use helpers::{to_client_config, execute_upgrades, passwords_from_files}; use dir::Directories; use cache::CacheConfig; use...
else { sync_config.subprotocol_name.clone_from_slice(spec.subprotocol_name().as_bytes()); } sync_config.fork_block = spec.fork_block(); sync_config.warp_sync = cmd.warp_sync; // prepare account provider let account_provider = Arc::new(try!(prepare_account_provider(&cmd.dirs, cmd.acc_conf))); // create miner ...
{ warn!("Your chain specification's subprotocol length is not 3. Ignoring."); }
conditional_block
run.rs
cmd.logger_config)); // increase max number of open files raise_fd_limit(); // create dirs used by parity try!(cmd.dirs.create_dirs()); // load spec let spec = try!(cmd.spec.spec()); // load genesis hash let genesis_hash = spec.genesis_header().hash(); // database paths let db_dirs = cmd.dirs.database(ge...
{ Err("daemon is no supported on windows".into()) }
identifier_body
util.rs
// Copyright 2017 PingCAP, 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 i...
{ location: PointRef, name: String, } impl From<FeatureRef> for Feature { fn from(r: FeatureRef) -> Feature { let mut f = Feature::default(); f.set_name(r.name); f.mut_location().set_latitude(r.location.latitude); f.mut_location().set_longitude(r.location.longitude); ...
FeatureRef
identifier_name
util.rs
// Copyright 2017 PingCAP, 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 i...
f.mut_location().set_longitude(r.location.longitude); f } } pub fn load_db() -> Vec<Feature> { let data = include_str!("db.json"); let features: Vec<FeatureRef> = serde_json::from_str(data).unwrap(); features.into_iter().map(From::from).collect() } pub fn same_point(lhs: &Point, rhs: &...
random_line_split
init.rs
use std::sync::{atomic, mpsc}; use std::{io, process, thread}; use ctrlc; use crate::control::acio; use crate::{args, control, disk, log, rpc, throttle, tracker}; use crate::{CONFIG, SHUTDOWN, THROT_TOKS}; pub fn init(args: args::Args) -> Result<(), ()> { if let Some(level) = args.level { log::log_init(l...
{ ctrlc::set_handler(move || { if SHUTDOWN.load(atomic::Ordering::SeqCst) { info!("Terminating process!"); process::abort(); } else { info!("Shutting down cleanly. Interrupt again to shut down immediately."); SHUTDOWN.store(true, atomic::Ordering::SeqC...
identifier_body
init.rs
use std::sync::{atomic, mpsc}; use std::{io, process, thread}; use ctrlc; use crate::control::acio; use crate::{args, control, disk, log, rpc, throttle, tracker}; use crate::{CONFIG, SHUTDOWN, THROT_TOKS}; pub fn init(args: args::Args) -> Result<(), ()> { if let Some(level) = args.level { log::log_init(l...
if let Err(e) = init_signals() { error!("Failed to initialize signal handlers: {}", e); return Err(()); } Ok(()) } pub fn run() -> Result<(), ()> { match init_threads() { Ok(threads) => { for thread in threads { if thread.join().is_err() { ...
info!("Initializing"); // Since the config is lazy loaded, dereference now to check it. CONFIG.port;
random_line_split
init.rs
use std::sync::{atomic, mpsc}; use std::{io, process, thread}; use ctrlc; use crate::control::acio; use crate::{args, control, disk, log, rpc, throttle, tracker}; use crate::{CONFIG, SHUTDOWN, THROT_TOKS}; pub fn
(args: args::Args) -> Result<(), ()> { if let Some(level) = args.level { log::log_init(level); } else if cfg!(debug_assertions) { log::log_init(log::LogLevel::Debug); } else { log::log_init(log::LogLevel::Info); } info!("Initializing"); // Since the config is lazy loade...
init
identifier_name
codetest.js
new require('styles/dark')
module.exports = class extends require('base/app'){ prototype(){ this.tools = { Rect:require('shaders/quad'), Code: require('views/code').extend({ w:'100#', h:'100%' }) } } constructor(){ super() //this.code = new this.Code(this, {text:require('/examples/tiny.js').__module__.source}) le...
random_line_split
codetest.js
new require('styles/dark') module.exports = class extends require('base/app'){ prototype(){ this.tools = { Rect:require('shaders/quad'), Code: require('views/code').extend({ w:'100#', h:'100%' }) } } constructor(){ super() //this.code = new this.Code(this, {text:require('/examples/tiny.j...
}
{ /*this.drawRect({ w:100, h:100, color:'red' })*/ this.code.draw(this) }
identifier_body
codetest.js
new require('styles/dark') module.exports = class extends require('base/app'){
(){ this.tools = { Rect:require('shaders/quad'), Code: require('views/code').extend({ w:'100#', h:'100%' }) } } constructor(){ super() //this.code = new this.Code(this, {text:require('/examples/tiny.js').__module__.source}) let code = 'var x=(1,2,)\n' this.code = new this.Code(thi...
prototype
identifier_name
text.rs
extern crate graphics; use piston_window::{Transformed}; use widget::{Widget, State}; use appearance; use layout; use renderer::{self, geometry}; use graphics::character::CharacterCache; #[derive(Default, Clone, Debug)] pub struct Text{ pub text: &'static str, } impl Widget for Text{ fn layout(&self, cartogra...
// TODO - Font's don't render very nicely, seems partly related to sub-pixel positioning graphics::text(color, size as u32, self.text, renderer.glyphs, renderer.context.transform.trans(geometry.position.x, geometry.position.y + (size - (size / 4.11315283...
{ size = font.size; color = font.color; }
conditional_block
text.rs
extern crate graphics; use piston_window::{Transformed}; use widget::{Widget, State}; use appearance; use layout; use renderer::{self, geometry}; use graphics::character::CharacterCache; #[derive(Default, Clone, Debug)] pub struct Text{ pub text: &'static str, } impl Widget for Text{ fn layout(&self, cartogra...
<'a>(&self, renderer: &mut renderer::Renderer, appearance: &appearance::Appearance, geometry: &geometry::Geometry, _state: &'a State) { // Determine font y-position related to size... // Unsure if magic numbers, specific to a font, or related to font system in rust. // 400:(-94..<97.249>..-100.4...
render
identifier_name
text.rs
extern crate graphics; use piston_window::{Transformed}; use widget::{Widget, State}; use appearance; use layout; use renderer::{self, geometry}; use graphics::character::CharacterCache; #[derive(Default, Clone, Debug)] pub struct Text{ pub text: &'static str,
impl Widget for Text{ fn layout(&self, cartographer: &mut layout::Cartographer, appearance: &appearance::Appearance) -> geometry::Xy { let mut size = 20.0; if let Some(ref font) = appearance.font { size = font.size; } geometry::Xy{ x: cartographer.glyphs.wid...
}
random_line_split
text.rs
extern crate graphics; use piston_window::{Transformed}; use widget::{Widget, State}; use appearance; use layout; use renderer::{self, geometry}; use graphics::character::CharacterCache; #[derive(Default, Clone, Debug)] pub struct Text{ pub text: &'static str, } impl Widget for Text{ fn layout(&self, cartogra...
fn render<'a>(&self, renderer: &mut renderer::Renderer, appearance: &appearance::Appearance, geometry: &geometry::Geometry, _state: &'a State) { // Determine font y-position related to size... // Unsure if magic numbers, specific to a font, or related to font system in rust. // 400:(-94..<...
{ let mut size = 20.0; if let Some(ref font) = appearance.font { size = font.size; } geometry::Xy{ x: cartographer.glyphs.width(size as u32, self.text), y: size } }
identifier_body
HomeStreamDemo.tsx
import React from 'react' import range from 'lodash/range' import random from 'lodash/random' import { Stream } from '@nivo/stream' import { useHomeTheme } from './theme' import { dimensions } from './dimensions' const streamDataLayerCount = 5 const generateStreamData = () => range(16).map(() => range(stre...
}
random_line_split
nls.ts
export module nls { export const _nls = { 'custom': { }, 'en-US': { monday: true, weekdays: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], months: ['January', 'February', 'March', 'April', ...
'fi' | 'zh-TW' | 'zh-CN' | 'custom';
'de' |
identifier_name
nls.ts
export module nls { export const _nls = { 'custom': { }, 'en-US': { monday: true, weekdays: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], months: ['January', 'February', 'March', 'April', '...
months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'] } }; export function getWeekdays(locale: languages): string[] { return this.getNls(locale).weekdays; } export function getMonths(locale: languages): string[] { return this....
weekdays: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
random_line_split
nls.ts
export module nls { export const _nls = { 'custom': { }, 'en-US': { monday: true, weekdays: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], months: ['January', 'February', 'March', 'April', ...
identifier_body
cache.py
""" Add simple, flexible caching layer. Uses `dogpile caching http://dogpilecache.readthedocs.org/en/latest/index.html`_. """ __author__ = 'Dan Gunter <dkgunter@lbl.gov>' __date__ = '9/26/15' from dogpile.cache import make_region def my_key_generator(namespace, fn, **kw): fname = fn.__name__ def generate_ke...
(redis_host='localhost', redis_port=6379): region = make_region( function_key_generator=my_key_generator ).configure( 'dogpile.cache.redis', arguments={ 'host': redis_host, 'port': redis_port, 'db': 0, 'redis_expiration_time': 60 * 60 * 2, ...
get_redis_cache
identifier_name
cache.py
""" Add simple, flexible caching layer. Uses `dogpile caching http://dogpilecache.readthedocs.org/en/latest/index.html`_. """ __author__ = 'Dan Gunter <dkgunter@lbl.gov>' __date__ = '9/26/15' from dogpile.cache import make_region def my_key_generator(namespace, fn, **kw): fname = fn.__name__ def generate_ke...
'distributed_lock': True } ) return region
arguments={ 'host': redis_host, 'port': redis_port, 'db': 0, 'redis_expiration_time': 60 * 60 * 2, # 2 hours
random_line_split
cache.py
""" Add simple, flexible caching layer. Uses `dogpile caching http://dogpilecache.readthedocs.org/en/latest/index.html`_. """ __author__ = 'Dan Gunter <dkgunter@lbl.gov>' __date__ = '9/26/15' from dogpile.cache import make_region def my_key_generator(namespace, fn, **kw): fname = fn.__name__ def generate_ke...
region = make_region( function_key_generator=my_key_generator ).configure( 'dogpile.cache.redis', arguments={ 'host': redis_host, 'port': redis_port, 'db': 0, 'redis_expiration_time': 60 * 60 * 2, # 2 hours 'distributed_lock': True...
identifier_body
issue-13853.rs
trait Node { fn zomg(); } trait Graph<N: Node> { fn nodes<'a, I: Iterator<Item=&'a N>>(&'a self) -> I where N: 'a; } impl<N: Node> Graph<N> for Vec<N> { fn nodes<'a, I: Iterator<Item=&'a N>>(&self) -> I where N: 'a { self.iter() //~ ERROR mismatched types } } struct Stuff;...
<N: Node, G: Graph<N>>(graph: &G) { for node in graph.iter() { //~ ERROR no method named `iter` found node.zomg(); } } pub fn main() { let graph = Vec::new(); graph.push(Stuff); iterate(graph); //~ ERROR mismatched types }
iterate
identifier_name
issue-13853.rs
trait Node { fn zomg(); } trait Graph<N: Node> { fn nodes<'a, I: Iterator<Item=&'a N>>(&'a self) -> I where N: 'a;
impl<N: Node> Graph<N> for Vec<N> { fn nodes<'a, I: Iterator<Item=&'a N>>(&self) -> I where N: 'a { self.iter() //~ ERROR mismatched types } } struct Stuff; impl Node for Stuff { fn zomg() { println!("zomg"); } } fn iterate<N: Node, G: Graph<N>>(graph: &G) { for node ...
}
random_line_split
issue-13853.rs
trait Node { fn zomg(); } trait Graph<N: Node> { fn nodes<'a, I: Iterator<Item=&'a N>>(&'a self) -> I where N: 'a; } impl<N: Node> Graph<N> for Vec<N> { fn nodes<'a, I: Iterator<Item=&'a N>>(&self) -> I where N: 'a { self.iter() //~ ERROR mismatched types } } struct Stuff;...
} fn iterate<N: Node, G: Graph<N>>(graph: &G) { for node in graph.iter() { //~ ERROR no method named `iter` found node.zomg(); } } pub fn main() { let graph = Vec::new(); graph.push(Stuff); iterate(graph); //~ ERROR mismatched types }
{ println!("zomg"); }
identifier_body
pat.rs
extern crate std; #[derive(Debug)] pub struct ProgramAssociationTable { pub table_id: u8, pub transport_stream_id: u16, pub version_number: u8, pub current_next_indicator: bool, pub section_number: u8, pub last_section_number: u8, pub program_map: std::collections::HashMap<u16, u16>, pu...
table_id: table_id, transport_stream_id: transport_stream_id, version_number: version_number, current_next_indicator: current_next_indicator, section_number: section_number, last_section_number: last_section_number, program_map: program...
(payload[index + 2] as u32) << 8 | payload[index + 3] as u32; Ok(ProgramAssociationTable {
random_line_split
pat.rs
extern crate std; #[derive(Debug)] pub struct ProgramAssociationTable { pub table_id: u8, pub transport_stream_id: u16, pub version_number: u8, pub current_next_indicator: bool, pub section_number: u8, pub last_section_number: u8, pub program_map: std::collections::HashMap<u16, u16>, pu...
} let section_length = ((payload[1] & 0b00001111) as usize) << 8 | payload[2] as usize; let transport_stream_id = ((payload[3] as u16) << 8) | payload[4] as u16; let version_number = (payload[5] & 0b00111110) >> 1; let current_next_indicator = (payload[5] & 0b00000001) != 0; ...
{ // ISO/IEC 13818-1 2.4.4.1 Table 2-29 // ISO/IEC 13818-1 2.4.4.2 let pointer_field = payload[0] as usize; let payload = &payload[(1 + pointer_field)..]; // ISO/IEC 13818-1 2.4.4.3 Table 2-30 // ISO/IEC 13818-1 2.4.4.4 let table_id = payload[0]; if table...
identifier_body
pat.rs
extern crate std; #[derive(Debug)] pub struct
{ pub table_id: u8, pub transport_stream_id: u16, pub version_number: u8, pub current_next_indicator: bool, pub section_number: u8, pub last_section_number: u8, pub program_map: std::collections::HashMap<u16, u16>, pub crc32: u32, } impl ProgramAssociationTable { pub fn parse(paylo...
ProgramAssociationTable
identifier_name
pat.rs
extern crate std; #[derive(Debug)] pub struct ProgramAssociationTable { pub table_id: u8, pub transport_stream_id: u16, pub version_number: u8, pub current_next_indicator: bool, pub section_number: u8, pub last_section_number: u8, pub program_map: std::collections::HashMap<u16, u16>, pu...
else { program_map.insert(pid, program_number); } } let index = 8 + n * 4; let crc32 = (payload[index] as u32) << 24 | (payload[index + 1] as u32) << 16 | (payload[index + 2] as u32) << 8 | payload[index + 3] as u32; O...
{ // Network_PID }
conditional_block
rooms.service.ts
import {Injectable} from '@angular/core'; @Injectable() export class RoomsService { smartTableData = [ { Name: "93692657-f9c0-4a5e-a89f-f5058743b6c4", Description: "Bonusprint 2", Floor: 2, Sensors: [], Indicators: [] }, { Name: "93632657-f9c0-4a5e-a89f-f5058743b6c4",...
const request = new XMLHttpRequest(); request.responseType = "json"; request.addEventListener("load", () => { resolve(request.response); }); request.open("GET", `http://10.41.60.221/stahplight/api/v1/rooms`); request.send(); }); } static createRoom(data) { const...
} ]; getData(): Promise<any> { return new Promise((resolve, reject) => {
random_line_split
rooms.service.ts
import {Injectable} from '@angular/core'; @Injectable() export class RoomsService { smartTableData = [ { Name: "93692657-f9c0-4a5e-a89f-f5058743b6c4", Description: "Bonusprint 2", Floor: 2, Sensors: [], Indicators: [] }, { Name: "93632657-f9c0-4a5e-a89f-f5058743b6c4",...
(data) { const request = new XMLHttpRequest(); request.responseType = "json"; request.open("POST", `http://10.41.60.221/stahplight/api/v1/rooms`); request.setRequestHeader('Content-Type', 'application/json'); request.send(JSON.stringify(data)); } static updateRoom(data) { const request = ne...
createRoom
identifier_name
cpg_gene.py
#!/usr/bin/env python ''' Purpose: This script, using default values, determines and plots the CpG islands in relation to a given feature "type" (e.g. "gene" or "mRNA") from a GFF file which corresponds to the user-provided fasta file. Note: CpG Islands are determined by ObEx = (Observed CpG) / (Expected CpG) , def...
print "CpG Islands predicted...\n" print "Generating Figure...\n" # Releasing SeqRecs MergedRecs = None SeqRecList = None # Pre-check DistArr Results if len(DistArr) < 2: print "WARNING, "+ str(len(DistArr)) + " sites were found." print "Consider changing parameters.\n" # Generate Figure: ObExRes = pd.Data...
Arr = cpgmod.get_closest(Rec, GffDb, StartRange, FeatGFF, ID_Feat) if Arr <> False: Arr.append(ObEx) DistArr.append(Arr)
conditional_block
cpg_gene.py
#!/usr/bin/env python ''' Purpose: This script, using default values, determines and plots the CpG islands in relation to a given feature "type" (e.g. "gene" or "mRNA") from a GFF file which corresponds to the user-provided fasta file. Note: CpG Islands are determined by ObEx = (Observed CpG) / (Expected CpG) , def...
# Capture command line args, with or without defaults if __name__ == '__main__': # Parse the arguments LineArgs = cpgmod.parseArguments() # Populate vars with args FastaFile = LineArgs.FastaFile GffFile = LineArgs.GffFile OutFile = LineArgs.FileOut Step = LineArgs.s WinSize = LineArgs.w ObExthresh = LineArgs....
import pandas as pd import numpy as np from ggplot import *
random_line_split
search_box.js
'use strict' var React = require('react') var request = require('xhr') var object_assign = require('object-assign') var Spinner = require('../../shared/spinner.js') var make_query = function () { var email = this.refs.email.value var vals = { id: this.refs.id.value, last_name: this.refs.last_name.value, ...
var query = make_query.bind(this)() var { updateResults, none_found, clear_none_found } = this.props this.props.clear_none_found() this.setState({ loading: true }) request({ method: 'GET', url: '/api/members?where=' + JSON.stringify(query) + '&populate=[payments]' }, function (err, r...
e.preventDefault()
random_line_split
search_box.js
'use strict' var React = require('react') var request = require('xhr') var object_assign = require('object-assign') var Spinner = require('../../shared/spinner.js') var make_query = function () { var email = this.refs.email.value var vals = { id: this.refs.id.value, last_name: this.refs.last_name.value, ...
return !!email ? { or: [ add_in_filtered({primary_email: email}), add_in_filtered({secondary_email: email}) ] } : filtered_vals } function get_actual_values (object) { return Object.keys(object) .filter(function (key) { return ( !!object[key] || object[key] === false ) }) .reduce(function (agg,...
{ return object_assign({}, obj, filtered_vals) }
identifier_body
search_box.js
'use strict' var React = require('react') var request = require('xhr') var object_assign = require('object-assign') var Spinner = require('../../shared/spinner.js') var make_query = function () { var email = this.refs.email.value var vals = { id: this.refs.id.value, last_name: this.refs.last_name.value, ...
(object) { return Object.keys(object) .filter(function (key) { return ( !!object[key] || object[key] === false ) }) .reduce(function (agg, key) { agg[key] = object[key] return agg }, {}) } var SearchBox = React.createClass({ getInitialState: function () { return { loading: false } }...
get_actual_values
identifier_name
index.d.ts
/* * @license Apache-2.0
* 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 writing, software * distributed under the...
* * Copyright (c) 2019 The Stdlib Authors. *
random_line_split
passwordStrength.ts
/* * Copyright (c) 2014-2021 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ import { waitForInputToHaveValue, waitForInputToNotBeEmpty, waitForElementToGetClicked, waitInMs, waitForAngularRouteToBeVisited, waitForLogOut } from '../helpers/helpers' import { ChallengeInstruction } from '../' export co...
}
random_line_split
CollateralToken.js
const CollateralToken = artifacts.require('CollateralToken'); // basic tests to ensure collateral token works and is set up to allow trading contract('CollateralToken', function(accounts) { let initBalance; let collateralToken; // test setup of token for collateral it('Initial supply should be 1e+22', async fu...
const balanceToTransfer = initBalance / 2; await collateralToken.transfer(accounts[1], balanceToTransfer, { from: accounts[0] }); const secondAcctBalance = await collateralToken.balanceOf.call(accounts[1]); assert.isTrue(secondAcctBalance.eq(balanceToTransfer), "Transfer didn't register correctly"); }...
it('Main account should be able to transfer balance', async function() {
random_line_split
test_requestobject.py
#!/usr/bin/env python import unittest import securetrading from securetrading.test import abstract_test_stobjects import six class Test_Request(abstract_test_stobjects.Abstract_Test_StObjects): def setUp(self): super(Test_Request, self).setUp() self.class_ = securetrading.Request def test___...
(self): get_requests = self.get_securetrading_requests get_request = self.get_securetrading_request requests1 = get_requests([]) requests2 = get_requests( [get_request({"a": "b"})]) requests3 = get_requests( [get_request({"a": "b"}), get_req...
test_verify
identifier_name
test_requestobject.py
#!/usr/bin/env python import unittest import securetrading from securetrading.test import abstract_test_stobjects import six class Test_Request(abstract_test_stobjects.Abstract_Test_StObjects): def setUp(self): super(Test_Request, self).setUp() self.class_ = securetrading.Request def test___...
def test__set_cachetoken(self): exp1 = self.get_securetrading_request( {"datacenterurl": "https://webservices.securetrading.net", "datacenterpath": "/json/", "cachetoken": "17-ae7e511172a07c2fb45db4c73388087e4d850777386a5d72029aaf895\ 87f3cf0"}) ...
request = self.class_() six.assertRegex(self, request["requestreference"], "A[a-z0-9]+") self.assertEqual(securetrading.version_info, self.version_info)
identifier_body
test_requestobject.py
#!/usr/bin/env python import unittest import securetrading from securetrading.test import abstract_test_stobjects import six class Test_Request(abstract_test_stobjects.Abstract_Test_StObjects): def setUp(self): super(Test_Request, self).setUp() self.class_ = securetrading.Request def test___...
get_request(datacenter_url_dict)]) datacenter_path_dict = {"datacenterpath": "path"} requests5 = get_requests( [get_request({"a": "b"}), get_request(datacenter_path_dict)]) tests = [(requests1, None, None, None, None), (requests2, None, Non...
[get_request({"a": "b"}),
random_line_split
test_requestobject.py
#!/usr/bin/env python import unittest import securetrading from securetrading.test import abstract_test_stobjects import six class Test_Request(abstract_test_stobjects.Abstract_Test_StObjects): def setUp(self): super(Test_Request, self).setUp() self.class_ = securetrading.Request def test___...
self.assertEqual(request, expected) class Test_Requests(Test_Request): def setUp(self): super(Test_Requests, self).setUp() self.class_ = securetrading.Requests def test_verify(self): get_requests = self.get_securetrading_requests get_request = self.get_securetrad...
del obj["requestreference"] # Unique for every request object
conditional_block
lib.rs
_controller.record_event(event_category, event_action, event_label, event_value); let cid1 = read_client_id(); // This sleep is necessary there is no file system interactions. thread::sleep(std::time::Duration::from_secs(3)); { let mut metrics_controller2 = MetricsController::new( e...
read_client_id
identifier_name
lib.rs
saved to the // disk properly. Otherwise, you get a file not found error. thread::sleep(std::time::Duration::from_secs(2)); let path = Path::new("thread.dat"); let display = path.display(); // Open the path in read-only mode. let mut file = match File::open(&path) { Err(why) => panic!...
// Read the environment variable for the Google Access Token... Obtain // this from Query Explorer. It is good for an hour. let access_token:String; let key = "GOOGLE_ACCESS_TOKEN"; match env::var_os(key) { Some(val) => { access_token = val.to_str().unwrap().to_string(); ...
{ let event_category = "test"; let event_action = "integration"; let event_label = &Uuid::new_v4().to_simple_string().to_string(); let event_value = 5; let ei = get_event_info(); create_config("metricsconfig.json"); let mut metrics_controller = MetricsController::new...
identifier_body
lib.rs
saved to the // disk properly. Otherwise, you get a file not found error. thread::sleep(std::time::Duration::from_secs(2)); let path = Path::new("thread.dat"); let display = path.display(); // Open the path in read-only mode. let mut file = match File::open(&path) { Err(why) => panic!...
pub app_name: &'a str, pub app_version: &'a str, pub app_update_channel: &'a str, pub app_build_id: &'a str, pub app_platform: &'a str, pub locale: &'a str, pub device: &'a str, pub arch: &'a str, pub os: &'a str, pub os_version: &'a str } #[cfg(feature = "integration")] fn get_...
#[cfg(feature = "integration")] struct MockEventInfo<'a> {
random_line_split
hex.rs
#![allow(deprecated)] use std::hash::{Hasher, Hash, SipHasher}; use rustc_serialize::hex::ToHex; pub fn to_hex(num: u64) -> String {
(num >> 32) as u8, (num >> 40) as u8, (num >> 48) as u8, (num >> 56) as u8, ].to_hex() } pub fn hash_u64<H: Hash>(hashable: &H) -> u64 { let mut hasher = SipHasher::new_with_keys(0, 0); hashable.hash(&mut hasher); hasher.finish() } pub fn short_hash<H: Hash>(hashable: &...
[ (num >> 0) as u8, (num >> 8) as u8, (num >> 16) as u8, (num >> 24) as u8,
random_line_split
hex.rs
#![allow(deprecated)] use std::hash::{Hasher, Hash, SipHasher}; use rustc_serialize::hex::ToHex; pub fn to_hex(num: u64) -> String { [ (num >> 0) as u8, (num >> 8) as u8, (num >> 16) as u8, (num >> 24) as u8, (num >> 32) as u8, (num >> 40) as u8, (num >> ...
<H: Hash>(hashable: &H) -> String { to_hex(hash_u64(hashable)) }
short_hash
identifier_name
hex.rs
#![allow(deprecated)] use std::hash::{Hasher, Hash, SipHasher}; use rustc_serialize::hex::ToHex; pub fn to_hex(num: u64) -> String
pub fn hash_u64<H: Hash>(hashable: &H) -> u64 { let mut hasher = SipHasher::new_with_keys(0, 0); hashable.hash(&mut hasher); hasher.finish() } pub fn short_hash<H: Hash>(hashable: &H) -> String { to_hex(hash_u64(hashable)) }
{ [ (num >> 0) as u8, (num >> 8) as u8, (num >> 16) as u8, (num >> 24) as u8, (num >> 32) as u8, (num >> 40) as u8, (num >> 48) as u8, (num >> 56) as u8, ].to_hex() }
identifier_body
sync-username-and-names.py
#!/usr/bin/env python3 # Copyright 2020 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0+ import sys from wazo_auth_client import Client as AuthClient from wazo_confd_client import Client as ConfdClient from xivo.chain_map import ChainMap from xivo.config_helper import read_config_file_hier...
(): file_config = read_config_file_hierarchy(_DEFAULT_CONFIG) key_config = _load_key_file(ChainMap(file_config, _DEFAULT_CONFIG)) return ChainMap(key_config, file_config, _DEFAULT_CONFIG) def _load_key_file(config): key_file = parse_config_file(config['auth']['key_file']) return {'auth': {'usernam...
load_config
identifier_name
sync-username-and-names.py
#!/usr/bin/env python3 # Copyright 2020 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0+ import sys from wazo_auth_client import Client as AuthClient from wazo_confd_client import Client as ConfdClient from xivo.chain_map import ChainMap from xivo.config_helper import read_config_file_hier...
def _load_key_file(config): key_file = parse_config_file(config['auth']['key_file']) return {'auth': {'username': key_file['service_id'], 'password': key_file['service_key']}} def list_broken_endpoints(confd_client): endpoints = [] response = confd_client.lines.list() for line in response['item...
file_config = read_config_file_hierarchy(_DEFAULT_CONFIG) key_config = _load_key_file(ChainMap(file_config, _DEFAULT_CONFIG)) return ChainMap(key_config, file_config, _DEFAULT_CONFIG)
identifier_body
sync-username-and-names.py
#!/usr/bin/env python3 # Copyright 2020 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0+ import sys from wazo_auth_client import Client as AuthClient from wazo_confd_client import Client as ConfdClient from xivo.chain_map import ChainMap from xivo.config_helper import read_config_file_hier...
return endpoints def fix_endpoint(confd_client, endpoint_uuid): endpoint = confd_client.endpoints_sip.get(endpoint_uuid) name = endpoint['name'] auth_section_options = endpoint.get('auth_section_options', []) for key, value in auth_section_options: if key == 'username': auth_s...
endpoint = line['endpoint_sip'] if not endpoint: continue name = endpoint.get('name') auth_section_options = endpoint.get('auth_section_options', []) username = None for key, value in auth_section_options: if key == 'username': username = v...
conditional_block
sync-username-and-names.py
#!/usr/bin/env python3 # Copyright 2020 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0+ import sys from wazo_auth_client import Client as AuthClient from wazo_confd_client import Client as ConfdClient from xivo.chain_map import ChainMap from xivo.config_helper import read_config_file_hier...
def fix_endpoint(confd_client, endpoint_uuid): endpoint = confd_client.endpoints_sip.get(endpoint_uuid) name = endpoint['name'] auth_section_options = endpoint.get('auth_section_options', []) for key, value in auth_section_options: if key == 'username': auth_section_options.remove([...
endpoints.append(endpoint['uuid']) return endpoints
random_line_split
stackvec.rs
use minimal_lexical::bigint; #[cfg(feature = "alloc")] pub use minimal_lexical::heapvec::HeapVec as VecType; #[cfg(not(feature = "alloc"))] pub use minimal_lexical::stackvec::StackVec as VecType; pub fn vec_from_u32(x: &[u32]) -> VecType { let mut vec = VecType::new(); #[cfg(not(all(target_pointer_width = "64"...
{ for xi in x.chunks(2) { match xi.len() { 1 => vec.try_push(xi[0] as bigint::Limb).unwrap(), 2 => { let xi0 = xi[0] as bigint::Limb; let xi1 = xi[1] as bigint::Limb; vec.try_push((xi1 << 32) | xi0).unwra...
random_line_split
stackvec.rs
use minimal_lexical::bigint; #[cfg(feature = "alloc")] pub use minimal_lexical::heapvec::HeapVec as VecType; #[cfg(not(feature = "alloc"))] pub use minimal_lexical::stackvec::StackVec as VecType; pub fn vec_from_u32(x: &[u32]) -> VecType
} } } vec }
{ let mut vec = VecType::new(); #[cfg(not(all(target_pointer_width = "64", not(target_arch = "sparc"))))] { for &xi in x { vec.try_push(xi as bigint::Limb).unwrap(); } } #[cfg(all(target_pointer_width = "64", not(target_arch = "sparc")))] { for xi in x.chunks...
identifier_body
stackvec.rs
use minimal_lexical::bigint; #[cfg(feature = "alloc")] pub use minimal_lexical::heapvec::HeapVec as VecType; #[cfg(not(feature = "alloc"))] pub use minimal_lexical::stackvec::StackVec as VecType; pub fn
(x: &[u32]) -> VecType { let mut vec = VecType::new(); #[cfg(not(all(target_pointer_width = "64", not(target_arch = "sparc"))))] { for &xi in x { vec.try_push(xi as bigint::Limb).unwrap(); } } #[cfg(all(target_pointer_width = "64", not(target_arch = "sparc")))] { ...
vec_from_u32
identifier_name
profile.ts
import { Cloud } from './cloud'; export class Credentials { id: string; name: string; default: boolean; resourcetype: string; cloud: Cloud; cloud_id: string; // only used when saving new record } export class AWSCredentials extends Credentials { aws_access_key: string; aws_secret_key: ...
export class CredVerificationResult { result: string; details: string; }
random_line_split
profile.ts
import { Cloud } from './cloud'; export class Credentials { id: string; name: string; default: boolean; resourcetype: string; cloud: Cloud; cloud_id: string; // only used when saving new record } export class AWSCredentials extends Credentials { aws_access_key: string; aws_secret_key: ...
extends Credentials { os_username: string; os_password: string; os_project_name: string; os_project_domain_id: string; os_project_domain_name: string; os_user_domain_name: string; os_identity_api_version: string; } export class AzureCredentials extends Credentials { azure_subscription_...
OpenStackCredentials
identifier_name
plots.py
import numpy as np import matplotlib.pyplot as plt from wwb_scanner.scan_objects.spectrum import compare_spectra from wwb_scanner.file_handlers import BaseImporter class BasePlot(object): def __init__(self, **kwargs): self.filename = kwargs.get('filename') if self.filename is not None: ...
plt.show() class DiffSpectrum(object): def __init__(self, **kwargs): self.spectra = [] self.figure, self.axes = plt.subplots(3, 1, sharex='col') def add_spectrum(self, spectrum=None, **kwargs): name = kwargs.get('name') if name is None: name = str(len(self.s...
samples = [self.spectrum.samples.get(f) for f in center_frequencies] ymin = self.y.min() plt.vlines(center_frequencies, [ymin] * len(center_frequencies), [s.magnitude-5 if s.magnitude-5 > ymin else s.magnitude for s in samples])
conditional_block
plots.py
import numpy as np import matplotlib.pyplot as plt from wwb_scanner.scan_objects.spectrum import compare_spectra from wwb_scanner.file_handlers import BaseImporter class BasePlot(object):
self._y = value @property def figure(self): return getattr(self, '_figure', None) @figure.setter def figure(self, figure): self._figure = figure #self.timer = figure.canvas.new_timer(interval=100) #self.timer.add_callback(self.on_timer) def on_timer(self): ...
def __init__(self, **kwargs): self.filename = kwargs.get('filename') if self.filename is not None: self.spectrum = BaseImporter.import_file(self.filename) else: self.spectrum = kwargs.get('spectrum') #self.figure.canvas.mpl_connect('idle_event', self.on_idle) ...
identifier_body
plots.py
import numpy as np import matplotlib.pyplot as plt from wwb_scanner.scan_objects.spectrum import compare_spectra from wwb_scanner.file_handlers import BaseImporter class BasePlot(object): def __init__(self, **kwargs): self.filename = kwargs.get('filename') if self.filename is not None: ...
(BasePlot): def build_plot(self): self.figure = plt.figure() self.plot = plt.plot(*self.build_data())[0] plt.xlabel('frequency (MHz)') plt.ylabel('dBm') center_frequencies = self.spectrum.center_frequencies if len(center_frequencies): samples = [self.spect...
SpectrumPlot
identifier_name
plots.py
import numpy as np import matplotlib.pyplot as plt from wwb_scanner.scan_objects.spectrum import compare_spectra from wwb_scanner.file_handlers import BaseImporter class BasePlot(object): def __init__(self, **kwargs): self.filename = kwargs.get('filename') if self.filename is not None: ...
x = self.x = np.fromiter(self.spectrum.iter_frequencies(), dtype) y = self.y = np.fromiter((s.magnitude for s in self.spectrum.iter_samples()), dtype) if not hasattr(self, 'plot'): self.spectrum.data_updated.clear() return x, y def update_plot(self): ...
random_line_split
add_sponsorship.py
__author__ = 'tbri' from openerp import models, fields, api, _ class add_sponsorship_wizard(models.TransientModel): _name = 'add_sponsorship_wizard' def _get_all_children(self): c = [] children = self.env['res.partner'].search([('sponsored_child', '=', 'True')]) for n in children: ...
return c #sponsor_id = fields.Many2one('sponsor') # see partner.py........... ## child_id = fields.Many2one('sponsored_child', domain=[('active','=',True)]) child_id = fields.Selection( _get_all_children , string=_('Child')) sub_sponsor = fields.Many2one('res.partner', _('Sub Sponsor'), d...
child_ref = '%s %s' % (n.child_ident, n.name) c.append( (n.id, child_ref) )
conditional_block
add_sponsorship.py
__author__ = 'tbri' from openerp import models, fields, api, _ class add_sponsorship_wizard(models.TransientModel):
def data_save(self): print "DATA_SAVE 1", self._context """ DATA_SAVAE! {'lang': 'en_US', 'search_disable_custom_filters': True, 'tz': False, 'uid': 1, 'active_model': 'sponsor', 'active_ids': [1], 'active_id': 1} """ model = self._context['active_model'] active_id = ...
_name = 'add_sponsorship_wizard' def _get_all_children(self): c = [] children = self.env['res.partner'].search([('sponsored_child', '=', 'True')]) for n in children: child_ref = '%s %s' % (n.child_ident, n.name) c.append( (n.id, child_ref) ) return c #...
identifier_body
add_sponsorship.py
__author__ = 'tbri' from openerp import models, fields, api, _ class
(models.TransientModel): _name = 'add_sponsorship_wizard' def _get_all_children(self): c = [] children = self.env['res.partner'].search([('sponsored_child', '=', 'True')]) for n in children: child_ref = '%s %s' % (n.child_ident, n.name) c.append( (n.id, child_r...
add_sponsorship_wizard
identifier_name
add_sponsorship.py
__author__ = 'tbri'
class add_sponsorship_wizard(models.TransientModel): _name = 'add_sponsorship_wizard' def _get_all_children(self): c = [] children = self.env['res.partner'].search([('sponsored_child', '=', 'True')]) for n in children: child_ref = '%s %s' % (n.child_ident, n.name) ...
from openerp import models, fields, api, _
random_line_split
testTwoLayerQG.py
import time, sys import numpy as np import matplotlib.pyplot as plt sys.path.append('../../') from py2Periodic.physics import twoLayerQG from numpy import pi params = { 'f0' : 1.0e-4, 'Lx' : 1.0e6, 'beta' : 1.5e-11, 'defRadius' : 1.5e4, 'H1' : 500.0, 'H2' ...
qg = twoLayerQG.model(**params) qg.describe_model() # Initial condition: Ro = 1.0e-3 f0 = 1.0e-4 q1 = Ro*f0*np.random.standard_normal(qg.physVarShape) q2 = Ro*f0*np.random.standard_normal(qg.physVarShape) qg.set_q1_and_q2(q1, q2) # Run a loop nt = 1e3 for ii in np.arange(0, 1e3): qg.step_nSteps(nSteps=nt, dnL...
# Create the two-layer model
random_line_split
testTwoLayerQG.py
import time, sys import numpy as np import matplotlib.pyplot as plt sys.path.append('../../') from py2Periodic.physics import twoLayerQG from numpy import pi params = { 'f0' : 1.0e-4, 'Lx' : 1.0e6, 'beta' : 1.5e-11, 'defRadius' : 1.5e4, 'H1' : 500.0, 'H2' ...
print("Close the plot to end the program") plt.show()
qg.step_nSteps(nSteps=nt, dnLog=nt) qg.update_state_variables() fig = plt.figure('Perturbation vorticity', figsize=(8, 8)); plt.clf() plt.subplot(221); plt.imshow(qg.q1) plt.subplot(222); plt.imshow(qg.q2) plt.subplot(223); plt.imshow(np.abs(qg.soln[0:qg.ny//2, :, 0])) plt.subplot(224); plt.i...
conditional_block
build.rs
/* * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to i...
config, &proto_files .iter() .map(|path| path.to_str().unwrap()) .collect::<Vec<_>>(), &include_dirs .iter() .map(|p| p.to_str().unwrap()) .collect::<Vec<_>>(), )?; // This te...
tonic_build::configure() .build_server(true) .compile_with_config(
random_line_split
build.rs
/* * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to i...
"proto/quilkin/filters/pass/v1alpha1/pass.proto", "proto/quilkin/filters/token_router/v1alpha1/token_router.proto", "proto/udpa/xds/core/v3/resource_name.proto", ] .iter() .map(|name| std::env::current_dir().unwrap().join(name)) .collect::<Vec<_>>(); let include_dirs = vec![...
{ let proto_files = vec![ "proto/data-plane-api/envoy/config/accesslog/v3/accesslog.proto", "proto/data-plane-api/envoy/config/cluster/v3/cluster.proto", "proto/data-plane-api/envoy/config/listener/v3/listener.proto", "proto/data-plane-api/envoy/config/route/v3/route.proto", ...
identifier_body
build.rs
/* * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to i...
() -> Result<(), Box<dyn std::error::Error>> { let proto_files = vec![ "proto/data-plane-api/envoy/config/accesslog/v3/accesslog.proto", "proto/data-plane-api/envoy/config/cluster/v3/cluster.proto", "proto/data-plane-api/envoy/config/listener/v3/listener.proto", "proto/data-plane-api...
main
identifier_name
x86_64.rs
pub type c_long = i64; pub type c_ulong = u64; pub type time_t = i64; pub type suseconds_t = i64; s! { pub struct stat { pub st_dev: ::dev_t, pub st_ino: ::ino_t, pub st_mode: ::mode_t, pub st_nlink: ::nlink_t, pub st_uid: ::uid_t, pub st_gid: ::gid_t, pub st...
pub st_blocks: ::blkcnt_t, pub st_blksize: ::blksize_t, pub st_flags: ::fflags_t, pub st_gen: ::uint32_t, pub st_lspare: ::int32_t, pub st_birthtime: ::time_t, pub st_birthtime_nsec: ::c_long, } }
pub st_ctime_nsec: ::c_long, pub st_size: ::off_t,
random_line_split
note.py
: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Gene...
(self, cr, uid, data, context=None): user_id = super(res_users, self).create(cr, uid, data, context=context) note_obj = self.pool['note.stage'] data_obj = self.pool['ir.model.data'] is_employee = self.has_group(cr, user_id, 'base.group_user') if is_employee: for n in ...
create
identifier_name
note.py
: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Gene...
result[0]['__domain'] = domain + ['|', dom_in, dom_not_in] result[0]['stage_id_count'] += nb_notes_ws else: # add the first stage column result = [{ '__context': {'group_by': g...
current_stage_ids = self.pool.get('note.stage').search(cr,uid,[('user_id','=',uid)], context=context) if current_stage_ids: #if the user have some stages stages = self.pool['note.stage'].browse(cr, uid, current_stage_ids, context=context) result = [{ #notes by stage for sta...
conditional_block
note.py
: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Gene...
_description = "Note Stage" _columns = { 'name': fields.char('Stage Name', translate=True, required=True), 'sequence': fields.integer('Sequence', help="Used to order the note stages"), 'user_id': fields.many2one('res.users', 'Owner', help="Owner of the note stage.", required=True, ondele...
""" Category of Note """ _name = "note.stage"
random_line_split
note.py
: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Gene...
def onclick_note_not_done(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'open': True}, context=context) #return the default stage for the uid user def _get_default_stage_id(self,cr,uid,context=None): ids = self.pool.get('note.stage').search(cr,uid,[('user_id','=',uid...
return self.write(cr, uid, ids, {'open': False, 'date_done': fields.date.today()}, context=context)
identifier_body
unsized2.rs
// run-pass #![allow(unconditional_recursion)] #![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_imports)] #![feature(box_syntax)] // Test sized-ness checking in substitution. use std::marker; // Unbounded. fn f1<X: ?Sized>(x: &X) { f1::<X>(x); } fn f2<X>(x: &X) { f1::<X>(x); f2::<X>(x); ...
trait T4<X> { fn dummy(&self) { } fn m1(&self, x: &dyn T4<X>, y: X); fn m2(&self, x: &dyn T5<X>, y: X); } trait T5<X: ?Sized> { fn dummy(&self) { } // not an error (for now) fn m1(&self, x: &dyn T4<X>); fn m2(&self, x: &dyn T5<X>); } trait T6<X: T> { fn dummy(&self) { } fn m1(&self,...
let _: Box<X> = T3::f(); }
random_line_split
unsized2.rs
// run-pass #![allow(unconditional_recursion)] #![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_imports)] #![feature(box_syntax)] // Test sized-ness checking in substitution. use std::marker; // Unbounded. fn f1<X: ?Sized>(x: &X) { f1::<X>(x); } fn f2<X>(x: &X) { f1::<X>(x); f2::<X>(x); ...
{ }
identifier_body
unsized2.rs
// run-pass #![allow(unconditional_recursion)] #![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_imports)] #![feature(box_syntax)] // Test sized-ness checking in substitution. use std::marker; // Unbounded. fn f1<X: ?Sized>(x: &X) { f1::<X>(x); } fn f2<X>(x: &X) { f1::<X>(x); f2::<X>(x); ...
<X: T>(x: &X) { f3::<X>(x); f4::<X>(x); } // Self type. trait T2 { fn f() -> Box<Self>; } struct S; impl T2 for S { fn f() -> Box<S> { box S } } fn f5<X: ?Sized+T2>(x: &X) { let _: Box<X> = T2::f(); } fn f6<X: T2>(x: &X) { let _: Box<X> = T2::f(); } trait T3 { fn f() -> Box<Sel...
f4
identifier_name