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
regexp.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // The testing package implements a simple regular expression library. // It is a reduced version of the regular expression package suitable // for use in tests...
func (re *Regexp) doParse() string { p := newParser(re); start := new(_Start); re.add(start); s, e := p.regexp(); if p.error != "" { return p.error } start.setNext(s); re.start = start; e.setNext(re.add(new(_End))); re.eliminateNops(); return p.error; } // CompileRegexp parses a regular expression and r...
{ for i := 0; i < len(re.inst); i++ { inst := re.inst[i]; if inst.kind() == _END { continue } inst.setNext(unNop(inst.next())); if inst.kind() == _ALT { alt := inst.(*_Alt); alt.left = unNop(alt.left); } } }
identifier_body
regexp.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // The testing package implements a simple regular expression library. // It is a reduced version of the regular expression package suitable // for use in tests...
(c int) bool { for i := 0; i < len(cclass.ranges); i = i + 2 { min := cclass.ranges[i]; max := cclass.ranges[i+1]; if min <= c && c <= max { return !cclass.negate } } return cclass.negate; } func newCharClass() *_CharClass { c := new(_CharClass); c.ranges = make([]int, 0, 20); return c; } // --- ANY ...
matches
identifier_name
mod.rs
use crate::domain; use crate::ops; use crate::prelude::*; use petgraph; use std::collections::{HashMap, HashSet}; use std::ops::{Deref, DerefMut}; mod process; #[cfg(test)] pub(crate) use self::process::materialize; pub mod special; mod ntype; pub use self::ntype::NodeType; // crate viz for tests mod debug; // NOT...
ool { if let NodeType::Base(..) = self.inner { true } else { false } } pub fn is_union(&self) -> bool { if let NodeType::Internal(NodeOperator::Union(_)) = self.inner { true } else { false } } pub fn is_sha...
f) -> b
identifier_name
mod.rs
use crate::domain; use crate::ops; use crate::prelude::*; use petgraph; use std::collections::{HashMap, HashSet}; use std::ops::{Deref, DerefMut}; mod process; #[cfg(test)] pub(crate) use self::process::materialize; pub mod special; mod ntype; pub use self::ntype::NodeType; // crate viz for tests mod debug; // NOT...
is_shard_merger(&self) -> bool { if let NodeType::Internal(NodeOperator::Union(ref u)) = self.inner { u.is_shard_merger() } else { false } } }
let NodeType::Internal(NodeOperator::Union(_)) = self.inner { true } else { false } } pub fn
identifier_body
mod.rs
use crate::domain; use crate::ops; use crate::prelude::*; use petgraph; use std::collections::{HashMap, HashSet}; use std::ops::{Deref, DerefMut}; mod process; #[cfg(test)] pub(crate) use self::process::materialize; pub mod special; mod ntype; pub use self::ntype::NodeType; // crate viz for tests mod debug; // NOT...
children: Vec::new(), inner: inner.into(), taken: false, purge: false, sharded_by: Sharding::None, } } pub fn mirror<NT: Into<NodeType>>(&self, n: NT) -> Node { Self::new(&*self.name, &self.fields, n) } pub fn named_mirror<N...
index: None, domain: None, fields: fields.into_iter().map(|s| s.to_string()).collect(), parents: Vec::new(),
random_line_split
gdb_stub.rs
use std::io::{self, Read, Write}; use std::net::{TcpListener, TcpStream, ToSocketAddrs}; use num_traits::PrimInt; use crate::log::LogKind::GDB; use std::fmt::Arguments; use crate::gba::Gba; use crate::bus::{BusPtr, Bus}; use crate::utils::OrderedSet; use crate::renderer::{Framebuffer, PHYS_WIDTH, PHYS_HEIGHT}; use std:...
WriteWatchpoint(u32), AccessWatchpoint(u32), Breakpoint(u32), Step, } impl StopReason { fn to_command(&self) -> Vec<u8> { let mut result = Vec::new(); match self { StopReason::ReadWatchpoint(addr) => write!(result, "T{:02}rwatch:{}", SIGTRAP, std::str::from_utf8(&int_to_...
#[derive(Debug)] enum StopReason { ReadWatchpoint(u32),
random_line_split
gdb_stub.rs
use std::io::{self, Read, Write}; use std::net::{TcpListener, TcpStream, ToSocketAddrs}; use num_traits::PrimInt; use crate::log::LogKind::GDB; use std::fmt::Arguments; use crate::gba::Gba; use crate::bus::{BusPtr, Bus}; use crate::utils::OrderedSet; use crate::renderer::{Framebuffer, PHYS_WIDTH, PHYS_HEIGHT}; use std:...
(&mut self, addr: u32) -> u16 { self.check_read(addr); self.delegate.read16(addr) } fn read32(&mut self, addr: u32) -> u32 { self.check_read(addr); self.delegate.read32(addr) } fn write8(&mut self, addr: u32, value: u8) { self.check_write(addr); self.del...
read16
identifier_name
gdb_stub.rs
use std::io::{self, Read, Write}; use std::net::{TcpListener, TcpStream, ToSocketAddrs}; use num_traits::PrimInt; use crate::log::LogKind::GDB; use std::fmt::Arguments; use crate::gba::Gba; use crate::bus::{BusPtr, Bus}; use crate::utils::OrderedSet; use crate::renderer::{Framebuffer, PHYS_WIDTH, PHYS_HEIGHT}; use std:...
fn read32(&mut self, addr: u32) -> u32 { self.check_read(addr); self.delegate.read32(addr) } fn write8(&mut self, addr: u32, value: u8) { self.check_write(addr); self.delegate.write8(addr, value); } fn write16(&mut self, addr: u32, value: u16) { self.check...
{ self.check_read(addr); self.delegate.read16(addr) }
identifier_body
install.js
const cp = require('child_process'); const crypto = require('crypto'); const path = require('path'); const fs = require('fs'); const net = require('net'); let nmPath = path.join(__dirname, './node_modules/'); if (!fs.existsSync(nmPath)) { console.log('[info] installing dependencies...') let out = cp.execSync('...
JSON.parse(file); } catch (err) { warn('config.json file for www service is invalid json. It should be deleted.'); let isOk = rl('Can the config.json file in www folder be deleted [y/n]?\n'); if (isOk.toLowerCase() === 'y') { fs.unlinkSync(file); info('www/con...
// Confirm it's valid let file = fs.readFileSync(confDir).toString(); try {
random_line_split
install.js
const cp = require('child_process'); const crypto = require('crypto'); const path = require('path'); const fs = require('fs'); const net = require('net'); let nmPath = path.join(__dirname, './node_modules/'); if (!fs.existsSync(nmPath)) { console.log('[info] installing dependencies...') let out = cp.execSync('...
else { // Ok conf.redis = { host: add, port, keyPrefix: prefix, enableOfflineQueue: true, password: pass, }...
{ // Ask for pass err(rErr) pass = rl('It looks like your redis server requires a password. Please enter it and press enter.\n'); if (!pass) { err('Exiting due to no pass.'); ...
conditional_block
declare.rs
/*! Functionality for declaring Objective-C classes. Classes can be declared using the `ClassDecl` struct. Instance variables and methods can then be added before the class is ultimately registered. # Example The following example demonstrates declaring a class named `MyNumber` that has one ivar, a `u32` named `_num...
/// Adds a requirement on another protocol. pub fn add_protocol(&mut self, proto: &Protocol) { unsafe { runtime::protocol_addProtocol(self.proto, proto); } } /// Registers self, consuming it and returning a reference to the /// newly registered `Protocol`. pub fn r...
{ self.add_method_description_common::<Args, Ret>(sel, is_required, false) }
identifier_body
declare.rs
/*! Functionality for declaring Objective-C classes. Classes can be declared using the `ClassDecl` struct. Instance variables and methods can then be added before the class is ultimately registered. # Example The following example demonstrates declaring a class named `MyNumber` that has one ivar, a `u32` named `_num...
else { Some(ClassDecl { cls }) } } /// Constructs a `ClassDecl` with the given name and superclass. /// Returns `None` if the class couldn't be allocated. pub fn new(name: &str, superclass: &Class) -> Option<ClassDecl> { ClassDecl::with_superclass(name, Some(superclass)) ...
{ None }
conditional_block
declare.rs
/*! Functionality for declaring Objective-C classes. Classes can be declared using the `ClassDecl` struct. Instance variables and methods can then be added before the class is ultimately registered. # Example The following example demonstrates declaring a class named `MyNumber` that has one ivar, a `u32` named `_num...
let size = mem::size_of::<T>(); let align = log2_align_of::<T>(); let success = unsafe { runtime::class_addIvar(self.cls, c_name.as_ptr(), size, align, encoding.as_ptr()) }; assert!(success != NO, "Failed to add ivar {}", name); } /// Adds a p...
let encoding = CString::new(T::encode().as_str()).unwrap();
random_line_split
declare.rs
/*! Functionality for declaring Objective-C classes. Classes can be declared using the `ClassDecl` struct. Instance variables and methods can then be added before the class is ultimately registered. # Example The following example demonstrates declaring a class named `MyNumber` that has one ivar, a `u32` named `_num...
<F>(&mut self, sel: Sel, func: F) where F: MethodImplementation<Callee=Object> { let encs = F::Args::encodings(); let encs = encs.as_ref(); let sel_args = count_args(sel); assert!(sel_args == encs.len(), "Selector accepts {} arguments, but function accepts {}", ...
add_method
identifier_name
annealing3.rs
use crate::common::*; use geo::algorithm::coords_iter::CoordsIter; use rand::prelude::*; use rand::seq::SliceRandom; use std::collections::VecDeque; use std::time::{Duration, Instant}; static SEED: [u8; 32] = [ 0xfd, 0x00, 0xf1, 0x5c, 0xde, 0x01, 0x11, 0xc6, 0xc3, 0xea, 0xfb, 0xbf, 0xf3, 0xca, 0xd8, 0x32, 0x6a...
fn ascore(value: (f64, f64), progress: f64) -> f64 { value.0 * progress + (1.0 - progress) * value.1 } pub fn solve( input: &Input, mut solution: Vec<Point>, time_limit: Duration, fix_seed: bool, initial_temperature: f64, ) -> (Vec<Point>, f64) { let n = solution.len(); let mut rng = i...
{ let dislike = calculate_dislike(&solution, &input.hole); let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); } gx /= solution.len() as f64; gy /= solution.len() as f64; let mut vx: f64 = 0.0; let mut vy: f64 = 0.0; ...
identifier_body
annealing3.rs
use crate::common::*; use geo::algorithm::coords_iter::CoordsIter; use rand::prelude::*; use rand::seq::SliceRandom; use std::collections::VecDeque; use std::time::{Duration, Instant}; static SEED: [u8; 32] = [ 0xfd, 0x00, 0xf1, 0x5c, 0xde, 0x01, 0x11, 0xc6, 0xc3, 0xea, 0xfb, 0xbf, 0xf3, 0xca, 0xd8, 0x32, 0x6a...
temperature = initial_temperature * (1.0 - progress) * (-progress).exp2(); } // move to neighbor let r = rng.gen::<f64>(); if r > progress { let mut i = 0; { let r = rng.gen::<usize>() % distance_total; let mut sum = 0;...
// tweak temperature progress = elapsed.as_secs_f64() / time_limit.as_secs_f64();
random_line_split
annealing3.rs
use crate::common::*; use geo::algorithm::coords_iter::CoordsIter; use rand::prelude::*; use rand::seq::SliceRandom; use std::collections::VecDeque; use std::time::{Duration, Instant}; static SEED: [u8; 32] = [ 0xfd, 0x00, 0xf1, 0x5c, 0xde, 0x01, 0x11, 0xc6, 0xc3, 0xea, 0xfb, 0xbf, 0xf3, 0xca, 0xd8, 0x32, 0x6a...
return p; } return solution[i]; } unreachable!() } fn is_valid_point_move( index: usize, p: &Point, solution: &[Point], original_vertices: &[Point], out_edges: &[Vec<usize>], hole: &Polygon, epsilon: i64, ) -> bool { let ok1 = out_edges[index].iter()...
{ continue; }
conditional_block
annealing3.rs
use crate::common::*; use geo::algorithm::coords_iter::CoordsIter; use rand::prelude::*; use rand::seq::SliceRandom; use std::collections::VecDeque; use std::time::{Duration, Instant}; static SEED: [u8; 32] = [ 0xfd, 0x00, 0xf1, 0x5c, 0xde, 0x01, 0x11, 0xc6, 0xc3, 0xea, 0xfb, 0xbf, 0xf3, 0xca, 0xd8, 0x32, 0x6a...
( from: usize, w: usize, solution: &Vec<Point>, input: &Input, rng: &mut SmallRng, out_edges: &Vec<Vec<usize>>, orders: &Vec<Vec<usize>>, ) -> Option<Vec<Point>> { let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); ...
random_move_one_point
identifier_name
mod.rs
use futures::prelude::*; use http::Uri; use slog::Logger; use std::{ iter::FromIterator, path::{Path, PathBuf}, str::FromStr, }; use crate::{ cache::{self, Cacheable, Cache as _}, download, error::prelude::*, }; use tokio::io::AsyncReadExt; mod hash_writer; use hash_writer::HashWriter; mod erro...
(&self, repo_uri: Uri) -> ResolvedArtifact { ResolvedArtifact { artifact: self.clone(), repo: repo_uri, } } pub fn download_from( &self, location: &Path, repo_uri: Uri, manager: download::Manager, log: Logger, ) -> impl Future<...
resolve
identifier_name
mod.rs
use futures::prelude::*; use http::Uri; use slog::Logger; use std::{ iter::FromIterator, path::{Path, PathBuf}, str::FromStr, }; use crate::{ cache::{self, Cacheable, Cache as _}, download, error::prelude::*, }; use tokio::io::AsyncReadExt; mod hash_writer; use hash_writer::HashWriter; mod erro...
if let Some(ref ext) = self.extension { strn.push('@'); strn.push_str(ext); } strn } } impl FromStr for Artifact { type Err = ArtifactParseError; fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> { let parts: Vec<&str> = s.split('@').col...
{ strn.push(':'); strn.push_str(classifier); }
conditional_block
mod.rs
use futures::prelude::*; use http::Uri; use slog::Logger; use std::{ iter::FromIterator, path::{Path, PathBuf}, str::FromStr, }; use crate::{ cache::{self, Cacheable, Cache as _}, download, error::prelude::*, }; use tokio::io::AsyncReadExt; mod hash_writer; use hash_writer::HashWriter; mod erro...
classifier = classifier_fmt, extension = extension_fmt ) } pub fn resolve(&self, repo_uri: Uri) -> ResolvedArtifact { ResolvedArtifact { artifact: self.clone(), repo: repo_uri, } } pub fn download_from( &self, loca...
random_line_split
mod.rs
use futures::prelude::*; use http::Uri; use slog::Logger; use std::{ iter::FromIterator, path::{Path, PathBuf}, str::FromStr, }; use crate::{ cache::{self, Cacheable, Cache as _}, download, error::prelude::*, }; use tokio::io::AsyncReadExt; mod hash_writer; use hash_writer::HashWriter; mod erro...
pub fn get_uri_on(&self, base: &Uri) -> Result<Uri,error::Error> { let base = crate::util::uri_to_url(base).context(error::BadUrl)?; let path = self.to_path(); let url = base.join(path.to_str().expect("non unicode path encountered")).context(error::BadUrl)?; crate::util::url_to_uri...
{ let mut p = PathBuf::new(); p.push(&self.group_path()); p.push(&self.artifact); p.push(&self.version); p.push(&self.artifact_filename()); p }
identifier_body
plots.py
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
def plot_roc_curve(ax, scores, e, t, a, folds, groups, quant, plot=True): """Function to plot ROC at a specified time horizon. Accepts a matplotlib figure inst...
"""Function to plot Calibration Curve at a specified time horizon. Accepts a matplotlib figure instance, risk scores from a trained survival analysis model, and quantiles of event interest and generates an IPCW adjusted calibration curve. Args: ax: a matplotlib subfigure object. scores: ri...
identifier_body
plots.py
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
# Finally the interpolated curves are averaged over to compute AUC. mean_tpr = np.mean(mean_tprs, axis=0) std_tpr = 1.96 * np.std(mean_tprs, axis=0) / np.sqrt(10) fprs[group]['macro'] = all_fpr tprs[group]['macro'] = mean_tpr tprs_std[group] = std_tpr roc_auc[group] = auc(fprs[group]['ma...
mean_tprs.append(np.interp(all_fpr, fprs[group][i], tprs[group][i]))
conditional_block
plots.py
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
mean_tpr = np.mean(mean_tprs, axis=0) std_tpr = 1.96 * np.std(mean_tprs, axis=0) / np.sqrt(10) fprs[group]['macro'] = all_fpr tprs[group]['macro'] = mean_tpr tprs_std[group] = std_tpr roc_auc[group] = auc(fprs[group]['macro'], tprs[group]['macro']) ctds_mean[group] = np.mean([ctds[group]...
mean_tprs = [] for i in set(folds): mean_tprs.append(np.interp(all_fpr, fprs[group][i], tprs[group][i])) # Finally the interpolated curves are averaged over to compute AUC.
random_line_split
plots.py
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
(ax, scores, e, t, a, folds, groups, quant, plot=True): """Function to plot ROC at a specified time horizon. Accepts a matplotlib figure instance, risk scores fro...
plot_roc_curve
identifier_name
main.rs
use std::{io, thread}; use std::num::ParseIntError; use std::time::Duration; fn main() { memory(); } struct Punto { _x: i8, _y: i8 } fn memory() { let _punto = Punto { _x: 1, _y: 2 }; println!("Inicio address: {:p}", &_punto); _address(&_punto); _copy_value(_punto); println!("------...
let x = 2; let num = match x { 1 | 2 => "1, 2", 3 => "3", _ => "...", }; assert_eq!("1, 2", num); } fn _match_rangos() { let x = 3; let resultado = match x { 1 ..= 5 => "uno al cinco", _ => "cualquier cosa", }; assert_eq!("uno al cinco", resultado...
}; } } fn _multiples_patrones() {
random_line_split
main.rs
use std::{io, thread}; use std::num::ParseIntError; use std::time::Duration; fn main() { memory(); } struct Punto { _x: i8, _y: i8 } fn memory() { let _punto = Punto { _x: 1, _y: 2 }; println!("Inicio address: {:p}", &_punto); _address(&_punto); _copy_value(_punto); println!("------...
let origen = Punto { x: 1, y: 2 }; let suma = foo(&origen); assert_eq!(3, suma); assert_eq!(1, origen.x); } fn _tupla_estructuras() { struct Color(i32, i32, i32); let azul = Color(0, 0, 255); assert_eq!(255, azul.2); } fn _estructuras_tipo_unitario() { struct Electron; let _e = Electr...
punto.x + punto.y }
identifier_body
main.rs
use std::{io, thread}; use std::num::ParseIntError; use std::time::Duration; fn main() { memory(); } struct Punto { _x: i8, _y: i8 } fn memory() { let _punto = Punto { _x: 1, _y: 2 }; println!("Inicio address: {:p}", &_punto); _address(&_punto); _copy_value(_punto); println!("------...
let x = 2; let num = match x { 1 | 2 => "1, 2", 3 => "3", _ => "...", }; assert_eq!("1, 2", num); } fn _match_rangos() { let x = 3; let resultado = match x { 1 ..= 5 => "uno al cinco", _ => "cualquier cosa", }; assert_eq!("uno al cinco", resultad...
tiples_patrones() {
identifier_name
main.rs
use std::{io, thread}; use std::num::ParseIntError; use std::time::Duration; fn main() { memory(); } struct Punto { _x: i8, _y: i8 } fn memory() { let _punto = Punto { _x: 1, _y: 2 }; println!("Inicio address: {:p}", &_punto); _address(&_punto); _copy_value(_punto); println!("------...
continua el ciclo por encima de y println!("x: {}, y: {}", x, y); } } } fn _enumerate() { for (i,j) in (5..10).enumerate() { println!("i = {} y j = {}", i, j); } let lineas = "hola\nmundo".lines(); for (numero_linea, linea) in lineas.enumerate() { println!("{}: ...
ntinue 'interior; } //
conditional_block
main.go
package main import ( "fmt" "math/rand" "strconv" "time" ) const ( // direction up = iota down right left stuck ) const ( // entity in map entity_path = iota + 1 entity_treasure entity_player entity_obstacle ) const ( // axis axis_x = iota axis_y ) const ( // render terminal unix = iota + 1 pla...
() { player := NewPlayer() treasure := NewTreasure() treasureMap := NewTreasureMap(mapSize) treasureMap.createMap(listCustomObstacle) treasureMap.setEntity(entity_player, player.Position) for true { treasure.randomizePosition(mapSize[0], mapSize[1]) if treasureMap.setEntity(entity_treasure, treasure.Position...
main
identifier_name
main.go
package main import ( "fmt" "math/rand" "strconv" "time" ) const ( // direction up = iota down right left stuck ) const ( // entity in map entity_path = iota + 1 entity_treasure entity_player entity_obstacle ) const ( // axis axis_x = iota axis_y ) const ( // render terminal unix = iota + 1 pla...
p.FoundTreasure = true } // check possibility of path intersection with best probability to get the most explored map if p.DirectionTaken == up && p.Range[right] > p.Range[up] { p.DirectionTaken = right } else if p.DirectionTaken == right && p.Range[down] > p.Range[right] { p.DirectionTaken = down } retur...
if treasureMap.OriginalMapping[treasureFound] == entity_treasure {
random_line_split
main.go
package main import ( "fmt" "math/rand" "strconv" "time" ) const ( // direction up = iota down right left stuck ) const ( // entity in map entity_path = iota + 1 entity_treasure entity_player entity_obstacle ) const ( // axis axis_x = iota axis_y ) const ( // render terminal unix = iota + 1 pla...
// move the player into new position, put path on the older position treasureMap.setEntity(entity_path, oldPosition) treasureMap.setEntity(entity_player, newPosition) treasureMap.render() // update player position player.setPosition(newPosition) } else { treasureMap.clearPossibleTreasureLocati...
{ break }
conditional_block
main.go
package main import ( "fmt" "math/rand" "strconv" "time" ) const ( // direction up = iota down right left stuck ) const ( // entity in map entity_path = iota + 1 entity_treasure entity_player entity_obstacle ) const ( // axis axis_x = iota axis_y ) const ( // render terminal unix = iota + 1 pla...
// checkMap a shorthand to validate an unobstructed line of sight in original mapping, return treasure location, list of clear path in sight func checkMap(treasureMap TreasureMap, startAxis int, staticAxis int, addValue int, typeAxis int) ([2]int, [][2]int) { var ( check = true treasurePosition [2]int...
{ var ( startX, startY = p.Position[0], p.Position[1] treasurePosition, treasureFound [2]int listPathPosition, pathFound [][2]int ) // see all entity in x axis with same y axis / right direction -> treasurePosition, pathFound = checkMap(treasureMap, startX+1, startY, 1, axis_x) if treas...
identifier_body
vessel.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: proto/vessel/vessel.proto /*/ 5 Package vessel is a generated protocol buffer package. 6 It is generated from these files: 7 proto/vessel/vessel.proto 8 It has these top-level messages: 9 Vessel 10 Specification 11 Response 12 */ package vessel import (...
serviceName = "vessel" } return &vesselServiceClient{ c: c, serviceName: serviceName, } } func (c *vesselServiceClient) FindAvailable(ctx context.Context, in *Specification, opts ...client.CallOption) (*Response, error) { req := c.c.NewRequest(c.serviceName, "VesselService.FindAvailable", in) out ...
if c == nil { c = client.NewClient() } if len(serviceName) == 0 {
random_line_split
vessel.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: proto/vessel/vessel.proto /*/ 5 Package vessel is a generated protocol buffer package. 6 It is generated from these files: 7 proto/vessel/vessel.proto 8 It has these top-level messages: 9 Vessel 10 Specification 11 Response 12 */ package vessel import (...
func (m *Specification) XXX_Size() int { return xxx_messageInfo_Specification.Size(m) } func (m *Specification) XXX_DiscardUnknown() { xxx_messageInfo_Specification.DiscardUnknown(m) } var xxx_messageInfo_Specification proto.InternalMessageInfo func (m *Specification) GetCapacity() int32 { if m != nil { return ...
{ xxx_messageInfo_Specification.Merge(m, src) }
identifier_body
vessel.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: proto/vessel/vessel.proto /*/ 5 Package vessel is a generated protocol buffer package. 6 It is generated from these files: 7 proto/vessel/vessel.proto 8 It has these top-level messages: 9 Vessel 10 Specification 11 Response 12 */ package vessel import (...
return out, nil } func (c *vesselServiceClient) Create(ctx context.Context, in *Vessel, opts ...client.CallOption) (*Response, error) { req := c.c.NewRequest(c.serviceName, "VesselService.Create", in) out := new(Response) err := c.c.Call(ctx, req, out, opts...) if err != nil { return nil, err } return out, n...
{ return nil, err }
conditional_block
vessel.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: proto/vessel/vessel.proto /*/ 5 Package vessel is a generated protocol buffer package. 6 It is generated from these files: 7 proto/vessel/vessel.proto 8 It has these top-level messages: 9 Vessel 10 Specification 11 Response 12 */ package vessel import (...
(src proto.Message) { xxx_messageInfo_Response.Merge(m, src) } func (m *Response) XXX_Size() int { return xxx_messageInfo_Response.Size(m) } func (m *Response) XXX_DiscardUnknown() { xxx_messageInfo_Response.DiscardUnknown(m) } var xxx_messageInfo_Response proto.InternalMessageInfo func (m *Response) GetVessel() *...
XXX_Merge
identifier_name
download.go
// Copyright 2020 The Moov Authors // Use of this source code is governed by an Apache License // license that can be found in the LICENSE file. package main import ( "database/sql" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "time" moovhttp "github.com/moov-io/base/http" "github.com/moov-io/watch...
alts := precomputeAlts(results.AlternateIdentities) deniedPersons, err := dplRecords(s.logger, initialDir) if err != nil { lastDataRefreshFailure.WithLabelValues("DPs").Set(float64(time.Now().Unix())) return nil, fmt.Errorf("DPL records: %v", err) } dps := precomputeDPs(deniedPersons, s.pipe) consolidatedL...
sdns := precomputeSDNs(results.SDNs, results.Addresses, s.pipe) adds := precomputeAddresses(results.Addresses)
random_line_split
download.go
// Copyright 2020 The Moov Authors // Use of this source code is governed by an Apache License // license that can be found in the LICENSE file. package main import ( "database/sql" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "time" moovhttp "github.com/moov-io/base/http" "github.com/moov-io/watch...
updates <- stats // send stats for re-search and watch notifications } } } func ofacRecords(logger log.Logger, initialDir string) (*ofac.Results, error) { files, err := ofac.Download(logger, initialDir) if err != nil { return nil, fmt.Errorf("download: %v", err) } if len(files) == 0 { return nil, errors...
{ s.logger.Log( "main", fmt.Sprintf("data refreshed %v ago", time.Since(stats.RefreshedAt)), "SDNs", stats.SDNs, "AltNames", stats.Alts, "Addresses", stats.Addresses, "SSI", stats.SectoralSanctions, "DPL", stats.DeniedPersons, "BISEntities", stats.BISEntities, ) }
conditional_block
download.go
// Copyright 2020 The Moov Authors // Use of this source code is governed by an Apache License // license that can be found in the LICENSE file. package main import ( "database/sql" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "time" moovhttp "github.com/moov-io/base/http" "github.com/moov-io/watch...
func getLatestDownloads(logger log.Logger, repo downloadRepository) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w = wrapResponseWriter(logger, w, r) limit := extractSearchLimit(r) downloads, err := repo.latestDownloads(limit) if err != nil { moovhttp.Problem(w, err) return...
{ r.Methods("GET").Path("/downloads").HandlerFunc(getLatestDownloads(logger, repo)) }
identifier_body
download.go
// Copyright 2020 The Moov Authors // Use of this source code is governed by an Apache License // license that can be found in the LICENSE file. package main import ( "database/sql" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "time" moovhttp "github.com/moov-io/base/http" "github.com/moov-io/watch...
(stats *downloadStats) error { if stats == nil { return errors.New("recordStats: nil downloadStats") } query := `insert into download_stats (downloaded_at, sdns, alt_names, addresses, sectoral_sanctions, denied_persons, bis_entities) values (?, ?, ?, ?, ?, ?, ?);` stmt, err := r.db.Prepare(query) if err != nil ...
recordStats
identifier_name
basics.py
# Input Examples
# print('Hello World') # myName = input("Whats your name?\n") # print("It is good to meet you, " + myName) # print('The length of your name is: ') # print(len(myName)) # myAge = input("Whats age?\n") # print('you will be ' + str(int(myAge) + 1) + ' in a year.') # Flow Controls # example 1 # name = 'Msry' # password =...
random_line_split
profile.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: github.com/micro/examples/booking/srv/profile/proto/profile.proto /* Package profile is a generated protocol buffer package. It is generated from these files: github.com/micro/examples/booking/srv/profile/proto/profile.proto It has these top-level messages...
(cc *grpc.ClientConn) ProfileClient { return &profileClient{cc} } func (c *profileClient) GetProfiles(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Result, error) { out := new(Result) err := grpc.Invoke(ctx, "/profile.Profile/GetProfiles", in, out, c.cc, opts...) if err != nil { return nil, err }...
NewProfileClient
identifier_name
profile.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: github.com/micro/examples/booking/srv/profile/proto/profile.proto /* Package profile is a generated protocol buffer package. It is generated from these files: github.com/micro/examples/booking/srv/profile/proto/profile.proto It has these top-level messages...
return &profileClient{cc} } func (c *profileClient) GetProfiles(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Result, error) { out := new(Result) err := grpc.Invoke(ctx, "/profile.Profile/GetProfiles", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } // Server API for...
type profileClient struct { cc *grpc.ClientConn } func NewProfileClient(cc *grpc.ClientConn) ProfileClient {
random_line_split
profile.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: github.com/micro/examples/booking/srv/profile/proto/profile.proto /* Package profile is a generated protocol buffer package. It is generated from these files: github.com/micro/examples/booking/srv/profile/proto/profile.proto It has these top-level messages...
return "" } func (m *Hotel) GetName() string { if m != nil { return m.Name } return "" } func (m *Hotel) GetPhoneNumber() string { if m != nil { return m.PhoneNumber } return "" } func (m *Hotel) GetDescription() string { if m != nil { return m.Description } return "" } func (m *Hotel) GetAddress()...
{ return m.Id }
conditional_block
profile.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: github.com/micro/examples/booking/srv/profile/proto/profile.proto /* Package profile is a generated protocol buffer package. It is generated from these files: github.com/micro/examples/booking/srv/profile/proto/profile.proto It has these top-level messages...
func (m *Address) GetState() string { if m != nil { return m.State } return "" } func (m *Address) GetCountry() string { if m != nil { return m.Country } return "" } func (m *Address) GetPostalCode() string { if m != nil { return m.PostalCode } return "" } type Image struct { Url string `protob...
{ if m != nil { return m.City } return "" }
identifier_body
default.py
# -*- coding: utf-8 -*- import locale locale.setlocale(locale.LC_ALL, 'es_CL.UTF8') #@cache(request.env.path_info, time_expire=150, cache_model=cache.ram) def index(): del response.headers['Cache-Control'] del response.headers['Pragma'] del response.headers['Expires'] response.headers['Cache-Control'] ...
.ajax: return '' from gluon.tools import prettydate from datetime import datetime if request.args: catslug_data = db(db.categoria.slug == request.args(0)).select(db.categoria.slug) for cat in catslug_data: catslug = cat.slug else: catslug = 'notic...
f not request
identifier_name
default.py
# -*- coding: utf-8 -*- import locale locale.setlocale(locale.LC_ALL, 'es_CL.UTF8') #@cache(request.env.path_info, time_expire=150, cache_model=cache.ram) def index(): del response.headers['Cache-Control'] del response.headers['Pragma'] del response.headers['Expires'] response.headers['Cache-Control'] ...
return sm def sitemap4(): sm = [str('<?xml version="1.0" encoding="UTF-8" ?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">')] prefix = request.env.wsgi_url_scheme+'://'+request.env.http_host data = db(db.noticia.id>0).select(db.noticia.id, db.noticia.created_on, db.noticia.title, db.noticia...
TAG.loc(prefix,URL(c='default',f='blog',args=[noti.slug,noti.id],extension='')), TAG.lastmod(noti.created_on.date()), TAG.changefreq('always') ))) sm.append('</urlset>')
conditional_block
default.py
# -*- coding: utf-8 -*- import locale locale.setlocale(locale.LC_ALL, 'es_CL.UTF8') #@cache(request.env.path_info, time_expire=150, cache_model=cache.ram) def index(): del response.headers['Cache-Control'] del response.headers['Pragma'] del response.headers['Expires'] response.headers['Cache-Control'] ...
else: cat = request.args(0) return redirect('http://feeds.feedburner.com/blogchile%s' % cat) # verificamos si pasó por c=default f=mobile y activó el bit de sesión if session.mobile: response.view = 'default/index.mobi' response.files.append(URL('static','css/blogchi...
cat = ''
random_line_split
default.py
# -*- coding: utf-8 -*- import locale locale.setlocale(locale.LC_ALL, 'es_CL.UTF8') #@cache(request.env.path_info, time_expire=150, cache_model=cache.ram) def index(): del response.headers['Cache-Control'] del response.headers['Pragma'] del response.headers['Expires'] response.headers['Cache-Control'] ...
e.headers['Cache-Control'] del response.headers['Pragma'] del response.headers['Expires'] response.headers['Cache-Control'] = 'max-age=300' if request.extension == 'xml': sm = [str('<?xml version="1.0" encoding="UTF-8" ?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">')] ...
/[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password use @auth.requires_login() @auth.requires_members...
identifier_body
fixed.rs
//! Groups all the static pages together. use maud::Markup; use rocket::Route; mod contacts; mod links; mod projects; mod resume; /// Returns the "index" page, aka the home page of the website. /// /// This simply calls [`page_client::home::index()`] from [`page_client`]. #[get("/")] fn get_index() -> Markup { h...
() -> Vec<Route> { routes![ get_index, resume::get, links::get, contacts::get, projects::get, projects::project::get, ] } /// Functions generating my home page. pub mod htmlgen { use maud::{html, Markup, Render}; use page_client::{data, partials}; //...
routes
identifier_name
fixed.rs
//! Groups all the static pages together. use maud::Markup; use rocket::Route; mod contacts; mod links; mod projects; mod resume; /// Returns the "index" page, aka the home page of the website. /// /// This simply calls [`page_client::home::index()`] from [`page_client`]. #[get("/")] fn get_index() -> Markup { h...
/// Returns the first slide as [`Markup`]. fn my_intro() -> Markup { slide( "Nice to meet you", html! { p { "My name is Ben. I am a developer, but I am also:" } ul { li { "a reader; I love to read. But t...
{ html! { div id = { "slide-marker-"(idx) } class={"slide-marker" @if idx == 0 { (" active-slide-marker") }} {} } }
identifier_body
fixed.rs
//! Groups all the static pages together. use maud::Markup; use rocket::Route; mod contacts; mod links; mod projects; mod resume; /// Returns the "index" page, aka the home page of the website. /// /// This simply calls [`page_client::home::index()`] from [`page_client`]. #[get("/")] fn get_index() -> Markup { h...
@for i in 0..slide_cnt { (slide_marker(i)) } } } /// Returns the slide_marker as [`Markup`]. fn slide_marker(idx: u8) -> Markup { html! { div id = { "slide-marker-"(idx) } class={"slide-marker" @if idx == 0 { (" active-slide-marker") }} {}...
/// Returns the slide_markers as [`Markup`]. fn slide_markers(slide_cnt: u8) -> Markup { html! {
random_line_split
attention_refine.py
import tensorflow as tf import numpy as np EMBEDDING_SIZE = 64 DIC_SIZE = 7148 LABEL_SIZE = 3440 # 0为padding,24为start SEQ_LEN = 128 BATCH_SIZE = 512 GRU_UNITS = 256 model_path = "./" feature_description = { "word_id": tf.io.VarLenFeature(dtype=tf.int64), "word_label": tf.io.VarLenFeature(dtype=tf.int64) } ...
pred = sess.run(output, feed_dict={en_input: features[:, :f_max_len + 1], de_in_label: np.concatenate((decoder_start, labels[:, :l_max_len + 1]), axis=-1)[:, 0:-1]}) print(i, np.sum(...
# saver.save(sess, model_path + "ner.model", global_step=int(loss_value * 1000))
random_line_split
attention_refine.py
import tensorflow as tf import numpy as np EMBEDDING_SIZE = 64 DIC_SIZE = 7148 LABEL_SIZE = 3440 # 0为padding,24为start SEQ_LEN = 128 BATCH_SIZE = 512 GRU_UNITS = 256 model_path = "./" feature_description = { "word_id": tf.io.VarLenFeature(dtype=tf.int64), "word_label": tf.io.VarLenFeature(dtype=tf.int64) } ...
Variable( tf.truncated_normal(shape=[step_dimension + self.units * 2, self.units * 2]) / 10000) self.de_b_r_z = tf.Variable(tf.truncated_normal(shape=[self.units * 2, ]) / 10000) self.de_w_h = tf.Variable(tf.truncated_normal(shape=[step_dimension + self.units * 2, self.units]) / 10000) ...
_z = tf.
identifier_name
attention_refine.py
import tensorflow as tf import numpy as np EMBEDDING_SIZE = 64 DIC_SIZE = 7148 LABEL_SIZE = 3440 # 0为padding,24为start SEQ_LEN = 128 BATCH_SIZE = 512 GRU_UNITS = 256 model_path = "./" feature_description = { "word_id": tf.io.VarLenFeature(dtype=tf.int64), "word_label": tf.io.VarLenFeature(dtype=tf.int64) } ...
f_lengths, axis=-1)] l_max_len = l_lengths[np.argmax(l_lengths, axis=-1)] loss_value, _ = sess.run((loss, optimizer), feed_dict={en_input: features[:, :f_max_len + 1], de_in_label: np.concatenate( ...
conditional_block
attention_refine.py
import tensorflow as tf import numpy as np EMBEDDING_SIZE = 64 DIC_SIZE = 7148 LABEL_SIZE = 3440 # 0为padding,24为start SEQ_LEN = 128 BATCH_SIZE = 512 GRU_UNITS = 256 model_path = "./" feature_description = { "word_id": tf.io.VarLenFeature(dtype=tf.int64), "word_label": tf.io.VarLenFeature(dtype=tf.int64) } ...
last_state = de_gru_output[:, i] attention_weight = tf.nn.softmax(tf.squeeze(tf.matmul(encoder_output, tf.expand_dims(last_state, axis=2)))) context_c = tf.reduce_sum(tf.multiply(tf.expand_dims(attention_weight, axis=2), encoder_output), axis=1) step_in = tf.concat((step_in, context_c), axis=-1)...
al(shape=[step_dimension + self.units * 2, self.units * 2]) / 10000) self.de_b_r_z = tf.Variable(tf.truncated_normal(shape=[self.units * 2, ]) / 10000) self.de_w_h = tf.Variable(tf.truncated_normal(shape=[step_dimension + self.units * 2, self.units]) / 10000) self.de_b_h = tf.Variable(tf.truncat...
identifier_body
client.go
// +build linux /* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ...
// GetShortID returns short container ID (12 chars) func GetShortID(dockerID string) (string, error) { if len(dockerID) < 12 { return "", fmt.Errorf("Docker id %v is too short (the length of id should equal at least 12)", dockerID) } return dockerID[:12], nil } // GetStatsFromContainer returns docker containers...
{ return cgroups.FindCgroupMountpoint(subsystem) }
identifier_body
client.go
// +build linux /* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ...
func (dc *DockerClient) GetStatsFromContainer(id string, collectFs bool) (*wrapper.Statistics, error) { var ( err error pid int workingSet uint64 container = &docker.Container{} groupWrap = wrapper.Cgroups2Stats // wrapper for cgroup name and interface for stats extraction stats = wrappe...
// notes that incoming container id has to be full-length to be able to inspect container
random_line_split
client.go
// +build linux /* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ...
dc.inspectCache[id] = info return info, nil } // ListContainersAsMap returns list of all available docker containers and base information about them (status, uptime, etc.) func (dc *DockerClient) ListContainersAsMap() (map[string]docker.APIContainers, error) { containers := make(map[string]docker.APIContainers) ...
{ return nil, err }
conditional_block
client.go
// +build linux /* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ...
() bool { fi, err := os.Lstat("/run/systemd/system") if err != nil { return false } return fi.IsDir() } // isHost returns true if a given id pointing to host func isHost(id string) bool { if id == "/" { // it's a host return true } return false } // version returns version of docker engine func (dc *Do...
isRunningSystemd
identifier_name
M130104.py
# -*- coding: utf-8 -*- """ 中国闽台缘博物馆博物馆爬虫文件 @author: lxx http://www.mtybwg.org.cn/index.aspx 130104 代码更新: 2020.05.10 代码完成 2020.05.10 代码创建 """ import requests import os from bs4 import BeautifulSoup import re import json from selenium import webdriver import time ID = "130104" def debugP...
ref = [] for item in soup.find("div", class_="rightcon").find("ul",class_="falllist animated").find_all("li"): href0 = item.find("a",class_="pic")["href"] href.append(href0) # print(href) # exit() n = len(href) - 1 for href1 in href: if href1 == "http://vr1.mtybwg.or...
.find("div", class_="rightcon").find("ul",class_="falllist animated").find_all("li"): href0 = item.find("a",class_="pic")["href"] href.append(href0) # print(href) # exit() n = len(href) for href1 in href: url = href1 html = askURL(url) soup = BeautifulS...
identifier_body
M130104.py
# -*- coding: utf-8 -*- """ 中国闽台缘博物馆博物馆爬虫文件 @author: lxx http://www.mtybwg.org.cn/index.aspx 130104 代码更新: 2020.05.10 代码完成 2020.05.10 代码创建 """ import requests import os from bs4 import BeautifulSoup import re import json from selenium import webdriver import time ID = "130104" def debugP...
"] = "130104" datadict["M_CName"] = "中国闽台缘博物馆" datadict["M_EName"] = "China Museum for Fujian Taiwan kinship" datadict["M_Batch"] = 1 datadict["M_Address"] = "福建泉州北清东路212号" #官网主页相关内容 baseurl = "http://www.mtybwg.org.cn/" #要爬取的网页链接 datadict["M_Web"] = baseurl html = askURL(bas...
atadict["M_ID
identifier_name
M130104.py
# -*- coding: utf-8 -*- """ 中国闽台缘博物馆博物馆爬虫文件 @author: lxx http://www.mtybwg.org.cn/index.aspx 130104 代码更新: 2020.05.10 代码完成 2020.05.10 代码创建 """ import requests import os from bs4 import BeautifulSoup import re import json from selenium import webdriver import time ID = "130104" def debugP...
html = askURL(index) soup = BeautifulSoup(html,"html.parser") # print(soup) # exit() href = [] for item in soup.find("div", class_="rightcon").find("ul",class_="falllist animated").find_all("li"): href0 = item.find("a",class_="pic")["href"] href.append(href0) # prin...
# 展览 index = "http://www.mtybwg.org.cn/zhanlan.aspx"
random_line_split
M130104.py
# -*- coding: utf-8 -*- """ 中国闽台缘博物馆博物馆爬虫文件 @author: lxx http://www.mtybwg.org.cn/index.aspx 130104 代码更新: 2020.05.10 代码完成 2020.05.10 代码创建 """ import requests import os from bs4 import BeautifulSoup import re import json from selenium import webdriver import time ID = "130104" def debugP...
conditional_block
routes.rs
use rocket::State; use rocket::response::{Flash, Redirect}; use rocket::request::{Form, FormItems, FromForm}; use option_filter::OptionFilterExt; use super::{html, StudentPreferences, TimeSlotRating}; use config; use db::Db; use dict::{self, Locale}; use errors::*; use state::PreparationState; use template::{NavItem, ...
(locale: Locale) -> Vec<NavItem> { // TODO: pass `Dict` once possible let dict = dict::new(locale).prep; vec![ NavItem::new(dict.nav_overview_title(), "/prep"), NavItem::new(dict.nav_timeslots_title(), "/prep/timeslots"), ] } #[get("/prep")] pub fn overview( auth_user: AuthUser, ...
nav_items
identifier_name
routes.rs
use rocket::State; use rocket::response::{Flash, Redirect}; use rocket::request::{Form, FormItems, FromForm}; use option_filter::OptionFilterExt; use super::{html, StudentPreferences, TimeSlotRating}; use config; use db::Db; use dict::{self, Locale}; use errors::*; use state::PreparationState; use template::{NavItem, ...
").get_result::<f64>(conn)?; let avg_ok_rating_per_student = sql(" select cast(avg(count) as float) from ( select count(*) as count, user_id from timeslot_ratings inner join users ...
where rating = 'good' and role = 'student' group by user_id ) as counts
random_line_split
handlers.go
package device import ( "bytes" "context" "net/http" "strconv" "sync" "sync/atomic" "time" "github.com/Comcast/webpa-common/httperror" "github.com/Comcast/webpa-common/logging" "github.com/Comcast/webpa-common/wrp" "github.com/gorilla/mux" ) const ( DefaultMessageTimeout time.Duration = 2 * time.Minute ...
type ConnectHandler struct { Logger logging.Logger Connector Connector ResponseHeader http.Header } func (ch *ConnectHandler) logger() logging.Logger { if ch.Logger != nil { return ch.Logger } return logging.DefaultLogger() } func (ch *ConnectHandler) ServeHTTP(response http.ResponseWriter, re...
{ deviceRequest, err := mh.decodeRequest(httpRequest) if err != nil { httperror.Formatf( httpResponse, http.StatusBadRequest, "Could not decode WRP message: %s", err, ) return } // deviceRequest carries the context through the routing infrastructure if deviceResponse, err := mh.Router.Route(dev...
identifier_body
handlers.go
package device import ( "bytes" "context" "net/http" "strconv" "sync" "sync/atomic" "time" "github.com/Comcast/webpa-common/httperror" "github.com/Comcast/webpa-common/logging" "github.com/Comcast/webpa-common/wrp" "github.com/gorilla/mux" ) const ( DefaultMessageTimeout time.Duration = 2 * time.Minute ...
return } func (mh *MessageHandler) ServeHTTP(httpResponse http.ResponseWriter, httpRequest *http.Request) { deviceRequest, err := mh.decodeRequest(httpRequest) if err != nil { httperror.Formatf( httpResponse, http.StatusBadRequest, "Could not decode WRP message: %s", err, ) return } // devic...
{ deviceRequest = deviceRequest.WithContext(httpRequest.Context()) }
conditional_block
handlers.go
package device import ( "bytes" "context" "net/http" "strconv" "sync" "sync/atomic" "time" "github.com/Comcast/webpa-common/httperror" "github.com/Comcast/webpa-common/logging" "github.com/Comcast/webpa-common/wrp" "github.com/gorilla/mux" ) const ( DefaultMessageTimeout time.Duration = 2 * time.Minute ...
// ListHandler is an HTTP handler which can take updated JSON device lists. type ListHandler struct { initializeOnce sync.Once cachedJSON atomic.Value } // Consume spawns a goroutine that processes updated JSON from the given channel. // This method can be called multiple times with different update sources. Ty...
random_line_split
handlers.go
package device import ( "bytes" "context" "net/http" "strconv" "sync" "sync/atomic" "time" "github.com/Comcast/webpa-common/httperror" "github.com/Comcast/webpa-common/logging" "github.com/Comcast/webpa-common/wrp" "github.com/gorilla/mux" ) const ( DefaultMessageTimeout time.Duration = 2 * time.Minute ...
(httpRequest *http.Request) (deviceRequest *Request, err error) { deviceRequest, err = DecodeRequest(httpRequest.Body, mh.Decoders) if err == nil { deviceRequest = deviceRequest.WithContext(httpRequest.Context()) } return } func (mh *MessageHandler) ServeHTTP(httpResponse http.ResponseWriter, httpRequest *http....
decodeRequest
identifier_name
server.py
#!/usr/bin/python3 # -*- encoding: utf-8 -*- """An API for the Critical Pāli Dictionary""" import argparse import configparser import datetime import json import logging import os.path import re import flask from flask import request, current_app import sqlalchemy from sqlalchemy.sql import text import flask_sqlalch...
run_simple ('localhost', port, application)
app.config['APPLICATION_ROOT'] : app, })
random_line_split
server.py
#!/usr/bin/python3 # -*- encoding: utf-8 -*- """An API for the Critical Pāli Dictionary""" import argparse import configparser import datetime import json import logging import os.path import re import flask from flask import request, current_app import sqlalchemy from sqlalchemy.sql import text import flask_sqlalch...
return arg cpd_iso_trans = str.maketrans ('âêîôû', 'aeiou') def normalize_iso (text): """Normalize to ISO 15919 CPD transliteration is almost ISO 15919, but uses uppercase for proper names and 'â' instead of 'a' to signal a syncope 'a' + 'a'. We have to replace all 'â's because they definitely do n...
g is None: msg = 'Invalid %s parameter' % name flask.abort (msg)
conditional_block
server.py
#!/usr/bin/python3 # -*- encoding: utf-8 -*- """An API for the Critical Pāli Dictionary""" import argparse import configparser import datetime import json import logging import os.path import re import flask from flask import request, current_app import sqlalchemy from sqlalchemy.sql import text import flask_sqlalch...
ect): """ Database Interface """ def __init__ (self, **kwargs): args = self.get_connection_params (kwargs) self.url = 'mysql+pymysql://{user}:{password}@{host}:{port}/{database}'.format (**args) logger.log (logging.INFO, 'MySQLEngine: Connecting to mysql+pymysql://...
Engine (obj
identifier_name
server.py
#!/usr/bin/python3 # -*- encoding: utf-8 -*- """An API for the Critical Pāli Dictionary""" import argparse import configparser import datetime import json import logging import os.path import re import flask from flask import request, current_app import sqlalchemy from sqlalchemy.sql import text import flask_sqlalch...
oint ('articles_id') def articles_id (_id = None): """ Endpoint. Retrieve an article. """ with current_app.config.dba.engine.begin () as conn: res = execute (conn, r""" SELECT no FROM article WHERE no = :id """, { 'id' : _id }) return make_articles_response (re...
. Retrieve a list of articles. """ offset = int (arg ('offset', '0', re_integer_arg)) limit = clip (arg ('limit', str (MAX_RESULTS), re_integer_arg), 1, MAX_RESULTS) with current_app.config.dba.engine.begin () as conn: res = execute (conn, r""" SELECT no FROM article ORDER...
identifier_body
Train.py
# -*- coding: utf-8 -*- """ # Part1: Training """ import os import numpy as np import pandas as pd # Commented out IPython magic to ensure Python compatibility. # %matplotlib inline # Python 2/3 compatibility from __future__ import print_function, division import itertools import time import numpy as np import mat...
headers = next(reader) return [{ headers[column_index]: row[column_index] for column_index in range(len(row)) } for row in reader] class CustomDataset(Dataset): def __init__(self, root, split='train', incr=None, transform=None): self.root = ...
reader = csv.reader(csvfile)
random_line_split
Train.py
# -*- coding: utf-8 -*- """ # Part1: Training """ import os import numpy as np import pandas as pd # Commented out IPython magic to ensure Python compatibility. # %matplotlib inline # Python 2/3 compatibility from __future__ import print_function, division import itertools import time import numpy as np import mat...
def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = self.bn2(self.conv2(out)) out += self.shortcut(x) out = F.relu(out) return out class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=4246): super(ResNet, self).__init__() ...
if option == 'A': """ For CIFAR10 ResNet paper uses option A. """ self.shortcut = LambdaLayer(lambda x: F.pad(x[:, :, ::2, ::2], (0, 0, 0, 0, planes//4, planes//4), "constant", 0)) elif option == 'B':...
conditional_block
Train.py
# -*- coding: utf-8 -*- """ # Part1: Training """ import os import numpy as np import pandas as pd # Commented out IPython magic to ensure Python compatibility. # %matplotlib inline # Python 2/3 compatibility from __future__ import print_function, division import itertools import time import numpy as np import mat...
# train the model train_history, val_history = train(net, batch_size=128, n_epochs=20, learning_rate=0.01) plot_losses(train_history, val_history) """See next part for testing and prediction """
""" Train a neural network and print statistics of the training :param net: (PyTorch Neural Network) :param batch_size: (int) :param n_epochs: (int) Number of iterations on the training set :param learning_rate: (float) learning rate used by the optimizer """ print("===== HYPERPARAMETE...
identifier_body
Train.py
# -*- coding: utf-8 -*- """ # Part1: Training """ import os import numpy as np import pandas as pd # Commented out IPython magic to ensure Python compatibility. # %matplotlib inline # Python 2/3 compatibility from __future__ import print_function, division import itertools import time import numpy as np import mat...
(net, batch_size, n_epochs, learning_rate): """ Train a neural network and print statistics of the training :param net: (PyTorch Neural Network) :param batch_size: (int) :param n_epochs: (int) Number of iterations on the training set :param learning_rate: (float) learning rate used by the ...
train
identifier_name
PAD.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ photoangular distributions for isotropically oriented ensembles of molecules in the gas phase Initial bound and final continuum orbitals are obtained by the multiple scattering (MS) and the continuum multiple scattering (CMS) methods, respectively. """ from __future...
def save_pads(pke,pad, pol, tbl_file, units="eV-Mb"): """ A table with the PAD is written to `tbl_file`. It contains the 4 columns PKE SIGMA BETA1 BETA_2 which define the PAD(th) at each energy according to .. code-block:: none ...
""" Parameters ---------- muffin : instance of `MuffinTinPotential` muffin tin potential, which provides the continuum orbitals """ def __init__(self, muffin): self.muffin = muffin def compute_pads(self, bound_orbitals, pke, ...
identifier_body
PAD.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ photoangular distributions for isotropically oriented ensembles of molecules in the gas phase Initial bound and final continuum orbitals are obtained by the multiple scattering (MS) and the continuum multiple scattering (CMS) methods, respectively. """ from __future...
# last extremum is a minimum, which is not bracketed # by two maxima maxima = maxima + [-1] # After appending last point, we have # maxima[i ] < minima[i] < maxima[i+1] # for all minima assert len(minima) == le...
# maxima[j ] < minima[j] < maxima[j+1] if pke[minima[-1]] > pke[maxima[-1]]:
random_line_split
PAD.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ photoangular distributions for isotropically oriented ensembles of molecules in the gas phase Initial bound and final continuum orbitals are obtained by the multiple scattering (MS) and the continuum multiple scattering (CMS) methods, respectively. """ from __future...
(energy): # compute (-1) x photoionization cross section for initial orbital # with index `i` at energy `energy` pad_i = self.muffin.photoelectron_distribution(energy, grid, orbs[i:i+1,:], pol=pol) ...
func
identifier_name
PAD.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ photoangular distributions for isotropically oriented ensembles of molecules in the gas phase Initial bound and final continuum orbitals are obtained by the multiple scattering (MS) and the continuum multiple scattering (CMS) methods, respectively. """ from __future...
print( "" ) return resonances def save_pads(pke,pad, pol, tbl_file, units="eV-Mb"): """ A table with the PAD is written to `tbl_file`. It contains the 4 columns PKE SIGMA BETA1 BETA_2 which define the PAD(th) at each energy according to .. code-block:...
print( " %4.1d %4.1d %12.8f %12.8f %6.4e" % (i+1, j+1, res.energy, res.energy * AtomicData.hartree_to_eV, res.tags["sigma"] * AtomicData.bohr2_to_megabarn) )
conditional_block
IssuanceHelpers.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License in the project root for license information. *-------------------------------------------------------------------...
const contract = 'https://portableidentitycards.azure-api.net/42b39d9d-0cdd-4ae0-b251-b7b39a561f91/api/portable/v1.0/contracts/test/schema'; const request = await IssuanceHelpers.createSiopRequest( setup, didJwkPrivate, issuance ? contract : undefined, '', attestations ); ...
{ attestations = { presentations: {} }; attestations.presentations['DrivingLicense'] = vp.rawToken; }
conditional_block
IssuanceHelpers.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License in the project root for license information. *-------------------------------------------------------------------...
tokenJwkPrivate, tokenJwkPublic); const vp = await IssuanceHelpers.createVp(setup, [vc], didJwkPrivate); const si = IssuanceHelpers.createSelfIssuedToken({ name: 'jules', birthDate: new Date().toString() }); let attestations: { [claim: string]: any }; if (issuance) { attestations = { ...
}; const vc = await IssuanceHelpers.createVc( setup, vcPayload, vcConfiguration,
random_line_split
IssuanceHelpers.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License in the project root for license information. *-------------------------------------------------------------------...
public static async createRequest( setup: TestSetup, tokenDescription: TokenType, issuance: boolean, idTokenIssuer?: string, idTokenAudience?: string, idTokenExp?: number): Promise<[ClaimToken, ValidationOptions, any]> { const options = new ValidationOptions(setup.validatorOptions, token...
{ const keyId = new KeyReference(jwkPrivate.kid); await setup.keyStore.save(keyId, <any>jwkPrivate); setup.validatorOptions.crypto.builder.useSigningKeyReference(keyId); setup.validatorOptions.crypto.signingProtocol(JoseBuilder.JWT).builder.useKid(keyId.keyReference); const signature = await setup.v...
identifier_body
IssuanceHelpers.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License in the project root for license information. *-------------------------------------------------------------------...
(setup: TestSetup, payload: object, configuration: string, jwkPrivate: any): Promise<ClaimToken> { const keyId = new KeyReference(jwkPrivate.kid); await setup.keyStore.save(keyId, <any>jwkPrivate); setup.validatorOptions.crypto.builder.useSigningKeyReference(keyId); setup.validatorOptions.crypto.signing...
signAToken
identifier_name
ui.rs
//! Implements how the user interfaces with the application. pub(crate) use crate::num::{Length, NonNegativeI32}; use crate::{fmt, Debug, Display, Formatter, Mrc, TryFrom, TryFromIntError}; use pancurses::Input; use std::cell::RefCell; use std::error; use std::rc::Rc; /// The [`Result`] returned by functions of this...
Change::Clear => write!(f, "Clear"), Change::Format(n, color) => write!(f, "Format {} cells to {}", n, color), Change::Insert(input) => write!(f, "Insert '{}'", input), Change::Nothing => write!(f, "Nothing"), Change::Row(row_str) => write!(f, "Write row '{}'"...
#[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Change::Backspace => write!(f, "Backspace"),
random_line_split
ui.rs
//! Implements how the user interfaces with the application. pub(crate) use crate::num::{Length, NonNegativeI32}; use crate::{fmt, Debug, Display, Formatter, Mrc, TryFrom, TryFromIntError}; use pancurses::Input; use std::cell::RefCell; use std::error; use std::rc::Rc; /// The [`Result`] returned by functions of this...
} /// Signifies a [`Change`] to make to an [`Address`]. /// /// [`Change`]: enum.Change.html /// [`Address`]: struct.Address.html #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] pub struct Edit { /// The [`Change`] to be made. change: Change, /// The [`Address`] on which the [`Change`] is intended. ...
{ match self { Color::Default => write!(f, "Default"), Color::Red => write!(f, "Red"), Color::Green => write!(f, "Green"), Color::Yellow => write!(f, "Yellow"), Color::Blue => write!(f, "Blue"), } }
identifier_body
ui.rs
//! Implements how the user interfaces with the application. pub(crate) use crate::num::{Length, NonNegativeI32}; use crate::{fmt, Debug, Display, Formatter, Mrc, TryFrom, TryFromIntError}; use pancurses::Input; use std::cell::RefCell; use std::error; use std::rc::Rc; /// The [`Result`] returned by functions of this...
(&self) -> Outcome { Self::process(self.window.delch(), Error::Wdelch) } /// Disables echoing received characters on the screen. fn disable_echo(&self) -> Outcome { Self::process(pancurses::noecho(), Error::Noecho) } /// Sets user interface to not wait for an input. fn enable_n...
delete_char
identifier_name
command.py
"""common/command.py Classes and utility functions for working with and creating ZeroBot commands. """ from __future__ import annotations from argparse import ArgumentParser, _SubParsersAction from dataclasses import dataclass, field from functools import partial from typing import Any, Optional, Union from ZeroBot...
return subparser.name.split()[-1] except (IndexError, KeyError, TypeError): return None @dataclass class CommandHelp: """Encapsulates the result of a command help request. ZeroBot's `Core` will create and pass these to `core_command_help` callbacks. Attributes --...
action = subparser._actions[0] if isinstance(action, _SubParsersAction): subparser = action.choices[self.args[action.dest]] current += 1 else: return None
conditional_block
command.py
"""common/command.py Classes and utility functions for working with and creating ZeroBot commands. """ from __future__ import annotations from argparse import ArgumentParser, _SubParsersAction from dataclasses import dataclass, field from functools import partial from typing import Any, Optional, Union from ZeroBot...
(self, name: str) -> "CommandHelp": """Get the `CommandHelp` object for the given subcommand. `name` may be an alias, in which case it is resolved to the appropriate subcommand. """ try: return self.subcmds[name] except KeyError: # Try looking up ...
get_subcmd
identifier_name
command.py
"""common/command.py Classes and utility functions for working with and creating ZeroBot commands. """ from __future__ import annotations from argparse import ArgumentParser, _SubParsersAction from dataclasses import dataclass, field from functools import partial from typing import Any, Optional, Union from ZeroBot...
except (KeyError, IndexError): self._subcmd = None @property def invoker(self) -> User: """The User that invoked the command.""" return self.msg.source @property def source(self) -> Union[User, Channel]: """Where the command was sent from. Can be ei...
name_map = action.choices canon_parser = name_map[self.args[action.dest]] self._subcmd = canon_parser.name.split()[-1] else: self._subcmd = None
random_line_split
command.py
"""common/command.py Classes and utility functions for working with and creating ZeroBot commands. """ from __future__ import annotations from argparse import ArgumentParser, _SubParsersAction from dataclasses import dataclass, field from functools import partial from typing import Any, Optional, Union from ZeroBot...
def nested_subcmd(self, depth: int = 2) -> Optional[str]: """Get the name of a nested subcommand. Like the `subcmd` property, the name returned is always the canonical name for the subcommand. The `depth` parameter determines how many levels of nesting to traverse; the default of ...
"""The invoked subcommand name, if one was invoked. For subcommands with aliases, the name returned is always the canonical name that the aliases are associated with. For this reason, this attribute should be preferred to extracting the subcommand name from `ParsedCommand.args`. ...
identifier_body
store.go
// Copyright 2022-2023 The Parca Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to...
func (s *Store) uploadIsStale(upload *debuginfopb.DebuginfoUpload) bool { return upload.StartedAt.AsTime().Add(s.maxUploadDuration + 2*time.Minute).Before(s.timeNow()) } func validateInput(id string) error { _, err := hex.DecodeString(id) if err != nil { return fmt.Errorf("failed to validate input: %w", err) }...
{ if err := validateInput(buildID); err != nil { return status.Errorf(codes.InvalidArgument, "invalid build ID: %q", err) } dbginfo, err := s.metadata.Fetch(ctx, buildID, typ) if err != nil { if errors.Is(err, ErrMetadataNotFound) { return status.Error(codes.FailedPrecondition, "metadata not found, this ind...
identifier_body
store.go
// Copyright 2022-2023 The Parca Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to...
(buildID string, typ debuginfopb.DebuginfoType) string { switch typ { case debuginfopb.DebuginfoType_DEBUGINFO_TYPE_EXECUTABLE: return path.Join(buildID, "executable") case debuginfopb.DebuginfoType_DEBUGINFO_TYPE_SOURCES: return path.Join(buildID, "sources") default: return path.Join(buildID, "debuginfo") }...
objectPath
identifier_name
store.go
// Copyright 2022-2023 The Parca Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to...
if err != nil { return nil, status.Error(codes.Internal, err.Error()) } return &debuginfopb.MarkUploadFinishedResponse{}, nil } func (s *Store) Upload(stream debuginfopb.DebuginfoService_UploadServer) error { if s.signedUpload.Enabled { return status.Error(codes.Unimplemented, "signed URL uploads are the onl...
{ return nil, status.Error(codes.InvalidArgument, "upload id mismatch") }
conditional_block
store.go
// Copyright 2022-2023 The Parca Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to...
if err != nil { return nil, err } if !shouldInitiateResp.ShouldInitiateUpload { if shouldInitiateResp.Reason == ReasonDebuginfoEqual { return nil, status.Error(codes.AlreadyExists, ReasonDebuginfoEqual) } return nil, status.Errorf(codes.FailedPrecondition, "upload should not have been attempted to be init...
})
random_line_split
server.go
// Copyright (c) 2017-2020 VMware, Inc. or its affiliates // SPDX-License-Identifier: Apache-2.0 package hub import ( "context" "encoding/json" "fmt" "io" "net" "os" "strconv" "strings" "sync" "time" "github.com/greenplum-db/gp-common-go-libs/gplog" "github.com/hashicorp/go-multierror" "github.com/pkg/e...
(target *greenplum.Cluster) *idl.Message { data := make(map[string]string) data[idl.ResponseKey_target_port.String()] = strconv.Itoa(target.MasterPort()) data[idl.ResponseKey_target_master_data_directory.String()] = target.MasterDataDir() return &idl.Message{ Contents: &idl.Message_Response{ Response: &idl.Re...
MakeTargetClusterMessage
identifier_name