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
sql_utils.rs
//! Module for SQL Utility functions use diesel::prelude::*; use std::{ borrow::Cow, fs::File, io::BufReader, path::Path, }; use crate::error::IOErrorToError; use super::archive::import::{ detect_archive_type, import_ytdlr_json_archive, ArchiveType, ImportProgress, }; /// All migrations from "libytdlr/migra...
(c: &RwLock<Vec<ImportProgress>>) -> impl FnMut(ImportProgress) + '_ { return |imp| c.write().expect("write failed").push(imp); } #[test] fn test_input_unknown_archive() { let string0 = " youtube ____________ youtube ------------ youtube aaaaaaaaaaaa soundcloud 0000000000 "; let (path, _...
callback_counter
identifier_name
__init__.py
import numpy as np, functools as ft, itertools as it, pandas import sys, cStringIO, contextlib import re from grading import * def filter_trial(frame, exp_id, trial_id=None): if trial_id is None: return frame[frame.exp_id == exp_id] else: return frame[(frame.exp_id == exp_id) & (frame.trial_id ...
return buffer @contextlib.contextmanager def stdoutIO(stdout=None): old = sys.stdout if stdout is None: stdout = cStringIO.StringIO() sys.stdout = stdout yield stdout sys.stdout = old def rolling_func(fixations, fun, window_size_ms, step_ms): start, end = 0, window_size_ms re...
chars = ([" "] * pad_left) + list(line) buffer[r, :len(chars)] = chars
conditional_block
__init__.py
import numpy as np, functools as ft, itertools as it, pandas import sys, cStringIO, contextlib import re from grading import * def filter_trial(frame, exp_id, trial_id=None): if trial_id is None: return frame[frame.exp_id == exp_id] else: return frame[(frame.exp_id == exp_id) & (frame.trial_id ...
(code_lines, indent_size=4): from pygments.lexers import PythonLexer indent_regex = re.compile(r"^\s*") lexer = PythonLexer() code_str = "".join(code_lines) all_tokens = list(lexer.get_tokens(code_str, unfiltered=True)) line_tokens = [] current_line = [] for t in all_tokens: if...
python_token_metrics
identifier_name
__init__.py
import numpy as np, functools as ft, itertools as it, pandas import sys, cStringIO, contextlib import re from grading import * def filter_trial(frame, exp_id, trial_id=None): if trial_id is None: return frame[frame.exp_id == exp_id] else: return frame[(frame.exp_id == exp_id) & (frame.trial_id ...
yield next(it, None) yield tuple(it) def just2(n, seq): """Iterates over a sequence, splitting each item into n, rest parts.""" for inner_seq in seq: yield tuple(just(n, inner_seq)) def significant(p_value): if p_value < 0.001: return "***" if p_value < 0.01: r...
"""Splits a sequence into n, rest parts.""" it = iter(seq) for _ in range(n - 1):
random_line_split
__init__.py
import numpy as np, functools as ft, itertools as it, pandas import sys, cStringIO, contextlib import re from grading import * def filter_trial(frame, exp_id, trial_id=None): if trial_id is None: return frame[frame.exp_id == exp_id] else: return frame[(frame.exp_id == exp_id) & (frame.trial_id ...
def window(seq, n): """Returns a sliding window (of width n) over data from the iterable s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...""" seq_it = iter(seq) result = tuple(it.islice(seq_it, n)) if len(result) == n: yield result for elem in seq_it: result = result[1:] + (elem,...
start, end = 0, window_size_ms return_series = False if not isinstance(fun, dict): fun = { "value" : fun } return_series = True values = { k : [] for k, v in fun.iteritems() } times = [] while start < fixations.end_ms.max(): times.append(start + (window_size_ms / 2)) ...
identifier_body
scheduler.rs
#![allow(unused)] mod run_queue; use std::alloc::Layout; use std::fmt::{self, Debug}; use std::mem; use std::ops::Deref; use std::ptr; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Weak}; use hashbrown::HashMap; use anyhow::anyhow; use lazy_static::lazy_static; use log::info; use liblumen_core...
#[export_name = "__lumen_builtin_yield"] pub unsafe extern "C" fn process_yield() -> bool { let s = <Scheduler as rt_core::Scheduler>::current(); // NOTE: We always set root=false here because the root // process never invokes this function s.process_yield(/* root= */ false) } #[naked] #[inline(never...
{ unimplemented!() }
identifier_body
scheduler.rs
#![allow(unused)] mod run_queue; use std::alloc::Layout; use std::fmt::{self, Debug}; use std::mem; use std::ops::Deref; use std::ptr; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Weak}; use hashbrown::HashMap; use anyhow::anyhow; use lazy_static::lazy_static; use log::info; use liblumen_core...
(&self, priority: Priority) -> usize { self.run_queues.read().run_queue_len(priority) } /// Returns true if the given process is in the current scheduler's run queue #[cfg(test)] pub fn is_run_queued(&self, value: &Arc<Process>) -> bool { self.run_queues.read().contains(value) } ...
run_queue_len
identifier_name
scheduler.rs
#![allow(unused)] mod run_queue; use std::alloc::Layout; use std::fmt::{self, Debug}; use std::mem; use std::ops::Deref; use std::ptr; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Weak}; use hashbrown::HashMap; use anyhow::anyhow; use lazy_static::lazy_static; use log::info; use liblumen_core...
Err(_) => { panic!("invalid term kind: {}", kind); } } ptr::null_mut() } /// Called when the current process has finished executing, and has /// returned all the way to its entry function. This marks the process /// as exiting (if it wasn't already), and then yields to the schedul...
{ unimplemented!("unhandled use of malloc for {:?}", tk); }
conditional_block
scheduler.rs
#![allow(unused)] mod run_queue; use std::alloc::Layout; use std::fmt::{self, Debug}; use std::mem; use std::ops::Deref; use std::ptr; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Weak}; use hashbrown::HashMap; use anyhow::anyhow; use lazy_static::lazy_static; use log::info; use liblumen_core...
pub enum Run { /// Run the process now Now(Arc<Process>), /// There was a process in the queue, but it needs to be delayed because it is `Priority::Low` /// and hadn't been delayed enough yet. Ask the `RunQueue` again for another process. /// -- https://github.com/erlang/otp/blob/fe2b1323a3866ed0a9...
} } /// What to run
random_line_split
client.go
/* Package synapse is a wrapper library for the Synapse API (https://docs.synapsefi.com) Instantiate client // credentials used to set headers for each method request var client = synapse.New( "CLIENT_ID", "CLIENT_SECRET", "IP_ADDRESS", "FINGERPRINT", ) # Examples Enable logging & turn off developer mode (de...
return c.do("GET", url, "", nil) } /********** OTHER **********/ // GetCryptoMarketData returns market data for cryptocurrencies func (c *Client) GetCryptoMarketData() (map[string]interface{}, error) { log.info("========== GET CRYPTO MARKET DATA ==========") url := buildURL(path["nodes"], "crypto-market-watch") ...
random_line_split
client.go
/* Package synapse is a wrapper library for the Synapse API (https://docs.synapsefi.com) Instantiate client // credentials used to set headers for each method request var client = synapse.New( "CLIENT_ID", "CLIENT_SECRET", "IP_ADDRESS", "FINGERPRINT", ) # Examples Enable logging & turn off developer mode (de...
qp := []string{"issue_public_key=YES&scope=" + defaultScope} if len(scope) > 1 { userId := scope[1] qp[0] += "&user_id=" + userId } return c.do("GET", url, "", qp) } /********** NODE **********/ // GetNodes returns all of the nodes func (c *Client) GetNodes(queryParams ...string) (map[string]interface{}, ...
{ defaultScope = scope[0] }
conditional_block
client.go
/* Package synapse is a wrapper library for the Synapse API (https://docs.synapsefi.com) Instantiate client // credentials used to set headers for each method request var client = synapse.New( "CLIENT_ID", "CLIENT_SECRET", "IP_ADDRESS", "FINGERPRINT", ) # Examples Enable logging & turn off developer mode (de...
(subscriptionID string, data string) (map[string]interface{}, error) { log.info("========== UPDATE SUBSCRIPTION ==========") url := buildURL(path["subscriptions"], subscriptionID) return c.do("PATCH", url, data, nil) } // GetWebhookLogs returns all of the webhooks sent to a specific client func (c *Client) GetWebh...
UpdateSubscription
identifier_name
client.go
/* Package synapse is a wrapper library for the Synapse API (https://docs.synapsefi.com) Instantiate client // credentials used to set headers for each method request var client = synapse.New( "CLIENT_ID", "CLIENT_SECRET", "IP_ADDRESS", "FINGERPRINT", ) # Examples Enable logging & turn off developer mode (de...
/********** SUBSCRIPTION **********/ // GetSubscriptions returns all of the nodes associated with a user func (c *Client) GetSubscriptions(queryParams ...string) (map[string]interface{}, error) { log.info("========== GET SUBSCRIPTIONS ==========") url := buildURL(path["subscriptions"]) return c.do("GET", url, ""...
{ log.info("========== VERIFY ROUTING NUMBER ==========") url := buildURL("routing-number-verification") return c.do("POST", url, data, nil) }
identifier_body
controller.go
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is d...
/* Copyright © 2020 Dell Inc. or its subsidiaries. All Rights Reserved.
random_line_split
controller.go
/* Copyright © 2020 Dell Inc. or its subsidiaries. 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 ...
func (nc *nodesMapping) getCSIBMNodeName(k8sNodeName string) (string, bool) { res, ok := nc.k8sToBMNode[k8sNodeName] return res, ok } func (nc *nodesMapping) put(k8sNodeName, bmNodeName string) { nc.k8sToBMNode[k8sNodeName] = bmNodeName nc.bmToK8sNode[bmNodeName] = k8sNodeName } // NewController returns instance...
res, ok := nc.bmToK8sNode[bmNodeName] return res, ok }
identifier_body
controller.go
/* Copyright © 2020 Dell Inc. or its subsidiaries. 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 ...
// check for OS labels name, version, err := util.GetOSNameAndVersion(k8sNode.Status.NodeInfo.OSImage) if err == nil { // os name if k8sNode.Labels[common.NodeOSNameLabelKey] != name { // not set or matches ll.Infof("Setting label %s=%s on node %s", common.NodeOSNameLabelKey, name, k8sNode.Name) k8sNode...
k8sNode.ObjectMeta.Labels = make(map[string]string, 1) }
conditional_block
controller.go
/* Copyright © 2020 Dell Inc. or its subsidiaries. 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 ...
k8sNode *coreV1.Node) string { if bmc.externalAnnotation { if val, ok := k8sNode.GetAnnotations()[bmc.annotationKey]; ok { return val } } return uuid.New().String() }
onstructNodeID(
identifier_name
svh_visitor.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
SawGenerics, SawFn, SawTraitItem, SawImplItem, SawStructField, SawVariant, SawPath, SawBlock, SawPat, SawLocal, SawArm, SawExpr(SawExprComponent<'a>), SawStmt(SawStmtComponent), } /// SawExprComponent carries all of the information that we want /// to include in the ...
SawTy,
random_line_split
svh_visitor.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
fn visit_path(&mut self, path: &'tcx Path, _: ast::NodeId) { debug!("visit_path: st={:?}", self.st); SawPath.hash(self.st); visit::walk_path(self, path) } fn visit_block(&mut self, b: &'tcx Block) { debug!("visit_block: st={:?}", self.st); SawBlock.hash(self.st); visit::wa...
{ debug!("visit_struct_field: st={:?}", self.st); SawStructField.hash(self.st); visit::walk_struct_field(self, s) }
identifier_body
svh_visitor.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&mut self, v: &'tcx Variant, g: &'tcx Generics, item_id: NodeId) { debug!("visit_variant: st={:?}", self.st); SawVariant.hash(self.st); // walk_variant does not call walk_generics, so do it here. visit::walk_generics(self, g); visit::walk_variant(self, v, g, item_id) } ...
visit_variant
identifier_name
config.rs
//! Configuration for the iroh CLI. use std::{ collections::HashMap, env, fmt, path::{Path, PathBuf}, str::FromStr, }; use anyhow::{anyhow, bail, Result}; use config::{Environment, File, Value}; use iroh_net::{ defaults::{default_eu_derp_region, default_na_derp_region}, derp::{DerpMap, DerpReg...
() -> Self { Self { // TODO(ramfox): this should probably just be a derp map derp_regions: [default_na_derp_region(), default_eu_derp_region()].into(), } } } impl Config { /// Make a config using a default, files, environment variables, and commandline flags. /// ...
default
identifier_name
config.rs
//! Configuration for the iroh CLI. use std::{ collections::HashMap, env, fmt, path::{Path, PathBuf}, str::FromStr, }; use anyhow::{anyhow, bail, Result}; use config::{Environment, File, Value}; use iroh_net::{ defaults::{default_eu_derp_region, default_na_derp_region}, derp::{DerpMap, DerpReg...
/// Get the path for this [`IrohPath`] by joining the name to a root directory. pub fn with_root(self, root: impl AsRef<Path>) -> PathBuf { let path = root.as_ref().join(self); path } } /// The configuration for the iroh cli. #[derive(PartialEq, Eq, Debug, Deserialize, Serialize, Clone)] ...
{ let mut root = iroh_data_root()?; if !root.is_absolute() { root = std::env::current_dir()?.join(root); } Ok(self.with_root(root)) }
identifier_body
config.rs
//! Configuration for the iroh CLI. use std::{ collections::HashMap, env, fmt, path::{Path, PathBuf}, str::FromStr, }; use anyhow::{anyhow, bail, Result}; use config::{Environment, File, Value}; use iroh_net::{ defaults::{default_eu_derp_region, default_na_derp_region}, derp::{DerpMap, DerpReg...
} } impl FromStr for IrohPaths { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self> { Ok(match s { "keypair" => Self::Keypair, "blobs.v0" => Self::BaoFlatStoreComplete, "blobs-partial.v0" => Self::BaoFlatStorePartial, _ => bail!("unknown fi...
IrohPaths::Keypair => "keypair", IrohPaths::BaoFlatStoreComplete => "blobs.v0", IrohPaths::BaoFlatStorePartial => "blobs-partial.v0", }
random_line_split
UAGS.py
 #random test for VS2010 import glob, platform from urllib.request import * import ssl import os from bs4 import BeautifulSoup from uags.UAGS_Functions import * from uags.UAGS_oagd import * class bc
HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def disable(self): self.HEADER = '' self.OKBLUE = '' self.OKGREEN = '' self.WARNING = '' ...
olors:
identifier_name
UAGS.py
 #random test for VS2010 import glob, platform from urllib.request import * import ssl import os from bs4 import BeautifulSoup from uags.UAGS_Functions import * from uags.UAGS_oagd import * class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = ...
## check XML validity if XML.find("?xml version=")<0 or XML.find("<gameList>")<0 or XML.find("</gameList>")<0: print (bcolors.FAIL + ">> XML File "+ bcolors.BOLD + XML_File + bcolors.ENDC + bcolors.FAIL + " is malformed." + bcolors.ENDC ) KillXML = input ("Delete file prior to restart? (y/n) "+ bcolors.ENDC )...
text_file = open(XML_File, "r") XML = text_file.read() text_file.close()
random_line_split
UAGS.py
 #random test for VS2010 import glob, platform from urllib.request import * import ssl import os from bs4 import BeautifulSoup from uags.UAGS_Functions import * from uags.UAGS_oagd import * class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = ...
print() ## all a filter to be used ScanFilter = input("Limit scanned files to a specific pattern match? " + bcolors.OKBLUE + "(Enter pattern or leave blank) " + bcolors.ENDC) print() ## check for overwrite of existing images NewImages = input("Overwrite existing images, such as in " + bcolors.BOLD + "boxarts...
wScrapes = "y" print("All found game entries will be scraped.")
conditional_block
UAGS.py
 #random test for VS2010 import glob, platform from urllib.request import * import ssl import os from bs4 import BeautifulSoup from uags.UAGS_Functions import * from uags.UAGS_oagd import * class bcolors: HE
## main section starting here... print() print(bcolors.BOLD + bcolors.OKBLUE + "HoraceAndTheSpider" + bcolors.ENDC + "'s " + "openretro.org " + bcolors.BOLD + "UAE4Arm Amiga Game Scraper" + bcolors.ENDC + " | " + "" + bcolors.FAIL + "www.ultimateamiga.co.uk" + bcolors.ENDC) print() ## check for overwrite of existing ...
ADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def disable(self): self.HEADER = '' self.OKBLUE = '' self.OKGREEN = '' self.WARNING = '' ...
identifier_body
databaseDemo.go
package main import ( "bufio" "database/sql" "fmt" _ "github.com/mattn/go-sqlite3" //import for side effects "log" "math/rand" "os" "strconv" "strings" ) func main() { myDatabase := OpenDataBase("./Demo.db") defer myDatabase.Close() create_tables(myDatabase) //addSampleStudents(myDatabase) //addCourses(...
(dbfile string) *sql.DB { database, err := sql.Open("sqlite3", dbfile) if err != nil { log.Fatal(err) } return database } func getMinGPA() float64 { fmt.Print("What is the minimum GPA for good standing:") reader := bufio.NewReader(os.Stdin) value, err := reader.ReadString('\n') if err != nil { log.Fatal("H...
OpenDataBase
identifier_name
databaseDemo.go
package main import ( "bufio" "database/sql" "fmt" _ "github.com/mattn/go-sqlite3" //import for side effects "log" "math/rand" "os" "strconv" "strings" ) func main() { myDatabase := OpenDataBase("./Demo.db") defer myDatabase.Close() create_tables(myDatabase) //addSampleStudents(myDatabase) //addCourses(...
} } func registerForClasses(database *sql.DB) { insertStatement := "INSERT INTO CLASS_LIST (banner_id, course_prefix, course_number, registration_date)" + "VALUES(?, 'Comp', 510, DATE('now'))" preppedStatement, err := database.Prepare(insertStatement) if err != nil { log.Fatal("Hey prof you goofed it trying t...
log.Fatal(err) } fmt.Printf("%s %s is on probation with a GPA of %f\n", firstName, lastName, gpa)
random_line_split
databaseDemo.go
package main import ( "bufio" "database/sql" "fmt" _ "github.com/mattn/go-sqlite3" //import for side effects "log" "math/rand" "os" "strconv" "strings" ) func main() { myDatabase := OpenDataBase("./Demo.db") defer myDatabase.Close() create_tables(myDatabase) //addSampleStudents(myDatabase) //addCourses(...
atabase *sql.DB) { sampleNames := map[string]string{"John": "Santore", "Enping": "Li", "Michael": "Black", "Seikyung": "Jung", "Haleh": "Khojasteh", "Abdul": "Sattar", "Paul": "Kim", "Yiheng": "Liang"} statement := "INSERT INTO STUDENTS (banner_id, first_name, last_name, gpa, credits)" + " VALUES (?, ?, ?, ?, ?)...
{ var sampleData = map[string]string{ "comp502": "Research\n(3 credits)\nPrerequisite: Consent of the department; formal application required\nOriginal research is undertaken by the graduate student in their field. This course culminates in a capstone project. For details, consult the paragraph titled “Directed or I...
identifier_body
databaseDemo.go
package main import ( "bufio" "database/sql" "fmt" _ "github.com/mattn/go-sqlite3" //import for side effects "log" "math/rand" "os" "strconv" "strings" ) func main() { myDatabase := OpenDataBase("./Demo.db") defer myDatabase.Close() create_tables(myDatabase) //addSampleStudents(myDatabase) //addCourses(...
s(database *sql.DB) { sampleNames := map[string]string{"John": "Santore", "Enping": "Li", "Michael": "Black", "Seikyung": "Jung", "Haleh": "Khojasteh", "Abdul": "Sattar", "Paul": "Kim", "Yiheng": "Liang"} statement := "INSERT INTO STUDENTS (banner_id, first_name, last_name, gpa, credits)" + " VALUES (?, ?, ?, ?,...
numVal := course[4:7] courseNum, err := strconv.Atoi(numVal) if err != nil { log.Fatal("ooops we must have mistyped", err) } preppedStatement.Exec(prefix, courseNum, desc) } } func addSampleStudent
conditional_block
utils.rs
// Copyright (c) 2011 Jan Kokemüller // Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wit...
>( &self, channel: usize, iter: impl Iterator<Item = U>, mut func: impl FnMut(&'a S, U), ) { assert!(channel < self.channels); for (v, u) in Iterator::zip(self.data.chunks_exact(self.channels), iter) { func(&v[channel], u) } } #[inline] ...
reach_sample_zipped<U
identifier_name
utils.rs
// Copyright (c) 2011 Jan Kokemüller // Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wit...
const MAX_AMPLITUDE: f64 = -(Self::MIN as f64); #[inline(always)] fn as_f64_raw(self) -> f64 { self as f64 } } impl Sample for i32 { const MAX_AMPLITUDE: f64 = -(Self::MIN as f64); #[inline(always)] fn as_f64_raw(self) -> f64 { self as f64 } } /// An extension-trait to...
} } impl Sample for i16 {
random_line_split
utils.rs
// Copyright (c) 2011 Jan Kokemüller // Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wit...
impl Sample for i16 { const MAX_AMPLITUDE: f64 = -(Self::MIN as f64); #[inline(always)] fn as_f64_raw(self) -> f64 { self as f64 } } impl Sample for i32 { const MAX_AMPLITUDE: f64 = -(Self::MIN as f64); #[inline(always)] fn as_f64_raw(self) -> f64 { self as f64 } } //...
self } }
identifier_body
narwhal.js
console.log('Narwhal scripts'); (function ($) { 'use strict'; // // Helpers // const ifExistsDo = ($item, action) => { if ($item.length) action($item) } const loadStyle = (url) => (new Promise((resolve, reject) => { const $style = $('<link rel="stylesheet">') ...
: '' const $createOverviewItem = ($artifact, $configuration, alias) => $('<div class="n-overview-item"></div>') .append($createAlias(alias)) .append($createArtifact($artifact)) .append($createConfiguration($configur...
const $createConfiguration = ($configuration) => $configuration ? $('<h5></h5>') .append($configuration.clone().find('td:nth-child(2)')) .css({ fontSize: 11 })
random_line_split
narwhal.js
console.log('Narwhal scripts'); (function ($) { 'use strict'; // // Helpers // const ifExistsDo = ($item, action) => { if ($item.length) action($item) } const loadStyle = (url) => (new Promise((resolve, reject) => { const $style = $('<link rel="stylesheet">') ...
}) .then(() => loadScriptAndWait('https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.44.0/mode/jinja2/jinja2.min.js', 300)) .then(() => loadScriptAndWait('https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.44.0/mode/yaml/yaml.min.js', 300)) .then(() => ...
{ throw Error('CodeMirror was not loaded correctly ...') }
conditional_block
mul_fixed.rs
use super::{ add, add_incomplete, EccBaseFieldElemFixed, EccScalarFixed, EccScalarFixedShort, FixedPoint, NonIdentityEccPoint, FIXED_BASE_WINDOW_SIZE, H, }; use crate::utilities::decompose_running_sum::RunningSumConfig; use std::marker::PhantomData; use group::{ ff::{Field, PrimeField, PrimeFieldBits}, ...
config.running_sum_coords_gate(meta); config } /// Check that each window in the running sum decomposition uses the correct y_p /// and interpolated x_p. /// /// This gate is used both in the mul_fixed::base_field_elem and mul_fixed::short /// helpers, which decompose the scala...
}
random_line_split
mul_fixed.rs
use super::{ add, add_incomplete, EccBaseFieldElemFixed, EccScalarFixed, EccScalarFixedShort, FixedPoint, NonIdentityEccPoint, FIXED_BASE_WINDOW_SIZE, H, }; use crate::utilities::decompose_running_sum::RunningSumConfig; use std::marker::PhantomData; use group::{ ff::{Field, PrimeField, PrimeFieldBits}, ...
pl From<&EccScalarFixedShort> for ScalarFixed { fn from(scalar_fixed: &EccScalarFixedShort) -> Self { Self::Short(scalar_fixed.clone()) } } impl From<&EccBaseFieldElemFixed> for ScalarFixed { fn from(base_field_elem: &EccBaseFieldElemFixed) -> Self { Self::BaseFieldElem(base_field_elem.clon...
Self::FullWidth(scalar_fixed.clone()) } } im
identifier_body
mul_fixed.rs
use super::{ add, add_incomplete, EccBaseFieldElemFixed, EccScalarFixed, EccScalarFixedShort, FixedPoint, NonIdentityEccPoint, FIXED_BASE_WINDOW_SIZE, H, }; use crate::utilities::decompose_running_sum::RunningSumConfig; use std::marker::PhantomData; use group::{ ff::{Field, PrimeField, PrimeFieldBits}, ...
) -> Vec<Value<pallas::Scalar>> { let running_sum_to_windows = |zs: Vec<AssignedCell<pallas::Base, pallas::Base>>| { (0..(zs.len() - 1)) .map(|idx| { let z_cur = zs[idx].value(); let z_next = zs[idx + 1].value(); let word = ...
s_field(&self
identifier_name
RhinoResponse.ts
import { HTTPServer, Cookies, Path } from "../deps.ts"; import { HeaderField, MIMEType, StatusCode, StatusCodeName, ExtMIMEType } from "../mod.ts"; import { Utils } from "../utils.ts"; // Derives the optional values of a cookie export type CookieOptions = Omit<Omit<Cookies.Cookie, "name">, "value">; export class
{ private _headersSent: boolean = false; private STATUS: number = 200; private COOKIES: HTTPServer.Response = {}; private readonly RESPONSE_HEADERS = new Headers(); constructor(private readonly HTTP_REQUEST: HTTPServer.ServerRequest) {} /** * Appends a value to an already existing HTTP ...
RhinoResponse
identifier_name
RhinoResponse.ts
import { HTTPServer, Cookies, Path } from "../deps.ts"; import { HeaderField, MIMEType, StatusCode, StatusCodeName, ExtMIMEType } from "../mod.ts"; import { Utils } from "../utils.ts"; // Derives the optional values of a cookie export type CookieOptions = Omit<Omit<Cookies.Cookie, "name">, "value">; export class Rhin...
* * Clears a cookie from the response by setting * its expiration date to a date before now. * @param name The name of the cookie */ public clearCookie(name: string) { // Sets the cookie to be appended to the response Cookies.delCookie(this.COOKIES, name); } /** * S...
const _filename = filename ? `filename=${filename};` : ""; this.setHeader(HeaderField.ContentDisposition, `attachment; ${_filename}`); const ext = Path.extname(filename || ""); this.contentType(ext); return this; } /*
identifier_body
RhinoResponse.ts
import { HTTPServer, Cookies, Path } from "../deps.ts"; import { HeaderField, MIMEType, StatusCode, StatusCodeName, ExtMIMEType } from "../mod.ts"; import { Utils } from "../utils.ts"; // Derives the optional values of a cookie export type CookieOptions = Omit<Omit<Cookies.Cookie, "name">, "value">; export class Rhin...
return this; } /** * Sets the status code for the response sent to the client * Visit https://www.restapitutorial.com/httpstatuscodes.html for * more information on what each status code means. * @param code The status code */ public status(code: StatusCode): RhinoResponse { ...
// Otherwise, just adds the value to the header this.RESPONSE_HEADERS.set(field, value); }
conditional_block
RhinoResponse.ts
import { HTTPServer, Cookies, Path } from "../deps.ts"; import { HeaderField, MIMEType, StatusCode, StatusCodeName, ExtMIMEType } from "../mod.ts"; import { Utils } from "../utils.ts";
// Derives the optional values of a cookie export type CookieOptions = Omit<Omit<Cookies.Cookie, "name">, "value">; export class RhinoResponse { private _headersSent: boolean = false; private STATUS: number = 200; private COOKIES: HTTPServer.Response = {}; private readonly RESPONSE_HEADERS = new Heade...
random_line_split
node.go
package tree import ( "database/sql/driver" "encoding/binary" "fmt" "math" "reflect" "strings" "time" "github.com/colinking/go-sqlite3-native/internal" "github.com/colinking/go-sqlite3-native/internal/pager" ) type node struct { pager *pager.Pager // the following fields are kept for debugging purposes: ...
(typ int) int { switch typ { case 0, 8, 9: return 0 case 1: return 1 case 2: return 2 case 3: return 3 case 4: return 4 case 5: return 6 case 6, 7: return 8 case 10, 11: // https://github.com/sqlite/sqlite/blob/96e3c39bd58ede59150c00e4f8609cbac674ffae/tool/offsets.c#L216 // return 0 panic(f...
columnContentSize
identifier_name
node.go
package tree import ( "database/sql/driver" "encoding/binary" "fmt" "math" "reflect" "strings" "time" "github.com/colinking/go-sqlite3-native/internal" "github.com/colinking/go-sqlite3-native/internal/pager" ) type node struct { pager *pager.Pager // the following fields are kept for debugging purposes: ...
// https://www.sqlite.org/fileformat2.html#serialtype func columnContentSize(typ int) int { switch typ { case 0, 8, 9: return 0 case 1: return 1 case 2: return 2 case 3: return 3 case 4: return 4 case 5: return 6 case 6, 7: return 8 case 10, 11: // https://github.com/sqlite/sqlite/blob/96e3c3...
{ // TODO: validate this works with negative integers (2's complement) switch c.typ { case 0: return nil case 1: return int64(c.content[0]) case 2: return int64(binary.BigEndian.Uint16(c.content)) case 3: // stdlib binary does not have a 24-bit option b := c.content u := uint32(b[2]) | uint32(b[1])<<...
identifier_body
node.go
package tree import ( "database/sql/driver" "encoding/binary" "fmt" "math" "reflect" "strings" "time" "github.com/colinking/go-sqlite3-native/internal" "github.com/colinking/go-sqlite3-native/internal/pager" ) type node struct { pager *pager.Pager // the following fields are kept for debugging purposes: ...
func (c Column) AsInt() (int, bool) { // [1, 6] are the various int64 types if c.typ >= 1 && c.typ <= 6 { i64 := c.Value().(int64) return int(i64), true } return 0, false } func (c Column) Value() driver.Value { // TODO: validate this works with negative integers (2's complement) switch c.typ { case 0: ...
random_line_split
node.go
package tree import ( "database/sql/driver" "encoding/binary" "fmt" "math" "reflect" "strings" "time" "github.com/colinking/go-sqlite3-native/internal" "github.com/colinking/go-sqlite3-native/internal/pager" ) type node struct { pager *pager.Pager // the following fields are kept for debugging purposes: ...
if typ != TreeTypeTableLeaf { // Extract the rowid from the last column: idx := len(columns) - 1 var ok bool rowid, ok = columns[idx].AsInt() if !ok { return nil, fmt.Errorf("expected final index column to be rowid: %+v", columns[idx]) } // Trim the rowid column off: columns =...
{ return nil, err }
conditional_block
terminal.rs
//! Provides a low-level terminal interface use std::io; use std::time::Duration; use mortal::{self, PrepareConfig, PrepareState, TerminalReadGuard, TerminalWriteGuard}; use crate::sys; pub use mortal::{CursorMode, Signal, SignalSet, Size}; /// Default `Terminal` interface pub struct DefaultTerminal(mortal::Termina...
(&mut self) -> io::Result<()> { self.move_to_first_column() } fn set_cursor_mode(&mut self, mode: CursorMode) -> io::Result<()> { self.set_cursor_mode(mode) } fn write(&mut self, s: &str) -> io::Result<()> { self.write_str(s) } fn flush(&mut self) -> io::Result<()> { ...
move_to_first_column
identifier_name
terminal.rs
//! Provides a low-level terminal interface use std::io; use std::time::Duration; use mortal::{self, PrepareConfig, PrepareState, TerminalReadGuard, TerminalWriteGuard}; use crate::sys; pub use mortal::{CursorMode, Signal, SignalSet, Size}; /// Default `Terminal` interface pub struct DefaultTerminal(mortal::Termina...
fn move_left(&mut self, n: usize) -> io::Result<()> { self.move_left(n) } fn move_right(&mut self, n: usize) -> io::Result<()> { self.move_right(n) } fn move_to_first_column(&mut self) -> io::Result<()> { self.move_to_first_column() } fn set_cursor_mode(&mut self, ...
{ self.move_down(n) }
identifier_body
terminal.rs
//! Provides a low-level terminal interface use std::io; use std::time::Duration; use mortal::{self, PrepareConfig, PrepareState, TerminalReadGuard, TerminalWriteGuard}; use crate::sys; pub use mortal::{CursorMode, Signal, SignalSet, Size}; /// Default `Terminal` interface pub struct DefaultTerminal(mortal::Termina...
/// Flushes any currently buffered output data. /// /// `TerminalWriter` instances may not buffer data on all systems. /// /// Data must be flushed when the `TerminalWriter` instance is dropped. fn flush(&mut self) -> io::Result<()>; } impl DefaultTerminal { /// Opens access to the termina...
/// /// The terminal interface shall not automatically move the cursor to the next /// line when `write` causes a character to be written to the final column. fn write(&mut self, s: &str) -> io::Result<()>;
random_line_split
passThrough.go
// // Copyright 2019-2020 Nestybox, 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
cntr.SetData(path, resource, data) } cntr.Unlock() } else { data, err = h.fetchFile(n, process) if err != nil { return 0, err } } data += "\n" return copyResultBuffer(req.Data, []byte(data)) } func (h *PassThrough) Write( n domain.IOnodeIface, req *domain.HandlerRequest) (int, error) { var ...
{ cntr.Unlock() return 0, err }
conditional_block
passThrough.go
// // Copyright 2019-2020 Nestybox, 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
return 0, io.EOF } var ( data string ok bool err error ) path := n.Path() prs := h.Service.ProcessService() process := prs.ProcessCreate(req.Pid, req.Uid, req.Gid) cntr := req.Container // // Caching here improves performance by avoiding dispatching the nsenter agent. But // note that caching i...
if req.Offset > 0 {
random_line_split
passThrough.go
// // Copyright 2019-2020 Nestybox, 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
( n domain.IOnodeIface, req *domain.HandlerRequest) error { logrus.Debugf("Executing Open() for req-id: %#x, handler: %s, resource: %s", req.ID, h.Name, n.Name()) // Create nsenterEvent to initiate interaction with container namespaces. nss := h.Service.NSenterService() event := nss.NewEvent( req.Pid, &do...
Open
identifier_name
passThrough.go
// // Copyright 2019-2020 Nestybox, 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
func (h *PassThrough) GetEnabled() bool { return h.Enabled } func (h *PassThrough) SetEnabled(b bool) { h.Enabled = b } func (h *PassThrough) GetResourcesList() []string { var resources []string for resourceKey, resource := range h.EmuResourceMap { resource.Mutex.Lock() if !resource.Enabled { resource....
{ return h.Service }
identifier_body
utils.go
/* Copyright 2021 The Kubernetes Authors. 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, ...
// QuerySnapshotsUtil helps invoke CNS QuerySnapshot API. The method takes in a snapshotQueryFilter that represents // the criteria to retrieve the snapshots. The maxEntries represents the max number of results that the caller of this // method can handle. func QuerySnapshotsUtil(ctx context.Context, m cnsvolume.Mana...
{ log := logger.GetLogger(ctx) var queryAsyncNotSupported bool var queryResult *cnstypes.CnsQueryResult var err error if useQueryVolumeAsync { // AsyncQueryVolume feature switch is enabled. queryResult, err = m.QueryVolumeAsync(ctx, queryFilter, querySelection) if err != nil { if err.Error() == cnsvsphere...
identifier_body
utils.go
/* Copyright 2021 The Kubernetes Authors. 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, ...
(ctx context.Context, m cnsvolume.Manager, snapshotQueryFilter cnstypes.CnsSnapshotQueryFilter, maxEntries int64) ([]cnstypes.CnsSnapshotQueryResultEntry, string, error) { log := logger.GetLogger(ctx) var allQuerySnapshotResults []cnstypes.CnsSnapshotQueryResultEntry var snapshotQuerySpec cnstypes.CnsSnapshotQueryS...
QuerySnapshotsUtil
identifier_name
utils.go
/* Copyright 2021 The Kubernetes Authors. 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, ...
err := vc.Disconnect(ctx) if err != nil { log.Errorf("Error while disconnect vCenter client for host %s. Error: %+v", vc.Config.Host, err) continue } log.Infof("Disconnected vCenter client for host %s", vc.Config.Host) } log.Info("Successfully logged out vCenter sessions") }
if err != nil { continue } } log.Infof("Disconnecting vCenter client for host %s", vc.Config.Host)
random_line_split
utils.go
/* Copyright 2021 The Kubernetes Authors. 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, ...
else { batchSize = snapshotQueryFilter.Cursor.Limit } iteration := int64(1) for { if iteration > maxIteration { // Exceeds the max number of results that can be handled by callers. nextToken := strconv.FormatInt(snapshotQueryFilter.Cursor.Offset, 10) log.Infof("the number of results: %d approached max-...
{ // Setting the default limit(128) explicitly. snapshotQueryFilter = cnstypes.CnsSnapshotQueryFilter{ Cursor: &cnstypes.CnsCursor{ Offset: 0, Limit: DefaultQuerySnapshotLimit, }, } batchSize = DefaultQuerySnapshotLimit }
conditional_block
block.go
package rpc import ( "encoding/hex" "fmt" "net/http" "strconv" "time" "github.com/gorilla/mux" "github.com/orientwalt/htdf/client" "github.com/orientwalt/htdf/client/context" "github.com/orientwalt/htdf/codec" sdk "github.com/orientwalt/htdf/types" "github.com/orientwalt/htdf/types/rest" sdkRest "github.c...
func formatTxResult(cdc *codec.Codec, res *ctypes.ResultTx, resBlock *ctypes.ResultBlock) (sdk.TxResponse, error) { tx, err := parseTx(cdc, res.Tx) if err != nil { return sdk.TxResponse{}, err } return sdk.NewResponseResultTx(res, tx, resBlock.Block.Time.Format(time.RFC3339)), nil } // func GetTxFn(cdc *codec.C...
return tx, nil }
random_line_split
block.go
package rpc import ( "encoding/hex" "fmt" "net/http" "strconv" "time" "github.com/gorilla/mux" "github.com/orientwalt/htdf/client" "github.com/orientwalt/htdf/client/context" "github.com/orientwalt/htdf/codec" sdk "github.com/orientwalt/htdf/types" "github.com/orientwalt/htdf/types/rest" sdkRest "github.c...
// CMD func printBlock(cmd *cobra.Command, args []string) error { var height *int64 // optional height if len(args) > 0 { h, err := strconv.Atoi(args[0]) if err != nil { return err } if h > 0 { tmp := int64(h) height = &tmp } } output, err := getBlock(context.NewCLIContext(), height) if err...
{ node, err := cliCtx.GetNode() if err != nil { return -1, err } status, err := node.Status() if err != nil { return -1, err } height := status.SyncInfo.LatestBlockHeight return height, nil }
identifier_body
block.go
package rpc import ( "encoding/hex" "fmt" "net/http" "strconv" "time" "github.com/gorilla/mux" "github.com/orientwalt/htdf/client" "github.com/orientwalt/htdf/client/context" "github.com/orientwalt/htdf/codec" sdk "github.com/orientwalt/htdf/types" "github.com/orientwalt/htdf/types/rest" sdkRest "github.c...
(cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) height, err := strconv.ParseInt(vars["height"], 10, 64) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, "ERROR: Couldn't parse block height. Assumed format is '/block/...
BlockRequestHandlerFn
identifier_name
block.go
package rpc import ( "encoding/hex" "fmt" "net/http" "strconv" "time" "github.com/gorilla/mux" "github.com/orientwalt/htdf/client" "github.com/orientwalt/htdf/client/context" "github.com/orientwalt/htdf/codec" sdk "github.com/orientwalt/htdf/types" "github.com/orientwalt/htdf/types/rest" sdkRest "github.c...
default: fmt.Printf("unknown type: %+v\n", currTx) } } sdkRest.PostProcessResponse(w, cdc, &blockInfo, cliCtx.Indent) } } func parseTx(cdc *codec.Codec, txBytes []byte) (sdk.Tx, error) { var tx auth.StdTx err := cdc.UnmarshalBinaryLengthPrefixed(txBytes, &tx) if err != nil { return nil, err } ...
{ //fmt.Printf("msg|route=%s|type=%s\n", msg.Route(), msg.Type()) switch msg := msg.(type) { case htdfservice.MsgSend: displayTx.From = msg.From displayTx.To = msg.To displayTx.Hash = hex.EncodeToString(tx.Hash()) displayTx.Amount = unit_convert.DefaultCoinsToBigCoins(msg.Amount)...
conditional_block
benchmarking.py
""" This module performs benchmarking to compare the computational costs of generating predictions using the ligpy model, trained neural nets for the full set of outputs and collections of individual outputs, and the trained decision tree estimator. """ import sys sys.path.append('../../../ligpy/ligpy') import os impor...
def teardown_predict_ligpy(): """ Clean up after running predict_ligpy(). Parameters ---------- None Returns ------- None """ call('rm -rf bsub.c bsub.o ddat.in fort.11 f.out greg10.in jacobian.c ' 'jacobian.o model.c model.o net_rates.def parest rates.def ' ...
""" Create the proper environment to run predict_ligpy() and set up the kinetic model. Parameters ---------- standard arguments passed to `ligpy.py` Returns ------- standard arguments for `ddasac.run_ddasac()` """ call('cp ligpy_benchmarking_files/sa_compositionlist.dat ' ...
identifier_body
benchmarking.py
""" This module performs benchmarking to compare the computational costs of generating predictions using the ligpy model, trained neural nets for the full set of outputs and collections of individual outputs, and the trained decision tree estimator. """ import sys sys.path.append('../../../ligpy/ligpy') import os impor...
return y_scaler.inverse_transform(predicted) def predict_decision_tree(input_data=rand_input, tree=dtr_full): """ Predict the output measures using a decision tree trained on all 30 output measures at once. Parameters ---------- input_data : numpy.ndarray, optional an...
predicted[:, i] = nets[i].predict(input_data).ravel()
conditional_block
benchmarking.py
""" This module performs benchmarking to compare the computational costs of generating predictions using the ligpy model, trained neural nets for the full set of outputs and collections of individual outputs, and the trained decision tree estimator. """ import sys sys.path.append('../../../ligpy/ligpy') import os impor...
(): """ Clean up after running predict_ligpy(). Parameters ---------- None Returns ------- None """ call('rm -rf bsub.c bsub.o ddat.in fort.11 f.out greg10.in jacobian.c ' 'jacobian.o model.c model.o net_rates.def parest rates.def ' 'results_dir/', shell=True)...
teardown_predict_ligpy
identifier_name
benchmarking.py
""" This module performs benchmarking to compare the computational costs of generating predictions using the ligpy model, trained neural nets for the full set of outputs and collections of individual outputs, and the trained decision tree estimator. """ import sys sys.path.append('../../../ligpy/ligpy') import os impor...
relative_tolerance = float(1e-8) # These are the files and paths that will be referenced in this program: (file_completereactionlist, file_completerateconstantlist, file_compositionlist) = utils.set_paths() working_directory = 'results_dir' if not os.path.exists(working_directory): os....
'../../../ligpy/ligpy/data/compositionlist.dat;', shell=True ) absolute_tolerance = float(1e-10)
random_line_split
main.py
import time # import math import gym # from gym import spaces, logger # from gym.utils import seeding from gym.envs.classic_control import rendering import random import math import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as T import numpy...
(self) -> Node: delta = self.on_track.get_delta() progress = self.dist_on_track / self.on_track.track_length x = self.on_track.begins_at.x + progress * delta.x y = self.on_track.begins_at.y + progress * delta.y return Node(x=x, y=y) def curr_station(self): stations...
pos
identifier_name
main.py
import time # import math import gym # from gym import spaces, logger # from gym.utils import seeding from gym.envs.classic_control import rendering import random import math import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as T import numpy...
# At this point we have run the policy for 10 episodes, and we are # ready for a policy update using the algorithm described earlier. all_rewards_normalized = discount_and_normalize_rewards(all_rewards, DISCOUNT_RATE) feed_dict = {} for idx, grad_and_var in enumerate(car_a['Gra...
print(f" game: {game}") curr_rewards = [] # all raw rewards from the current episode curr_gradients = [] # all gradients from the current episode world.reset() # world.render() # time.sleep(1 / RENDER_FPS) for step in range(N_MAX_STEPS): ...
conditional_block
main.py
import time # import math import gym # from gym import spaces, logger # from gym.utils import seeding from gym.envs.classic_control import rendering import random import math import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as T import numpy...
return Node(x=delta_x, y=delta_y) def get_angle(self): delta_x = self.ends_at.x - self.begins_at.x delta_y = self.ends_at.y - self.begins_at.y # np.arctan(-1) / np.pi return np.arctan(delta_y / delta_x) def __repr__(self): return f'Track: {self.begins_at} -> {s...
delta_y = self.ends_at.y - self.begins_at.y
random_line_split
main.py
import time # import math import gym # from gym import spaces, logger # from gym.utils import seeding from gym.envs.classic_control import rendering import random import math import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as T import numpy...
# Called with either one element to determine next action, or a batch # during optimization. Returns tensor([[left0exp,right0exp]...]). def forward(self, x): x = F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x))) return s...
super(DQN, self).__init__() self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2) self.bn1 = nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2) self.bn2 = nn.BatchNorm2d(32) self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2) self.bn3 = nn.Bat...
identifier_body
test_expand.rs
use super::utils::check; use hex_literal::hex; #[test] fn aes128_expand_key_test() { use super::aes128::expand_key; let keys = [0x00; 16]; check( unsafe { &expand_key(&keys) }, &[ [0x0000000000000000, 0x0000000000000000], [0x6263636362636363, 0x6263636362636363], ...
], ); let keys = hex!("6920e299a5202a6d656e636869746f2a"); check( unsafe { &expand_key(&keys) }, &[ [0x6920e299a5202a6d, 0x656e636869746f2a], [0xfa8807605fa82d0d, 0x3ac64e6553b2214f], [0xcf75838d90ddae80, 0xaa1be0e5f9a9c1aa], [0x180d2f...
random_line_split
test_expand.rs
use super::utils::check; use hex_literal::hex; #[test] fn aes128_expand_key_test() { use super::aes128::expand_key; let keys = [0x00; 16]; check( unsafe { &expand_key(&keys) }, &[ [0x0000000000000000, 0x0000000000000000], [0x6263636362636363, 0x6263636362636363], ...
#[test] fn aes256_expand_key_test() { use super::aes256::expand_key; let keys = [0x00; 32]; check( unsafe { &expand_key(&keys) }, &[ [0x0000000000000000, 0x0000000000000000], [0x0000000000000000, 0x0000000000000000], [0x6263636362636363, 0x6263636362636...
{ use super::aes192::expand_key; let keys = [0x00; 24]; check( unsafe { &expand_key(&keys) }, &[ [0x0000000000000000, 0x0000000000000000], [0x0000000000000000, 0x6263636362636363], [0x6263636362636363, 0x6263636362636363], [0x9b9898c9f9fbfbaa,...
identifier_body
test_expand.rs
use super::utils::check; use hex_literal::hex; #[test] fn aes128_expand_key_test() { use super::aes128::expand_key; let keys = [0x00; 16]; check( unsafe { &expand_key(&keys) }, &[ [0x0000000000000000, 0x0000000000000000], [0x6263636362636363, 0x6263636362636363], ...
() { use super::aes256::expand_key; let keys = [0x00; 32]; check( unsafe { &expand_key(&keys) }, &[ [0x0000000000000000, 0x0000000000000000], [0x0000000000000000, 0x0000000000000000], [0x6263636362636363, 0x6263636362636363], [0xaafbfbfbaafbfb...
aes256_expand_key_test
identifier_name
day11.rs
use std::{collections::HashSet, io::Write}; use itertools::Itertools; use snafu::Snafu; type Result<T> = std::result::Result<T, Error>; #[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone)] enum Item { Chip(char), Generator(char), ChipAndGenerator, } impl std::str::FromStr for Item { type Err = Er...
} impl std::fmt::Debug for Item { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Item::Chip(id) => write!(f, "{}M", id), Item::Generator(id) => write!(f, "{}G", id), Item::ChipAndGenerator => write!(f, "<>"), } } } #[deriv...
{ let s: Vec<char> = s.chars().collect(); if s.len() != 2 { return Err(Error::ParseItem { data: s[0].to_string(), }); } match s[1] { 'M' => Ok(Item::Chip(s[0])), 'G' => Ok(Item::Generator(s[0])), _ => Err(Error:...
identifier_body
day11.rs
use std::{collections::HashSet, io::Write}; use itertools::Itertools; use snafu::Snafu; type Result<T> = std::result::Result<T, Error>; #[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone)] enum Item { Chip(char), Generator(char), ChipAndGenerator, } impl std::str::FromStr for Item { type Err = Er...
(&self) -> usize { self.floors .iter() .enumerate() .map(|(i, f)| f.len() * (i + 1) * 10) .sum::<usize>() } fn is_success(&self) -> bool { for floor in &self.floors[..self.floors.len() - 1] { if !floor.is_empty() { retu...
score
identifier_name
day11.rs
use std::{collections::HashSet, io::Write}; use itertools::Itertools; use snafu::Snafu; type Result<T> = std::result::Result<T, Error>; #[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone)] enum Item { Chip(char), Generator(char), ChipAndGenerator, } impl std::str::FromStr for Item { type Err = Er...
for floor in &self.floors[..self.floors.len() - 1] { if !floor.is_empty() { return false; } } true } fn get_neighbors(&self) -> Vec<State> { let mut out = Vec::new(); // calculate valid floors that the elevator can move to ...
.map(|(i, f)| f.len() * (i + 1) * 10) .sum::<usize>() } fn is_success(&self) -> bool {
random_line_split
smpl.tpl.js
if (typeof define !== 'function') {var define = require('amdefine')(module)} /** * @module smpl * @submodule smpl.tpl * @class smpl.tpl * @static */ define(['./smpl.string', './smpl.utils'], function(smpl) { 'use strict'; var MESSAGES = { wrongClosed: 'Incorrect element closed <{0}.{1}>. Openned one was <{2}...
} else if (chr === '/' && input.charAt(pos) === '*') { //Multi line comment if (!at) return initialPos; var newpos = input.indexOf('*/', pos + 1); pos = (newpos === -1) ? l : newpos + 2; } else { if (chr === '"' || chr === "'") { //String pos = this.findUnescaped(input, chr, pos); } else ...
if (!at) return initialPos; } else if (chr === '/' && input.charAt(pos) === '/') { //Single line comment if (!at) return initialPos; while (!newLine.test(input.charAt(++pos))); ++pos;
random_line_split
smpl.tpl.js
if (typeof define !== 'function') {var define = require('amdefine')(module)} /** * @module smpl * @submodule smpl.tpl * @class smpl.tpl * @static */ define(['./smpl.string', './smpl.utils'], function(smpl) { 'use strict'; var MESSAGES = { wrongClosed: 'Incorrect element closed <{0}.{1}>. Openned one was <{2}...
} } if (smpl.tpl.globalObj) { this.__globalKey = this.__name + '_' + smpl.utils.uniq(); smpl.tpl.globalObj[this.__globalKey] = this; this.__globalKey = smpl.tpl.globalKey + '["' + this.__globalKey + '"]'; } }; smpl.tpl.Template.prototype.set = function(block, key, value) { if (arguments.length ...
{ this.__blocks[blkId] = new Function('smpl', '$', '"use strict";' + this.__blocks[blkId]); }
conditional_block
cart.component.ts
import { Component, OnInit } from '@angular/core'; import { AuthenticationService } from '../services/authentication.service'; import { ProductService } from '../services/product.service'; import { ToastrService } from '../toast.service'; import {Router} from '@angular/router'; import { environment } from '../../enviro...
} else{ this.hideLoader(); } }, error=> { console.log( error ); } ) } getTextWidth(text, font) { // re-use canvas object for better performance var canvas = document.createElement("canvas"); var context = canvas.getContext(...
{ this.hideLoader(); }
conditional_block
cart.component.ts
import { Component, OnInit } from '@angular/core'; import { AuthenticationService } from '../services/authentication.service'; import { ProductService } from '../services/product.service'; import { ToastrService } from '../toast.service'; import {Router} from '@angular/router'; import { environment } from '../../enviro...
(items){ this.productService.updateData(this.shoppingEnpoint, items).subscribe(result => { console.log( 'result', result ); this.getTotalPricing(); }, error => { this.toast.error("Error updating cart!", "Error",{positionClass:"toast-top-right"} ); }) } checkout(){ localSto...
updatecart
identifier_name
cart.component.ts
import { Component, OnInit } from '@angular/core'; import { AuthenticationService } from '../services/authentication.service'; import { ProductService } from '../services/product.service'; import { ToastrService } from '../toast.service'; import {Router} from '@angular/router'; import { environment } from '../../enviro...
validateMax(i){ console.log(this.products[i].quantity.value); if(this.products[i].quantity.value > this.products[i].fish.maximumOrder){ this.products[i].quantity.value = this.products[i].fish.maximumOrder; this.getAllProductsCount(); }else{ this.getAllProductsCount(); } } /...
{ console.log("Product modal ID", itemID, index); this.itemToDelete = itemID; this.index = index; jQuery('#confirmDelete').modal('show'); }
identifier_body
cart.component.ts
import { Component, OnInit } from '@angular/core'; import { AuthenticationService } from '../services/authentication.service'; import { ProductService } from '../services/product.service'; import { ToastrService } from '../toast.service'; import {Router} from '@angular/router'; import { environment } from '../../enviro...
var context = canvas.getContext("2d"); context.font = font; var metrics = context.measureText(text); return metrics.width; } public isVacio(id, idSuffix) { let element = document.querySelector('#' + id) as HTMLInputElement; if (element === null) return true; //unit measure const su...
var canvas = document.createElement("canvas");
random_line_split
sink.rs
use anyhow::{anyhow, Context, Result}; use byte_unit::n_mib_bytes; use fuzztruction_shared::util::try_get_child_exit_reason; use log::error; use std::env::set_current_dir; use std::os::unix::prelude::AsRawFd; use std::{ convert::TryFrom, ffi::CString, fs::{File, OpenOptions}, io::{Seek, SeekFrom, Writ...
else { unsafe { libc::dup2(dev_null_fd, libc::STDERR_FILENO); } } unsafe { libc::close(dev_null_fd); } unsafe { // Close the pipe ends used by our pa...
{ //unsafe { // let fd = self.stderr_file.as_ref().unwrap().0.as_raw_fd(); // libc::dup2(fd, libc::STDERR_FILENO); // libc::close(fd); //} }
conditional_block
sink.rs
use anyhow::{anyhow, Context, Result}; use byte_unit::n_mib_bytes; use fuzztruction_shared::util::try_get_child_exit_reason; use log::error; use std::env::set_current_dir; use std::os::unix::prelude::AsRawFd; use std::{ convert::TryFrom, ffi::CString, fs::{File, OpenOptions}, io::{Seek, SeekFrom, Writ...
(&mut self, data: &[u8]) { debug_assert!( self.input_channel == InputChannel::Stdin || self.input_channel == InputChannel::File ); self.input_file.0.seek(SeekFrom::Start(0)).unwrap(); self.input_file.0.set_len(0).unwrap(); self.input_file.0.write_all(data).unwrap(); ...
write
identifier_name
sink.rs
use anyhow::{anyhow, Context, Result}; use byte_unit::n_mib_bytes; use fuzztruction_shared::util::try_get_child_exit_reason; use log::error; use std::env::set_current_dir; use std::os::unix::prelude::AsRawFd; use std::{ convert::TryFrom, ffi::CString, fs::{File, OpenOptions}, io::{Seek, SeekFrom, Writ...
let ret = repeat_on_interrupt(|| unsafe { libc::read(self.receive_fd.unwrap(), buf_ptr, 4) }); if ret != 4 { error!("Failed to get exit status"); return Err(anyhow!("Failed to read from receive_non_blocking_fd")); } let exit_status = i32::from_le_byte...
log::trace!("Child terminated, getting exit status");
random_line_split
app_store_connect.py
"""Tasks for managing Debug Information Files from Apple App Store Connect. Users can instruct Sentry to download dSYM from App Store Connect and put them into Sentry's debug files. These tasks enable this functionality. """ import logging import pathlib import tempfile from typing import List, Mapping, Tuple impor...
# Sadly this decorator makes this entire function untyped for now as it does not itself have # typing annotations. So we do all the work outside of the decorated task function to work # around this. # Since all these args must be pickled we keep them to built-in types as well. @instrumented_task(name="sentry.tasks.a...
random_line_split
app_store_connect.py
"""Tasks for managing Debug Information Files from Apple App Store Connect. Users can instruct Sentry to download dSYM from App Store Connect and put them into Sentry's debug files. These tasks enable this functionality. """ import logging import pathlib import tempfile from typing import List, Mapping, Tuple impor...
def create_difs_from_dsyms_zip(dsyms_zip: str, project: Project) -> None: with sentry_sdk.start_span(op="dsym-difs", description="Extract difs dSYM zip"): with open(dsyms_zip, "rb") as fp: created = debugfile.create_files_from_dif_zip(fp, project, accept_unknown=True) for proj_deb...
with sdk.configure_scope() as scope: scope.set_context("dsym_downloads", {"total": len(builds), "completed": i}) with tempfile.NamedTemporaryFile() as dsyms_zip: try: client.download_dsyms(build, pathlib.Path(dsyms_zip.name)) # For no dSYMs, let the build be m...
conditional_block
app_store_connect.py
"""Tasks for managing Debug Information Files from Apple App Store Connect. Users can instruct Sentry to download dSYM from App Store Connect and put them into Sentry's debug files. These tasks enable this functionality. """ import logging import pathlib import tempfile from typing import List, Mapping, Tuple impor...
def get_or_create_persisted_build( project: Project, config: appconnect.AppStoreConnectConfig, build: appconnect.BuildInfo ) -> AppConnectBuild: """Fetches the sentry-internal :class:`AppConnectBuild`. The build corresponds to the :class:`appconnect.BuildInfo` as returned by the AppStore Connect API...
with sentry_sdk.start_span(op="dsym-difs", description="Extract difs dSYM zip"): with open(dsyms_zip, "rb") as fp: created = debugfile.create_files_from_dif_zip(fp, project, accept_unknown=True) for proj_debug_file in created: logger.debug("Created %r for project %s", pro...
identifier_body
app_store_connect.py
"""Tasks for managing Debug Information Files from Apple App Store Connect. Users can instruct Sentry to download dSYM from App Store Connect and put them into Sentry's debug files. These tasks enable this functionality. """ import logging import pathlib import tempfile from typing import List, Mapping, Tuple impor...
() -> None: """Refreshes all AppStoreConnect builds for all projects. This iterates over all the projects configured in Sentry and for any which has an AppStoreConnect symbol source configured will poll the AppStoreConnect API to check if there are new builds. """ # We have no way to query for ...
inner_refresh_all_builds
identifier_name
player.rs
use std::collections::HashMap; use std::convert::TryInto; use std::path::PathBuf; use std::sync::mpsc::Sender; use std::time::{Duration, Instant}; use dbus::arg::RefArg; use dbus::blocking::stdintf::org_freedesktop_dbus::Properties; use dbus::blocking::BlockingSender; use dbus::blocking::{Connection, Proxy}; use dbus:...
.map(|reply| { reply .get1() .expect("GetNameOwner must have name as first member") }) } fn query_all_player_buses(c: &Connection) -> Result<Vec<String>, String> { let list_names = Message::new_method_call( "org.freedesktop.DBus", "/", ...
c.send_with_reply_and_block(get_name_owner, Duration::from_millis(100)) .map_err(|e| e.to_string())
random_line_split
player.rs
use std::collections::HashMap; use std::convert::TryInto; use std::path::PathBuf; use std::sync::mpsc::Sender; use std::time::{Duration, Instant}; use dbus::arg::RefArg; use dbus::blocking::stdintf::org_freedesktop_dbus::Properties; use dbus::blocking::BlockingSender; use dbus::blocking::{Connection, Proxy}; use dbus:...
fn parse_player_metadata<T: arg::RefArg>( metadata_map: HashMap<String, T>, ) -> Result<Option<Metadata>, String> { debug!("metadata_map = {:?}", metadata_map); let file_path_encoded = match metadata_map.get("xesam:url") { Some(url) => url .as_str() .ok_or("url metadata sh...
{ query_player_property::<String>(p, "PlaybackStatus").map(|v| parse_playback_status(&v)) }
identifier_body
player.rs
use std::collections::HashMap; use std::convert::TryInto; use std::path::PathBuf; use std::sync::mpsc::Sender; use std::time::{Duration, Instant}; use dbus::arg::RefArg; use dbus::blocking::stdintf::org_freedesktop_dbus::Properties; use dbus::blocking::BlockingSender; use dbus::blocking::{Connection, Proxy}; use dbus:...
(&self) -> Duration { self.position } } fn query_player_property<T>(p: &ConnectionProxy, name: &str) -> Result<T, String> where for<'b> T: dbus::arg::Get<'b>, { p.get("org.mpris.MediaPlayer2.Player", name) .map_err(|e| e.to_string()) } pub fn query_player_position(p: &ConnectionProxy) -> R...
position
identifier_name
initialize.py
#! usr/bin/env python3 ############################################################# # # Author: John Turner # Version: 1.0 # Last Updated: 2/18/2015 # # This file contains the database initialization script for # the Recruiter Connect Database. This file will drop, recreate # and migrate the db, and then insert the...
for key in data: setattr(transaction, key, data[key]) transaction.save() ################################# RENTAL ##################################### for data in [ {'date_out':'2000-01-01 00:00:00', 'due_date': '2001-01-01', 'item':item, 'transaction':transaction, 'amount':40.87}, {'date_out':...
random_line_split
initialize.py
#! usr/bin/env python3 ############################################################# # # Author: John Turner # Version: 1.0 # Last Updated: 2/18/2015 # # This file contains the database initialization script for # the Recruiter Connect Database. This file will drop, recreate # and migrate the db, and then insert the...
rental.save()
setattr(rental, key, data[key])
conditional_block
pharmacie-details.ts
import { Component, ViewChild, ElementRef, EventEmitter, ApplicationRef, NgZone } from '@angular/core'; import { ModalController, NavController, NavParams, ToastController, Platform, LoadingController } from 'ionic-angular'; import { SocialSharing, Push, GoogleAnalytics } from 'ionic-native'; // Importantion du provi...
import {Pharmacie} from '../../models/pharmacie'; // Importation de la page de détail d'une pharmacie import {OpinionPage} from '../opinion/opinion'; // Importation de la page de saisie des horaires de la pharmacie import {HoursPage} from '../hours/hours'; declare var google; declare var $; declare var _; declare va...
import {SubscriberProvider} from '../../providers/subscriber/subscriber'; // Importation du modèle de données Pharmacie
random_line_split
pharmacie-details.ts
import { Component, ViewChild, ElementRef, EventEmitter, ApplicationRef, NgZone } from '@angular/core'; import { ModalController, NavController, NavParams, ToastController, Platform, LoadingController } from 'ionic-angular'; import { SocialSharing, Push, GoogleAnalytics } from 'ionic-native'; // Importantion du provi...
abonne l'utilisateur aux commentaires de la pharmacie this.subscriberProvider.subscribe(this.pharmacie._id); classIcon = 'ion-md-star'; msgToast = 'Pharmacie ajoutée aux favoris'; if (localStorage.getItem('favorites')) { favorites = JSON.parse(localStorage.getItem('favorites')); ...
bonne l'utilisateur aux commentaires de la pharmacie this.subscriberProvider.unsubscribe(this.pharmacie._id); classIcon = 'ion-md-star-outline'; msgToast = 'Pharmacie retirée des favoris'; // Mise a jour de la liste des pharmacies favorites favorites = JSON.parse(localStorage.getItem('fa...
conditional_block
pharmacie-details.ts
import { Component, ViewChild, ElementRef, EventEmitter, ApplicationRef, NgZone } from '@angular/core'; import { ModalController, NavController, NavParams, ToastController, Platform, LoadingController } from 'ionic-angular'; import { SocialSharing, Push, GoogleAnalytics } from 'ionic-native'; // Importantion du provi...
his.pharmacie.hours) { function addZero(i) { if (i < 10) { i = "0" + i; } return i; } function formatDay(amo, amc, pmo, pmc) { if (amo == 0 && pmc == 1440) return 'Ouvert 24h/24'; // Pas d'horaire le matin if (amo == 0 && amc == 0...
{ if (t
identifier_name
did.rs
#[cfg(feature = "alloc")] use alloc::string::String; #[cfg(feature = "alloc")] use alloc::string::ToString as _; use core::cmp::Ordering; use core::convert::TryFrom; use core::fmt::Debug; use core::fmt::Display; use core::fmt::Formatter; use core::fmt::Result as FmtResult; use core::hash::Hash; use core::hash::Hasher; ...
// Replace prefix /. [b'/', b'.'] => { input = &input[..1]; } // Replace prefix /../ [b'/', b'.', b'.', b'/', ..] => { input = &input[3..]; output.pop(); } // Replace prefix /.. [b'/', b'.', b'.'] => { input = &inpu...
{ input = &input[2..]; }
conditional_block
did.rs
#[cfg(feature = "alloc")] use alloc::string::String; #[cfg(feature = "alloc")] use alloc::string::ToString as _; use core::cmp::Ordering; use core::convert::TryFrom; use core::fmt::Debug; use core::fmt::Display; use core::fmt::Formatter; use core::fmt::Result as FmtResult; use core::hash::Hash; use core::hash::Hasher; ...
} impl Display for DID { fn fmt(&self, f: &mut Formatter) -> FmtResult { f.write_fmt(format_args!("{}", self.as_str())) } } impl AsRef<str> for DID { fn as_ref(&self) -> &str { self.data.as_ref() } } impl FromStr for DID { type Err = Error; fn from_str(string: &str) -> Result<Self, Self::Err> {...
{ f.write_fmt(format_args!("{:?}", self.as_str())) }
identifier_body
did.rs
#[cfg(feature = "alloc")] use alloc::string::String; #[cfg(feature = "alloc")] use alloc::string::ToString as _; use core::cmp::Ordering; use core::convert::TryFrom; use core::fmt::Debug; use core::fmt::Display; use core::fmt::Formatter; use core::fmt::Result as FmtResult; use core::hash::Hash; use core::hash::Hasher; ...
self.core.path(self.as_str()) } /// Returns the [`DID`] method query, if any. #[inline] pub fn query(&self) -> Option<&str> { self.core.query(self.as_str()) } /// Returns the [`DID`] method fragment, if any. #[inline] pub fn fragment(&self) -> Option<&str> { self.core.fragment(self.as_str(...
#[inline] pub fn path(&self) -> &str {
random_line_split