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
execution.rs
// Copyright 2018-2021 Parity Technologies (UK) Ltd. // // 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 applicab...
/// where `E` is some unspecified error type. /// If the contract initializer returns `Result::Err` the utility /// method that is used to initialize an ink! smart contract will /// revert the state of the contract instantiation. pub trait ConstructorReturnType<C>: private::Sealed { /// Is `true` if `Self` is `Resu...
random_line_split
fate_of_ashborne.py
#======================================== #Title: The Fate of Ashborne #Creator: Adam Majmudar #Date Created: Friday, January 11th, 2019 #======================================== import text_adventure_engine as txt import text_adventure_gui as gui """ Add intial phrase that establishes goal to 'find ou...
#Ease of Use for True and False T = True F = False towering_cliffs = txt.Location("The Towering Cliffs", -1, 0, 0, T, [T, T, F, F, F, F]) towering_cliffs.initial_description = "A few hundred feet below, a river rushes by and beats the side of the precipitous cliff. You look out in the distance and can see what lo...
"""
random_line_split
svm_1_0_0.py
#!/usr/bin/env python """ usage: svm.py unified_input.csv engine_score_column_name i.e. : svm.py omssa_2_1_6_unified.csv 'OMSSA:pvalue' Writes a new file with added column "SVMscore" which is the distance to the separating hyperplane of a Percolator-like support vector machine. """ impo...
) if s["kernel"].lower() == "linear": print() # print SVM coefficients (only works for linear kernel) print(svm_classifier.coef_) print() print("\nCounter:") print(s.counter) print() s.add_scores_to_csv()
s.classify( svm_classifier, s.X[test_index],
random_line_split
svm_1_0_0.py
#!/usr/bin/env python """ usage: svm.py unified_input.csv engine_score_column_name i.e. : svm.py omssa_2_1_6_unified.csv 'OMSSA:pvalue' Writes a new file with added column "SVMscore" which is the distance to the separating hyperplane of a Percolator-like support vector machine. """ impo...
self.matrix_csv_path = self["dump_svm_matrix"] print("Dumping raw SVM input matrix to", self.matrix_csv_path) with open(self.matrix_csv_path, "w") as f: f.write("\t".join(colnames) + "\n") def dump_svm_matrix_row( self, row=None, psm_id=None, lab...
colnames.append("proteinId{0}".format(n_proteins + 1))
conditional_block
svm_1_0_0.py
#!/usr/bin/env python """ usage: svm.py unified_input.csv engine_score_column_name i.e. : svm.py omssa_2_1_6_unified.csv 'OMSSA:pvalue' Writes a new file with added column "SVMscore" which is the distance to the separating hyperplane of a Percolator-like support vector machine. """ impo...
def add_scores_to_csv(self): outfname = os.path.basename(self["output_csv"]) print("Writing output csv {0} ...".format(outfname)) msg = "Writing output csv {0} (line ~{1})..." with open(self["output_csv"], "w", newline="") as out_csv, open( self.csv_path, "r" )...
msg = "Classifying {0} PSMs...".format(len(psm_matrix)) print(msg, end="\r") for i, row in enumerate(psm_matrix): # get the distance to the separating SVM hyperplane and use it as a score: svm_score = classifier.decision_function(np.array([row]))[0] features = tuple(...
identifier_body
svm_1_0_0.py
#!/usr/bin/env python """ usage: svm.py unified_input.csv engine_score_column_name i.e. : svm.py omssa_2_1_6_unified.csv 'OMSSA:pvalue' Writes a new file with added column "SVMscore" which is the distance to the separating hyperplane of a Percolator-like support vector machine. """ impo...
(self, row): """ Converts a unified CSV row to a SVM feature matrix (numbers only!) """ sequence = unify_sequence(row["Sequence"]) charge = field_to_float(row["Charge"]) score = field_to_bayes_float(row[self.col_for_sorting]) calc_mz, exp_mz, calc_mass, exp_mass =...
row_to_features
identifier_name
exec.rs
// Copyright 2018 Grove Enterprises 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 ...
df.write("_uk_cities_wkt.csv").unwrap(); //TODO: check that generated file has expected contents } fn create_context() -> ExecutionContext { // create execution context let mut ctx = ExecutionContext::new(); // define schemas for test data ctx.define_schema("p...
ctx.define_function(&STPointFunc {}); let df = ctx.sql(&"SELECT ST_AsText(ST_Point(lat, lng)) FROM uk_cities").unwrap();
random_line_split
exec.rs
// Copyright 2018 Grove Enterprises 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 ...
(&self, expr: Vec<Expr>) -> Result<Box<DataFrame>, DataFrameError> { let plan = LogicalPlan::Projection { expr: expr, input: self.plan.clone(), schema: self.plan.schema().clone() }; Ok(Box::new(DF { ctx: self.ctx.clone(), plan: Box::new(plan) })) } ...
select
identifier_name
exec.rs
// Copyright 2018 Grove Enterprises 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 ...
pub fn udf(&self, name: &str, args: Vec<Expr>) -> Expr { Expr::ScalarFunction { name: name.to_string(), args: args.clone() } } } pub struct DF { ctx: Box<ExecutionContext>, plan: Box<LogicalPlan> } impl DataFrame for DF { fn select(&self, expr: Vec<Expr>) -> Result<Box<DataFrame>, D...
{ //TODO: this is a huge hack since the functions have already been registered with the // execution context ... I need to implement this so it dynamically loads the functions match function_name.to_lowercase().as_ref() { "sqrt" => Ok(Box::new(SqrtFunction {})), "st_poi...
identifier_body
refresh.go
// Copyright 2016-2022, Pulumi Corporation. // // 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...
() *cobra.Command { var debug bool var expectNop bool var message string var execKind string var execAgent string var stackName string // Flags for remote operations. remoteArgs := RemoteArgs{} // Flags for engine.UpdateOptions. var jsonDisplay bool var diffDisplay bool var eventLogPath string var parall...
newRefreshCmd
identifier_name
refresh.go
// Copyright 2016-2022, Pulumi Corporation. // // 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...
op, err := f(op) if err != nil { return err } if op != nil { pending = append(pending, *op) } } snap.PendingOperations = pending return nil }) } // Apply the CLI args from --import-pending-creates [[URN ID]...]. If an error was found, // it is returned. The list of URNs that were not map...
{ pending = append(pending, op) continue }
conditional_block
refresh.go
// Copyright 2016-2022, Pulumi Corporation. // // 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...
// Apply the CLI args from --import-pending-creates [[URN ID]...]. If an error was found, // it is returned. The list of URNs that were not mapped to a pending create is also // returned. func pendingCreatesToImports(ctx context.Context, s backend.Stack, yes bool, opts display.Options, importToCreates []string, ) ([...
{ return totalStateEdit(ctx, s, yes, opts, func(opts display.Options, snap *deploy.Snapshot) error { var pending []resource.Operation for _, op := range snap.PendingOperations { if op.Resource == nil { return fmt.Errorf("found operation without resource") } if op.Type != resource.OperationTypeCreating...
identifier_body
refresh.go
// Copyright 2016-2022, Pulumi Corporation. // // 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...
"the program text isn't updated accordingly, subsequent updates may still appear to be out of\n" + "synch with respect to the cloud provider's source of truth.\n" + "\n" + "The program to run is loaded from the project in the current directory. Use the `-C` or\n" + "`--cwd` flag to use a different direct...
Short: "Refresh the resources in a stack", Long: "Refresh the resources in a stack.\n" + "\n" + "This command compares the current stack's resource state with the state known to exist in\n" + "the actual cloud provider. Any such changes are adopted into the current stack. Note that if\n" +
random_line_split
main.rs
extern crate hsl; extern crate rand; extern crate sdl2; use sdl2::audio::{AudioCVT, AudioSpecDesired, AudioSpecWAV, AudioQueue}; use sdl2::event::Event; use sdl2::image::{INIT_PNG, LoadSurface}; use sdl2::gfx::rotozoom::RotozoomSurface; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::rect::Rect; use sd...
} struct RandomPositionStrategy {} impl PositionStrategy for RandomPositionStrategy { // Return a random position that fits rect within rect fn next_position(&mut self, rect: Rect, within_rect: Rect) -> Rect { let rx: f64 = thread_rng().gen(); let ry: f64 = thread_rng().gen(); let pos...
{ }
identifier_body
main.rs
extern crate hsl; extern crate rand; extern crate sdl2; use sdl2::audio::{AudioCVT, AudioSpecDesired, AudioSpecWAV, AudioQueue}; use sdl2::event::Event; use sdl2::image::{INIT_PNG, LoadSurface}; use sdl2::gfx::rotozoom::RotozoomSurface; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::rect::Rect; use sd...
.collect(); let mut background_color = random_colour(Color::RGB(255, 255, 255)); 'running: loop { for event in event_pump.poll_iter() { match event { Event::Quit { .. } | Event::KeyDown { keycode: Some(Keycode::Escape), ...
("U", "upsiedaisy"), ("W", "woody"), ].iter() .map(|(s1, s2)| (s1.to_string(), s2.to_string()))
random_line_split
main.rs
extern crate hsl; extern crate rand; extern crate sdl2; use sdl2::audio::{AudioCVT, AudioSpecDesired, AudioSpecWAV, AudioQueue}; use sdl2::event::Event; use sdl2::image::{INIT_PNG, LoadSurface}; use sdl2::gfx::rotozoom::RotozoomSurface; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::rect::Rect; use sd...
(&mut self) { } } struct RandomPositionStrategy {} impl PositionStrategy for RandomPositionStrategy { // Return a random position that fits rect within rect fn next_position(&mut self, rect: Rect, within_rect: Rect) -> Rect { let rx: f64 = thread_rng().gen(); let ry: f64 = thread_rng().ge...
reset
identifier_name
main.rs
extern crate hsl; extern crate rand; extern crate sdl2; use sdl2::audio::{AudioCVT, AudioSpecDesired, AudioSpecWAV, AudioQueue}; use sdl2::event::Event; use sdl2::image::{INIT_PNG, LoadSurface}; use sdl2::gfx::rotozoom::RotozoomSurface; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::rect::Rect; use sd...
} _ => {} } } // Draw the chars canvas.set_draw_color(background_color); canvas.clear(); for &(ref texture, target) in drawables.iter() { canvas.copy(&texture, None, Some(target.clone())).unwrap(); } canvas....
{ let mut surface = load_image(&filename); let sf = (100f64 / surface.height() as f64); println!("{}", sf ); let surface = surface.rotozoom(0f64, sf, false).unwrap(); let texture = texture_creator ...
conditional_block
system.rs
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: 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 // // ht...
inline(always)] fn check_signature(utx: &Extrinsic) -> Result<(), TransactionValidityError> { use sp_runtime::traits::BlindCheckable; utx.clone().check().map_err(|_| InvalidTransaction::BadProof.into()).map(|_| ()) } fn execute_transaction_backend(utx: &Extrinsic, extrinsic_index: u32) -> ApplyExtrinsicResult { che...
{ let extrinsic_index: u32 = storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX).unwrap(); let txs: Vec<_> = (0..extrinsic_index).map(ExtrinsicData::take).collect(); let extrinsics_root = trie::blake2_256_ordered_root(txs).into(); let number = <Number>::take().expect("Number is set by `initialize_block`"); l...
identifier_body
system.rs
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: 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 // // ht...
else { vec![] }; let provides = vec![encode(&tx.from, tx.nonce)]; Ok(ValidTransaction { priority: tx.amount, requires, provides, longevity: 64, propagate: true }) } /// Execute a transaction outside of the block execution function. /// This doesn't attempt to validate anything regarding the block. pub fn execu...
{ vec![encode(&tx.from, tx.nonce - 1)] }
conditional_block
system.rs
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: 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 // // ht...
{ Verify, Overwrite, } /// Actually execute all transitioning for `block`. pub fn polish_block(block: &mut Block) { execute_block_with_state_root_handler(block, Mode::Overwrite); } pub fn execute_block(mut block: Block) { execute_block_with_state_root_handler(&mut block, Mode::Verify); } fn execute_block_with_s...
Mode
identifier_name
system.rs
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: 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 // // ht...
} } pub fn balance_of_key(who: AccountId) -> Vec<u8> { who.to_keyed_vec(BALANCE_OF) } pub fn balance_of(who: AccountId) -> u64 { storage::hashed::get_or(&blake2_256, &balance_of_key(who), 0) } pub fn nonce_of(who: AccountId) -> u64 { storage::hashed::get_or(&blake2_256, &who.to_keyed_vec(NONCE_OF), 0) } pub fn ...
NewAuthorities get(fn new_authorities): Option<Vec<AuthorityId>>; NewChangesTrieConfig get(fn new_changes_trie_config): Option<Option<ChangesTrieConfiguration>>; StorageDigest get(fn storage_digest): Option<Digest>; Authorities get(fn authorities) config(): Vec<AuthorityId>;
random_line_split
main.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # from functions import * #import objects here import api import db import comm import stats from config import * from functions import * from traceback import format_tb as traceback_format def
(): cryptowatch_api.close() transaction_api.close() print("") print("-" * 15) print("closed Api connection") database.commit() database.close() print("closed db connection") print(time.ctime()) print("<---- QUITTING ---->") """ start cryptowatch - make an api object - make a db...
wrap_up
identifier_name
main.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # from functions import * #import objects here import api import db import comm import stats from config import * from functions import * from traceback import format_tb as traceback_format def wrap_up(): cryptowatch_api.close() transaction_api.close() prin...
elif e.args[0] == 28 and error_stats[28] < 10: pass # don't send an email on an occasional timeout elif e.args[0] == 28 and error_stats[28] == 10: cryptowatch_api.reset_connection() transaction_api.reset_connection() communicator.send_message("Timeout oc...
pass # wait for the network to get up maybe
conditional_block
main.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # from functions import * #import objects here import api import db import comm import stats from config import * from functions import * from traceback import format_tb as traceback_format def wrap_up(): cryptowatch_api.close() transaction_api.close() prin...
error_stats[e.args[0]] = 1 else: error_stats[e.args[0]] += 1 db_id = database.put_error(e, int(time.time())) print(e) print("error counts:", error_stats) if e.args[0] == 7 and e.args[1].split()[4] in [ p["ip"] for h, p in PROXIES.items() ...
if e.args[0] not in error_stats.keys():
random_line_split
main.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # from functions import * #import objects here import api import db import comm import stats from config import * from functions import * from traceback import format_tb as traceback_format def wrap_up():
""" start cryptowatch - make an api object - make a db object - query api and insert into db in a loop """ stats_file_name = '/dev/shm/gdax.stats' communicator = comm.Comm('Trade_bot_test_run', 'email@example.com') #leaving as example #database = db.Bitmarket(DB_USER, DB_PASSWORD, dbname='bitmarket', dbhost='aruba...
cryptowatch_api.close() transaction_api.close() print("") print("-" * 15) print("closed Api connection") database.commit() database.close() print("closed db connection") print(time.ctime()) print("<---- QUITTING ---->")
identifier_body
delaunay_triangulation.rs
/*! The following code has been modified from the original delaunator-rs project: https://github.com/mourner/delaunator-rs For a description of the data structure, including the halfedge connectivity, see: https://mapbox.github.io/delaunator/ # Description A very fast 2D [Delaunay Triangulation](https://en.wikiped...
r. pub fn triangle_center(&self, points: &[Point2D], triangle: usize) -> Point2D { let p = self.points_of_triangle(triangle); points[p[0]].circumcenter(&points[p[1]], &points[p[2]]) } /// Returns the edges around a point connected to halfedge '*start*'. pub fn edges_around_point(&self, ...
angle(t) // .into_iter() // .map(|e| self.triangles[*e]) // .collect() let e = self.edges_of_triangle(triangle); [ self.triangles[e[0]], self.triangles[e[1]], self.triangles[e[2]], ] } /// Triangle circumcente
identifier_body
delaunay_triangulation.rs
/*! The following code has been modified from the original delaunator-rs project: https://github.com/mourner/delaunator-rs For a description of the data structure, including the halfedge connectivity, see: https://mapbox.github.io/delaunator/ # Description A very fast 2D [Delaunay Triangulation](https://en.wikiped...
result.push(incoming); break; } // i += 1; // if i > 100 { // // println!("{} {} {}", outgoing, incoming, start); // break; // } } result } pub fn natural_neighbours_from_incoming_edge...
} else if incoming == start {
conditional_block
delaunay_triangulation.rs
/*! The following code has been modified from the original delaunator-rs project: https://github.com/mourner/delaunator-rs For a description of the data structure, including the halfedge connectivity, see: https://mapbox.github.io/delaunator/ # Description A very fast 2D [Delaunay Triangulation](https://en.wikiped...
} impl Triangulation { /// Constructs a new *Triangulation*. fn new(n: usize) -> Self { let max_triangles = 2 * n - 5; Self { triangles: Vec::with_capacity(max_triangles * 3), halfedges: Vec::with_capacity(max_triangles * 3), hull: Vec::new(), } }...
/// counter-clockwise. pub hull: Vec<usize>,
random_line_split
delaunay_triangulation.rs
/*! The following code has been modified from the original delaunator-rs project: https://github.com/mourner/delaunator-rs For a description of the data structure, including the halfedge connectivity, see: https://mapbox.github.io/delaunator/ # Description A very fast 2D [Delaunay Triangulation](https://en.wikiped...
0: usize, i1: usize, i2: usize, a: usize, b: usize, c: usize, ) -> usize { let t = self.triangles.len(); self.triangles.push(i0); self.triangles.push(i1); self.triangles.push(i2); self.halfedges.push(a); self.halfedges.push(b)...
f, i
identifier_name
api.py
import requests from requests import HTTPError from pbincli.utils import PBinCLIError def _config_requests(settings=None, shortener=False): if settings['no_insecure_warning']: from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(Insecure...
class Shortener: """Some parts of this class was taken from python-yourls (https://github.com/tflink/python-yourls/) library """ def __init__(self, settings=None): self.api = settings['short_api'] if self.api is None: PBinCLIError("Unable to activate link shortener withou...
def __init__(self, settings=None): self.server = settings['server'] self.headers = {'X-Requested-With': 'JSONHttpRequest'} self.session = _config_requests(settings, False) def post(self, request): result = self.session.post( url = self.server, headers = self...
identifier_body
api.py
import requests from requests import HTTPError from pbincli.utils import PBinCLIError def _config_requests(settings=None, shortener=False): if settings['no_insecure_warning']: from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(Insecure...
except Exception as ex: PBinCLIError("Shorter: unexcepted behavior: {}".format(ex))
print("Short Link:\t{}".format(result.text))
random_line_split
api.py
import requests from requests import HTTPError from pbincli.utils import PBinCLIError def _config_requests(settings=None, shortener=False): if settings['no_insecure_warning']: from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(Insecure...
def getVersion(self): result = self.session.get( url = self.server + '?jsonld=paste', headers = self.headers) try: jsonldSchema = result.json() return jsonldSchema['@context']['v']['@value'] \ if ('@context' in jsonldSchema and ...
PBinCLIError("Something went wrong...\nError: Empty response.")
conditional_block
api.py
import requests from requests import HTTPError from pbincli.utils import PBinCLIError def _config_requests(settings=None, shortener=False): if settings['no_insecure_warning']: from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(Insecure...
(self, url): request = {'url': url} try: result = self.session.post( url = "https://clck.ru/--", data = request) print("Short Link:\t{}".format(result.text)) except Exception as ex: PBinCLIError("clck.ru: unexcepted behavior: {...
_clckru
identifier_name
txn_process.go
// Copyright (c) 2018 Cisco and/or its affiliates. // // 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 applicabl...
if origin == kvs.FromSB && getNodeOrigin(node) == kvs.FromNB { s.Log.WithFields(logging.Fields{ "txnSeqNum": txnSeqNum, "key": key, }).Debug("Ignoring notification for a NB-managed value") return false } } return true }
{ s.Log.WithFields(logging.Fields{ "txnSeqNum": txnSeqNum, "key": key, }).Warn("Transaction attempting to change a derived value") return false }
conditional_block
txn_process.go
// Copyright (c) 2018 Cisco and/or its affiliates. // // 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 applicabl...
// postProcessTransaction schedules retry for failed operations and propagates // errors to the subscribers and to the caller of a blocking commit. func (s *Scheduler) postProcessTransaction(txn *preProcessedTxn, executed kvs.RecordedTxnOps, failed map[string]bool, preErrors []kvs.KeyWithError) { // refresh base val...
{ graphR := s.graph.Read() defer graphR.Release() for _, key := range qTxn.retry.keys.Iterate() { node := graphR.GetNode(key) if node == nil { continue } lastChange := getNodeLastChange(node) if lastChange.txnSeqNum > qTxn.retry.txnSeqNum { // obsolete retry, the value has been changed since the fai...
identifier_body
txn_process.go
// Copyright (c) 2018 Cisco and/or its affiliates. // // 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 applicabl...
(graphR graph.ReadAccess, key string, value proto.Message, origin kvs.ValueOrigin, txnSeqNum uint64) bool { if key == "" { s.Log.WithFields(logging.Fields{ "txnSeqNum": txnSeqNum, }).Warn("Empty key for a value in the transaction") return false } if origin == kvs.FromSB { descriptor := s.registry.GetDescr...
validTxnValue
identifier_name
txn_process.go
// Copyright (c) 2018 Cisco and/or its affiliates. // // 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 applicabl...
s.enqueueRetry(retryTxn) } graphW.Release() } // collect errors var txnErrors []kvs.KeyWithError txnErrors = append(txnErrors, preErrors...) for _, txnOp := range executed { if txnOp.PrevErr == nil && txnOp.NewErr == nil { continue } txnErrors = append(txnErrors, kvs.KeyWithError{ Key: ...
random_line_split
model.py
#!/usr/bin/env python # coding: utf-8 ''' Event Clustering within News Articles accepted to AESPEN in LREC 2020. Faik Kerem Örs, Süveyda Yeniterzi, Reyyan Yeniterzi 2nd April 2020 - Version 1 ''' import numpy as np import pandas as pd import json import torch import time import datetime import random from torch....
def get_classes(preds): # Function to calculate the accuracy of our predictions vs labels # Based on https://medium.com/@aniruddha.choudhury94/part-2-bert-fine-tuning-tutorial-with-pytorch-for-text-classification-on-the-corpus-of-linguistic-18057ce330e1 pred_flat = np.argmax(preds, axis=1).flatten() ...
' Takes a time in seconds and returns a string hh:mm:ss Based on https://medium.com/@aniruddha.choudhury94/part-2-bert-fine-tuning-tutorial-with-pytorch-for-text-classification-on-the-corpus-of-linguistic-18057ce330e1 ''' # Round to the nearest second. elapsed_rounded = int(round((elapsed))) ...
identifier_body
model.py
#!/usr/bin/env python # coding: utf-8 ''' Event Clustering within News Articles accepted to AESPEN in LREC 2020. Faik Kerem Örs, Süveyda Yeniterzi, Reyyan Yeniterzi 2nd April 2020 - Version 1 ''' import numpy as np import pandas as pd import json import torch import time import datetime import random from torch....
ews_clusters): for news_index, clusters in news_clusters.items(): for lst in clusters: lst.sort() clusters.sort(key=lambda x: x[0]) def check_duplicates(news_clusters): # Check an element exists in other lists for news_index, clusters in news_clusters.items(): for lst in clusters: ...
rt_clusters(n
identifier_name
model.py
#!/usr/bin/env python # coding: utf-8 ''' Event Clustering within News Articles accepted to AESPEN in LREC 2020. Faik Kerem Örs, Süveyda Yeniterzi, Reyyan Yeniterzi 2nd April 2020 - Version 1 ''' import numpy as np import pandas as pd import json import torch import time import datetime import random from torch....
sentences.loc[sentences['Sentences'] == row['Sen_max'], 'Group'] = sentences.loc[sentences['Sentences'] == row['Sen_min'], 'Group'].iloc[0] else: pass # At the end if there are still sentences that have not been assigned to any group, then assign them to...
sentences.loc[sentences['Sentences'] == row['Sen_min'], 'Group'] = sentences.loc[sentences['Sentences'] == row['Sen_max'], 'Group'].iloc[0] elif sentences.loc[sentences['Sentences'] == row['Sen_max'], 'Group'].iloc[0] == 0:
random_line_split
model.py
#!/usr/bin/env python # coding: utf-8 ''' Event Clustering within News Articles accepted to AESPEN in LREC 2020. Faik Kerem Örs, Süveyda Yeniterzi, Reyyan Yeniterzi 2nd April 2020 - Version 1 ''' import numpy as np import pandas as pd import json import torch import time import datetime import random from torch....
# Unpack this training batch from our dataloader. # # As we unpack the batch, we'll also copy each tensor to the GPU using the # `to` method. # # `batch` contains three pytorch tensors: # [0]: input ids # [1]: attenti...
apsed = format_time(time.time() - t0) # Report progress. print(' Batch {:>5,} of {:>5,}. Elapsed: {:}.'.format(step, len(train_dataloader), elapsed))
conditional_block
toggle.rs
use bars_duration_ticks; use conrod_core::{self as conrod, widget}; use env; use ruler; use time_calc::{self as time, Ticks}; use track; pub use env::{Point, PointTrait, Toggle as ToggleValue, Trait as EnvelopeTrait}; /// The envelope type compatible with the `Toggle` automation track. pub type Envelope = env::bounde...
{ ids: Ids, } widget_ids! { struct Ids { circles[], rectangles[], phantom_line, } } #[derive(Copy, Clone, Debug, Default, PartialEq, WidgetStyle)] pub struct Style { #[conrod(default = "theme.shape_color")] pub color: Option<conrod::Color>, #[conrod(default = "4.0")] ...
State
identifier_name
toggle.rs
use bars_duration_ticks; use conrod_core::{self as conrod, widget}; use env; use ruler; use time_calc::{self as time, Ticks}; use track; pub use env::{Point, PointTrait, Toggle as ToggleValue, Trait as EnvelopeTrait}; /// The envelope type compatible with the `Toggle` automation track. pub type Envelope = env::bounde...
builder_methods! { pub point_radius { style.point_radius = Some(conrod::Scalar) } } } impl<'a> track::Widget for Toggle<'a> { fn playhead(mut self, playhead: (Ticks, Ticks)) -> Self { self.maybe_playhead = Some(playhead); self } } impl<'a> conrod::Colorable for Toggle<'a> { ...
{ Toggle { bars: bars, ppqn: ppqn, maybe_playhead: None, envelope: envelope, common: widget::CommonBuilder::default(), style: Style::default(), } }
identifier_body
toggle.rs
use bars_duration_ticks; use conrod_core::{self as conrod, widget}; use env; use ruler; use time_calc::{self as time, Ticks}; use track; pub use env::{Point, PointTrait, Toggle as ToggleValue, Trait as EnvelopeTrait}; /// The envelope type compatible with the `Toggle` automation track. pub type Envelope = env::bounde...
// _ => return, // }, // // Only draw the clicked point if it is still after the last point. // Clicked(Elem::AfterLastPoint, _, _) => // match envelope.points().last() { // Some(p) if p.ticks <= tic...
// // Only draw the clicked point if it is still before the first point. // Clicked(Elem::BeforeFirstPoint, _, _) => // match envelope.points().nth(0) { // Some(p) if ticks <= p.ticks => color.clicked().alpha(0.7),
random_line_split
ArabicOCR.py
# To Run Arabic OCR # python ArabicOCR.py <featureMethod> <classifier> # featureMethod: StatisticalFeatures - NewGeometricFeatures # classifier: SVM # TRAINING_DATASET = './Letters-Dataset-Generator/LettersDataset' TRAINING_DATASET = './Dataset/scanned' TESTING_DATASET = './Dataset/Testing' from importlib import imp...
(string, str_list): res = [ele for ele in str_list if(ele in string)] return bool(res) def readImages(folder, trainTest = 0): images = [] folders = [f for f in glob.glob(folder + "**/*", recursive=True)] y_vals = [] filesNames = [] for folder in folders: img_files = [img_file for i...
contains
identifier_name
ArabicOCR.py
# To Run Arabic OCR # python ArabicOCR.py <featureMethod> <classifier> # featureMethod: StatisticalFeatures - NewGeometricFeatures # classifier: SVM # TRAINING_DATASET = './Letters-Dataset-Generator/LettersDataset' TRAINING_DATASET = './Dataset/scanned' TESTING_DATASET = './Dataset/Testing' from importlib import imp...
skippedImages = 0 TotalImages = 0 processes = [] start_time = timeit.default_timer() dataset = sorted(glob.glob(TRAINING_DATASET + "*/*.png"), key=natural_keys)[4400:4600] # 3000 DONE for i in list(dataset): p = Process(target=loop, args=(i,)) p...
processedCharacters = 0 ignoredWords = 0 processedWords = 0 segmented = None
random_line_split
ArabicOCR.py
# To Run Arabic OCR # python ArabicOCR.py <featureMethod> <classifier> # featureMethod: StatisticalFeatures - NewGeometricFeatures # classifier: SVM # TRAINING_DATASET = './Letters-Dataset-Generator/LettersDataset' TRAINING_DATASET = './Dataset/scanned' TESTING_DATASET = './Dataset/Testing' from importlib import imp...
print("running time = ", timeit.default_timer() - start_time) print('Finished All#########################################') elif mode==2: featuresList=list(glob.glob("textFiles" + "/*.txt"))[:1000] for filepath in tqdm(featuresList): with open(filepath) as fp: ...
in()
conditional_block
ArabicOCR.py
# To Run Arabic OCR # python ArabicOCR.py <featureMethod> <classifier> # featureMethod: StatisticalFeatures - NewGeometricFeatures # classifier: SVM # TRAINING_DATASET = './Letters-Dataset-Generator/LettersDataset' TRAINING_DATASET = './Dataset/scanned' TESTING_DATASET = './Dataset/Testing' from importlib import imp...
def loop(i): pictureFeatures = [] pictureLabels = [] # actualCharacters = [] image = cv2.imread(i) textFileName = i[:-4].replace('scanned', 'text') textWords = open(textFileName + '.txt', encoding='utf-8').read().replace('\n', ' ').split(' ') textWords = [item for item in textWords if i...
lines = LineSegmentation(img, saveResults=False) # Segment lines into words words = [] for i in range(len(lines)): words.extend(WordSegmentation(lines[i], lineNumber = i, saveResults=False)) characters = [] # Segment words into characters for word in words: characters.append(Char...
identifier_body
trace_service.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: envoy/service/trace/v3alpha/trace_service.proto package envoy_service_trace_v3alpha import ( context "context" fmt "fmt" core "github.com/altipla-consulting/envoy-api/envoy/api/v3alpha/core" v1 "github.com/census-instrumentation/opencensus-proto/gen-go/t...
() { *m = StreamTracesMessage{} } func (m *StreamTracesMessage) String() string { return proto.CompactTextString(m) } func (*StreamTracesMessage) ProtoMessage() {} func (*StreamTracesMessage) Descriptor() ([]byte, []int) { return fileDescriptor_838555a39f11343b, []int{1} } func (m *StreamTracesMessage) XXX...
Reset
identifier_name
trace_service.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: envoy/service/trace/v3alpha/trace_service.proto package envoy_service_trace_v3alpha import ( context "context" fmt "fmt" core "github.com/altipla-consulting/envoy-api/envoy/api/v3alpha/core" v1 "github.com/census-instrumentation/opencensus-proto/gen-go/t...
return nil } func init() { proto.RegisterType((*StreamTracesResponse)(nil), "envoy.service.trace.v3alpha.StreamTracesResponse") proto.RegisterType((*StreamTracesMessage)(nil), "envoy.service.trace.v3alpha.StreamTracesMessage") proto.RegisterType((*StreamTracesMessage_Identifier)(nil), "envoy.service.trace.v3alpha...
{ return m.Node }
conditional_block
trace_service.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: envoy/service/trace/v3alpha/trace_service.proto package envoy_service_trace_v3alpha import ( context "context" fmt "fmt" core "github.com/altipla-consulting/envoy-api/envoy/api/v3alpha/core" v1 "github.com/census-instrumentation/opencensus-proto/gen-go/t...
func (m *StreamTracesResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_StreamTracesResponse.Merge(m, src) } func (m *StreamTracesResponse) XXX_Size() int { return xxx_messageInfo_StreamTracesResponse.Size(m) } func (m *StreamTracesResponse) XXX_DiscardUnknown() { xxx_messageInfo_StreamTracesResponse.DiscardU...
{ return xxx_messageInfo_StreamTracesResponse.Marshal(b, m, deterministic) }
identifier_body
trace_service.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: envoy/service/trace/v3alpha/trace_service.proto package envoy_service_trace_v3alpha import ( context "context" fmt "fmt" core "github.com/altipla-consulting/envoy-api/envoy/api/v3alpha/core" v1 "github.com/census-instrumentation/opencensus-proto/gen-go/t...
Methods: []grpc.MethodDesc{}, Streams: []grpc.StreamDesc{ { StreamName: "StreamTraces", Handler: _TraceService_StreamTraces_Handler, ClientStreams: true, }, }, Metadata: "envoy/service/trace/v3alpha/trace_service.proto", }
random_line_split
msMHE_stgen.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue May 22 07:56:11 2018 @author: flemmingholtorf """ from __future__ import print_function from main.mods.SemiBatchPolymerization.mod_class_stgen import SemiBatchPolymerization_multistage from main.mods.SemiBatchPolymerization.mod_class import SemiBatchPol...
x_e = [c.nmpc_trajectory[i,'tf'] for i in range(1,iters)] for var in poi[:-2]: if var == 'MX': for k in [0,1]: y_e = [c.nmpc_trajectory[i,(var,(k,))] for i in range(1,iters)] y = [c.monitor[i][var,(1,cp,k,1)] for i in range(1,iters+1) for cp in range(ncp+1)] ...
x.append(x[-cp-1]+c.pc_trajectory['tf',(i,cp)] if i > 1 else c.pc_trajectory['tf',(i,cp)])
conditional_block
msMHE_stgen.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue May 22 07:56:11 2018 @author: flemmingholtorf """ from __future__ import print_function from main.mods.SemiBatchPolymerization.mod_class_stgen import SemiBatchPolymerization_multistage from main.mods.SemiBatchPolymerization.mod_class import SemiBatchPol...
[x[i][j],y[i][j],z[i][j]] = np.dot(U,[x[i][j],y[i][j],z[i][j]]) + center z[i][j] *= c.olnmpc.Hrxn['p'].value #f.write(str(x[i][j]) + '\t' + str(y[i][j]) + '\t' + str(z[i][j]) + '\n') #f.write('\n') #f.close() fig = plt.figure() ...
random_line_split
islandora_bulk_downloader.py
#!/usr/bin/env python3 import sys import os import csv import re import logging import argparse import urllib.request import requests from PIL import Image from PyPDF2 import PdfFileMerger from shutil import rmtree, copytree # Functions def pid_to_path(pid): # Converts PID into a string suitable for use in filesys...
def get_rels_ext_properties(pid): rels_ext_properties = dict() url = args.host.rstrip('/') + '/islandora/object/' + pid + '/datastream/RELS-EXT/view' request_url = urllib.request.urlopen(url) rels_ext_xml = request_url.read().decode('utf-8').strip() rels_ext_properties['PID'] = pid # <fedora:...
return pid.replace(':', '__')
identifier_body
islandora_bulk_downloader.py
#!/usr/bin/env python3 import sys import os import csv import re import logging import argparse import urllib.request import requests from PIL import Image from PyPDF2 import PdfFileMerger from shutil import rmtree, copytree # Functions def pid_to_path(pid): # Converts PID into a string suitable for use in filesys...
isSequenceNumberOfs = re.findall('>.*<', isSequenceNumberOf) isSequenceNumberOf = isSequenceNumberOfs[0].lstrip('>') isSequenceNumberOf = isSequenceNumberOf.rstrip('<') rels_ext_properties['isSequenceNumberOf'] = isSequenceNumberOf else: rels_ext_properties['isSequenceNumberO...
isSequenceNumberOfs = re.findall('<islandora:isSequenceNumberOf.*>.*<', rels_ext_xml) if len(isSequenceNumberOfs) > 0: # Assumes that the object has only one parent. isSequenceNumberOf = isSequenceNumberOfs[0].replace('<.*', '')
random_line_split
islandora_bulk_downloader.py
#!/usr/bin/env python3 import sys import os import csv import re import logging import argparse import urllib.request import requests from PIL import Image from PyPDF2 import PdfFileMerger from shutil import rmtree, copytree # Functions def
(pid): # Converts PID into a string suitable for use in filesystem paths. # Uses __ in case some PIDs contain a single _. return pid.replace(':', '__') def get_rels_ext_properties(pid): rels_ext_properties = dict() url = args.host.rstrip('/') + '/islandora/object/' + pid + '/datastream/RELS-EXT/vie...
pid_to_path
identifier_name
islandora_bulk_downloader.py
#!/usr/bin/env python3 import sys import os import csv import re import logging import argparse import urllib.request import requests from PIL import Image from PyPDF2 import PdfFileMerger from shutil import rmtree, copytree # Functions def pid_to_path(pid): # Converts PID into a string suitable for use in filesys...
else: rels_ext_properties['isMemberOfCollection'] = None # Newspaper issues use isMemberOf in relationship to their newspaper and isSequenceNumber to sequence within that newspaper. # <fedora:isMemberOf rdf:resource="info:fedora/ctimes:1"/> # <islandora:isSequenceNumber>16219</islandora:isSequ...
isMemberOfCollection = isMemberOfCollections[0].replace('fedora:isMemberOfCollection rdf:resource="info:fedora/', '') isMemberOfCollection = isMemberOfCollection.strip('"') rels_ext_properties['isMemberOfCollection'] = isMemberOfCollection
conditional_block
route_planner.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{ future_help::{Observer, PollMutex}, labels::{NodeId, NodeLinkId}, link::LinkStatus, router::Router, }; use anyhow::{bail, form...
} Ok::<_, Error>(()) }, async move { while let Some(status) = local_updates.next().await { let mut node_table = local_node_table.lock().await; let root_node = node_table.root_node; if let Err(e) = node_table.update_link...
{ log::warn!("Update remote links from {:?} failed: {:?}", from_node_id, e); continue; }
conditional_block
route_planner.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{ future_help::{Observer, PollMutex}, labels::{NodeId, NodeLinkId}, link::LinkStatus, router::Router, }; use anyhow::{bail, form...
async move { while let Some(status) = local_updates.next().await { let mut node_table = local_node_table.lock().await; let root_node = node_table.root_node; if let Err(e) = node_table.update_links(root_node, status) { log::warn!("Up...
} Ok::<_, Error>(()) },
random_line_split
route_planner.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{ future_help::{Observer, PollMutex}, labels::{NodeId, NodeLinkId}, link::LinkStatus, router::Router, }; use anyhow::{bail, form...
fn update_links(&mut self, from: NodeId, links: Vec<LinkStatus>) -> Result<(), Error> { self.get_or_create_node_mut(from).links.clear(); for LinkStatus { to, local_id, round_trip_time } in links.into_iter() { self.update_link(from, to, local_id, LinkDescription { round_trip_time })?; ...
{ log::trace!( "{:?} update_link: from:{:?} to:{:?} link_id:{:?} desc:{:?}", self.root_node, from, to, link_id, desc ); if from == to { bail!("Circular link seen"); } self.get_or_create_node_mut(t...
identifier_body
route_planner.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{ future_help::{Observer, PollMutex}, labels::{NodeId, NodeLinkId}, link::LinkStatus, router::Router, }; use anyhow::{bail, form...
( &mut self, from: NodeId, to: NodeId, link_id: NodeLinkId, desc: LinkDescription, ) -> Result<(), Error> { log::trace!( "{:?} update_link: from:{:?} to:{:?} link_id:{:?} desc:{:?}", self.root_node, from, to, ...
update_link
identifier_name
flappy_bird.js
// get canvas const canvas = document.getElementById('canvas'); // get context 2d const ctx = canvas.getContext('2d'); // load sprite.png const sprite = new Image(); sprite.src = 'image.png'; // we need to keep track of the number of frames let frames = 0; // to rotate the bird, the ctx.rotation requires radians. So...
() { update(); draw(); frames++; } setInterval(loop, 12);
loop
identifier_name
flappy_bird.js
// get canvas const canvas = document.getElementById('canvas'); // get context 2d const ctx = canvas.getContext('2d'); // load sprite.png const sprite = new Image(); sprite.src = 'image.png'; // we need to keep track of the number of frames let frames = 0; // to rotate the bird, the ctx.rotation requires radians. So...
this.rotation = toRadian(-20); } } }, draw() { let birdImg = this.animation[this.frame]; // rotate the bird ctx.save(); ctx.translate(this.x, this.y); ctx.rotate(this.rotation); // coordinates center in bird image rather than up-left corner ctx.drawImage(sprite, birdI...
random_line_split
flappy_bird.js
// get canvas const canvas = document.getElementById('canvas'); // get context 2d const ctx = canvas.getContext('2d'); // load sprite.png const sprite = new Image(); sprite.src = 'image.png'; // we need to keep track of the number of frames let frames = 0; // to rotate the bird, the ctx.rotation requires radians. So...
} // draw game over Image const gameOver = { sX: 175, sY: 228, w: 225, h: 202, x: canvas.width / 2 - 225 / 2, y: 100, draw() { if (gameState.current === gameState.gameOver) { ctx.drawImage(sprite, this.sX, this.sY, this.w, this.h, this.x, this.y, this.w, this.h); } } } // draw score co...
{ if (gameState.current === gameState.getReady) { ctx.drawImage(sprite, this.sX, this.sY, this.w, this.h, this.x, this.y, this.w, this.h); } }
identifier_body
lib.rs
mod data; mod nn; use std::mem; use std::slice; //use std::os::raw::{/*c_double, c_int, */c_void}; // for js functions imports use once_cell::sync::Lazy; use std::sync::Mutex; // for lazy_static // for global variables use ndarray::prelude::*; use ndarray::{array, Array, Array1, Array3, Axis, Zip}; use data::Data...
}); } #[cfg(test)] mod kernel_test { use super::*; static POINT_DRAW_TIMES: Lazy<Mutex<u32>> = Lazy::new(|| Mutex::new(0)); // Override the extern functions #[no_mangle] extern "C" fn draw_point(_: u32, _: u32, _: f32) { *POINT_DRAW_TIMES.lock().unwrap() += 1; } use std:...
{ // floor let x = x as u32; let y = y as u32; let label_ratio = label as f32 / num_classes; unsafe { draw_point(x, y, label_ratio); } }
conditional_block
lib.rs
mod data; mod nn; use std::mem; use std::slice; //use std::os::raw::{/*c_double, c_int, */c_void}; // for js functions imports use once_cell::sync::Lazy; use std::sync::Mutex; // for lazy_static // for global variables use ndarray::prelude::*; use ndarray::{array, Array, Array1, Array3, Axis, Zip}; use data::Data...
const DATA_GEN_RADIUS: f32 = 1f32; const SPIN_SPAN: f32 = PI; const NUM_CLASSES: u32 = 3; const DATA_NUM: u32 = 300; const FC_SIZE: u32 = 100; const REGULAR_RATE: f32 = 0.001f32; const DESCENT_RATE: f32 = 1f32; const DATA_GEN_RAND_MAX: f32 = 0.25f32; const NETWORK_GEN_RAND_MAX: f32 ...
*POINT_DRAW_TIMES.lock().unwrap() += 1; } use std::f32::consts::PI; // for math functions
random_line_split
lib.rs
mod data; mod nn; use std::mem; use std::slice; //use std::os::raw::{/*c_double, c_int, */c_void}; // for js functions imports use once_cell::sync::Lazy; use std::sync::Mutex; // for lazy_static // for global variables use ndarray::prelude::*; use ndarray::{array, Array, Array1, Array3, Axis, Zip}; use data::Data...
#[test] fn test_buffer_allocation() { let buffer = alloc(114514); free(buffer, 114514); } #[test] fn test_draw_prediction() { init( DATA_GEN_RADIUS, SPIN_SPAN, DATA_NUM, NUM_CLASSES, DATA_GEN_RAND_MAX, ...
{ init( DATA_GEN_RADIUS, SPIN_SPAN, DATA_NUM, NUM_CLASSES, DATA_GEN_RAND_MAX, NETWORK_GEN_RAND_MAX, FC_SIZE, DESCENT_RATE, REGULAR_RATE, ); let loss_before: f32 = train(); for _ in...
identifier_body
lib.rs
mod data; mod nn; use std::mem; use std::slice; //use std::os::raw::{/*c_double, c_int, */c_void}; // for js functions imports use once_cell::sync::Lazy; use std::sync::Mutex; // for lazy_static // for global variables use ndarray::prelude::*; use ndarray::{array, Array, Array1, Array3, Axis, Zip}; use data::Data...
{ fc_size: u32, num_classes: u32, descent_rate: f32, regular_rate: f32, } #[derive(Default)] struct CriticalSection(MetaData, Data, Network); // Imported js functions extern "C" { // for debug fn log_u64(num: u32); // for data pointer draw // x,y: the offset from upper left corner ...
MetaData
identifier_name
common.js
/* 本地存储 userInfo openid userType teacherStatusInfo */ const myHttps = "wj.1-zhao.com"; const host = `https://${myHttps}`; const webStock = `wss://${myHttps}/WebSocketServer.ashx`; const QQMapWX = require('./qqmap-wx-jssdk.min.js'); const mapKey = new QQMapWX({ key: '4WABZ-V2ARX-NLS45-T5Q7T-CETWK-KMB7C' // 必填 }); c...
, method: 'POST', success: (res) => { if (res.data.res) { callback(); } } }); }, //学生注册 studentRegister() { wx.request({ url: config.RisStudent, method: 'POST', data: { openId: wx.getStorageSync('openid') }, success: (res) =...
f (callback) === 'function' ? callback : function (res) { }; wx.setStorageSync('userInfo', userInfo); wx.request({ url: config.UpdateAvaUrlNick, data: { openId: wx.getStorageSync('openid'), avaUrl: userInfo.avatarUrl, nickName: userInfo.nickName, gender: userInfo.gend...
identifier_body
common.js
/* 本地存储 userInfo openid userType teacherStatusInfo */ const myHttps = "wj.1-zhao.com"; const host = `https://${myHttps}`; const webStock = `wss://${myHttps}/WebSocketServer.ashx`; const QQMapWX = require('./qqmap-wx-jssdk.min.js'); const mapKey = new QQMapWX({ key: '4WABZ-V2ARX-NLS45-T5Q7T-CETWK-KMB7C' // 必填 }); c...
wx.setStorageSync('userType', res.data.userType); callback(); } } }); } } }) }, //获取并更新用户头像等信息 getUserInfo(userInfo, callback) { callback = typeof (callback) === 'function' ? callback : function (res) { }; wx.setStorageS...
//保存用户类型 let userType = res.data.userType && res.data.userType;
random_line_split
common.js
/* 本地存储 userInfo openid userType teacherStatusInfo */ const myHttps = "wj.1-zhao.com"; const host = `https://${myHttps}`; const webStock = `wss://${myHttps}/WebSocketServer.ashx`; const QQMapWX = require('./qqmap-wx-jssdk.min.js'); const mapKey = new QQMapWX({ key: '4WABZ-V2ARX-NLS45-T5Q7T-CETWK-KMB7C' // 必填 }); c...
conditional_block
common.js
/* 本地存储 userInfo openid userType teacherStatusInfo */ const myHttps = "wj.1-zhao.com"; const host = `https://${myHttps}`; const webStock = `wss://${myHttps}/WebSocketServer.ashx`; const QQMapWX = require('./qqmap-wx-jssdk.min.js'); const mapKey = new QQMapWX({ key: '4WABZ-V2ARX-NLS45-T5Q7T-CETWK-KMB7C' // 必填 }); c...
identifier_name
cache.rs
use crate::clean::{self, GetDefId, AttributesExt}; use crate::fold::DocFolder; use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId}; use rustc::middle::privacy::AccessLevels; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use std::mem; use std::path::{Path, PathBuf}; use std::collections::BTreeMap; use sy...
fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> { clean_type.generics() .and_then(|types| { let r = types.iter() .filter_map(|t| get_index_type_name(t, false)) .map(|s| s.to_ascii_lowercase()) ...
{ match *clean_type { clean::ResolvedPath { ref path, .. } => { let segments = &path.segments; let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!( "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path", ...
identifier_body
cache.rs
use crate::clean::{self, GetDefId, AttributesExt}; use crate::fold::DocFolder; use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId}; use rustc::middle::privacy::AccessLevels; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use std::mem; use std::path::{Path, PathBuf}; use std::collections::BTreeMap; use sy...
cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module)); } // Cache where all known primitives have their documentation located. // // Favor linking to as local extern as possible, so iterate all crates in // reverse topological order. ...
let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u); cache.extern_locations.insert(n, (e.name.clone(), src_root, extern_location(e, extern_url, &dst))); let did = DefId { krate: n, index: CRATE_DEF_INDEX };
random_line_split
cache.rs
use crate::clean::{self, GetDefId, AttributesExt}; use crate::fold::DocFolder; use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId}; use rustc::middle::privacy::AccessLevels; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use std::mem; use std::path::{Path, PathBuf}; use std::collections::BTreeMap; use sy...
(krate: &clean::Crate, cache: &mut Cache) -> String { let mut nodeid_to_pathid = FxHashMap::default(); let mut crate_items = Vec::with_capacity(cache.search_index.len()); let mut crate_paths = Vec::<Json>::new(); let Cache { ref mut search_index, ref orphan_impl_items, r...
build_index
identifier_name
cache.rs
use crate::clean::{self, GetDefId, AttributesExt}; use crate::fold::DocFolder; use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId}; use rustc::middle::privacy::AccessLevels; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use std::mem; use std::path::{Path, PathBuf}; use std::collections::BTreeMap; use sy...
Remote(url) }).next().unwrap_or(Unknown) // Well, at least we tried. } /// Builds the search index from the collected metadata fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String { let mut nodeid_to_pathid = FxHashMap::default(); let mut crate_items = Vec::with_capacity(cache.search_...
{ url.push('/') }
conditional_block
l2fib_evpn_ipmac_info.pb.go
/* Copyright 2019 Cisco Systems 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 d...
var xxx_messageInfo_L2FibEvpnIpmacInfo_KEYS proto.InternalMessageInfo func (m *L2FibEvpnIpmacInfo_KEYS) GetNodeId() string { if m != nil { return m.NodeId } return "" } func (m *L2FibEvpnIpmacInfo_KEYS) GetBdid() uint32 { if m != nil { return m.Bdid } return 0 } func (m *L2FibEvpnIpmacInfo_KEYS) GetIpAdd...
{ xxx_messageInfo_L2FibEvpnIpmacInfo_KEYS.DiscardUnknown(m) }
identifier_body
l2fib_evpn_ipmac_info.pb.go
/* Copyright 2019 Cisco Systems 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 d...
return false } func (m *L2FibEvpnIpmacInfo) GetArpNdProbePending() bool { if m != nil { return m.ArpNdProbePending } return false } func (m *L2FibEvpnIpmacInfo) GetArpNdDeletePending() bool { if m != nil { return m.ArpNdDeletePending } return false } func (m *L2FibEvpnIpmacInfo) GetIsLocalXr() bool { if ...
if m != nil { return m.ArpNdSyncPending }
random_line_split
l2fib_evpn_ipmac_info.pb.go
/* Copyright 2019 Cisco Systems 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 d...
return "" } func (m *L2FibEvpnIpmacInfo_KEYS) GetIsLocal() bool { if m != nil { return m.IsLocal } return false } func (m *L2FibEvpnIpmacInfo_KEYS) GetMacAddress() string { if m != nil { return m.MacAddress } return "" } type L2FibIpAddrT struct { AddrType string `protobuf:"bytes,1,opt,nam...
{ return m.IpAddress }
conditional_block
l2fib_evpn_ipmac_info.pb.go
/* Copyright 2019 Cisco Systems 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 d...
(src proto.Message) { xxx_messageInfo_L2FibEvpnIpmacInfo_KEYS.Merge(m, src) } func (m *L2FibEvpnIpmacInfo_KEYS) XXX_Size() int { return xxx_messageInfo_L2FibEvpnIpmacInfo_KEYS.Size(m) } func (m *L2FibEvpnIpmacInfo_KEYS) XXX_DiscardUnknown() { xxx_messageInfo_L2FibEvpnIpmacInfo_KEYS.DiscardUnknown(m) } var xxx_messa...
XXX_Merge
identifier_name
constants.rs
use lazy_static::lazy_static; use crate::options::ConfigColours; // Default widget ID pub const DEFAULT_WIDGET_ID: u64 = 56709; // How long to store data. pub const STALE_MAX_MILLISECONDS: u64 = 600 * 1000; // Keep 10 minutes of data. // How much data is SHOWN pub const DEFAULT_TIME_MILLISECONDS: u64 = 60 * 1000; /...
// rx_color: None, // tx_color: None, // rx_total_color: None, // tx_total_color: None, // border_color: None, // highlighted_border_color: None, // text_color: None, // selected_text_color: None, // selected_bg_color: None, // widget_title...
// all_cpu_color: None, // avg_cpu_color: None, // cpu_core_colors: None, // ram_color: None, // swap_color: None,
random_line_split
etcd.go
// // Go Config // Copyright (c) 2014 Brian W. Wolter, All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // ...
/** * Obtain the response */ func (e *etcdCacheEntry) Response() *etcdResponse { e.RLock() defer e.RUnlock() return e.response } /** * Set the response */ func (e *etcdCacheEntry) SetResponse(rsp *etcdResponse) { e.Lock() defer e.Unlock() e.response = rsp } /** * Add an observer for this entry and ...
{ return &etcdCacheEntry{key: key, response:rsp, observers: make([]etcdObserver, 0)} }
identifier_body
etcd.go
// // Go Config // Copyright (c) 2014 Brian W. Wolter, All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // ...
() { e.Lock() defer e.Unlock() e.observers = make([]etcdObserver, 0) } /** * Are we watching this entry */ func (e *etcdCacheEntry) IsWatching() bool { e.RLock() defer e.RUnlock() return e.watching } /** * Start watching this entry for updates if we aren't already */ func (e *etcdCacheEntry) Watch(c *...
RemoveAllObservers
identifier_name
etcd.go
// // Go Config // Copyright (c) 2014 Brian W. Wolter, All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // ...
e.RLock() key := e.key rsp := e.response e.RUnlock() rsp, err = c.get(key, true, rsp) if err == io.EOF || err == io.ErrUnexpectedEOF { errcount = 0 continue }else if err != nil { errcount++ delay := backoff * time.Duration(errcount * errcount) if delay...
random_line_split
etcd.go
// // Go Config // Copyright (c) 2014 Brian W. Wolter, All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // ...
return path }
{ if i > 0 { path += "/" } path += url.QueryEscape(p) }
conditional_block
shell.rs
use crate::error_pages::ErrorPageData; use crate::errors::*; use crate::path_prefix::get_path_prefix_client; use crate::serve::PageData; use crate::template::Template; use crate::ClientTranslationsManager; use crate::ErrorPages; use fmterr::fmt_err; use js_sys::Reflect; use std::cell::RefCell; use std::collections::Has...
/// Gets the initial state injected by the server, if there was any. This is used to differentiate initial loads from subsequent ones, /// which have different log chains to prevent double-trips (a common SPA problem). pub fn get_initial_state() -> InitialState { let val_opt = web_sys::window().unwrap().get("__PE...
{ let val_opt = web_sys::window().unwrap().get("__PERSEUS_RENDER_CFG"); let js_obj = match val_opt { Some(js_obj) => js_obj, None => return None, }; // The object should only actually contain the string value that was injected let cfg_str = match js_obj.as_string() { Some(cfg...
identifier_body
shell.rs
use crate::error_pages::ErrorPageData; use crate::errors::*; use crate::path_prefix::get_path_prefix_client; use crate::serve::PageData; use crate::template::Template; use crate::ClientTranslationsManager; use crate::ErrorPages; use fmterr::fmt_err; use js_sys::Reflect; use std::cell::RefCell; use std::collections::Has...
() -> InitialState { let val_opt = web_sys::window().unwrap().get("__PERSEUS_INITIAL_STATE"); let js_obj = match val_opt { Some(js_obj) => js_obj, None => return InitialState::NotPresent, }; // The object should only actually contain the string value that was injected let state_str =...
get_initial_state
identifier_name
shell.rs
use crate::error_pages::ErrorPageData; use crate::errors::*; use crate::path_prefix::get_path_prefix_client; use crate::serve::PageData; use crate::template::Template; use crate::ClientTranslationsManager; use crate::ErrorPages; use fmterr::fmt_err; use js_sys::Reflect; use std::cell::RefCell; use std::collections::Has...
/// A representation of whether or not the initial state was present. If it was, it could be `None` (some templates take no state), and /// if not, then this isn't an initial load, and we need to request the page from the server. It could also be an error that the server /// has rendered. pub enum InitialState { //...
random_line_split
groups-edit.component.ts
import {Component, OnInit, ViewChild} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import {Subscription} from 'rxjs/Subscription'; import {GroupEditEntity, GroupEntity, GroupsHttpService} from '../groups-http.service'; import {GlobalService} from '../../../core/global.service'; import {RegionEntity...
identifier_name
groups-edit.component.ts
import {Component, OnInit, ViewChild} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import {Subscription} from 'rxjs/Subscription'; import {GroupEditEntity, GroupEntity, GroupsHttpService} from '../groups-http.service'; import {GlobalService} from '../../../core/global.service'; import {RegionEntity...
}) export class GroupsEditComponent implements OnInit, CanDeactivateComponent { public groupsInfo: GroupEntity = new GroupEntity(); public updateGroupInfo: GroupEditEntity = new GroupEditEntity(); public groupTypeList: Array<number> = [1, 2, 3, 4, 5, 0]; public regionsList: Array<RegionEntity> = []; publ...
providers: [ParkingsHttpService]
random_line_split
groups-edit.component.ts
import {Component, OnInit, ViewChild} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import {Subscription} from 'rxjs/Subscription'; import {GroupEditEntity, GroupEntity, GroupsHttpService} from '../groups-http.service'; import {GlobalService} from '../../../core/global.service'; import {RegionEntity...
identifier_body
groups-edit.component.ts
import {Component, OnInit, ViewChild} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import {Subscription} from 'rxjs/Subscription'; import {GroupEditEntity, GroupEntity, GroupsHttpService} from '../groups-http.service'; import {GlobalService} from '../../../core/global.service'; import {RegionEntity...
}); } } public onCancelBtnClick() { this.navigated(); } private navigated() { if (this.fromPath === 'detail') { this.router.navigate(['../../detail', this.group_id], {relativeTo: this.route}); } else { this.router.navigate(['../'], {relativeTo: this.route}); } } public can...
.parkingsList.push(new ParkingItem(parking));
conditional_block
review.go
/* Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
ct, err := r.Repo.GetCommitTime(commit) if err != nil { return false } lt, err := r.Repo.GetCommitTime(latestCommit) if err != nil { return true } return ct > lt } updateLatest := func(commit string) { if commit == "" { return } if isLater(commit) { latestCommit = commit } } for _...
{ return false }
conditional_block
review.go
/* Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
// Verify verifies the signature on a comment. func (thread *CommentThread) Verify() error { err := gpg.Verify(&thread.Comment) if err != nil { hash, _ := thread.Comment.Hash() return fmt.Errorf("verification of comment [%s] failed: %s", hash, err) } for _, child := range thread.Children { err = child.Verif...
{ resolved := updateThreadsStatus(thread.Children) if resolved == nil { thread.Resolved = thread.Comment.Resolved return } if !*resolved { thread.Resolved = resolved return } if thread.Comment.Resolved == nil || !*thread.Comment.Resolved { thread.Resolved = nil return } thread.Resolved = resolved...
identifier_body
review.go
/* Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
return } if thread.Comment.Resolved == nil || !*thread.Comment.Resolved { thread.Resolved = nil return } thread.Resolved = resolved } // Verify verifies the signature on a comment. func (thread *CommentThread) Verify() error { err := gpg.Verify(&thread.Comment) if err != nil { hash, _ := thread.Comment...
if !*resolved { thread.Resolved = resolved
random_line_split
review.go
/* Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
(startingCommit, latestCommit string, commentThreads []CommentThread) string { isLater := func(commit string) bool { if err := r.Repo.VerifyCommit(commit); err != nil { return false } if t, e := r.Repo.IsAncestor(latestCommit, commit); e == nil && t { return true } if t, e := r.Repo.IsAncestor(starting...
findLastCommit
identifier_name
lib.rs
//! An Entity Component System for game development. //! //! Currently used for personal use (for a roguelike game), this library is highly unstable, and a WIP. #![allow(dead_code)] #![feature(append,drain)] use std::iter; use std::collections::HashMap; use std::ops::{Index, IndexMut}; use std::collections::hash_map::...
(&mut self, ent: Entity) { self.clear_family_data_for(ent); self.components.remove(&ent); } fn remove_from_family(&mut self, family: &str, ent: Entity) { let mut idx: Option<usize> = None; { let vec = self.families.get_mut(family).expect("No such family"); ...
delete_component_data_for
identifier_name
lib.rs
//! An Entity Component System for game development. //! //! Currently used for personal use (for a roguelike game), this library is highly unstable, and a WIP. #![allow(dead_code)] #![feature(append,drain)] use std::iter; use std::collections::HashMap; use std::ops::{Index, IndexMut}; use std::collections::hash_map::...
// Give this EntityDataHolder a list of which families this entity has. self.data[self.ent].set_families(families); } } /* fn main() { println!("Hello, world!"); let mut manager = EntityManager::new(); let ent = manager.new_entity(); manager.add_component_to(ent, Position{x:1, y:2}); println!("p...
{ self.processor.add_processable(self.ent); }
conditional_block
lib.rs
//! An Entity Component System for game development. //! //! Currently used for personal use (for a roguelike game), this library is highly unstable, and a WIP. #![allow(dead_code)] #![feature(append,drain)] use std::iter; use std::collections::HashMap; use std::ops::{Index, IndexMut}; use std::collections::hash_map::...
if self.$access.has_it() { b.field(stringify!($access), &self.$access); } )+*/ b.finish() } } impl EntityDataHolder for $data { fn new() -> Self { $data::new_empty() ...
/*$(
random_line_split