file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
ethereum-block.ts
import {toBigIntBE, toBufferBE} from 'bigint-buffer'; import {RlpEncode, RlpList} from 'rlp-stream'; import * as secp256k1 from 'secp256k1'; declare var process: {browser: boolean;}; const keccak = require('keccak'); interface NativeInterface { recoverFromAddress(verifyBlock: Buffer, signature: Buffer, recovery: bo...
: EthereumHeader, transactions: RlpList, uncleList: EthereumHeader[]): Buffer { const asRlpList: RlpList = [ encodeHeaderAsRLP(header), transactions, uncleList.map(uncle => encodeHeaderAsRLP(uncle)) ]; return RlpEncode(asRlpList); } /** * Get the public address of a given private key. * * @param p...
header
identifier_name
ethereum-block.ts
import {toBigIntBE, toBufferBE} from 'bigint-buffer'; import {RlpEncode, RlpList} from 'rlp-stream'; import * as secp256k1 from 'secp256k1'; declare var process: {browser: boolean;}; const keccak = require('keccak'); interface NativeInterface { recoverFromAddress(verifyBlock: Buffer, signature: Buffer, recovery: bo...
const TRANSACTION_NONCE = 0; const TRANSACTION_GASPRICE = 1; const TRANSACTION_STARTGAS = 2; const TRANSACTION_TO = 3; const TRANSACTION_VALUE = 4; const TRANSACTION_DATA = 5; const TRANSACTION_V = 6; const TRANSACTION_R = 7; const TRANSACTION_S = 8; /** * Given a RLP-serialized list with an Ethereum transaction, de...
extraData: (header[HEADER_EXTRADATA] as Buffer), mixHash: toBigIntBE(header[HEADER_MIXHASH] as Buffer), nonce: toBigIntBE(header[HEADER_NONCE] as Buffer) }; }
random_line_split
ethereum-block.ts
import {toBigIntBE, toBufferBE} from 'bigint-buffer'; import {RlpEncode, RlpList} from 'rlp-stream'; import * as secp256k1 from 'secp256k1'; declare var process: {browser: boolean;}; const keccak = require('keccak'); interface NativeInterface { recoverFromAddress(verifyBlock: Buffer, signature: Buffer, recovery: bo...
pList: RlpList = [ removeNullPrefix(toBufferBE(transaction.nonce, 32)), removeNullPrefix(toBufferBE(transaction.gasPrice, 32)), removeNullPrefix(toBufferBE(transaction.gasLimit, 32)), transaction.to === CONTRACT_CREATION ? Buffer.from([]) : toBufferBE(transacti...
identifier_body
test_service.py
#!/usr/bin/env python # # Copyright 2011-2015 Splunk, 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...
def test_default_app(self): kwargs = self.opts.kwargs.copy() kwargs.update({'app': None, 'owner': "admin"}) service_ns = client.connect(**kwargs) service_ns.apps.list() def test_app_wildcard(self): kwargs = self.opts.kwargs.copy() kwargs.update({'app': "-", 'owne...
random_line_split
test_service.py
#!/usr/bin/env python # # Copyright 2011-2015 Splunk, 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...
(self): kwargs = self.opts.kwargs.copy() kwargs.update({'app': "search", 'owner': None}) service_ns = client.connect(**kwargs) service_ns.apps.list() def test_owner_wildcard(self): kwargs = self.opts.kwargs.copy() kwargs.update({'app': "search", 'owner': "-"}) ...
test_app_namespace
identifier_name
test_service.py
#!/usr/bin/env python # # Copyright 2011-2015 Splunk, 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...
def _create_unauthenticated_service(self): return Service(**{ 'host': self.opts.kwargs['host'], 'port': self.opts.kwargs['port'], 'scheme': self.opts.kwargs['scheme'] }) # To check the HEC event endpoint using Endpoint instance @pytest.mark.smoke de...
raise
conditional_block
test_service.py
#!/usr/bin/env python # # Copyright 2011-2015 Splunk, 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...
def test_login_with_cookie(self): self.service.login() self.assertIsNotNone(self.service.get_cookies()) # Use the cookie from the other service as the only auth param (don't need user/password) service2 = client.Service(**{"cookie": "%s=%s" % list(self.service.get_cookies().items()...
self.assertIsNotNone(self.service.get_cookies()) self.assertEqual(len(self.service.get_cookies()), 0) self.service.login() self.assertIsNotNone(self.service.get_cookies()) self.assertNotEqual(self.service.get_cookies(), {}) self.assertEqual(len(self.service.get_cookies()), 1)
identifier_body
completion.rs
use std::{borrow::Cow, path::PathBuf, str::FromStr, sync::Arc}; use floem::{ peniko::kurbo::Rect, reactive::{ReadSignal, RwSignal, Scope}, }; use lapce_core::{buffer::rope_text::RopeText, movement::Movement}; use lapce_rpc::{plugin::PluginId, proxy::ProxyRpcHandler}; use lsp_types::{ CompletionItem, Comple...
(&mut self) { let count = self.display_count(); let active = self.active.get_untracked(); let new = Movement::Up.update_index( active, self.filtered_items.len(), count, false, ); self.active.set(new); } /// The currently se...
previous_page
identifier_name
completion.rs
use std::{borrow::Cow, path::PathBuf, str::FromStr, sync::Arc}; use floem::{ peniko::kurbo::Rect, reactive::{ReadSignal, RwSignal, Scope}, }; use lapce_core::{buffer::rope_text::RopeText, movement::Movement}; use lapce_rpc::{plugin::PluginId, proxy::ProxyRpcHandler}; use lsp_types::{ CompletionItem, Comple...
// TODO: Possibly handle the 'is_incomplete' field on List. CompletionResponse::List(list) => &list.items, }; let items: im::Vector<ScoredCompletionItem> = items .iter() .map(|i| ScoredCompletionItem { item: i.to_owned(), pl...
random_line_split
completion.rs
use std::{borrow::Cow, path::PathBuf, str::FromStr, sync::Arc}; use floem::{ peniko::kurbo::Rect, reactive::{ReadSignal, RwSignal, Scope}, }; use lapce_core::{buffer::rope_text::RopeText, movement::Movement}; use lapce_rpc::{plugin::PluginId, proxy::ProxyRpcHandler}; use lsp_types::{ CompletionItem, Comple...
fn all_items(&self) -> im::Vector<ScoredCompletionItem> { self.input_items .get(&self.input) .cloned() .filter(|items| !items.is_empty()) .unwrap_or_else(move || { self.input_items.get("").cloned().unwrap_or_default() }) } ...
{ if self.status == CompletionStatus::Inactive { return; } self.input = input; // TODO: If the user types a letter that continues the current active item, we should // try keeping that item active. Possibly give this a setting. // ex: `p` has `print!` and `pri...
identifier_body
feature_engineer.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging logger = logging.getLogger('code_submission') import random import numpy as np import pandas as pd from pandas import Series import torch import time from torch_geometric.data import Data from s...
return data pca=PCA(n_components=pca_threshold, svd_solver ='full') data = pca.fit_transform(data) return data def _check_file_exist(file_path, flag_directed_graph): if flag_directed_graph and os.path.exists(os.path.join(file_path,'NR_EB/STRAP_strap_frpca_d_U.npy')) and os.path.exists(os.path.j...
import os def _pca_processing(data, pca_threshold=0.75): if data.shape[1] == 0:
random_line_split
feature_engineer.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging logger = logging.getLogger('code_submission') import random import numpy as np import pandas as pd from pandas import Series import torch import time from torch_geometric.data import Data from s...
(edge_index, edge_weight, num_nodes): row, col = edge_index in_deg = scatter_add(edge_weight, col, dim_size=num_nodes).numpy() out_deg = scatter_add(edge_weight, row, dim_size=num_nodes).numpy() degree = np.concatenate([np.expand_dims(in_deg,-1), np.expand_dims(out_deg,-1)], axis=-1) return degree...
get_node_degree
identifier_name
feature_engineer.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging logger = logging.getLogger('code_submission') import random import numpy as np import pandas as pd from pandas import Series import torch import time from torch_geometric.data import Data from s...
node_embed = np.concatenate([node_embed_u, node_embed_v], axis=1) else: node_embed = np.load(os.path.join(file_path, 'NR_EB/STRAP_strap_frpca_u_U.npy')) if np.isnan(node_embed).any(): node_embed[np.isnan(node_embed)] = 0.0 ...
node_embed_v[np.isnan(node_embed_v)] = 0.0 logger.info('find nan in node_embed_V')
conditional_block
feature_engineer.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging logger = logging.getLogger('code_submission') import random import numpy as np import pandas as pd from pandas import Series import torch import time from torch_geometric.data import Data from s...
def normalize(x): norm_time = time.time() tol = min(int(1e-3*x.shape[1]), 5) normal_funs = ['l2', 'minmax', 'z-score'] normal_fun = normal_funs[0] cont_feature_idx = [i for i in range(len(x)) if len(np.unique(x[i])) > 5 and check_continuous(x[i], tol)] cate_feature_idx = [i for i in rang...
if len(np.unique(x)) > len(x) * 0.5: return True x = get_value_counts_with_moving_average(x) max_index = np.argmax(x) min_index = np.argmax(-np.array(x)) if check_monotony(x, tol): return True elif check_monotony(x[:max_index+1], tol) and check_monotony(x[max_index:], tol): r...
identifier_body
lib.rs
// lib.rs -- RUST wasm interface for Conways game of life mod utils; use quad_rand; use js_sys; use wasm_bindgen::prelude::*; // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeA...
{ width: u32, // width of each row height: u32, // number of rows cells: Vec<Cell>, // width*height cells, each one byte prevcells: Vec<Cell>, // cells from previous tick mousedown: bool // set when shift-click event, so that associated click ignored } // methods for Universe, but not exposed...
Universe
identifier_name
lib.rs
// lib.rs -- RUST wasm interface for Conways game of life mod utils; use quad_rand; use js_sys; use wasm_bindgen::prelude::*; // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeA...
} // impl Universe block w/o wasm_bindgen attribute // Needed for testing -- don't expose to our JS. // Rust-generated WebAsm functions cannot return borrowed references. // NOTE/SUGGEST: Try compiling the Rust-generated WebAsm with // the wasm_bindgen attribute and examine errors. // NOTE: get_cells returns b...
{ log!("reset_board() : {:?}", pattern); let width = self.width(); let height = self.height(); self.prevcells = self.cells.clone(); // current grid, needed for correct redraw self.cells = generate_cells(width, height, pattern); }
identifier_body
lib.rs
// lib.rs -- RUST wasm interface for Conways game of life mod utils; use quad_rand; use js_sys; use wasm_bindgen::prelude::*; // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeA...
+ if self.cells[self.get_index(down,right)] == Cell::Alive { 1 } else { 0 }; neighbors } } // standalone method, not part of Universe directly fn generate_cells(width: u32, height: u32, _pattern: InitialPattern) -> Vec<Cell> { // expression generating Vec<Cell> let cells = (0..width...
{ 0 }
conditional_block
lib.rs
// lib.rs -- RUST wasm interface for Conways game of life mod utils; use quad_rand; use js_sys; use wasm_bindgen::prelude::*; // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeA...
}).collect(); inverted_cells } // Public methods, exposed to JS #[wasm_bindgen] impl Universe { pub fn width(&self) -> u32 { self.width } pub fn height(&self) -> u32 { self.height } // set_width -- set width of Universe, set all cells to Dead state pub fn set_width(&m...
let inverted_cells = (0..count).map(|i| { if cells[i] == Cell::Alive { Cell::Dead } else { Cell::Alive }
random_line_split
mod.rs
//! Drop range analysis finds the portions of the tree where a value is guaranteed to be dropped //! (i.e. moved, uninitialized, etc.). This is used to exclude the types of those values from the //! generator type. See `InteriorVisitor::record` for where the results of this analysis are used. //! //! There are three ph...
use crate::FnCtxt; use hir::def_id::DefId; use hir::{Body, HirId, HirIdMap, Node}; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_hir as hir; use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; use rustc_middle::hir::map::Map; use rustc_middle::hir::place::{PlaceBase, PlaceWithHirId}; use ru...
use self::cfg_build::build_control_flow_graph; use self::record_consumed_borrow::find_consumed_and_borrowed;
random_line_split
mod.rs
//! Drop range analysis finds the portions of the tree where a value is guaranteed to be dropped //! (i.e. moved, uninitialized, etc.). This is used to exclude the types of those values from the //! generator type. See `InteriorVisitor::record` for where the results of this analysis are used. //! //! There are three ph...
(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("DropRanges") .field("hir_id_map", &self.tracked_value_map) .field("post_order_maps", &self.post_order_map) .field("nodes", &self.nodes.iter_enumerated().collect::<BTreeMap<_, _>>()) .fi...
fmt
identifier_name
mod.rs
//! Drop range analysis finds the portions of the tree where a value is guaranteed to be dropped //! (i.e. moved, uninitialized, etc.). This is used to exclude the types of those values from the //! generator type. See `InteriorVisitor::record` for where the results of this analysis are used. //! //! There are three ph...
else { match self { Self::Variable(hir_id) => write!(f, "Variable({hir_id:?})"), Self::Temporary(hir_id) => write!(f, "Temporary({hir_id:?})"), } } }) } } impl TrackedValue { fn hir_id(&self) -> HirId { match s...
{ write!(f, "{}", tcx.hir().node_to_string(self.hir_id())) }
conditional_block
mod.rs
//! Drop range analysis finds the portions of the tree where a value is guaranteed to be dropped //! (i.e. moved, uninitialized, etc.). This is used to exclude the types of those values from the //! generator type. See `InteriorVisitor::record` for where the results of this analysis are used. //! //! There are three ph...
fn node_mut(&mut self, id: PostOrderId) -> &mut NodeInfo { let size = self.num_values(); self.nodes.ensure_contains_elem(id, || NodeInfo::new(size)) } fn add_control_edge(&mut self, from: PostOrderId, to: PostOrderId) { trace!("adding control edge from {:?} to {:?}", from, to); ...
{ self.tracked_value_map.len() }
identifier_body
forward_chain_bandaid.py
#!/usr/bin/python # -*- coding: utf-8 -*- # vim: expandtab:tabstop=4:shiftwidth=4 #FIXME: This script is not packaged. That goes against team policy. #FIXME: This script must be removed or packaged. # Script added in violation of policy because: # 1. we're in a hurry to get it rolled out because of a related, current...
# assume that source_chain already exists # flush the source_chain since we're about to recreate its rules in_data += "-F %s\n" % self.source_chain in_data += ("\n".join(updated_rules))+"\n" in_data += "COMMIT\n" cmd = self._build_restore_cmd() # as seen on http:...
in_data += ":%s - [0:0]\n" % self.jump_chain
conditional_block
forward_chain_bandaid.py
#!/usr/bin/python # -*- coding: utf-8 -*- # vim: expandtab:tabstop=4:shiftwidth=4 #FIXME: This script is not packaged. That goes against team policy. #FIXME: This script must be removed or packaged. # Script added in violation of policy because: # 1. we're in a hurry to get it rolled out because of a related, current...
# pylint: enable=too-few-public-methods # pylint: disable=too-many-instance-attributes # pylint: disable=too-many-arguments class TopRule(object): '''A single rule that should be at the top of the chain''' def __init__(self, table, source_chain, jump_chain, ver, top_rule, noop_rule): '''Create the To...
'''A dummy context manager that does nothing so that a 'with' can conditionally do nothing''' def __enter__(self): return None def __exit__(self, exc_type, exc_value, traceback_): return False
identifier_body
forward_chain_bandaid.py
#!/usr/bin/python # -*- coding: utf-8 -*- # vim: expandtab:tabstop=4:shiftwidth=4 #FIXME: This script is not packaged. That goes against team policy. #FIXME: This script must be removed or packaged. # Script added in violation of policy because: # 1. we're in a hurry to get it rolled out because of a related, current...
# 2. this script should go away within a few weeks when it gets obsoleted by # https://github.com/openshift/origin/pull/13465 ''' This entire script is a band-aid that needs to be in place until https://github.com/openshift/origin/pull/13465 is merged and backported to 3.4 and 3.5 and the hotfix that contains it ...
random_line_split
forward_chain_bandaid.py
#!/usr/bin/python # -*- coding: utf-8 -*- # vim: expandtab:tabstop=4:shiftwidth=4 #FIXME: This script is not packaged. That goes against team policy. #FIXME: This script must be removed or packaged. # Script added in violation of policy because: # 1. we're in a hurry to get it rolled out because of a related, current...
(self, *args): ''' Create an iptables-restore or ip6tables-restore command Return a list of command args suitable for use with subprocess.* ''' cmd = 'iptables-restore' if self.ver == 'ipv4' else 'ip6tables-restore' retval = ["/usr/sbin/%s" % cmd, '--noflush', '--table', ...
_build_restore_cmd
identifier_name
jobOptions_TileLasMon.py
# # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration # #***************************************************************** # # """topOptions file for Tile Laser Reconstruciton and Monitoring in Athena""" # """This topOptions is intended to test the monitoring code""" #==========================...
(path, runinput): run = str(runinput) while len(run) < 7: run = '0' + run files = [] fullname = [] if path.startswith("/castor") : for f in popen('nsls %(path)s | grep %(run)s' % {'path': path, 'run':run }): files.append(f) elif path.startswith("/eos") : ...
FindFile
identifier_name
jobOptions_TileLasMon.py
# # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration # #***************************************************************** # # """topOptions file for Tile Laser Reconstruciton and Monitoring in Athena""" # """This topOptions is intended to test the monitoring code""" #==========================...
print(topSequence.TileLasMon) import os # -- use root histos -- # THistService for native root in Athena if not athenaCommonFlags.isOnline() or storeHisto or athenaCommonFlags.isOnlineStateless(): #theApp.HistogramPersistency = "ROOT" if not hasattr(svcMgr,"THistSvc"): from GaudiSvc.GaudiSvcConf impo...
topSequence.TileLasMon.AthenaMonTools += [ TileLasDQFragMon ]; print(TileLasDQFragMon)
random_line_split
jobOptions_TileLasMon.py
# # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration # #***************************************************************** # # """topOptions file for Tile Laser Reconstruciton and Monitoring in Athena""" # """This topOptions is intended to test the monitoring code""" #==========================...
if not 'FileNameVec' in dir(): if not 'FileName' in dir(): tmp = FindFile(InputDirectory,RunNumber) FileNameVec = tmp[0] FormattedRunNumber = tmp[1] else: FileNameVec = [ InputDirectory+'/'+FileName ] FormattedRunNumber ...
if InputDirectory=="." or RunNumber<10: RunFromLocal=True else: RunFromLocal=False
conditional_block
jobOptions_TileLasMon.py
# # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration # #***************************************************************** # # """topOptions file for Tile Laser Reconstruciton and Monitoring in Athena""" # """This topOptions is intended to test the monitoring code""" #==========================...
# include Flags jobOption include( "TileMonitoring/TileRec_FlagOptions.py" ) ## get a handle to the default top-level algorithm sequence from AthenaCommon.AlgSequence import AlgSequence topSequence = AlgSequence() # Get a handle to the ServiceManager from AthenaCommon.AppMgr import ServiceMgr as svcMgr from AthenaC...
run = str(runinput) while len(run) < 7: run = '0' + run files = [] fullname = [] if path.startswith("/castor") : for f in popen('nsls %(path)s | grep %(run)s' % {'path': path, 'run':run }): files.append(f) elif path.startswith("/eos") : for f in popen(...
identifier_body
trainer.py
import logging import os.path as osp import queue import sys import threading import time from collections import OrderedDict import torch from det3d import torchie from . import hooks from .checkpoint import load_checkpoint, save_checkpoint from .hooks import ( CheckpointHook, Hook, IterTimerHook, Lr...
else: return model(example, return_loss=False) def train(self, data_loader, epoch, **kwargs): self.model.train() self.mode = "train" self.data_loader = data_loader self.length = len(data_loader) self._max_iters = self._max_epochs * self.length s...
losses = model(example, return_loss=True) self.call_hook("after_forward") loss, log_vars = parse_second_losses(losses) del losses outputs = dict( loss=loss, log_vars=log_vars, num_samples=-1 # TODO: FIX THIS ) self.call_hook("afte...
conditional_block
trainer.py
import logging import os.path as osp import queue import sys import threading import time from collections import OrderedDict import torch from det3d import torchie from . import hooks from .checkpoint import load_checkpoint, save_checkpoint from .hooks import ( CheckpointHook, Hook, IterTimerHook, Lr...
self, model, batch_processor, optimizer=None, lr_scheduler=None, work_dir=None, log_level=logging.INFO, logger=None, **kwargs, ): assert callable(batch_processor) self.model = model self.optimizer = optimizer sel...
random_line_split
trainer.py
import logging import os.path as osp import queue import sys import threading import time from collections import OrderedDict import torch from det3d import torchie from . import hooks from .checkpoint import load_checkpoint, save_checkpoint from .hooks import ( CheckpointHook, Hook, IterTimerHook, Lr...
(self, optimizer): """Init the optimizer Args: optimizer (dict or :obj:`~torch.optim.Optimizer`) Returns: :obj:`~torch.optim.Optimizer` Examples: >>> optimizer = dict(type='SGD', lr=0.01, momentum=0.9) >>> type(runner.init_optimizer(opti...
init_optimizer
identifier_name
trainer.py
import logging import os.path as osp import queue import sys import threading import time from collections import OrderedDict import torch from det3d import torchie from . import hooks from .checkpoint import load_checkpoint, save_checkpoint from .hooks import ( CheckpointHook, Hook, IterTimerHook, Lr...
""" A training helper for PyTorch Args: model: batch_processor: optimizer: workdir: log_level: logger: """ def __init__( self, model, batch_processor, optimizer=None, lr_scheduler=None, work_dir=None, l...
identifier_body
path_planning.py
#!/usr/bin/python2 # -*- coding: UTF-8 -*- # coding: utf-8 #!/usr/bin/env python ''' 发布轨迹信息 path.x; path.y; c_speed; ''' import numpy as np import matplotlib.pyplot as plt import copy import math from cubic_spline import Spline2D from polynomials import QuarticPolynomial, QuinticPolynomial import time import...
GPS_y = GPS_y - zero_cord_y plt.plot(GPS_x,GPS_y, "-r", label="GPS point ") plt.plot() plt.show() return GPS_x, GPS_y class Info(object): def __init__(self): self.CurrGPS_lat = float(-1) self.CurrGPS_lon = float(-1) self.CurrentVelocity = float(-1) self.Targ...
#print("cy:",cy) zero_cord_x = GPS_x[0] zero_cord_y = GPS_y[0] GPS_x = GPS_x - zero_cord_x
random_line_split
path_planning.py
#!/usr/bin/python2 # -*- coding: UTF-8 -*- # coding: utf-8 #!/usr/bin/env python ''' 发布轨迹信息 path.x; path.y; c_speed; ''' import numpy as np import matplotlib.pyplot as plt import copy import math from cubic_spline import Spline2D from polynomials import QuarticPolynomial, QuinticPolynomial import time import...
############################## def load_global_path(): global zero_cord_x,zero_cord_y bet = 0.1 blank = [] #buffer white = [] #buffer yellow = [] ...
.cos(csp.calc_yaw(i_s)+math.pi / 2.0) road_right_iy = iy - MAX_ROAD_WIDTH/2 * math.sin(csp.calc_yaw(i_s)+math.pi / 2.0) road_left_x.append(road_left_ix) road_left_y.append(road_left_iy) road_right_x.append(road_right_ix) road_right_y.append(road_right_iy) return road_left_x, ...
identifier_body
path_planning.py
#!/usr/bin/python2 # -*- coding: UTF-8 -*- # coding: utf-8 #!/usr/bin/env python ''' 发布轨迹信息 path.x; path.y; c_speed; ''' import numpy as np import matplotlib.pyplot as plt import copy import math from cubic_spline import Spline2D from polynomials import QuarticPolynomial, QuinticPolynomial import time import...
gnss_message', GNSS_CAN, self.FeedbackCallbackGPSIMU,queue_size = 10) #订阅GPS数据 rospy.Subscriber("Motor_Feedback_mssage", Motor_Feedback,self.RVcallback,queue_size = 10) def FeedbackCallbackGPSIMU(self, msg): self.CurrGPS_lat = msg.latitude self.Curr...
criber('
identifier_name
path_planning.py
#!/usr/bin/python2 # -*- coding: UTF-8 -*- # coding: utf-8 #!/usr/bin/env python ''' 发布轨迹信息 path.x; path.y; c_speed; ''' import numpy as np import matplotlib.pyplot as plt import copy import math from cubic_spline import Spline2D from polynomials import QuarticPolynomial, QuinticPolynomial import time import...
#buffer GPS_x = [] #所采集预描点的x GPS_y = [] #所采集预描点的x #读取预描点 nums, ber = np.loadtxt("/home/robot/Robot/Smart_robot_ws/sr...
#buffer white = [] #buffer yellow = []
conditional_block
pyNN_target_sim.py
# -*- coding: utf-8 -*- """ Building and simulating spiking neural networks using `pyNN <http://neuralensemble.org/docs/PyNN/>`_. @author: rbodo """ import os import sys import time import warnings import numpy as np from six.moves import cPickle from snntoolbox.utils.utils import confirm_overwrite, is_module_insta...
elf, path, filename): """Load the populations in an assembly. Loads the populations in an assembly that was saved with the `save_assembly` function. The term "assembly" refers to pyNN internal nomenclature, where ``Assembly`` is a collection of layers (``Populations``), which i...
ad_assembly(s
identifier_name
pyNN_target_sim.py
# -*- coding: utf-8 -*- """ Building and simulating spiking neural networks using `pyNN <http://neuralensemble.org/docs/PyNN/>`_. @author: rbodo """ import os import sys import time import warnings import numpy as np from six.moves import cPickle from snntoolbox.utils.utils import confirm_overwrite, is_module_insta...
def save_connections(self, path): """Write parameters of a neural network to disk. The parameters between two layers are saved in a text file. They can then be used to connect pyNN populations e.g. with ``sim.Projection(layer1, layer2, sim.FromListConnector(filename))``, w...
"""Write layers of neural network to disk. The size, structure, labels of all the population of an assembly are stored in a dictionary such that one can load them again using the `load_assembly` function. The term "assembly" refers to pyNN internal nomenclature, where ``Assembl...
identifier_body
pyNN_target_sim.py
# -*- coding: utf-8 -*- """ Building and simulating spiking neural networks using `pyNN <http://neuralensemble.org/docs/PyNN/>`_. @author: rbodo """ import os import sys import time import warnings import numpy as np from six.moves import cPickle from snntoolbox.utils.utils import confirm_overwrite, is_module_insta...
def end_sim(self): self.sim.end() def save(self, path, filename): print("Saving model to {}...".format(path)) self.save_assembly(path, filename) self.save_connections(path) self.save_biases(path) print("Done.\n") def load(self, path, filename): ...
print("Resetting simulator...") self.sim.reset() print("Done.")
conditional_block
pyNN_target_sim.py
# -*- coding: utf-8 -*- """ Building and simulating spiking neural networks using `pyNN <http://neuralensemble.org/docs/PyNN/>`_. @author: rbodo """ import os import sys import time import warnings import numpy as np from six.moves import cPickle from snntoolbox.utils.utils import confirm_overwrite, is_module_insta...
---------- path: str Path to directory where connections are saved. Return ------ Text files containing the layer connections. Each file is named after the layer it connects to, e.g. ``layer2.txt`` if connecting layer1 to layer2. ...
NEST. Parameters
random_line_split
models.py
# DeerTrees (Django App) # By Natasha L. # www.lupinia.net | github.com/lupinia # # ================= # Models # ================= from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.d...
else: return False @property def is_old(self): if self.cat.always_fresh or not self.admin_owned: return False else: if self.timestamp_mod < (timezone.now() - timedelta(days=365*10)): return True elif (self.timestamp_post < (timezone.now() - timedelta(days=365*10))) and (self.timestamp_mod < (...
return True
conditional_block
models.py
# DeerTrees (Django App) # By Natasha L. # www.lupinia.net | github.com/lupinia # # ================= # Models # ================= from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.d...
def save(self, *args, **kwargs): if self.parent: self.cached_url = '%s/%s' % (self.parent.cached_url, self.slug) else: self.cached_url = self.slug super(category, self).save(*args, **kwargs) def can_edit(self, request=False): if not request: return (False,'access_norequest') else: canview = ...
return self.summary_short
random_line_split
models.py
# DeerTrees (Django App) # By Natasha L. # www.lupinia.net | github.com/lupinia # # ================= # Models # ================= from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.d...
(self): return '%s%s' % (reverse('category', kwargs={'cached_url':self.cat.cached_url,}), self.url) def __unicode__(self): return self.title def get_summary(self,length=255): if length > 255: return summarize(body=self.desc, length=length, prefer_long=True) else: return summarize(body=self.desc, len...
get_absolute_url
identifier_name
models.py
# DeerTrees (Django App) # By Natasha L. # www.lupinia.net | github.com/lupinia # # ================= # Models # ================= from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.d...
# ALIAS @property def rss_description(self): return self.summary_short class Meta: ordering = ['slug',] class tag_synonym(models.Model): parent = models.ForeignKey(tag, on_delete=models.CASCADE, related_name='synonyms') slug = models.SlugField(max_length=200,unique=True) timestamp_mod = models.DateTime...
return self.get_summary(512)
identifier_body
util.py
# Copyright (c) 2019-2020 SAP SE or an SAP affiliate company. All rights reserved. This file is # licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the L...
def _filter_single_tar( in_file: tarfile.TarFile, remove_entries, ): temp_fh = tempfile.TemporaryFile() temptar = tarfile.TarFile(fileobj=temp_fh, mode='w') for tar_info in in_file: if not tar_info.isfile(): temptar.addfile(tar_info) continue if tar_info....
layer_paths = set(manifest['Layers']) changed_layer_hashes = [] # [(old, new),] # copy everything that does not need to be patched for tar_info in in_tarfile: if not tar_info.isfile(): out_tarfile.addfile(tar_info) continue # cfg needs to be rewritten - so do not cp...
identifier_body
util.py
# Copyright (c) 2019-2020 SAP SE or an SAP affiliate company. All rights reserved. This file is # licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the L...
( image_file, out_file, remove_entries, ): ci.util.existing_file(image_file) if not remove_entries: raise ValueError('remove_entries must not be empty') # allow absolute paths remove_entries = [e.lstrip('/') for e in remove_entries] with tarfile.open(image_file) as tf: m...
filter_container_image
identifier_name
util.py
# Copyright (c) 2019-2020 SAP SE or an SAP affiliate company. All rights reserved. This file is # licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the L...
image_reference=target_ref, digest=(layer_digest := 'sha256:' + layer_hash.hexdigest()), octets_count=leng, data=f, ) # update copy of layers-list with new layer new_layer = dataclasses.replace(layer, digest=layer_diges...
f.write(chunk) f.seek(0) oci_client.put_blob(
random_line_split
util.py
# Copyright (c) 2019-2020 SAP SE or an SAP affiliate company. All rights reserved. This file is # licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the L...
if tar_info.name.lstrip('./') in remove_entries: logging.debug(f'purging entry: {tar_info.name}') continue # copy entry entry = in_file.extractfile(tar_info) temptar.addfile(tar_info, fileobj=entry) size = temp_fh.tell() temp_fh.flush() temp_fh.see...
temptar.addfile(tar_info) continue
conditional_block
kibana.py
# -*- coding: utf-8 -*- """Kibana module.""" import pandas import requests import json from . import util class Kibana(object): def __init__(self, host='localhost', port=5601, protocol='http', verify_certs=True, **kwargs): self._host = host self._port = port self._protoco...
# }, # 'title': title, # 'type': visType, # } assert isinstance(viz, Visualization) visState = viz.visState(title) searchSourceJSON = { "index":indexPatternUID, "filter":[], "query":{"language":"kuery","query":""} ...
# ], # 'params': { # 'type': 'histogram'
random_line_split
kibana.py
# -*- coding: utf-8 -*- """Kibana module.""" import pandas import requests import json from . import util class Kibana(object): def __init__(self, host='localhost', port=5601, protocol='http', verify_certs=True, **kwargs): self._host = host self._port = port self._protoco...
def agg2(self): return { "id": "2", "enabled": True, "type": "histogram", "schema": "segment", "params": { "field": self.field, "interval": self.interval, "extended_bounds": {} } ...
super(Histogram, self).__init__(field) self.visType = 'histogram' self.interval = interval
identifier_body
kibana.py
# -*- coding: utf-8 -*- """Kibana module.""" import pandas import requests import json from . import util class Kibana(object): def __init__(self, host='localhost', port=5601, protocol='http', verify_certs=True, **kwargs): self._host = host self._port = port self._protoco...
how = how if isinstance(how, list) else [how] url = self.kibanaUrl(*args, **kwargs) if 'print' in how: print(f"Open: {url}") if 'webbrowser' in how: import webbrowser webbrowser.open(url) if 'jupyter' in how or 'ipython' in how: fr...
how = 'jupyter' if util.__IS_JUPYTER else 'webbrowser' # TODO can we figure out "non-interactive" to put how='print' then?
conditional_block
kibana.py
# -*- coding: utf-8 -*- """Kibana module.""" import pandas import requests import json from . import util class Kibana(object): def __init__(self, host='localhost', port=5601, protocol='http', verify_certs=True, **kwargs): self._host = host self._port = port self._protoco...
(HorizontalBar): def __init__(self, field, size=20): super(TagCloud, self).__init__(field, size) self.visType = 'tagcloud' self.params = { "scale": "linear", "orientation": "single", "minFontSize": 18, "maxFontSize": 72, "showLabel...
TagCloud
identifier_name
mod.rs
//! Code to compute example inputs given a backtrace. use crate::grammar::repr::*; use crate::message::builder::InlineBuilder; use crate::message::Content; use crate::style::Style; use crate::tls::Tls; use ascii_canvas::AsciiView; use std::{ cmp::Ordering, fmt::{Debug, Error, Formatter}, }; #[cfg(test)] mod t...
fn starting_positions(&self, lengths: &[usize]) -> Vec<usize> { lengths .iter() .scan(0, |counter, &len| { let start = *counter; // Leave space for "NT " (if "NT" is the name // of the nonterminal). *counter = start +...
{ let lengths = self.lengths(); let positions = self.positions(&lengths); InlineBuilder::new() .push(Box::new(ExamplePicture { example: self, positions, styles, })) .indented() .end() }
identifier_body
mod.rs
//! Code to compute example inputs given a backtrace. use crate::grammar::repr::*; use crate::message::builder::InlineBuilder; use crate::message::Content; use crate::style::Style; use crate::tls::Tls; use ascii_canvas::AsciiView; use std::{ cmp::Ordering, fmt::{Debug, Error, Formatter}, }; #[cfg(test)] mod t...
(&self) -> Vec<::ascii_canvas::Row> { let this = self.clone(); let content = this.into_picture(ExampleStyles::default()); let min_width = content.min_width(); let canvas = content.emit_to_canvas(min_width); canvas.to_strings() } fn paint_on(&self, styles: &ExampleStyles,...
paint_unstyled
identifier_name
mod.rs
//! Code to compute example inputs given a backtrace. use crate::grammar::repr::*; use crate::message::builder::InlineBuilder; use crate::message::Content; use crate::style::Style; use crate::tls::Tls; use ascii_canvas::AsciiView; use std::{ cmp::Ordering, fmt::{Debug, Error, Formatter}, }; #[cfg(test)] mod t...
/// /// The top-line is the `symbols` vector. The groupings below are /// stored in the `reductions` vector, in order from smallest to /// largest (they are always properly nested). The `cursor` field /// indicates the current lookahead token. /// /// The `symbols` vector is actually `Option<Symbol>` to account /// for...
/// ```
random_line_split
install.go
// Copyright 2021 Ross Light // // 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 in ...
func sortedStringDictKeys(d starlark.StringDict) []string { keys := make([]string, 0, len(d)) for k := range d { keys = append(keys, k) } sort.Strings(keys) return keys }
{ return sortedStringDictKeys(mod.attrs) }
identifier_body
install.go
// Copyright 2021 Ross Light // // 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 in ...
return err } return nil } const threadContextKey = "zombiezen.com/go/biome.Context" func threadContext(t *starlark.Thread) context.Context { ctx, _ := t.Local(threadContextKey).(context.Context) if ctx == nil { ctx = context.Background() } return ctx } type envValue struct { vars *starlark.Dict pr...
return fmt.Errorf("install return value: %w", err) } if err := writeBiomeEnvironment(db, rec.id, rec.env.Merge(installEnv)); err != nil {
random_line_split
install.go
// Copyright 2021 Ross Light // // 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 in ...
return starlark.String(biome.JoinPath(bio.Describe(), stringArgs...)), nil }), "exists": starlark.NewBuiltin("path.exists", func(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { var path string if err := starlark.UnpackArgs(fn.Name...
{ arg, ok := starlark.AsString(args.Index(i)) if !ok { return nil, fmt.Errorf("%s: could not convert arg[%d] to string", fn.Name(), i) } stringArgs = append(stringArgs, arg) }
conditional_block
install.go
// Copyright 2021 Ross Light // // 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 in ...
() []string { return sortedStringDictKeys(mod.attrs) } func sortedStringDictKeys(d starlark.StringDict) []string { keys := make([]string, 0, len(d)) for k := range d { keys = append(keys, k) } sort.Strings(keys) return keys }
AttrNames
identifier_name
mod.rs
/* File_config_functionalities_pmz */ // conditions: /* exec trait: [alias:(file/any)] [operations] [path/name] [parameters/--options] Read:Content _ none Write:Content _ String : if use multi line content -> check len()::Enum -> i32|&str Update:Content _ String ...
println!( "test {:?} ", (match_inside_brac.is_match(test), test.trim_matches(x)) ); }
println!("t {}", test); let x: &[_] = &['[', ']'];
random_line_split
mod.rs
/* File_config_functionalities_pmz */ // conditions: /* exec trait: [alias:(file/any)] [operations] [path/name] [parameters/--options] Read:Content _ none Write:Content _ String : if use multi line content -> check len()::Enum -> i32|&str Update:Content _ String ...
{ let match_inside_brac = regex::Regex::new(r"^\[(.*)\]$").unwrap(); let test = "[Apple sauce bananan ba;;;a]"; println!("t {}", test); let x: &[_] = &['[', ']']; println!( "test {:?} ", (match_inside_brac.is_match(test), test.trim_matches(x)) ); }
identifier_body
mod.rs
/* File_config_functionalities_pmz */ // conditions: /* exec trait: [alias:(file/any)] [operations] [path/name] [parameters/--options] Read:Content _ none Write:Content _ String : if use multi line content -> check len()::Enum -> i32|&str Update:Content _ String ...
(result: &str) -> OriResult<String> { if result.is_empty() { let empty_err = FileError::new().set_message("The Folder is Empty inside"); Err(empty_err) } else { Ok(result.trim().to_string()) } } impl Operation for Fileconfig { fn read(&self) -> OriResult<String> { let fil...
checkempty
identifier_name
sketch.js
//playerSprite let pharahSprite; //crosshair let crosshairSprite; //player let pharah; //enemies!!!!! let enemy1sprite; let enemy2sprite; let enemy3sprite; //enemy array let enemyArr; //enemyImage array let images; let enemyNum; let bulletSprite; //gamestate, 0 = menu, 1 = gameplay let state; //boring initializer...
{ score += 1; if (score >= 6) { state = 2; } } //Pharah takes damage if she touches people if(pharah.detectHit(enemyArr[i].xPos, enemyArr[i].yPos)) { pharah.health -= 10; } } } } //standard gameov...
random_line_split
sketch.js
//playerSprite let pharahSprite; //crosshair let crosshairSprite; //player let pharah; //enemies!!!!! let enemy1sprite; let enemy2sprite; let enemy3sprite; //enemy array let enemyArr; //enemyImage array let images; let enemyNum; let bulletSprite; //gamestate, 0 = menu, 1 = gameplay let state; //boring initializer...
//preload assets function preload() { pharahSprite = loadImage("images/pharahSprite_small.png"); bg = loadImage("images/bg.png"); crosshairSprite = loadImage("images/crosshair.png"); bulletSprite = loadImage("images/bullet.png"); soundFormats("mp3"); shotSound = loadSound("sounds/exp.mp3"); //enemies, p...
{ // grab the range data as an integer rangeData = int(clickedRange.value); }
identifier_body
sketch.js
//playerSprite let pharahSprite; //crosshair let crosshairSprite; //player let pharah; //enemies!!!!! let enemy1sprite; let enemy2sprite; let enemy3sprite; //enemy array let enemyArr; //enemyImage array let images; let enemyNum; let bulletSprite; //gamestate, 0 = menu, 1 = gameplay let state; //boring initializer...
() { //contain logic within borders if (this.xPos + this.sprite.width > width) { this.xSpeed = 0; this.collided = true; this.xPos = width - this.sprite.width } if (this.xPos < 0) { this.xSpeed = 0; this.collided = true; this.xPos = 0; } if (this.yPos...
move
identifier_name
sketch.js
//playerSprite let pharahSprite; //crosshair let crosshairSprite; //player let pharah; //enemies!!!!! let enemy1sprite; let enemy2sprite; let enemy3sprite; //enemy array let enemyArr; //enemyImage array let images; let enemyNum; let bulletSprite; //gamestate, 0 = menu, 1 = gameplay let state; //boring initializer...
else if (this.left) { this.xSpeed += this.gravity; if (this.xSpeed > 0) { this.right = true; this.left = false; } } //the standard movement. Add gravity, speed to position this.ySpeed += this.gravity; this.xPos += this.xSpeed; this.yPos += this.ySpee...
{ this.xSpeed -= this.gravity; if (this.xSpeed < 0) { this.right = false; this.left = true; } }
conditional_block
FactorPropertyController.js
Ext.define('Factor.controller.panel.FactorPropertyController', { extend: 'Factor.controller.Base', stores: [ "FactorPropertyStore", "FactorDataStore" ], models: [ "FactorPropertyModel" ], views: [ // 'window.FactorWindow' ], controller...
Ext.MessageBox.alert('提示', '您选中的属性包含固有属性,因子固有属性不能删除!'); return; } } Ext.MessageBox.confirm('确认', '确定要删除选中因子属性?', function(btn){ if('yes'===btn){ Store.remove(sm.getSelection()); if (Store.getCount() > 0) { sm.select(0); } var delstores= Store.get...
if("1"===(sm.getSelection()[i].get('prototype')+"")){
random_line_split
FactorPropertyController.js
Ext.define('Factor.controller.panel.FactorPropertyController', { extend: 'Factor.controller.Base', stores: [ "FactorPropertyStore", "FactorDataStore" ], models: [ "FactorPropertyModel" ], views: [ // 'window.FactorWindow' ], controller...
(deleteJson) }, success: function(response, options) { var factorSelectModel = me.getFactorGrid().selModel; if(0 < factorSelectModel.selected.length){ parentUuid = factorSelectModel.selected.items[0].get('uuid'); } Factor.App.getPanelFactorPropertyControllerController(...
} Ext.Ajax.request({ url: '../work-platform/deleteFactorInstances.do', params: { deleteFactorInstances:Ext.encode
conditional_block
train_ibp.py
import numpy as np import keras.backend as K from keras.optimizers import Adam from keras.preprocessing.image import ImageDataGenerator from keras.utils import to_categorical from keras.callbacks import EarlyStopping, LearningRateScheduler, ModelCheckpoint, \ ReduceLROnPlateau, TensorBoard ...
(y_true, y_pred): return model.robust_accuracy if config.load_weights_from is not None: model.load_weights(config.load_weights_from) metrics = ["accuracy", robust_acc] model.compile(loss=loss, optimizer=Adam(lr=config.lr), metrics=metrics) model.summary() ################## # Setup training # #############...
robust_acc
identifier_name
train_ibp.py
import numpy as np import keras.backend as K from keras.optimizers import Adam from keras.preprocessing.image import ImageDataGenerator from keras.utils import to_categorical from keras.callbacks import EarlyStopping, LearningRateScheduler, ModelCheckpoint, \ ReduceLROnPlateau, TensorBoard ...
else: mean, std = None, None if config.model_name == "SmallCNN": model = SmallCNN(input_shape=input_shape) elif config.model_name == "MediumCNN": model = MediumCNN(input_shape=input_shape) elif config.model_name == "LargeCNN": model = LargeCNN(input_shape=input_shape) elif config.model_name == "LargeC...
mean, std = x_train.mean(axis=(0, 1, 2)), x_train.std(axis=(0, 1, 2)) + 1e-6 x_train = (x_train - mean) / std x_valid = (x_valid - mean) / std print("Normalising channels with values", mean, std)
conditional_block
train_ibp.py
import numpy as np import keras.backend as K from keras.optimizers import Adam from keras.preprocessing.image import ImageDataGenerator from keras.utils import to_categorical from keras.callbacks import EarlyStopping, LearningRateScheduler, ModelCheckpoint, \ ReduceLROnPlateau, TensorBoard ...
if config.load_weights_from is not None: model.load_weights(config.load_weights_from) metrics = ["accuracy", robust_acc] model.compile(loss=loss, optimizer=Adam(lr=config.lr), metrics=metrics) model.summary() ################## # Setup training # ################## # Prepare model model saving directory mode...
return model.robust_accuracy
identifier_body
train_ibp.py
import numpy as np import keras.backend as K from keras.optimizers import Adam from keras.preprocessing.image import ImageDataGenerator from keras.utils import to_categorical from keras.callbacks import EarlyStopping, LearningRateScheduler, ModelCheckpoint, \ ReduceLROnPlateau, TensorBoard ...
batch_size=config.batch_size, callbacks=callbacks) else: print('Using real-time data augmentation.') shift = 4 if config.dataset == "CIFAR10" else 2 # This will do preprocessing and realtime data augmentation: datagen = ImageDataGenerator( # randomly rotate images in ...
random_line_split
main.rs
use crossterm::{ cursor, event::{self, DisableMouseCapture, EnableMouseCapture, Event}, queue, style::{self, Color::Rgb, Colors, Print, SetColors}, terminal, }; use serde::{Deserialize, Serialize}; use std::{ cmp::min, collections::HashMap, env, fs, io::{self, Write}, iter, p...
dir: Direction, skip: bool, } #[derive(Clone)] enum Direction { Next, Prev, } pub struct Bk<'a> { quit: bool, chapters: Vec<epub::Chapter>, // position in the book chapter: usize, line: usize, mark: HashMap<char, (usize, usize)>, links: HashMap<String, (usize, usize)>, ...
archArgs {
identifier_name
main.rs
use crossterm::{ cursor, event::{self, DisableMouseCapture, EnableMouseCapture, Event}, queue, style::{self, Color::Rgb, Colors, Print, SetColors}, terminal, }; use serde::{Deserialize, Serialize}; use std::{ cmp::min, collections::HashMap, env, fs, io::{self, Write}, iter, p...
} false } } } } #[derive(argh::FromArgs)] /// read a book struct Args { #[argh(positional)] path: Option<String>, /// background color (eg 282a36) #[argh(option)] bg: Option<String>, /// foreground color (eg f8f8f2) #[argh(option)] ...
self.jump_byte(c, index); return true; }
conditional_block
main.rs
use crossterm::{ cursor, event::{self, DisableMouseCapture, EnableMouseCapture, Event}, queue, style::{self, Color::Rgb, Colors, Print, SetColors}, terminal, }; use serde::{Deserialize, Serialize}; use std::{ cmp::min, collections::HashMap, env, fs, io::{self, Write}, iter, p...
let byte = bk.chapters[bk.chapter].lines[bk.line].0; state .save .files .insert(state.path.clone(), (bk.chapter, byte)); state.save.last = state.path; let serialized = ron::to_string(&state.save).unwrap(); fs::write(state.save_path, serialized).unwrap_or_else(|e| { p...
random_line_split
colors.rs
use std::io; use std::mem; use std::os::windows::io::AsRawHandle; use std::str::Bytes; use windows_sys::Win32::Foundation::HANDLE; use windows_sys::Win32::System::Console::{ GetConsoleScreenBufferInfo, SetConsoleTextAttribute, CONSOLE_SCREEN_BUFFER_INFO, FOREGROUND_BLUE as FG_BLUE, FOREGROUND_GREEN as FG_GREEN...
cur_attr: TextAttributes, } #[derive(Clone, Copy, Debug)] enum HandleKind { Stdout, Stderr, } impl HandleKind { fn handle(&self) -> HANDLE { match *self { HandleKind::Stdout => io::stdout().as_raw_handle() as HANDLE, HandleKind::Stderr => io::stderr().as_raw_handle() as...
#[derive(Debug)] pub struct Console { kind: HandleKind, start_attr: TextAttributes,
random_line_split
colors.rs
use std::io; use std::mem; use std::os::windows::io::AsRawHandle; use std::str::Bytes; use windows_sys::Win32::Foundation::HANDLE; use windows_sys::Win32::System::Console::{ GetConsoleScreenBufferInfo, SetConsoleTextAttribute, CONSOLE_SCREEN_BUFFER_INFO, FOREGROUND_BLUE as FG_BLUE, FOREGROUND_GREEN as FG_GREEN...
}
{ let attr = "leading bytes \x1b[1m trailing bytes"; let parsed = driver(parse_attr, attr).unwrap(); assert_eq!(parsed, b'1'); }
identifier_body
colors.rs
use std::io; use std::mem; use std::os::windows::io::AsRawHandle; use std::str::Bytes; use windows_sys::Win32::Foundation::HANDLE; use windows_sys::Win32::System::Console::{ GetConsoleScreenBufferInfo, SetConsoleTextAttribute, CONSOLE_SCREEN_BUFFER_INFO, FOREGROUND_BLUE as FG_BLUE, FOREGROUND_GREEN as FG_GREEN...
() -> io::Result<Console> { Self::create_for_stream(HandleKind::Stdout) } /// Create a new Console to stderr. /// /// If there was a problem creating the console, then an error is returned. pub fn stderr() -> io::Result<Console> { Self::create_for_stream(HandleKind::Stderr) } ...
stdout
identifier_name
log.go
package log import ( "errors" "github.com/qjpcpu/filelog" "github.com/qjpcpu/log/logging" "io" syslog "log" "os" "path/filepath" "runtime/debug" "strings" "sync" ) type moduleLoggers struct { loggers map[string]*logWrapper *sync.RWMutex } type logWrapper struct { *logging.Logger option *LogOptio...
filename return lo } // SetLevel set log level func (lo *LogOption) SetLevel(level string) *LogOption { lo.Level = parseLogLevel(level) return lo } // SetTypedLevel set log level func (lo *LogOption) SetTypedLevel(level Level) *LogOption { lo.Level = level return lo } // SetFormat set log format func (lo *LogO...
gFile =
identifier_name
log.go
package log import ( "errors" "github.com/qjpcpu/filelog" "github.com/qjpcpu/log/logging" "io" syslog "log" "os" "path/filepath" "runtime/debug" "strings" "sync" ) type moduleLoggers struct { loggers map[string]*logWrapper *sync.RWMutex } type logWrapper struct { *logging.Logger option *LogOptio...
count := 0 for i, ch := range stackInfo { if ch == '\n' { if count == 0 { start = i } else if count == 4 { stackInfo = append(stackInfo[0:start+1], stackInfo[i+1:]...) break } count++ } } var extra string if len(desc) > 0 && desc[0] != "" { extra = "[" + desc[0] + "]" ...
func MustNoErr(err error, desc ...string) { if err != nil { stackInfo := debug.Stack() start := 0
random_line_split
log.go
package log import ( "errors" "github.com/qjpcpu/filelog" "github.com/qjpcpu/log/logging" "io" syslog "log" "os" "path/filepath" "runtime/debug" "strings" "sync" ) type moduleLoggers struct { loggers map[string]*logWrapper *sync.RWMutex } type logWrapper struct { *logging.Logger option *LogOptio...
LogFp, "", 0) backendInfoFormatter := logging.NewBackendFormatter(backendInfo, format) backendInfoLeveld := logging.AddModuleLevel(backendInfoFormatter) backendInfoLeveld.SetLevel(opt.Level.loggingLevel(), "") leveldBackend = backendInfoLeveld backends = append(backends, backendInfoLeveld) opt.files = appen...
", filename, err) } backendInfo := logging.NewLogBackend(info
conditional_block
log.go
package log import ( "errors" "github.com/qjpcpu/filelog" "github.com/qjpcpu/log/logging" "io" syslog "log" "os" "path/filepath" "runtime/debug" "strings" "sync" ) type moduleLoggers struct { loggers map[string]*logWrapper *sync.RWMutex } type logWrapper struct { *logging.Logger option *LogOptio...
...interface{}) { if defaultLgr == nil { return } defaultLgr.Fatalf(strings.TrimSpace(strings.Repeat("%+v ", len(args))), args...) } // Error write leveled log func Error(args ...interface{}) { if defaultLgr == nil { return } defaultLgr.Errorf(strings.TrimSpace(strings.Repeat("%+v ", len(args))), args...) }...
ltLgr.Criticalf(strings.TrimSpace(strings.Repeat("%+v ", len(args))), args...) } // Fatal write leveled log func Fatal(args
identifier_body
appendlist.rs
use std::cell::{Cell, UnsafeCell}; use std::fmt::{self, Debug}; use std::iter::FromIterator; use std::ops::Index; use crate::common::{chunk_size, chunk_start, index_chunk}; /// A list that can be appended to while elements are borrowed /// /// This looks like a fairly bare-bones list API, except that it has a `push` ...
/// Create a new `AppendList` pub fn new() -> Self { Self { chunks: UnsafeCell::new(Vec::new()), len: Cell::new(0), } } /// Append an item to the end /// /// Note that this does not require `mut`. pub fn push(&self, item: T) { self.check_inv...
{ #[cfg(test)] { if self.len.get() > 0 { // Correct number of chunks assert_eq!(index_chunk(self.len.get() - 1), self.chunks().len() - 1); // Every chunk holds enough items for chunk_id in 0..self.chunks().len() { ...
identifier_body
appendlist.rs
use std::cell::{Cell, UnsafeCell}; use std::fmt::{self, Debug}; use std::iter::FromIterator; use std::ops::Index; use crate::common::{chunk_size, chunk_start, index_chunk}; /// A list that can be appended to while elements are borrowed /// /// This looks like a fairly bare-bones list API, except that it has a `push` ...
(&self) -> usize { self.check_invariants(); self.len.get() } /// Get an item from the list, if it is in bounds /// /// Returns `None` if the `index` is out-of-bounds. Note that you can also /// index with `[]`, which will panic on out-of-bounds. pub fn get(&self, index: usize) ...
len
identifier_name
appendlist.rs
use std::cell::{Cell, UnsafeCell}; use std::fmt::{self, Debug}; use std::iter::FromIterator; use std::ops::Index; use crate::common::{chunk_size, chunk_start, index_chunk}; /// A list that can be appended to while elements are borrowed /// /// This looks like a fairly bare-bones list API, except that it has a `push` ...
impl<'l, T> Iterator for Iter<'l, T> { type Item = &'l T; fn next(&mut self) -> Option<Self::Item> { let item = self.list.get(self.index); self.index += 1; item } fn size_hint(&self) -> (usize, Option<usize>) { let remaining = self.list.len() - self.index; (r...
index: usize, }
random_line_split
unified.rs
use std::cmp; use std::collections::HashSet; use std::convert::{TryFrom, TryInto}; use std::error::Error; use std::fmt; use std::io::Write; use zcash_encoding::CompactSize; use crate::kind; /// The HRP for a Bech32m-encoded mainnet Unified Address. /// /// Defined in [ZIP 316][zip-0316]. /// /// [zip-0316]: https://z...
else { typecodes.insert(t); } } if typecodes.iter().all(|t| t.is_transparent()) { Err(ParseError::OnlyTransparent) } else { // All checks pass! Ok(Address(receivers)) } } } impl Address { /// Returns the raw encod...
{ return Err(ParseError::BothP2phkAndP2sh); }
conditional_block
unified.rs
use std::cmp; use std::collections::HashSet; use std::convert::{TryFrom, TryInto}; use std::error::Error; use std::fmt; use std::io::Write; use zcash_encoding::CompactSize; use crate::kind; /// The HRP for a Bech32m-encoded mainnet Unified Address. /// /// Defined in [ZIP 316][zip-0316]. /// /// [zip-0316]: https://z...
{ /// The unified address contains both P2PKH and P2SH receivers. BothP2phkAndP2sh, /// The unified address contains a duplicated typecode. DuplicateTypecode(Typecode), /// The parsed typecode exceeds the maximum allowed CompactSize value. InvalidTypecodeValue(u64), /// The string is an inv...
ParseError
identifier_name
unified.rs
use std::cmp; use std::collections::HashSet; use std::convert::{TryFrom, TryInto}; use std::error::Error; use std::fmt; use std::io::Write; use zcash_encoding::CompactSize; use crate::kind; /// The HRP for a Bech32m-encoded mainnet Unified Address. /// /// Defined in [ZIP 316][zip-0316]. /// /// [zip-0316]: https://z...
// Unknown typecodes are treated as not transparent for the purpose of disallowing // only-transparent UAs, which can be represented with existing address encodings. matches!(self, Typecode::P2pkh | Typecode::P2sh) } } /// An error while attempting to parse a string as a Zcash address. #[de...
impl Typecode { fn is_transparent(&self) -> bool {
random_line_split
__init__.py
""" Copyright 2015-2016 Christian Fobel and Ryan Fobel This file is part of dropbot_dx_plugin. dropbot_dx_plugin is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your optio...
return wrapped return wrapper(_lambda) def get_unique_path(filepath): ''' Append `-###` to the base name of a file until a file path is found that does not exist. Args ---- filepath (str) : Full file path to target file. Returns ------- (path) : Full path w...
f(self, *f_args, **f_kwargs)
conditional_block
__init__.py
""" Copyright 2015-2016 Christian Fobel and Ryan Fobel This file is part of dropbot_dx_plugin. dropbot_dx_plugin is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your optio...
def get_environment_state(self, master=None, i2c_address=0x27): ''' Acquire temperature and humidity from Honeywell HIH6000 series sensor. [1]: http://sensing.honeywell.com/index.php/ci_id/142171/la_id/1/document/1/re_id/0 ''' if master is None: master ...
''' Connect to dropbot-dx instrument. ''' self.has_environment_data = False self.environment_sensor_master = None # if the dropbot dx plugin is installed and enabled, try getting its # reference try: service = get_service_instance_by_name('wheelerlab....
identifier_body
__init__.py
""" Copyright 2015-2016 Christian Fobel and Ryan Fobel This file is part of dropbot_dx_plugin. dropbot_dx_plugin is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your optio...
(Plugin, AppDataController, StepOptionsController): """ This class is automatically registered with the PluginManager. """ implements(IPlugin) version = get_plugin_info(path(__file__).parent).version plugin_name = get_plugin_info(path(__file__).parent).plugin_name AppFields = Form.of(Float....
DropBotDxAccessoriesPlugin
identifier_name
__init__.py
""" Copyright 2015-2016 Christian Fobel and Ryan Fobel This file is part of dropbot_dx_plugin. dropbot_dx_plugin is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your optio...
########################################################################### # # Plugin signal handlers # def get_schedule_requests(self, function_name): """ Returns a list of scheduling requests (i.e., ScheduleRequest instances) for the function specified by function_name. "...
if valid: options['dstat_params_file'] = response['dstat_params_file'] self.set_step_values(options)
random_line_split
Script_graph_data.py
from os import chdir, listdir, mkdir, remove from urllib.request import urlretrieve from tkinter import font as tkFont from datetime import datetime, timedelta, date import pathlib, time, tkinter import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as colors im...
return Countries_to_annotate, Annotations_mask def Scatter_graph(COVID_data_scatter, Display_annotations_mask = False): """ Plots data entered in parameters Parameters: - COVID_data_scatter: Reconstructed dictionnary of the 3 columns the user asked to plot throughout ...
Countries_to_annotate[Country] = Points_to_display[Country_inc] # The country has to be annotated Annotations_mask[Annotation_slice] = True # All the elements in Annotations_mask in this area are set to True to signify there is now an annotation displayed there
conditional_block
Script_graph_data.py
from os import chdir, listdir, mkdir, remove from urllib.request import urlretrieve from tkinter import font as tkFont from datetime import datetime, timedelta, date import pathlib, time, tkinter import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as colors im...
def Scatter_graph(COVID_data_scatter, Display_annotations_mask = False): """ Plots data entered in parameters Parameters: - COVID_data_scatter: Reconstructed dictionnary of the 3 columns the user asked to plot throughout time - Display_annotations_mask: Boolean indicat...
""" Tells which countries to annotate and which not to. Since the lists in parameters are sorted by descending order of positivity rate, the countries with higher positivity rates will be examined first and thus annotatd with more priority Parameters: - Points_to_display: List of X and Y coordi...
identifier_body
Script_graph_data.py
from os import chdir, listdir, mkdir, remove from urllib.request import urlretrieve from tkinter import font as tkFont from datetime import datetime, timedelta, date import pathlib, time, tkinter import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as colors im...
X_list_frame, Y_list_frame = zip(*Points_to_display) # Separate X and Y axes and plot the points scatter = ax.scatter(X_list_frame, Y_list_frame, c = Points_colors, s = np.pi * (Marker_ray*72/fig.dpi)**2, linewidth = 0.5, edgecolors = 'black') # Marker ray is the radius of the circle in pixel...
random_line_split
Script_graph_data.py
from os import chdir, listdir, mkdir, remove from urllib.request import urlretrieve from tkinter import font as tkFont from datetime import datetime, timedelta, date import pathlib, time, tkinter import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as colors im...
(X_axis_inc = 1, Y_axis_inc = 7, Z_axis_inc = 12, Date_start = None, Date_end = None): """ Main routine to execute to download, extract, reconstruct and plot COVID data Parameters: - X_axis_inc: Integer, data to use for the X axis. Default is 1 (Total cases per million) - Y_axis_i...
Main_script
identifier_name
script.js
///IMPORTS----------------------------------------- import screens from './components/screens.js' import PausedTimeout from './functions/pausedTimeout.js' import map1 from './maps/map1.js' import map2 from './maps/map2.js' import map3 from './maps/map3.js' import map4 from './maps/map4.js' import map5 from './maps/map...
(){ for(let key in activeKeys){ delete activeKeys[key] } } function handleVictory(){ clearIntervals() screens({ title:'Goal reached!', content:"", button:"Next Level", }) state.paused=true state.completed=true } var crashListener = setInte...
deleteKeys
identifier_name
script.js
///IMPORTS----------------------------------------- import screens from './components/screens.js' import PausedTimeout from './functions/pausedTimeout.js' import map1 from './maps/map1.js' import map2 from './maps/map2.js' import map3 from './maps/map3.js' import map4 from './maps/map4.js' import map5 from './maps/map...
} function checkCrash(){ if(state.paused) return let ratio = rotationPercentage() function checkBoundaries(){ if( (yPosition + (25 * ratio) ) < 0 | //TOP ((yPosition + mycar.offsetHeight) - (25 * ratio) ) > gameArea.offsetHeight | //BOTTOM (xPosition - (25 * r...
{ return false }
conditional_block