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
domain_randomization.py
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and # Technical University of Darmstadt. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source ...
(self, init_state: np.ndarray = None, domain_param: dict = None) -> np.ndarray: if domain_param is None: # No explicit specification of domain parameters, so randomizer is requested if isinstance(self._buffer, dict): # The buffer consists of one domain parameter set ...
reset
identifier_name
domain_randomization.py
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and # Technical University of Darmstadt. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source ...
def fill_buffer(self, num_domains: int): """ Fill the internal buffer with domains. :param num_domains: number of randomized domain parameter sets to store in the buffer """ if self._randomizer is None: raise pyrado.TypeErr(msg="The randomizer must not be None ...
"""Set the selection method.""" if selection not in ["cyclic", "random"]: raise pyrado.ValueErr(given=selection, eq_constraint="cyclic or random") self._selection = selection
identifier_body
borrow_set.rs
use crate::borrow_check::place_ext::PlaceExt; use crate::borrow_check::nll::ToRegionVid; use crate::borrow_check::path_utils::allow_two_phase_borrow; use crate::dataflow::indexes::BorrowIndex; use crate::dataflow::move_paths::MoveData; use rustc::mir::traversal; use rustc::mir::visit::{PlaceContext, Visitor, NonUseCont...
( locals_are_invalidated_at_exit: bool, body: &Body<'tcx>, move_data: &MoveData<'tcx> ) -> Self { struct HasStorageDead(BitSet<Local>); impl<'tcx> Visitor<'tcx> for HasStorageDead { fn visit_local(&mut self, local: &Local, ctx: PlaceContext, _: Location) { ...
build
identifier_name
borrow_set.rs
use crate::borrow_check::place_ext::PlaceExt; use crate::borrow_check::nll::ToRegionVid; use crate::borrow_check::path_utils::allow_two_phase_borrow; use crate::dataflow::indexes::BorrowIndex; use crate::dataflow::move_paths::MoveData; use rustc::mir::traversal; use rustc::mir::visit::{PlaceContext, Visitor, NonUseCont...
} } if locals_are_invalidated_at_exit { LocalsStateAtExit::AllAreInvalidated } else { let mut has_storage_dead = HasStorageDead(BitSet::new_empty(body.local_decls.len())); has_storage_dead.visit_body(body); let mut has_storage_dead_or...
{ self.0.insert(*local); }
conditional_block
borrow_set.rs
use crate::borrow_check::place_ext::PlaceExt; use crate::borrow_check::nll::ToRegionVid; use crate::borrow_check::path_utils::allow_two_phase_borrow; use crate::dataflow::indexes::BorrowIndex; use crate::dataflow::move_paths::MoveData; use rustc::mir::traversal; use rustc::mir::visit::{PlaceContext, Visitor, NonUseCont...
} } impl<'tcx> BorrowSet<'tcx> { pub fn build( tcx: TyCtxt<'tcx>, body: &Body<'tcx>, locals_are_invalidated_at_exit: bool, move_data: &MoveData<'tcx>, ) -> Self { let mut visitor = GatherBorrows { tcx, body, idx_vec: IndexVec::new(...
LocalsStateAtExit::SomeAreInvalidated{ has_storage_dead_or_moved } }
random_line_split
train_denoise_clouds.py
import shutil import numpy as np import torch import torch.nn as nn import torch.functional as tf import torch.utils.data import time from tqdm import tqdm import model_denoise_clouds as model import argparse try: import nvidia_smi NVIDIA_SMI = True except: NVIDIA_SMI = False import sys import os import pat...
self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr, weight_decay=self.weight_decay) self.loss_fn = nn.MSELoss().to(self.device) self.scheduler = torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=scheduler, gamma=0.5) np.random.seed(123) self.surf0 = ...
f.close()
random_line_split
train_denoise_clouds.py
import shutil import numpy as np import torch import torch.nn as nn import torch.functional as tf import torch.utils.data import time from tqdm import tqdm import model_denoise_clouds as model import argparse try: import nvidia_smi NVIDIA_SMI = True except: NVIDIA_SMI = False import sys import os import pat...
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): torch.save(state, filename) if is_best: shutil.copyfile(filename, filename+'.best') class Training(object): def __init__(self, batch_size, validation_split=0.2, gpu=0, smooth=0.05, K=3, model_class='conv1d'): sel...
""" Dataset class that will provide data during training. Modify it accordingly for your dataset. This one shows how to do augmenting during training for a very simple training set """ def __init__(self, n_training): """ Args: n_training (int): number of tra...
identifier_body
train_denoise_clouds.py
import shutil import numpy as np import torch import torch.nn as nn import torch.functional as tf import torch.utils.data import time from tqdm import tqdm import model_denoise_clouds as model import argparse try: import nvidia_smi NVIDIA_SMI = True except: NVIDIA_SMI = False import sys import os import pat...
(self, index): Phi = self.matrix[self.index_matrix[index], :, :].astype('float32') rho = 0.4 / self.eigenvals[self.index_matrix[index]] Phi_split = Phi.reshape((5, 24, 3072)) surface = np.random.uniform(low=0.2, high=1.0) * self.surface[self.index_surface[index], :] clou...
__getitem__
identifier_name
train_denoise_clouds.py
import shutil import numpy as np import torch import torch.nn as nn import torch.functional as tf import torch.utils.data import time from tqdm import tqdm import model_denoise_clouds as model import argparse try: import nvidia_smi NVIDIA_SMI = True except: NVIDIA_SMI = False import sys import os import pat...
return Phi_split, surface.astype('float32'), clouds.astype('float32'), rho.astype('float32'), d_split.astype('float32') def __len__(self): return self.n_training def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): torch.save(state, filename) if is_best: ...
d_split[i, :] = Phi_split[i, :, :] @ (clouds[i, :] + (1.0 - clouds[i, :])**2 * surface)
conditional_block
create_load_files.py
import pandas as pd import calendar import re import csv import codecs from src.clean_text import give_clean_words_list import pyspark.sql.types as types from pyspark.sql import SQLContext from pyspark import SparkConf, SparkContext import numpy as np import operator from collections import defaultdict def bags_forma...
conf = SparkConf().setAppName('word count') sc = SparkContext(conf=conf) sqlContext = SQLContext(sc) schema = types.StructType([types.StructField('Word', types.StringType(), False), types.StructField('Count', types.IntegerType(), False), types.StructField('Percen...
contents = line.split() return str(contents[0]), int(contents[1]), float(contents[2])
identifier_body
create_load_files.py
import pandas as pd import calendar import re import csv import codecs from src.clean_text import give_clean_words_list import pyspark.sql.types as types from pyspark.sql import SQLContext from pyspark import SparkConf, SparkContext import numpy as np import operator from collections import defaultdict def bags_forma...
r5_url = amazon_data["R5 URL"][index] if type(r5_url) is float: r5_url = "" amazon_url = amazon_data["Book URL"][index] if type(amazon_url) is float: amazon_url = "" # Description data good_reads_desc = desc_data["GoodReads Description"][index] if type(good_reads_desc) is...
r5 = ""
conditional_block
create_load_files.py
import pandas as pd import calendar import re import csv import codecs from src.clean_text import give_clean_words_list import pyspark.sql.types as types from pyspark.sql import SQLContext from pyspark import SparkConf, SparkContext import numpy as np import operator from collections import defaultdict def bags_forma...
elif genre == "science fiction": genre = "SF" elif genre == "self-help": genre = "SH" genre_bag_words = crime_words.map(bags_format) genre_word_df = sqlContext.createDataFrame(genre_bag_words, schema=schema).cache() genre_word_df.createOrReplaceTempView(genre + '_words') # Inpu...
elif genre == "non-fiction": genre = "NF"
random_line_split
create_load_files.py
import pandas as pd import calendar import re import csv import codecs from src.clean_text import give_clean_words_list import pyspark.sql.types as types from pyspark.sql import SQLContext from pyspark import SparkConf, SparkContext import numpy as np import operator from collections import defaultdict def
(line): contents = line.split() return str(contents[0]), int(contents[1]), float(contents[2]) conf = SparkConf().setAppName('word count') sc = SparkContext(conf=conf) sqlContext = SQLContext(sc) schema = types.StructType([types.StructField('Word', types.StringType(), False), types.S...
bags_format
identifier_name
zigzag_graph.rs
use std::collections::HashMap; use std::marker::PhantomData; use std::sync::{Arc, RwLock}; use crate::crypto::feistel::{self, FeistelPrecomputed}; use crate::drgraph::{BucketGraph, Graph, BASE_DEGREE}; use crate::hasher::Hasher; use crate::layered_drgporep::Layerable; use crate::parameter_cache::ParameterSetMetadata; ...
} #[inline] fn real_index(&self, i: usize) -> usize { if self.reversed { (self.size() - 1) - i } else { i } } } impl<H, G> PartialEq for ZigZagGraph<H, G> where H: Hasher, G: Graph<H>, { fn eq(&self, other: &ZigZagGraph<H, G>) -> bool { ...
{ cache.read_reverse(node as u32, |parents| cb(parents.unwrap())) }
conditional_block
zigzag_graph.rs
use std::collections::HashMap; use std::marker::PhantomData; use std::sync::{Arc, RwLock}; use crate::crypto::feistel::{self, FeistelPrecomputed}; use crate::drgraph::{BucketGraph, Graph, BASE_DEGREE}; use crate::hasher::Hasher; use crate::layered_drgporep::Layerable; use crate::parameter_cache::ParameterSetMetadata; ...
(&self) -> usize { self.expansion_degree } fn reversed(&self) -> bool { self.reversed } // TODO: Optimization: Evaluate providing an `all_parents` (and hence // `all_expanded_parents`) method that would return the entire cache // in a single lock operation, or at least (if the ...
expansion_degree
identifier_name
zigzag_graph.rs
use std::collections::HashMap; use std::marker::PhantomData; use std::sync::{Arc, RwLock}; use crate::crypto::feistel::{self, FeistelPrecomputed}; use crate::drgraph::{BucketGraph, Graph, BASE_DEGREE}; use crate::hasher::Hasher; use crate::layered_drgporep::Layerable; use crate::parameter_cache::ParameterSetMetadata; ...
/// To zigzag a graph, we just toggle its reversed field. /// All the real work happens when we calculate node parents on-demand. // We always share the two caches (forward/reversed) between // ZigZag graphs even if each graph will use only one of those // caches (depending of its direction). This...
{ Self::new(None, nodes, base_degree, expansion_degree, seed) }
identifier_body
zigzag_graph.rs
use std::collections::HashMap; use std::marker::PhantomData; use std::sync::{Arc, RwLock}; use crate::crypto::feistel::{self, FeistelPrecomputed}; use crate::drgraph::{BucketGraph, Graph, BASE_DEGREE}; use crate::hasher::Hasher; use crate::layered_drgporep::Layerable; use crate::parameter_cache::ParameterSetMetadata; ...
F: FnMut(&Vec<u32>) -> T, { if !self.use_cache { // No cache usage, generate on demand. return cb(&self.generate_expanded_parents(node)); } // Check if we need to fill the cache. if !self.contains_parents_cache(node) { // Cache is empty so...
random_line_split
converter.py
from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFPage from pdfminer.pdfdevice import PDFDevice from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter, PDFTextState, PDFGraphicState from pdfminer.pdftypes import list_value, dict_value, ...
@get_default('font') def get_font(self, objid, obj=None): for (fontid, spec) in dict_value(obj).items(): spec = dict_value(spec) spec, fontType, embedFont, opentype = pdffonts.getType(spec) if fontType: font = fontType(spec, embedFont=embedFont and s...
get_function = getattr(self, 'get_' + res_type.lower(), None) return get_function and get_function(None, obj=res_obj)
identifier_body
converter.py
from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFPage from pdfminer.pdfdevice import PDFDevice from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter, PDFTextState, PDFGraphicState from pdfminer.pdftypes import list_value, dict_value, ...
(self, name): if isinstance(name, PSLiteral): name = name.name gstate = self.resources['ExtGState'].get(name) if gstate and not self.textstate.extState: gstate = resolve1(gstate) self.textstate.extState = gstate def do_q(self): self.gstack.append(...
do_gs
identifier_name
converter.py
from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFPage from pdfminer.pdfdevice import PDFDevice from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter, PDFTextState, PDFGraphicState from pdfminer.pdftypes import list_value, dict_value, ...
self.fonts[literal(fontid)] = font @get_default('colorspace') def get_colorspace(self, objid, obj=None): for (csid, spec) in dict_value(obj).items(): cs = colorspace.parse(spec) if cs: self.colorspaces[literal(csid)] = cs def get_procset(sel...
self.xobjects[objid] = font.embedFont
conditional_block
converter.py
from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFPage from pdfminer.pdfdevice import PDFDevice from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter, PDFTextState, PDFGraphicState from pdfminer.pdftypes import list_value, dict_value, s...
def do_Q(self): self.gstack and self.set_current_state(self.gstack.pop()) # def do_Td(self, tx, ty): # x, y = self.textstate.linematrix # # print((x,y), (tx,ty)) # (a, b, c, d, e, f) = self.textstate.matrix # print((x,y), (tx,ty), (tx*a+ty*c+e, tx*b+ty*d+f)) # self.textstate.m...
random_line_split
diagnostic_server.rs
//! A small TCP server to handle collection of diagnostics information in a //! cross-platform way for the `cargo fix` command. use std::collections::HashSet; use std::io::{BufReader, Read, Write}; use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; use std::path::PathBuf; use std::sync::atomic::{AtomicBool,...
{ listener: TcpListener, addr: SocketAddr, } pub struct StartedServer { addr: SocketAddr, done: Arc<AtomicBool>, thread: Option<JoinHandle<()>>, } impl RustfixDiagnosticServer { pub fn new() -> Result<Self, Error> { let listener = TcpListener::bind("127.0.0.1:0") .with_con...
RustfixDiagnosticServer
identifier_name
diagnostic_server.rs
//! A small TCP server to handle collection of diagnostics information in a //! cross-platform way for the `cargo fix` command. use std::collections::HashSet; use std::io::{BufReader, Read, Write}; use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; use std::path::PathBuf; use std::sync::atomic::{AtomicBool,...
if !files.is_empty() { writeln!( self.config.shell().err(), "\nafter fixes were automatically applied the compiler \ reported errors within these files:\n" )?; for file i...
{ self.config .shell() .warn("failed to automatically apply fixes suggested by rustc")?; }
conditional_block
diagnostic_server.rs
//! A small TCP server to handle collection of diagnostics information in a //! cross-platform way for the `cargo fix` command. use std::collections::HashSet; use std::io::{BufReader, Read, Write}; use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; use std::path::PathBuf; use std::sync::atomic::{AtomicBool,...
self.config.shell().warn(&format!("\ {} If you are trying to migrate from the previous edition ({prev_edition}), the process requires following these steps: 1. Start with `edition = \"{prev_edition}\"` in `Cargo.toml` 2. Run `cargo fix --edition` 3. Modify `Cargo.toml` to set `edition = \"{this_ed...
message: "".to_string(), // Dummy, so that this only long-warns once. edition: *edition, }) {
random_line_split
getast.go
package parse import ( "errors" "fmt" "github.com/philhofer/msgp/gen" "github.com/ttacon/chalk" "go/ast" "go/parser" "go/token" "os" "reflect" "strings" ) type Identity uint8 const ( IDENT Identity = iota Struct Builtin Map Unsupported ) var ( // this records a set of all the // identifiers in the ...
return nil case *ast.InterfaceType: // support `interface{}` if len(e.(*ast.InterfaceType).Methods.List) == 0 { return &gen.BaseElem{ Value: gen.Intf, } } return nil default: // other types not supported return nil } } func pullIdent(name string) gen.Base { switch name { case "string": r...
random_line_split
getast.go
package parse import ( "errors" "fmt" "github.com/philhofer/msgp/gen" "github.com/ttacon/chalk" "go/ast" "go/parser" "go/token" "os" "reflect" "strings" ) type Identity uint8 const ( IDENT Identity = iota Struct Builtin Map Unsupported ) var ( // this records a set of all the // identifiers in the ...
(filename string) (files []*ast.File, pkgName string, err error) { var ( f *ast.File fInfo os.FileInfo ) fset := token.NewFileSet() fInfo, err = os.Stat(filename) if err != nil { return } if fInfo.IsDir() { var pkgs map[string]*ast.Package pkgs, err = parser.ParseDir(fset, filename, nil, parser.Al...
GetAST
identifier_name
getast.go
package parse import ( "errors" "fmt" "github.com/philhofer/msgp/gen" "github.com/ttacon/chalk" "go/ast" "go/parser" "go/token" "os" "reflect" "strings" ) type Identity uint8 const ( IDENT Identity = iota Struct Builtin Map Unsupported ) var ( // this records a set of all the // identifiers in the ...
// GetAST simply creates the ast out of a filename and filters // out non-exported elements. func GetAST(filename string) (files []*ast.File, pkgName string, err error) { var ( f *ast.File fInfo os.FileInfo ) fset := token.NewFileSet() fInfo, err = os.Stat(filename) if err != nil { return } if fInfo...
{ globalIdents = make(map[string]gen.Base) globalProcessed = make(map[string]struct{}) }
identifier_body
getast.go
package parse import ( "errors" "fmt" "github.com/philhofer/msgp/gen" "github.com/ttacon/chalk" "go/ast" "go/parser" "go/token" "os" "reflect" "strings" ) type Identity uint8 const ( IDENT Identity = iota Struct Builtin Map Unsupported ) var ( // this records a set of all the // identifiers in the ...
return out } // extract embedded field name func embedded(f ast.Expr) string { switch f.(type) { case *ast.Ident: return f.(*ast.Ident).Name case *ast.StarExpr: return embedded(f.(*ast.StarExpr).X) default: // other possibilities (like selector expressions) // are disallowed; we can't reasonably know /...
{ var sf gen.StructField // field name switch len(field.Names) { case 1: sf.FieldName = field.Names[0].Name case 0: sf.FieldName = embedded(field.Type) if sf.FieldName == "" { // means it's a selector expr., or // something else unsupported fmt.Printf(chalk.Yellow.Color(" (\u26a0 field %...
conditional_block
main.go
package main import ( "database/sql" "encoding/json" "fmt" "github.com/oschwald/geoip2-golang" "github.com/umahmood/haversine" "log" "net" "net/http" "reflect" "strconv" "time" _ "github.com/mattn/go-sqlite3" ) // NullString is an alias for sql.NullString data type type NullString sql.NullString // Scan...
else { *ns = NullString{s.String, true} } return nil } type Env struct { sqlDb *sql.DB } // json object to map the endpoint input data type RequestInput struct { Event_UUID string `json:"event_uuid"` Username string `json:"username"` Unix_timestamp int64 `json:"unix_timestamp"` IP_Address string `...
{ *ns = NullString{s.String, false} }
conditional_block
main.go
package main import ( "database/sql" "encoding/json" "fmt" "github.com/oschwald/geoip2-golang" "github.com/umahmood/haversine" "log" "net" "net/http" "reflect" "strconv" "time" _ "github.com/mattn/go-sqlite3" ) // NullString is an alias for sql.NullString data type type NullString sql.NullString // Scan...
// this function return latitude, longitude and radius give an IPAddress. If it couldnt find the ip it returns dummy value of -10000 func GetLatitudeAndLongitude(ip string) (lat, lon float64, radius uint16) { geoIpdb, err := geoip2.Open("databases/GeoLite2-City.mmdb") if err != nil { log.Fatal(err) } defer geoI...
{ decoder := json.NewDecoder(req.Body) var input RequestInput writer.Header().Set("Content-Type", "application/json") err := decoder.Decode(&input) if err != nil { respondWithError(err.Error(), writer) fmt.Println("handling ", req.RequestURI, ": ", err) return } tm := time.Unix(input.Unix_timestamp, 0) ...
identifier_body
main.go
package main import ( "database/sql" "encoding/json" "fmt" "github.com/oschwald/geoip2-golang" "github.com/umahmood/haversine" "log" "net" "net/http" "reflect" "strconv" "time" _ "github.com/mattn/go-sqlite3" ) // NullString is an alias for sql.NullString data type type NullString sql.NullString // Scan...
(writer http.ResponseWriter, req *http.Request){ decoder := json.NewDecoder(req.Body) var input RequestInput writer.Header().Set("Content-Type", "application/json") err := decoder.Decode(&input) if err != nil { respondWithError(err.Error(), writer) fmt.Println("handling ", req.RequestURI, ": ", err) return ...
home
identifier_name
main.go
package main import ( "database/sql" "encoding/json" "fmt" "github.com/oschwald/geoip2-golang" "github.com/umahmood/haversine" "log" "net" "net/http" "reflect" "strconv" "time" _ "github.com/mattn/go-sqlite3" ) // NullString is an alias for sql.NullString data type type NullString sql.NullString // Scan...
tx.Commit() // Defined the paramters as NullString to handle dereferencing issue with nil values returned from the database. type sqlrow struct { uuid NullString username NullString ipaddress NullString date_time NullString } // variables to hold the current, preceeding and succeeding database records ...
_, err = env.sqlDb.Exec("insert into request(uuid, username, ipaddress, date_time) values(?, ?, ?, ?)", input.Event_UUID, input.Username, input.IP_Address, input.Unix_timestamp) if err != nil { log.Fatal(err) panic(err) }
random_line_split
btc-arbitrage.ts
import * as GTT from 'gdax-trading-toolkit'; import { GDAXFeed } from "gdax-trading-toolkit/build/src/exchanges"; import { StreamMessage, TradeMessage } from "gdax-trading-toolkit/build/src/core"; import { LiveOrder } from "gdax-trading-toolkit/build/src/lib"; import { PlaceOrderMessage } from 'gdax-trading-toolkit/bui...
console.log(`arbitrageValue: ${arbitrageValue}`); sufficentBalances(btc_needed, eth_needed, usd_needed).then(result => { if (!result) { console.log('Insufficient Balances'); return } // alert me. process.stdout.write("\x07"); // buy eth with bi...
let btc_needed = eth_btc.times(amount); let usd_needed = btc_min_amount.times(btc_price.minus(min_increment));
random_line_split
btc-arbitrage.ts
import * as GTT from 'gdax-trading-toolkit'; import { GDAXFeed } from "gdax-trading-toolkit/build/src/exchanges"; import { StreamMessage, TradeMessage } from "gdax-trading-toolkit/build/src/core"; import { LiveOrder } from "gdax-trading-toolkit/build/src/lib"; import { PlaceOrderMessage } from 'gdax-trading-toolkit/bu...
de: string, product: string, amount: string, price: string) { const [base, quote] = product.split('-'); console.log(side + ' ' + base + ' ' + amount + ' ' + product + '@ ' + price); const order: PlaceOrderMessage = { time: new Date(), type: 'placeOrder', productId: product, size: amount, ...
erMessageWithREST(si
identifier_name
btc-arbitrage.ts
import * as GTT from 'gdax-trading-toolkit'; import { GDAXFeed } from "gdax-trading-toolkit/build/src/exchanges"; import { StreamMessage, TradeMessage } from "gdax-trading-toolkit/build/src/core"; import { LiveOrder } from "gdax-trading-toolkit/build/src/lib"; import { PlaceOrderMessage } from 'gdax-trading-toolkit/bu...
if (arbitrageValue.gt(arbitrageLimit)) {return} // if (executedArbitrage === true) {return} // i need 0.01 BTC // I need 0.01 / btc_eth exchange rate // I need 0.01 * btc_usd exchange rate let buy_price = eth_btc; let btc_min_amount = Big(0.01); let amount = btc_min_amount.div(eth_btc); ...
turn}
conditional_block
btc-arbitrage.ts
import * as GTT from 'gdax-trading-toolkit'; import { GDAXFeed } from "gdax-trading-toolkit/build/src/exchanges"; import { StreamMessage, TradeMessage } from "gdax-trading-toolkit/build/src/core"; import { LiveOrder } from "gdax-trading-toolkit/build/src/lib"; import { PlaceOrderMessage } from 'gdax-trading-toolkit/bu...
tion sufficentBalances(btc_needed: BigJS, eth_needed: BigJS, usd_needed: BigJS ): Promise<boolean | void> { // I need at least eth_usd_sell of ether to sell // I need at least eth_btc_buy of btc to buy ether // I need at least btc_usd_buy of usd to buy btc console.log(`btc_needed: ${btc_needed}, eth_nee...
// arbitrageValue = eth_price2 - eth_price let arbitrageLimit = Big(-1); let min_increment = Big(0.01); if (arbitrageValue.gte(zero)) {return} if (eth_btc.isZero() || eth_btc.lt(zero)) {return} if (arbitrageValue.gt(arbitrageLimit)) {return} // if (executedArbitrage === true) {return} /...
identifier_body
asset.rs
// RGB20 Library: fungible digital assets for bitcoin & lightning // Written in 2020-2021 by // Dr. Maxim Orlovsky <orlovsky@pandoracore.com> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. T...
let supply = *genesis_meta .u64(FieldType::IssuedSupply) .first() .ok_or(Error::UnsatisfiedSchemaRequirement)?; let mut issue_limit = 0; // Check if issue limit can be known for assignment in genesis.owned_rights_by_type(OwnedRightType::In...
random_line_split
asset.rs
// RGB20 Library: fungible digital assets for bitcoin & lightning // Written in 2020-2021 by // Dr. Maxim Orlovsky <orlovsky@pandoracore.com> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. T...
lf) -> &str { &self.active_nomination().ticker() } /// Current version of the asset contract, represented in Ricardian form /// /// Current value determined by the last known renomination operation – /// or, by the genesis nomination, if no renomination are known /// /// NB: the ret...
(&se
identifier_name
asset.rs
// RGB20 Library: fungible digital assets for bitcoin & lightning // Written in 2020-2021 by // Dr. Maxim Orlovsky <orlovsky@pandoracore.com> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. T...
/ Returns sum of all known allocations, in atomic value units #[inline] pub fn known_value(&self) -> AtomicValue { self.known_allocations.iter().map(Allocation::value).sum() } /// Returns sum of known allocation after applying `filter` function. Useful /// for filtering UTXOs owned by the c...
self.last_nomination().unwrap_or(&self.genesis_nomination) } //
identifier_body
csv_import_accts_txns.rs
// Copyright (c) 2017-2020, scoobybejesus // Redistributions must include the license: https://github.com/scoobybejesus/cryptools/blob/master/LEGAL.txt use std::error::Error; use std::process; use std::fs::File; use std::cell::{RefCell}; use std::collections::{HashMap}; use std::path::PathBuf; use chrono::NaiveDate; ...
// A StringRecord doesn't accept the same range indexing needed below, so a Vec of Strings will be used let headerstrings: Vec<String> = header1.into_iter().map(|field| field.to_string()).collect(); let acct_num_warn = "Transactions will not import correctly if account numbers in th...
random_line_split
csv_import_accts_txns.rs
// Copyright (c) 2017-2020, scoobybejesus // Redistributions must include the license: https://github.com/scoobybejesus/cryptools/blob/master/LEGAL.txt use std::error::Error; use std::process; use std::fs::File; use std::cell::{RefCell}; use std::collections::{HashMap}; use std::path::PathBuf; use chrono::NaiveDate; ...
(field: &str) -> String { // First, remove commas. let no_comma_string = field.replace(",", ""); let almost_done = no_comma_string.replace(" ", ""); // Next, if ASCII (better be), check for accounting formatting if almost_done.is_ascii() { if...
sanitize_string_for_d128_parsing_basic
identifier_name
csv_import_accts_txns.rs
// Copyright (c) 2017-2020, scoobybejesus // Redistributions must include the license: https://github.com/scoobybejesus/cryptools/blob/master/LEGAL.txt use std::error::Error; use std::process; use std::fs::File; use std::cell::{RefCell}; use std::collections::{HashMap}; use std::path::PathBuf; use chrono::NaiveDate; ...
if let Some(incoming_ar) = incoming_ar { let x = incoming_ar_num.unwrap(); action_records.insert(x, incoming_ar); } if let Some(outgoing_ar) = outgoing_ar { let y = outgoing_ar_num.unwrap(); action_records.insert(y, outgoing_ar); } ...
{ let mut near_done = "".to_string(); // First, remove commas. let no_comma_string = field.replace(",", ""); let almost_done = no_comma_string.replace(" ", ""); // Next, if ASCII (better be), check for accounting formating if almost_done.is_ascii...
identifier_body
csv_import_accts_txns.rs
// Copyright (c) 2017-2020, scoobybejesus // Redistributions must include the license: https://github.com/scoobybejesus/cryptools/blob/master/LEGAL.txt use std::error::Error; use std::process; use std::fs::File; use std::cell::{RefCell}; use std::collections::{HashMap}; use std::path::PathBuf; use chrono::NaiveDate; ...
; if amount.is_nan() { println!("FATAL: Couldn't convert amount to d128 for transaction:\n{:#?}", record); std::process::exit(1); } let amount_rounded = round_d128_1e8(&amount); if amount != amount_rounded { changed...
{ let c = sanitize_string_for_d128_parsing_full(field).parse::<d128>().unwrap(); amount = c; }
conditional_block
servergroup.go
package servergroup import ( "context" "fmt" "net" "net/http" "net/url" "path" "strings" "sync/atomic" "time" "github.com/pkg/errors" "github.com/prometheus/client_golang/api" v1 "github.com/prometheus/client_golang/api/prometheus/v1" "github.com/prometheus/client_golang/prometheus" config_util "github....
} apiClients = append(apiClients, apiClient) } } } apiClientMetricFunc := func(i int, api, status string, took float64) { serverGroupSummary.WithLabelValues(targets[i], api, status).Observe(took) } logrus.Debugf("Updating targets from discovery manager: %v", targets) apiClient, err := promclient...
{ return err }
conditional_block
servergroup.go
package servergroup import ( "context" "fmt" "net" "net/http" "net/url" "path" "strings" "sync/atomic" "time" "github.com/pkg/errors" "github.com/prometheus/client_golang/api" v1 "github.com/prometheus/client_golang/api/prometheus/v1" "github.com/prometheus/client_golang/prometheus" config_util "github....
{ return s.State().apiClient.Metadata(ctx, metric, limit) }
identifier_body
servergroup.go
package servergroup import ( "context" "fmt" "net" "net/http" "net/url" "path" "strings" "sync/atomic" "time" "github.com/pkg/errors" "github.com/prometheus/client_golang/api" v1 "github.com/prometheus/client_golang/api/prometheus/v1" "github.com/prometheus/client_golang/prometheus" config_util "github....
(ctx context.Context, matchers []string, startTime time.Time, endTime time.Time) ([]string, v1.Warnings, error) { return s.State().apiClient.LabelNames(ctx, matchers, startTime, endTime) } // Series finds series by label matchers. func (s *ServerGroup) Series(ctx context.Context, matches []string, startTime, endTime ...
LabelNames
identifier_name
servergroup.go
package servergroup import ( "context" "fmt" "net" "net/http" "net/url" "path" "strings" "sync/atomic" "time" "github.com/pkg/errors" "github.com/prometheus/client_golang/api" v1 "github.com/prometheus/client_golang/api/prometheus/v1" "github.com/prometheus/client_golang/prometheus" config_util "github....
End: s.Cfg.AbsoluteTimeRangeConfig.End, Truncate: s.Cfg.AbsoluteTimeRangeConfig.Truncate, } } if s.Cfg.RelativeTimeRangeConfig != nil { apiClient = &promclient.RelativeTimeFilter{ API: apiClient, Start: s.Cfg.RelativeTimeRangeConfig.Start, End: s.Cfg.Re...
API: apiClient, Start: s.Cfg.AbsoluteTimeRangeConfig.Start,
random_line_split
server.js
/* * name: server * version: 0.5.0 * update: bug fix/ add openSelecter * date: 2017-04-28 */ define(function(require, exports, module) { "use strict"; var $ = app.util; var etpl = require('etpl'); //资源路径处理 var _source = function(source, host) { if (!$.trim(source)) { return ""; } host = host && host...
} else { if (typeof(errcb) === 'function') { errcb(); } else { app.toast('GPS定位超时!', 1000); } } }, appcfg.set.outime); bMap.getLocation({ accuracy: '10m', autoStop: true, filter: 1 }, function(ret, err) { app.loading.hide(); if (ret && ret.status) { chaoshi = clearTi...
var gpsCache = app.storage.val('gps'); if (typeof(callback) === 'function') { callback(gpsCache.lat, gpsCache.lng); } console.log('定位超时,使用缓存数据');
random_line_split
server.js
/* * name: server * version: 0.5.0 * update: bug fix/ add openSelecter * date: 2017-04-28 */ define(function(require, exports, module) { "use strict"; var $ = app.util; var etpl = require('etpl'); //资源路径处理 var _source = function(source, host) { if (!$.trim(source)) { return ""; } host = host && host...
p.window.evaluate('', 'bdMapView', 'refresh()'); } else { setTimeout(function() { var offset = $("#" + dom)[0].getBoundingClientRect(); app.window.popoverElement({ id: dom, name: 'bdMapView', url: seajs.root + '/view/common/baiduMap/temp.html', top: parseInt(window.selfTop) + offset.top...
ata.longitude }; app.storage.val('bdMapData', bdMapParam); if (refresh) { ap
conditional_block
spline.rs
//! Spline curves and operations. #[cfg(feature = "serialization")] use serde_derive::{Deserialize, Serialize}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; #[cfg(feature = "std")] use std::cmp::Ordering; #[cfg(feature = "std")] use std::ops::{Div, Mul}; #[cfg(not(feature = "std"))] use core::ops::{Div, Mul}; #[c...
key and return the key already present. /// /// The key is updated — if present — with the provided function. /// /// # Notes /// /// That function makes sense only if you want to change the interpolator (i.e. [`Key::t`]) of /// your key. If you just want to change the interpolation mode or the carried v...
= self.0.len() { None } else { Some(self.0.remove(index)) } } /// Update a
identifier_body
spline.rs
//! Spline curves and operations. #[cfg(feature = "serialization")] use serde_derive::{Deserialize, Serialize}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; #[cfg(feature = "std")] use std::cmp::Ordering; #[cfg(feature = "std")] use std::ops::{Div, Mul}; #[cfg(not(feature = "std"))] use core::ops::{Div, Mul}; #[c...
ried value. pub value: &'a mut V, /// Interpolation mode to use for that key. pub interpolation: &'a mut Interpolation<T, V>, } // Normalize a time ([0;1]) given two control points. #[inline(always)] pub(crate) fn normalize_time<T, V>( t: T, cp: &Key<T, V>, cp1: &Key<T, V> ) -> T where T: Additive + Div<T,...
// Car
identifier_name
spline.rs
//! Spline curves and operations. #[cfg(feature = "serialization")] use serde_derive::{Deserialize, Serialize}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; #[cfg(feature = "std")] use std::cmp::Ordering; #[cfg(feature = "std")] use std::ops::{Div, Mul}; #[cfg(not(feature = "std"))] use core::ops::{Div, Mul}; #[c...
Interpolation::Linear => { let cp1 = &keys[i + 1]; let nt = normalize_time(t, cp0, cp1); let value = Interpolate::lerp(cp0.value, cp1.value, nt); Some((value, cp0, Some(cp1))) } Interpolation::Cosine => { let two_t = T::one() + T::one(); let cp1 = &key...
random_line_split
spline.rs
//! Spline curves and operations. #[cfg(feature = "serialization")] use serde_derive::{Deserialize, Serialize}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; #[cfg(feature = "std")] use std::cmp::Ordering; #[cfg(feature = "std")] use std::ops::{Div, Mul}; #[cfg(not(feature = "std"))] use core::ops::{Div, Mul}; #[c...
None } } }) } /// Sample a spline at a given time with clamping. pub fn clamped_sample(&self, t: T) -> Option<V> where T: Additive + One + Trigo + Mul<T, Output = T> + Div<T, Output = T> + PartialOrd, V: Interpolate<T> { self.clamped_sample_with_key(t).map(|(v, _, _)| v) } ...
((last.value, &last, None)) } else {
conditional_block
data_import.py
#!/usr/local/bin/python3 import functools import glob import os import sys from datetime import datetime from collections import defaultdict import csv import json import dexag_client import oneinch_client import paraswap_client import totle_client import exchange_utils from v2_compare_prices import canonicalize_and_...
return dict(sorted(tok_ts_dex_prices.items())) # generator def token_ts_agg_split_gen(tok_ts_splits_by_agg): """Generates a sequence of (token, trade_size, agg, split) for all leaves in the given dict""" for token, ts_splits_by_agg in tok_ts_splits_by_agg.items(): for trade_size, agg_splits in t...
for token, ts_agg_prices in json.load(open(f)).items(): for ts, agg_prices in ts_agg_prices.items(): # test for agg_name keys because Totle's JSON structure is different from aggs if any(map(lambda k: k in AGG_NAMES, agg_prices.keys())): # agg dex_prices f...
conditional_block
data_import.py
#!/usr/local/bin/python3 import functools import glob import os import sys from datetime import datetime from collections import defaultdict import csv import json import dexag_client import oneinch_client import paraswap_client import totle_client import exchange_utils from v2_compare_prices import canonicalize_and_...
@functools.lru_cache() def get_all_agg_prices(files=None): files = files or glob.glob(f'{JSON_DATA_DIR}/2019*ts_agg_prices.json') tok_ts_agg_prices = defaultdict(lambda: defaultdict(lambda: defaultdict(list))) for f in files: for token, ts_agg_prices in json.load(open(f)).items(): fo...
"""Returns an aggregated dict of DEXs used in splits, i.e. token: {trade_size: [dex, dex, ...]}""" files = files or glob.glob(f'{JSON_DATA_DIR}/2019*ts_dexs_with_pair.json') tok_ts_dexs_with_pair = defaultdict(lambda: defaultdict(list)) for f in files: for token, ts_dexs_with_pair in json.load(ope...
identifier_body
data_import.py
#!/usr/local/bin/python3 import functools import glob import os import sys from datetime import datetime from collections import defaultdict import csv import json import dexag_client import oneinch_client import paraswap_client import totle_client import exchange_utils from v2_compare_prices import canonicalize_and_...
for file in csv_files: print(f"reading {file} ...") f_exchange, f_token, *_ = os.path.basename(file).split('_') with open(file, newline='') as csvfile: reader = csv.DictReader(csvfile, fieldnames=None) # time,action,trade_size,token,exchange,exchange_price,slippage,co...
tok_ts_ex_pscs = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
random_line_split
data_import.py
#!/usr/local/bin/python3 import functools import glob import os import sys from datetime import datetime from collections import defaultdict import csv import json import dexag_client import oneinch_client import paraswap_client import totle_client import exchange_utils from v2_compare_prices import canonicalize_and_...
(files=None): """Returns an aggregated dict of split data, i.e. token: {trade_size: {agg: [{dex: pct, dex: pct}, {...}, ...]}}""" files = files or glob.glob(f'{JSON_DATA_DIR}/2019*ts_splits_by_agg.json') tok_ts_splits_by_agg = defaultdict(lambda: defaultdict(lambda: defaultdict(list))) for f in files: ...
get_all_splits_by_agg
identifier_name
ourairports.rs
use serde::de::{self, Unexpected}; use serde::{Deserialize, Deserializer, Serialize}; /// Contains a record of a single airport. #[derive(Deserialize, Serialize)] pub struct Airport { /// Internal OurAirports integer identifier for the airport. /// This will stay persistent, even if the airport code changes. ...
<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error> where D: Deserializer<'de>, { let keywords = String::deserialize(deserializer)?; match keywords.len() { 0 => Ok(vec![]), _ => Ok(keywords.split(',').map(|s| s.trim().to_string()).collect()), } }
vec_string_from_string
identifier_name
ourairports.rs
use serde::de::{self, Unexpected}; use serde::{Deserialize, Deserializer, Serialize}; /// Contains a record of a single airport. #[derive(Deserialize, Serialize)] pub struct Airport { /// Internal OurAirports integer identifier for the airport. /// This will stay persistent, even if the airport code changes. ...
/// for voice communication (radio navigation aids appear in struct Navaids) #[derive(Deserialize, Serialize)] pub struct AirportFrequency { /// Internal OurAirports integer identifier for the frequency. /// This will stay persistent, even if the radio frequency or description changes. id: String, /// I...
keywords: Vec<String>, } /// Contains information about a single airport radio frequency
random_line_split
num_format.rs
// This file is part of the uutils coreutils package. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // spell-checker:ignore (vars) charf cninetyninehexfloatf decf floatf intf scif strf Cninety //! handles creating printed output for nu...
(field: &FormatField, in_str_opt: Option<&String>) -> Option<String> { let field_char = field.field_char; // num format mainly operates by further delegating to one of // several Formatter structs depending on the field // see formatter.rs for more details // to do switch to static dispatch le...
num_format
identifier_name
num_format.rs
// This file is part of the uutils coreutils package. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // spell-checker:ignore (vars) charf cninetyninehexfloatf decf floatf intf scif strf Cninety //! handles creating printed output for nu...
// when character constant arguments have excess characters // issue a warning when POSIXLY_CORRECT is not set fn warn_char_constant_ign(remaining_bytes: &[u8]) { match env::var("POSIXLY_CORRECT") { Ok(_) => {} Err(e) => { if let env::VarError::NotPresent = e { show_war...
{ // important: keep println here not print show_error!("{}: expected a numeric value", pf_arg.maybe_quote()); }
identifier_body
num_format.rs
// This file is part of the uutils coreutils package. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // spell-checker:ignore (vars) charf cninetyninehexfloatf decf floatf intf scif strf Cninety //! handles creating printed output for nu...
ret.offset += 1; top_char = str_it.next(); } _ => {} } // we want to exit with offset being // the index of the first non-zero // digit before the decimal point or // if there is none, the zero before the // decimal point, or, if there is none, // the ...
random_line_split
qaoaLibrary.py
#----------------------------------------------------------------------------# # Title: A python helper library for QAOA-type optimization # Author: Aniruddha Bapat # Date: 05-28-2018 # # Description: Here, I will maintain a library of frequently used functions # in QAOA-type optimizations. #---------------------------...
break; maxLength = max(maxLength, len(spline)-1) clauses.append(map(int,spline[:-1])) if len(clauses)!=M: print("Error: Need %d clauses"%M) f.close() const = 0 Bi = np.zeros(n) Jall = [np.zeros([n]*i) for i in range(1,maxLength+1)] for i in range(M): ...
break; if spline[-1]!='0': print("Error: clause descriptions must have a terminal 0")
random_line_split
qaoaLibrary.py
#----------------------------------------------------------------------------# # Title: A python helper library for QAOA-type optimization # Author: Aniruddha Bapat # Date: 05-28-2018 # # Description: Here, I will maintain a library of frequently used functions # in QAOA-type optimizations. #---------------------------...
(n): psi = state() H = ham() qc.allocate(byref(psi),n) qc.allocateH(byref(H),n) return (psi, H) # Generate Ham object from coefficients zzc, xc and zc (given as np arrays) def hamGen(H, zzc, xc, zc): n = len(xc) H.zzc = (c_double * n**2)(*zzc.flatten().tolist()) H.xc ...
initialize
identifier_name
qaoaLibrary.py
#----------------------------------------------------------------------------# # Title: A python helper library for QAOA-type optimization # Author: Aniruddha Bapat # Date: 05-28-2018 # # Description: Here, I will maintain a library of frequently used functions # in QAOA-type optimizations. #---------------------------...
# Set input and return types qc.expectH.restype = c_double qc.overlap.resype = c_double qc.energy.restype = c_double qc.qaoa1energy.restype = c_double # Initialize state and hamiltonian def initialize(n): psi = state() H = ham() qc.allocate(byref(psi),n) qc.allocateH(byref(H),...
"""random displacement with bounds""" def __init__(self, T, stepsize=0.5): self.maxT= T def __call__(self, **kwargs): """take a random step but ensure the new position is within the bounds""" x = kwargs["x_new"] return (sum(x)<self.maxT)
identifier_body
qaoaLibrary.py
#----------------------------------------------------------------------------# # Title: A python helper library for QAOA-type optimization # Author: Aniruddha Bapat # Date: 05-28-2018 # # Description: Here, I will maintain a library of frequently used functions # in QAOA-type optimizations. #---------------------------...
if spline[-1]!='0': print("Error: clause descriptions must have a terminal 0") break; maxLength = max(maxLength, len(spline)-1) clauses.append(map(int,spline[:-1])) if len(clauses)!=M: print("Error: Need %d clauses"%M) f.close() const = 0 ...
print("Error: variable indices must lie between 0 and %d"%n) break;
conditional_block
publish.rs
//! //! The Zargo package manager `publish` subcommand. //! use std::convert::TryFrom; use std::path::PathBuf; use std::str::FromStr; use colored::Colorize; use structopt::StructOpt; use zksync::web3::types::H256; use zksync_eth_signer::PrivateKeySigner; use zksync_types::tx::PackedEthSignature; use crate::error::E...
let verifying_key = VerifyingKeyFile::try_from(&verifying_key_path)?; if !self.quiet { eprintln!( " {} the instance `{}` of `{} v{}` to network `{}`", "Uploading".bright_green(), self.instance, manifest.project.name, ...
{ VirtualMachine::setup_contract( self.verbosity, self.quiet, &binary_path, zinc_const::contract::CONSTRUCTOR_IDENTIFIER, &proving_key_path, &verifying_key_path, )?; }
conditional_block
publish.rs
//! //! The Zargo package manager `publish` subcommand. //! use std::convert::TryFrom; use std::path::PathBuf; use std::str::FromStr; use colored::Colorize; use structopt::StructOpt; use zksync::web3::types::H256; use zksync_eth_signer::PrivateKeySigner; use zksync_types::tx::PackedEthSignature; use crate::error::E...
let initial_transfer = crate::transaction::new_initial( &wallet, response.address, self.change_pubkey_fee_token, response.change_pubkey_fee, ) .await?; let address = response.address; let response = http_client .initial...
let wallet = zksync::Wallet::new(zksync::RpcProvider::new(network.into()), wallet_credentials) .await?;
random_line_split
publish.rs
//! //! The Zargo package manager `publish` subcommand. //! use std::convert::TryFrom; use std::path::PathBuf; use std::str::FromStr; use colored::Colorize; use structopt::StructOpt; use zksync::web3::types::H256; use zksync_eth_signer::PrivateKeySigner; use zksync_types::tx::PackedEthSignature; use crate::error::E...
} impl Command { /// /// A shortcut constructor. /// pub fn new( verbosity: usize, quiet: bool, manifest_path: PathBuf, instance: String, network: Option<String>, change_pubkey_fee_token: Option<String>, ) -> Self { Self { verbosi...
{ Self { address, account_id, } }
identifier_body
publish.rs
//! //! The Zargo package manager `publish` subcommand. //! use std::convert::TryFrom; use std::path::PathBuf; use std::str::FromStr; use colored::Colorize; use structopt::StructOpt; use zksync::web3::types::H256; use zksync_eth_signer::PrivateKeySigner; use zksync_types::tx::PackedEthSignature; use crate::error::E...
{ /// The address of the published contract instance. pub address: zksync_types::Address, /// The account ID of the published contract instance. pub account_id: zksync_types::AccountId, } impl Data { /// /// A shortcut constructor. /// pub fn new(address: zksync_types::Address, account...
Data
identifier_name
process_release_data.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Script to download release files or upload new files in INCOMING folder as release files. It can be run from the command-line. Requires `githubrelease` package to be installed, installable with ``pip install githubrelease``. Download SHA256 hashed files to DOWNLOAD f...
# Upload updated releaes info and new data files # Create hashalgo release (in case it does not exist) github_release.gh_release_create(repo_name, hashalgo, publish=True) # Delete old hashalgo.csv and hashalgo.md github_release.gh_asset_delete(repo_name, hashalgo, hashalgo + ".csv") github_rel...
fileindex.sort(key=lambda a: (a[COLUMN_FILENAME].casefold(), a[COLUMN_FILEDATE])) write_fileindex_csv(hashalgo_csv, fileindex) hashalgo_md = os.path.join(root_dir, hashalgo_dir, hashalgo + ".md") write_fileindex_md(hashalgo_md, fileindex, repo_name, hashalgo)
random_line_split
process_release_data.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Script to download release files or upload new files in INCOMING folder as release files. It can be run from the command-line. Requires `githubrelease` package to be installed, installable with ``pip install githubrelease``. Download SHA256 hashed files to DOWNLOAD f...
: """Context manager for changing the current working directory""" def __init__(self, newPath): self.newPath = os.path.expanduser(newPath) def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype, value, traceback): os.chdir(sel...
cd
identifier_name
process_release_data.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Script to download release files or upload new files in INCOMING folder as release files. It can be run from the command-line. Requires `githubrelease` package to be installed, installable with ``pip install githubrelease``. Download SHA256 hashed files to DOWNLOAD f...
def upload(repo_name, root_dir, incoming_dir, hashalgo, github_token=None): """Upload incoming files associated them with hashalgo release.""" if github_token: github_release._github_token_cli_arg = github_token hashcmd = get_hashcmd(hashalgo) if not hashcmd: raise ValueError('hasha...
"""Download files associated with HASHALGO release into directory (root_dir)/(hashalgo). List of files is taken from (root_dir)/(hashalgo).csv. If multiple hashes associated with the same filename then the last entry will be used. """ if github_token: github_release._github_token_cli_arg = github_tok...
identifier_body
process_release_data.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Script to download release files or upload new files in INCOMING folder as release files. It can be run from the command-line. Requires `githubrelease` package to be installed, installable with ``pip install githubrelease``. Download SHA256 hashed files to DOWNLOAD f...
return fileindex def write_fileindex_csv(hashalgo_csv, fileindex): with open(hashalgo_csv, "wb") as f: for fileindex_item in fileindex: fields = [fileindex_item[COLUMN_CHECKSUM], fileindex_item[COLUMN_FILENAME]] if len(fileindex_item) > COLUMN_FILEDATE: fields....
fields = line.rstrip().split(";") if len(fields) <= COLUMN_FILEDATE: fields.append("") # if date is missing then add an empty field fileindex.append(fields)
conditional_block
model.py
""" Most of the codes are borrowed from https://github.com/huggingface/pytorch-openai-transformer-lm/blob/master/model_pytorch.py """ import copy import json import math import re import numpy as np import torch import torch.nn as nn from torch.nn.parameter import Parameter ############## activation functions ######...
class Block(nn.Module): def __init__(self, n_ctx, cfg, scale=False): super(Block, self).__init__() nx = cfg.n_embd self.attn = Attention(nx, n_ctx, cfg, scale) self.ln_1 = LayerNorm(nx) self.mlp = MLP(4 * nx, cfg) self.ln_2 = LayerNorm(nx) def forward(self, x,...
if pre_sts is None: e = self.drop(self.embed(x)) # Add the position information to the input embeddings h = e.sum(dim=2) # for eval mode else: # get newly added words' embeddings prev_len = pre_sts[0].size(1) e_new = self.drop(self....
identifier_body
model.py
""" Most of the codes are borrowed from https://github.com/huggingface/pytorch-openai-transformer-lm/blob/master/model_pytorch.py """ import copy import json import math import re import numpy as np import torch import torch.nn as nn from torch.nn.parameter import Parameter ############## activation functions ######...
size_out = x.size()[:-1] + (self.nf,) x = torch.addmm(self.b, x.view(-1, x.size(-1)), self.w) x = x.view(*size_out) else: raise NotImplementedError return x class Attention(nn.Module): def __init__(self, nx, n_ctx, cfg, scale=False): super(At...
if self.rf == 1:
random_line_split
model.py
""" Most of the codes are borrowed from https://github.com/huggingface/pytorch-openai-transformer-lm/blob/master/model_pytorch.py """ import copy import json import math import re import numpy as np import torch import torch.nn as nn from torch.nn.parameter import Parameter ############## activation functions ######...
else: raise NotImplementedError return x class Attention(nn.Module): def __init__(self, nx, n_ctx, cfg, scale=False): super(Attention, self).__init__() n_state = nx # in Attention: n_state=768 (nx=n_embd) # [switch nx => n_state from Block to Attention to keep...
size_out = x.size()[:-1] + (self.nf,) x = torch.addmm(self.b, x.view(-1, x.size(-1)), self.w) x = x.view(*size_out)
conditional_block
model.py
""" Most of the codes are borrowed from https://github.com/huggingface/pytorch-openai-transformer-lm/blob/master/model_pytorch.py """ import copy import json import math import re import numpy as np import torch import torch.nn as nn from torch.nn.parameter import Parameter ############## activation functions ######...
(self, x, pre_key=None, pre_value=None): x = self.c_attn(x) query, key, value = x.split(self.split_size, dim=2) query = self.split_heads(query) key = self.split_heads(key, k=True) value = self.split_heads(value) # prevent recalculation if pre_key is not None and p...
forward
identifier_name
manager.rs
use std::rc::Rc; use std::cell::RefCell; use std::path::{Path,PathBuf}; use std::fs; use std::collections::HashMap; use std::io::Write; use Realm; use Result; use Systemd; use RealmSymlinks; use NetworkConfig; use util::*; const REALMS_BASE_PATH: &str = "/realms"; pub struct RealmManager { /// Map from realm na...
fn create_network_config() -> Result<Rc<RefCell<NetworkConfig>>> { let mut network = NetworkConfig::new(); network.add_bridge("clear", "172.17.0.0/24")?; Ok(Rc::new(RefCell::new(network))) } pub fn load() -> Result<RealmManager> { let mut manager = RealmManager::new()?; ...
{ let network = RealmManager::create_network_config()?; Ok(RealmManager { realm_map: HashMap::new(), realm_list: Vec::new(), symlinks: Rc::new(RefCell::new(RealmSymlinks::new())), network: network.clone(), systemd: Systemd::new(network), ...
identifier_body
manager.rs
use std::rc::Rc; use std::cell::RefCell; use std::path::{Path,PathBuf}; use std::fs; use std::collections::HashMap; use std::io::Write; use Realm; use Result; use Systemd; use RealmSymlinks; use NetworkConfig; use util::*; const REALMS_BASE_PATH: &str = "/realms"; pub struct RealmManager { /// Map from realm na...
pub fn set_default_by_name(&self, realm_name: &str) -> Result<()> { self.with_named_realm(realm_name, false, |realm| realm.set_default()) } pub fn realm_name_exists(&self, name: &str) -> bool { self.realm_map.contains_key(name) } pub fn realm(&self, name: &str) -> Option<&Realm> { ...
random_line_split
manager.rs
use std::rc::Rc; use std::cell::RefCell; use std::path::{Path,PathBuf}; use std::fs; use std::collections::HashMap; use std::io::Write; use Realm; use Result; use Systemd; use RealmSymlinks; use NetworkConfig; use util::*; const REALMS_BASE_PATH: &str = "/realms"; pub struct RealmManager { /// Map from realm na...
(&mut self, realm: Realm) -> &Realm { self.realm_map.insert(realm.name().to_owned(), realm.clone()); self.realm_list.push(realm.clone()); self.realm_map.get(realm.name()).expect("cannot find realm we just added to map") } fn remove_realm_entry(&mut self, name: &str) -> Result<()> { ...
add_realm_entry
identifier_name
Multiple_PhotometryConstruction.py
import os import re import numpy as np import pandas as pd import pymysql import mysql.connector from mysql.connector import errorcode from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Float, Date, PrimaryKeyConstraint, VARCHAR, insert from sqlalchemy.ext.automap import automap_base from...
(s,f,import_tdt): eventsA = [] eventsB = [] if '&' in f: subjs = f.split() subjs.remove('&') else: subjs = [f] if len(subjs) == 1: test465A = import_tdt.streams['_465A'].data[1000] test465C = import_tdt.streams['_465C'].data[1000] if test465A > test46...
pulleventdata
identifier_name
Multiple_PhotometryConstruction.py
import os import re import numpy as np import pandas as pd import pymysql import mysql.connector from mysql.connector import errorcode from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Float, Date, PrimaryKeyConstraint, VARCHAR, insert from sqlalchemy.ext.automap import automap_base from...
def evaluate_rawdata(time,Subjects_465,Subjects_405, subjs): trim = [] note = [] if len(Subjects_465) == 1: fig1 = plt.figure() plt.plot(time[0],Subjects_465[0].data, color='green', label = 'Gcamp6f') plt.plot(time[0],Subjects_405[0].data, color='blueviolet', label = 'ISOS') ...
timex = [] if len(s465) == 1: timex.append(np.linspace(1,len(s465[0].data), len(s465[0].data))/s465[0].fs) else: for i in range(0, len(s465)): timex.append(np.linspace(1,len(s465[i].data), len(s465[i].data))/s465[i].fs) return timex
identifier_body
Multiple_PhotometryConstruction.py
import os import re import numpy as np import pandas as pd import pymysql import mysql.connector from mysql.connector import errorcode from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Float, Date, PrimaryKeyConstraint, VARCHAR, insert from sqlalchemy.ext.automap import automap_base from...
y_all.append(np.multiply(baseline[0][0], np.array(trimmed_s405[0])) + baseline[0][1]) y_df.append(np.array(trimmed_s465[0]) - y_all[0]) dFF.append(np.multiply(100,np.divide(y_df[0],y_all[0]))) std_dFF.append(np.std(dFF[0])) else: for i in range(0, len(s465)): s_in...
#process data baseline.append(np.polyfit(np.array(trimmed_s405[0]), np.array(trimmed_s465[0]), 1))
random_line_split
Multiple_PhotometryConstruction.py
import os import re import numpy as np import pandas as pd import pymysql import mysql.connector from mysql.connector import errorcode from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Float, Date, PrimaryKeyConstraint, VARCHAR, insert from sqlalchemy.ext.automap import automap_base from...
return event_list_dict def send_events(event_list_dict): md= MetaData(engine) test_conn = engine.connect() if not engine.dialect.has_table(test_conn,'eventdata'): eventdata = Table('eventdata', md, Column('idx', Integer, primary_key=True, nullable=False, autoincrement=True), ...
for e in all_events[i]: subject_list = [int(subjects[i])]*len(e.onset) session_list = [s]*len(e.onset) name_list = [e.name]*len(e.onset) onset_list = e.onset.tolist() offset_list = e.offset.tolist() for j in range(0,len(onse...
conditional_block
apps.go
package commands import ( "bytes" "encoding/json" "fmt" "io" "log" "os" "os/exec" "strconv" "strings" "time" "github.com/olekukonko/tablewriter" "github.com/section/sectionctl/api" ) // AppsCmd manages apps on Section type AppsCmd struct { List AppsListCmd `cmd help:"List apps on Section." default:"...
() (err error) { var aids []int if c.AccountID == 0 { s := NewSpinner("Looking up accounts") s.Start() as, err := api.Accounts() if err != nil { return fmt.Errorf("unable to look up accounts: %w", err) } for _, a := range as { aids = append(aids, a.ID) } s.Stop() } else { aids = append(aids...
Run
identifier_name
apps.go
package commands import ( "bytes" "encoding/json" "fmt" "io" "log" "os" "os/exec" "strconv" "strings" "time" "github.com/olekukonko/tablewriter" "github.com/section/sectionctl/api" ) // AppsCmd manages apps on Section type AppsCmd struct { List AppsListCmd `cmd help:"List apps on Section." default:"...
() } fmt.Println() return err } // AppsCreateCmd handles creating apps on Section type AppsCreateCmd struct { AccountID int `required short:"a" help:"ID of account to create the app under"` Hostname string `required short:"d" help:"FQDN the app can be accessed at"` Origin string `required short:"o" help...
ing{p.Name, p.Image} table.Append(r) } table.Render
conditional_block
apps.go
package commands import ( "bytes" "encoding/json" "fmt" "io" "log" "os" "os/exec" "strconv" "strings" "time" "github.com/olekukonko/tablewriter" "github.com/section/sectionctl/api" ) // AppsCmd manages apps on Section type AppsCmd struct { List AppsListCmd `cmd help:"List apps on Section." default:"...
// Run executes the command func (c *AppsListCmd) Run() (err error) { var aids []int if c.AccountID == 0 { s := NewSpinner("Looking up accounts") s.Start() as, err := api.Accounts() if err != nil { return fmt.Errorf("unable to look up accounts: %w", err) } for _, a := range as { aids = append(aid...
{ t = tablewriter.NewWriter(out) t.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false}) t.SetCenterSeparator("|") t.SetAlignment(tablewriter.ALIGN_LEFT) return t }
identifier_body
apps.go
package commands import ( "bytes" "encoding/json" "fmt" "io" "log" "os" "os/exec" "strconv" "strings" "time" "github.com/olekukonko/tablewriter" "github.com/section/sectionctl/api" ) // AppsCmd manages apps on Section type AppsCmd struct { List AppsListCmd `cmd help:"List apps on Section." default:"...
s.Stop() if err != nil { if err == api.ErrStatusForbidden { stacks, herr := api.Stacks() if herr != nil { return fmt.Errorf("unable to query stacks: %w", herr) } for _, s := range stacks { if s.Name == c.StackName { return err } } return fmt.Errorf("bad request: unable to find sta...
api.Timeout = 120 * time.Second // this specific request can take a long time r, err := api.ApplicationCreate(c.AccountID, c.Hostname, c.Origin, c.StackName)
random_line_split
Week_05.py
# Functions """ Functions give us the ability to make our programs much more powerful and clean while also saving us time. We use functions is because of the ability to write once and call repeatedly. Overview • How to use functions and what they are • Passing data around using parameters • Returning data from functi...
input("Enter your name") checkCaps(name) """ 2. No Name: Define a function that takes in two arguments, first_name and last_ name, and makes both optional. If no values are passed into the parameters, it should output “No name passed in”; otherwise, it should print out the name. """ # solution # def checkName(first_...
se") name =
conditional_block
Week_05.py
# Functions """ Functions give us the ability to make our programs much more powerful and clean while also saving us time. We use functions is because of the ability to write once and call repeatedly. Overview • How to use functions and what they are • Passing data around using parameters • Returning data from functi...
.5) # *args """ The use of *args allows you to pass a variable number of arguments into a function. This allows you to make functions more modular. The magic isn’t the “args” keyword here though; it’s really the unary operator ( * ) that allows us to perform this feature. You could theoretically replace the word args ...
t(num1) addNums(5, num2=2
identifier_body
Week_05.py
# Functions """ Functions give us the ability to make our programs much more powerful and clean while also saving us time. We use functions is because of the ability to write once and call repeatedly. Overview • How to use functions and what they are • Passing data around using parameters • Returning data from functi...
outputData("John Smith", 5, True, "Jess") # **kwargs """ Like args, kwargs allows us to take in an arbitrary number of values in a function; however, it works as a dictionary with keyword arguments instead. Keyword arguments are values passed in with keys, which allow us to access them easily within the function bl...
def outputData(name, *args): print(type(args)) for arg in args: print(arg)
random_line_split
Week_05.py
# Functions """ Functions give us the ability to make our programs much more powerful and clean while also saving us time. We use functions is because of the ability to write once and call repeatedly. Overview • How to use functions and what they are • Passing data around using parameters • Returning data from functi...
print("Your name is: {}".format(full_name)) printName("John Smith") printName("Amanda") # Multiple parameters # passing multiple parameters into a function def addNums(num1, num2): result = num1+num2 print("{} + {} = {}".format(num1, num2, result)) addNums(5, 8) addNums(3.5, 5.5) # passing a list # ...
ll_name):
identifier_name
controller.go
/* Copyright 2018 The Rook Authors. 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 ...
(mode string) error { switch s.ToLower(mode) { case "readonly": case "readwrite": case "none": default: return fmt.Errorf("Invalid value (%s) for accessMode, valid values are (ReadOnly, ReadWrite, none)", mode) } return nil } func validateSquashMode(mode string) error { switch s.ToLower(mode) { case "none":...
validateAccessMode
identifier_name
controller.go
/* Copyright 2018 The Rook Authors. 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 ...
{ switch s.ToLower(mode) { case "none": case "rootid": case "root": case "all": default: return fmt.Errorf("Invalid value (%s) for squash, valid values are (none, rootId, root, all)", mode) } return nil }
identifier_body
controller.go
/* Copyright 2018 The Rook Authors. 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 ...
} // Controller represents a controller object for nfs server custom resources type Controller struct { context *clusterd.Context containerImage string } // NewController create controller for watching nfsserver custom resources created func NewController(context *clusterd.Context, containerImage string) *Co...
Group: nfsv1alpha1.CustomResourceGroup, Version: nfsv1alpha1.Version, Scope: apiextensionsv1beta1.NamespaceScoped, Kind: reflect.TypeOf(nfsv1alpha1.NFSServer{}).Name(),
random_line_split
controller.go
/* Copyright 2018 The Rook Authors. 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 ...
return pvcNameList } func createPVCSpecList(spec *nfsv1alpha1.NFSServerSpec) []v1.Volume { pvcSpecList := make([]v1.Volume, 0) pvcNameList := getPVCNameList(spec) for _, claimName := range pvcNameList { pvcSpecList = append(pvcSpecList, v1.Volume{ Name: claimName, VolumeSource: v1.VolumeSource{ Persi...
{ claimName := export.PersistentVolumeClaim.ClaimName if claimName != "" { pvcNameList = append(pvcNameList, claimName) } }
conditional_block
role_conversion.py
#!/usr/bin/env python2.5 # # Copyright 2011 the Melange 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 applic...
def updateStudentProposalReferences(request): """Starts a bunch of iterative tasks which update references in StudentProposals. """ return updateReferencesForModel('student_proposal') def updateReferences(request): """Starts a bunch of iterative tasks which update references to various roles. """ #...
"""Starts a bunch of iterative tasks which update references in StudentProjects. """ return updateReferencesForModel('student_project')
identifier_body
role_conversion.py
#!/usr/bin/env python2.5 # # Copyright 2011 the Melange 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 applic...
(request): """Starts a task which updates Host entities. """ updater = HostUpdater() updater.run() return http.HttpResponse("Ok") def updateRole(role_name): """Starts a task which updates a particular role. """ if role_name == 'gsoc_mentor': updater = RoleUpdater(GSoCMentor, GSoCProfile, 'progra...
updateHosts
identifier_name
role_conversion.py
#!/usr/bin/env python2.5 # # Copyright 2011 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """...
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #
random_line_split