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
has_loc.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::borrow::Cow; use proc_macro2::Ident; use proc_macro2::Span; use proc_macro2::TokenStream; use quote::quote; use quote::ToToken...
})); } NestedMeta::Lit(Lit::Str(n)) => { return Ok(Some(Field { kind: FieldKind::Named(Cow::Owned(Ident::new( &n.value(), ...
random_line_split
has_loc.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::borrow::Cow; use proc_macro2::Ident; use proc_macro2::Span; use proc_macro2::TokenStream; use quote::quote; use quote::ToToken...
fn get_select_field<'a>( variant: &'a Variant, default_select_field: &Option<Field<'a>>, ) -> Result<Option<Field<'a>>> { if let Some(f) = handle_has_loc_attr(&variant.attrs)? { return Ok(Some(f)); } if let Some(f) = default_select_field.as_ref() { return Ok(Some(f.clone())); ...
{ // struct Foo { // ... // loc: LocId, // } let struct_name = &input.ident; let default_select_field = handle_has_loc_attr(&input.attrs)?; let loc_field = if let Some(f) = default_select_field { match f.kind { FieldKind::Named(name) => { let name = n...
identifier_body
reader_test.go
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
if err != nil { t.Errorf("#%d: %v", i, err) continue } if got := string(gotb); got != test.want { t.Errorf("#%d: got %q, want %q", i, got, test.want) } if r.Attrs.Size != int64(len(readData)) { t.Errorf("#%d: got Attrs.Size=%q, want %q", i, r.Attrs.Size, len(readData)) } wantOffset...
{ n, err := r.Read(buf) gotb = append(gotb, buf[:n]...) if err == io.EOF { break } if err != nil { t.Fatalf("#%d: %v", i, err) } }
conditional_block
reader_test.go
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
"google.golang.org/api/option" ) const readData = "0123456789" func TestRangeReader(t *testing.T) { ctx := context.Background() hc, close := newTestServer(handleRangeRead) defer close() multiReaderTest(ctx, t, func(t *testing.T, c *Client) { obj := c.Bucket("b").Object("o") for _, test := range []struct { ...
random_line_split
reader_test.go
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
func (f *fakeReadCloser) Read(buf []byte) (int, error) { i := f.c n := 0 if i < len(f.counts) { n = f.counts[i] } var err error if i >= len(f.counts)-1 { err = f.err } copy(buf, f.data[f.d:f.d+n]) if len(buf) < n { n = len(buf) f.counts[i] -= n err = nil } else { f.c++ } f.d += n return n, er...
{ return nil }
identifier_body
reader_test.go
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
(t *testing.T) { e := errors.New("") f := &fakeReadCloser{ data: []byte(readData), counts: []int{1, 2, 3}, err: e, } wants := []string{"0", "12", "345"} buf := make([]byte, 10) for i := 0; i < 3; i++ { n, err := f.Read(buf) if got, want := n, f.counts[i]; got != want { t.Fatalf("i=%d: got %d, wa...
TestFakeReadCloser
identifier_name
moment-ext.ts
import * as moment from 'moment' import * as $ from 'jquery' import { isNativeDate } from './util' /* GENERAL NOTE on moments throughout the *entire rest* of the codebase: All moments are assumed to be ambiguously-zoned unless otherwise noted, with the NOTABLE EXCEOPTION of start/end dates that live on *Event Objects*...
seconds: 0, ms: 0 }) // Mark the time as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(), // which clears all ambig flags. this._ambigTime = true this._ambigZone = true // if ambiguous time, also ambiguous timezone offset } return this // for ch...
minutes: 0,
random_line_split
moment-ext.ts
import * as moment from 'moment' import * as $ from 'jquery' import { isNativeDate } from './util' /* GENERAL NOTE on moments throughout the *entire rest* of the codebase: All moments are assumed to be ambiguously-zoned unless otherwise noted, with the NOTABLE EXCEOPTION of start/end dates that live on *Event Objects*...
(mom, formatStr?) { return oldMomentProto.format.call(mom, formatStr) // oldMomentProto defined in moment-ext.js } export { newMomentProto, oldMomentProto, oldMomentFormat } // Creating // ------------------------------------------------------------------------------------------------- // Creates a new moment, si...
oldMomentFormat
identifier_name
moment-ext.ts
import * as moment from 'moment' import * as $ from 'jquery' import { isNativeDate } from './util' /* GENERAL NOTE on moments throughout the *entire rest* of the codebase: All moments are assumed to be ambiguously-zoned unless otherwise noted, with the NOTABLE EXCEOPTION of start/end dates that live on *Event Objects*...
// Week Number // ------------------------------------------------------------------------------------------------- // Returns the week number, considering the locale's custom week number calcuation // `weeks` is an alias for `week` newMomentProto.week = newMomentProto.weeks = function(input) { let weekCalc = th...
{ let input = args[0] let isSingleString = args.length === 1 && typeof input === 'string' let isAmbigTime let isAmbigZone let ambigMatch let mom if (moment.isMoment(input) || isNativeDate(input) || input === undefined) { mom = moment.apply(null, args) } else { // "parsing" is required isAmbigTi...
identifier_body
qwe58.py
#from __future__ import print_function # -*- coding: UTF-8 -*- import cv2 import numpy as np import sys from cython_bbox import bbox_overlaps from projection import ground_point_to_bird_view_proj from projection import bird_view_proj_to_ground_point as bv2gp #import projection.brid_view_proj_to_ground_point as bv2gp im...
for cls_ind, cls in enumerate(CLASSES[1:]): cls_ind += 1 cls_boxes = boxes[:, 4:8] #boxes[:, 4*cls_ind:4*(cls_ind + 1)] cls_scores = scores[:, cls_ind] cls_dets = np.hstack((cls_boxes,cls_scores[:, np.newaxis])).astype(np.float32) keep = nms(cls_dets, NMS_THRESH) # add vote ...
random_line_split
qwe58.py
#from __future__ import print_function # -*- coding: UTF-8 -*- import cv2 import numpy as np import sys from cython_bbox import bbox_overlaps from projection import ground_point_to_bird_view_proj from projection import bird_view_proj_to_ground_point as bv2gp #import projection.brid_view_proj_to_ground_point as bv2gp im...
outfile=i.split(".")[0]+"_pre.json" infile=os.path.join(imp,i) timefile=i.split(".")[0]+"_time.txt" timefile=os.path.join(imp,timefile) print(infile) print(outfile) print(timefile) nnn += 1 t = threading.Thread(target = action, args = (model, deploy,infile,outfile,time...
inue
conditional_block
qwe58.py
#from __future__ import print_function # -*- coding: UTF-8 -*- import cv2 import numpy as np import sys from cython_bbox import bbox_overlaps from projection import ground_point_to_bird_view_proj from projection import bird_view_proj_to_ground_point as bv2gp #import projection.brid_view_proj_to_ground_point as bv2gp im...
def action(model, deploy,infile,outfile,timefile, nnn): run_video(model, deploy,infile,outfile,timefile, nnn) if __name__ == '__main__': model = sys.argv[2] #model deploy = sys.argv[1] #deploy imp = sys.argv[3] # video path output = sys.argv[4] # output json timer_tot = Timer() timer_tot.tic() ...
dets_voted = np.zeros_like(dets_NMS) # Empty matrix with the same shape and type _overlaps = bbox_overlaps( np.ascontiguousarray(dets_NMS[:, 0:4], dtype=np.float), np.ascontiguousarray(dets_all[:, 0:4], dtype=np.float)) # for each survived box for i, det in enumerate(dets_NMS): dets_...
identifier_body
qwe58.py
#from __future__ import print_function # -*- coding: UTF-8 -*- import cv2 import numpy as np import sys from cython_bbox import bbox_overlaps from projection import ground_point_to_bird_view_proj from projection import bird_view_proj_to_ground_point as bv2gp #import projection.brid_view_proj_to_ground_point as bv2gp im...
(x_result,N): plen=N head = [x_result[0] for z in range(plen)] tail = [x_result[-1] for z in range(plen)] pad_result= head+x_result+tail xm_result=[] for i in range(len(x_result)): xm_result.append(np.mean(pad_result[i:i+plen+1])) xm_result.reverse() head = [xm_result[0] for z in range(plen)] t...
smooth_curve
identifier_name
address.go
// Copyright 2016 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. //go:build darwin || dragonfly || freebsd || netbsd || openbsd // +build darwin dragonfly freebsd netbsd openbsd package route import ( "runtime" "syscall" ...
func (a *Inet4Addr) marshal(b []byte) (int, error) { l, ll := a.lenAndSpace() if len(b) < ll { return 0, errShortBuffer } b[0] = byte(l) b[1] = syscall.AF_INET copy(b[4:8], a.IP[:]) return ll, nil } // An Inet6Addr represents an internet address for IPv6. type Inet6Addr struct { IP [16]byte // IP addre...
{ return sizeofSockaddrInet, roundup(sizeofSockaddrInet) }
identifier_body
address.go
// Copyright 2016 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. //go:build darwin || dragonfly || freebsd || netbsd || openbsd // +build darwin dragonfly freebsd netbsd openbsd package route import ( "runtime" "syscall" ...
(af int, b []byte) (Addr, error) { switch af { case syscall.AF_INET: if len(b) < sizeofSockaddrInet { return nil, errInvalidAddr } a := &Inet4Addr{} copy(a.IP[:], b[4:8]) return a, nil case syscall.AF_INET6: if len(b) < sizeofSockaddrInet6 { return nil, errInvalidAddr } a := &Inet6Addr{ZoneID: ...
parseInetAddr
identifier_name
address.go
// Copyright 2016 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. //go:build darwin || dragonfly || freebsd || netbsd || openbsd // +build darwin dragonfly freebsd netbsd openbsd package route import ( "runtime" "syscall" ...
b = b[l:] } } // The only remaining bytes in b should be alignment. // However, under some circumstances DragonFly BSD appears to put // more addresses in the message than are indicated in the address // bitmask, so don't check for this. return as[:], nil }
{ return nil, errMessageTooShort }
conditional_block
address.go
// Copyright 2016 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. //go:build darwin || dragonfly || freebsd || netbsd || openbsd // +build darwin dragonfly freebsd netbsd openbsd package route import ( "runtime" "syscall" ...
b = b[l:] } } // The only remaining bytes in b should be alignment. // However, under some circumstances DragonFly BSD appears to put // more addresses in the message than are indicated in the address // bitmask, so don't check for this. return as[:], nil }
if len(b) < l { return nil, errMessageTooShort }
random_line_split
main.rs
extern crate sdl2; use sdl2::pixels::Color; use sdl2::event::Event; use sdl2::GameControllerSubsystem; use sdl2::controller::GameController; use sdl2::controller::Button; use sdl2::render::Canvas; use sdl2::render::Texture; use sdl2::render::TextureCreator; use sdl2::rect::Point; use sdl2::rect::Rect; use sdl2::control...
} } Err(e) => { panic!("{}", e); } } } fn obtain_result<T, E: std::fmt::Display>(res: Result<T, E>) -> T { match res { Ok(r) => { r } Err(e) => { panic!("{}", e); } } } fn draw_centered_text(canvas: &mut Canvas<Window>, texture: &Texture, y_offset: i32) { //Draw the title let dst = { ...
{ panic!("{}", e); }
conditional_block
main.rs
extern crate sdl2; use sdl2::pixels::Color; use sdl2::event::Event; use sdl2::GameControllerSubsystem; use sdl2::controller::GameController; use sdl2::controller::Button; use sdl2::render::Canvas; use sdl2::render::Texture; use sdl2::render::TextureCreator; use sdl2::rect::Point; use sdl2::rect::Rect; use sdl2::control...
fn obtain_result<T, E: std::fmt::Display>(res: Result<T, E>) -> T { match res { Ok(r) => { r } Err(e) => { panic!("{}", e); } } } fn draw_centered_text(canvas: &mut Canvas<Window>, texture: &Texture, y_offset: i32) { //Draw the title let dst = { let query = texture.query(); let xpos = (SCREEN_W...
{ let color = Color::RGB(0, 255, 0); match font.render(text).solid(color) { Ok(surface) => { match texture_creator.create_texture_from_surface(surface) { Ok(t) => { t } Err(e) => { panic!("{}", e); } } } Err(e) => { panic!("{}", e); } } }
identifier_body
main.rs
extern crate sdl2; use sdl2::pixels::Color; use sdl2::event::Event; use sdl2::GameControllerSubsystem; use sdl2::controller::GameController; use sdl2::controller::Button; use sdl2::render::Canvas; use sdl2::render::Texture; use sdl2::render::TextureCreator; use sdl2::rect::Point; use sdl2::rect::Rect; use sdl2::control...
if !going_to_next_round { //Start the timer round_transition_timer = ticks; //Increment round number game_state.round_number += 1; //Create round # texture round_number_texture = text_texture(&format!("Round {}", game_state.round_number), &texture_creator, &font); going...
random_line_split
main.rs
extern crate sdl2; use sdl2::pixels::Color; use sdl2::event::Event; use sdl2::GameControllerSubsystem; use sdl2::controller::GameController; use sdl2::controller::Button; use sdl2::render::Canvas; use sdl2::render::Texture; use sdl2::render::TextureCreator; use sdl2::rect::Point; use sdl2::rect::Rect; use sdl2::control...
<T: std::cmp::PartialOrd>(value: T, lower_bound: T, upper_bound: T) -> T{ let mut clamped_value = value; if clamped_value < lower_bound { clamped_value = lower_bound; } if clamped_value > upper_bound { clamped_value = upper_bound; } clamped_value } fn main() { let sdl_context = sdl2::init().unwrap(); let v...
clamp
identifier_name
bind.go
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not...
import ( "reflect" "github.com/apache/beam/sdks/v2/go/pkg/beam/core/funcx" "github.com/apache/beam/sdks/v2/go/pkg/beam/core/typex" "github.com/apache/beam/sdks/v2/go/pkg/beam/internal/errors" ) // TODO(herohde) 4/21/2017: Bind is where most user mistakes will likely show // up. We should verify that common mista...
// See the License for the specific language governing permissions and // limitations under the License. package graph
random_line_split
bind.go
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not...
return 1, nil } func trimIllegal(list []reflect.Type) []reflect.Type { var ret []reflect.Type for _, elm := range list { switch typex.ClassOf(elm) { case typex.Concrete, typex.Universal, typex.Container: ret = append(ret, elm) } } return ret }
{ switch t.Type() { case typex.KVType: if isMain { return 2, nil } // A KV side input must be a single iterator/map. return 1, nil case typex.CoGBKType: return len(t.Components()), nil default: return 0, errors.Errorf("unexpected composite inbound type: %v", t.Type()) } }
conditional_block
bind.go
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not...
(fn *funcx.Fn, typedefs map[string]reflect.Type, in ...typex.FullType) ([]typex.FullType, []InputKind, []typex.FullType, []typex.FullType, error) { addContext := func(err error, fn *funcx.Fn) error { return errors.WithContextf(err, "binding fn %v", fn.Fn.Name()) } inbound, kinds, err := findInbound(fn, in...) if...
Bind
identifier_name
bind.go
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not...
func tryBindInbound(t typex.FullType, args []funcx.FnParam, isMain bool) (typex.FullType, InputKind, error) { kind := Main var other typex.FullType switch t.Class() { case typex.Concrete, typex.Container: if isMain { other = typex.New(args[0].T) } else { // We accept various forms for side input. We ha...
{ // log.Printf("Bind inbound: %v %v", fn, in) addContext := func(err error, p []funcx.FnParam, in any) error { return errors.WithContextf(err, "binding params %v to input %v", p, in) } var inbound []typex.FullType var kinds []InputKind params := funcx.SubParams(fn.Param, fn.Params(funcx.FnValue|funcx.FnIter|f...
identifier_body
helper.go
package util import ( "bytes" "crypto/md5" "encoding/binary" "encoding/json" "errors" "fmt" "math" "math/rand" "net" "net/http" "net/url" "reflect" "strconv" "strings" "time" ) //helper工具集 type helper struct { } var Helper *helper func init() { Helper = NewHelper() } func NewHelper() *helper { r...
identifier_name
helper.go
package util import ( "bytes" "crypto/md5" "encoding/binary" "encoding/json" "errors" "fmt" "math" "math/rand" "net" "net/http" "net/url" "reflect" "strconv" "strings" "time" ) //helper工具集 type helper struct { } var Helper *helper func init() { Helper = NewHelper() } func NewHelper() *helper { r...
dic = strings.Split(dicStr, ",") } length := len(dic) for i := 0; i < randStrLength; i++ { rand.Seed(time.Now().UnixNano()) randNum := rand.Intn(length - 1) key += dic[randNum] } return key } //http响应json-成功数据 //@params string message 响应消息 //@params interface{} data 响应数据,一般也是map数据类型 func (thisObj *helper)...
} else { dicStr := "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"
random_line_split
helper.go
package util import ( "bytes" "crypto/md5" "encoding/binary" "encoding/json" "errors" "fmt" "math" "math/rand" "net" "net/http" "net/url" "reflect" "strconv" "strings" "time" ) //helper工具集 type helper struct { } var Helper *helper func init() { Hel
NewHelper() *helper { return &helper{ } } //获取当前时间戳-int类型数据 func (thisObj *helper) CurrTimeInt() int { return int(time.Now().Unix()) } //json解析 //@params interface{} t 基本上传参都是map数据类型,如map[string]interface{}或是map[string]string func (thisObj *helper) JSONMarshal(t interface{}) ([]byte, error) { buffer := &bytes.B...
per = NewHelper() } func
identifier_body
helper.go
package util import ( "bytes" "crypto/md5" "encoding/binary" "encoding/json" "errors" "fmt" "math" "math/rand" "net" "net/http" "net/url" "reflect" "strconv" "strings" "time" ) //helper工具集 type helper struct { } var Helper *helper func init() { Helper = NewHelper() } func NewHelper() *helper { r...
p的代码: // // 有可能传递过来的是ip2long转换的整型ip值 转换成ip字符串 // // $ipStr = is_numeric($ip) ? long2ip($ip) : $ip; // ipStr := "" // //若是整型值 // if thisObj.IsNumeric(ip) { // //转成字符串 // ipInt,ipIntErr := strconv.Atoi(ip) // //若转换出错 // if ipIntErr!=nil { // actionResultItem["ipAddr"] = "IP_TO_INT_ERROR" // actionResul...
------- // //模拟ph
conditional_block
q19.rs
/* LDBC SNB BI query 19. Interaction path between cities https://ldbc.github.io/ldbc_snb_docs_snapshot/bi-read-19.pdf */ use differential_dataflow::collection::AsCollection; use differential_dataflow::input::Input; use differential_dataflow::operators::{Join, Count, Iterate, Reduce}; use timely::dataflow::ProbeHandle;...
(path: String, change_path: String, params: &Vec<String>) { // unpack parameters let param_city1 = params[0].parse::<u64>().unwrap(); let param_city2 = params[1].parse::<u64>().unwrap(); timely::execute_from_args(std::env::args(), move |worker| { let mut timer = worker.timer(); let inde...
run
identifier_name
q19.rs
/* LDBC SNB BI query 19. Interaction path between cities https://ldbc.github.io/ldbc_snb_docs_snapshot/bi-read-19.pdf */ use differential_dataflow::collection::AsCollection; use differential_dataflow::input::Input; use differential_dataflow::operators::{Join, Count, Iterate, Reduce}; use timely::dataflow::ProbeHandle;...
{ // unpack parameters let param_city1 = params[0].parse::<u64>().unwrap(); let param_city2 = params[1].parse::<u64>().unwrap(); timely::execute_from_args(std::env::args(), move |worker| { let mut timer = worker.timer(); let index = worker.index(); let peers = worker.peers(); ...
identifier_body
q19.rs
/* LDBC SNB BI query 19. Interaction path between cities https://ldbc.github.io/ldbc_snb_docs_snapshot/bi-read-19.pdf */ use differential_dataflow::collection::AsCollection; use differential_dataflow::input::Input; use differential_dataflow::operators::{Join, Count, Iterate, Reduce}; use timely::dataflow::ProbeHandle;...
&knows.map(|conn| (conn.a().clone(), conn.b().clone())) ) ; // calculate weights starting from personB let weights = bi_knows .join_map( // join messages of personB &has_creator.map(|conn| (conn.b().clone(),...
random_line_split
train_full_random.py
import numpy as np import matplotlib as mpl mpl.use('Agg') import sys import time import matplotlib.pyplot as plt if sys.version_info[0] < 3: import cPickle as pickle else: import pickle import neuron_models as nm import lab_manager as lm import experiments as ex from sklearn.utils import shuffle as rshuff...
#probability inter-AL connections #0.5 PAL = 0.5 #AL->KCs #0.01 PALKC = 0.02 #KCs->BLs #0.3 PKCBL = 0.3 taupre = 15*ms #width of STDP taupost = taupre input_intensity = 0.3 #scale input reset_time = 30 #ms # needed for gradual current tr = 20*ms # rise time tf = 20*ms # fall time width = 150*ms # duration of const...
random_line_split
train_full_random.py
import numpy as np import matplotlib as mpl mpl.use('Agg') import sys import time import matplotlib.pyplot as plt if sys.version_info[0] < 3: import cPickle as pickle else: import pickle import neuron_models as nm import lab_manager as lm import experiments as ex from sklearn.utils import shuffle as rshuff...
# Parallelize using OpenMP. Might not work.... # also only works with C++ standalone/comp = True # prefs.devices.cpp_standalone.openmp_threads = 4 start_scope() #path to the data folder MNIST_data_path = 'data_set/' # MNIST_data_path = '/home/jplatt/Mothnet/MNIST_data/' #path to folder to save data prefix = 'total...
set_device('cpp_standalone', debug=True, build_on_run=False)
conditional_block
conf_utils.py
#!/usr/bin/env python # # Copyright (c) 2015 All rights reserved # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 # """Tempest configuration uti...
with open(conf_file, 'wb') as config_file: rconfig.write(config_file) def configure_tempest_update_params( tempest_conf_file, image_id=None, flavor_id=None, compute_cnt=1, image_alt_id=None, flavor_alt_id=None, admin_role_name='admin', cidr='192.168.120.0/24', domain_id='...
sections = rconfig.sections() for section in conf_yaml: if section not in sections: rconfig.add_section(section) sub_conf = conf_yaml.get(section) for key, value in sub_conf.items(): rconfig.set(section, key, value)
conditional_block
conf_utils.py
#!/usr/bin/env python # # Copyright (c) 2015 All rights reserved # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 # """Tempest configuration uti...
Returns deployment id for active Rally deployment """ cmd = ("rally deployment list | awk '/" + getattr(config.CONF, 'rally_deployment_name') + "/ {print $2}'") proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, ...
def get_verifier_deployment_id(): """
random_line_split
conf_utils.py
#!/usr/bin/env python # # Copyright (c) 2015 All rights reserved # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 # """Tempest configuration uti...
def create_verifier(): """Create new verifier""" LOGGER.info("Create verifier from existing repo...") cmd = ['rally', 'verify', 'delete-verifier', '--id', str(getattr(config.CONF, 'tempest_verifier_name')), '--force'] try: output = subprocess.check_output(cmd) LO...
"""Create new rally deployment""" # set the architecture to default pod_arch = env.get("POD_ARCH") arch_filter = ['aarch64'] if pod_arch and pod_arch in arch_filter: LOGGER.info("Apply aarch64 specific to rally config...") with open(RALLY_AARCH64_PATCH_PATH, "r") as pfile: r...
identifier_body
conf_utils.py
#!/usr/bin/env python # # Copyright (c) 2015 All rights reserved # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 # """Tempest configuration uti...
( tempest_conf_file, image_id=None, flavor_id=None, compute_cnt=1, image_alt_id=None, flavor_alt_id=None, admin_role_name='admin', cidr='192.168.120.0/24', domain_id='default'): # pylint: disable=too-many-branches,too-many-arguments,too-many-statements """ Add/update needed p...
configure_tempest_update_params
identifier_name
navfunc.py
#!/usr/bin/python #>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>> # author: Luciano Augusto Kruk # website: www.kruk.eng.br # # description: Package of functions for quaternions and # geodetic coordinates handling. #>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>> import nu...
output: nparray() with Q """ return self.euler2Q(self.C2euler(C)) def C2euler(self, C): """ Navigation -- from C to (phi,theta,psi)[rad] output: tuple with angles in [rad] """ assert(C[2,2] != 0) assert(C[0,0] != 0) assert(C[0,2]>=...
""" Navigation -- from C to Q
random_line_split
navfunc.py
#!/usr/bin/python #>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>> # author: Luciano Augusto Kruk # website: www.kruk.eng.br # # description: Package of functions for quaternions and # geodetic coordinates handling. #>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>> import nu...
def rect2geo(self, rect): """ Converter coordenadas ECEF retangulares para geodeticas. pgeo [out] Coordenadas geodeticas. prect [in] Coordenadas retangulares. """ p = sqrt((rect.x * rect.x) + (rect.y * rect.y)); geo = CGEO(0,0,0); geo.h = 0; ...
""" Converter coordenadas ECEF geodeticas para retangulares. pgeo [in] Coordenadas geodeticas. prect [out] Coordenadas retangulares. """ s = sin(geo.lat); RN = self.earth_a / sqrt(1.0 - (self.earth_e2 * s * s)); return CRECT(( (RN + geo.h) * cos(geo...
identifier_body
navfunc.py
#!/usr/bin/python #>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>> # author: Luciano Augusto Kruk # website: www.kruk.eng.br # # description: Package of functions for quaternions and # geodetic coordinates handling. #>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>> import nu...
(self): K = 180./mt.pi; return "<CGEO: lat=%1.2f[deg] lon=%1.2f[deg] h=%1.1f[m]>" % (self.lat*K, self.lon*K, self.h) class CRECT: def __init__(self, r_e): if type(r_e) is np.ndarray: self.x = r_e.squeeze()[0]; self.y = r_e.squeeze()[1]; self.z = r_e.squ...
__repr__
identifier_name
navfunc.py
#!/usr/bin/python #>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>> # author: Luciano Augusto Kruk # website: www.kruk.eng.br # # description: Package of functions for quaternions and # geodetic coordinates handling. #>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>>--<<..>> import nu...
else: print "ainda nao suportado!" def __repr__(self): K = 180./mt.pi; return "<CRECT: x=%1.2f[m] y=%1.2f[m] z=%1.2f[m]>" % (self.x, self.y, self.z) def aslist(self): return [ self.x, self.y, self.z ]; #>>--<<..>>--<<....
self.x = r_e[0] self.y = r_e[1] self.z = r_e[2]
conditional_block
cluster_save_all_model_flam.py
from __future__ import division import numpy as np from numpy import nansum from scipy.interpolate import griddata import multiprocessing as mp from scipy.integrate import simps import os import sys import time import datetime # Get data and filter curve directories if 'agave' in os.uname()[1]: figs_data_dir = "...
# Save a txt file data = np.array(zip(zrange, dl_mpc, dl_cm), dtype=[('zrange', float), ('dl_mpc', float), ('dl_cm', float)]) np.savetxt('dl_lookup_table.txt', data, fmt=['%.3f', '%.6e', '%.6e'], delimiter=' ', header='z dl_mpc dl_cm') print "Luminosity distance lookup table saved in txt file.", ...
random_line_split
cluster_save_all_model_flam.py
from __future__ import division import numpy as np from numpy import nansum from scipy.interpolate import griddata import multiprocessing as mp from scipy.integrate import simps import os import sys import time import datetime # Get data and filter curve directories if 'agave' in os.uname()[1]: figs_data_dir = "...
# transverse array to make shape consistent with others # I did it this way so that in the above for loop each filter is looped over only once # i.e. minimizing the number of times each filter is gridded on to the model grid #filt_flam_model_t = filt_flam_model.T # save the mo...
num = simps(y=model_comp_spec[i] * filt_interp / (4 * np.pi * dl * dl * (1+z)), x=model_lam_grid_z) filt_flam_model[j, i] = num / den
conditional_block
cluster_save_all_model_flam.py
from __future__ import division import numpy as np from numpy import nansum from scipy.interpolate import griddata import multiprocessing as mp from scipy.integrate import simps import os import sys import time import datetime # Get data and filter curve directories if 'agave' in os.uname()[1]: figs_data_dir = "...
def main(): # Start time start = time.time() dt = datetime.datetime print "Starting at --", dt.now() # Redshift grid for models zrange = np.arange(0.005, 6.005, 0.005) print "Redshift grid for models:" print zrange # Read in lookup table for luminosity distances if not o...
print "\n", "Working on filter:", filtername if filtername == 'u': filt['trans'] /= 100.0 # They've given throughput percentages for the u-band filt_flam_model = np.zeros(shape=(len(zrange), total_models), dtype=np.float64) """ print model_comp_spec.nbytes / (1024 * 1024) print model...
identifier_body
cluster_save_all_model_flam.py
from __future__ import division import numpy as np from numpy import nansum from scipy.interpolate import griddata import multiprocessing as mp from scipy.integrate import simps import os import sys import time import datetime # Get data and filter curve directories if 'agave' in os.uname()[1]: figs_data_dir = "...
(filt, filtername, start, model_comp_spec, model_lam_grid, \ total_models, zrange, dl_tbl): print "\n", "Working on filter:", filtername if filtername == 'u': filt['trans'] /= 100.0 # They've given throughput percentages for the u-band filt_flam_model = np.zeros(shape=(len(zrange), total_mod...
compute_filter_flam
identifier_name
lib.rs
// Copyright (c) Microsoft. All rights reserved. #![deny(rust_2018_idioms, warnings)] #![deny(clippy::all, clippy::pedantic)] #![allow( clippy::default_trait_access, clippy::doc_markdown, // clippy want the "IoT" of "IoT Hub" in a code fence clippy::missing_errors_doc, clippy::module_name_repetitions, ...
fn init_runtime<M>( settings: M::Settings, tokio_runtime: &mut tokio::runtime::Runtime, create_socket_channel_snd: UnboundedSender<ModuleAction>, ) -> Result<M::ModuleRuntime, Error> where M: MakeModuleRuntime + Send + 'static, M::ModuleRuntime: Send, M::Future: 'static, { info!("Initializ...
{ let iot_hub_name = workload_config.iot_hub_name().to_string(); let device_id = workload_config.device_id().to_string(); let (mgmt_tx, mgmt_rx) = oneshot::channel(); let (mgmt_stop_and_reprovision_tx, mgmt_stop_and_reprovision_rx) = mpsc::unbounded(); let mgmt = start_management::<M>(settings, ru...
identifier_body
lib.rs
// Copyright (c) Microsoft. All rights reserved. #![deny(rust_2018_idioms, warnings)] #![deny(clippy::all, clippy::pedantic)] #![allow( clippy::default_trait_access, clippy::doc_markdown, // clippy want the "IoT" of "IoT Hub" in a code fence clippy::missing_errors_doc, clippy::module_name_repetitions, ...
; impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Error") } } lazy_static::lazy_static! { static ref ENV_LOCK: std::sync::Mutex<()> = Default::default(); } #[test] fn settings_for_edge_ca_cert() { ...
Error
identifier_name
lib.rs
// Copyright (c) Microsoft. All rights reserved. #![deny(rust_2018_idioms, warnings)] #![deny(clippy::all, clippy::pedantic)] #![allow( clippy::default_trait_access, clippy::doc_markdown, // clippy want the "IoT" of "IoT Hub" in a code fence clippy::missing_errors_doc, clippy::module_name_repetitions, ...
// Normally aziot-edged will stop all modules when it shuts down. But if it crashed, // modules will continue to run. On Linux systems where aziot-edged is responsible for // creating/binding the socket (e.g., CentOS 7.5, which uses systemd but does not // support systemd socket activati...
}; }; info!("Finished provisioning edge device.");
random_line_split
util.go
package util import ( "fmt" "io/ioutil" "strconv" "strings" "golang.org/x/exp/constraints" ) const MaxUint = ^uint(0) const MaxInt = int(MaxUint >> 1) // Number is a Float or Integer type Number interface { constraints.Float | constraints.Integer } func LowestTrue(lowFalseStart int, pred func(int) (bool, err...
func highestTrueRange(lowTrue int, highFalse int, pred func(int) (bool, error)) (int, error) { if lowTrue >= highFalse { return 0, fmt.Errorf("highestTrue(%d,%d, pred): want arg1 < arg2", lowTrue, highFalse) } lt, err := pred(lowTrue) if err != nil { return 0, err } if !lt { return 0, fmt.Errorf("highestT...
{ lf, err := pred(lowFalseStart) if err != nil { return 0, err } if lf { return 0, fmt.Errorf("lowestTrue expected pred(lowFalseStart)==false; got pred(%d)==true", lowFalseStart) } lowFalse := lowFalseStart highTrue := 0 for lowFalse < MaxInt/2 { attempt := lowFalse * 2 st, err := pred(attempt) if err...
identifier_body
util.go
package util import ( "fmt" "io/ioutil" "strconv" "strings" "golang.org/x/exp/constraints" ) const MaxUint = ^uint(0) const MaxInt = int(MaxUint >> 1) // Number is a Float or Integer type Number interface { constraints.Float | constraints.Integer } func LowestTrue(lowFalseStart int, pred func(int) (bool, err...
if chunk != nil { result = append(result, chunk) } return result } // KeyValuePairs splits a space-separated sequence of colon-separated key:value // pairs into a map. func KeyValuePairs(input string) map[string]string { result := make(map[string]string) parts := strings.Split(input, " ") for _, part := range...
{ if line == "" { if chunk != nil { result = append(result, chunk) chunk = nil } } else { chunk = append(chunk, line) } }
conditional_block
util.go
package util import ( "fmt" "io/ioutil" "strconv" "strings" "golang.org/x/exp/constraints" ) const MaxUint = ^uint(0) const MaxInt = int(MaxUint >> 1) // Number is a Float or Integer type Number interface { constraints.Float | constraints.Integer } func LowestTrue(lowFalseStart int, pred func(int) (bool, err...
} lowFalse := lowFalseStart highTrue := 0 for lowFalse < MaxInt/2 { attempt := lowFalse * 2 st, err := pred(attempt) if err != nil { return 0, err } if st { highTrue = attempt break } lowFalse <<= 1 } if highTrue == 0 { return 0, fmt.Errorf("cannot find high enough value to make pred(valu...
if lf { return 0, fmt.Errorf("lowestTrue expected pred(lowFalseStart)==false; got pred(%d)==true", lowFalseStart)
random_line_split
util.go
package util import ( "fmt" "io/ioutil" "strconv" "strings" "golang.org/x/exp/constraints" ) const MaxUint = ^uint(0) const MaxInt = int(MaxUint >> 1) // Number is a Float or Integer type Number interface { constraints.Float | constraints.Integer } func LowestTrue(lowFalseStart int, pred func(int) (bool, err...
(lines []string) [][]string { var result [][]string var chunk []string for _, line := range lines { if line == "" { if chunk != nil { result = append(result, chunk) chunk = nil } } else { chunk = append(chunk, line) } } if chunk != nil { result = append(result, chunk) } return result } ...
LinesByParagraph
identifier_name
FilterListViewModel.ts
// Copyright 2021 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, softwar...
const query = layer.createQuery(); query.where = layer.definitionExpression ? layer.definitionExpression : "1=1"; if (layer?.capabilities?.query?.supportsCacheHint) { query.cacheHint = true; } if (field) { query.outFields = [field]; query.returnDistinctValues = true...
} async calculateStatistics(layerId: string, field: string): Promise<__esri.Graphic[]> { const layer = this.map.layers.find(({ id }) => id === layerId) as __esri.FeatureLayer; if (layer && layer.type === "feature") {
random_line_split
FilterListViewModel.ts
// Copyright 2021 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, softwar...
handleResetDatePicker(expression: Expression, layerId: string, event: Event): void { const datePicker = document.getElementById(expression.id.toString()) as HTMLCalciteInputDatePickerElement; datePicker.start = null; datePicker.startAsDate = null; datePicker.end = null; datePicker.endAsDate = null...
setTimeout(() => { const datePicker = event.target as HTMLCalciteInputDatePickerElement; this.setExpressionDates(datePicker.startAsDate, datePicker.endAsDate, expression, layerId); }, 1000); }
identifier_body
FilterListViewModel.ts
// Copyright 2021 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, softwar...
this._generateOutput(layerId); } handleNumberInputCreate( expression: Expression, layerId: string, type: "min" | "max", input: HTMLCalciteInputElement ): void { input.addEventListener("calciteInputInput", this.handleNumberInput.bind(this, expression, layerId, type)); } handleNumberInp...
delete this._layers[layerId].expressions[expression.id]; }
conditional_block
FilterListViewModel.ts
// Copyright 2021 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, softwar...
: void { this.layerExpressions?.map((layerExpression) => { let tmpExp = {}; const { id } = layerExpression; layerExpression.expressions.map((expression) => { if (!expression.checked) { expression.checked = false; } else { tmpExp = { [expression.id]: ...
itExpressions()
identifier_name
a3c_v10_cnn_lstm.py
from A3C.sharedAdam import SharedAdam import os import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical import torch.multiprocessing as mp import numpy as np import pommerman from pommerman import agents import matplotlib.pyplot as plt # on windows, multiprocess...
torch.nn.init.xavier_uniform_(self.encoder2.weight) torch.nn.init.xavier_uniform_(self.encoder3.weight) torch.nn.init.xavier_uniform_(self.critic_linear.weight) # torch.nn.init.xavier_uniform_(self.actor_linear.weight) def forward(self, x, raw, hx, cx): timesteps, batch_size...
torch.nn.init.xavier_uniform_(self.encoder1.weight)
random_line_split
a3c_v10_cnn_lstm.py
from A3C.sharedAdam import SharedAdam import os import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical import torch.multiprocessing as mp import numpy as np import pommerman from pommerman import agents import matplotlib.pyplot as plt # on windows, multiprocess...
def ensure_shared_grads(lnet, gnet): for param, shared_param in zip(lnet.parameters(), gnet.parameters()): if shared_param.grad is not None: return shared_param._grad = param.grad def update_glob_net(opt, lnet, gnet, agent, GAMMA): R = 0 actor_loss = 0 value_loss = 0 ...
"""Stops all agents""" return [agent.shutdown() for agent in agents]
identifier_body
a3c_v10_cnn_lstm.py
from A3C.sharedAdam import SharedAdam import os import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical import torch.multiprocessing as mp import numpy as np import pommerman from pommerman import agents import matplotlib.pyplot as plt # on windows, multiprocess...
shared_param._grad = param.grad def update_glob_net(opt, lnet, gnet, agent, GAMMA): R = 0 actor_loss = 0 value_loss = 0 gae = 0 agent.values.append(torch.zeros(1)) # we need to add this for the deltaT equation(below) # print(agent.rewards) for i in reversed(range(len(agent.rewar...
return
conditional_block
a3c_v10_cnn_lstm.py
from A3C.sharedAdam import SharedAdam import os import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical import torch.multiprocessing as mp import numpy as np import pommerman from pommerman import agents import matplotlib.pyplot as plt # on windows, multiprocess...
(self): # TODO I believe here should be self.hn, self.cn self.hx, self.cx = self.model.get_lstm_reset() self.action_history = np.zeros(6) def clear_actions(self): self.values = [] self.logProbs = [] self.rewards = [] self.entropies = [] return self ...
reset_lstm
identifier_name
LCOGT_submit_requests.py
""" Validate and submit requests made in LCOGT_make_requests.py """ ########### # imports # ########### import pickle, requests, socket from parse import search import os from glob import glob import numpy as np, pandas as pd from astropy.time import Time import astropy.units as u HOMEDIR = os.path.expanduser('~') ...
if submit_all: if isinstance(requestgroup, dict): print('SUBMITTING...') print(requestgroup) submit_single_request(requestgroup) else: print('vvv DID NOT SUBMIT B/C FAILED TO VALIDATE vvv') ...
while is_modified: if n_iter >= 10: raise AssertionError('too many iterations') requestgroup, is_modified = ( validate_single_request( requestgroup, max...
conditional_block
LCOGT_submit_requests.py
""" Validate and submit requests made in LCOGT_make_requests.py """ ########### # imports # ########### import pickle, requests, socket from parse import search import os from glob import glob import numpy as np, pandas as pd from astropy.time import Time import astropy.units as u HOMEDIR = os.path.expanduser('~') ...
def submit_single_request(requestgroup): # Submit the fully formed RequestGroup response = requests.post( 'https://observe.lco.global/api/requestgroups/', headers={'Authorization': 'Token {}'.format(token)}, json=requestgroup ) # Make sure the API call was successful try: ...
format(window_durn/60, billed_durn/60, expcount)) print(42*'-') return requestgroup, is_modified
random_line_split
LCOGT_submit_requests.py
""" Validate and submit requests made in LCOGT_make_requests.py """ ########### # imports # ########### import pickle, requests, socket from parse import search import os from glob import glob import numpy as np, pandas as pd from astropy.time import Time import astropy.units as u HOMEDIR = os.path.expanduser('~') ...
(requestgroup, max_duration_error=15, raise_error=True): """ Submit the RequestGroup through the "validate" API, cf. https://developers.lco.global/#validate-a-requestgroup max_duration_error: in minutes, is the maximum allowable difference between the start & end times o...
validate_single_request
identifier_name
LCOGT_submit_requests.py
""" Validate and submit requests made in LCOGT_make_requests.py """ ########### # imports # ########### import pickle, requests, socket from parse import search import os from glob import glob import numpy as np, pandas as pd from astropy.time import Time import astropy.units as u HOMEDIR = os.path.expanduser('~') ...
if __name__=="__main__": validate_all = 1 submit_all = 1 max_N_transit_per_object = 2 max_duration_error = 20 eventclass = 'OIBEO' savstr = 'request_19B_59859387_{}'.format(eventclass) # eventclass = 'OIB' # savstr = 'request_19B_2m_faint_{}'.format(eventclass) # eventclass = ...
""" savstr: used for directory management validate_all: if true, first validates observation requests to ensure that they can be submitted submit_all: actually submits them max_N_transit_per_object: max_duration_error: in minutes, maximum acceptable difference between _desired_ observati...
identifier_body
base_plugin.go
package transformation import ( envoyapi "github.com/envoyproxy/go-control-plane/envoy/api/v2" envoycore "github.com/envoyproxy/go-control-plane/envoy/api/v2/core" envoyroute "github.com/envoyproxy/go-control-plane/envoy/api/v2/route" envoyhttp "github.com/envoyproxy/go-control-plane/envoy/config/filter/network/ht...
(getTemplate GetTransformationFunction, in *v1.Route, extractors map[string]*Extraction, out *envoyroute.Route) error { switch { case in.MultipleDestinations != nil: for _, dest := range in.MultipleDestinations { err := p.setTransformationForRoute(getTemplate, dest.Destination, extractors, out) if err != nil ...
setTransformationsForRoute
identifier_name
base_plugin.go
package transformation import ( envoyapi "github.com/envoyproxy/go-control-plane/envoy/api/v2" envoycore "github.com/envoyproxy/go-control-plane/envoy/api/v2/core" envoyroute "github.com/envoyproxy/go-control-plane/envoy/api/v2/route" envoyhttp "github.com/envoyproxy/go-control-plane/envoy/config/filter/network/ht...
if err != nil { return err } hash := fmt.Sprintf("%v", intHash) // cache the transformation, the filter config needs to contain all of them p.cachedTransformations[hash] = &t // set the filter metadata on the route if out.Metadata == nil { out.Metadata = &envoycore.Metadata{} } filterMetadata := common....
random_line_split
base_plugin.go
package transformation import ( envoyapi "github.com/envoyproxy/go-control-plane/envoy/api/v2" envoycore "github.com/envoyproxy/go-control-plane/envoy/api/v2/core" envoyroute "github.com/envoyproxy/go-control-plane/envoy/api/v2/route" envoyhttp "github.com/envoyproxy/go-control-plane/envoy/config/filter/network/ht...
} return extractors, nil } // TODO: clean up the response transformation // params should live on the source (upstream/function) func (p *transformationPlugin) AddResponseTransformationsToRoute(in *v1.Route, out *envoyroute.Route) error { if in.Extensions == nil { return nil } extension, err := DecodeRouteExt...
{ return nil, errors.Wrap(err, "error processing parameter") }
conditional_block
base_plugin.go
package transformation import ( envoyapi "github.com/envoyproxy/go-control-plane/envoy/api/v2" envoycore "github.com/envoyproxy/go-control-plane/envoy/api/v2/core" envoyroute "github.com/envoyproxy/go-control-plane/envoy/api/v2/route" envoyhttp "github.com/envoyproxy/go-control-plane/envoy/config/filter/network/ht...
// sets all transformations a route may need // if single destination, just one transformation // if multi destination, one transformation for each functional // that specifies a transformation spec func (p *transformationPlugin) setTransformationsForRoute(getTemplate GetTransformationFunction, in *v1.Route, extracto...
{ var regexString string var prevEnd int for _, startStop := range rxp.FindAllStringIndex(paramString, -1) { start := startStop[0] end := startStop[1] subStr := regexp.QuoteMeta(paramString[prevEnd:start]) + `([\-._[:alnum:]]+)` regexString += subStr prevEnd = end } return regexString + regexp.QuoteMeta...
identifier_body
tasks.py
import logging import os import random from datetime import timedelta from urllib.parse import urlparse from celery import shared_task from django.conf import settings from django.db import transaction from django.db.models import Count, Q from django.utils.timezone import now from requests import HTTPError from rest_...
ja_names.extend(self.get_values_from_info('name_ja')) if not ja_names: ja_names = [self.tag.name.replace("_", " ")] self._get_and_save_info(AtwikiInfoService, *ja_names) if self.tag.type == Tag.COPYRIGHT: self._get_and_save_info(ASDBCopyrightInfoService, *ja_name...
ja_names.append(self.tag.ja_name)
conditional_block
tasks.py
import logging import os import random from datetime import timedelta from urllib.parse import urlparse from celery import shared_task from django.conf import settings from django.db import transaction from django.db.models import Count, Q from django.utils.timezone import now from requests import HTTPError from rest_...
def _save_info_to_tag(self): for k, v in self.info.items(): if v: try: logger.info("Info [{}: {}] is being added " "to Tag[{}]. Overwrite: {}".format(k, v, ...
assert isinstance(tag, Tag) self.tag = tag self.overwrite = overwrite self.info = dict()
identifier_body
tasks.py
import logging import os import random from datetime import timedelta from urllib.parse import urlparse from celery import shared_task from django.conf import settings from django.db import transaction from django.db.models import Count, Q from django.utils.timezone import now from requests import HTTPError from rest_...
self.info.setdefault(k, v) def get_values_from_info(self, *keys): return [self.info.get(key, None) for key in keys if self.info.get(key, None)] def translate_artist(self): if self.tag.type != Tag.ARTIST: return name = self.tag.name.replace("_", " ") self...
for k, v in info.items(): if k in overwrite_keys: self.info[k] = v continue
random_line_split
tasks.py
import logging import os import random from datetime import timedelta from urllib.parse import urlparse from celery import shared_task from django.conf import settings from django.db import transaction from django.db.models import Count, Q from django.utils.timezone import now from requests import HTTPError from rest_...
(self): if self.tag.type != Tag.COPYRIGHT: return name = self.tag.name.replace("_", " ") self._get_and_save_info(MALCopyrightInfoService, name) names = [name] + self.get_values_from_info('name_ja') self._get_and_save_info(BangumiCopyrightInfoService, ...
translate_copyright
identifier_name
day04.rs
//! # --- Day 4: Passport Processing --- //! //! You arrive at the airport only to realize that you grabbed your North Pole //! Credentials instead of your passport. While these documents are extremely //! similar, North Pole Credentials aren't issued by a country and therefore //! aren't actually valid documentation f...
.filter_map(|x| Passport::from_hashmap(x)) .collect(); assert_eq!( passports, vec![ Passport { ecl: "gry".into(), pid: "860033327".into(), eyr: 2020, hcl: "#fffffd".in...
random_line_split
day04.rs
//! # --- Day 4: Passport Processing --- //! //! You arrive at the airport only to realize that you grabbed your North Pole //! Credentials instead of your passport. While these documents are extremely //! similar, North Pole Credentials aren't issued by a country and therefore //! aren't actually valid documentation f...
() { let input = "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm"; let (_, kvs) = kvlist_parser(input).unwrap(); assert_eq!( kvs, vec![ ("ecl", "gry"), ("pid", "860033327"), ("eyr", "2020"), ...
test_kvlist_parser
identifier_name
AtivContex 5.py
###################################################################################################### # ESTE PROGRAMA É REFERENTE AO NÚMERO DE CASOS DE CORONAVIRUS POR REGIÃO # ###################################################################################################### import mat...
Regioes[5].append(AC[5]) Regioes[6].append(AC[6]) ## Remove os dados das regiões AC.remove(regiaoAC) ##Soma dos dados do municipio de AC (h) somaAC=[sum(AC[1]),sum(AC[2]),sum(AC[3]),sum(AC[4]),sum(AC[5])] ##DICIONÁRIO Nordeste=["Alagoas ","Bahia","Ceará ","Maranhão","Paraíba","Pernambuco", "Piauí","Rio Grande do N...
Regioes[1].append(AC[1]) Regioes[2].append(AC[2]) Regioes[3].append(AC[3]) Regioes[4].append(AC[4])
random_line_split
AtivContex 5.py
###################################################################################################### # ESTE PROGRAMA É REFERENTE AO NÚMERO DE CASOS DE CORONAVIRUS POR REGIÃO # ###################################################################################################### import mat...
cipais regiões de saúde***\n") print("\n0-Maceió\n1-Salvador\n2-Fortaleza\n3-São Luis\n4-João Pessoa\n5-Recife\n6-Teresina\n7-Natal\n8-Aracaju\n9-Parnamirim") ## Max e Min dos valores númericos de óbitos novos (j) print("Menor valor numérico de óbitos novos:",min(Regioes[6])) print("Maior valor ...
mulado aperte em 2:")) if(e1==1): print("***Wiki:estados do Brasil**\n") print("\nNORTE:\n0-Acre\n1-Amapá\n2-Amazonas\n3-Rondônia\n4-Roraima\n5-Tocantins\n6-Pará") print("\nNORDESTE:\n7-Alagoas\n8-Bahia\n9-Ceará\n10-Maranhão\n11-Paraíba\nPernanbuco\n13-Piauí\n14-Rio Grande do Nort...
conditional_block
sync.go
package logsync import ( "context" "errors" "fmt" "io/ioutil" "net/http" "net/url" "regexp" "strings" "sync" "time" "github.com/mongodb/mongo-go-driver/bson" "github.com/mongodb/mongo-go-driver/mongo" "golang.org/x/net/html" ) var dburl = "mongodb://127.0.0.1:27017" //CburnFile defines the cburn file t...
} case fetcher := <-s.routineDone: s.routineReturned++ fmt.Printf("Processor|End[ %d| %d] : %s\n", fetcher.id, s.routineLauched-s.routineReturned, fetcher.urlEntry.url.String()) default: if s.routineMax == 0 || s.routineLauched-s.routineReturned < s.routineMax { select { case record, ok := <-c....
{ break loop }
conditional_block
sync.go
package logsync import ( "context" "errors" "fmt" "io/ioutil" "net/http" "net/url" "regexp" "strings" "sync" "time" "github.com/mongodb/mongo-go-driver/bson" "github.com/mongodb/mongo-go-driver/mongo" "golang.org/x/net/html" ) var dburl = "mongodb://127.0.0.1:27017" //CburnFile defines the cburn file t...
(urlEntry *URLEntry) *RecordFetcher { r := &RecordFetcher{ Fetcher: Fetcher{ id: c.recordStat.routineLauched, client: c.recordClient, ctx: c.ctx, done: c.recordStat.routineDone, urlEntry: urlEntry, timeout: time.Second * 30, }, subUrls: newURLQueue(100), files: ma...
newRecordFetcher
identifier_name
sync.go
package logsync import ( "context" "errors" "fmt" "io/ioutil" "net/http" "net/url" "regexp" "strings" "sync" "time" "github.com/mongodb/mongo-go-driver/bson" "github.com/mongodb/mongo-go-driver/mongo" "golang.org/x/net/html" ) var dburl = "mongodb://127.0.0.1:27017" //CburnFile defines the cburn file t...
routineDone chan *Fetcher routineMax int } //Controller is the global data type Controller struct { ctx context.Context wg sync.WaitGroup explorerClient *clientConn recordClient *clientConn subTree chan *URLEntry record chan *URLEntry urlCache map[string]...
random_line_split
sync.go
package logsync import ( "context" "errors" "fmt" "io/ioutil" "net/http" "net/url" "regexp" "strings" "sync" "time" "github.com/mongodb/mongo-go-driver/bson" "github.com/mongodb/mongo-go-driver/mongo" "golang.org/x/net/html" ) var dburl = "mongodb://127.0.0.1:27017" //CburnFile defines the cburn file t...
//CreateTime builds url time func CreateTime(ts string) time.Time { regex, _ := regexp.Compile("([0-9]+)-([A-Za-z]+)-[0-9]{2}([0-9]{2})[\t ]*([0-9]{2}:[0-9]{2})") tss := regex.FindStringSubmatch(ts) if len(tss) == 5 { ts = fmt.Sprintf("%s %s %s %s PDT", tss[1], tss[2], tss[3], tss[4]) tm, _ := time.Parse(time....
{ for _, attr := range t.Attr { if attr.Key == "href" { return attr.Val, nil } } return "", errors.New("No Href attribute in the link") }
identifier_body
auth.go
package server import ( "crypto/md5" "crypto/rand" "crypto/x509" "crypto/sha256" "encoding/base64" "encoding/hex" "fmt" "io" "log" "net/http" "os" "path" "strings" "sync" "time" ) type Authenticator struct { nonces map[string]Nonce mutex sync.Mutex } type AuthDomain struct { Realm string Entry En...
(entry Entry, res http.ResponseWriter, req *http.Request) bool { Auth.mutex.Lock() defer Auth.mutex.Unlock() now := time.Now() Auth.purge(now) authorized, found_auth, stale, errors := Auth.checkRequest(entry, req, now) if len(errors) > 0 { for err := range errors { fmt.Println(err) } } auths, auth_err...
Authenticate
identifier_name
auth.go
package server import ( "crypto/md5" "crypto/rand" "crypto/x509" "crypto/sha256" "encoding/base64" "encoding/hex" "fmt" "io" "log" "net/http" "os" "path" "strings" "sync" "time" ) type Authenticator struct { nonces map[string]Nonce mutex sync.Mutex } type AuthDomain struct { Realm string Entry En...
func (Auth *Authenticator) checkRequest(entry Entry, req *http.Request, now time.Time) (bool, bool, bool, []error) { var errors []error var stale = false var found_auth_all = false if req.TLS != nil { certs := req.TLS.PeerCertificates; for _, cert := range certs { authList, ers := authList(entry); if...
{ // FIXME do something with nonce_count nonce, ok := auth.nonces[noncekey] if !ok { return false, "", "", "" } opaque := nonce.Opaque auth_domain := nonce.Domain auth_realm := nonce.Realm valid := nonce.Time.Add(nonce.Validity).After(now) if !valid { delete(auth.nonces, noncekey) //log.Printf("Purge sta...
identifier_body
auth.go
package server import ( "crypto/md5" "crypto/rand" "crypto/x509" "crypto/sha256" "encoding/base64" "encoding/hex" "fmt" "io" "log" "net/http" "os" "path" "strings" "sync" "time" ) type Authenticator struct { nonces map[string]Nonce mutex sync.Mutex } type AuthDomain struct { Realm string Entry En...
for ent := entry; ent != nil; ent = ent.Parent(true) { auths := entry.Parameters().Child("auth") auth_list, err := auths.Children() if err != nil && os.IsExist(err) { errors = append(errors, err) continue } for _, auth := range auth_list { found := false if auth.Name() == AnonymousAuthDomain { ...
random_line_split
auth.go
package server import ( "crypto/md5" "crypto/rand" "crypto/x509" "crypto/sha256" "encoding/base64" "encoding/hex" "fmt" "io" "log" "net/http" "os" "path" "strings" "sync" "time" ) type Authenticator struct { nonces map[string]Nonce mutex sync.Mutex } type AuthDomain struct { Realm string Entry En...
for _, auth := range auth_list { found := false if auth.Name() == AnonymousAuthDomain { continue } for _, v := range res_auths { if v == auth.Name() { found = true break } } if !found { res_auths = append(res_auths, auth.Name()) } } if !auths.Child("inherit").Exists...
{ errors = append(errors, err) continue }
conditional_block
tools.py
import matplotlib.pyplot as plt import numpy as np cos = np.cos sin = np.sin twopi = np.pi*2. pi = np.pi def myrotate(th): # Add pi/2 to make it reference the x-axis # on range [0,2pi] # th = (th+pi/2.) if th<(3.*pi/2.) else (th-3.*pi/2.) # if th > pi: th -= pi th = th + pi/2. if th > twopi: t...
th0 = th # Detect false rotations if (0): gap = 5 # Thetas are wrt alpha for ith, th in enumerate(thetas): if ith > gap: iref = max(0,ith-gap) dth = th - thetas[iref] if dth > pi: # angles should be ...
pol = np.sign(dalpha) thetas[ith] = th - alpha
random_line_split
tools.py
import matplotlib.pyplot as plt import numpy as np cos = np.cos sin = np.sin twopi = np.pi*2. pi = np.pi def myrotate(th): # Add pi/2 to make it reference the x-axis # on range [0,2pi] # th = (th+pi/2.) if th<(3.*pi/2.) else (th-3.*pi/2.) # if th > pi: th -= pi th = th + pi/2. if th > twopi: t...
(ref,rs): # ref is 1x2 ndarray # rs is list of vectors to compare, nx2 return np.linalg.norm((ref-rs),axis=1) def nematicdirector(Q): # Given Q matrix return order parameter and angle w,v = np.linalg.eig(Q) idx = np.argmax(w) Lam = w[idx] # Equiv to sqrt(S*S+T*T) nu = v[:,idx] alpha...
dist_from
identifier_name
tools.py
import matplotlib.pyplot as plt import numpy as np cos = np.cos sin = np.sin twopi = np.pi*2. pi = np.pi def myrotate(th): # Add pi/2 to make it reference the x-axis # on range [0,2pi] # th = (th+pi/2.) if th<(3.*pi/2.) else (th-3.*pi/2.) # if th > pi: th -= pi th = th + pi/2. if th > twopi: t...
def get_lat_nbrs(block,n_nbr,edge,nx,probes,use_bulk=False,\ method="random",ret_nbrs=False,sparse_bulk_factor=1,\ use_xyth=False): ''' Return (xprobe, n_nbr) array of neighbours I use xprobe because if use_bulk is true then It's some indeterminant ...
''' rod x,y coordinates must be relative to their probe center angular coordinates are in range [0,2pi] Given your application, they will have their 4th column as a variable vector Instead of strict polar sort, the next rod is actually a nearest neighbour in the winding direction We can ach...
identifier_body
tools.py
import matplotlib.pyplot as plt import numpy as np cos = np.cos sin = np.sin twopi = np.pi*2. pi = np.pi def myrotate(th): # Add pi/2 to make it reference the x-axis # on range [0,2pi] # th = (th+pi/2.) if th<(3.*pi/2.) else (th-3.*pi/2.) # if th > pi: th -= pi th = th + pi/2. if th > twopi: t...
# Return nbrs to original coords nbrs[:,0] += com_x nbrs[:,1] += com_y nbrs_full[i] = nbrs if ret_nbrs: return features, nbrs_full, alphas else: return features def get_xyth_feature(nbrs): c2 = cos(2.* nbrs[:,2]) s2 = sin(...
features[i,:] = nbrs[:,-1] / pi
conditional_block
resnext_cifar.py
""" Creates a ResNeXt Model as defined in: Xie, S., Girshick, R., Dollar, P., Tu, Z., & He, K. (2016). Aggregated residual transformations for deep neural networks. arXiv preprint arXiv:1611.05431. import from https://github.com/prlz77/ResNeXt.pytorch/blob/master/models/model.py """ import torch import torch.nn as nn ...
(**kwargs): """Constructs a ResNeXt. """ model = CifarResNeXt(**kwargs) return model # """ # resneXt for cifar with pytorch # Reference: # [1] S. Xie, G. Ross, P. Dollar, Z. Tu and K. He Aggregated residual transformations for deep neural networks. In CVPR, 2017 # """ # # import t...
resnext
identifier_name
resnext_cifar.py
""" Creates a ResNeXt Model as defined in: Xie, S., Girshick, R., Dollar, P., Tu, Z., & He, K. (2016). Aggregated residual transformations for deep neural networks. arXiv preprint arXiv:1611.05431. import from https://github.com/prlz77/ResNeXt.pytorch/blob/master/models/model.py """ import torch import torch.nn as nn i...
stride: conv stride. Replaces pooling layer. cardinality: num of convolution groups. widen_factor: factor to reduce the input dimensionality before convolution. """ super(ResNeXtBottleneck, self).__init__() D = cardinality * out_channels // widen_factor ...
out_channels: output channel dimensionality
random_line_split
resnext_cifar.py
""" Creates a ResNeXt Model as defined in: Xie, S., Girshick, R., Dollar, P., Tu, Z., & He, K. (2016). Aggregated residual transformations for deep neural networks. arXiv preprint arXiv:1611.05431. import from https://github.com/prlz77/ResNeXt.pytorch/blob/master/models/model.py """ import torch import torch.nn as nn ...
elif key.split('.')[-1] == 'bias': self.state_dict()[key][...] = 0 def block(self, name, in_channels, out_channels, pool_stride=2): """ Stack n bottleneck modules where n is inferred from the depth of the network. Args: name: string name of the current block...
if 'conv' in key: init.kaiming_normal(self.state_dict()[key], mode='fan_out') if 'bn' in key: self.state_dict()[key][...] = 1
conditional_block
resnext_cifar.py
""" Creates a ResNeXt Model as defined in: Xie, S., Girshick, R., Dollar, P., Tu, Z., & He, K. (2016). Aggregated residual transformations for deep neural networks. arXiv preprint arXiv:1611.05431. import from https://github.com/prlz77/ResNeXt.pytorch/blob/master/models/model.py """ import torch import torch.nn as nn ...
# """ # resneXt for cifar with pytorch # Reference: # [1] S. Xie, G. Ross, P. Dollar, Z. Tu and K. He Aggregated residual transformations for deep neural networks. In CVPR, 2017 # """ # # import torch # import torch.nn as nn # import math # # # class Bottleneck(nn.Module): # expansion = 4 # ...
"""Constructs a ResNeXt. """ model = CifarResNeXt(**kwargs) return model
identifier_body
store.ts
// store.ts import { InjectionKey, State } from 'vue'; import { createLogger, createStore, useStore as baseUseStore, Store, } from 'vuex'; import { nextLine, playerAnswered, runLine } from './vm/renpy-vm'; import { DialogKey, MachineStack } from './types/vuex'; import { addDataHelper, getModifiableData, s...
, setButtons(state, buttons: { [key: string]: ButtonConfig }) { for (const i in buttons) { state.buttons[i] = { enabled: buttons[i].enabled, }; } }, clearDialog(state) { state.dialog.splice(0); }, changeButton(state, payload: { button...
{ state.currentScreen = screen; }
identifier_body
store.ts
// store.ts import { InjectionKey, State } from 'vue'; import { createLogger, createStore, useStore as baseUseStore, Store, } from 'vuex'; import { nextLine, playerAnswered, runLine } from './vm/renpy-vm'; import { DialogKey, MachineStack } from './types/vuex'; import { addDataHelper, getModifiableData, s...
// define injection key key = Symbol('Store Injection Key'); console.log('setup store'); store = createStore<State>({ state: { machine: { stack: [], script: {}, data: { playerName: 'Player', }, }, dialog: [], ready: false, count: 0, ...
{ plugins.push(createLogger()); }
conditional_block
store.ts
// store.ts import { InjectionKey, State } from 'vue'; import { createLogger, createStore, useStore as baseUseStore, Store, } from 'vuex'; import { nextLine, playerAnswered, runLine } from './vm/renpy-vm'; import { DialogKey, MachineStack } from './types/vuex'; import { addDataHelper, getModifiableData, s...
(state) { state.errors = []; }, addNotification(state, { id, notification }) { state.notifications[id] = notification; return id; }, deleteNotification(state, id) { console.log('delete notif', id); delete state.notifications[id]; }, }, plugin...
clearErrors
identifier_name
store.ts
// store.ts import { InjectionKey, State } from 'vue'; import { createLogger, createStore, useStore as baseUseStore, Store, } from 'vuex'; import { nextLine, playerAnswered, runLine } from './vm/renpy-vm'; import { DialogKey, MachineStack } from './types/vuex'; import { addDataHelper, getModifiableData, s...
plugins, }); return { store, key, }; } // define your own `useStore` composition function export function useStore() { console.log('use store'); console.log(`key `, key); console.log(`store `, store); const result = baseUseStore(key); console.log(result); return result; }
},
random_line_split
tls_pstm_montgomery_reduce.rs
use libc; use libc::free; extern "C" { #[no_mangle] fn memset(_: *mut libc::c_void, _: libc::c_int, _: libc::c_ulong) -> *mut libc::c_void; #[no_mangle] fn xzalloc(size: size_t) -> *mut libc::c_void; #[no_mangle] fn pstm_clamp(a: *mut pstm_int); #[no_mangle] fn pstm_cmp_mag(a: *mut pstm_int, b: *mut ...
( mut a: *mut pstm_int, mut m: *mut pstm_int, mut mp: pstm_digit, mut paD: *mut pstm_digit, mut paDlen: uint32, ) -> int32 { let mut c: *mut pstm_digit = 0 as *mut pstm_digit; //bbox: was int16 let mut _c: *mut pstm_digit = 0 as *mut pstm_digit; let mut tmpm: *mut pstm_digit = 0 as *mut pstm_digit; le...
pstm_montgomery_reduce
identifier_name
tls_pstm_montgomery_reduce.rs
use libc; use libc::free; extern "C" { #[no_mangle] fn memset(_: *mut libc::c_void, _: libc::c_int, _: libc::c_ulong) -> *mut libc::c_void; #[no_mangle] fn xzalloc(size: size_t) -> *mut libc::c_void; #[no_mangle] fn pstm_clamp(a: *mut pstm_int); #[no_mangle] fn pstm_cmp_mag(a: *mut pstm_int, b: *mut ...
/* copy the input */ oldused = (*a).used; x = 0i32; while x < oldused { *c.offset(x as isize) = *(*a).dp.offset(x as isize); x += 1 } x = 0i32; while x < pa { let mut cy: pstm_digit = 0i32 as pstm_digit; /* get Mu for this round */ mu = (*c.offset(x as isize)).wrapping_mul(mp); _c...
{ c = xzalloc((2i32 * pa + 1i32) as size_t) as *mut pstm_digit //bbox }
conditional_block
tls_pstm_montgomery_reduce.rs
use libc; use libc::free; extern "C" { #[no_mangle] fn memset(_: *mut libc::c_void, _: libc::c_int, _: libc::c_ulong) -> *mut libc::c_void; #[no_mangle] fn xzalloc(size: size_t) -> *mut libc::c_void; #[no_mangle] fn pstm_clamp(a: *mut pstm_int); #[no_mangle] fn pstm_cmp_mag(a: *mut pstm_int, b: *mut ps...
* the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This General Public License does NOT permit incorporating this software * into proprietary programs. If you are unable to comply with the GPL, a * commercial license for this software may be purchased fr...
* * The latest version of this code is available at http://www.matrixssl.org * * This software is open source; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by
random_line_split