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
ahrs_serv.py
(): global ahrs global gyro_addr ahrs.write_byte_data(gyro_addr,0x20,0x8F) #DataRate 400Hz, BW 20Hz, All Axis enabled, Gyro ON ahrs.write_byte_data(gyro_addr,0x23,0xA0) #Escala 2000dps, BlockUpdates ahrs.write_byte_data(gyro_addr,0x24,0x02) #OutSel = 10h, use HPF and LPF2, HP...
gyro_setup
identifier_name
a1.py
) loop_end = time.time() np_start = time.time() B2 = A + (A@(A+(A@A))) np_end = time.time() print("Magnitude of B1-B2: " + str(np.linalg.norm(B1-B2, 2))) print("Execution time for naive iterative method with N = " + str(N) + " is " + str(loop_end - loop_start)) print("Execution time for vectorized method ...
def plot_data(X,T,elevation=30,azimuth=30): colors = np.array(['r','b']) # red for class 0 , blue for class 1 fig = plt.figure() ax = fig.add_subplot(111, projection='3d') colors = np.array(['r','b']) # red for class 0 , blue for class 1 X = X.T ax.scatter(X[0],X[1],X[2],color=colors[T]...
X = X.T xmin = np.min(X[0]) xmax = np.max(X[0]) zmin = np.min(X[2]) zmax = np.max(X[2]) x = np.linspace(xmin,xmax,2) z = np.linspace(zmin,zmax,2) xx,zz = np.meshgrid(x,z) yy = -(xx*w[0] + zz*w[2] + w0)/w[1] return xx,yy,zz
identifier_body
a1.py
) loop_end = time.time() np_start = time.time() B2 = A + (A@(A+(A@A))) np_end = time.time() print("Magnitude of B1-B2: " + str(np.linalg.norm(B1-B2, 2))) print("Execution time for naive iterative method with N = " + str(N) + " is " + str(loop_end - loop_start)) print("Execution time for vectorized method ...
def plot_data(X,T,elevation=30,azimuth=30): colors = np.array(['r','b']) # red for class 0 , blue for class 1 fig = plt.figure() ax = fig.add_subplot(111, projection='3d') colors = np.array(['r','b']) # red for class 0 , blue for class 1 X = X.T ax.scatter(X[0],X[1],X[2],color=colors[T],...
random_line_split
a1.py
# find A*(A + A*A) final = mat_mul(A,final) # find A + (A*(A + A*A)) for i in range(A.shape[0]): for j in range(A.shape[1]): final[i,j] += A[i,j] return final # Q2(b) def timing(N): A = np.random.rand(N,N) loop_start = time.time() B1 = matrix_poly(A) loop_end = time.time() np_start = ti...
final[i,j] += A[i,j]
conditional_block
a1.py
) loop_end = time.time() np_start = time.time() B2 = A + (A@(A+(A@A))) np_end = time.time() print("Magnitude of B1-B2: " + str(np.linalg.norm(B1-B2, 2))) print("Execution time for naive iterative method with N = " + str(N) + " is " + str(loop_end - loop_start)) print("Execution time for vectorized method ...
(x,t,w): # logistic-cross-entropy return (t@np.logaddexp(0,-z(x,w))+(1-t)@np.logaddexp(0,z(x,w)))/t.shape[0] train_CE = [] test_CE = [] train_acc = [] test_acc = [] E0 = E(unbiased_train,Ttrain,w0) E1 = 1 # Q5(d). while abs(E0-E1) >= np.float64(10**-10): # for i in range(200): E0 = E1 ...
E
identifier_name
validation.go
func recurseValidationCode(att *expr.AttributeExpr, put expr.UserType, attCtx *AttributeContext, req, alias bool, target, context string, seen map[string]*bytes.Buffer) *bytes.Buffer { var ( buf = new(bytes.Buffer) first = true ut, isUT = att.Type.(expr.UserType) ) // Break infinite recursions if i...
{ seen := make(map[string]*bytes.Buffer) return recurseValidationCode(att, put, attCtx, req, alias, target, target, seen).String() }
identifier_body
validation.go
attCtx, req, alias, target, context) if validation != "" { buf.WriteString(validation) first = false } // Recurse down depending on attribute type. switch { case expr.IsObject(att.Type): if isUT { put = ut } for _, nat := range *(expr.AsObject(att.Type)) { tgt := fmt.Sprintf("%s.%s", target, attC...
if format := validation.Format; format != "" { data["format"] = string(format) if val := runTemplate(formatValT, data); val != "" { res = append(res, val) } } if pattern := validation.Pattern; pattern != "" { data["pattern"] = pattern if val := runTemplate(patternValT, data); val != "" { res = appen...
{ data["values"] = values if val := runTemplate(enumValT, data); val != "" { res = append(res, val) } }
conditional_block
validation.go
attCtx, req, alias, target, context) if validation != "" { buf.WriteString(validation) first = false } // Recurse down depending on attribute type. switch { case expr.IsObject(att.Type): if isUT { put = ut } for _, nat := range *(expr.AsObject(att.Type)) { tgt := fmt.Sprintf("%s.%s", target, attC...
(att *expr.AttributeExpr, attCtx *AttributeContext, req, alias bool, target, context string) string { validation := att.Validation if ut, ok := att.Type.(expr.UserType); ok { val := ut.Attribute().Validation if val != nil { if validation == nil { validation = val } else { validation.Merge(val) } ...
validationCode
identifier_name
validation.go
attCtx, req, alias, target, context) if validation != "" { buf.WriteString(validation) first = false } // Recurse down depending on attribute type. switch { case expr.IsObject(att.Type): if isUT { put = ut } for _, nat := range *(expr.AsObject(att.Type)) { tgt := fmt.Sprintf("%s.%s", target, attC...
panic(err) // bug } } case expr.IsUnion(att.Type): // NOTE: the only time we validate a union is when we are // validating a proto-generated type since the HTTP // serialization transforms unions into objects. u := expr.AsUnion(att.Type) tref := attCtx.Scope.Ref(&expr.AttributeExpr{Type: put}, attCt...
random_line_split
mod.rs
#[inline] /// Gets relevance for ERR fn get_relevance(score: f32, score_max: f32) -> f32 { (2f32.powf(score) - 1.) / 2f32.powf(score_max) } /// Computes ERR. Assumes scores are sorted pub fn get_err(scores: &[f32], k_opt: Option<usize>) -> f32 { let k = k_opt.unwrap_or(scores.len()).min(scores.len()); le...
{ let size = k.unwrap_or(scores.len()).min(scores.len()); let r_dcg = dcg(scores, size); // Sort them in ascending order scores.sort_by_key(|v| FloatOrd(-*v)); let idcg = dcg(scores, size); if idcg > 0.0 { r_dcg / idcg } else { 0.0 } }
identifier_body
mod.rs
data = [1., 2., 6.]; assert_eq!(get_mean(&data, None), 3.); assert_eq!(get_mean(&data, Some(2)), 1.5); assert_eq!(get_mean(&data, Some(10)), 3.); } #[test] fn test_ndcg() { let mut t1 = vec![4., 0., 2., 1., 2.]; assert!((ndcg(&mut t1.clone(), None) - 0.96110010).abs...
test_get_percentiles
identifier_name
mod.rs
() { *val /= num_examples as f32; } weights } /// Gets the subtopics. Run this once /// # Arguments /// /// * data: Data to get subtopics from /// * field_name: field containing the topic /// * discretize_fn specifies the name of the bucket and how to handle missing data. pub fn get_subtopics<F>(data:...
left * (1. - delta) + right * delta } } /// Compute a set of percentiles and average them pub fn get_percentiles( vals: &mut [f32], percentiles: &[usize], interpolate_arg_opt: Option<f32>, ) -> f32 { // Can happen at test time if vals.is_empty() { std::f32::NAN } else { ...
let right = vals[pos.ceil() as usize]; let delta = pos.fract();
random_line_split
mod.rs
for topic in subtopics.iter() { let counter = weights.entry(*topic).or_insert(0.); *counter += 1.; } for (_, val) in weights.iter_mut() { *val /= num_examples as f32; } weights } /// Gets the subtopics. Run this once /// # Arguments /// /// * data: Data to get subtopics f...
{ return weights; }
conditional_block
imager_prepare.py
Map, MultiDataMap class imager_prepare(BaseRecipe, RemoteCommandRecipeMixIn): """ Prepare phase master: 1. Validate input 2. Create mapfiles with input for work to be perform on the individual nodes based on the structured input mapfile. The input mapfile contains a list of measurement ...
# outputs output_ms_mapfile_path = self.inputs['mapfile'] # ********************************************************************* # schedule the actual work # TODO: Refactor this function into: load data, perform work, # create output node_command = " python %...
return 1
conditional_block
imager_prepare.py
Map, MultiDataMap class imager_prepare(BaseRecipe, RemoteCommandRecipeMixIn):
**Arguments:** """ inputs = { 'ndppp_exec': ingredient.ExecField( '--ndppp-exec', help="The full path to the ndppp executable" ), 'parset': ingredient.FileField( '-p', '--parset', help="The full path to a prepare parset" ), ...
""" Prepare phase master: 1. Validate input 2. Create mapfiles with input for work to be perform on the individual nodes based on the structured input mapfile. The input mapfile contains a list of measurement sets. Each node computes a single subband group but needs this for all ...
identifier_body
imager_prepare.py
Map, MultiDataMap class imager_prepare(BaseRecipe, RemoteCommandRecipeMixIn): """ Prepare phase master: 1. Validate input 2. Create mapfiles with input for work to be perform on the individual nodes based on the structured input mapfile. The input mapfile contains a list of measurement ...
'--subbands-per-image', help="The number of subbands to be collected in each output image" ), 'asciistat_executable': ingredient.ExecField( '--asciistat-executable', help="full path to the ascii stat executable" ), 'statplot_executable': in...
), 'subbands_per_image': ingredient.IntField(
random_line_split
imager_prepare.py
this for all timeslices. 3. Call the node scripts with correct input 4. validate performance Only output the measurement nodes that finished succesfull **Command Line arguments:** The only command line argument is the a to a mapfile containing "all" the measurement sets needed for ...
_validate_input_map
identifier_name
room.go
Landlord(nil) r.setLandlordPlayCardCount(0) r.setFarmerPlayCardCount(0) for _, user := range r.getUsers() { if user != nil { user.resume() } } r.users_cards = make(map[string]string, pcount) } //设置房间的基础信息 func (r *Room) setRoomBaseInfo() { allRoomData := *r.getAllRoomData() arrAllRoomData := strings.Spli...
ltiple := r.getBaseCardsInfo() userids := []string{} addToCards := 0 if user == nil { //只执行一次(地主出现的时候) //根据底牌加倍 if multiple > 1 { r.setMultiple(r.getMultiple() * multiple) r.pushMultiple() } userids = r.getUserIDs() addToCards = 1 } else { //短线重连进来的 userids = []string{*user.getUserID()} } messag...
r.getBaseCards() cardsType, mu
identifier_body
room.go
nil { pushMessageToUsers("BaseCards_Push", []string{message}, userids) r.pushJudgment("BaseCards_Push", message) } else { pushMessageToUsers("BaseCards_Push", []string{message}, userids) } } //将底牌放入地主牌面中 func (r *Room) addCardsToLandlord() { cards := r.getBaseCards() landlord := r.getLandlord() if landlord...
r.userids = nil
identifier_name
room.go
赛制(0常规赛 1加倍赛) */ func (r *Room) setCanHandleUser(canHandleUser *User, handleType int) { r.canHandleUser = canHandleUser message := fmt.Sprintf("%s,%d,%d,%d", *canHandleUser.getUserID(), handleType, r.getBaseScore(), r.getGameType()) pushMessageToUsers("Handle_Push", []string{message}, r.getUserIDs()) r.pushJudgment...
hMessageToUsers("Multiple_Push", []str
conditional_block
room.go
.setLandlord(nil) r.setLandlordPlayCardCount(0) r.setFarmerPlayCardCount(0) for _, user := range r.getUsers() { if user != nil { user.resume() } } r.users_cards = make(map[string]string, pcount) } //设置房间的基础信息 func (r *Room) setRoomBaseInfo() { allRoomData := *r.getAllRoomData() arrAllRoomData := strings....
/* 获取牌的类型(-1不是特殊底牌 0豹子 1同花 2顺子 3王炸 4同花顺) */ func (r *Room) getBaseCardsInfo() (cardsType int, multiple int) { cardsType = -1 multiple = 1 var
landlord.setCards(tmpCards) } }
random_line_split
workload_placement_nodelabel.go
, err := makePaddingPod(fxt.Namespace.Name, podName, zone, zoneRes) Expect(err).NotTo(HaveOccurred(), "unable to create padding pod %q on zone %q", podName, zone.Name) padPod, err = pinPodTo(padPod, nodeName, zone.Name) Expect(err).NotTo(HaveOccurred(), "unable to pin pod %q to zone %q", podName, zone.N...
nodesUnlabeled = true
random_line_split
workload_placement_nodelabel.go
map[string]string{ labelName: labelValueMedium, } err = fxt.Client.Create(context.TODO(), pod) Expect(err).NotTo(HaveOccurred(), "unable to create pod %q", pod.Name) By("waiting for pod to be running") updatedPod, err := e2ewait.ForPodPhase(fxt.Client, pod.Namespace, pod.Name, corev1.PodRunning, 1...
createNodeAffinityPreferredDuringSchedulingIgnoredDuringExecution
identifier_name
workload_placement_nodelabel.go
].Resources.Limits = requiredRes pod.Spec.NodeSelector = map[string]string{ labelName: labelValueMedium, } err = fxt.Client.Create(context.TODO(), pod) Expect(err).NotTo(HaveOccurred(), "unable to create pod %q", pod.Name) By("waiting for pod to be running") updatedPod, err := e2ewait.ForPodPhas...
{ nodeSelReq := &corev1.NodeSelectorRequirement{ Key: labelName, Operator: selectOperator, Values: labelValue, } nodeSelTerm := &corev1.NodeSelectorTerm{ MatchExpressions: []corev1.NodeSelectorRequirement{*nodeSelReq}, MatchFields: []corev1.NodeSelectorRequirement{}, } aff := &corev1.Affini...
identifier_body
workload_placement_nodelabel.go
, zone.Name) paddingPods = append(paddingPods, padPod) } } By("Waiting for padding pods to be ready") failedPodIds := e2ewait.ForPaddingPodsRunning(fxt, paddingPods) Expect(failedPodIds).To(BeEmpty(), "some padding pods have failed to run") var err error targetNodeNRTInitial, err = e2enrt.F...
{ nodesUnlabeled = false klog.Errorf("Error while trying to unlabel node %q. %v", alternativeNodeName, err) }
conditional_block
pix2pix_GAN.py
leaky relu activation g = LeakyReLU(alpha=0.2)(g) return g # define a decoder block def decoder_block(layer_in, skip_in, n_filters, dropout=True): # weight initialization init = RandomNormal(stddev=0.02) # add upsampling layer g = Conv2DTranspose(n_filters, (4,4), strides=(2,2), padding='same', kernel_initiali...
(image_shape=(128,128,4)): # weight initialization init = RandomNormal(stddev=0.02) # image input in_image = Input(shape=image_shape) # encoder model: C64-C128-C256-C512-C512-C512-C512-C512 e1 = define_encoder_block(in_image, 64, batchnorm=False) e2 = define_encoder_block(e1, 128) e3 = define_encoder_block(e2, ...
define_generator
identifier_name
pix2pix_GAN.py
# leaky relu activation g = LeakyReLU(alpha=0.2)(g) return g # define a decoder block def decoder_block(layer_in, skip_in, n_filters, dropout=True): # weight initialization init = RandomNormal(stddev=0.02) # add upsampling layer g = Conv2DTranspose(n_filters, (4,4), strides=(2,2), padding='same', kernel_initial...
d5 = decoder_block(d4, e3, 256, dropout=False) d6 = decoder_block(d5, e2, 128, dropout=False) d7 = decoder_block(d6, e1, 64, dropout=False) # output g = Conv2DTranspose(4, (4,4), strides=(2,2), padding='same', kernel_initializer=init)(d7) out_image = Activation('tanh')(g) # define model model = Model(in_image, ...
# decoder model: CD512-CD1024-CD1024-C1024-C1024-C512-C256-C128 # d1 = decoder_block(b, e7, 512) d2 = decoder_block(b, e6, 512) d3 = decoder_block(d2, e5, 512) d4 = decoder_block(d3, e4, 512, dropout=False)
random_line_split
pix2pix_GAN.py
8): # size = imgs.shape[0] # print("size is : ", size) # for i in range(size): # im = imgs[i] # for j in range(im_size): # for k in range(im_size): # pixel = im[j][k] # # remove the obstacles # if(pixel[1]>80 and pixel[0]<40 and pi...
img = Image.open(p).convert('L')
conditional_block
pix2pix_GAN.py
leaky relu activation g = LeakyReLU(alpha=0.2)(g) return g # define a decoder block def decoder_block(layer_in, skip_in, n_filters, dropout=True): # weight initialization init = RandomNormal(stddev=0.02) # add upsampling layer g = Conv2DTranspose(n_filters, (4,4), strides=(2,2), padding='same', kernel_initiali...
# # extracts path images. Its given a batch of color images with obstacles and paths # # implement a thresholding method to extract only the path i.e. remove the obstacles # def extract_path_image(imgs, im_size = 128): # size = imgs.shape[0] # print("size is : ", size) # for i in range(size): # ...
X = g_model.predict(samples) # create 'fake' class labels (0) y = np.zeros((len(X), patch_shape, patch_shape, 1)) return X, y
identifier_body
utils.rs
_data = w_1 comma w_2 ... pub fn load_raw_obj_from_file<K, ParseErr>(path: &Path) -> Result<BTreeMap<Height, Vec<Object<K>>>> where K: Num + FromStr<Err = ParseErr>, ParseErr: StdError + Sync + Send + 'static, { let mut reader = BufReader::new(File::open(path)?); let mut buf = String::new(); reader....
(path: &Path) -> PathBuf { path.join("pk") } } pub fn init_tracing_subscriber(directives: &str) -> Result<()> { let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(directives)); tracing_subscriber::fmt() .with_env_filter(filter) .try_init() .map_...
pk_path
identifier_name
utils.rs
} } }; } pub fn load_query_param_from_file(path: &Path) -> Result<Vec<QueryParam<u32>>> { let data = fs::read_to_string(path)?; let query_params: Vec<QueryParam<u32>> = serde_json::from_str(&data)?; Ok(query_params) } // input format: block_id sep [ v_data ] sep { w_data } // sep =...
static ID_CNT: AtomicU16 = AtomicU16::new(0); Self(ID_CNT.fetch_add(1, Ordering::SeqCst))
random_line_split
utils.rs
_data = w_1 comma w_2 ... pub fn load_raw_obj_from_file<K, ParseErr>(path: &Path) -> Result<BTreeMap<Height, Vec<Object<K>>>> where K: Num + FromStr<Err = ParseErr>, ParseErr: StdError + Sync + Send + 'static, { let mut reader = BufReader::new(File::open(path)?); let mut buf = String::new(); reader....
fn sk_path(path: &Path) -> PathBuf { path.join("sk") } fn pk_path(path: &Path) -> PathBuf { path.join("pk") } } pub fn init_tracing_subscriber(directives: &str) -> Result<()> { let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(directives)); trac...
{ let path = path.as_ref(); let sk_file = File::open(Self::sk_path(path))?; let sk_reader = BufReader::new(sk_file); let sk: AccSecretKey = bincode::deserialize_from(sk_reader)?; let pk_file = File::open(Self::pk_path(path))?; let pk_data = unsafe { Mmap::map(&pk_file) }?...
identifier_body
utils.rs
_data = w_1 comma w_2 ... pub fn load_raw_obj_from_file<K, ParseErr>(path: &Path) -> Result<BTreeMap<Height, Vec<Object<K>>>> where K: Num + FromStr<Err = ParseErr>, ParseErr: StdError + Sync + Send + 'static, { let mut reader = BufReader::new(File::open(path)?); let mut buf = String::new(); reader....
let mut split_str = line.splitn(3, |c| c == '[' || c == ']'); let blk_height: Height = Height( split_str .next() .with_context(|| format!("failed to parse line {}", line))? .trim() .parse()?, ); let v_data: Vec<...
{ continue; }
conditional_block
huffman.rs
::new(io::ErrorKind::UnexpectedEof, "Incomplete Huffman code"))); } Ok(code.value) } fn find_long_code(&self, bits: u32, len: usize) -> Result<CodeValue> { // TODO: Use binary search here. self.long_codes.iter() .filter(|lc| lc.len <= len && ...
}; if is_long_code { let lc = LongCode { sort_key: code_straight, code: code.code, value: value.value, len: len, }; self.long_codes.push(lc); } Ok(()) } pub fn build(mut self) ...
{ let code_straight = try!(self.next_code(len)); let code = code_straight.reverse_bits() >> (32 - len); let code = Code { code: code, len: len }; let value = CodeValue { value: value, len: len, }; let is_long_code = if !self.lookup_table.is_empty(...
identifier_body
huffman.rs
_reader(bits: &str) -> BitReader<Cursor<Vec<u8>>> { let mut buf = Vec::new(); let mut byte = 0; let mut bit_pos = 0; for c in bits.chars() { match c { '0' => {}, '1' => byte |= 1 << bit_pos, _ => continue, } ...
random_line_split
huffman.rs
new(io::ErrorKind::UnexpectedEof, "Incomplete Huffman code"))); } Ok(code.value) } fn find_long_code(&self, bits: u32, len: usize) -> Result<CodeValue> { // TODO: Use binary search here. self.long_codes.iter() .filter(|lc| lc.len <= len && ...
{ lookup_table: LookupTable, long_codes: Vec<LongCode>, /// Current lowest codes for each code length (length 1 is at index 0). cur_codes: [Option<u32>; 31], max_code_len: usize, } impl HuffmanDecoderBuilder { pub fn create_code(&mut self, value: u32, len: usize) -> Result<()> { let co...
HuffmanDecoderBuilder
identifier_name
huffman.rs
Ok(code.value) } fn find_long_code(&self, bits: u32, len: usize) -> Result<CodeValue> { // TODO: Use binary search here. self.long_codes.iter() .filter(|lc| lc.len <= len && lc.code.ls_bits(lc.len) == bits.ls_bits(lc.len)) .next() ...
{ return Err(Error::Io(io::Error::new(io::ErrorKind::UnexpectedEof, "Incomplete Huffman code"))); }
conditional_block
audio_feature.py
self.n_fft = n_fft self.hop_length = hop_length def frame_to_second(self, frame, sr=16000): return (frame * self.hop_length + self.n_fft / 2) / sr def second_to_frame(self, second, sr=16000): return (second * sr - (self.n_fft/2)) / self.hop_length if second > 0 else 0 def get_aud...
zero_num = 0 word = 0 for v in l: if v >= -1 and v <= 1: zero_num += 1 plus = int((v + 32)/value)
#量化
conditional_block
audio_feature.py
self.n_fft = n_fft self.hop_length = hop_length def frame_to_second(self, frame, sr=16000): return (frame * self.hop_length + self.n_fft / 2) / sr def second_to_frame(self, second, sr=16000): return (second * sr - (self.n_fft/2)) / self.hop_length if second > 0 else 0 def get_aud...
paired_df_peak_locations, n_pairs = self._query_dataframe_for_peaks_in_target_zone_binary_search( df_peak_locations, peak_locations_t_sort, peak_locations_f_sort, zone_freq_end, zone_freq_start, zone_time_end, zone_time_start) avg_n_pairs_per_peak += n_pairs ...
zone_t_size)
random_line_split
audio_feature.py
.n_fft = n_fft self.hop_length = hop_length def frame_to_second(self, frame, sr=16000): return (frame * self.hop_length + self.n_fft / 2) / sr def second_to_frame(self, second, sr=16000): return (second * sr - (self.n_fft/2)) / self.hop_length if second > 0 else 0 def get_audio_fe...
def _combine_parts_into_key(self, peak_f, second_peak_f, time_delta): peak_f = np.uint32(peak_f) second_peak_f = np.uint32(second_peak_f) time_delta = np.uint32(time_delta) first_part = np.left_shift(peak_f, np.uint32(20)) second_part = np.left_shift(second_peak_f, np.uint3...
'right') if isinstance(start, np.ndarray): start = start[0] if isinstance(end, np.ndarray): end = end[0] t_index = peak_locations_t.index[start:end] f_start = peak_locations_f.searchsorted(zone_freq_start, side='left') f_end = peak_locations_f.searchsorte...
identifier_body
audio_feature.py
.n_fft = n_fft self.hop_length = hop_length def frame_to_second(self, frame, sr=16000): return (frame * self.hop_length + self.n_fft / 2) / sr def second_to_frame(self, second, sr=16000): return (second * sr - (self.n_fft/2)) / self.hop_length if second > 0 else 0 def get_audio_fe...
if feature_type == FeatureType.FEATURE_MFCC: return self.get_mfcc_quantify(audio_data, audio_sr) elif feature_type == FeatureType.FEATURE_FINGERS: return self.get_fingerprints(audio_data, audio_sr) def get_fingerprints(self, audio_data, audio_sr=16000): '''音频指纹特征 ...
ature_type):
identifier_name
Experiments.py
@abstractmethod def evaluate(self, prediction_fn): """ This function should compute all relevant metrics to the task, prediction_fn: (inp) -> (pred): it's an end-to-end prediction function from any model. returns: dict: metrics """ pass ...
""" task_data: [(str, str)]: input/target pairs for translation evaluation. """ self.task_data = task_data
identifier_body
Experiments.py
_translate) {'BLEU': 1.4384882092392364e-09} """ super().__init__(task_data) self.src_splitter = src_splitter self.tgt_splitter = tgt_splitter def evaluate(self, prediction_fn, save_dir=None, save_name="translation_eval.txt", batched=None): """ ...
eval_results[q_id][metric] = float(score) for sample in samples: if sample['q_id'] not in eval_results: print(f"q_rel missing for q_id {sample['q_id']}. No scores added to sample") continue sample.update(eval_results[sampl...
eval_results[q_id] = {}
conditional_block
Experiments.py
_translate) {'BLEU': 1.4384882092392364e-09} """ super().__init__(task_data) self.src_splitter = src_splitter self.tgt_splitter = tgt_splitter def evaluate(self, prediction_fn, save_dir=None, save_name="translation_eval.txt", batched=None): """ ...
eval_results[q_id] = {} eval_results[q_id][metric] = float(score) for sample in samples: if sample['q_id'] not in eval_results: print(f"q_rel missing for q_id {sample['q_id']}. No scores added to sample") continue ...
for row in eval_f: if not any([metric in row for metric in self.relevant_metrics]): continue metric, q_id, score = row.split() if q_id not in eval_results:
random_line_split
Experiments.py
(self, path): """ Saves the entire object ready to be loaded. """ torch.save(self, path) def load(path): """ STATIC METHOD accessed through class, loads a pre-existing experiment. """ return torch.load(path) class Translation...
save
identifier_name
mod.rs
use k8s_openapi::api::core::v1::Pod; use serde::{Deserialize, Serialize}; use std::path::PathBuf; use std::time::Duration; mod k8s_paths_provider; mod lifecycle; mod parser; mod partial_events_merger; mod path_helpers; mod pod_metadata_annotator; mod transform_utils; mod util; use k8s_paths_provider::K8sPathsProvider...
{ let mut event = Event::from(line); // Add source type. event .as_mut_log() .insert(event::log_schema().source_type_key(), COMPONENT_NAME); // Add file. event.as_mut_log().insert(FILE_KEY, file); event }
identifier_body
mod.rs
, Event}; use crate::internal_events::{KubernetesLogsEventAnnotationFailed, KubernetesLogsEventReceived}; use crate::kubernetes as k8s; use crate::{ dns::Resolver, shutdown::ShutdownSignal, sources, topology::config::{DataType, GlobalOptions, SourceConfig, SourceDescription}, transforms::Transform, ...
<O>(self, out: O, global_shutdown: ShutdownSignal) -> crate::Result<()> where O: Sink<Event> + Send + 'static, <O as Sink<Event>>::Error: std::error::Error, { let Self { client, self_node_name, data_dir, auto_partial_merge, fiel...
run
identifier_name
mod.rs
, Event}; use crate::internal_events::{KubernetesLogsEventAnnotationFailed, KubernetesLogsEventReceived}; use crate::kubernetes as k8s; use crate::{ dns::Resolver, shutdown::ShutdownSignal, sources, topology::config::{DataType, GlobalOptions, SourceConfig, SourceDescription}, transforms::Transform, ...
emit!(KubernetesLogsEventAnnotationFailed { event: &event }); } event }); let events = events .filter_map(move |event| futures::future::ready(parser.transform(event))) .filter_map(move |event| { futures::future::ready(partia...
if annotator.annotate(&mut event, &file).is_none() {
random_line_split
PacketDownloader.py
from oauth2client import tools from oauth2client import file from googleapiclient import errors UPDATE_INTERVAL = 5 # seconds NEW_LABEL_ID = None # Gmail label ID of 'new' label # command line arguments try: import argparse parser = argparse.ArgumentParser(parents=[tools.argparser]) parser.add_a...
(service, user_id, msg_id, msg_labels): try: message = service.users().messages().modify(userId=user_id, id=msg_id, body=msg_labels).execute() label_ids = message['labelIds'] return message except errors.HttpError, error: print('An error occurred: %s...
ModifyMessage
identifier_name
PacketDownloader.py
from oauth2client import tools from oauth2client import file from googleapiclient import errors UPDATE_INTERVAL = 5 # seconds NEW_LABEL_ID = None # Gmail label ID of 'new' label # command line arguments try: import argparse parser = argparse.ArgumentParser(parents=[tools.argparser]) parser.add_a...
# set which labels to add/remove def CreateMsgLabels(new_label_id, label_id): return {'removeLabelIds': [new_label_id], 'addLabelIds': [label_id]} # use to find label ID of 'new' label (only used on initial run for each new Gmail account) def ListLabels(service, user_id): try: response = service.users().la...
try: message = service.users().messages().modify(userId=user_id, id=msg_id, body=msg_labels).execute() label_ids = message['labelIds'] return message except errors.HttpError, error: print('An error occurred: %s' % error)
identifier_body
PacketDownloader.py
from oauth2client import tools from oauth2client import file from googleapiclient import errors UPDATE_INTERVAL = 5 # seconds NEW_LABEL_ID = None # Gmail label ID of 'new' label # command line arguments try: import argparse parser = argparse.ArgumentParser(parents=[tools.argparser]) parser.add_a...
else: localtime = time.asctime(time.localtime(time.time())) print(localtime + '\tLabel \'' + flags.label + '\' does not exist.') check = False # download all new packets and relabel with specified label else: messages = ListMessagesMatch...
messages = ListMessagesMatchingQuery(service,'me', 'label:' + flags.label) if not messages: record('No messages found.') else: for message in messages: GetData(service, 'me', message['id'], dir_path)
conditional_block
PacketDownloader.py
client from oauth2client import tools from oauth2client import file from googleapiclient import errors UPDATE_INTERVAL = 5 # seconds NEW_LABEL_ID = None # Gmail label ID of 'new' label # command line arguments try: import argparse parser = argparse.ArgumentParser(parents=[tools.argparser]) parse...
labels = response['labels'] return labels except errors.HttpError, error: print('An error occurred: %s' % error) # log data and print to screen def record(text): localtime = time.asctime(time.localtime(time.time())) log_path = os.path.join(flags.directory, flags.label, 'log.txt') with open(lo...
random_line_split
trace_context.rs
size, wg: WaitGroup, tracer: WeakTracer, } impl std::fmt::Debug for TracingContext { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.debug_struct("TracingContext") .field("trace_id", &self.trace_id) .field("trace_segment_id", &self.trace_segment_id) ...
peek_active_span_id
identifier_name
trace_context.rs
() } } impl TracingContext { /// Generate a new trace context. pub(crate) fn new( service_name: impl Into<String>, instance_name: impl Into<String>, tracer: WeakTracer, ) -> Self { TracingContext { trace_id: RandomGenerator::generate(), trace_segm...
{ self.tracer.upgrade().expect("Tracer has dropped") }
identifier_body
trace_context.rs
{ self.uid } } pub(crate) struct FinalizeSpan { uid: SpanUid, /// When the span is [AsyncSpan] and unfinished, it is None. obj: Option<SpanObject>, /// For [TracingContext::continued] used. r#ref: Option<SegmentReference>, } impl FinalizeSpan { pub(crate) fn new( uid: usiz...
&self.service_instance } fn next_span_id(&self) -> i32 { self.next_span_id } #[inline] fn inc_next_span_id(&mut self) -> i32 { let span_id = self.next_span_id; self.next_span_id += 1; span_id } /// The span uid is to identify the [Span] for crate. ...
} /// Get service instance. #[inline] pub fn service_instance(&self) -> &str {
random_line_split
trace_context.rs
(finalize_span); } /// Close async span, fill the span object. pub(crate) fn finalize_async_span(&self, uid: SpanUid, mut obj: SpanObject) { for finalize_span in &mut *self.finalized_mut() { if finalize_span.uid == uid { obj.end_time = fetch_time(TimePeriod::End); ...
{ self.trace_id = snapshot.trace_id.clone(); let tracer = self.upgrade_tracer(); let segment_ref = SegmentReference { ref_type: RefType::CrossThread as i32, trace_id: snapshot.trace_id, parent_trace_segment_id: snapshot.trace_segment_...
conditional_block
fslogical.go
// Just advance the consistent point. if err := events.OnBegin(ctx, t.cp); err != nil { return err } if err := events.OnCommit(ctx); err != nil { return err } case batchStart: toMark = toMark[:0] if err := events.OnBegin(ctx, t.cp); err != nil { return err } case batchDoc: d...
{ return fmt.Sprintf("fs-doc-%s", ref.Path) }
identifier_body
fslogical.go
.State, ) error { prev, _ := state.GetConsistentPoint().(*consistentPoint) to := time.Now() for { log.Tracef("backfilling %s from %s", d.sourcePath, prev) err := d.backfillOneBatch(ctx, ch, to, prev, state) if err != nil { return errors.Wrap(err, d.sourcePath) } select { case next := <-state.Notify...
log.Tracef("collection %s: %d events", d.sourcePath, len(snap.Changes)) if err := send(batchStart{streamPoint(snap.ReadTime)}); err != nil { return err } for _, change := range snap.Changes { switch change.Kind { case firestore.DocumentAdded, firestore.DocumentModified: // Ignore documents t...
{ // Mask cancellations errors. if status.Code(err) == codes.Canceled || errors.Is(err, iterator.Done) { return nil } return errors.WithStack(err) }
conditional_block
fslogical.go
fillOneBatch grabs a single batch of documents from the backend. // It will return the next incremental consistentPoint and whether the // backfill is expected to continue. func (d *Dialect) backfillOneBatch( ctx context.Context, ch chan<- logical.Message, now time.Time, cp *consistentPoint, state logical.State, )...
ZeroStamp
identifier_name
fslogical.go
We're going to call GetAll since we're running with a reasonable // limit value. This allows us to peek at the id of the last // document, so we can compute the eventual consistent point for // this batch of docs. docs, err := snap.Documents.GetAll() if err != nil { return errors.WithStack(err) } log.Tracef(...
// specified document. func marshalDeletion(id *firestore.DocumentRef, updatedAt time.Time) (types.Mutation, error) {
random_line_split
test_query_performance.py
""") index_para_template = Template(""" <parameters> <index>$index_path</index> <memory>$memory</memory> $corpora <stemmer><name>$stemmer</name></stemmer> $fields $stopper </parameters>""") corpus_template = Template(""" <corpus> \t<path>$path</path> \t<class>trectext</class> </corpus> """) text_template = Template(...
(self): return self._text_struct.raw_model() @property def text(self): return "%s" %self._text class ExpandedQuery(Query): """Queries with expansion """ def __init__(self,qid,query_text,para_lambda): self._para_lambda = para_lambda super(ExpandedQuery,self).__init...
original_model
identifier_name
test_query_performance.py
""") index_para_template = Template(""" <parameters> <index>$index_path</index> <memory>$memory</memory> $corpora <stemmer><name>$stemmer</name></stemmer> $fields $stopper </parameters>""") corpus_template = Template(""" <corpus> \t<path>$path</path> \t<class>trectext</class> </corpus> """) text_template = Template(...
def read_query_file(query_file,qrels): queries = {} data = json.load(open(query_file)) for single_query in data: qid = single_query["topid"] if qid not in qrels: continue # text = re.sub("[^\w ]+"," ",single_query["title"]) # queries[qid] = text queries...
qrel_file = os.path.join(eval_dir,"qrels.txt") qrels = {} with open(qrel_file) as f: for line in f: line = line.rstrip() parts = line.split() qid = parts[0] docid = parts[2] jud = max(0,int(parts[3]) ) if qid not in qrels: ...
identifier_body
test_query_performance.py
query_template = Template(""" <query> \t<number>$qid</number> \t<text>$q_string</text> </query> """) structure_template = Template(""" <parameters> <index>$index</index> <trecFormat>true</trecFormat> <runID>$run_id</runID> <count>$count</count> $query_body $rule $stopper $psr </parameters>""") index_para_template = ...
import argparse import codecs from string import Template
random_line_split
test_query_performance.py
""") index_para_template = Template(""" <parameters> <index>$index_path</index> <memory>$memory</memory> $corpora <stemmer><name>$stemmer</name></stemmer> $fields $stopper </parameters>""") corpus_template = Template(""" <corpus> \t<path>$path</path> \t<class>trectext</class> </corpus> """) text_template = Template(...
stopper += "</stopper>" else: stopper = "" for qid in queries: sinlge_query_data = queries[qid] if isinstance(sinlge_query_data,Query): original_text = re.sub("[^\w]"," ",sinlge_query_data.text) if isinsta...
stopper += "<word>%s</word>\n" %stopword
conditional_block
translator.py
: class Argument: def __init__(self, content, begin_pos, end_pos): self.content = content self.begin_pos = begin_pos self.end_pos = end_pos def __hash__(self): return hash(self.content) def __eq__(self, other): return isinstance(other, Tag.Argument) and self.content == other.content def __str...
Tag
identifier_name
translator.py
pc = doc[i-1] if i-1 > 0 else None c = doc[i] if c == '{' and pc != '\\': depth += 1 elif c == '}' and pc != '\\': depth -= 1 if depth == 0: break i += 1 return i while True: i = doc.find(tag, pos) if i < 0: break args = [] start_tag = i end =...
texts.append(Tag(tag, args, start_tag, end)) return texts class Translation: ALLOW_NOT_EXISTING = 1 TAG_MSGID = 'msgid' TAG_MSGID_PLURAL = 'msgid_plural' TAG_MSGSTR = 'msgstr' TAG_MSGCTXT = 'msgctxt' @staticmethod def load(input_file, file, flags=0): _, name = os.path.split(file) name = RE_PO_FILE...
try: end = _find_matching_closing(start) except Exception as e: raise Exception( 'Could not find end for tag that starts at line '+ '{line} ({text})'.format( line=line_number[start], text=( doc[max(start-20, 0):start]+' --> '+ doc[start:min(start+20, len...
conditional_block
translator.py
pc = doc[i-1] if i-1 > 0 else None c = doc[i] if c == '{' and pc != '\\': depth += 1 elif c == '}' and pc != '\\': depth -= 1 if depth == 0: break i += 1 return i while True: i = doc.find(tag, pos) if i < 0: break args = [] start_tag = i e...
sys.stderr.write('Updating translation {}...\n'.format(self)) if not os.path.exists(self.file): sys.stderr.write('Generating new translation file: {}...\n'.format(self.file)) subprocess.check_call(['msginit', '-i', template_name, '-l', self.locale, '-o', self.file]) return True with open(self.file, ...
template_name = self.generate_template(document)
random_line_split
translator.py
def __str__(self): return self.content def __init__(self, name, args, begin_pos, end_pos): self.name = name self.args = args self.begin_pos = begin_pos self.end_pos = end_pos def __eq__(self, other): return isinstance(other, Tag) and self.name == other.name and self.args == other.args def __hash_...
return isinstance(other, Tag.Argument) and self.content == other.content
identifier_body
obj.rs
str) -> Result<Self, Self::Err> { let mut tokens = s.split('/'); // Get vertex index let vertex_index: T = tokens .next() .ok_or_else(|| io_error("Missing vertex index"))? .parse() .map_err(io_error)?; let texture_index: Option<T> = tokens ...
other => { eprintln!("Unhandled line type: {}", other); } } } // Push the last group groups.push(cur_group); // Average out the center let center = center * (1.0 / (num_vertices as f32)); println!("Center fo...
{ let face_indices = tokens.map(FaceIndex::from_str).flatten().collect(); cur_group.faces.push(face(face_indices)); }
conditional_block
obj.rs
&str) -> Result<Self, Self::Err> { let mut tokens = s.split('/'); // Get vertex index let vertex_index: T = tokens .next() .ok_or_else(|| io_error("Missing vertex index"))? .parse() .map_err(io_error)?; let texture_index: Option<T> = token...
(name: &str) -> Self { Group { name: name.into(), faces: Vec::new(), } } } struct Material { /// Ka ambient_color: Color, /// Kd diffuse_color: Color, /// Ks specular_color: Color, /// Ns specular_exponent: f32, /// Ni optical_density:...
new
identifier_name
obj.rs
&str) -> Result<Self, Self::Err> { let mut tokens = s.split('/'); // Get vertex index let vertex_index: T = tokens .next() .ok_or_else(|| io_error("Missing vertex index"))? .parse() .map_err(io_error)?; let texture_index: Option<T> = token...
name: name.into(), faces: Vec::new(), } } } struct Material { /// Ka ambient_color: Color, /// Kd diffuse_color: Color, /// Ks specular_color: Color, /// Ns specular_exponent: f32, /// Ni optical_density: f32, /// d or Tr transparency:...
random_line_split
cortex.pb.go
samples,omitempty"` } func (m *TimeSeries) Reset() { *m = TimeSeries{} } func (m *TimeSeries) String() string { return proto.CompactTextString(m) } func (*TimeSeries) ProtoMessage() {} func (*TimeSeries) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func...
() string { return proto.CompactTextString(m) } func (*LabelMatcher) ProtoMessage() {} func (*LabelMatcher) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } type ReadRequest struct { StartTimestampMs int64 `protobuf:"varint,1,opt,name=start_timestamp_ms,json=startTi...
String
identifier_name
cortex.pb.go
samples,omitempty"` } func (m *TimeSeries) Reset() { *m = TimeSeries{} } func (m *TimeSeries) String() string { return proto.CompactTextString(m) } func (*TimeSeries) ProtoMessage() {} func (*TimeSeries) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func...
} return nil } type LabelValuesRequest struct { LabelName string `protobuf:"bytes,1,opt,name=label_name,json=labelName" json:"label_name,omitempty"` } func (m *LabelValuesRequest) Reset() { *m = LabelValuesRequest{} } func (m *LabelValuesRequest) String() string { return proto.Compact...
func (*ReadResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } func (m *ReadResponse) GetTimeseries() []*TimeSeries { if m != nil { return m.Timeseries
random_line_split
cortex.pb.go
samples,omitempty"` } func (m *TimeSeries) Reset() { *m = TimeSeries{} } func (m *TimeSeries) String() string { return proto.CompactTextString(m) } func (*TimeSeries) ProtoMessage() {} func (*TimeSeries) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func...
func (*LabelValuesResponse) ProtoMessage() {} func (*LabelValuesResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } type UserStatsResponse struct { IngestionRate float64 `protobuf:"fixed64,1,opt,name=ingestion_rate,json=ingestionRate" json:"ingestion_rate,omitempty"` NumSeries ...
{ return proto.CompactTextString(m) }
identifier_body
cortex.pb.go
,omitempty"` } func (m *TimeSeries) Reset() { *m = TimeSeries{} } func (m *TimeSeries) String() string { return proto.CompactTextString(m) } func (*TimeSeries) ProtoMessage() {} func (*TimeSeries) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *Ti...
return nil } type LabelValuesRequest struct { LabelName string `protobuf:"bytes,1,opt,name=label_name,json=labelName" json:"label_name,omitempty"` } func (m *LabelValuesRequest) Reset() { *m = LabelValuesRequest{} } func (m *LabelValuesRequest) String() string { return proto.CompactTe...
{ return m.Timeseries }
conditional_block
sss.py
pop = startpop minbboxarea = bbox[2]*bbox[3] mingen = 0 # Keep track of the total bbox maxx = bbox[2] maxy = bbox[3] maxpop = startpop # Ignore ship if rule is not a 2-state rule if not g.numstates()==2: return (minpop, speed) for ii in xrange(maxgen): g.ru...
else: rle_strB = str (rl_i[0] - rl_x - 1) rle_res = rle_res + rle_strA + "o" + rle_strB + "b" rle_len = 1 else: if rle_len == 1: rle_strA = "" else: rle_strA = str (rle_len) if rl_i[1] - rl_y == 1: rle_st...
rle_len += 1 else: if rle_len == 1: rle_strA = "" else: rle_strA = str (rle_len) if rl_i[0] - rl_x - 1 == 1: rle_strB = ""
random_line_split
sss.py
Return the minimum and maximum of the absolute value of a list of numbers def minmaxofabs(v): v = [abs(x) for x in v] return min(v), max(v) # Define a sign function sign = lambda x: int(math.copysign(1, x)) # Find the canonical pattern for a sss format ship # This is determined by orienting the ship...
if g.empty(): return if period < 1: return rule = g.getrule().split(':')[0] if not (rule[0] == 'B' and '/S' in rule): g.exit('Please set Golly to an isotropic 2-state rule.') # Parse rule string to list of transitions for Birth and Survival oldrule =...
identifier_body
sss.py
pop = startpop minbboxarea = bbox[2]*bbox[3] mingen = 0 # Keep track of the total bbox maxx = bbox[2] maxy = bbox[3] maxpop = startpop # Ignore ship if rule is not a 2-state rule if not g.numstates()==2: return (minpop, speed) for ii in xrange(maxgen): g.ru...
else: rle_strB = str (rl_i[1] - rl_y) if rl_i[0] == 1: rle_strC = "b" elif rl_i[0] == 0: rle_strC = "" else: rle_strC = str (rl_i[0]) + "b" rle_res = rle_res + rle_strA + "o" + rle_strB + "$" + rle_strC rle_len = 1 ...
rle_strB = ""
conditional_block
sss.py
pop = startpop minbboxarea = bbox[2]*bbox[3] mingen = 0 # Keep track of the total bbox maxx = bbox[2] maxy = bbox[3] maxpop = startpop # Ignore ship if rule is not a 2-state rule if not g.numstates()==2: return (minpop, speed) for ii in xrange(maxgen): g.ru...
(l, n): for i in range(0, len(l), n): yield l[i:i+n] def giveRLE(clist): # clist_chunks = list (chunks (g.evolve(clist,0), 2)) clist_chunks = list(chunks(clist, 2)) clist_chunks.sort(key=lambda l:(l[1], l[0])) mcc = min(clist_chunks) rl_list = [[x[0]-mcc[0],x[1]-mcc[1]] for x i...
chunks
identifier_name
limit.rs
} fn record_demand(&mut self, buf: &[u8]) { self.buf.extend_from_slice(buf); } fn add_demand_cap(&mut self, more: usize) { self.buf.reserve(more + self.get_demand_remaining()); } fn take_allowance(&mut self, taken: usize) { if taken > self.allowance { panic!("taken > allowance"); } ...
fn flush(&mut self) -> io::Result<()> { match self.wstatus { SErr => // if there was an error, wbuf might not have been consumed, so output error even if wbuf is non-empty Err(unwrap_err_or(self.inner.write(&mut []), io::Error::new(ErrorKind::Other, "Ok after Err"))), _ => match self...
{ match self.wstatus { SOpen => { // TODO: figure out when it's appropriate to automatically grow the buffer capacity let remain = self.wbuf.get_demand_remaining(); match remain { 0 => Err(io::Error::new(ErrorKind::WouldBlock, "")), _ => { let n = cmp::m...
identifier_body
limit.rs
} fn record_demand(&mut self, buf: &[u8]) { self.buf.extend_from_slice(buf); } fn add_demand_cap(&mut self, more: usize) { self.buf.reserve(more + self.get_demand_remaining()); } fn take_allowance(&mut self, taken: usize) { if taken > self.allowance { panic!("taken > allowance"); } ...
pub(crate) inner: T, } impl<T> RateLimited<T> { /** Create a new `RateLimited` with the given initial capacity. The inner stream must already be in non-blocking mode. */ pub fn new_lb(inner: T, init: usize) -> RateLimited<T> { RateLimited { inner: inner, rstatus: SOpen, rbuf: RLBuf::...
random_line_split
limit.rs
} fn record_demand(&mut self, buf: &[u8]) { self.buf.extend_from_slice(buf); } fn add_demand_cap(&mut self, more: usize) { self.buf.reserve(more + self.get_demand_remaining()); } fn take_allowance(&mut self, taken: usize) { if taken > self.allowance { panic!("taken > allowance"); } ...
(&mut self, buf: &mut [u8]) -> usize { let to_drain = cmp::min(buf.len(), self.allowance); self.buf.copy_to_slice(&mut buf[..to_drain]); self.buf.reserve(to_drain); self.take_allowance(to_drain); to_drain } fn consume_write<F, E>(&mut self, sz: usize, mut write: F) -> (usize, Option<E>) where...
consume_read
identifier_name
de.rs
, str>), Invalid(&'static str), } impl<'a> Deserializer<'a> { // Call this with a map, with key k, and rest should the rest of the key. // I.e. a[b][c]=v would be called as parse(map, "a", "b][c]", v) fn parse(map: &mut HashMap<Cow<'a, str>, Level<'a>>, k: Cow<'a, str>, rest: Cow<'a, str>, v: Cow<'a, ...
// visitor.visit_seq(self) if let Level::Sequence(x) = self.0 { SeqDeserializer::new(x.into_iter()).deserialize(visitor) } else { Err(de::Error::custom("value does not appear to be a sequence")) } }
identifier_body
de.rs
able<iter::Fuse<IntoIter<Cow<'a, str>, Level<'a>>>>, } // use serde::de::MapVisitor; use std::iter; use std::collections::hash_map::{Entry, IntoIter}; #[derive(Debug)] enum Level<'a> { Nested(HashMap<Cow<'a, str>, Level<'a>>), Sequence(Vec<Cow<'a, str>>), Flat(Cow<'a, str>), Invalid(&'static str), } ...
{ self.deserialize_map(visitor) }
random_line_split
de.rs
a `application/x-wwww-url-encoded` value from a `&str`. /// /// ``` /// let meal = vec![ /// ("bread".to_owned(), "baguette".to_owned()), /// ("cheese".to_owned(), "comté".to_owned()), /// ("fat".to_owned(), "butter".to_owned()), /// ("meat".to_owned(), "ham".to_owned()), /// ]; /// /// let mut res = s...
>(self, _name: &'static str, _fields: &'static [&'static str], visitor: V) -> Result<V::Value, Self::Error> where V: de::Visitor { visitor.visit_map(self) } fn deserialize_seq...
serialize_struct<V
identifier_name
de.rs
/// with or without a given length. /// /// * Main `deserialize` methods defers to `deserialize_map`. /// /// * Everything else but `deserialize_seq` and `deserialize_seq_fixed_size` /// defers to `deserialize`. pub struct Deserializer<'a> { // value: &'a [u8], // map: HashMap<Cow<'a, str>, Level<'a>>, ...
Deserializer::with_map(x).deserialize_map(visitor) } e
conditional_block
JsPsych.js
}, [stimuliUrls]); useEffect(() => { if (ready) { setTimeout(() => { // Implementation of previous team timeline & trial logic -------------------------- START /* create timeline */ const timeline = []; /* number of trials */ // NOTE: Adjust line below to shorten...
{ setReady(true); }
conditional_block
JsPsych.js
(true); } }, [stimuliUrls]); useEffect(() => { if (ready) { setTimeout(() => { // Implementation of previous team timeline & trial logic -------------------------- START /* create timeline */ const timeline = []; /* number of trials */ // NOTE: Adjust line bel...
'</div>' : // For the last 200 images that are rendered, show inverted on left & show original on right "<div style='width: 900px; margin: auto;'>" + "<div class='float: left;'><img width='300' src='" + invFilePath + ...
{ const trials = []; for (let i = 0; i <= numberOfTrial; i++) { const invFilePath = stimuliUrls[i]; const oriFilePath = stimuliUrls[i + 1]; const twoStimulusHtml = // For the first 200 images that are rendered, show original on left & show inverted o...
identifier_body
JsPsych.js
(true); } }, [stimuliUrls]); useEffect(() => { if (ready) { setTimeout(() => { // Implementation of previous team timeline & trial logic -------------------------- START /* create timeline */ const timeline = []; /* number of trials */ // NOTE: Adjust line bel...
(numberOfTrial) { const trials = []; for (let i = 0; i <= numberOfTrial; i++) { const invFilePath = stimuliUrls[i]; const oriFilePath = stimuliUrls[i + 1]; const twoStimulusHtml = // For the first 200 images that are rendered, show original on left &...
generateTrials
identifier_name
JsPsych.js
(true); } }, [stimuliUrls]); useEffect(() => { if (ready) { setTimeout(() => { // Implementation of previous team timeline & trial logic -------------------------- START /* create timeline */ const timeline = []; /* number of trials */ // NOTE: Adjust line bel...
data: { label: 'trial', trial_num: i }, }; trials.push(newStimuli); } return trials; } const fixation = { type: 'html-keyboard-response', stimulus: '<div style="height:307px; width:900px;"><div style="width:900px;...
random_line_split
merge_zips.go
string) { oz.excludeFiles = excludeFiles } // Adds an entry with given name whose source is given ZipEntryContents. Returns old ZipEntryContents // if entry with given name already exists. func (oz *OutputZip) addZipEntry(name string, source ZipEntryContents) (ZipEntryContents, error) { if existingSource, exists := ...
} noInitPackages := make([]string, 0) for pyPkg := range allPackages { if _, found := initedPackages[pyPkg]; !found { noInitPackages = append(noInitPackages, pyPkg) } } return noInitPackages, nil } // An InputZip owned by the InputZipsManager. Opened ManagedInputZip's are chained in the open order. type M...
{ if err := inputZip.Open(); err != nil { return nil, err } for _, file := range inputZip.Entries() { pyPkg := getPackage(file.Name) if filepath.Base(file.Name) == "__init__.py" { if _, found := initedPackages[pyPkg]; found { panic(fmt.Errorf("found __init__.py path duplicates during pars mergin...
conditional_block
merge_zips.go
string) { oz.excludeFiles = excludeFiles } // Adds an entry with given name whose source is given ZipEntryContents. Returns old ZipEntryContents // if entry with given name already exists. func (oz *OutputZip) addZipEntry(name string, source ZipEntryContents) (ZipEntryContents, error) { if existingSource, exists := ...
(inputZip InputZip, index int) error { entry := NewZipEntryFromZip(inputZip, index) if oz.stripDirEntries && entry.IsDir() { return nil } existingEntry, err := oz.addZipEntry(entry.name, entry) if err != nil { return err } if existingEntry == nil { return nil } // File types should match if existingEnt...
copyEntry
identifier_name
merge_zips.go
string) { oz.excludeFiles = excludeFiles } // Adds an entry with given name whose source is given ZipEntryContents. Returns old ZipEntryContents // if entry with given name already exists. func (oz *OutputZip) addZipEntry(name string, source ZipEntryContents) (ZipEntryContents, error) { if existingSource, exists := ...
} return false } // Creates a zip entry whose contents is an entry from the given input zip. func (oz *OutputZip) copyEntry(inputZip InputZip, index int) error { entry := NewZipEntryFromZip(inputZip, index) if oz.stripDirEntries && entry.IsDir() { return nil } existingEntry, err := oz.addZipEntry(entry.name, e...
} if match { return true }
random_line_split
merge_zips.go
string) { oz.excludeFiles = excludeFiles } // Adds an entry with given name whose source is given ZipEntryContents. Returns old ZipEntryContents // if entry with given name already exists. func (oz *OutputZip) addZipEntry(name string, source ZipEntryContents) (ZipEntryContents, error) { if existingSource, exists := ...
func (oz *OutputZip) alphanumericSorted() []string { entries := oz.entriesArray() sort.Strings(entries) return entries } func (oz *OutputZip) writeEntries(entries []string) error { for _, entry := range entries { source, _ := oz.sourceByDest[entry] if err := source.WriteToZip(entry, oz.outputWriter); err != ...
{ entries := oz.entriesArray() sort.SliceStable(entries, func(i, j int) bool { return jar.EntryNamesLess(entries[i], entries[j]) }) return entries }
identifier_body
submasterDurations.py
subsequent swap to B # create some counters that explain the reason for dropping various submasters numDuplicateSubsErrors = 0 numKeepOutSolsErrors = 0 numSubDatabaseErrors = 0 numMissingMarginErrors = 0 numMarginDatabaseErrors = 0 numMissingActualsErrors = 0 numMultipleActualsE...
{"not": {"term" : {"seqId": "00000"}}} ] } } } }, "size": queryLen, "_source": ["seqId","Duration","Children","masterSol", "seqgenDuration"], "sort": { "masterSol": { "order": "des...
random_line_split
submasterDurations.py
keepOutSols = range(1759, 1779)+range(2172,2209)+range(2320,2348) # a list of soles we know we don't want to include in the results; #1759-1779 = conjunction; 2172-2209 = 2172 anomaly recovery; 2320-2348 = Safing on RCE-A on 2320 and again on 2339 and subsequent swap to B # create some counters that expl...
verbose = False # a verbose flag that identifies every time a submaster was rejected from the analysis filename = 'demonstrationoutput' # name of the .json file output to be used as a pseudo-database queryLen = 5000 # how large do we let the query get. Currently we wouldn't want anything larger than 5000 res...
identifier_body
submasterDurations.py
and subsequent swap to B # create some counters that explain the reason for dropping various submasters numDuplicateSubsErrors = 0 numKeepOutSolsErrors = 0 numSubDatabaseErrors = 0 numMissingMarginErrors = 0 numMarginDatabaseErrors = 0 numMissingActualsErrors = 0 numMultipleActu...
seqId = result['_source']['seqId'] # masterSol = int(result['_source']['masterSol']) masterSol = int(result['_source'].get('masterSol',"0")) uniqueID = 'sol' + str(masterSol)+'_' + seqId # initialize a new entry in the temporary submasters dict for this submaster ...
print("{}%".format(percentComplete)) percentComplete+=1
conditional_block
submasterDurations.py
(): #Query for all submasters. We want all activity groups (Pie observations) where the seqID field = sub_XXXX in the last 1000 sols. # --------------------------------------------- Input Parameters and Initializaton ------------------------------------------------- # parameters that should eventually b...
main
identifier_name
transaction.component.ts
<any>; dataExpense: Array<any>; dataDebtLoan: Array<any>; // hiện thị phần thêm chi tiết public adddetail = true; // KHỞI TẠO CÁC BIẾN VỊ TRÍ lat: number = 10.812035; lng: number = 106.7119887 zoom: number = 14; // DANH SÁCH TẤT CẢ CÁC ĐỊA ĐIỂM allPlace: any[] = []; // OBJ...
this.transaction.moneytransaction = (Number(this.transaction.moneytransaction) * -1).toString(); } } // tạo một giao dịch this.TransactionService.createTransaction(this.transaction) .then((result) => { ...
random_line_split
transaction.component.ts
: GooleMapsService, public toastr: ToastsManager, vcr: ViewContainerRef, ) { this.toastr.setRootViewContainerRef(vcr); // LẤY TÊN VÍ HIỆN THỊ LÊN GIAO DIỆN this.paramIdWalletURL(); // PHẦN CHỨC NĂNG TAG USER let thisglob = this; window.onloa...
/ MỞ MODAL CHỌN ĐỊA ĐIỂM GOOGLE MAP open(content) { this.GooleMapsService.getPlaceNear(this.lat, this.lng).then((data) => { this.allPlace = data.results; }) this.modalService.open(content); } // SUBMIT ĐỊA ĐIỂM submitLocation(pla
identifier_body