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
core.py
in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDE...
def get_weight_ops(self, ops=None, skip_bias_op=False): """ Get all ops that contain weights. If a list of ops is passed search only ops from this list. Return the sequenced list of weight ops always with Conv/FC first, followed by the bias op, if present. :param ops: List of...
random_line_split
config.go
// EnableNodePort enables k8s NodePort service implementation in BPF EnableNodePort bool // EnableHostPort enables k8s Pod's hostPort mapping through BPF EnableHostPort bool // NodePortMode indicates in which mode NodePort implementation should run // ("snat", "dsr" or "hybrid") NodePortMode string // NodePortA...
////////////////////////////// Service //////////////////////////
random_line_split
config.go
) c.EndpointInterfaceNamePrefix = viper.GetString(EndpointInterfaceNamePrefix) c.DevicePreFilter = viper.GetString(PrefilterDevice) c.DisableCiliumEndpointCRD = viper.GetBool(DisableCiliumEndpointCRDName) c.DisableK8sServices = viper.GetBool(DisableK8sServices) c.EgressMasqueradeInterfaces = viper.GetString(Egress...
File) } else { viper.SetConfigName(configN
conditional_block
config.go
Port enables k8s Pod's hostPort mapping through BPF EnableHostPort bool // NodePortMode indicates in which mode NodePort implementation should run // ("snat", "dsr" or "hybrid") NodePortMode string // NodePortAcceleration indicates whether NodePort should be accelerated // via XDP ("none", "generic" or "native") ...
c.DirectRoutingDevice = viper.GetString(DirectRoutingDevice) c.DisableConntrack = viper.GetBool(DisableConntrack) c.EnableIPv4 = getIPv4Enabled() c.EnableIPv6 = viper.GetBool(EnableIPv6Name) c.EnableIPSec = viper.GetBool(EnableIPSecName) c.EnableWellKnownIdentities = viper.GetBool(EnableWellKnownIdentities) c.En...
{ c.LibDir = viper.GetString(LibDir) c.BpfDir = filepath.Join(c.LibDir, defaults.BpfDir) c.AgentHealthPort = viper.GetInt(AgentHealthPort) c.AgentLabels = viper.GetStringSlice(AgentLabels) c.AllowICMPFragNeeded = viper.GetBool(AllowICMPFragNeeded) c.AllowLocalhost = viper.GetString(AllowLocalhost) c.AnnotateK8s...
identifier_body
config.go
= viper.GetBool(EnableExternalIPs) c.EnableL7Proxy = viper.GetBool(EnableL7Proxy) c.EnableTracing = viper.GetBool(EnableTracing) c.EnableNodePort = viper.GetBool(EnableNodePort) c.EnableHostPort = viper.GetBool(EnableHostPort) c.NodePortMode = viper.GetString(NodePortMode) c.NodePortAcceleration = viper.GetStrin...
ing]interface
identifier_name
extract_patch.py
(evals, evecs) = np.linalg.eig(M2x2) l1, l2 = evals v1, v2 = evecs return l1, l2, v1, v2 #----------------------- # INPUT #----------------------- # We will call perdoch's invA = invV print('--------------------------------') print('Let V = Perdoch.A') print(...
arrow.set_facecolor(color) ax.add_patch(arrow) df2.update() def _2x2_eig(M2x2):
random_line_split
extract_patch.py
invV = ', invV) print('--------------------------------') print('V is a transformation from points on the ellipse to a unit circle') helpers.horiz_print('V = ', V) print('--------------------------------') print('Points on a matrix satisfy (x).T.dot(Z).dot(x) = 1') print('where Z = (V.T).dot(V)'...
_2x2_eig
identifier_name
extract_patch.py
else: patch, subkp = get_patch(rchip, kp) #print('[extract] kp = '+str(kp)) #print('[extract] subkp = '+str(subkp)) #print('[extract] patch.shape = %r' % (patch.shape,)) color = (0, 0, 1) fig, ax = df2.imshow(patch, **kwargs) df2.draw_kpts2([subkp], ell_color=color, pts=True) ...
wpatch, wkp = get_warped_patch(rchip, kp) patch = wpatch subkp = wkp
conditional_block
extract_patch.py
df2.update() def _2x2_eig(M2x2): (evals, evecs) = np.linalg.eig(M2x2) l1, l2 = evals v1, v2 = evecs return l1, l2, v1, v2 #----------------------- # INPUT #----------------------- # We will call perdoch's invA = invV print('------------------------------...
from hotspotter import draw_func2 as df2 np.set_printoptions(precision=8) tau = 2 * np.pi df2.reset() df2.figure(9003, docla=True, doclf=True) ax = df2.gca() ax.invert_yaxis() def _plotpts(data, px, color=df2.BLUE, label=''): #df2.figure(9003, docla=True, pnum=(1, 1, px)) df...
identifier_body
main.rs
impl FnOnce<()> for Closure { type Output = u32; extern "rust-call" fn call_once(self, args: ()) -> u32 { println!("call it FnOnce()"); self.env_var + 2 } } impl FnMut<()> for Closure { extern "rust-call" fn call_mut(&mut self, args: ()) -> u32 { println!("call it FnMut()"); ...
env_var: u32, }
random_line_split
main.rs
fn call(&self, args: ()) -> () { println!("{:?}", self.env_var); } } // 使用 `FnOnce()` 闭包作为参数 // 在函数体内执行闭包, 用于判断自身的所有权是否转移 fn call<F: FnOnce()>(f: F) { f() } fn boxed_closure(c: &mut Vec<Box<Fn()>>) { let s = "second"; c.push(Box::new(|| println!("first"))); // 以不可变方式捕获了环境变量 `s`, // 但这里需
装箱稍后在迭代器中使用 // 所以这里必须使用 `move` 关键字将 `s` 的所有权转移到闭包中, // 因为变量 `s` 是复制语义类型, 所以该闭包捕获的是原始变量 `s` 的副本 c.push(Box::new(move || println!("{}", s))); c.push(Box::new(|| println!("third"))); } // `Fn` 并不受孤儿规则限制, 可有可无 // use std::ops::Fn; // 以 trait 限定的方式实现 any 方法 // 自定义的 Any 不同于标准库的 Any // 该函数的泛型 `F` 的 trait 限定为...
要将闭包
identifier_name
main.rs
" fn call(&self, args: ()) -> () { println!("{:?}", self.env_var); } } // 使用 `FnOnce()` 闭包作为参数 // 在函数体内执行闭包, 用于判断自身的所有权是否转移 fn call<F: FnOnce()>(f: F) { f() } fn boxed_closure(c: &mut Vec<Box<Fn()>>) { let s = "second"; c.push(Box::new(|| println!("first"))); // 以不可变方式捕获了环境变量 `s`, // 但这里需要...
Pick<F> // where // F: Fn(&(u32, u32)) -> &u32, // { // fn call(&self) -> &u32 { (self.func)(&self.data) } // } // 实际生命周期 impl<F> Pick<F> where F: for<'f> Fn(&'f (u32, u32)) -> &'f u32, { fn call(&self) -> &u32 { (self.func)(&self.data) } } fn max(data: &(u32, u32)) -> &u32 { if data.0 > data.1 {...
器自动补齐了生命周期参数 // impl<F>
identifier_body
main.rs
fn call(&self, args: ()) -> () { println!("{:?}", self.env_var); } } // 使用 `FnOnce()` 闭包作为参数 // 在函数体内执行闭包, 用于判断自身的所有权是否转移 fn call<F: FnOnce()>(f: F) { f() } fn boxed_closure(c: &mut Vec<Box<Fn()>>) { let s = "second"; c.push(Box::new(|| println!("first"))); // 以不可变方式捕获了环境变量 `s`, // 但这里需要将...
let env_var = 1; let c = || env_var + 2; assert_eq!(3, c()); // 显式指定闭包类型 let env_var = 1; // 该类型为 trait 对象, 此处必须使用 trait 对象 let c: Box<Fn() -> i32> = Box::new(|| env_var + 2); assert_eq!(3, c()); // 复制语义类型自动实现 `Fn` // 绑定为字符串字面量, 为复制语义类型 let s = "hello"; // 闭包会按照不可变引用类型来捕获...
} // 与上者等价的闭包示例
conditional_block
onsite_create_calibration_file.py
27017/") optional.add_argument('-y', '--yes', action="store_true", help='Do not ask interactively for permissions, assume true') optional.add_argument('--no_pro_symlink', action="store_true", help='Do not update the pro dir symbolic link, assume true') optional.add_argument( '--flatfield-heur...
random_line_split
onsite_create_calibration_file.py
output file name (change only for debugging)", default="calibration") optional.add_argument('--sub_run', help="sub-run to be processed.", type=int, default=0) optional.add_argument('--min_ff', help="Min FF intensity cut in ADC.", type=float) optional.add_argument('--max_ff', help="Max FF intensi...
""" return the range of charges to select the FF events """ try: if filters is None: raise ValueError("Filters are not defined") # give standard values if standard filters if filters == '52': min_ff = 3000 max_ff = 12000 else: # ... ...
identifier_body
onsite_create_calibration_file.py
run_number', help="Run number if the flat-field data", type=int, required=True) optional.add_argument('-p', '--pedestal_run', help="Pedestal run to be used. If None, it looks for the pedestal run of the date of the FF data.", type=int) version = lstchai...
(): args, remaining_args = parser.parse_known_args() run = args.run_number prod_id = args.prod_version stat_events = args.statistics time_run = args.time_run sys_date = args.sys_date no_sys_correction = args.no_sys_correction output_base_name = args.output_base_name sub_run = args.su...
main
identifier_name
onsite_create_calibration_file.py
. If None, search the last time run before or equal the FF run", type=int) optional.add_argument( '--sys_date', help=( "Date of systematic correction file (format YYYYMMDD). \n" "Default: automatically search the best date \n" ), ) optional.add_argument('--no_sys_correc...
raise ValueError("Filters are not defined")
conditional_block
auto-py-torrent.py
ER = '\033[1m\033[31m' def get_parser(): """Load parser for command line arguments. It parses argv/input into args variable. """ # Parent and only parser. parser = argparse.ArgumentParser( add_help=True, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('m...
build_url
identifier_name
auto-py-torrent.py
GREEN = '\033[42m' CYAN = '\033[36m' RED = '\033[41m' PINK = '\033[95m' PURPLE = '\033[35m' LIGHTBLUE = '\033[94m' LGREEN = '\033[0m\033[32m' LIGHTCYAN = '\033[0m\033[36m' LRED = '\033[0m\033[31m' LIGHTPURPLE = '\033[0m\033[35m' SEEDER = '\033[1m\033[32m' LEECHER = '\033[...
titles = [] seeders = [] leechers = [] ages = [] sizes = [] if self.page == 'the_pirate_bay': for elem in self.elements[0]: title = elem.find('a', {'class': 'detLink'}).get_text() titles.append(title) font_text...
def build_table(self): """Build table.""" headers = ['Title', 'Seeders', 'Leechers', 'Age', 'Size']
random_line_split
auto-py-torrent.py
GREEN = '\033[42m' CYAN = '\033[36m' RED = '\033[41m' PINK = '\033[95m' PURPLE = '\033[35m' LIGHTBLUE = '\033[94m' LGREEN = '\033[0m\033[32m' LIGHTCYAN = '\033[0m\033[36m' LRED = '\033[0m\033[31m' LIGHTPURPLE = '\033[0m\033[35m' SEEDER = '\033[1m\033[32m' LEECHER = '\033[...
elif self.mode_search == 'list': if self.selected is not None: # t_p, pirate and 1337x got magnet inside, else direct. if self.page in ['the_pirate_bay', 'torrent_project', ...
print('Nothing found.') return
conditional_block
auto-py-torrent.py
GREEN = '\033[42m' CYAN = '\033[36m' RED = '\033[41m' PINK = '\033[95m' PURPLE = '\033[35m' LIGHTBLUE = '\033[94m' LGREEN = '\033[0m\033[32m' LIGHTCYAN = '\033[0m\033[36m' LRED = '\033[0m\033[31m' LIGHTPURPLE = '\033[0m\033[35m' SEEDER = '\033[1m\033[32m' LEECHER = '\033[...
'Invalid input. ' + 'Please select an appropiate one or other option.' + Colors.ENDC) return False def select_torrent(self): """Select torrent. First check if specific element/info is obtained in content_page.
"""Handle user's input in list mode.""" #self.selected = input('>> ') self.selected = '0' if self.selected in ['Q', 'q']: sys.exit(1) elif self.selected in ['B', 'b']: self.back_to_menu = True return True elif is_num(self.selected): ...
identifier_body
filter.go
FilterOpLt FilterOp = "<" // FilterOpGte greater than or equal FilterOpGte FilterOp = ">=" // FilterOpLte less than or equal FilterOpLte FilterOp = "<=" // FilterOpCont contains the specified text, case sensitive FilterOpCont FilterOp = "%=" // FilterOpNotCont does not contain the specified text, case sensitive...
nd(
identifier_name
filter.go
that must be implemented by plugins - the string value is // used in the core string formatting method (for logging etc.) type FilterOp string const ( // FilterOpAnd and FilterOpAnd FilterOp = "&&" // FilterOpOr or FilterOpOr FilterOp = "||" // FilterOpEq equal FilterOpEq FilterOp = "==" // FilterOpNe not equa...
} return f
random_line_split
filter.go
case sensitive IContains(name string, value driver.Value) Filter // INotContains disallows the string anywhere - case sensitive NotIContains(name string, value driver.Value) Filter } // NullBehavior specifies whether to sort nulls first or last in a query type NullBehavior int const ( NullsDefault NullBehavior =...
return fb.fieldFilter(FilterOpNotCont, name, value) }
identifier_body
filter.go
convenience methods to add conditions type MultiConditionFilter interface { Filter // Add adds filters to the condition Condition(...Filter) MultiConditionFilter } type AndFilter interface{ MultiConditionFilter } type OrFilter interface{ MultiConditionFilter } // FilterOp enum of filter operations that must be i...
} else if f.fb.forceAscending { for _, sf := range f.fb.sort { sf.Descending = false } } return &FilterInfo{ Children: children, Op: f.op, Field: f.field, Values: values, Value: value, Sort: f.fb.sort, Skip: f.fb.skip, Limit: f.fb.limit, Count: f.fb.count, }, ni...
sf.Descending = true }
conditional_block
wdpost_dispute_test.go
) // First, we configure two miners. After sealing, we're going to turn off the first miner so // it doesn't submit proofs. // // Then we're going to manually submit bad proofs. opts := []kit.NodeOpt{kit.WithAllSubsystems()} ens := kit.NewEnsemble(t, kit.MockProofs()). FullNode(&client, opts...). Miner(&cha...
{ //stm: @CHAIN_SYNCER_LOAD_GENESIS_001, @CHAIN_SYNCER_FETCH_TIPSET_001, //stm: @CHAIN_SYNCER_START_001, @CHAIN_SYNCER_SYNC_001, @BLOCKCHAIN_BEACON_VALIDATE_BLOCK_VALUES_01 //stm: @CHAIN_SYNCER_COLLECT_CHAIN_001, @CHAIN_SYNCER_COLLECT_HEADERS_001, @CHAIN_SYNCER_VALIDATE_TIPSET_001 //stm: @CHAIN_SYNCER_NEW_PEER_HEAD...
identifier_body
wdpost_dispute_test.go
build.Clock.Sleep(blocktime) } t.Log("accepted evil proof") //stm: @CHAIN_STATE_MINER_POWER_001 // Make sure the evil node didn't lose any power. p, err = client.StateMinerPower(ctx, evilMinerAddr, types.EmptyTSK) require.NoError(t, err) require.Equal(t, p.MinerPower.RawBytePower, types.NewInt(uint64(ssz))) ...
return err
random_line_split
wdpost_dispute_test.go
_SECTOR_LIST_001 evilSectors, err := evilMiner.SectorsListNonGenesis(ctx) require.NoError(t, err) evilSectorNo := evilSectors[0] // only one. //stm: @CHAIN_STATE_SECTOR_PARTITION_001 evilSectorLoc, err := client.StateSectorPartition(ctx, evilMinerAddr, evilSectorNo, types.EmptyTSK) require.NoError(t, err) t.Log...
{ //stm: @CHAIN_STATE_MINER_CALCULATE_DEADLINE_001 di, err := client.StateMinerProvingDeadline(ctx, maddr, types.EmptyTSK) require.NoError(t, err) // wait until the deadline finishes. if di.Index == ((targetDeadline + 1) % di.WPoStPeriodDeadlines) { break } build.Clock.Sleep(blocktime) }
conditional_block
wdpost_dispute_test.go
TSK) require.NoError(t, err) if di.Index == evilSectorLoc.Deadline && di.CurrentEpoch-di.Open > 1 { break } build.Clock.Sleep(blocktime) } err = submitBadProof(ctx, client, evilMiner.OwnerKey.Address, evilMinerAddr, di, evilSectorLoc.Deadline, evilSectorLoc.Partition) require.NoError(t, err, "evil proof ...
submitBadProof
identifier_name
deferred_call.rs
interrupts, //! and lets a kernel component return the function call stack up to the scheduler, //! automatically being called again. //! //! Usage //! ----- //! //! The `DEFCALLS` array size determines how many //! [DeferredCall](crate::deferred_call::DeferredCall)s //! may be registered. By default this is set to 32...
// To reduce monomorphization bloat, the non-generic portion of register is moved into this // function without generic parameters. #[inline(never)] fn register_internal_non_generic(&self, handler: DynDefCallRef<'static>) { // SAFETY: No accesses to DEFCALLS are via an &mut, and the Tock kerne...
{ // SAFETY: No accesses to CTR are via an &mut, and the Tock kernel is // single-threaded so all accesses will occur from this thread. let ctr = unsafe { &CTR }; let idx = ctr.get() + 1; ctr.set(idx); DeferredCall { idx } }
identifier_body
deferred_call.rs
important interrupts, //! and lets a kernel component return the function call stack up to the scheduler, //! automatically being called again. //! //! Usage //! ----- //! //! The `DEFCALLS` array size determines how many //! [DeferredCall](crate::deferred_call::DeferredCall)s //! may be registered. By default this is...
() -> bool { // SAFETY: No accesses to BITMASK are via an &mut, and the Tock kernel is // single-threaded so all accesses will occur from this thread. let bitmask = unsafe { &BITMASK }; bitmask.get() != 0 } /// This function should be called at the beginning of the kernel loop ...
has_tasks
identifier_name
deferred_call.rs
should look like: //! let some_capsule = unsafe { static_init!(SomeCapsule, SomeCapsule::new()) }; //! some_capsule.register(); //! ``` use crate::utilities::cells::OptionalCell; use core::cell::Cell; use core::marker::Copy; use core::marker::PhantomData; // This trait is not intended to be used as a trait object; /...
{ panic!( "ERROR: > 32 deferred calls, or a component forgot to register a deferred call." ); }
conditional_block
deferred_call.rs
important interrupts, //! and lets a kernel component return the function call stack up to the scheduler, //! automatically being called again. //! //! Usage //! ----- //! //! The `DEFCALLS` array size determines how many //! [DeferredCall](crate::deferred_call::DeferredCall)s //! may be registered. By default this is...
DeferredCall { idx } } // To reduce monomorphization bloat, the non-generic portion of register is moved into this // function without generic parameters. #[inline(never)] fn register_internal_non_generic(&self, handler: DynDefCallRef<'static>) { // SAFETY: No accesses to DEFCALLS a...
// SAFETY: No accesses to CTR are via an &mut, and the Tock kernel is // single-threaded so all accesses will occur from this thread. let ctr = unsafe { &CTR }; let idx = ctr.get() + 1; ctr.set(idx);
random_line_split
cut_plane.py
_1 maximum on cropping") if crop_x2: if crop_x2[0] < min(df_sub[x2]): raise Exception("Invalid x_2 minimum on cropping") if crop_x2[1] > max(df_sub[x2]): raise Exception("Invalid x_2 maximum on cropping") # If cropping x1 do it now # if c...
paper_plot
identifier_name
cut_plane.py
# Assign the axis names self.x1_name = x1 self.x2_name = x2 self.x3_name = [x3 for x3 in ['x','y','z'] if x3 not in [x1,x2]][0] # Find the nearest value in 3rd dimension search_values = np.array(sorted(df_flow[self.x3_name].unique())) nearest_idx = (np.abs(searc...
output: flow_file: full path name of flow file"""
random_line_split
cut_plane.py
self.x1_name = x1 self.x2_name = x2 self.x3_name = [x3 for x3 in ['x','y','z'] if x3 not in [x1,x2]][0] # Find the nearest value in 3rd dimension search_values = np.array(sorted(df_flow[self.x3_name].unique())) nearest_idx = (np.abs(search_values-x3_value)).argmin() nea...
if crop_x2: if crop_x2[0] < min(df_sub[x2]): raise Exception("Invalid x_2 minimum on cropping") if crop_x2[1] > max(df_sub[x2]): raise Exception("Invalid x_2 maximum on cropping") # If cropping x1 do it now # if crop_x1: # df...
raise Exception("Invalid x_1 maximum on cropping")
conditional_block
cut_plane.py
self.x1_name = x1 self.x2_name = x2 self.x3_name = [x3 for x3 in ['x','y','z'] if x3 not in [x1,x2]][0] # Find the nearest value in 3rd dimension search_values = np.array(sorted(df_flow[self.x3_name].unique())) nearest_idx = (np.abs(search_values-x3_value)).argmin() nea...
# Define cross plane subclass class CrossPlane(_CutPlane): def __init__(self, df_flow, x_value, y_center, z_center, D, resolution=100, crop_y=None,crop_z=None,invert_x1=True): #
def __init__(self, df_flow, z_value, resolution=100, x1_center=0.0,x2_center=0.0, D=None): # Set up call super super().__init__(df_flow, x1='x', x2='y', x3_value=z_value,resolution=resolution,x1_center=x1_center,x2_center=x2_center, D=D, invert_x1=False)
identifier_body
ground_glass.py
.set(contrast_data0) s1.place(x= 300,y = 310) s2 = tk.Scale(window,label='对比度1',from_=0.0 , to = 2.5,orient = tk.HORIZONTAL, length = 250, showvalue = 1, tickinterval = 0.5, resolution = 0.1,command = chang_contrast1) s2.set(contrast_data1) s2.place(x= 300,y = 390) s3 = tk.Sc...
img,anchor="nw") canvas1.create_image(image.width,0,image = img,anchor="nw") canvas1.pack() word_box.pack() top1.mainloop() def opencv(): global address1 src = cv.imread('output/%s/cutted.jpg'%(folder)) src = cv.cvtColor(src, cv.COLOR_BGR2GRAY) cv.imwrite('output/%s/gray.jp...
identifier_body
ground_glass.py
None: n = height / float(h) newsize = (int(n * w), height) else: n = width / float(w) newsize = (width, int(h * n)) # 缩放图像 newimage = cv.resize(image, newsize, interpolation=inter) return newimage def on_mouse(event, x, y, flags, param): global img, i...
if width is
conditional_block
ground_glass.py
int1, point2, point1_dis, point2_dis img2 = img1.copy() if event == cv.EVENT_LBUTTONDOWN: #左键点击 point1 = (x*4, y*4) point1_dis = (x, y) cv.circle(img2, point1_dis, 10, (0,255,0), 5) cv.imshow('image', img2) elif event == cv.EVENT_MOUSEMOVE and (flags & cv.EVENT...
img1, po
identifier_name
ground_glass.py
osing_data = float(input) def change_expansion_data(input): global expansion_data expansion_data = int(input) def change_rust_data(input): global rust_data rust_data = int(input) def change_winner_data(input): global rust_data rust_data = float(input) def scale_creat():...
canvas1.create_image(image.width,0,image = img,anchor="nw")
random_line_split
operator.go
.ApproximateSize to.RegionCount++ } // AddLearner is an OperatorStep that adds a region learner peer. type AddLearner struct { ToStore, PeerID uint64 } func (al AddLearner) String() string { return fmt.Sprintf("add learner peer %v on store %v", al.PeerID, al.ToStore) } // IsFinish checks if current step is finish...
// GetPriorityLevel get the priority level func (o *Operator) GetPriorityLevel() core.PriorityLevel { return o.level } // IsFinish checks if all steps are finished. func (o *Operator) IsFinish() bool { return atomic.LoadInt32(&o.currentStep) >= int32(len(o.steps)) } // IsTimeout checks the operator's create time ...
{ o.level = level }
identifier_body
operator.go
region.ApproximateSize to.RegionCount++ } // AddLearner is an OperatorStep that adds a region learner peer. type AddLearner struct { ToStore, PeerID uint64 } func (al AddLearner) String() string { return fmt.Sprintf("add learner peer %v on store %v", al.PeerID, al.ToStore) } // IsFinish checks if current step is...
return "split region" } // IsFinish checks if current step is finished. func (sr SplitRegion) IsFinish(region *core.RegionInfo) bool { return !bytes.Equal(region.StartKey, sr.StartKey) || !bytes.Equal(region.EndKey, sr.EndKey) } // Influence calculates the store difference that current step make. func (sr SplitRegi...
func (sr SplitRegion) String() string {
random_line_split
operator.go
Operator) SetDesc(desc string) { o.desc = desc } // AttachKind attaches an operator kind for the operator. func (o *Operator) AttachKind(kind OperatorKind) { o.kind |= kind } // RegionID returns the region that operator is targeted. func (o *Operator) RegionID() uint64 { return o.regionID } // RegionEpoch returns...
{ steps = append(steps, TransferLeader{FromStore: source.Leader.GetStoreId(), ToStore: target.Leader.GetStoreId()}) kind |= OpLeader }
conditional_block
operator.go
region.ApproximateSize to.RegionCount++ } // AddLearner is an OperatorStep that adds a region learner peer. type AddLearner struct { ToStore, PeerID uint64 } func (al AddLearner) String() string { return fmt.Sprintf("add learner peer %v on store %v", al.PeerID, al.ToStore) } // IsFinish checks if current step is...
() string { return fmt.Sprintf("merge region %v into region %v", mr.FromRegion.GetId(), mr.ToRegion.GetId()) } // IsFinish checks if current step is finished func (mr MergeRegion) IsFinish(region *core.RegionInfo) bool { if mr.IsPassive { return bytes.Compare(region.Region.StartKey, mr.ToRegion.StartKey) != 0 || b...
String
identifier_name
date.rs
: &str = "output date and time in RFC 5322 format. Example: Mon, 14 Aug 2006 02:34:56 -0600"; static RFC_3339_HELP_STRING: &str = "output date/time in RFC 3339 format. FMT='date', 'seconds', or 'ns' for date and time to the indicated precision. Example: 2006-08-14 02:34:56-06:00"; #[cfg(not(any(target_os = "macos...
{ Date, Seconds, Ns, } impl<'a> From<&'a str> for Rfc3339Format { fn from(s: &str) -> Self { match s { DATE => Self::Date, SECONDS => Self::Seconds, NS => Self::Ns, // Should be caught by clap _ => panic!("Invalid format: {s}"), ...
Rfc3339Format
identifier_name
date.rs
}; let date_source = if let Some(date) = matches.get_one::<String>(OPT_DATE) { if let Ok(duration) = parse_datetime::from_str(date.as_str()) { DateSource::Human(duration) } else { DateSource::Custom(date.into()) } } else if let Some(file) = matches.get_one::...
random_line_split
registry.go
service is healthy or not. Default value is True . Healthy bool // To show service is isolate or not. Default value is False . Isolate bool // TTL timeout. if node needs to use heartbeat to report,required. If not set,server will throw ErrorCode-400141 TTL int // optional, Timeout for single query. Default va...
(timeout time.Duration) RegistryOption { return func(o *registryOptions) { o.Timeout = timeout } } // WithRegistryRetryCount with RetryCount option. func WithRegistryRetryCount(retryCount int) RegistryOption { return func(o *registryOptions) { o.RetryCount = retryCount } } // Register the registration. func (r *Reg...
WithRegistryTimeout
identifier_name
registry.go
service is healthy or not. Default value is True . Healthy bool // To show service is isolate or not. Default value is False . Isolate bool // TTL timeout. if node needs to use heartbeat to report,required. If not set,server will throw ErrorCode-400141 TTL int // optional, Timeout for single query. Default va...
} } } } // handle AddEvent if
w.ServiceInstances[update.After.GetMetadata()["merge"]] = []model.Instance{update.After}
random_line_split
registry.go
service is healthy or not. Default value is True . Healthy bool // To show service is isolate or not. Default value is False . Isolate bool // TTL timeout. if node needs to use heartbeat to report,required. If not set,server will throw ErrorCode-400141 TTL int // optional, Timeout for single query. Default va...
// WithRegistryTimeout with Timeout option. func WithRegistryTimeout(timeout time.Duration) RegistryOption { return func(o *registryOptions) { o.Timeout = timeout } } // WithRegistryRetryCount with RetryCount option. func WithRegistryRetryCount(retryCount int) RegistryOption { return func(o *registryOptions) { o.R...
{ return func(o *registryOptions) { o.TTL = TTL } }
identifier_body
registry.go
Instance) error { id := uuid.NewString() for _, endpoint := range instance.Endpoints { u, err := url.Parse(endpoint) if err != nil { return err } host, port, err := net.SplitHostPort(u.Host) if err != nil { return err } portNum, err := strconv.Atoi(port) if err != nil { return err } //...
{ if len(inss) == 0 { continue } ins := &registry.ServiceInstance{ ID: inss[0].GetId(), Name: inss[0].GetService(), Version: inss[0].GetVersion(), Metadata: inss[0].GetMetadata(), } for _, item := range inss { if item.IsHealthy() { ins.Endpoints = append(ins.Endpoints, fmt.Spr...
conditional_block
device_route.go
*DeviceRoutes) AddPort(ctx context.Context, lp *voltha.LogicalPort, lps []*voltha.LogicalPort) error { logger.Debugw("add-port-to-routes", log.Fields{"port": lp, "len-logical-ports": len(lps)}) dr.routeBuildLock.Lock() if len(dr.Routes) == 0 { dr.routeBuildLock.Unlock() return dr.ComputeRoutes(ctx, lps) } /...
getReverseRoute
identifier_name
device_route.go
ni-ports-combination") } return nil } // AddPort augments the current set of routes with new routes corresponding to the logical port "lp". If the routes have // not been built yet then use logical port "lps" to compute all current routes (lps includes lp) func (dr *DeviceRoutes) AddPort(ctx context.Context, lp *vo...
{ dr.rootPortsLock.Lock() dr.RootPorts = make(map[uint32]uint32) dr.rootPortsLock.Unlock() // Do not numGetDeviceCalledLock Routes, logicalPorts as the callee function already holds its numGetDeviceCalledLock. dr.Routes = make(map[PathID][]Hop) dr.logicalPorts = make([]*voltha.LogicalPort, 0) dr.devicesPonPorts...
identifier_body
device_route.go
routes between the logical ports. This will clear up any existing route func (dr *DeviceRoutes) ComputeRoutes(ctx context.Context, lps []*voltha.LogicalPort) error { dr.routeBuildLock.Lock() defer dr.routeBuildLock.Unlock() logger.Debugw("computing-all-routes", log.Fields{"len-logical-ports": len(lps)}) var err ...
} } if copyFromNNIPort == nil { // Trying to add the same NNI port. Just return return nil } // Adding NNI Port? If we are here we already have an NNI port with a set of routes. Just copy the existing // routes using an existing NNI port if lp.RootPort { dr.copyFromExistingNNIRoutes(lp, copyFromNNI...
{ copyFromNNIPort = lport }
conditional_block
device_route.go
the routes between the logical ports. This will clear up any existing route func (dr *DeviceRoutes) ComputeRoutes(ctx context.Context, lps []*voltha.LogicalPort) error { dr.routeBuildLock.Lock() defer dr.routeBuildLock.Unlock() logger.Debugw("computing-all-routes", log.Fields{"len-logical-ports": len(lps)}) var ...
dr.logicalPorts = append(dr.logicalPorts, lp) nniLogicalPortExist = nniLogicalPortExist || lp.RootPort uniLogicalPortExist = uniLogicalPortExist || !lp.RootPort } // If we do not have both NNI and UNI ports then return an error if !(nniLogicalPortExist && uniLogicalPortExist) { fmt.Println("errors", nniLogi...
break } } if !exist {
random_line_split
controller.go
ert-manager/pkg/metrics" "github.com/jetstack/cert-manager/pkg/util" utilfeature "github.com/jetstack/cert-manager/pkg/util/feature" "github.com/jetstack/cert-manager/pkg/util/profiling" ) const controllerAgentName = "cert-manager" // This sets the informer's resync period to 10 hours // following the controller-r...
} return nil }) g.Go(func() error { log.V(logf.InfoLevel).Info("starting profiler", "address", profilerLn.Addr()) if err := profilerServer.Serve(profilerLn); err != http.ErrServerClosed { return err } return nil }) } elected := make(chan struct{}) if opts.LeaderElect { g.Go(func() erro...
if err := profilerServer.Shutdown(ctx); err != nil { return err
random_line_split
controller.go
return utilerrors.NewAggregate([]error{err, err2}) } return err } g.Go(func() error { log.V(logf.InfoLevel).Info("starting controller") // TODO: make this either a constant or a command line flag workers := 5 return iface.Run(workers, rootCtx.Done()) }) } log.V(logf.DebugLevel).Info("start...
{ // Identity used to distinguish between multiple controller manager instances id, err := os.Hostname() if err != nil { return fmt.Errorf("error getting hostname: %v", err) } // Set up Multilock for leader election. This Multilock is here for the // transitionary period from configmaps to leases see // https...
identifier_body
controller.go
-manager/pkg/metrics" "github.com/jetstack/cert-manager/pkg/util" utilfeature "github.com/jetstack/cert-manager/pkg/util/feature" "github.com/jetstack/cert-manager/pkg/util/profiling" ) const controllerAgentName = "cert-manager" // This sets the informer's resync period to 10 hours // following the controller-runt...
kubeCfg.QPS = opts.KubernetesAPIQPS kubeCfg.Burst = opts.KubernetesAPIBurst // Add User-Agent to client kubeCfg = rest.AddUserAgent(kubeCfg, util.CertManagerUserAgent) // Create a cert-manager api client intcl, err := clientset.NewForConfig(kubeCfg) if err != nil { return nil, nil, fmt.Errorf("error creati...
{ return nil, nil, fmt.Errorf("error creating rest config: %s", err.Error()) }
conditional_block
controller.go
-manager/pkg/metrics" "github.com/jetstack/cert-manager/pkg/util" utilfeature "github.com/jetstack/cert-manager/pkg/util/feature" "github.com/jetstack/cert-manager/pkg/util/profiling" ) const controllerAgentName = "cert-manager" // This sets the informer's resync period to 10 hours // following the controller-runt...
(ctx context.Context, opts *options.ControllerOptions) (*controller.Context, *rest.Config, error) { log := logf.FromContext(ctx, "build-context") // Load the users Kubernetes config kubeCfg, err := clientcmd.BuildConfigFromFlags(opts.APIServerHost, opts.Kubeconfig) if err != nil { return nil, nil, fmt.Errorf("err...
buildControllerContext
identifier_name
agvCtrl.py
): global g_point loadPoint() if g_point[originPoint] is not None: return g_point[originPoint] return originPoint @lock.lock(g_lock) def getOriginPoint(point): global g_point loadPoint() for itemIndex in g_point: if g_point[itemIndex] == point: return itemIndex return point @lock.lock(g_lock) def loa...
global g_carts p = os.path.dirname(__file__) pp = "cart.cfg" if p: pp = p+"/"+pp json_codec.dump_file(pp,g_carts) def findCart(scanId): global g_carts for c in g_carts: if g_carts[c] == scanId: return c return "unknown" global g_carts if g_carts is None: loadCart() if cartId in g_...
def saveCart():
random_line_split
agvCtrl.py
global g_point loadPoint() if g_point[originPoint] is not None: return g_point[originPoint] return originPoint @lock.lock(g_lock) def getOriginPoint(point): global g_point loadPoint() for itemIndex in g_point: if g_point[itemIndex] == point: return itemIndex return point @lock.lock(g_lock) def loadPo...
_col4") assert resulta== "begin_1" resultb= getPoint("StockA_row8_col4") assert resultb == "begin_2" def testgetOrginPoint(): resulta= getOriginPoint("begin_1") assert resulta== "StockA_row7_col4" resultb= getOriginPoint("begin_2") assert resultb == "StockA_row8_col4" resultc = getOriginPoint("hhahahaa") a...
kA_row7
identifier_name
agvCtrl.py
): global g_point loadPoint() if g_point[originPoint] is not None: return g_point[originPoint] return originPoint @lock.lock(g_lock) def getOriginPoint(point): global g_point loadPoint() for itemIndex in g_point: if g_point[itemIndex] == point: return itemIndex return point @lock.lock(g_lock) def loa...
int(): resulta= getPoint("StockA_row7_col4") assert resulta== "begin_1" resultb= getPoint("StockA_row8_col4") assert resultb == "begin_2" def testgetOrginPoint(): resulta= getOriginPoint("begin_1") assert resulta== "StockA_row7_col4" resultb= getOriginPoint("begin_2") assert resultb == "StockA_row8_col4" re...
agvId2 = api.getAgvId(agvId) api.reset(agvId2) def Init(): import interface.dashboard.dashboardApi locationEvent.connect(interface.dashboard.dashboardApi.reportAgvLoc) time.sleep(3) ################# unit test ################# def testgetPo
identifier_body
agvCtrl.py
ow%2 != 1: row -= 1 return row*1000+col @lock.lock(g_lock) def checkTimeout(index,agvId,loc): global g_stockLock if index in g_stockLock: if utility.ticks() - g_stockLock[index] > 10*60*1000: unlockStockA(agvId,loc) log.warning("delete timeout locked",index) #解决在StockA两个车头对撞的问题 def lockStockA(agv...
if r
conditional_block
Exam4x2.py
: {self.nombre}\nApellido: {self.apellido}' \ f'\nFecha de Nacimiento: {self.nacimiento}\nPais: {self.pais}' \ f'\nEdad: {self.edad}\nEstatus: {self.estatus}\n ' ListaP = list() def pacientes(): pass def ModStatus(patients): NuevoPaciente = paciente('', '', '', '...
m('cls') nombre =
Principal() genero = input('Opcion Incorrecta') syste
conditional_block
Exam4x2.py
('Ingrese el Nombre: ') break elif opc == 5: Principal() except: system('cls') print('Opcion Invalida') input() Recorrer = 0 while nombre != NuevoPaciente.nombre: try...
le opc != '0': system('cls') print('\033[1:35m ') print('|///////////////////|') print('| COVID-19 |') print('|///////////////////|') print('\033[0:0m ') print('''1) Acerca de Coronavirus 2) Agregar un Paciente 3) Mostrar Todos los Pacientes 4) ...
identifier_body
Exam4x2.py
: {self.nombre}\nApellido: {self.apellido}' \ f'\nFecha de Nacimiento: {self.nacimiento}\nPais: {self.pais}' \ f'\nEdad: {self.edad}\nEstatus: {self.estatus}\n ' ListaP = list() def pacientes(): pass def ModStatus(patients): NuevoPaciente = paciente('', '', '', '...
print('\033[0:0m ') print('''La COVID-19 se caracteriza por síntomas leves, como, secreciones nasales, dolor de garganta, tos y fiebre. La enfermedad puede ser más grave en algunas personas y provocar neumonía o dificultades respiratorias. Más raramente puede ser mortal. Las personas de edad avanzada y la...
print('\033[1:30m ') print('Sintomas:')
random_line_split
Exam4x2.py
(self): system('cls') print('\033[1:31m ') print('|///////////////////|') print('| MOSTRAR PACIENTES |') print('|///////////////////|') print('\033[0:0m ') return f'\nGenero: {self.genero}\nNombre: {self.nombre}\nApellido: {self.apellido}' \ ...
mostrar
identifier_name
Simulated_Image_PD_points.py
(np.vstack((j11[good].T, j22[good].T)).T) a, b, c, d = rect mappa1 = (2.* wam[:, 0] - b - a) / (b - a) mappa2 = (2.* wam[:, 1] - d - c) / (d - c) mappa = np.vstack((mappa1.T, mappa2.T)).T V1 = np.cos(np.multiply(couples[:,0], np.arccos(mappa[:,0].T))) V2 = np.cos(np.multiply(couples[:,1], np.arc...
plt.savefig('%s.eps' %fig_name,bbox_inches='tight') plt.savefig('%s.png' %fig_name,bbox_inches='tight') plt.close() # Load the image matr = scipy.io.loadmat('sm_simulata.mat') Image_large = matr["image_temp"] plot_image(Image_large, 'Simulated_ImageLarge') sx, sy = Image_large.shape lx, rx, ly, ry = 1...
plt.plot(pts[0], pts[1], 'r.')
conditional_block
Simulated_Image_PD_points.py
(n): zn = np.cos(np.linspace(0, 1, n+1)*np.pi) zn1 = np.cos(np.linspace(0, 1, n+2)*np.pi) Pad1, Pad2 = np.meshgrid(zn, zn1) f1 = np.linspace(0, n, n+1) f2 = np.linspace(0, n+1, n+2) M1, M2 = np.meshgrid(f1,f2) h = np.array(np.mod(M1 + M2, 2)) g = np.array(np.concatenate(h.T)) findM ...
_pdpts
identifier_name
Simulated_Image_PD_points.py
# Compute the coefficients for polynomial approximation def _wamfit(deg, wam, pts, fval): both = np.vstack((wam, pts)) rect = [np.min(both[:,0]), np.max(both[:,0]), np.min(both[:,1]), np.max(both[:,1])] Q, R1, R2 = _wamdop(deg, wam, rect) DOP = _wamdopeval(deg, R1, R2, pts, rect) cfs = np...
zn = np.cos(np.linspace(0, 1, n+1)*np.pi) zn1 = np.cos(np.linspace(0, 1, n+2)*np.pi) Pad1, Pad2 = np.meshgrid(zn, zn1) f1 = np.linspace(0, n, n+1) f2 = np.linspace(0, n+1, n+2) M1, M2 = np.meshgrid(f1,f2) h = np.array(np.mod(M1 + M2, 2)) g = np.array(np.concatenate(h.T)) findM = np.argw...
identifier_body
Simulated_Image_PD_points.py
(np.vstack((j11[good].T, j22[good].T)).T) a, b, c, d = rect mappa1 = (2.* wam[:, 0] - b - a) / (b - a) mappa2 = (2.* wam[:, 1] - d - c) / (d - c) mappa = np.vstack((mappa1.T, mappa2.T)).T V1 = np.cos(np.multiply(couples[:,0], np.arccos(mappa[:,0].T))) V2 = np.cos(np.multiply(couples[:,1], np.arc...
# Define the evaluation points X, Y = np.meshgrid(range(n), range(m)); x = X.T.flatten() y = Y.T.flatten() pts = np.vstack((x,y)).T ptsv = np.vstack((np.array(x/(n-1)), np.array(y/(m-1)))).T fvalev = np.array([Image[y[i], x[i]] for i in range(x.shape[0])]) threshold = fvalev > 0 extra_ep = np.zeros(Image.flatten().sha...
MSE_VSDK, MSE_POLY = [], [] PSNR_VSDK, PSNR_POLY = [], []
random_line_split
workerthread.rs
0, steal_fails: 0, sleep_us: 0, first_after: 1}, } } pub fn get_stealer(&self) -> Stealer<Task<Arg,Ret>> { assert!(!self.started); self.stealer.clone() } pub fn add_other_stealer(&mut self, stealer: Stealer<Task<Arg,Ret>>) { assert!(!self.started); self.other_s...
trIter<
identifier_name
workerthread.rs
Sync> { id: usize, started: bool, supervisor_port: Receiver<()>, supervisor_channel: Sender<SupervisorMsg<Arg, Ret>>, deque: Worker<Task<Arg, Ret>>, stealer: Stealer<Task<Arg, Ret>>, other_stealers: Vec<Stealer<Task<Arg, Ret>>>, rng: XorShiftRng, sleepers: Arc<AtomicUsize>, thre...
mem::forget(joinbarrier) // Don't drop if we are not last task }
conditional_block
workerthread.rs
{ assert!(!self.started); self.other_stealers.push(stealer); self.threadcount += 1; } pub fn spawn(mut self) -> thread_scoped::JoinGuard<'a, ()> { assert!(!self.started); self.started = true; unsafe { thread_scoped::scoped(move|| { se...
let ptr = unsafe { Unique::new(self.ptr_0.offset(self.offset)) }; self.offset += 1; Some(ptr) }
identifier_body
workerthread.rs
{Task,JoinBarrier,TaskResult,ResultReceiver,AlgoStyle,ReduceStyle,Algorithm}; use ::poolsupervisor::SupervisorMsg; static STEAL_TRIES_UNTIL_BACKOFF: u32 = 30; static BACKOFF_INC_US: u32 = 10; pub struct WorkerThread<Arg: Send, Ret: Send + Sync> { id: usize, started: bool, supervisor_port: Receiver<()>, ...
/// Try to steal tasks from the other workers. /// Starts at a random worker and tries every worker until a task is stolen or /// every worker has been tried once. fn try_steal(&mut self) -> Option<Task<Arg,Ret>> { let len = self.other_stealers.len(); let start_victim = self.rng.gen_rang...
} }
random_line_split
server.go
: Primary ping view number " + strconv.Itoa(int(args.Viewnum)) + "--> Current viewnum is " + strconv.Itoa(int(vs.currentView.Viewnum))) // fmt.Println("CAODAN ERHAO *(*(*(*(*(*(*(*(") } } else if args.Me == vs.currentView.Backup { // If backup pings // Do nothing. testLog("ACKED = False && BACKUP...
{ vs := new(ViewServer) vs.me = me // Your vs.* initializations here. vs.idle = make([]string, 0) vs.currentView = View{0, "", ""} vs.acked = false vs.pingKeeper = make(map[string]time.Time) // tell net/rpc about our RPC server and handlers. rpcs := rpc.NewServer() rpcs.Register(vs) // prepare to receive c...
identifier_body
server.go
view# " + strconv.Itoa(int(view.Viewnum)) + ", primary: " + view.Primary + ", backup: " + view.Backup + ". " } // // server Ping RPC handler. // func (vs *ViewServer) Ping(args *PingArgs, reply *PingReply) error { vs.viewMu.Lock() if vs.getViewNum() == 0 { // If current view number in ping is 0 // If ping vi...
if vs.currentView.Backup != "" { // fmt.Println("Put backup: ", vs.currentView.Backup, " in") // Turn backup into primary vs.currentView.Primary = vs.currentView.Backup vs.currentView.Backup = "" // Turn idle into backup if len(vs.idle) > 0 { // fmt.Println("TEST #150: ", ...
random_line_split
server.go
view# " + strconv.Itoa(int(view.Viewnum)) + ", primary: " + view.Primary + ", backup: " + view.Backup + ". " } // // server Ping RPC handler. // func (vs *ViewServer) Ping(args *PingArgs, reply *PingReply) error { vs.viewMu.Lock() if vs.getViewNum() == 0 { // If current view number in ping is 0 // If ping vi...
else { // If already has backup // put it into idle // fmt.Println("TEST #600: put", args.Me, " in idle") if !idleContains(vs.idle, args.Me) { vs.idle = append(vs.idle, args.Me) } } } } } // Set up the return view vs.pingKeeper[args.Me] = time.Now() reply.View = vs.currentVi...
{ // If no backup // put ping server into backup and set acked = false // fmt.Println("Before backup added: ", vs.currentView) // fmt.Println("Add backup: ", args.Me) if (idleContains(vs.idle, args.Me)) { vs.currentView.Backup = vs.idle[0] vs.idle = vs.idle[1:] } else { vs....
conditional_block
server.go
(message string) { // Log the put operation into log file. f, err := os.OpenFile("TestLog.txt", os.O_APPEND|os.O_RDWR|os.O_CREATE , 0777) if err != nil { panic(err) } defer f.Close() if _, err = f.WriteString(message + "\n"); err != nil { panic(err) } } func (vs *ViewServer) increaseViewNum() { testLog("...
testLog
identifier_name
listener.go
, batches them and then publishes them to a NATS // subject. type Listener struct { c *config.Config nc *nats.Conn stats *stats.Stats probes probes.Probes batch *batch.Batch wg sync.WaitGroup stop chan struct{} mu sync.Mutex // only used for HTTP listener } // Stop shuts down a running listener...
{ if l.batch.Size() < 1 { return // Nothing to do } l.stats.Inc(statSent) // The goal is for the batch size to never be bigger than what // NATS will accept but there is a small chance that a series of // large incoming chunks could cause the batch to grow beyond the // intended limit. For these cases, use t...
identifier_body
listener.go
2/probes" "github.com/jumptrading/influx-spout/v2/stats" nats "github.com/nats-io/nats.go" ) const ( // Listener stats counters statReceived = "received" statSent = "sent" statReadErrors = "read_errors" statFailedNATSPublish = "failed_nats_publish" // The maximum possible UDP read...
return default: } } } func (l *Listener) setupHTTP() *http.Server { l.wg.Add(1) go l.oldBatchSender() mux := http.NewServeMux() mux.HandleFunc("/write", l.handleHTTPWrite) return &http.Server{ Addr: fmt.Sprintf(":%d", l.c.Port), Handler: mux, } } // oldBatchSender is a goroutine which sends the...
{ // Read deadline is used so that the stop channel can be // periodically checked. sc.SetReadDeadline(time.Now().Add(time.Second)) bytesRead, err := l.batch.ReadOnceFrom(sc) if err != nil && !isTimeout(err) { l.stats.Inc(statReadErrors) } if bytesRead > 0 { if l.c.Debug { log.Printf("listener r...
conditional_block
listener.go
2/probes" "github.com/jumptrading/influx-spout/v2/stats" nats "github.com/nats-io/nats.go" ) const ( // Listener stats counters statReceived = "received" statSent = "sent" statReadErrors = "read_errors" statFailedNATSPublish = "failed_nats_publish" // The maximum possible UDP read...
(r *http.Request) (int64, error) { l.mu.Lock() defer l.mu.Unlock() return l.batch.ReadFrom(r.Body) } func (l *Listener) readHTTPBodyWithPrecision(r *http.Request, precision string) (int, error) { scanner := bufio.NewScanner(r.Body) // scanLines is like bufio.ScanLines but the returned lines // includes the trai...
readHTTPBodyNanos
identifier_name
listener.go
2/probes" "github.com/jumptrading/influx-spout/v2/stats" nats "github.com/nats-io/nats.go" ) const ( // Listener stats counters statReceived = "received" statSent = "sent" statReadErrors = "read_errors" statFailedNATSPublish = "failed_nats_publish" // The maximum possible UDP read...
continue } newLine := applyTimestampPrecision(line, precision) l.mu.Lock() l.batch.Append(newLine) l.mu.Unlock() } return bytesRead, scanner.Err() } func scanLines(data []byte, atEOF bool) (advance int, token []byte, err error) { if atEOF && len(data) == 0 { return 0, nil, nil } if i := bytes.Inde...
random_line_split
messages.go
unmarshal(out interface{}, packet []byte, expectedType uint8) error { if len(packet) == 0 { return ParseError{expectedType} } if packet[0] != expectedType { return UnexpectedMessageError{expectedType, packet[0]} } packet = packet[1:] v := reflect.ValueOf(out).Elem() structType := v.Type() var ok bool for...
{ // A zero is the zero length string }
conditional_block
messages.go
rest"` } // See RFC 4254, section 5.4. type channelRequestSuccessMsg struct { PeersId uint32 } // See RFC 4254, section 5.4. type channelRequestFailureMsg struct { PeersId uint32 } // See RFC 4254, section 5.3 type channelCloseMsg struct { PeersId uint32 } // See RFC 4254, section 5.3 type channelEOFMsg struct {...
parseUint32
identifier_name
messages.go
252, section 5.1 type userAuthFailureMsg struct { Methods []string PartialSuccess bool } // See RFC 4254, section 5.1. type channelOpenMsg struct { ChanType string PeersId uint32 PeersWindow uint32 MaxPacketSize uint32 TypeSpecificData []byte `ssh:"rest"` } // See RFC 4254, sect...
return out } var bigOne = big.NewInt(1) func parseString(in []byte) (out, rest []byte, ok bool) { if len(in) < 4 { return } length := uint32(in[0])<<24 | uint32(in[1])<<16 | uint32(in[2])<<8 | uint32(in[3]) if uint32(len(in)) < 4+length { return } out = in[4 : 4+length] rest = in[4+length:] ok = true re...
random_line_split
messages.go
[0]} } packet = packet[1:] v := reflect.ValueOf(out).Elem() structType := v.Type() var ok bool for i := 0; i < v.NumField(); i++ { field := v.Field(i) t := field.Type() switch t.Kind() { case reflect.Bool: if len(packet) < 1 { return ParseError{expectedType} } field.SetBool(packet[0] != 0) ...
{ length := 4 /* length bytes */ if n.Sign() < 0 { nMinus1 := new(big.Int).Neg(n) nMinus1.Sub(nMinus1, bigOne) bitLen := nMinus1.BitLen() if bitLen%8 == 0 { // The number will need 0xff padding length++ } length += (bitLen + 7) / 8 } else if n.Sign() == 0 { // A zero is the zero length string } ...
identifier_body
siadir.go
UnknownPath is an error when a siadir cannot be found with the given path ErrUnknownPath = errors.New("no siadir known with that path") // ErrUnknownThread is an error when a siadir is trying to be closed by a // thread that is not in the threadMap ErrUnknownThread = errors.New("thread should not be calling Close()...
// Delete removes the directory from disk and marks it as deleted. Once the directory is // deleted, attempting to access the directory will return an error. func (sd *SiaDir) Delete() error { sd.mu.Lock() defer sd.mu.Unlock() return sd.delete() } // Deleted returns the deleted field of the siaDir func (sd *SiaDi...
{ update := sd.createDeleteUpdate() err := sd.createAndApplyTransaction(update) sd.deleted = true return err }
identifier_body
siadir.go
UnknownPath is an error when a siadir cannot be found with the given path ErrUnknownPath = errors.New("no siadir known with that path") // ErrUnknownThread is an error when a siadir is trying to be closed by a // thread that is not in the threadMap ErrUnknownThread = errors.New("thread should not be calling Close()...
(b []byte) (int, error) { return sdr.f.Read(b) } // Stat returns the FileInfo of the underlying file. func (sdr *DirReader) Stat() (os.FileInfo, error) { return sdr.f.Stat() } // New creates a new directory in the renter directory and makes sure there is a // metadata file in the directory and creates one as needed...
Read
identifier_name
siadir.go
that path") // ErrUnknownThread is an error when a siadir is trying to be closed by a // thread that is not in the threadMap ErrUnknownThread = errors.New("thread should not be calling Close(), does not have control of the siadir") ) type ( // SiaDir contains the metadata information about a renter directory Sia...
{ sd.mu.Unlock() return nil, errors.New("can't copy deleted SiaDir") }
conditional_block
siadir.go
ErrUnknownThread = errors.New("thread should not be calling Close(), does not have control of the siadir") ) type ( // SiaDir contains the metadata information about a renter directory SiaDir struct { metadata Metadata // siaPath is the path to the siadir on the sia network siaPath modules.SiaPath // roo...
} // Open file. path := sd.siaPath.SiaDirMetadataSysPath(sd.rootDir) f, err := os.Open(path) if err != nil {
random_line_split
fpdf.go
{0xDD, 0x2F, 0x00}, // DD2F00 {0xE1, 0x00, 0x06}, // E10006 {0xE5, 0x00, 0x3F}, // E5003F */ {0x00, 0xBF, 0xA9}, // 00BFA9 {0x00, 0xC2, 0x66}, // 00C266 {0x00, 0xC5, 0x21}, // 00C521 {0x25, 0xC9, 0x00}, // 25C900 {0x6F, 0xCC, 0x00}, // 6FCC00 {0xBB, 0xD0, 0x00}, // BBD000 {0xD3, 0x9D, 0x00}, // D39...
// }}} // {{{ altitudeToY, distNMToX func altitudeToY(alt float64) float64 { distY := (alt/ApproachHeightFeet) * ApproachBoxHeight y := ApproachBoxHeight - distY // In PDF, the Y scale goes down the page return y + ApproachBoxOffsetY } func distNMToX(distNM float64) float64 { distX := (distNM/ApproachWidthNM) * ...
{ f := delta / 4.0 // How many 5knot increments this delta is f += 3.0 // [0,1,2] are braking, [3] is nochange, [4,5,6] are accelerating i := int(f) if i<0 { i = 0 } if i>6 { i = 6 } rgbw := DeltaGradientColors[i] fAbs := math.Abs(delta/4.0) widthPercent := int (fAbs * 0.33 * 100) if widthPercent ...
identifier_body
fpdf.go
+ApproachBoxHeight) pdf.LineTo(ApproachBoxOffsetX, ApproachBoxOffsetY+ApproachBoxHeight) pdf.LineTo(ApproachBoxOffsetX, ApproachBoxOffsetY) pdf.DrawPath("D") // X axis tickmarks and labels pdf.SetLineWidth(0.05) pdf.SetFont("Arial", "", 8) for _,nm := range []float64{10,20,30,...
random_line_split
fpdf.go
OffsetY + 10) pdf.Cell(40, 10, title) } // }}} // {{{ DrawApproachFrame func DrawApproachFrame(pdf *gofpdf.Fpdf) { pdf.SetLineWidth(0.05) pdf.SetDrawColor(0xa0, 0xa0, 0xa0) pdf.MoveTo(ApproachBoxOffsetX, ApproachBoxOffsetY) pdf.LineTo(ApproachBoxOffsetX+ApproachBoxWidth, ApproachBoxOffsetY) pdf...
NewApproachPdf
identifier_name
fpdf.go
aking: by >8 knots within 5s", "braking: by 4-8 knots within 5s", "braking: by 0-4 knots within 5s", "no change", "accelerating: by 0-4 knots within 5s", "accelerating: by 4-8 knots within 5s", "accelerating: by >8 knots within 5s", } for i,rgb := range DeltaGradientColors { x,y := ApproachBoxOffsetX...
{ continue }
conditional_block
auth.go
byte(secretSalt), } } /******************************************************************************* * Compute a salted hash of the specified clear text password. The hash is suitable * for storage and later use for validation of input passwords, using the * companion function PasswordHashIsValid. Thus, the hash...
action = i } } if action == -1 {
{ return false, utilities.ConstructUserError("More than one field set in action mask") }
conditional_block
auth.go
...") var sessionId = getSessionIdFromCookie(httpReq) if sessionId != "" { fmt.Println("obtained session id:", sessionId) sessionToken = authSvc.identifySession(sessionId) // returns nil if invalid } return sessionToken } /******************************************************************************* * ...
{ var parts []string = strings.Split(sessionId, ":") if len(parts) != 2 { fmt.Println("Ill-formatted sessionId:", sessionId) return false } var uniqueNonRandomValue string = parts[0] var untrustedHash string = parts[1] var empty = []byte{} var actualSaltedHashBytes []byte = authSvc.computeHash(uniqueNonR...
identifier_body
auth.go
[]byte(secretSalt), } } /******************************************************************************* * Compute a salted hash of the specified clear text password. The hash is suitable * for storage and later use for validation of input passwords, using the * companion function PasswordHashIsValid. Thus, the h...
if user.getId() == resourceId { return true, nil } // Verify that at most one field of the actionMask is true. var nTrue = 0 for _, b := range actionMask { if b { if nTrue == 1 { return false, utilities.ConstructUserError("More than one field in mask may not be true") } nTrue++ } } // Check if...
} // Special case: Allow user all capabilities for their own user object.
random_line_split
auth.go
byte(secretSalt), } } /******************************************************************************* * Compute a salted hash of the specified clear text password. The hash is suitable * for storage and later use for validation of input passwords, using the * companion function PasswordHashIsValid. Thus, the hash...
(pswd string) []byte { var h []byte = authSvc.computeHash(pswd).Sum([]byte{}) return h } /******************************************************************************* * Validate session Id: return true if valid, false otherwise. Thus, a return * of true indicates that the sessionId is recognized as having bee...
CreatePasswordHash
identifier_name
_typecheck.py
"AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Minimal runtime type checking library. T...
def _replace_forward_references(t, context): """Replace forward references in the given type.""" if isinstance(t, str): return context[t] elif isinstance(t, Type): return type(t)(*[_replace_forward_references(t, context) for t in t._types]) # pylint: disable=protected-access else: return t def...
"""A typed dict. A correct type has the correct parametric types for keys and values. """ def __instancecheck__(self, instance): return (isinstance(instance, dict) and super(Dict, self).__instancecheck__(instance))
identifier_body