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
ParamEffectsProcessedFCD.py
= False interval = 0 inputFile = open(path.FQedgeDump, 'r') for line in inputFile: words = line.split('"') if not begin and words[0].find("<end>") != -1: words = words[0].split(">") interval = int(words[1][:-5]) edgeDumpDict.setdefault(interval, []) ...
simpleTaxiMeanVList[0] += tup[2] simpleTaxiMeanVList[1] += 1 drivenEdgesSet.add(tup[1])
conditional_block
ParamEffectsProcessedFCD.py
250, 300] # [0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20., 50.] #how many taxis in percent of the total vehicles | single element or a hole list quota = [0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20., 50.] iteration = 2 vehId = 0 vehIdDict = {} edgeDumpDict = None vtypeDict = None vehList = None vehSum = None procFcdDict = None...
for quota in qList: print("create output for: period ", period, " quota ", quota) taxis = chooseTaxis(vehList) taxiSum = len(taxis) if mode == U_FCD: vtypeDictR = procFcdDict[(period, quota)] else: vtypeDictR = reduceVty...
if stopByPeriod: yield (period, None, None, None)
random_line_split
activemqartemisaddress_controller.go
activemqartemisaddress") var namespacedNameToAddressName = make(map[types.NamespacedName]brokerv2alpha2.ActiveMQArtemisAddress) //This channel is used to receive new ready pods var C = make(chan types.NamespacedName) /** * USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Co...
(instance *brokerv2alpha2.ActiveMQArtemisAddress, request reconcile.Request, client client.Client) error { reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name) reqLogger.Info("Deleting ActiveMQArtemisAddress") var err error = nil artemisArray := getPodBrokers(instance,...
deleteQueue
identifier_name
activemqartemisaddress_controller.go
activemqartemisaddress") var namespacedNameToAddressName = make(map[types.NamespacedName]brokerv2alpha2.ActiveMQArtemisAddress) //This channel is used to receive new ready pods var C = make(chan types.NamespacedName) /** * USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Co...
else { reqLogger.Info("Statefulset: " + ssNamespacedName.Name + " found") pod := &corev1.Pod{} podNamespacedName := types.NamespacedName{ Name: statefulset.Name + "-0", Namespace: request.Namespace, } // For each of the replicas var i int = 0 var replicas int = int(*statefulset.Spec.Replicas...
{ reqLogger.Info("Statefulset: " + ssNamespacedName.Name + " not found") }
conditional_block
activemqartemisaddress_controller.go
activemqartemisaddress") var namespacedNameToAddressName = make(map[types.NamespacedName]brokerv2alpha2.ActiveMQArtemisAddress) //This channel is used to receive new ready pods var C = make(chan types.NamespacedName) /** * USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Co...
} } } } } return err } func getPodBrokers(instance *brokerv2alpha2.ActiveMQArtemisAddress, request reconcile.Request, client client.Client) []*mgmt.Artemis { reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name) reqLogger.Info("Getting Pod Brokers") var...
reqLogger.Info("No bindings found removing " + instance.Spec.AddressName) a.DeleteAddress(instance.Spec.AddressName) } else { reqLogger.Info("Bindings found, not removing " + instance.Spec.AddressName)
random_line_split
activemqartemisaddress_controller.go
activemqartemisaddress") var namespacedNameToAddressName = make(map[types.NamespacedName]brokerv2alpha2.ActiveMQArtemisAddress) //This channel is used to receive new ready pods var C = make(chan types.NamespacedName) /** * USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Co...
} } return err } func deleteQueue(instance *brokerv2alpha2.ActiveMQArtemisAddress, request reconcile.Request, client client.Client) error { reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name) reqLogger.Info("Deleting ActiveMQArtemisAddress") var err error = nil ...
{ reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name) reqLogger.Info("Creating ActiveMQArtemisAddress") var err error = nil artemisArray := getPodBrokers(instance, request, client) if nil != artemisArray { for _, a := range artemisArray { if nil == a { reqLo...
identifier_body
mod.rs
: 0.0 } ]); } if freq * 4.0 > sps { return Option::None; } // How many of our smallest units of time represented // by a sample do we need for a full cycle of the // frequency. let timepersample = 1.0f64 / sps as f64; let units = ((1.0 / freq).abs() / timepersample).abs(); ...
else { self.tapi - ti }; si += self.tapvi[off] * self.taps[ti]; sq += self.tapvq[off] * self.taps[ti]; } self.tapi += 1; if self.tapi >= self.taps.len() { self.tapi = 0; } ...
{ self.taps.len() - (ti - self.tapi)}
conditional_block
mod.rs
} pub struct Alsa { sps: u32, pcm: PCM<Prepared>, } impl Alsa { pub fn new(sps: u32) -> Alsa { let pcm = PCM::open("default", Stream::Playback, Mode::Blocking).unwrap(); let mut pcm = pcm.set_parameters(Format::FloatLE, Access::Interleaved, 1, sps as usize).ok().unw...
{ let i = self.i * a.i - self.q * a.q; let q = self.i * a.q + self.q * a.i; self.i = i; self.q = q; }
identifier_body
mod.rs
(freq: f64, sps: f64, amp: f32) -> Option<Vec<Complex<f32>>> { // Do not build if too low in frequency. if freq.abs() < 500.0 { return Option::Some(vec![Complex { i: 1.0, q: 0.0 } ]); } if freq * 4.0 > sps { return Option::None; } // How many of our smallest units of time r...
buildsine
identifier_name
mod.rs
sps, 1.0).unwrap(); let mut tapvi: Vec<f32> = Vec::new(); let mut tapvq: Vec<f32> = Vec::new(); for x in 0..taps.len() { tapvi.push(0.0); tapvq.push(0.0); } // If the decimation is not set perfectly then we will have // a fracti...
for x in 0..buf.len() { fd.write_f32::<LittleEndian>(buf[x]); } //unsafe {
random_line_split
main.rs
, is it worth // keeping some scratch mem for this and running our own StrPool? // TODO for lint violations of names, emit a refactor script #[macro_use] extern crate log; extern crate getopts; extern crate rustc; extern crate rustc_driver; extern crate syntax; extern crate strings; use rustc::session::Session; us...
{ Overwrite, // str is the extension of the new file NewFile(&'static str), // Write the output to stdout. Display, // Return the result as a mapping from filenames to StringBuffers. Return(&'static Fn(HashMap<String, String>)), } #[derive(Copy, Clone, Eq, PartialEq, Debug)] enum BraceStyl...
WriteMode
identifier_name
main.rs
, is it worth // keeping some scratch mem for this and running our own StrPool? // TODO for lint violations of names, emit a refactor script #[macro_use] extern crate log; extern crate getopts; extern crate rustc; extern crate rustc_driver; extern crate syntax; extern crate strings; use rustc::session::Session; us...
#[cfg(test)] mod test { use std::collections::HashMap; use std::fs; use std::io::Read; use std::sync::atomic; use super::*; use super::run; // For now, the only supported regression tests are idempotent tests - the input and // output must match exactly. // FIXME(#28) would be good ...
random_line_split
main.rs
::var("USER").unwrap(); format!("postgres://{}@%2Frun%2Fpostgresql/pagefeed", user) }) } fn handle_request(req: &mut fastcgi::Request) -> Result<(), PagefeedError> { let url = get_url(req)?; let pathinfo = get_pathinfo(req); let slug = pathinfo.trim_matches('/'); let mut w = io::BufWriter:...
<W: Write>(url: &str, pages: &[Page], out: &mut W) -> Result<(), PagefeedError> { #[derive(serde::Serialize)] #[serde(rename = "opml")] struct Opml<'a> { version: &'a str, head: Head, body: Body<'a>, } #[derive(serde::Serialize)] struct Head {} #[derive(serde::Seria...
build_opml
identifier_name
main.rs
(false, _) => format!("http://{}:{}{}", server_addr, server_port, script_name), (true, 443) => format!("https://{}{}", server_addr, script_name), (true, _) => format!("https://{}:{}{}", server_addr, server_port, script_name), }) } fn get_pathinfo(req: &fastcgi::Request) -> String { req....
{ let query = " update pages set last_checked = current_timestamp where slug = $1 "; conn.execute(query, &[&page.slug])?; Ok(()) }
identifier_body
main.rs
::var("USER").unwrap(); format!("postgres://{}@%2Frun%2Fpostgresql/pagefeed", user) }) } fn handle_request(req: &mut fastcgi::Request) -> Result<(), PagefeedError> { let url = get_url(req)?; let pathinfo = get_pathinfo(req); let slug = pathinfo.trim_matches('/'); let mut w = io::BufWriter:...
fn describe_page_status(page: &Page) -> String { page.last_error.as_ref().map_or_else( || format!("{} was updated.", page.name), |err| format!("Error while checking {}: {}", page.name, err), ) } fn build_opml<W: Write>(url: &str, pages: &[Page], out: &mut W) -> Result<(), PagefeedError> { #...
random_line_split
main.rs
::var("USER").unwrap(); format!("postgres://{}@%2Frun%2Fpostgresql/pagefeed", user) }) } fn handle_request(req: &mut fastcgi::Request) -> Result<(), PagefeedError> { let url = get_url(req)?; let pathinfo = get_pathinfo(req); let slug = pathinfo.trim_matches('/'); let mut w = io::BufWriter:...
else { handle_feed_request(slug, &mut w) } } fn handle_opml_request<W: Write>(url: &str, out: &mut W) -> Result<(), PagefeedError> { let mut conn = database_connection()?; let mut trans = conn.transaction()?; let pages = get_enabled_pages(&mut trans)?; trans.commit()?; out.write_all(b"...
{ handle_opml_request(&url, &mut w) }
conditional_block
start.go
interface { CheckRequirements() error } //go:generate mockgen -package mocks -destination mocks/cache.go code.cloudfoundry.org/cfdev/cmd/start Cache type Cache interface { Sync(resource.Catalog) error } //go:generate mockgen -package mocks -destination mocks/cfdevd.go code.cloudfoundry.org/cfdev/cmd/start CFDevD t...
() *cobra.Command { args := Args{} cmd := &cobra.Command{ Use: "start", RunE: func(_ *cobra.Command, _ []string) error { if err := s.Execute(args); err != nil { return errors.SafeWrap(err, "cf dev start") } return nil }, } pf := cmd.PersistentFlags() pf.StringVarP(&args.DepsIsoPath, "file", "f"...
Cmd
identifier_name
start.go
Host interface { CheckRequirements() error } //go:generate mockgen -package mocks -destination mocks/cache.go code.cloudfoundry.org/cfdev/cmd/start Cache type Cache interface { Sync(resource.Catalog) error } //go:generate mockgen -package mocks -destination mocks/cfdevd.go code.cloudfoundry.org/cfdev/cmd/start CFD...
NoProvision bool Cpus int Mem int } type Start struct { Exit chan struct{} LocalExit chan string UI UI Config config.Config IsoReader IsoReader Analytics AnalyticsClient AnalyticsToggle Toggle HostNet HostNet ...
random_line_split
start.go
f.BoolVarP(&args.NoProvision, "no-provision", "n", false, "start vm but do not provision") pf.StringVarP(&args.DeploySingleService, "white-listed-services", "s", "", "list of supported services to deploy") pf.MarkHidden("no-provision") return cmd } func (s *Start) Execute(args Args) error { go func() { select {...
{ baseMem := defaultMemory if isoConfig.DefaultMemory > 0 { baseMem = isoConfig.DefaultMemory } availableMem, err := s.Profiler.GetAvailableMemory() if err != nil { return 0, errors.SafeWrap(err, "error retrieving available system memory") } customMemProvided := requestedMem > 0 if customMemProvided { i...
identifier_body
start.go
//go:generate mockgen -package mocks -destination mocks/stop.go code.cloudfoundry.org/cfdev/cmd/start Stop type Stop interface { RunE(cmd *cobra.Command, args []string) error } type Args struct { Registries string DeploySingleService string DepsIsoPath string NoProvision bool Cpus ...
{ if err := s.Provisioner.Ping(); err == nil { return } time.Sleep(time.Second) }
conditional_block
Embedding.py
at_reduce=True): if rat_reduce: g = gcd(a,b) a //= g b //= g self.numerator = a self.b = b def pairwise_check(self,other): if type(other) in [int,np.int32,np.int64]: other = Rational(other,1,rat_reduce=False) elif type(other) in [float,np.float64]: other = continued_frac_approx_convergents...
return n_adic(convs[0].numerator,n,0)
conditional_block
Embedding.py
0: current = q.pop(0) chl = self.__gac__(current.address)#don't be too picky about types with this one ai = 0 for v in current.neighbors: if v.address is None: if ai >= len(chl): raise ValueError("The graph contains nodes of higher degree than the tree allows. Increase the tree branching par...
def cross(self,l): return Isometry((self.rot * l.rot + l.rot * self.trans * np.conj(l.trans)) / (self.rot * l.trans * np.conj(self.trans) + 1), (self.rot * l.trans + self.trans) / (self.rot * l.trans * np.conj(self.trans) + 1)) def inv(self): a = Isometry(np.conj(self.rot),0) b = Isometry(1,-self.trans...
return (self.rot * arg + self.trans) / (1 + np.conj(self.trans) * self.rot * arg)
identifier_body
Embedding.py
(self,etype,atype,dtype): super().__init__(etype,atype,dtype) def get_adr_child(self,adr,i): self.atype_check(adr) ch = self.__gchld__(adr,i) self.atype_check(ch) return ch def get_root(self): r = self.__grt__() self.atype_check(r) return r @abstractmethod def __gchld__(self,adr,i): pass @ab...
__init__
identifier_name
Embedding.py
0: current = q.pop(0) chl = self.__gac__(current.address)#don't be too picky about types with this one ai = 0 for v in current.neighbors: if v.address is None: if ai >= len(chl): raise ValueError("The graph contains nodes of higher degree than the tree allows. Increase the tree branching par...
for i in range(self.q): didx = (idx+i)%self.q disom = isom.cross(generators[didx]) dcoord = disom.evaluate(0) d_coords.append((dcoord,didx,disom)) return d_coords def __dist__(self,adrx,adry): coordx,_,_ = adrx coordy,_,_ = adry return hyper_dist(coordx,coordy) def __gac__(self,adr): retur...
coords,idx,isom = adr generators = define_generators(self.q) d_coords = []
random_line_split
etcdstatedriver.go
encapsulates the etcd endpoints used to communicate // with it. type EtcdStateDriverConfig struct { Etcd struct { Machines []string } } // EtcdStateDriver implements the StateDriver interface for an etcd based distributed // key-value store used to store config and runtime state for the netplugin.
// KeysAPI client.KeysAPI Client *client.Client } // Init the driver with a core.Config. func (d *EtcdStateDriver) Init(instInfo *core.InstanceInfo) error { var err error var endpoint *url.URL if instInfo == nil || len(instInfo.DbURL) == 0 { return errors.New("no etcd config found") } tlsInfo := transport.T...
type EtcdStateDriver struct { // Client client.Client
random_line_split
etcdstatedriver.go
ulates the etcd endpoints used to communicate // with it. type EtcdStateDriverConfig struct { Etcd struct { Machines []string } } // EtcdStateDriver implements the StateDriver interface for an etcd based distributed // key-value store used to store config and runtime state for the netplugin. type EtcdStateDriver s...
} cfg := client.Config{ Endpoints: instInfo.DbURL, TLS: tlsConfig, } d.Client, err = client.New(cfg) if err != nil { log.Fatalf("error creating etcd client. Err: %v", err) } return nil } // Deinit is currently a no-op. func (d *EtcdStateDriver) Deinit() { d.Client.Close() } // Write state to key wi...
{ return core.Errorf("invalid etcd URL scheme %q", endpoint.Scheme) }
conditional_block
etcdstatedriver.go
ulates the etcd endpoints used to communicate // with it. type EtcdStateDriverConfig struct { Etcd struct { Machines []string } } // EtcdStateDriver implements the StateDriver interface for an etcd based distributed // key-value store used to store config and runtime state for the netplugin. type EtcdStateDriver s...
// ClearState removes key from etcd func (d *EtcdStateDriver) ClearState(key string) error { ctx, cancel := context.WithTimeout(context.Background(), ctxTimeout) defer cancel() _, err := d.Client.KV.Delete(ctx, key) return err } // ReadState reads key into a core.State with the unmarshaling function. func (d *E...
{ watcher := d.Client.Watch(context.Background(), baseKey, client.WithPrefix()) go d.channelEtcdEvents(watcher, rsps) return nil }
identifier_body
etcdstatedriver.go
ulates the etcd endpoints used to communicate // with it. type EtcdStateDriverConfig struct { Etcd struct { Machines []string } } // EtcdStateDriver implements the StateDriver interface for an etcd based distributed // key-value store used to store config and runtime state for the netplugin. type EtcdStateDriver s...
(instInfo *core.InstanceInfo) error { var err error var endpoint *url.URL if instInfo == nil || len(instInfo.DbURL) == 0 { return errors.New("no etcd config found") } tlsInfo := transport.TLSInfo{ CertFile: instInfo.DbTLSCert, KeyFile: instInfo.DbTLSKey, TrustedCAFile: instInfo.DbTLSCa, } tlsCon...
Init
identifier_name
deep_consensus.py
topology = input_args n_nodes = int(n_nodes) # Cluster specification; one port for the PS (usually 2222) and as many ports as needed # for the workers parameter_servers = ["localhost:2222"] workers = ["localhost:{}".format(i) for i in range(2223, 2223 + n_nodes)] cluster = tf.train.ClusterSpec({"ps": parameter_se...
(grads, vars_, learning_rate): mul_grads = [] for grad, var in zip(grads, vars_): mul_grad = tf.scalar_mul(learning_rate, grad) mul_grads.append(mul_grad) return mul_grads with tf.name_scope("softmax"): assign_ops = [] ...
grads_x_lr
identifier_name
deep_consensus.py
np.random.seed(SEED) rn.seed(SEED) # Raise error if trying to seed after graph construction if len(tf.get_default_graph()._nodes_by_id.keys()) > 0: raise RuntimeError("Seeding is not supported after building part of the graph. " "Please move set_seed to the beginning of your code.") # R...
os.environ['PYTHONHASHSEED'] = '0' SEED = 5 tf.set_random_seed(SEED)
random_line_split
deep_consensus.py
10], name="y-input") # Initialize weights and biases (parameter vectors) with tf.name_scope("weights"): W_conv1 = tf.Variable(tf.truncated_normal([5, 5, 1, 32], stddev=0.1, seed=SEED)) W_conv2 = tf.Variable(tf.truncated_normal([5, 5, 32, 64], stddev=0.1, seed=SEED)) ...
print("Iteration NO: ", count) batch_x, batch_y = mnist.train.next_batch(batch_size, shuffle=False) # perform the operations we defined earlier on batch _, cost = sess.run([train_op, cross_entropy], feed...
conditional_block
deep_consensus.py
, topology = input_args n_nodes = int(n_nodes) # Cluster specification; one port for the PS (usually 2222) and as many ports as needed # for the workers parameter_servers = ["localhost:2222"] workers = ["localhost:{}".format(i) for i in range(2223, 2223 + n_nodes)] cluster = tf.train.ClusterSpec({"ps": parameter_s...
with tf.name_scope("softmax"): assign_ops = [] for tensor1, tensor2 in zip((W_conv1, W_conv2, W_fc1, W_fc2, b_conv1, b_conv2, b_fc1, b_fc2), worker.vars_): assign_ops.append(tf.assign(tensor1, tensor2)) # This line must be equivalent to the...
mul_grads = [] for grad, var in zip(grads, vars_): mul_grad = tf.scalar_mul(learning_rate, grad) mul_grads.append(mul_grad) return mul_grads
identifier_body
rally.rs
VehToVehSystem, CollisionWeaponFireHitboxSystem, MoveParticlesSystem, MoveWeaponFireSystem, PathingLinesSystem, VehicleMoveSystem, VehicleShieldArmorHealthSystem, VehicleStatusSystem, VehicleTrackingSystem, VehicleWeaponsSystem, }; pub const PLAYER_CAMERA: bool = false; pub const DEBUG_LINES: bool = false;...
StateEvent::Input(_input) => { //log::info!("Input Event detected: {:?}.", input); Trans::None } }
{ // log::info!( // "[HANDLE_EVENT] You just interacted with a ui element: {:?}", // ui_event // ); Trans::None }
conditional_block
rally.rs
VehToVehSystem, CollisionWeaponFireHitboxSystem, MoveParticlesSystem, MoveWeaponFireSystem, PathingLinesSystem, VehicleMoveSystem, VehicleShieldArmorHealthSystem, VehicleStatusSystem, VehicleTrackingSystem, VehicleWeaponsSystem, }; pub const PLAYER_CAMERA: bool = false; pub const DEBUG_LINES: bool = false;...
} fn on_resume(&mut self, _data: StateData<'_, GameData<'_, '_>>) { self.paused = false; } fn on_stop(&mut self, data: StateData<'_, GameData<'_, '_>>) { if let Some(root_entity) = self.ui_root { data.world .delete_entity(root_entity) .expect...
fn on_pause(&mut self, _data: StateData<'_, GameData<'_, '_>>) { self.paused = true;
random_line_split
rally.rs
)); let weapon_fire_resource: WeaponFireResource = initialize_weapon_fire_resource(world, self.sprite_sheet_handle.clone().unwrap()); initialize_timer_ui(world); world.insert(ArenaNavMesh { vertices: Vec::new(), triangles: Vec::new(), }); ...
{ write!(f, "{:?}", self) }
identifier_body
rally.rs
VehToVehSystem, CollisionWeaponFireHitboxSystem, MoveParticlesSystem, MoveWeaponFireSystem, PathingLinesSystem, VehicleMoveSystem, VehicleShieldArmorHealthSystem, VehicleStatusSystem, VehicleTrackingSystem, VehicleWeaponsSystem, }; pub const PLAYER_CAMERA: bool = false; pub const DEBUG_LINES: bool = false;...
(&mut self, data: StateData<'_, GameData<'_, '_>>) { if let Some(root_entity) = self.ui_root { data.world .delete_entity(root_entity) .expect("Failed to remove Game Screen"); } let fetched_game_score = data.world.try_fetch::<GameScore>(); if ...
on_stop
identifier_name
file_header.go
if err == io.EOF { break } return nil, "", err } } return nil, "", nil } func (p *parser) ParseGitFileHeader() (*File, error) { const prefix = "diff --git " if !strings.HasPrefix(p.Line(0), prefix) { return nil, nil } header := p.Line(0)[len(prefix):] defaultName, err := parseGitHeaderName(he...
if err := p.Next(); err != nil {
random_line_split
file_header.go
if err := p.Next(); err != nil { if err == io.EOF { break } return nil, err } if end { break } } if f.OldName == "" && f.NewName == "" { if defaultName == "" { return nil, p.Errorf(0, "git file header: missing filename information") } f.OldName = defaultName f.NewName = defaultN...
{ return nil, p.Errorf(1, "git file header: %v", err) }
conditional_block
file_header.go
able) fragment header if len(p.Line(2)) < len(shortestValidFragHeader) || !strings.HasPrefix(p.Line(2), "@@ -") { return nil, nil } // advance past the first two lines so parser is after the header // no EOF check needed because we know there are >=3 valid lines if err := p.Next(); err != nil { return nil, er...
parseGitHeaderIndex
identifier_name
file_header.go
f.NewName = defaultName } if (f.NewName == "" && !f.IsDelete) || (f.OldName == "" && !f.IsNew) { return nil, p.Errorf(0, "git file header: missing filename information") } return f, nil } func (p *parser) ParseTraditionalFileHeader() (*File, error) { const shortestValidFragHeader = "@@ -1 +1 @@\n" const ( ...
func parseGitHeaderNewName(f *File, line, defaultName string) error { name, _, err := parseName(line, '\t', 1) if err != nil { return err } if f.NewName == "" && !f.IsDelete { f.NewName = name return nil } return verifyGitHeaderName(name, f.NewName, f.IsDelete, "new") } func parseGitHeaderOldMode(f *File...
{ name, _, err := parseName(line, '\t', 1) if err != nil { return err } if f.OldName == "" && !f.IsNew { f.OldName = name return nil } return verifyGitHeaderName(name, f.OldName, f.IsNew, "old") }
identifier_body
data_helper.py
, 'DATA SOURCES')['filename_prev'] file_pop_pred = ConfigSectionMap(config, 'DATA SOURCES')['filename_pop_pred'] file_best_weights = ConfigSectionMap(config, 'DATA SOURCES')['filename_best_weights'] file_music_dataset = ConfigSectionMap(config, 'DATA SOURCES')['filename_music_dataset'] file_final_res = ...
elif language == 'da': valid_language = 'danish' elif language == 'nl': valid_language = 'dutch' elif language == 'fr': valid_language = 'french' elif language == 'de': valid_language = 'german' elif language == 'el': valid_language = 'greek' elif languag...
valid_language = 'azerbaijani'
conditional_block
data_helper.py
latin-1') as reader: df = pd.read_csv(reader,index_col=0) return df def get_text_language(language): valid_language = '' if language =='en': valid_language = 'english' elif language == 'ar': valid_language = 'arabic' elif language == 'az': valid_language = 'aze...
cols_mfccs = ['MFCSS_' + str(i + 1) for i in range(mfcc[0])] k = [mfcc[1] for i in range(mfcc[0])] audio_features = dict(zip(cols_mfccs, k)) cols_chroma = ['Chroma_' + str(i + 1) for i in range(chromagram[0])] k = [chromagram[1] for i in range(chromagram[0])] audio_features .update(zip(cols_chroma,...
identifier_body
data_helper.py
': valid_language = 'kazakh' # elif language == 'ne': valid_language = 'nepali' elif language == 'no': valid_language = 'norwegian' elif language == 'pt': valid_language = 'portuguese' elif language == 'ro': valid_language = 'romanian' elif language ==...
str2bool
identifier_name
data_helper.py
(config, 'DATA SOURCES')['filename_prev'] file_pop_pred = ConfigSectionMap(config, 'DATA SOURCES')['filename_pop_pred'] file_best_weights = ConfigSectionMap(config, 'DATA SOURCES')['filename_best_weights'] file_music_dataset = ConfigSectionMap(config, 'DATA SOURCES')['filename_music_dataset'] file_final...
'East Asian':links[133:145], 'South & southeast Asian':links[146:164], 'Avant-garde':links[165:169],'Blues':links[170:196], 'Caribbean':links[197:233], 'Comedy':links[234:237], 'Country':links[238:273], 'Ea...
# in this case, all of the links we're in a '<li>' brackets. for i in b.find_all(name = 'li'): links.append(i.text) general_genres = {'African':links[81:127], 'Asian':links[128:132],
random_line_split
Minebot.py
4', 'Diamond'], ['265', 'Iron Ingot'], ['266', 'Gold Ingot'], ['267', 'Iron Sword'], ['268', 'Wooden Sword'], ['269', 'Wooden Shovel'], ['270', 'Wooden Pickaxe'], ['271', 'Wooden Axe'], ['272', 'Stone Sword'], ['273', 'Stone Shovel'], ['274', 'Stone Pickaxe'], ['275', 'Stone Axe'], ['276', 'Diamond Sw...
random_line_split
Minebot.py
Brown Wool'], ['35:13', 'Dark Green Wool'], ['35:14', 'Red Wool'], ['35:15', 'Black Wool'], ['37', 'Yellow Flower'], ['38', 'Red Rose'], ['39', 'Brown Mushroom'], ['40', 'Red Mushroom'], ['41', 'Gold Block'], ['42', 'Iron Block'], ['43', 'Double Stone Slab'], ['43:1', 'Double Sandstone Slab'], ['43:2'...
sres = filter(exact,items) if sres or len(res)==1: toMinecraft("ID: "+str(res[0])) return res[0][0] if len(res) > 1: lst = ", ".join(map(lambda x:" ".join(x[1:
toMinecraft("No items found") return
conditional_block
Minebot.py
Pressure Plate'], ['71', 'Iron Door'], ['72', 'Wooden Pressure Plate'], ['73', 'Redstone Ore'], ['74', 'Glowing Redstone Ore'], ['75', 'Redstone Torch (off)'], ['76', 'Redstone Torch (on)'], ['77', 'Stone Button'], ['78', 'Snow'], ['79', 'Ice'], ['80', 'Snow Block'], ['81', 'Cactus'], ['82', 'Clay'], ['83', 'S...
print "Lookup:",shorthand mc.send("list\n") resp = mc.recv(1024) if "Connected players:" not in resp: toMinecraft("Something strange happend...") toMinecraft(resp) return shorthand players = resp.split("players:")[1].replace(",","").split() matches = filter(lambda x:shorthand...
identifier_body
Minebot.py
'Redstone Ore'], ['74', 'Glowing Redstone Ore'], ['75', 'Redstone Torch (off)'], ['76', 'Redstone Torch (on)'], ['77', 'Stone Button'], ['78', 'Snow'], ['79', 'Ice'], ['80', 'Snow Block'], ['81', 'Cactus'], ['82', 'Clay'], ['83', 'Sugar Cane'], ['84', 'Jukebox'], ['85', 'Fence'], ['86', 'Pumpkin'], ['8...
mcThread
identifier_name
judger.rs
eng_protocol::internal::{ConnectionSettings, ErrorInfo, PartialConnectionSettings}; use heng_protocol::internal::ws_json::{ CreateJudgeArgs, FinishJudgeArgs, Message as RpcMessage, ReportStatusArgs, Request as RpcRequest, Response as RpcResponse, UpdateJudgeArgs, }; use std::sync::atomic::{AtomicU32, AtomicU6...
}; let _ = self.session.sender.send(Close(Some(close_frame))).await; return Err(err.into()); } }; match rpc_msg { RpcMessage::Request { seq, body, ....
{ info!("starting main loop"); while let Some(frame) = ws_stream.next().await { use tungstenite::Message::*; let frame = frame?; match frame { Close(reason) => { warn!(?reason, "ws session closed"); return Ok((...
identifier_body
judger.rs
eng_protocol::internal::{ConnectionSettings, ErrorInfo, PartialConnectionSettings}; use heng_protocol::internal::ws_json::{ CreateJudgeArgs, FinishJudgeArgs, Message as RpcMessage, ReportStatusArgs, Request as RpcRequest, Response as RpcResponse, UpdateJudgeArgs, }; use std::sync::atomic::{AtomicU32, AtomicU6...
(ws_stream: WsStream) -> Result<()> { let config = inject::<Config>(); let (ws_sink, ws_stream) = ws_stream.split(); let (tx, rx) = mpsc::channel::<WsMessage>(4096); task::spawn( ReceiverStream::new(rx) .map(Ok) .forward(ws_sink) ...
run
identifier_name
judger.rs
eng_protocol::internal::{ConnectionSettings, ErrorInfo, PartialConnectionSettings}; use heng_protocol::internal::ws_json::{ CreateJudgeArgs, FinishJudgeArgs, Message as RpcMessage, ReportStatusArgs, Request as RpcRequest, Response as RpcResponse, UpdateJudgeArgs, }; use std::sync::atomic::{AtomicU32, AtomicU6...
let judger = Arc::new(Self { settings: Settings { status_report_interval: AtomicU64::new(1000), }, session: WsSession { sender: tx, seq: AtomicU32::new(0), callbacks: DashMap::new(), }, c...
ReceiverStream::new(rx) .map(Ok) .forward(ws_sink) .inspect_err(|err| error!(%err, "ws forward error")), );
random_line_split
augment.py
1, 0) """ def __init__(self, swaps): self.swaps = swaps def __call__(self, image): """ Args: image (Tensor): image tensor to be transformed Return: a tensor with channels swapped according to swap """ # if torch.is_tensor(image): ...
s, labels): if random.randint(5): return image, boxes, labels height, width, depth = image.shape ratio = random.uniform(1, 4) left = random.uniform(0, width * ratio - width) top = random.uniform(0, height * ratio - height) expand_image = np.zeros( ...
elf, image, boxe
identifier_body
augment.py
(box_a[:, 2:], box_b[2:]) min_xy = np.maximum(box_a[:, :2], box_b[:2]) inter = np.clip((max_xy - min_xy), a_min=0, a_max=np.inf) return inter[:, 0] * inter[:, 1] def jaccard_numpy(box_a, box_b): """Compute the jaccard overlap of two sets of boxes. The jaccard overlap is simply the intersection ov...
nsform(x, y) xx.append(x_) yy.append(y_) box_rot = [min(xx) + dx, min(yy) + dy, max(xx) + dx, max(yy) + dy] boxes_rot.append(box_rot) img_out,box_out = np.array(img_rotate)/255.0, np.array(boxes_rot) return img_out,box_out, labels # class Augmenta...
conditional_block
augment.py
(self, image, boxes=None, labels=None): return image.astype(np.float32), boxes, labels class RandomSaturation(object): def __init__(self, lower=0.5, upper=1.5): self.lower = lower self.upper = upper assert self.upper >= self.lower, "contrast upper must be >= lower." assert ...
__call__
identifier_name
augment.py
= cv2.cvtColor(image, cv2.COLOR_BGR2HSV) elif self.current == 'HSV' and self.transform == 'BGR': image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR) else: raise NotImplementedError return image, boxes, labels class RandomContrast(object): def __init__(self, lower=0.5, u...
random_line_split
views.py
config["APP_KEY"] return render_template('main/index.html', callback=callback, app_key=app_key) class Update(MethodView): decorators = [login_required] def get(self, page): per_page = 10 unpushed_entry = WaitingQueue.query.order_by(WaitingQueue.cutting_weight.desc()).all() pa...
': title = data['title'] UserOperation(user_id=current_user.id, operation=Operation.DELETE, title=title).save() query = WaitingQueue.query.filter_by(title=data['title']).first() if query: query.delete() response = jsonify({'result': True}) ...
title = data["title"] env = Env() current_weight = env.get("CUTTING_WEIGHT_INIT") entry = WaitingQueue.query.filter_by(title=title).first() if entry: entry.cutting_weight = current_weight + 1 # FIXME: 即使条目处于权重最高状态亦可增加权限 entry.save() ...
conditional_block
views.py
["APP_KEY"] return render_template('main/index.html', callback=callback, app_key=app_key) class Update(MethodView): decorators = [login_required] def get(self, page): per_page = 10 unpushed_entry = WaitingQueue.query.order_by(WaitingQueue.cutting_weight.desc()).all() paginatio...
user_info = User.query.filter_by(username=username, deleted=False).first() if user_info: form = self.admin_form() form.email.data = user_info.email form.about_me.data = user_info.aboutme form.role.data = user_info.role.na...
identifier_name
views.py
try: from koushihime.crontab import push push() except Exception as e: flash(u"推送失败: {}".format(str(e))) flash(u"操作成功,词条将立即推送") return redirect(url_for('main.mupdate')) @staticmethod def check_push_validate(title): moegirl...
identifier_body
views.py
return response class ManualUpdate(MethodView): decorators = [login_required] def __init__(self): self.form = PushForm def get(self): return render_template('main/mupdate.html', form=self.form(), pushtime=10) def post(self): if not current_user.can(Permission.MANUAL_PUSH): ...
return render_template('main/success.html') else:
random_line_split
bfr.py
]) centroid = [] for _ in range(dim): centroid.append(0) for point in points: for i in range(dim): centroid[i] += point[1][i] tmp = [] for x in centroid: tmp.append(x/len(points)) centroid = tmp return centroid def comp(new_centroid, l_ctd): ...
for _ in range(k-1): dis = [] for point in points: #calculate tmp_ds = [] for i, c in enumerate(centroid): if point != c: # print("point",point) # print("c",c) tmp_ds.append((eucl...
random_line_split
bfr.py
centroid = [] for _ in range(dim): centroid.append(0) for point in points: for i in range(dim): centroid[i] += point[1][i] tmp = [] for x in centroid: tmp.append(x/len(points)) centroid = tmp return centroid def comp(new_centroid, l_ctd): ne...
(cluster,DIM): _sum = [] _sumq = [] for _ in range(DIM): _sum.append(0) _sumq.append(0) for point in cluster: _sum = point_addition(_sum, point[1],1) _sumq = point_addition(_sumq, point[1],2) lv = len(cluster) res = [lv, _sum, _sumq] return res def merge_list(...
cal_cluster_squ
identifier_name
bfr.py
centroid = [] for _ in range(dim): centroid.append(0) for point in points: for i in range(dim): centroid[i] += point[1][i] tmp = [] for x in centroid: tmp.append(x/len(points)) centroid = tmp return centroid def comp(new_centroid, l_ctd): ne...
#cal nonsample Sample_set = {point[0] for point in sample_points} non_sample = [] for point in POINTS: if point[0] not in Sample_set: non_sample.append(point) new_clusters = kmeans(non_sample, 3*n_clusters) ...
DS.append(cal_cluster_squ(cluster,DIM)) idx = [] for point in cluster: idx.append(point[0]) DS_CLUSTER.append(idx)
conditional_block
bfr.py
def find_centroid(points): points = list(points) dim = len(points[0][1]) centroid = [] for _ in range(dim): centroid.append(0) for point in points: for i in range(dim): centroid[i] += point[1][i] tmp = [] for x in centroid: tmp.append(x/len(points)) ...
ds = [] # print(point) for i, c in enumerate(centroid): if point != c: # print(c) if c == 0: print(point, centroid) eud = euclidean(point, (0,c)) ds.append((eud,i)) min_ds = min(ds) return (min_ds[1], point)
identifier_body
DoGrouping.py
other labels d1 = labelObj.dCollocates d1.update(labelObj.dCollocatesOther) lsPossible = [] for key2, labelObj2 in spreadObj2.dLabels.items(): # ...
writeSpreadsheet
identifier_name
DoGrouping.py
for key2, labelObj2 in spreadObj2.dLabels.items(): # already paired this label... #if same label just set cosine similarity to 1 c_sim = 0 if labelObj.strTextA...
rs = ReadSpreadsheets() print 'reading spreadsheets' rs.readSpreadsheets(lsSpreadsheets) dAllCombos = {} # dAll2 = {} print 'comparing spreadsheets' i = 0 for spreadObj in rs.lsSpreadsheetObjs[0:-1]: # print spreadObj for spreadOb...
identifier_body
DoGrouping.py
dMapRev global MIN_COSINE lsGrouping = [] lsGroupingIndex = [] lsGroupingScore = [] for i in range(0, len(lsMatrix)): # get max num in each column lsCol = [] for j in range(i, len(lsMatrix)): currElem = lsMatrix[j][i] ...
try: export_file.write('{},,'.format(label.lsOrigColumnValues[i-2])) except: export_file.write(',,')
conditional_block
DoGrouping.py
Combos = {} # dAll2 = {} print 'comparing spreadsheets' i = 0 for spreadObj in rs.lsSpreadsheetObjs[0:-1]: # print spreadObj for spreadObj2 in rs.lsSpreadsheetObjs[i + 1:]: dAll = {} for key, labelObj in spreadObj.dLabels.it...
lsMerged = [list(set(lsObj)) for lsObj in lsMerged] #create new name lsMerged2=[] for ls1 in lsMerged: ls2 = self.findName(ls1) lsMerged2.extend(ls2) return lsMerged2, list(set(lsAlone)) ...
random_line_split
parsers.py
LER, FIT_DATA_UNCLASSIFIED from app.utils.filesystem import get_relative_path from app.utils.mongodb import mongodb logger = logging.getLogger(__name__) class Parser(metaclass=abc.ABCMeta): class FileParsingError(PyrError): pass _DEFAULT_SAMPLING_FREQUENCY = 60 _COORDINATE_SYSTEM = COORDINATE_SY...
f = open(file_path, 'rb') tags = exifread.process_file(f) image_info = {} gps_info = {} thumbnail_info = {} maker_info = {} exit_info = {} other_info = {} for tag in tags: key_array = tag.split(' ') category = key_array[0].lower() ...
identifier_body
parsers.py
ographic.models import Coordinate from app.parse.constants import FIT_DATA_ACTIVITY_RECORD, FIT_DATA_GEAR, FIT_DATA_ACTIVITY, PHOTO_DATA_OTHER, \ PHOTO_DATA_MAKER, \ PHOTO_DATA_THUMBNAIL, PHOTO_DATA_EXIF, PHOTO_DATA_GPS, PHOTO_DATA_IMAGE, FIT_DATA_TRAVELLER, FIT_DATA_UNCLASSIFIED from app.utils.filesystem impor...
(Parser): def _parse(self): return self.parse_exif(self._file_path) @staticmethod def parse_exif(file_path): f = open(file_path, 'rb') tags = exifread.process_file(f) image_info = {} gps_info = {} thumbnail_info = {} maker_info = {} exit_info...
PhotoParser
identifier_name
parsers.py
Meta): class FileParsingError(PyrError): pass _DEFAULT_SAMPLING_FREQUENCY = 60 _COORDINATE_SYSTEM = COORDINATE_SYSTEM_WGS84 _result = None _sampling_frequency: int _file_path: str def __init__(self, file): self._get_file_path(file) def _get_file_path(self, obj): ...
gps_info.update(item)
conditional_block
parsers.py
ographic.models import Coordinate from app.parse.constants import FIT_DATA_ACTIVITY_RECORD, FIT_DATA_GEAR, FIT_DATA_ACTIVITY, PHOTO_DATA_OTHER, \ PHOTO_DATA_MAKER, \ PHOTO_DATA_THUMBNAIL, PHOTO_DATA_EXIF, PHOTO_DATA_GPS, PHOTO_DATA_IMAGE, FIT_DATA_TRAVELLER, FIT_DATA_UNCLASSIFIED from app.utils.filesystem impor...
data_for_store.update(extra_data) return mongodb.insert(collection, data_for_store) class FitParser(Parser): _activity_record: [] = [] _gears: [] = [] _activity: [] = [] _traveller: [] = [] _unclassified: [] = [] def _parse(self): try: fit_file = fitpa...
data_for_store = {'data': self._result, 'path': get_relative_path(self._file_path)} if extra_data is not None:
random_line_split
compile.rs
Document; use typst::eval::{eco_format, Tracer}; use typst::geom::Color; use typst::syntax::{FileId, Source}; use typst::World; use crate::args::{CompileCommand, DiagnosticFormat, OutputFormat}; use crate::watch::Status; use crate::world::SystemWorld; use crate::{color_stream, set_failed}; type CodespanResult<T> = Re...
Severity::Warning => Diagnostic::warning(), } .with_message(diagnostic.message.clone()) .with_notes( diagnostic .hints .iter() .map(|e| (eco_format!("hint: {e}")).into()) .collect(), ) .with_l...
for diagnostic in warnings.iter().chain(errors.iter()) { let diag = match diagnostic.severity { Severity::Error => Diagnostic::error(),
random_line_split
compile.rs
Document; use typst::eval::{eco_format, Tracer}; use typst::geom::Color; use typst::syntax::{FileId, Source}; use typst::World; use crate::args::{CompileCommand, DiagnosticFormat, OutputFormat}; use crate::watch::Status; use crate::world::SystemWorld; use crate::{color_stream, set_failed}; type CodespanResult<T> = Re...
.iter() .map(|e| (eco_format!("hint: {e}")).into()) .collect(), ) .with_labels(vec![Label::primary( diagnostic.span.id(), world.range(diagnostic.span), )]); term::emit(&mut w, &config, world, &diag)?; // St...
{ let mut w = match diagnostic_format { DiagnosticFormat::Human => color_stream(), DiagnosticFormat::Short => StandardStream::stderr(ColorChoice::Never), }; let mut config = term::Config { tab_width: 2, ..Default::default() }; if diagnostic_format == DiagnosticFormat::Short { co...
identifier_body
compile.rs
Document; use typst::eval::{eco_format, Tracer}; use typst::geom::Color; use typst::syntax::{FileId, Source}; use typst::World; use crate::args::{CompileCommand, DiagnosticFormat, OutputFormat}; use crate::watch::Status; use crate::world::SystemWorld; use crate::{color_stream, set_failed}; type CodespanResult<T> = Re...
(&'a self, id: FileId) -> CodespanResult<Self::Name> { let vpath = id.vpath(); Ok(if let Some(package) = id.package() { format!("{package}{}", vpath.as_rooted_path().display()) } else { // Try to express the path relative to the working directory. vpath ...
name
identifier_name
main.rs
_margin_top(4.0); //bottom_container.set_margin_bottom(4.0); bottom_container.set_margin_left(0.0); bottom_container.set_margin_right(0.0); bottom_container.set_height(Length::Fixed(32.0)); bottom_container.set_width(Length::Stretch { min: 0.0, max: f32::INFINITY }); let moon_img = Rc::new(Picture::from_encoded_...
random_line_split
main.rs
.0); bottom_container.set_margin_right(0.0); bottom_container.set_height(Length::Fixed(32.0)); bottom_container.set_width(Length::Stretch { min: 0.0, max: f32::INFINITY }); let moon_img = Rc::new(Picture::from_encoded_bytes(include_bytes!("../resource/moon.png"))); let light_img = Rc::new(Picture::from_encoded_by...
check_for_updates
identifier_name
main.rs
resource/usage.png")); let help_screen = Rc::new(HelpScreen::new(usage_img)); let bottom_container = Rc::new(HorizontalLayoutContainer::new()); //bottom_container.set_margin_top(4.0); //bottom_container.set_margin_bottom(4.0); bottom_container.set_margin_left(0.0); bottom_container.set_margin_right(0.0); bottom...
{ std::fs::create_dir_all(&config_folder).unwrap(); }
conditional_block
mod.rs
::Guild(channel)) => channel, Some(_other_channel) => { println!( "Warning: guild message was supposedly sent in a non-guild channel. Denying invocation" ); return false; } None => return false, }; // If member not in cache (probably b...
else { (self.options.on_error)( err, crate::ErrorContext::Command(crate::CommandErrorContext::Prefix(ctx)), ) .await; } } } Event::...
{ (on_error)(err, ctx).await; }
conditional_block
mod.rs
::Guild(channel)) => channel, Some(_other_channel) => { println!( "Warning: guild message was supposedly sent in a non-guild channel. Denying invocation" ); return false; } None => return false, }; // If member not in cache (probably b...
(&self) -> &U { // We shouldn't get a Message event before a Ready event. But if we do, wait until // the Ready event does come and the resulting data has arrived. loop { match self.user_data.get() { Some(x) => break x, None => tokio::time::sleep(std::...
get_user_data
identifier_name
mod.rs
); return false; } None => return false, }; // If member not in cache (probably because presences intent is not enabled), retrieve via HTTP let member = match guild.members.get(&ctx.author().id) { Some(x) => x.clone(), None => match ctx .d...
{ if required_permissions.is_empty() { return true; } let guild_id = match ctx.guild_id() { Some(x) => x, None => return true, // no permission checks in DMs }; let guild = match ctx.discord().cache.guild(guild_id) { Some(x) => x, None => return false, // Gu...
identifier_body
mod.rs
::Guild(channel)) => channel, Some(_other_channel) => { println!( "Warning: guild message was supposedly sent in a non-guild channel. Denying invocation" ); return false; } None => return false, }; // If member not in cache (probably b...
pub fn application_id(&self) -> serenity::ApplicationId { self.application_id } /// Returns the serenity's client shard manager. pub fn shard_manager(&self) -> std::sync::Arc<tokio::sync::Mutex<ShardManager>> { self.shard_manager .lock() .unwrap() .cl...
&self.options } /// Returns the application ID given to the framework on its creation.
random_line_split
plugin.go
[]string MatchEmail bool Port int Tunnel bool Debug bool Domain string AutoTLS bool Host []string } // Plugin values. Plugin struct { Repo Repo Build Build Config Config } // Audio format Audio struct { URL string Duration in...
} } } }) mux.HandleFunc("/metrics", func(w http.ResponseWriter, req *http.Request) { promhttp.Handler().ServeHTTP(w, req) }) // Setup HTTP Server for receiving requests from LINE platform mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintln(w, "Welcome to Line webhook p...
{ log.Print(err) }
conditional_block
plugin.go
[]string MatchEmail bool Port int Tunnel bool Debug bool Domain string AutoTLS bool Host []string } // Plugin values. Plugin struct { Repo Repo Build Build Config Config } // Audio format Audio struct { URL string Duration in...
func trimElement(keys []string) []string { var newKeys []string for _, value := range keys { value = strings.Trim(value, " ") if len(value) == 0 { continue } newKeys = append(newKeys, value) } return newKeys } func convertImage(value, delimiter string) []string { values := trimElement(strings.Split...
{ // Support metrics m := NewMetrics() prometheus.MustRegister(m) }
identifier_body
plugin.go
Location []string MatchEmail bool Port int Tunnel bool Debug bool Domain string AutoTLS bool Host []string } // Plugin values. Plugin struct { Repo Repo Build Build Config Config } // Audio format Audio struct { URL string Dur...
// Bot is new Line Bot clien. func (p Plugin) Bot() (*linebot.Client, error) { if len(p.Config.ChannelToken) == 0 || len(p.Config.ChannelSecret) == 0 { log.Println("missing line bot config") return nil, errors.New("missing line bot config") } return linebot.New(p.Config.ChannelSecret, p.Config.ChannelToken) } ...
}
random_line_split
plugin.go
Audio format Audio struct { URL string Duration int } // Location format Location struct { Title string Address string Latitude float64 Longitude float64 } ) var ( // ReceiveCount is receive notification count ReceiveCount int64 // SendCount is send notification count SendCount int64...
Exec
identifier_name
render.rs
0.0f, 1.0f ); int index = flipped != 0 ? flipped_vertex_id() : gl_VertexID; if (frame == -1) texcoord = TEXCOORD_FROM_ID[index]; else texcoord = frames[frame * 4 + index]; texcoord.y = 1 - texcoord.y; } ...
{ let count_ptr: *mut usize = &mut self.texcoord_count; slice::from_raw_parts_mut::<Texcoords>( transmute(count_ptr.offset(1)), self.texcoord_count ) }
identifier_body
render.rs
cam_pos; // in pixels uniform vec2 sprite_size; // in pixels uniform float scale; out vec2 texcoord; const vec2 TEXCOORD_FROM_ID[4] = vec2[4]( vec2(1.0, 1.0), vec2(1.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 1.0) ); vec2 from_pixel(vec2 pos) ...
} } /* fn put_texcoord(&mut self, index: usize, texcoord: Texcoords) { self.texcoords_mut()[index] = texcoord; } */ // NOTE this should be properly merged with add_frames. pub fn generate_texcoords_buffer( &mut self, frame_width: usize, frame_height: usize, space: ...
{ gl::Uniform2fv( frames_uniform, frames_len as GLint * 4, transmute(&(&*self.texcoords_space)[0]) ); }
conditional_block
render.rs
cam_pos; // in pixels uniform vec2 sprite_size; // in pixels uniform float scale; out vec2 texcoord; const vec2 TEXCOORD_FROM_ID[4] = vec2[4]( vec2(1.0, 1.0), vec2(1.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 1.0) ); vec2 from_pixel(vec2 pos) ...
macro_rules! check_log( ($typ:expr, $get_iv:ident | $get_log:ident $val:ident $status:ident $on_error:ident) => ( unsafe { let mut status = 0; gl::$get_iv($val, gl::$status, &mut status); if status == 0 { let mut len = 0; gl::$get_iv($val,...
color = texture(tex, texcoord); } ";
random_line_split
render.rs
- gl_VertexID; } void main() { vec2 pixel_screen_pos = (position - cam_pos) * 2; gl_Position = vec4( (vertex_pos * from_pixel(sprite_size) + from_pixel(pixel_screen_pos)) * scale, 0.0f, 1.0f ); int index = flipped ...
texcoords
identifier_name
Assignment+2.py
]: import nltk import pandas as pd import numpy as np # If you would like to work with the raw text you can use 'moby_raw' with open('moby.txt', 'r') as f: moby_raw = f.read() # If you would like to work with the novel in nltk.Text format you can use 'text1' moby_tokens = nltk.word_tokenize(moby_raw) text1 ...
# # Each of the recommenders should provide recommendations for the three default words provided: `['cormulent', 'incendenece', 'validrate']`. # In[94]: from nltk.corpus import words correct_spellings = words.words() # ### Question 9 # # For this recommender, your function should provide recommendations for the...
# # *Each of the three different recommenders will use a different distance measure (outlined below).
random_line_split
Assignment+2.py
]: import nltk import pandas as pd import numpy as np # If you would like to work with the raw text you can use 'moby_raw' with open('moby.txt', 'r') as f: moby_raw = f.read() # If you would like to work with the novel in nltk.Text format you can use 'text1' moby_tokens = nltk.word_tokenize(moby_raw) text1 ...
(): return len(set(nltk.word_tokenize(moby_raw))) # or alternatively len(set(text1)) example_two() # ### Example 3 # # After lemmatizing the verbs, how many unique tokens does text1 have? # # *This function should return an integer.* # In[85]: from nltk.stem import WordNetLemmatizer def example_three(...
example_two
identifier_name
Assignment+2.py
]: import nltk import pandas as pd import numpy as np # If you would like to work with the raw text you can use 'moby_raw' with open('moby.txt', 'r') as f: moby_raw = f.read() # If you would like to work with the novel in nltk.Text format you can use 'text1' moby_tokens = nltk.word_tokenize(moby_raw) text1 ...
def answer_ten(entries=['cormulent', 'incendenece', 'validrate']): max_dists, max_words, quadgrams = {}, {}, {} for entry in entries: max_dists[entry] = 1.0 max_words[entry] = None quadgrams[entry] = create_quadgram(entry) def try_correct(correct_spelling, incorrect_spelling): ...
quadgrams = [] for i in range(0, len(w)-3): quadgrams.append(w[i:i+4]) return set(quadgrams)
identifier_body
Assignment+2.py
work with the novel in nltk.Text format you can use 'text1' moby_tokens = nltk.word_tokenize(moby_raw) text1 = nltk.Text(moby_tokens) # ### Example 1 # # How many tokens (words and punctuation symbols) are in text1? # # *This function should return an integer.* # In[83]: def example_one(): return len(n...
try_correct(correct_spelling, entry)
conditional_block
vault.rs
pub fn token(&self) -> &str { &self.token } /// Returns the Vault address pub fn address(&self) -> &str { &self.address } /// Returns the HTTP Client pub fn http_client(&self) -> &HttpClient { &self.client } fn execute_request<T>(client: &HttpClient, reques...
nomad_token_request_is_built_properly
identifier_name
vault.rs
, /// Data for secrets requests #[serde(default)] data: Option<HashMap<String, String>>, // Missing and ignored fields: // - wrap_info } /// Authentication data from Vault #[derive(Serialize, Deserialize, Debug, Eq, PartialEq)] pub struct Authentication { /// The actual token pub client_to...
fn build_nomad_token_request( &self, nomad_path: &str, nomad_role: &str, ) -> Result<reqwest::Request, crate::Error> { let vault_address = url::Url::parse(self.address())?; let vault_address = vault_address.join(&format!("/v1/{}/creds/{}", nomad_path, nomad_...
{ let vault_address = url::Url::parse(self.address())?; let vault_address = vault_address.join("/v1/auth/token/revoke-self")?; Ok(self .client .post(vault_address) .header("X-Vault-Token", self.token.as_str()) .build()?) }
identifier_body
vault.rs
>, /// Data for secrets requests #[serde(default)] data: Option<HashMap<String, String>>, // Missing and ignored fields: // - wrap_info } /// Authentication data from Vault #[derive(Serialize, Deserialize, Debug, Eq, PartialEq)] pub struct Authentication { /// The actual token
/// List of tokens directly assigned to token pub token_policies: Vec<String>, /// Arbitrary metadata pub metadata: HashMap<String, String>, /// Lease Duration for the token pub lease_duration: u64, /// Whether the token is renewable pub renewable: bool, /// UUID for the entity p...
pub client_token: crate::Secret, /// The accessor for the Token pub accessor: String, /// List of policies for token, including from Identity pub policies: Vec<String>,
random_line_split
controlPanel.go
rapper = w flow := widget.NewFlow(widget.AxisHorizontal) flow.Insert(widget.NewSizer(unit.Ems(0.5), unit.Value{}, nil), nil) flow.Insert(widget.NewLabel(fmt.Sprintf("%-30s", text)), nil) flow.Insert(widget.NewSizer(unit.Ems(0.5), unit.Value{}, nil), nil) w.label = widget.NewLabel(fmt.Sprintf("%30s", "")) flow.In...
{ dest := &p.world.scenario.Destinations[i] if dest.ID == p.world.scenario.Exit.ID { continue } if open { dest.Close() } else { dest.Open() } }
conditional_block
controlPanel.go
() w.z.SetDstImage(ctx.Dst, w.Rect.Add(origin), draw.Over) return iconvg.Decode(&w.z, w.icon, nil) } type Ticker struct { node.ShellEmbed tick func() string label *widget.Label } func (p *ControlPanel) NewTicker(text string, tick func() string) *Ticker { w := &Ticker{ tick: tick, } w.Wrapper = w flow := w...
flow.Insert(widget.NewSizer(unit.Ems(0.5), unit.Value{}, nil), nil) w.label = widget.NewLabel(fmt.Sprintf("%-30s", text)) flow.Insert(w.label, nil) flow.Insert(widget.NewSizer(unit.Ems(0.5), unit.Value{}, nil), nil) flow.Insert(NewIcon(icon), nil) w.uniform = widget.NewUniform(theme.StaticColor(colornames.Light...
{ w := &Button{ icon: icon, } fn := func() { w.pressed = !w.pressed w.label.Text = fmt.Sprintf("%-30s", onClick()) w.label.Mark(node.MarkNeedsPaintBase) if w.pressed || !toggle { w.uniform.ThemeColor = theme.StaticColor(colornames.Lightgreen) } else { w.uniform.ThemeColor = theme.StaticColor(colorn...
identifier_body
controlPanel.go
node.LeafEmbed icon []byte z iconvg.Rasterizer } func NewIcon(icon []byte) *Icon { w := &Icon{ icon: icon, } w.Wrapper = w return w } func (w *Icon) Measure(t *theme.Theme, widthHint, heightHint int) { px := t.Pixels(unit.Ems(2)).Ceil() w.MeasuredSize = image.Point{X: px, Y: px} } func (w *Icon) PaintB...
type panelUpdate struct { } type Icon struct {
random_line_split
controlPanel.go
() w.z.SetDstImage(ctx.Dst, w.Rect.Add(origin), draw.Over) return iconvg.Decode(&w.z, w.icon, nil) } type Ticker struct { node.ShellEmbed tick func() string label *widget.Label } func (p *ControlPanel) NewTicker(text string, tick func() string) *Ticker { w := &Ticker{ tick: tick, } w.Wrapper = w flow := w...
() *Button { return p.NewButton("Highlight Active AI", icons.ActionFavorite, true, func() string { if p.world.highlightActive { p.world.highlightActive = false } else { p.world.highlightActive = true } p.r.w.Send(UpdateEvent{p.world}) return "Highlight Active AI" }) } func (p *ControlPanel) NewExitBu...
NewHighlightActiveButton
identifier_name