file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
scanner.rs
#[derive(Debug, Default, Copy, Clone)] #[cfg_attr(feature = "json", derive(serde_derive::Serialize))] pub struct Stats { pub added: usize, pub skipped: usize, pub dupes: usize, pub bytes_deduplicated: usize, pub hardlinks: usize, pub bytes_saved_by_hardlinks: usize, } pub trait ScanListener: De...
Ok(()) } fn add(&mut self, path: Box<Path>, metadata: &fs::Metadata) -> io::Result<()> { self.scan_listener.file_scanned(&path, &self.stats); let ty = metadata.file_type(); if ty.is_dir() { // Inode is truncated to group scanning of roughly close inodes together, ...
{ // Errors are ignored here, since it's super common to find permission denied and unreadable symlinks, // and it'd be annoying if that aborted the whole operation. // FIXME: store the errors somehow to report them in a controlled manner for entry in fs::read_dir(path)?.filter_map(|p| p...
identifier_body
scanner.rs
#[derive(Debug, Default, Copy, Clone)] #[cfg_attr(feature = "json", derive(serde_derive::Serialize))] pub struct Stats { pub added: usize, pub skipped: usize, pub dupes: usize, pub bytes_deduplicated: usize, pub hardlinks: usize, pub bytes_saved_by_hardlinks: usize, } pub trait ScanListener: De...
(&mut self, fileset: RcFileSet, path: Box<Path>, metadata: &fs::Metadata) -> io::Result<()> { let mut deferred = false; match self.by_content.entry(FileContent::new(path, Metadata::new(metadata))) { BTreeEntry::Vacant(e) => { // Seems unique so far e.insert(ve...
dedupe_by_content
identifier_name
index.js
{ canHandle(handlerInput) { return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest'; }, handle(handlerInput) { const speakOutput = 'Hello! Welcome to Caketime. What is your birthday?'; const repromptText = 'I was born Nov. 6th, 2014. When were you born?'; ...
(handlerInput) { const speakOutput = 'Goodbye!'; return handlerInput.responseBuilder .speak(speakOutput) .getResponse(); } }; /* * * FallbackIntent triggers when a customer says something that doesn’t map to any intents in your skill * It must also be defined in the langua...
handle
identifier_name
index.js
canHandle(handlerInput)
, handle(handlerInput) { const speakOutput = 'Hello! Welcome to Caketime. What is your birthday?'; const repromptText = 'I was born Nov. 6th, 2014. When were you born?'; return handlerInput.responseBuilder .speak(speakOutput) .reprompt(repromptText) .get...
{ return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest'; }
identifier_body
index.js
{ canHandle(handlerInput) { return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest'; }, handle(handlerInput) { const speakOutput = 'Hello! Welcome to Caketime. What is your birthday?'; const repromptText = 'I was born Nov. 6th, 2014. When were you born?'; ...
.speak(speakOutput) //.reprompt('add a reprompt if you want to keep the session open for the user to respond') .getResponse(); } }; /** * Generic error handling to capture any syntax or routing errors. If you receive an error * stating the request handler chain is not found, yo...
const intentName = Alexa.getIntentName(handlerInput.requestEnvelope); const speakOutput = `You just triggered ${intentName}`; return handlerInput.responseBuilder
random_line_split
index.js
canHandle(handlerInput) { return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest'; }, handle(handlerInput) { const speakOutput = 'Hello! Welcome to Caketime. What is your birthday?'; const repromptText = 'I was born Nov. 6th, 2014. When were you born?'; ...
return handlerInput.responseBuilder .speak(speakOutput) .getResponse(); } }; const CaptureBirthdayIntentHandler = { canHandle(handlerInput) { return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest' && Alexa.getIntentName(handlerInput.r...
{ const diffDays = Math.round(Math.abs((currentDate.getTime() - nextBirthdayDate.getTime()) / oneDay)); speakOutput = `Welcome back. It looks like there are ${diffDays} days until your ${nextBirthdayDate.getFullYear() - year}th birthday.` }
conditional_block
Trainer.py
we want to skip IO with the original file (only will use IO with the neural network training data) ONLY_TRAIN_NN = False # Path of the neural network training data PATH_REPLACE_DATA = FILE_NAME + '.replace.txt' PATH_ARRANGE_DATA = FILE_NAME + '.arrange.txt' def main(): # .spacy.txt is a pre-processed file conta...
(): # create the dataset samples = 0 max_length = 0 if ENABLE_PROCESS_ARRANGE_DATA: # saves the data to a file assert len(train_arrange_x) == len(train_arrange_y) max_length = len(max(train_arrange_x, key=len)) samples = len(train_arrange_x) with open(PATH_ARRANGE...
train_arrange_nn
identifier_name
Trainer.py
we want to skip IO with the original file (only will use IO with the neural network training data) ONLY_TRAIN_NN = False # Path of the neural network training data PATH_REPLACE_DATA = FILE_NAME + '.replace.txt' PATH_ARRANGE_DATA = FILE_NAME + '.arrange.txt' def main(): # .spacy.txt is a pre-processed file conta...
with open(PATH_REPLACE_DATA) as file_replace: max_start, max_end, samples = list(map(int, file_replace.readline().strip().split())) dataset = tf.data.Dataset.from_generator(replace_nn_generator, ({'start': tf.int32, 'end': tf.int32, 'delta': tf.int32}, tf.f...
with open(PATH_REPLACE_DATA) as file_replace: file_replace.readline() for replace_line in file_replace: start, end, delta1, delta2 = replace_line.rstrip().split('\t') start = list(map(int, start.split())) end = list(map(int, end.split())) ...
identifier_body
Trainer.py
when we want to skip IO with the original file (only will use IO with the neural network training data) ONLY_TRAIN_NN = False # Path of the neural network training data PATH_REPLACE_DATA = FILE_NAME + '.replace.txt' PATH_ARRANGE_DATA = FILE_NAME + '.arrange.txt' def main(): # .spacy.txt is a pre-processed file ...
line = line.strip() line = unicodedata.normalize('NFKD', line) p1, p2 = line.split('\t') t1, t2 = line_tag.split('\t') error_type = ErrorClassifier.classify_error_labeled(p1, p2) train(p1, p2, error_type, t1, t2) ...
continue
conditional_block
Trainer.py
when we want to skip IO with the original file (only will use IO with the neural network training data) ONLY_TRAIN_NN = False # Path of the neural network training data PATH_REPLACE_DATA = FILE_NAME + '.replace.txt' PATH_ARRANGE_DATA = FILE_NAME + '.arrange.txt' def main(): # .spacy.txt is a pre-processed file ...
def save_word_frequencies(): with open('learned_frequencies.csv', 'w', newline='') as fout: csv_writer = csv.writer(fout) for word, freq in word_freqs.items(): # don't bother with the little words if freq > 1: csv_writer.writerow([word, freq]) test1 = 0 te...
word_freqs[word] = 1
random_line_split
__init__.py
changing ip.') return except KeyError: print(f"Valid response from {self.url}") else: page_parsed = args[0] write_to = kwargs.get('write_to') # Save html to file if write_to: my_file = Path(write_to) ...
def print_binary_and_numeric_options(search_options): print("\n") for option_title, option_value in search_options['Filters'].items(): print("\t" + option_title + ":") print("\t-----") for option, option_api_value in option_value.items(): print("...
print("\t" + option_title + ":") print("\t-----") print("\t\t URL key:", "'" + option_value['url_key'] + "'") print("\t\t URL key options:") for option, option_api_value in option_value['value'].items(): print("\t\t\t* " + option + ":", "'" + option_api_va...
conditional_block
__init__.py
to", search_example['description'], search_example['url_key']) print("\n") def print_choice(selection_labels): print("What filters do you wnt to know about (quit with 'q')?") print( "1. Sort options \n2. Property types \n3. Price, size and number of rooms \n4. Kitchen and heati...
print_binary_and_numeric_options(eval(selection))
random_line_split
__init__.py
# Check validity of the page try: if page_parsed.find('meta').attrs['name'] == 'robots': print('ERROR: invalid result page - They might have detected the crawler, try changing ip.') return except KeyError: print...
""" Retrieve search parameters from the html page of a search on Seloger.com :param search_url: The page url is passed as an input (True) or a parsed page (False). :param args: A BeautifulSoup parsed page. :param kwargs: write_to: a string with the path and name of a file to ...
identifier_body
__init__.py
(object): """ Base class for all Seloger wrapper Parameters ---------- class_filters : dict Main search options ex. {'transaction_type':['achat'], 'bien': ['appartement', 'maison'], 'naturebien': ['ancien', 'neuf']} type_of_search: str Can be either 'base', for ads of pr...
SelogerBase
identifier_name
PositionAPI.py
,header=header) listdata=info.mysplider.tableTolistByNum(html,"DCE",1) """write to database""" for i in listdata[1:-1]: # col=[] # excelcol=[] Rank=i[0] if str(Rank).strip()=="": if str(i[4]).strip() != "": Rank=str(i[4]).strip() if st...
ksheet = writer.sheets['Sheet1'] worksheet.set_column('A:J', 15) # Add a header format. header_format = workbook.add_format({ 'bold': True, 'text_wrap': True, 'valign': 'vcenter', 'border': 1 }) header_format.set_align('center') header_format.set_align('vcenter')...
= writer.book wor
conditional_block
PositionAPI.py
"总计") == -1: if "null" not in i: InstrumentID = info.StagePositionCode Rank = str(i[0]).strip() Type = '0' ParticipantID1 = str(i[1]).strip() ParticipantABBR1 = str(i[2]).strip() CJ1 = str(i[3]).s...
random_line_split
PositionAPI.py
if str(i[4]).strip() != "": Rank=str(i[4]).strip() if str(i[8]).strip() != "": Rank = str(i[8]).strip() if Rank=="": continue ExchangeID='DCE' ParticipantABBR1=i[1] CJ1=i[2] CJ1_CHG=i[3] ParticipantABBR2=i[5...
ent': 'Mozilla/
identifier_name
PositionAPI.py
'Connection': 'keep-alive', 'Cache-Control': 'no-cache', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36', 'Acc...
identifier_body
ch8.go
() { // n.Add(1) // subdir := filepath.Join(dir, entry.Name()) // go walkDir(subdir, n, fileSizes) // } else { // fileSizes <- entry.Size() // } // } // } // var sema = make(chan struct{}, 20) // func dirents(dir string) []os.FileInfo { // sema <- struct{}{} // acquire token // defer func() ...
// "log" // "gopl.io/ch5/links" // ) // // tokens a counting semaphore used to enforce a limit of 20 concurrent requests // var tokens = make(chan struct{}, 20) // func crawl(url string) []string { // fmt.Println(url) // tokens <- struct{}{} // list, err := links.Extract(url) // <-tokens // release the token /...
// } // import ( // "fmt"
random_line_split
ch8.go
func handleConn(conn net.Conn) { ch := make(chan string) go clientWriter(conn, ch) who := conn.RemoteAddr().String() ch <- "You are " + who messages <- who + " has arrived" entering <- ch input := bufio.NewScanner(conn) for input.Scan() { messages <- who + ": " + input.Text() } // NOTE: ignoreing potent...
{ clients := make(map[client]bool) // all connected clients for { select { case msg := <-messages: // Broadcase incoming message to all // clients' outgoing message channels. for cli := range clients { cli <- msg } case cli := <-entering: clients[cli] = true case cli := <-leaving: delete...
identifier_body
ch8.go
() { listener, err := net.Listen("tcp", "localhost: 8000") if err != nil { log.Fatal(err) } go broadcaster() for { conn, err := listener.Accept() if err != nil { log.Print(err) continue } go handleConn(conn) } } type client chan<- string // an outgoing message channel var ( entering = make(chan...
main
identifier_name
ch8.go
// NOTE: ignoreing potentian errors from input.Err() leaving <- ch messages <- who + " has left" conn.Close() } func clientWriter(conn net.Connj, ch <-chan string) { for msg := range ch { fmt.Fprintln(conn, msg) // NOTE: ignoring network errors } } // var done = make(chan struct{}) // func cancelled() bool ...
{ messages <- who + ": " + input.Text() }
conditional_block
server.rs
rored(io::ErrorKind), } pub struct Server { size: usize, msg_sender: Sender<Message>, msg_recver: Receiver<Message>, handlers: HashMap<Id, Handler>, cmd_handler: CommandHandler, } impl Server { pub fn init(size: usize, cmd_prefix: char) -> ServerResult<Server> { if size == 0 { ...
(&self) -> Vec<usize> { use self::FinishedStatus::*; use self::HandlerAsync::*; self.handlers .iter() .filter(|(id, handler)| { if let Finished(status) = handler.check_status() { match status { TimedOut => { ...
check_handlers
identifier_name
server.rs
rored(io::ErrorKind), } pub struct Server { size: usize, msg_sender: Sender<Message>, msg_recver: Receiver<Message>, handlers: HashMap<Id, Handler>, cmd_handler: CommandHandler, } impl Server { pub fn init(size: usize, cmd_prefix: char) -> ServerResult<Server> { if size == 0 { ...
msg_sender, msg_recver, handlers, cmd_handler, }) } #[allow(unused)] pub fn from_cfg() -> Result<Server, &'static str> { unimplemented!(); } pub fn cmd<C: Command + 'static>(mut self, name: &'static str, command: C) -> Self { ...
Ok(Server { size,
random_line_split
main.rs
( device: &wgpu::Device, layout: &wgpu::PipelineLayout, color_format: wgpu::TextureFormat, depth_format: Option<wgpu::TextureFormat>, vertex_descs: &[wgpu::VertexBufferDescriptor], vs_src: wgpu::ShaderModuleSource, fs_src: wgpu::ShaderModuleSource, ) -> wgpu::RenderPipeline { // Create S...
create_render_pipeline
identifier_name
main.rs
Instance { position, rotation } }) }) .collect::<Vec<_>>(); let instance_data = instances.iter().map(Instance::to_raw).collect::<Vec<InstanceRaw>>(); let instance_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor{ label: Some("i...
state.resize(physical_size) }, WindowEvent::ScaleFactorChanged {new_inner_size, ../*scale_factor*/ } => { state.resize(*new_inner_size) },
random_line_split
main.rs
gpu::TextureViewDimension::D2, component_type: wgpu::TextureComponentType::Uint, }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStage::FRAGMENT, ...
{ self.camera_controller.process_scroll(delta); true }
conditional_block
assethook.py
current application context. """ if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db def init_db(): """Initialized the db file""" db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() ...
if r.status_code == 200: device_type_xml = 'mobile_device' device_type_url = 'mobiledevices' device_type = 'MobileDevice' if device_type is None: url = settings_dict['jsshost'] + ':' + settings_dict['jss_port'] + settings_dict['jss_path'] + \ '/JSSRes...
'/JSSResource/mobiledevices/serialnumber/' + serial_number r = requests.get(url, auth=(settings_dict['jss_username'], settings_dict['jss_password']))
random_line_split
assethook.py
application context. """ if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db def init_db(): """Initialized the db file""" db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() @app.cli...
(): """Initializes the database.""" init_db() print('Initialized the database.') def load_settings(): '''Loads settings from the database, if the table is empty, it will be initalized ''' db = get_db() try: cur = db.execute('select setting_name, setting_value from settings') ...
initdb_command
identifier_name
assethook.py
application context. """ if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db def init_db():
@app.cli.command('initdb') # if you want to do it from the command line def initdb_command(): """Initializes the database.""" init_db() print('Initialized the database.') def load_settings(): '''Loads settings from the database, if the table is empty, it will be initalized ''' db = get...
"""Initialized the db file""" db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit()
identifier_body
assethook.py
() v = [('jsshost', ''), ('jss_path', ''), ('jss_port', ''), ('jss_username', ''), ('jss_password', ''), ('set_name', '')] db.executemany( """insert into settings ('setting_name', 'setting_value') values (?,?)""", v) db.commit() def write_settings(_request): '''Write settings to the d...
device_type = 'MobileDevice'
conditional_block
lib.rs
VarName("".to_string()); } else { regex.push(byte); format_str.push(byte); parse_state = ParseState::Static; } } ParseState::VarName(mut name) => { if byte == '/' { // Validate 'name' as a Rust identifier if !ident_regex.is_match(&name) { return Err(RouteToRegexError::In...
st_route_to_regex_characters_after_wildcard() { let regex = route_to_regex("/p/:project_id/exams/:exam*ID/submissions_expired"); assert_eq!( regex, Err(RouteToRegexError::CharactersAfterWildcard) ); } #[test] fn test_route_to_regex_invalid_ending() { let regex = route_to_regex("/p/:project_id/exams/:exam_id/su...
route_to_regex("/p/:project_id/exams/:_exam_id/submissions_expired"); assert_eq!( regex, Err(RouteToRegexError::InvalidIdentifier("_exam_id".to_string())) ); } #[test] fn te
identifier_body
lib.rs
_expired"); assert_eq!( regex, Err(RouteToRegexError::InvalidIdentifier("_exam_id".to_string())) ); } #[test] fn test_route_to_regex_characters_after_wildcard() { let regex = route_to_regex("/p/:project_id/exams/:exam*ID/submissions_expired"); assert_eq!( regex, Err(RouteToRegexError::CharactersAfterWildca...
if query_string.starts_with('?') { query_string = &query_string[1..];
random_line_split
lib.rs
Name("".to_string()); } else { regex.push(byte); format_str.push(byte); parse_state = ParseState::Static; } } ParseState::VarName(mut name) => { if byte == '/' { // Validate 'name' as a Rust identifier if !ident_regex.is_match(&name) { return Err(RouteToRegexError::Inval...
ta) -> Vec<syn::Field> { match data { syn::Data::Struct(data_struct) => match data_struct.fields { syn::Fields::Named(ref named_fields) => named_fields.named.iter().cloned().collect(), _ => panic!("Struct fields must be named"), }, _ => panic!("AppRoute derive is only supported for structs"), } } fn fiel...
ds(data: &syn::Da
identifier_name
lib.rs
VarName("".to_string()); } else { regex.push(byte); format_str.push(byte); parse_state = ParseState::Static; } } ParseState::VarName(mut name) => { if byte == '/' { // Validate 'name' as a Rust identifier if !ident_regex.is_match(&name)
regex += &format!("(?P<{}>[^/]+)/", name); format_str += &format!("{}}}/", name); parse_state = ParseState::Static; } else if byte == '*' { // Found a wildcard - add the var name to the regex // Validate 'name' as a Rust identifier if !ident_regex.is_match(&name) { return Err(...
{ return Err(RouteToRegexError::InvalidIdentifier(name)); }
conditional_block
dockeranchor.js
ime) { return new Promise((resolve) => { setTimeout(resolve, time); }) } const splitEx = /(["'].*?["']|[^"'\s]+)/g function splitCommands(str) { return str.match(splitEx).map( (el) => el.replace(/^["']|["']$/g, '') ); } async function pingDocker() { try{ const info = await docker.info(); return[true, ...
yncWait(t
identifier_name
dockeranchor.js
If it's 0, problem is with the executed program (normal CE) */ async function compile(comp, file, _outfile) { return new Promise(async (resolve, reject) => { var logs = '' let container try { const fileBasename = path.basename(file) const fileDirname = path.dirname(file) const outfile = _outfile || f...
const infilename = fileBasename;//infile.replace(pathToFile, '') let stdininfilename = ''; if(stdinfile)stdininfilename = path.basename(stdinfile); console.log(`Let's execute! ${fileBasename}`); if((await pingDocker())[0] == false){ reject([1, 'Cannot reach docker machine']); return; } ...
const fileBasename = path.basename(infile); const fileDirname = path.dirname(infile); const tarfile = `${fileDirname}/${crypto.randomBytes(10).toString('hex')}.tar`;
random_line_split
dockeranchor.js
Function('return `' + template + '`;').call(vars) })(compilerInstance.exec_command, { file: fileBasename }).split(' ').map(el => el.replace(/_/g, ' ')), // file name could be required to be first argument or appear more than once in compiler commands of some weird languages :D AttachStdout: false, Atta...
return new Promise(async (resolve, reject) => { const _execInstance = await execenv.findOne({ name: exname }); const opts = optz || {}; if (!_execInstance) { reject([1, 'Invalid ExecEnv']); return; } let _container try { const fileBasename = path.basename(infile); const fileDirname = pat...
identifier_body
dockeranchor.js
. If it's 0, problem is with the executed program (normal CE) */ async function compile(comp, file, _outfile) { return new Promise(async (resolve, reject) => { var logs = '' let container try { const fileBasename = path.basename(file) const fileDirname = path.dirname(file) const outfile = _outfile || ...
var _unpromStream = await _container.fs.put(tarfile, { path: '.' }) await promisifyStreamNoSpam(_unpromStream); await unlinkAsync(tarfile); await _container.start(); //await _container.wait(); await asyncWait(_execInstance.time); const inspection = await _container.status(); if (inspect...
/*console.log("Redirecting input."); var [_stdinstream,] = await _container.attach({ stream: true, stderr: true }); var _fstrm = fs.createReadStream(stdinfile); _fstrm.pipe(_stdinstream) //readable->writable await promisifyStream(_fstrm);*/ await tar.r({ file: tarfile, cwd: fileDirnam...
conditional_block
Employees.component.ts
"qCommon/app/services/DateFormatter.service"; import {ReportService} from "reportsUI/app/services/Reports.service"; declare var jQuery:any; declare var _:any; @Component({ selector: 'employees', templateUrl: '../views/employees.html' }) export class EmployeesComponent { tableData:any = {}; tableOptions:any ...
getEmployeesTableData(inputData) { let tempData = _.cloneDeep(inputData); let newTableData: Array<any> = []; let temp
{ this.titleService.setPageTitle("Employees"); this.row = {}; this.showFlyout = !this.showFlyout; }
identifier_body
Employees.component.ts
"qCommon/app/services/DateFormatter.service"; import {ReportService} from "reportsUI/app/services/Reports.service"; declare var jQuery:any; declare var _:any; @Component({ selector: 'employees', templateUrl: '../views/employees.html' }) export class EmployeesComponent { tableData:any = {}; tableOptions:any ...
() { this.active = false; setTimeout(()=> this.active=true, 0); } handleError(error) { this.loadingService.triggerLoadingEvent(false); this._toastService.pop(TOAST_TYPE.error, "Failed To Perform Operation"); } hideFlyout(){ this.titleService.setPageTitle("Employees"); this.row = {}; ...
newCustomer
identifier_name
Employees.component.ts
"qCommon/app/services/DateFormatter.service"; import {ReportService} from "reportsUI/app/services/Reports.service"; declare var jQuery:any; declare var _:any; @Component({ selector: 'employees', templateUrl: '../views/employees.html' }) export class EmployeesComponent { tableData:any = {}; tableOptions:any ...
this.routeSubscribe = switchBoard.onClickPrev.subscribe(title => { if(this.showFlyout){ this.hideFlyout(); }else { this.toolsRedirect(); } }); } toolsRedirect(){ let link = ['tools']; this._router.navigate(link); } ngOnDestroy(){ this.routeSubscribe.unsu...
{ this._toastService.pop(TOAST_TYPE.error, "Please Add Company First"); }
conditional_block
Employees.component.ts
"qCommon/app/services/DateFormatter.service"; import {ReportService} from "reportsUI/app/services/Reports.service"; declare var jQuery:any; declare var _:any; @Component({ selector: 'employees', templateUrl: '../views/employees.html' }) export class EmployeesComponent { tableData:any = {}; tableOptions:any ...
let link = ['tools']; this._router.navigate(link); } ngOnDestroy(){ this.routeSubscribe.unsubscribe(); this.confirmSubscription.unsubscribe(); } buildTableData(employees) { this.employees = employees; this.hasEmployeesList = false; this.tableOptions.search = true; this.tableOp...
}); } toolsRedirect(){
random_line_split
gestalt.go
ations \ // include whitespace leading each new line. # e.g. this line appends " include whitespace ..." // // # ------------------------------------------ // # examples of []string properties - single line // # NOTE that the key includes the trailing `[]` // // this.is.a.string.array.key[] = alpha...
urns nil/zero-value if no such key or not a map, or if key type is not map func (p Properties) GetMap(key string) map[string]string { if isMapKey(key) { if v := p[key]; v == nil { return nil } return p[key].(map[string]string) } return nil } // returns prop value or default values if nil func (p Properties...
= p.GetArray(key); v == nil { v = defval } return } // ret
identifier_body
gestalt.go
continuations \ // include whitespace leading each new line. # e.g. this line appends " include whitespace ..." // // # ------------------------------------------ // # examples of []string properties - single line // # NOTE that the key includes the trailing `[]` // // this.is.a.string.array.key[]...
} // Return a clone of the argument Properties object func (p Properties) Clone() (clone Properties) { for k, v := range p { clone[k] = v } return } // Copy all entries from specified Properties to the receiver // Note this will overwrite existing matching values if overwrite is true, // otherwise if overwrite ...
return loadBuffer(spec)
random_line_split
gestalt.go
ations \ // include whitespace leading each new line. # e.g. this line appends " include whitespace ..." // // # ------------------------------------------ // # examples of []string properties - single line // # NOTE that the key includes the trailing `[]` // // this.is.a.string.array.key[] = alpha...
n p[key].([]string) } return nil } // returns prop value or default values if nil func (p Properties) GetArrayOrDefault(key string, defval []string) (v []string) { if v = p.GetArray(key); v == nil { v = defval } return } // returns nil/zero-value if no such key or not a map, or if key type is not map func (p P...
urn nil } retur
conditional_block
gestalt.go
// // this.is.a.string.array.key[] = alpha , omega # => []string{"alpha", "omega"} // so.is.this.[] = alpha, omega # only the suffix [] is significant of []string property type // // # array values can have embedded white space as well // # basically, any leading/trailing whitespace arou...
{ fm
identifier_name
gran_model.py
www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software
from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import paddle.fluid as fluid from model.graph_encoder import encoder, pre_process_layer logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%...
# 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. """GRAN model."""
random_line_split
gran_model.py
www.apache.org/licenses/LICENSE-2.0 # # 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...
self._dtype = "float16" if use_fp16 else "float32" # Initialize all weights by truncated normal initializer, and all biases # will be initialized by constant zero by default. self._param_initializer = fluid.initializer.TruncatedNormal( scale=config['initializer_range']) ...
self._n_layer = config['num_hidden_layers'] self._n_head = config['num_attention_heads'] self._emb_size = config['hidden_size'] self._intermediate_size = config['intermediate_size'] self._hidden_act = config['hidden_act'] self._prepostprocess_dropout = config['hidden_dropout_prob...
identifier_body
gran_model.py
www.apache.org/licenses/LICENSE-2.0 # # 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...
(self, input_ids, input_mask, edge_labels, config, weight_sharing=True, use_fp16=False): self._n_layer = config['num_hidden_layers'] self._n_head = config['num_attention_heads'] self._emb_size ...
__init__
identifier_name
gran_model.py
www.apache.org/licenses/LICENSE-2.0 # # 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...
special_indicator = fluid.layers.fill_constant_batch_size_like( input=mask_label, shape=[-1, 2], dtype='int64', value=-1) relation_indicator = fluid.layers.fill_constant_batch_size_like( input=mask_label, shape=[-1, self._n_relation], dtype='int64', ...
fc_out = fluid.layers.fc(input=mask_trans_feat, size=self._voc_size, param_attr=fluid.ParamAttr( name="mask_lm_out_fc.w_0", initializer=self._param_initializer), ...
conditional_block
generate_primers.go
if key[len(key)-7:] == "reverse" { primers[key] = getCode(reverseComplement(degens[key][i])) + primers[key] // If the current sequence is forward, get the code of the base and put // it at the end of the primer } else { primers[key] += getCode(degens[key][i]) } } } ...
// Get value split_line := strings.Split(line, "_") temp.val, _ = strconv.Atoi(split_line[0]) // Get isForward if split_line[1] == "forward" { temp.isForward = true } else { temp.isForward = false } // Get sequence scanner.Scan() temp.seq = scanner.Text() out ...
{ var out []Sequence // Open the .seq file fi, err := os.Open(seqFile) if err != nil { fmt.Println("Error - couldn't open .seq file") os.Exit(1) } scanner := bufio.NewScanner(fi) // For each line in the file for scanner.Scan() { var temp Sequence // Get name line := scanner.Text...
identifier_body
generate_primers.go
if key[len(key)-7:] == "reverse" { primers[key] = getCode(reverseComplement(degens[key][i])) + primers[key] // If the current sequence is forward, get the code of the base and put // it at the end of the primer } else { primers[key] += getCode(degens[key][i]) } } } ...
sequences := getSeqs(seqFile) genomes := getGenomes(fastaFile) // For each sequence for _, sequence := range sequences { // If sequence is a reverse, perform the reverse complement on it if !(sequence.isForward) { sequence.seq = reverseComplement(sequence.seq) } out[sequence.name] = m...
random_line_split
generate_primers.go
if key[len(key)-7:] == "reverse" { primers[key] = getCode(reverseComplement(degens[key][i])) + primers[key] // If the current sequence is forward, get the code of the base and put // it at the end of the primer } else { primers[key] += getCode(degens[key][i]) } } } ...
(sequence string) (out string) { for i := len(sequence)-1; i >= 0; i-- { switch sequence[i] { case 65: out += "T" break case 84: out += "A" break case 71: out += "C" break case 67: out += "G" break default: fmt.Println("Error -- Encounter...
reverseComplement
identifier_name
generate_primers.go
if key[len(key)-7:] == "reverse" { primers[key] = getCode(reverseComplement(degens[key][i])) + primers[key] // If the current sequence is forward, get the code of the base and put // it at the end of the primer } else { primers[key] += getCode(degens[key][i]) } } } ...
return out } // Gets the sequences from the .seq file and returns them in an array of Sequence structs // Assuming you have the following in the .seq file: // >99_forward // ACGT // You will get a Sequence struct with the following fields: // name = "99_forward" // seq = "ACGT" // isForward = true ...
{ line := scanner.Text() // If the line begins with '>', assume it's a header if line[0] == 62 { out = append(out, temp) temp = "" // If the line doesn't begin with '>', assume it's a seuence of nucleotides } else { temp += line } }
conditional_block
views.py
Relationship) from radiothon.forms import premium_choice_form_factory from radiothon.settings_local import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD, EMAIL_HOST, EMAIL_PORT class
(TemplateView): template_name = "index.html" class PledgeDetail(DetailView): queryset = Pledge.objects.all() template_name = 'pledge_detail.html' @login_required(login_url='/radiothon/accounts/login') def rthon_pledge(request): pledge_form = PledgeForm(request.POST or None, prefix="pledge_form") ...
MainView
identifier_name
views.py
Relationship) from radiothon.forms import premium_choice_form_factory from radiothon.settings_local import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD, EMAIL_HOST, EMAIL_PORT class MainView(TemplateView): template_name = "index.html" class PledgeDetail(DetailView): queryset = Pledge.objects.all() template_name...
def rthon_plain_logs(request, timespan): ip = get_client_ip(request) #if (ip != '192.168.0.59'): # should probably de-hardcode this # return HttpResponse('Error, not authorized.', content_type="text/plain") response = HttpResponse(content_type="text/plain") pledges = Pledge.objects.all() ...
subject = 'Radiothon Pledge System: %s' % pledge.donor.name message = pledge.as_email() sender = 'WUVT.IT@gmail.com' current_bm = BusinessManager.objects.order_by('-terms__year', 'terms__semester')[0] simple_send_email(sender, current_bm.email, subject, message)
identifier_body
views.py
Relationship) from radiothon.forms import premium_choice_form_factory from radiothon.settings_local import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD, EMAIL_HOST, EMAIL_PORT class MainView(TemplateView): template_name = "index.html" class PledgeDetail(DetailView): queryset = Pledge.objects.all() template_name...
'errors': errors, 'pledge': pledge_form, 'donor': donor_form, 'address': address_form, 'credit': credit_form, 'hokiepassport': hokiepassport_form, 'premium_formsets': premium_choice_forms, 'sending_to': BusinessManager.objects.order_by('-terms__year', 'ter...
random_line_split
views.py
Relationship) from radiothon.forms import premium_choice_form_factory from radiothon.settings_local import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD, EMAIL_HOST, EMAIL_PORT class MainView(TemplateView): template_name = "index.html" class PledgeDetail(DetailView): queryset = Pledge.objects.all() template_name...
else: donor.save() pledge.donor = donor else: errors.append(donor_form.errors) if len(errors) == 0: pledge.save() if pledge.premium_delivery != 'N': for form in premium_c...
errors.append('You must ask the donor for their email or their phone number')
conditional_block
analysiscore.go
in the probe and in the test helper. analysisFlagNullNullTLSMisconfigured // analysisFlagNullNullSuccessfulHTTPS indicates that we had no TH data // but all the HTTP requests used always HTTPS and never failed. analysisFlagNullNullSuccessfulHTTPS // analysisFlagNullNullNXDOMAINWithCensorship indicates that we h...
// safety net in case we're passed empty lists/maps return false
random_line_split
analysiscore.go
neither the probe nor the TH were // able to get any IP addresses from any resolver. analysisFlagNullNullNoAddrs = 1 << iota // analysisFlagNullNullAllConnectsFailed indicates that all the connect // attempts failed both in the probe and in the test helper. analysisFlagNullNullAllConnectsFailed // analysisFlag...
{ if tk.Control == nil { // we need control data to say we're in this case return false } for _, entry := range tk.TCPConnect { if entry.Status.Failure == nil { // we need all connect attempts to fail return false } epnt := net.JoinHostPort(entry.IP, fmt.Sprintf("%d", entry.Port)) thEntry, found :...
identifier_body
analysiscore.go
=%+v, blocking=%+v", tk.BlockingFlags, tk.Accessible, tk.Blocking, ) case (tk.BlockingFlags & analysisFlagHTTPDiff) != 0: tk.Blocking = "http-diff" tk.Accessible = false logger.Warnf( "ANOMALY: flags=%d, accessible=%+v, blocking=%+v", tk.BlockingFlags, tk.Accessible, tk.Blocking, ) case tk.Blocki...
analysisNullNullDetectTLSMisconfigured
identifier_name
analysiscore.go
, ) return } tk.Blocking = nil tk.Accessible = nil logger.Warnf( "UNKNOWN: flags=%d, accessible=%+v, blocking=%+v", tk.BlockingFlags, tk.Accessible, tk.Blocking, ) } } const ( // analysisFlagNullNullNoAddrs indicates neither the probe nor the TH were // able to get any IP addresses from any r...
{ // we need all connect attempts to fail return false }
conditional_block
lc0_analyzer.py
sort_values("N", ascending=False).head(NUM_MOVES) moves = list(best["sanmove"]) bestdf = df.loc[df["sanmove"].isin(moves)] # Plots fig, ax = plt.subplots() for move in moves: tmp = bestdf[bestdf["sanmove"] == move] tmp.plot.line(x="TN", y="N", logx=True, logy=True, ax=ax) ax.leg...
args.numplies = gamelen-plynum
conditional_block
lc0_analyzer.py
# # See https://github.com/killerducky/lc0_analyzer/README.md for description # # See example.sh # import chess import chess.pgn import chess.uci import chess.svg import re import matplotlib.pyplot as plt import matplotlib.axes import pandas as pd import numpy as np import os import math import argparse from collectio...
# # lc0_analyzer.py --help
random_line_split
lc0_analyzer.py
.08339) (Q+U: 0.04175) (V: 0.1052)" m = re.match("^INFO:", info) if not m: return None (_, _, TN, sanmove, ucimove, info) = info.split(maxsplit=5) floats = re.split(r"[^-.\d]+", info) (_, _, N, _, P, Q, U, Q_U, V, _) = floats move_infos = {} move_infos["TN"] = int(TN) move_infos["sanmo...
tmp = bestdf[bestdf["sanmove"] == move] tmp.plot.line(x="TN", y="N", logx=True, logy=True, ax=ax) ax.legend(moves) plt.title("Child Node Visits vs Total Nodes") plt.xlabel("Total Nodes") plt.ylabel("Child Nodes") plt.savefig("%s/N.svg" % (savedir)) fig, ax = plt.subplots() f...
savedir = "plots/%s_%s_%05.1f" % (pgn_filename, gamenum, (plynum+3)/2.0) # Parse data into pandas move_infos = [] with open("%s/data.html" % savedir) as infile: for line in infile.readlines(): info = parse_info(line) if not info: continue move_infos.append(info) ...
identifier_body
lc0_analyzer.py
(self): if "string" in self.info: #self.strings.append(self.info["string"]) # "c7f4 (268 ) N: 40 (+37) (P: 20.23%) (Q: -0.04164) (U: 0.08339) (Q+U: 0.04175) (V: 0.1052)" (move, info) = self.info["string"].split(maxsplit=1) move = self.board.san(self.board....
post_info
identifier_name
connection_test.go
/arbitrum/packages/arb-validator-core/test" "github.com/offchainlabs/arbitrum/packages/arb-validator-core/valprotocol" "github.com/offchainlabs/arbitrum/packages/arb-validator/chainlistener" "github.com/offchainlabs/arbitrum/packages/arb-validator/loader" "github.com/offchainlabs/arbitrum/packages/arb-validator/rol...
logger.Info().Msg("Launched aggregator, connecting to RPC") l2Client, err := ethclient.Dial("http://localhost:9546") if err != nil { t.Fatal(err) } t.Log("Connected to aggregator") logger.Info().Hex("account4", auths[4].From.Bytes()).Msg("Account being used to deploy fibonacci") // Do not wrap with MakeC...
{ t.Fatal(err) }
conditional_block
connection_test.go
/arbitrum/packages/arb-validator-core/test" "github.com/offchainlabs/arbitrum/packages/arb-validator-core/valprotocol" "github.com/offchainlabs/arbitrum/packages/arb-validator/chainlistener" "github.com/offchainlabs/arbitrum/packages/arb-validator/loader" "github.com/offchainlabs/arbitrum/packages/arb-validator/rol...
( client bind.DeployBackend, tx *types.Transaction, timeout time.Duration, ) (*types.Receipt, error) { ticker := time.NewTicker(timeout) for { select { case <-ticker.C: return nil, errors.Errorf("timed out waiting for receipt for tx %v", tx.Hash().Hex()) default: } receipt, err := client.TransactionRe...
waitForReceipt
identifier_name
connection_test.go
/arbitrum/packages/arb-validator-core/test" "github.com/offchainlabs/arbitrum/packages/arb-validator-core/valprotocol" "github.com/offchainlabs/arbitrum/packages/arb-validator/chainlistener" "github.com/offchainlabs/arbitrum/packages/arb-validator/loader" "github.com/offchainlabs/arbitrum/packages/arb-validator/rol...
select { case <-ticker.C: conn, err := net.DialTimeout( "tcp", net.JoinHostPort("127.0.0.1", "9546"), time.Second, ) if err != nil || conn == nil { break } if err := conn.Close(); err != nil { return err } conn, err = net.DialTimeout( "tcp", net.JoinHostPort("127.0....
{ go func() { if err := rpc.LaunchAggregator( context.Background(), client, rollupAddress, contract, db+"/aggregator", "9546", "9547", utils2.RPCFlags{}, time.Second, rpc.StatelessBatcherMode{Auth: auth}, ); err != nil { logger.Fatal().Stack().Err(err).Msg("LaunchAggregator failed"...
identifier_body
connection_test.go
/arbitrum/packages/arb-validator-core/test" "github.com/offchainlabs/arbitrum/packages/arb-validator-core/valprotocol" "github.com/offchainlabs/arbitrum/packages/arb-validator/chainlistener" "github.com/offchainlabs/arbitrum/packages/arb-validator/loader" "github.com/offchainlabs/arbitrum/packages/arb-validator/rol...
return nil } func launchAggregator(client ethutils.EthClient, auth *bind.TransactOpts, rollupAddress common.Address) error { go func() { if err := rpc.LaunchAggregator( context.Background(), client, rollupAddress, contract, db+"/aggregator", "9546", "9547", utils2.RPCFlags{}, time.Secon...
_ = managers
random_line_split
partition.rs
pub field_restriction: Option<BTreeSet<u32>>, /// General DataFusion expressions (arbitrary predicates) applied /// as a filter using logical conjuction (aka are 'AND'ed /// together). Only rows that evaluate to TRUE for all these /// expressions should be returned. pub partition_exprs: Vec<Expr>,...
{}
conditional_block
partition.rs
snafu(display("Error restoring WAL entry, missing partition key"))] MissingPartitionKey, } pub type Result<T, E = Error> = std::result::Result<T, E>; #[derive(Debug)] pub struct Partition { pub key: String, /// `dictionary` maps &str -> u32. The u32s are used in place of String or str to avoid slow /...
/// Return true if this column is the time column pub fn is_time_column(&self, id: u32) -> bool { self.time_column_id == id } /// Creates a DataFusion predicate for appliying a timestamp range: /// /// range.start <= time and time < range.end` fn make_timestamp_predicate_expr(&sel...
{ match &self.field_restriction { None => true, Some(field_restriction) => field_restriction.contains(&field_id), } }
identifier_body
partition.rs
#[snafu(display("Error restoring WAL entry, missing partition key"))] MissingPartitionKey, } pub type Result<T, E = Error> = std::result::Result<T, E>; #[derive(Debug)] pub struct Partition { pub key: String, /// `dictionary` maps &str -> u32. The u32s are used in place of String or str to avoid slow ...
/// of this dictionary. If there are no matching Strings in the /// partitions dictionary, those strings are ignored and a /// (potentially empty) set is returned. fn compile_string_list(&self, names: Option<&BTreeSet<String>>) -> Option<BTreeSet<u32>> { names.map(|names| { names ...
range, }) } /// Converts a potential set of strings into a set of ids in terms
random_line_split
partition.rs
snafu(display("Error restoring WAL entry, missing partition key"))] MissingPartitionKey, } pub type Result<T, E = Error> = std::result::Result<T, E>; #[derive(Debug)] pub struct Partition { pub key: String, /// `dictionary` maps &str -> u32. The u32s are used in place of String or str to avoid slow /...
{ /// At least one of the strings was not present in the partitions' /// dictionary. /// /// This is important when testing for the presence of all ids in /// a set, as we know they can not all be present AtLeastOneMissing, /// All strings existed in this partition's dictionary Present...
PartitionIdSet
identifier_name
mod.rs
FakeWfResponses { pub wf_id: String, pub hist: TestHistoryBuilder, pub response_batches: Vec<ResponseType>, pub task_q: String, } // TODO: turn this into a builder or make a new one? to make all these different build fns simpler pub struct MocksHolder<SG> { sg: SG, mock_pollers: HashMap<String...
num_expected_fails, mock_gateway: MockServerGatewayApis::new(), expect_fail_wft_matcher: Box::new(|_, _, _| true), } } pub fn from_resp_batches( wf_id: &str, t: TestHistoryBuilder, resps: impl IntoIterator<Item = impl Into<ResponseType>>, ...
num_expected_fails: Option<usize>, ) -> Self { Self { hists, enforce_correct_number_of_polls,
random_line_split
mod.rs
FakeWfResponses { pub wf_id: String, pub hist: TestHistoryBuilder, pub response_batches: Vec<ResponseType>, pub task_q: String, } // TODO: turn this into a builder or make a new one? to make all these different build fns simpler pub struct MocksHolder<SG> { sg: SG, mock_pollers: HashMap<String...
else { Some(Err(tonic::Status::out_of_range( "Ran out of mock responses!", ))) } }); Box::new(mock_poller) as BoxedPoller<T> } pub fn mock_poller<T>() -> MockPoller<T> where T: Send + Sync + 'static, { let mut mock_poller = MockPoller::new(); mock_po...
{ Some(Ok(t)) }
conditional_block
mod.rs
FakeWfResponses { pub wf_id: String, pub hist: TestHistoryBuilder, pub response_batches: Vec<ResponseType>, pub task_q: String, } // TODO: turn this into a builder or make a new one? to make all these different build fns simpler pub struct MocksHolder<SG> { sg: SG, mock_pollers: HashMap<String...
(mut cfg: MockPollCfg) -> MocksHolder<MockServerGatewayApis> { // Maps task queues to maps of wfid -> responses let mut task_queues_to_resps: HashMap<String, BTreeMap<String, VecDeque<_>>> = HashMap::new(); let outstanding_wf_task_tokens = Arc::new(RwLock::new(BiMap::new())); let mut correct_num_polls =...
build_mock_pollers
identifier_name
mod.rs
} pub fn from_resp_batches( wf_id: &str, t: TestHistoryBuilder, resps: impl IntoIterator<Item = impl Into<ResponseType>>, mock_gateway: MockServerGatewayApis, ) -> Self { Self { hists: vec![FakeWfResponses { wf_id: wf_id.to_owned(), ...
{ let mut evictions = 0; let expected_evictions = expect_and_reply.len() - 1; let mut executed_failures = HashSet::new(); let expected_fail_count = expect_and_reply .iter() .filter(|(_, reply)| !reply.is_success()) .count(); 'outer: loop { let expect_iter = expect_an...
identifier_body
main.rs
use std::io::{BufReader, BufWriter, Read}; use std::str; use std::thread::spawn; use url::Url; use curl::easy::{Easy, List}; const FORM_MAX_FILE_SIZE: u64 = 1099511627776; const FORM_MAX_FILE_COUNT: usize = 1048576; const FORM_EXPIRES: u64 = 4102444800; #[derive(Debug)] struct OpenStackConfig { auth_url: String, ...
use std::fs::File; use std::path::Path;
random_line_split
main.rs
{ url: String, redirect: String, max_file_size: u64, max_file_count: usize, expires: u64, signature: String } #[derive(Debug)] struct MissingToken; impl fmt::Display for MissingToken { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Token not found in Keystone response headers") ...
FormTemplate
identifier_name
transaction_builder_test.go
fb069c783cac754f5d38c3e08bed1960e31fdb1dda35c2420a10700" expectedTxid := "221ced4e8784290dea336afa1b0a06fa868812e51abbdca3126ce8d99335a6e2" expectedChangeAddress := "34K56kSjgUCUSD8GTtuF7c9Zzwokbs6uZ7" wallet := NewHDWalletFromWords(w, BaseCoinBip49MainNet) meta, err := wallet.BuildTransactionMetadata(data.Transac...
{ path := NewDerivationPath(BaseCoinBip49MainNet, 0, 80) utxo := NewUTXO("94b5bcfbd52a405b291d906e636c8e133407e68a75b0a1ccc492e131ff5d8f90", 0, 10261, path, nil, true) amount := 5000 feeAmount := 1000 changeAmount := 4261 changePath := NewDerivationPath(BaseCoinBip49MainNet, 1, 102) toAddress := "bc1ql2sdag2nm9c...
identifier_body
transaction_builder_test.go
0000001976a914b4716e71b900b957e49f749c8432b910417788e888ac0247304402204147d25961e7ea6f88df58878aa38167fe6f8ae04c3625485dc594ff716f18a002200c08aabefae62d59568155cfb7ca8df1a4d54c01e5abd767d59e7b982663db23012103a45ef894ab9e6f2e55683561181be9e69b20207af746d60b95fab33476dc932420a10700" expectedTxid := "86a9dc5bef7933df26d2...
expectedEncodedTx := "0100000000010126af32df83e27e27711f48d8ca76ee8776ea765d0a9b498bc448e2fb0e00fd1c000000001716001438971f73930f6c141d977ac4fd4a727c854935b3fdffffff02625291000000000017a914aa8f293a04a7df8794b743e14ffb96c2a30a1b2787e026f0490000000017a914251dd11457a259c3ba47e5cca3717fe4214e02988702483045022100f24650e94fd...
random_line_split
transaction_builder_test.go
0001716001436386ac950d557ae06bfffc51e7b8fa08474c05ffdffffff480aacb2cd21a7ed718fc550c158539617d08de86dc8c15eaa8890fc201c61ed010000001716001480e1e7dc2f6436a60abec5e9e7f6b62b0b9985c4fdffffff02c0c62d000000000017a914795c7bc23aebac7ddea222bb13c5357b32ed0cd487c63a01000000000017a914a4a2fab6264d22efbfc997f30738ccc6db0f8c0587024...
(t *testing.T) { path := NewDerivationPath(BaseCoinBip49MainNet, 1, 7) utxo := NewUTXO("f14914f76ad26e0c1aa5a68c82b021b854c93850fde12f8e3188c14be6dc384e", 1, 33255, path, nil, true) amount := 23147 feeAmount := 10108 changePath := NewDerivationPath(BaseCoinBip49MainNet, 1, 2) toAddress := "1HT6WtD5CAToc8wZdacCgY4...
TestTransactionBuilder_BuildP2KH_NoChange
identifier_name
interpolation.rs
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/lic...
NamedOrPositional::Named(..) => { result.named_count += 1; } } result .parameters .push((named_or_positional, format, String::new())); } } Ok(result) }...
{ result.positional_count += 1; }
conditional_block
interpolation.rs
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/lic...
{ Named(String), Positional, } /// Implement Python `%` format strings. pub struct Interpolation { /// String before first parameter init: String, /// Number of positional arguments positional_count: usize, /// Number of named arguments named_count: usize, /// Arguments followed by...
NamedOrPositional
identifier_name
interpolation.rs
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/lic...
box owned_tuple.iter() } None => box iter::once(argument), } }; for (named_or_positional, format, tail) in self.parameters { let arg = match named_or_positional { NamedOrPositional::Positional...
random_line_split
interpolation.rs
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/lic...
return Err( StringInterpolationError::UnexpectedEOFClosingParen.into() ); } Some(')') => { break; } ...
{ let mut result = Self { init: String::new(), positional_count: 0, named_count: 0, parameters: Vec::new(), }; let mut chars = format.chars(); while let Some(c) = chars.next() { if c != '%' { result.append_litera...
identifier_body
play.go
.Wrap(err, "failed waiting for video to advance playback") } if err := seekVideoRepeatedly(ctx, conn, outDir, numSeeks); err != nil { return err } return nil } // ColorDistance returns the maximum absolute difference between each component of a and b. // Both a and b are assumed to be RGBA colors. func ColorDis...
{ return errors.New("video decode acceleration was not used when it was expected to") }
conditional_block
play.go
} // Now go full screen, take a screenshot and verify it's all black. // Make the video go to full screen mode by pressing 'f': requestFullScreen() needs a user gesture. ew, err := input.Keyboard(ctx) if err != nil { return false, errors.Wrap(err, "failed to initialize the keyboard writer") } defer ew.Close...
} if err := seekVideoRepeatedly(ctx, conn, outDir, numSeeks); err != nil { return err } return nil } // ColorDistance returns the maximum absolute difference between each component of a and b. // Both a and b are assumed to be RGBA colors. func ColorDistance(a, b color.Color) int { aR, aG, aB, aA := a.RGBA() ...
{ ctx, st := timing.Start(ctx, "play_seek_video") defer st.End() // Establish a connection to a video play page conn, err := loadPage(ctx, cs, baseURL+"/video.html") if err != nil { return err } defer conn.Close() defer conn.CloseTarget(ctx) if err := conn.Call(ctx, nil, "playRepeatedly", videoFile); err !...
identifier_body
play.go
corresponding point. There are two categories of points: // // - Outer corners: the four absolute corners of the video offset by 1 to ignore acceptable // color blending artifacts on the edges. However, the outer bottom-right is not offset // because we never expect blending artifacts there. // // - Inner corners:...
TestPlayAndScreenshot
identifier_name
play.go
"path" "path/filepath" "time" "chromiumos/tast/common/perf" "chromiumos/tast/errors" "chromiumos/tast/local/audio/crastestclient" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/ash" "chromiumos/tast/local/colorcmp" "chromiumos/tast/local/graphics" "chromiumos/tast/local/input" "chromiumos/tas...
"image/png" "math" "net/http" "net/http/httptest" "os"
random_line_split
redisquota.go
.io/istio/mixer/pkg/status" "istio.io/istio/mixer/template/quota" ) var ( // LUA rate-limiting algorithm scripts rateLimitingLUAScripts = map[config.Params_QuotaAlgorithm]string{ config.FIXED_WINDOW: luaFixedWindow, config.ROLLING_WINDOW: luaRollingWindow, } ) type ( builder struct { quotaTypes map[st...
if quotas.ValidDuration > 0 && quotas.BucketDuration > 0 && quotas.ValidDuration <= quotas.BucketDuration { ce = ce.Appendf("valid_duration", "quotas.valid_duration: %v should be longer than quotas.bucket_duration: %v for ROLLING_WINDOW algorithm", quotas.ValidDuration, quotas.BucketDuration) cont...
{ ce = ce.Appendf("bucket_duration", "quotas.bucket_duration should be > 0 for ROLLING_WINDOW algorithm") continue }
conditional_block
redisquota.go
.io/istio/mixer/pkg/status" "istio.io/istio/mixer/template/quota" ) var ( // LUA rate-limiting algorithm scripts rateLimitingLUAScripts = map[config.Params_QuotaAlgorithm]string{ config.FIXED_WINDOW: luaFixedWindow, config.ROLLING_WINDOW: luaRollingWindow, } ) type ( builder struct { quotaTypes map[st...
continue } if quotas.RateLimitAlgorithm == config.ROLLING_WINDOW { if quotas.BucketDuration == 0 { ce = ce.Appendf("bucket_duration", "quotas.bucket_duration should be > 0 for ROLLING_WINDOW algorithm") continue } if quotas.ValidDuration > 0 && quotas.BucketDuration > 0 && quotas.ValidDura...
{ info := GetInfo() if len(b.adapterConfig.Quotas) == 0 { ce = ce.Appendf("quotas", "quota should not be empty") } limits := make(map[string]*config.Params_Quota, len(b.adapterConfig.Quotas)) for idx := range b.adapterConfig.Quotas { quotas := &b.adapterConfig.Quotas[idx] if len(quotas.Name) == 0 { ce ...
identifier_body
redisquota.go
Builder = &builder{} var _ quota.Handler = &handler{} ///////////////// Configuration Methods /////////////// func (b *builder) SetQuotaTypes(quotaTypes map[string]*quota.Type) { b.quotaTypes = quotaTypes } func (b *builder) SetAdapterConfig(cfg adapter.Config) { b.adapterConfig = cfg.(*config.Params) } func (b *...
result, err := script.Run( h.client, []string{ key + ".meta", // KEY[1]
random_line_split
redisquota.go
.io/istio/mixer/pkg/status" "istio.io/istio/mixer/template/quota" ) var ( // LUA rate-limiting algorithm scripts rateLimitingLUAScripts = map[config.Params_QuotaAlgorithm]string{ config.FIXED_WINDOW: luaFixedWindow, config.ROLLING_WINDOW: luaRollingWindow, } ) type ( builder struct { quotaTypes map[st...
(dimensions map[string]string) string { var keys []string for k := range dimensions { keys = append(keys, k) } sort.Strings(keys) h := fnv.New32a() for _, key := range keys { _, _ = io.WriteString(h, key+"\t"+dimensions[key]+"\n") } return strconv.Itoa(int(h.Sum32())) } func (b *builder) Build(context con...
getDimensionHash
identifier_name
answer_identification.old.py
.append(subtree) return phrases def get_dep_trees_with_tag(root_node, tag): tagged = [] for node in root_node.get_nodes: if node['tag'].lower() == tag.lower(): tagged.append(node) return tagged def calculate_overlap(sequence1, sequence2, eliminate_stopwords=True): overlap = 0...
question_sentence = "When did Babe play for \"the finest basketball team that ever stepped out on a floor\"?" answer_sentence = "Babe Belanger played with the Grads from 1929 to 1937." test = get_answer_phrase(question_sentence, answer_sentence) print(test)
identifier_body
answer_identification.old.py
.findall(span_pattern, tokens)) def num_occurrences_quant_regex(tokens): much_pattern = r'\$\s*\d+[,]?\d+[.]?\d*' much_pattern2 = r'\d+[,]?\d*\s(?:dollars|cents|crowns|pounds|euros|pesos|yen|yuan|usd|eur|gbp|cad|aud)' much_pattern3 = r'(?:dollar|cent|penny|pennies|euro|peso)[s]?' if isinstance(tokens...
elif question['qword'][0].lower() == "why": # q_verb = question.tuple # a_verb = answer.tuple parse_tree = next(CoreNLPParser().raw_parse(answer_sentence)) to_vp_phrases = [] prev_was_to = False for tree in parse_tree.subtrees(): ...
question_chunks = get_top_ner_chunk_of_each_tag(question_sentence) answer_chunks = get_top_ner_chunk_of_each_tag(answer_sentence) # todo: try something with checking the question tag with the answer tag # todo: consider stripping out the part of the answer with question entity in it...
conditional_block
answer_identification.old.py
_parse_tree(sentence_text): return next(CoreNLPParser().raw_parse(sentence_text)) def get_parse_trees_with_tag(sentence_text, tag): parse_tree = next(CoreNLPParser().raw_parse(sentence_text)) phrases = [] for subtree in parse_tree.subtrees(): if subtree.label() == tag: phrases.appe...
test_when
identifier_name
answer_identification.old.py
.findall(span_pattern, tokens)) def num_occurrences_quant_regex(tokens): much_pattern = r'\$\s*\d+[,]?\d+[.]?\d*' much_pattern2 = r'\d+[,]?\d*\s(?:dollars|cents|crowns|pounds|euros|pesos|yen|yuan|usd|eur|gbp|cad|aud)' much_pattern3 = r'(?:dollar|cent|penny|pennies|euro|peso)[s]?' if isinstance(tokens...
except: pass def test_who1(): question_sentence = "Who is the principal of South
[tree.leaves() for tree in qp_phrases], key=lambda x: num_occurrences_quant_regex(x) )) # todo: non-measure cases! (mostly thinking about "how did/does")
random_line_split