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
lib.rs
pub result: String, } impl fmt::Display for LayerResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} | {}", self.layer, self.result) } } /// A Transition is the LayerResult of running the command on the lower layer /// and of running the command on the higher layer. No-op tr...
match r.read(&mut g.buf[g.len..]) { Ok(0) => { break; } Ok(n) => g.len += n, Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(_e) => { break; } } if Syst...
{ g.buf.resize(g.len + reservation_size, 0); }
conditional_block
lib.rs
"); let first_image_name: String = first_layer.image_name.clone(); let last_image_name = &last_layer.image_name; let action_c = action.clone(); let left_handle = thread::spawn(move || action_c.try_container(&first_image_name)); let end = action.try_container(last_image_name); let start = left...
{}
identifier_body
meanS1.py
full_matrices=False) snew = np.clip(s - lambdap/beta, 0, None) thetay = np.reshape(np.dot(u, np.dot(np.diag(snew), v)), pnew, order = 'F') rho = rhohalf - alpha * beta * (thetax - thetay) diff = np.sum(np.abs(thetax - thetay)) itr = itr + 1 #if(diag == True): # ...
T1=100 T2=75 T3=150 T4=75 T5=100 nall=T1+T2+T3+T4+T5 true_cpt_pos=np.array([T1-1,T1+T2-1,T1+T2+T3-1,T1+T2+T3+T4-1]) cpt_num=np.zeros([Itermax]) d_under=np.zeros([Itermax]) d_over=np.zeros([Itermax]) MSIC=np.zeros([Itermax]) h_selected=np.zeros([Itermax]) np.random.seed(2019) test_number=5 for Iter in range(Iterma...
omega[i, j] = 0.5**(np.abs(i - j))
conditional_block
meanS1.py
def prsm(pX, pY, pnew, nh, m, thetaini, rhoini, alpha, beta, lambdap, epstol, maxiter, diag): pX = pX.reshape(nh * m, pnew, order = 'F') pY = pY.reshape(nh * m, 1, order = 'F') thetay = thetaini rho = rhoini itr = 0 diff = 1 while itr <= maxiter and diff > epstol: Xinverse = np.lin...
Theta = np.random.normal(mu1,sigma,size=(m,p)) u, s, v= np.linalg.svd(Theta, full_matrices = False) s[R:] = 0 smat = np.diag(s) Theta = np.dot(u, np.dot(smat, v)) X= np.random.multivariate_normal(np.zeros(p), omega, m*T) #X= np.random.multivariate_normal(np.zeros(m * p), omega, T) X= np.re...
identifier_body
meanS1.py
(mu1,m,p,R,omega,T,signal,mu,sigma): Theta = np.random.normal(mu1,sigma,size=(m,p)) u, s, v= np.linalg.svd(Theta, full_matrices = False) s[R:] = 0 smat = np.diag(s) Theta = np.dot(u, np.dot(smat, v)) X= np.random.multivariate_normal(np.zeros(p), omega, m*T) #X= np.random.multivariate_norma...
simu
identifier_name
meanS1.py
theta, full_matrices=False) snew = np.clip(s - lambdap/beta, 0, None) thetay = np.reshape(np.dot(u, np.dot(np.diag(snew), v)), pnew, order = 'F') rho = rhohalf - alpha * beta * (thetax - thetay) diff = np.sum(np.abs(thetax - thetay)) itr = itr + 1 #if(diag == True): ...
for k in range(Nr): for j in range(nw-1): dist = Vt[j,j:(nw-1)] + D[(j+1):nw] D[j] = np.min(dist) Pos[j,0] = int(np.where(dist == np.min(dist))[0][0] + j) +1 if k > 0: Pos[j,1:(k+1)] = Pos[int(Pos[j,0]),range(k)] U.append(D[0]) ...
taumat[:] = np.nan
random_line_split
lib.rs
new(); /// let input = r.create_input(111); /// let compute: react::InputCellID = r.create_compute(&[react::CellID::Input(input)], |_| 222).unwrap(); /// ``` #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ComputeCellID(usize); #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct CallbackID(usize...
} // Sets the value of the specified input cell. // // Returns false if the cell does not exist. // // Similarly, you may wonder about `get_mut(&mut self, id: CellID) -> Option<&mut Cell>`, with // a `set_value(&mut self, new_value: T)` method on `Cell`. // // As before, that turned...
}
random_line_split
lib.rs
new(); /// let input = r.create_input(111); /// let compute: react::InputCellID = r.create_compute(&[react::CellID::Input(input)], |_| 222).unwrap(); /// ``` #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ComputeCellID(usize); #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct CallbackID(usize...
} struct ComputeCell<'r, T: Debug> { fun: Box<dyn 'r + Fn(&[T]) -> T>, deps: Vec<CellID>, callbacks: HashMap<CallbackID, Callback<'r, T>>, prev_val: Cell<Option<T>>, next_cbid: usize, // increases monotonically; increments on adding a callback clients: HashSet<ComputeCellID>, } impl<'r, T: Co...
{ InputCell { clients: HashSet::new(), value: init, } }
identifier_body
lib.rs
new(); /// let input = r.create_input(111); /// let compute: react::InputCellID = r.create_compute(&[react::CellID::Input(input)], |_| 222).unwrap(); /// ``` #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ComputeCellID(usize); #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct CallbackID(usize...
() -> Self { Reactor { input_cells: Vec::new(), compute_cells: Vec::new(), } } // Creates an input cell with the specified initial value, returning its ID. pub fn create_input(&mut self, initial: T) -> InputCellID { let idx = self.input_cells.len(); l...
new
identifier_name
utils.py
, read = s() new_note = notes_o(samples) # note too high considered as noise if new_note[0] != 0 and new_note[0] <= 120: note_klass = Note(time=total_frames / float(samplerate), pitch=new_note[0], volume=new_note[1] - 20, duration=new_note[2]) ...
def drum_note_to_heart_beat_track(midi_instance: MIDIFile): """ @Deprecated """ # exporting bass drum notes bass_drum_beats_in_ms = [] ms_per_tick = 60 * 1000 / (tempo * TICKSPERQUARTERNOTE) for event in midi_instance.tracks[channel_map[CHANNEL_NAME_DRUM_KIT]].eventList: if isinstan...
end = range_time['end'] / length proportion_list.append(dict(start=start, end=end)) return proportion_list
random_line_split
utils.py
s = source(filename, samplerate, hop_s) samplerate = s.samplerate tolerance = 0.8 pitch_o = pitch("yin", win_s, hop_s, samplerate) pitch_o.set_unit("midi") pitch_o.set_tolerance(tolerance) result = [] # total number of frames read total_frames = 0 while True: samples, re...
esult = get_heart_beat_track(filename, bar_count, bpm) # reduce 3dB of the result result = result - 3 # tick_per_sec = 60 * 1000 / bpm # fade_time = round(tick_per_sec * 4) # result.fade_in(fade_time) # result.fade_out(fade_time) AudioSegment.export(result, dest_filename)
identifier_body
utils.py
read = s() new_note = notes_o(samples) # note too high considered as noise if new_note[0] != 0 and new_note[0] <= 120: note_klass = Note(time=total_frames / float(samplerate), pitch=new_note[0], volume=new_note[1] - 20, duration=new_note[2]) ...
pitch_result: List[dict]): group_result = [] group = [] for i, pitch_dict in enumerate(pitch_result): # current is not zero, but previous is zero # should flush the group if round(pitch_dict['pitch']) != 0 and i - 1 >= 0 and round(pitch_result[i - 1]['pitch']) == 0: group...
ompute_density_from_pitch_result(
identifier_name
utils.py
read = s() new_note = notes_o(samples) # note too high considered as noise if new_note[0] != 0 and new_note[0] <= 120: note_klass = Note(time=total_frames / float(samplerate), pitch=new_note[0], volume=new_note[1] - 20, duration=new_note[2]) ...
# transform proportion value for further beats computing proportion_list = [] for range_time in range_time_list: start = range_time['start'] / length end = range_time['end'] / length proportion_list.append(dict(start=start, end=end)) return proportion_list def drum_note_to_hea...
tart = pitch_group[0]['time'] end = pitch_group[len(pitch_group) - 1]['time'] range_time_list.append(dict(start=start, end=end))
conditional_block
save_articles.go
имеет значение NULL. func getArticleIds(limit int, showTiming bool) []string { startTime := time.Now() // db, err := sql.Open("sqlite3", dbFileName) db, err := sqlx.Open("postgres", DSN) checkErr(err) ids := make([]string, 0) err = db.Select(&ids, fmt.Sprintf("SELECT obj_id FROM articles WHERE migration_status...
conditional_block
save_articles.go
Показывать времена исполнения") flag.Parse() // flag.Usage() if batchSize == 0 { os.Exit(0) } return } // Порождает таблицу articles в базе данных func createArticlesTable() { sqlCreateArticles := ` CREATE TABLE IF NOT EXISTS articles ( obj_id text PRIMARY KEY, announce text NULL, a...
тексты статей articleTexts := getAPITextsParallel(ids, showTiming) // преобразовываем тексты в записи - массивы полей материала articleRecords := textsToArticleRecords(articleTexts) // Сохраняем записи в базу данных saveArticlesToDatabase(articleRecords, showTiming) // Выводим сообщение counter += len(i...
апросов к API. // - showTiming - Показывать времена исполнения func fillArticlesWithTexts(n, batchSize int, showTiming bool) { // время отдыха между порциями запросов var sleepTime = 50 * time.Millisecond // Счетчик сделанных запросов counter := 0 //Время начала процесса startTime := time.Now() //Берем первую п...
identifier_body
save_articles.go
Показывать времена исполнения") flag.Parse() // flag.Usage() if batchSize == 0 { os.Exit(0) } return } // Порождает таблицу articles в базе данных func createArticlesTable() { sqlCreateArticles := ` CREATE TABLE IF NOT EXISTS articles ( obj_id text PRIMARY KEY, announce text NULL, a...
ные запросы к API возвращая массив пар: // [ [id, text], [id,text],...] func getAPITextsParallel(ids []string, showTiming bool) [][]string { startTime := time.Now() articles := make([][]string, 0) ch := make(chan []string) for _, id := range ids { go func(id string) { ch <- getOneArticleFromAPI(id) }(id) }...
ает параллель
identifier_name
save_articles.go
Показывать времена исполнения") flag.Parse() // flag.Usage() if batchSize == 0 { os.Exit(0) } return } // Порождает таблицу articles в базе данных func createArticlesTable() { sqlCreateArticles := ` CREATE TABLE IF NOT EXISTS articles ( obj_id text PRIMARY KEY, announce text NULL, a...
} // Получает количество новых записей в таблице articles, // где поле migration_status имеет значение NULL. func getNewRecordsNumber() int { db, err := sqlx.Open("postgres", DSN) checkErr(err) ids := make([]int, 0) err = db.Select(&ids, "SELECT count(obj_id) FROM articles WHERE migration_status IS NULL") checkE...
// отдыхаем time.Sleep(sleepTime) // Берем следующую порцию идентификаторов ids = getArticleIds(batchSize, showTiming) }
random_line_split
segment_all_data.py
6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] def filter_bad_values(events): events2 = [item for item in events if item[key_value] > 0] return events2 ''' take list of events, find gaps of time in events, and use those gaps to split the events into segments of events wher...
''' remove segments that are too long or too short those that are in the acceptable range, pad with zeros to fill out the max length ''' def enforce_summary_limits(summary, min_length, max_length): summary2 = [] if summary is None: print 'got a nonexistant summary. wat?' re...
summary.append({key_counts : mycounts, key_energies : myenergies, key_lightvar : mylight, key_id : id, key_interval : (t0, tf)}) return summary
random_line_split
segment_all_data.py
6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] def filter_bad_values(events): events2 = [item for item in events if item[key_value] > 0] return events2 ''' take list of events, find gaps of time in events, and use those gaps to split the events into segments of events where...
def vectorize_measurements(summary): meas = [] info = [] for item in summary: e = item[key_energies] c = item[key_counts] l = item[key_lightvar] id = item[key_id] interval = item[key_interval] label = None if item.has_key(key...
for item in summary: for key in item: if key in k_sensor_keys: thisvector = item[key] item[key] = numpy.concatenate((numpy.zeros((numzeros, )), thisvector, numpy.zeros((numzeros2, ))))
identifier_body
segment_all_data.py
6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] def filter_bad_values(events): events2 = [item for item in events if item[key_value] > 0] return events2 ''' take list of events, find gaps of time in events, and use those gaps to split the events into segments of events where...
(x, logbase = 2.0, offset=1.0): return numpy.log(numpy.var(x) + offset) / numpy.log(logbase) def compute_log_range(x, logbase = 2.0, maxval=10.): imin = numpy.argmin(x) imax = numpy.argmax(x) min = x[imin] max = x[imax] #if the max happened later than the min, then this was an...
compute_log_variance
identifier_name
segment_all_data.py
6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] def filter_bad_values(events): events2 = [item for item in events if item[key_value] > 0] return events2 ''' take list of events, find gaps of time in events, and use those gaps to split the events into segments of events wher...
last_t2 = t1 is_one_segment_found = False for t in timelist: t2 = t dt = float(t2-t1)*k_conversion_factor if dt > k_segment_split_duaration: seg_t2 = last_t1 t1_list.append(seg_t1) ...
pilllists = dict_of_lists[key]['pill'] senselist = dict_of_lists[key]['sense'] timelist = pilllists[0] valuelist = pilllists[1] sensetimes = senselist[0] temperatures = senselist[1] humidities = senselist[2] lights = senselist[3] t1...
conditional_block
listparser.py
а итогов голосования по мажоритарной системе выборов(Протокол №1)', u'Сводная таблица результатов выборов', u'Сводная таблица итогов голосования', u'Сводный отчет об итогах голосования', u...
level is None or level == '': print('ERRORERROR: No level for elections list') exit(1) elections_list['level'] = level return elections_list # find the innermost table with this text if re.search(u'Всего найдено записей:', t...
get_level(table) if take_next: elections_list = self.parse_elections_list_table(table) if
conditional_block
listparser.py
таблица итогов голосования по мажоритарной системе выборов(Протокол №1)', u'Сводная таблица результатов выборов', u'Сводная таблица итогов голосования', u'Сводный отчет об итогах голосования', ...
if len(results_hrefs) == 0: print 'Did not find results_href, ERRORERROR' raise LoadFailedDoNotRetry(href) # If one link - return it elif len(results_hrefs) == 1: return results_hrefs[0]['href'] # If there are several protocols (links), try to return o...
results_hrefs.append ({'href':l['href'], 'title':l.text}) # If empty - exception
random_line_split
listparser.py
а итогов голосования по мажоритарной системе выборов(Протокол №1)', u'Сводная таблица результатов выборов', u'Сводная таблица итогов голосования', u'Сводный отчет об итогах голосования', u...
l == '': print('ERRORERROR: No level for elections list') exit(1) elections_list['level'] = level return elections_list # find the innermost table with this text if re.search(u'Всего найдено записей:', table.get_text()) is n...
please select one' exit(1) return level def parse_elections_list_file(self, file): f = codecs.open(file, encoding='windows-1251') d = f.read() soup = BeautifulSoup(d, 'html.parser') f.close() take_next = False for table in sou...
identifier_body
listparser.py
а итогов голосования по мажоритарной системе выборов(Протокол №1)', u'Сводная таблица результатов выборов', u'Сводная таблица итогов голосования', u'Сводный отчет об итогах голосования', u...
age raise LoadRetryWithDifferentFormat def check_lens(rr_cc, target_lens, error_message): if len(rr_cc) not in target_lens: print error_message raise LoadRetryWithDifferentFormat def check_text (r_c, target_texts, error_message): if not any_text_is_there(target_texts, r_c.get_text())...
ror_mess
identifier_name
wasitests.rs
#[derive(Debug, Clone, PartialEq, Eq)] pub struct NativeOutput { stdout: String, stderr: String, result: i64, } /// Compile and execute the test file as native code, saving the results to be /// compared against later. /// /// This function attempts to clean up its output after it executes it. fn generate_...
use super::util; use super::wasi_version::*;
random_line_split
wasitests.rs
executable_path.to_string_lossy() ); fs::set_permissions(&executable_path, perm)?; } println!( "Executing native program at {}", executable_path.to_string_lossy() ); // workspace root const EXECUTE_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/wasi"); let mu...
} Err(e) => println!("{:?}", e), } } println!("All modules generated."); } /// This is the structure of the `.wast` file #[derive(Debug, Default, Serialize, Deserialize)] pub struct WasiTest { /// The name of the wasm module to run pub wasm_prog_name: String, /// Th...
{ compile(temp_dir.path(), test, wasi_versions); }
conditional_block
wasitests.rs
executable_path.to_string_lossy() ); fs::set_permissions(&executable_path, perm)?; } println!( "Executing native program at {}", executable_path.to_string_lossy() ); // workspace root const EXECUTE_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/wasi");...
(temp_dir: &Path, file: &str, wasi_versions: &[WasiVersion]) { let src_code: String = fs::read_to_string(file).unwrap(); let options: WasiOptions = extract_args_from_source_file(&src_code).unwrap_or_default(); assert!(file.ends_with(".rs")); let rs_mod_name = { Path::new(&file.to_lowercase()) ...
compile
identifier_name
wasitests.rs
executable_path.to_string_lossy() ); fs::set_permissions(&executable_path, perm)?; } println!( "Executing native program at {}", executable_path.to_string_lossy() ); // workspace root const EXECUTE_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/wasi");...
.options .args .iter() .map(|v| format!("\"{}\"", v)) .collect::<Vec<String>>() .join(" "); let _ = write!(out, "\n (args {})", args); } if !self.options.dir.is_empty() { let preopen...
{ use std::fmt::Write; let mut out = format!( ";; This file was generated by https://github.com/wasmerio/wasi-tests\n (wasi_test \"{}\"", self.wasm_prog_name ); if !self.options.env.is_empty() { let envs = self .options ...
identifier_body
biology.js
with five-part symmetry and an internal skeleton made from calcium carbonate.", "Arthropoda: Phylum for segmented animals consisting of a head, thorax, and abdomen. Their bodies are covered with an exoskeleton.", "Crustacea: Phylum for segmented animals with 18 to 20 segments, two pairs of antennae, an...
{ $("#option-" + j).hide(); }
conditional_block
biology.js
). They generally have multiple cells.", "Bacteria: Kingdom for organisms with a single cell that have no nucleus.", "Fungi: Kingdom for organisms that absorb nutrients for energy. They may have one or more cells.", "Plantae: Kingdom for autotrophs - organisms that use photosynthesis to make their own...
"quadrangularis: A species for grey sea cucumbers with prominent tapering papillae along the corners of their squarish bodies." ]
random_line_split
biology.js
"Bacteria: Kingdom for organisms with a single cell that have no nucleus.", "Fungi: Kingdom for organisms that absorb nutrients for energy. They may have one or more cells.", "Plantae: Kingdom for autotrophs - organisms that use photosynthesis to make their own food. They usually have multiple cells."...
setOptions
identifier_name
biology.js
for segmented animals consisting of a head, thorax, and abdomen. Their bodies are covered with an exoskeleton.", "Crustacea: Phylum for segmented animals with 18 to 20 segments, two pairs of antennae, and compound eyes that are usually on stalks." ], [ "Magnoliophyta: Phylum for plants that...
{ if(k === undefined) k = 0; if(i > 6) throw "We use the six-kingdom system here"; $("#classifying").text(classifications[i]); for(var j = 1; j < 6; j++) { var option; if(i < 1) option = options[i][j-1]; else { if(k === 2 && i === 1) ...
identifier_body
app.js
'}, {type: '250 miles'}, {type: '500 miles'} ], arroBranches: [ { "sName": "Air Force", "bActiveFilter": false }, { "sName": "Army", "bActiveFilter": false }, { "sName": "Navy", "bActiveFilter": false }, { ...
scope.$apply(); }); } // bLazyLoadingDone is needed to trigger $compile because it creates a diff // also, make sure your lazily loaded element has some content. Or again, there will be no diff and no render will happen. // ref: https://stackoverflow.com/questions/38514918/when-lazy-load...
}
random_line_split
app.js
'}, {type: '250 miles'}, {type: '500 miles'} ], arroBranches: [ { "sName": "Air Force", "bActiveFilter": false }, { "sName": "Army", "bActiveFilter": false }, { "sName": "Navy", "bActiveFilter": false }, { ...
return { $location: $location, Data: MiData, getStyle: getStyle, getFirstMatch: getFirstMatch, init: init, State: MiState, $window: $window, Overlay: Overlay } }]) // syntactic sugar. Maybe collapse into one service if you want, but this is modu...
{ arrsfDirectives.forEach(function(sfDirective){ oLazyLoad[sfDirective](); }); scope.bLazyLoadingDone = true; }
identifier_body
app.js
'}, {type: '250 miles'}, {type: '500 miles'} ], arroBranches: [ { "sName": "Air Force", "bActiveFilter": false }, { "sName": "Army", "bActiveFilter": false }, { "sName": "Navy", "bActiveFilter": false }, { ...
(arrsfDirectives, scope) { arrsfDirectives.forEach(function(sfDirective){ oLazyLoad[sfDirective](); }); scope.bLazyLoadingDone = true; } return { $location: $location, Data: MiData, getStyle: getStyle, getFirstMatch: getFirstMatch, ini...
fLazyLoad
identifier_name
app.js
'}, {type: '250 miles'}, {type: '500 miles'} ], arroBranches: [ { "sName": "Air Force", "bActiveFilter": false }, { "sName": "Army", "bActiveFilter": false }, { "sName": "Navy", "bActiveFilter": false }, { ...
if ($event.currentTarget.classList.contains('panel-open')) { // ensure indicator is expanded in this case $openIndicator.animate({ width: 40 }, 300); } else { // ensure indicator is collapsed in this case $openIndicator.animat...
{ // create $openIndicator if it's not there $openIndicator = $('<div class="open-indicator">'); $panelHeading.before($openIndicator); }
conditional_block
test.rs
() { // Windows compatible. let output = sh("echo hi").read().unwrap(); assert_eq!("hi", output); } #[test] fn test_start() { let handle1 = cmd!(path_to_exe("echo"), "hi") .stdout_capture() .start() .unwrap(); let handle2 = cmd!(path_to_exe("echo"), "lo") .stdout_cap...
test_sh
identifier_name
test.rs
::thread::spawn(move || { arc_clone.wait().unwrap(); }); handle.kill().unwrap(); wait_thread.join().unwrap(); } #[test] fn test_nonblocking_waits() { let sleep_cmd = cmd!(path_to_exe("sleep"), "1000000"); // Make sure pipelines handle try_wait correctly. let handle = sleep_cmd.pipe(&sle...
{ assert_eq!(output1, ""); }
conditional_block
test.rs
let handle2 = cmd!(path_to_exe("echo"), "lo") .stdout_capture() .start() .unwrap(); let output1 = handle1.wait().unwrap(); let output2 = handle2.wait().unwrap(); assert_eq!("hi", str::from_utf8(&output1.stdout).unwrap().trim()); assert_eq!("lo", str::from_utf8(&output2.stdout...
.stdout_capture() .start() .unwrap();
random_line_split
test.rs
("status"), "2"); // Right takes precedence over left. let output = one.pipe(two.clone()).unchecked().run().unwrap(); assert_eq!(2, output.status.code().unwrap()); // Except that checked on the left takes precedence over unchecked on // the right. let output = one.pipe(two.unchecked()).uncheck...
#[test] fn test_pipe_start() { let nonexistent_cmd = cmd!(path_to_exe("nonexistent!!!")); let sleep_cmd = cmd!(path_to_exe("sleep"), "1000000"); // Errors starting the left side of a pipe are returned immediately, and // the right side is never started. nonexistent_cmd.pipe(&sleep_cmd).start().un...
{ // Make sure both sides get killed. let sleep_cmd = cmd!(path_to_exe("sleep"), "1000000"); // Note that we don't use unchecked() here. This tests that kill suppresses // exit status errors. let handle = sleep_cmd.pipe(sleep_cmd.clone()).start().unwrap(); handle.kill().unwrap(); // But call...
identifier_body
writebacker.go
Transactioner: transactionerConfig{ // Commit transaction once 20 write queries have been performed (as // identified in checksum_write_back benchmark). MaxTransactionSize: 20, // Commit transaction after 2 minutes regardless of the number of // queries performed. MaxTransactionLifetime: 2 * time.Minute, }...
() <-chan struct{} { return w.tomb.Dead() } func (w *WriteBacker) Err() error { return w.tomb.Err() } func (w *WriteBacker) endOfQueueHandler() error { select { case <-w.endOfQueueSignal: w.fieldLogger.Info("Received end-of-queue signal") w.fieldLogger.Debug("Draining and stopping worker pool as end-of-queue...
Dead
identifier_name
writebacker.go
Transactioner: transactionerConfig{ // Commit transaction once 20 write queries have been performed (as // identified in checksum_write_back benchmark). MaxTransactionSize: 20, // Commit transaction after 2 minutes regardless of the number of // queries performed. MaxTransactionLifetime: 2 * time.Minute, }...
func (w *WriteBacker) batcherManager() error { select { case <-w.batcher.Dead(): err := w.batcher.Err() if err == lifecycle.ErrStopSignalled { return nil } else if err != nil { err = pkgErrors.Wrap(err, "(*WriteBacker).batcherManager") w.fieldLogger.WithError(err).WithFields(log.Fields{ "action":...
{ select { case <-w.workerPoolStopped: // There is no way of receiving errors from the worker pool return nil case <-w.tomb.Dying(): w.fieldLogger.Debug("Stopping and waiting for worker pool as component is dying") w.workerPool.Stop() return tomb.ErrDying } }
identifier_body
writebacker.go
Transactioner: transactionerConfig{ // Commit transaction once 20 write queries have been performed (as // identified in checksum_write_back benchmark). MaxTransactionSize: 20, // Commit transaction after 2 minutes regardless of the number of // queries performed. MaxTransactionLifetime: 2 * time.Minute, }...
w.tomb, _ = tomb.WithContext(ctx) w.fieldLogger = w.Config.Logger.WithFields(log.Fields{ "run": w.Config.RunID, "snapshot": w.Config.SnapshotName, "filesystem": w.Config.FileSystemName, "namespace": w.Config.Namespace, "component": "workqueue.WriteBacker", }) w.endOfQueueSignal = make(chan st...
func (w *WriteBacker) Start(ctx context.Context) {
random_line_split
writebacker.go
") w.fieldLogger.WithError(err).WithFields(log.Fields{ "action": "stopping", }).Error("Encountered error while closing batcher") return err } return nil case <-w.tomb.Dying(): return tomb.ErrDying } } func (w *WriteBacker) workerPoolManager() error { select { case <-w.workerPoolStopped: // The...
{ err = pkgErrors.Wrap(err, "(*writeBackerContext).Process: unmarshal WriteBackPack from job") w.WriteBacker.fieldLogger.WithError(err).WithFields(log.Fields{ "action": "stopping", "args": job.Args, "job_name": job.Name, }).Error("Encountered error while unmarshaling WriteBackPack from job") w.Wr...
conditional_block
find_panics.py
iscv64-unknown-elf-objdump" # TODO: For all functions below the initial batch, it would like be preferable to # automatically populate the list with additional functions in the core library using # debug info. For now, however, I do this manually. panic_functions = [ "expect_failed", "unwrap_failed", "pani...
def any_origin_matches_panic_func(elf, addr): """returns name if any origin for the passed addr matches one of the functions in the panic_functions array """ origins = linkage_or_origin_all_parents(elf, addr) for origin in origins: name = matches_panic_funcs(origin) if name: ...
"""Returns a list of the abstract origin or linkage of all parents of the dwarf location for the passed address """ result = subprocess.run( (DWARFDUMP, "--lookup=0x" + addr, "-p", elf), capture_output=True, text=True ) dwarfdump = result.stdout regex = abstract_origin_re if linkage:...
identifier_body
find_panics.py
u20$core..ops..index..Index$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$5index17hfe7e43aa2388c47bE", ] # Pre-compiled regex lookups dw_at_file_re = re.compile(r""".*(?:DW_AT_call_file|DW_AT_decl_file).*""") dw_at_line_re = re.compile(r""".*(?:DW_AT_call_line|DW_AT_decl_line).*""") line_info_re = re.compile(r""".*Line info.*""...
raise RuntimeError("Unhandled")
conditional_block
find_panics.py
iscv64-unknown-elf-objdump" # TODO: For all functions below the initial batch, it would like be preferable to # automatically populate the list with additional functions in the core library using # debug info. For now, however, I do this manually. panic_functions = [ "expect_failed", "unwrap_failed", "pani...
(elf, addr, linkage=False): """Returns a list of the abstract origin or linkage of all parents of the dwarf location for the passed address """ result = subprocess.run( (DWARFDUMP, "--lookup=0x" + addr, "-p", elf), capture_output=True, text=True ) dwarfdump = result.stdout regex = ab...
linkage_or_origin_all_parents
identifier_name
find_panics.py
import re import subprocess import sys if platform.system() == 'Darwin': DWARFDUMP = "dwarfdump" elif platform.system() == 'Linux': DWARFDUMP = "llvm-dwarfdump" else: raise NotImplementedError("Unknown platform") # Note: In practice, GCC objdumps are better at symbol resolution than LLVM objdump ARM_OBJDU...
import argparse import platform
random_line_split
topics_and_partitions.go
itionsData) loadTopic(t string) *topicPartitionsData
// A helper type mapping topics to their partitions that can be updated // atomically. type topicsPartitions struct { v atomic.Value // topicsPartitionsData (map[string]*topicPartitions) } func (t *topicsPartitions) load() topicsPartitionsData { if t == nil { return nil } return t.v.Load().(topicsPartitionsDat...
{ tp, exists := d[t] if !exists { return nil } return tp.load() }
identifier_body
topics_and_partitions.go
to their partitions that can be updated // atomically. type topicsPartitions struct { v atomic.Value // topicsPartitionsData (map[string]*topicPartitions) } func (t *topicsPartitions) load() topicsPartitionsData { if t == nil { return nil } return t.v.Load().(topicsPartitionsData) } func (t *topicsPartitions) s...
// After the unlock above, record buffering can trigger drains // on the new sink, which is not yet consuming from these // records. Again, just more wasted drain triggers.
random_line_split
topics_and_partitions.go
itionsData) loadTopic(t string) *topicPartitionsData { tp, exists := d[t] if !exists { return nil } return tp.load() } // A helper type mapping topics to their partitions that can be updated // atomically. type topicsPartitions struct { v atomic.Value // topicsPartitionsData (map[string]*topicPartitions) } fun...
(new *topicPartition) { // First, remove our record buffer from the old sink. old.records.sink.removeRecBuf(old.records) // Before this next lock, record producing will buffer to the // in-migration-progress records and may trigger draining to // the old sink. That is fine, the old sink no longer consumes // fro...
migrateProductionTo
identifier_name
topics_and_partitions.go
itionsData) loadTopic(t string) *topicPartitionsData { tp, exists := d[t] if !exists { return nil } return tp.load() } // A helper type mapping topics to their partitions that can be updated // atomically. type topicsPartitions struct { v atomic.Value // topicsPartitionsData (map[string]*topicPartitions) } fun...
p := &cl.producer p.unknownTopicsMu.Lock() defer p.unknownTopicsMu.Unlock() // If the topic did not have partitions, then we need to store the // partition update BEFORE unlocking the mutex to guard against this // sequence of events: // // - unlock waiters // - delete waiter // - new produce recrea...
{ l.v.Store(lv) return }
conditional_block
lib.rs
::new(), skip: Default::default(), } } } /// A pretty-printable value from Javascript. pub struct Prettified { /// The current value we're visiting. value: JsValue, /// We just use a JS array here to avoid relying on wasm-bindgen's unstable /// ABI. seen: WeakSet, /// Pr...
; impl Debug for JsFunction { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "[Function]") } } #[cfg(test)] mod tests { use super::*; use futures::channel::oneshot::channel; use wasm_bindgen::closure::Closure; use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_confi...
JsFunction
identifier_name
lib.rs
where T: AsRef<JsValue>, { fn pretty(&self) -> Prettified { Prettified { value: self.as_ref().to_owned(), seen: WeakSet::new(), skip: Default::default(), } } } /// A pretty-printable value from Javascript. pub struct Prettified { /// The current value...
impl<T> Pretty for T
random_line_split
lib.rs
::new(), skip: Default::default(), } } } /// A pretty-printable value from Javascript. pub struct Prettified { /// The current value we're visiting. value: JsValue, /// We just use a JS array here to avoid relying on wasm-bindgen's unstable /// ABI. seen: WeakSet, /// Pr...
); } #[wasm_bindgen_test] fn repeated_siblings_are_not_cycles() { let with_siblings = js_sys::Function::new_no_args( r#" let root = { child: { nested: [] } }; let repeated_child = { foo: "bar" }; root.child.nested.push(repeated_child); ...
{ let with_cycles = js_sys::Function::new_no_args( r#" let root = { child: { nested: [] } }; root.child.nested.push(root); return root; "#, ) .call0(&JsValue::null()) .unwrap(); assert_eq!( with_cycles.pretty()....
identifier_body
readfile.py
map.josm.data.Preferences as Preferences; import org.openstreetmap.josm.data.osm.OsmPrimitive as OsmPrimitive; import org.openstreetmap.josm.data.projection.Projection; import org.openstreetmap.josm.Main as Main; import org.openstreetmap.josm.gui.layer.OsmDataLayer; import org.openstreetmap.josm.gui.progress.NullProgre...
def isInPolygon(n, polygon) : return Geometry.nodeInsidePolygon(n, polygon); def sameLayers( w1, w2) : if w1.get("layer") is not None : l1 = w1.get("layer") else : l1 = "0"; if w2.get("layer") is not None : l2 = w2.get("layer") ...
print "visitw:" # print w if (w.isUsable() and w.isClosed() and isBuilding(w)) : self.primitivesToCheck.add(w) self.index.add(w) print "added"
identifier_body
readfile.py
map.josm.data.Preferences as Preferences; import org.openstreetmap.josm.data.osm.OsmPrimitive as OsmPrimitive; import org.openstreetmap.josm.data.projection.Projection; import org.openstreetmap.josm.Main as Main; import org.openstreetmap.josm.gui.layer.OsmDataLayer; import org.openstreetmap.josm.gui.progress.NullProgre...
( w1, w2) : if w1.get("layer") is not None : l1 = w1.get("layer") else : l1 = "0"; if w2.get("layer") is not None : l2 = w2.get("layer") else : l2 ="0"; return l1.equals(l2); def evaluate
sameLayers
identifier_name
readfile.py
][columnIndex] = aValue def refresh(self): if len(self) > 0: self.fireTableRowsUpdated(0, len(self) - 1) def _validateColumn(self, column, index): #column = DelegateTableModel._validateColumn(self, column, index) self._getters[index] = lambda row: row.get(column[2]) r...
continue
conditional_block
readfile.py
.osm.OsmPrimitive as OsmPrimitive; import org.openstreetmap.josm.data.projection.Projection; import org.openstreetmap.josm.Main as Main; import org.openstreetmap.josm.gui.layer.OsmDataLayer; import org.openstreetmap.josm.gui.progress.NullProgressMonitor as NullProgressMonitor; import org.openstreetmap.josm.gui.progress...
def evaluateNode(self,p,obj): print "te" # print p # print obj
random_line_split
common.js
= new $.fn.Global(); // ajax json call - 비동기 방식(기본:로딩 화면 있음) JsonCall = function (url, params, reCall, showLoading) { //params = "paramList=" + JSON.stringify(params); if (showLoading == undefined) { showLoading = true; } try { if (showLoading) global.showLoading(true);...
때 : 010-222-3333 hp1 = phoneNum.substring(0, 3); hp2 = phoneNum.substring(4, 7); hp3 = phoneNum.substring(8); } else if (hpLen == 11) {// 11자리 번호 일때 : 01022223333 hp1 = phoneNum.substring(0, 3); hp2 = phoneNum.substring(3, 7); hp3 = phoneNum.substring(7); } else i...
{// 12자리 번호 일
identifier_name
common.js
= new $.fn.Global(); // ajax json call - 비동기 방식(기본:로딩 화면 있음) JsonCall = function (url, params, reCall, showLoading) { //params = "paramList=" + JSON.stringify(params); if (showLoading == undefined) { showLoading = true; } try { if (showLoading) global.showLoading(true);...
//ajax json call - 동기 방식(로딩 화면 없음) JsonCallSync = function (url, params, reCall) { //params = "paramList=" + JSON.stringify(params); try { $.ajax({ type: "post", async: false, url: url + "?nocashe=" + String(Math.random()), //dataType: "json", ...
};
random_line_split
common.js
= new $.fn.Global(); // ajax json call - 비동기 방식(기본:로딩 화면 있음) JsonCall = function (url, params, reCall, showLoading) { //params = "paramList=" + JSON.stringify(params); if (showLoading == undefined) { showLoading = true; } try { if (showLoading) global.showLoading(true);...
pLen == 10) {// 10자리 번호 일때 : 0102223333 hp1 = phoneNum.substring(0, 3); hp2 = phoneNum.substring(3, 6); hp3 = phoneNum.substring(6); } else { hp1 = phoneNum.substring(0, 3); hp2 = phoneNum.substring(3, 7); hp3 = phoneNum.substring(7); } hpArray.push(hp1); ...
010-222-3333 hp1 = phoneNum.substring(0, 3); hp2 = phoneNum.substring(4, 7); hp3 = phoneNum.substring(8); } else if (hpLen == 11) {// 11자리 번호 일때 : 01022223333 hp1 = phoneNum.substring(0, 3); hp2 = phoneNum.substring(3, 7); hp3 = phoneNum.substring(7); } else if (...
identifier_body
common.js
= new $.fn.Global(); // ajax json call - 비동기 방식(기본:로딩 화면 있음) JsonCall = function (url, params, reCall, showLoading) { //params = "paramList=" + JSON.stringify(params); if (showLoading == undefined) { showLoading = true; } try { if (showLoading) global.showLoading(true);...
"href", "/com/main.do"); } //팝업창을 띠운다 //sUrl - 띠울 URL //sFrame - 띠울이름 //sFeature - 창 속성 openDialog = function (sUrl, sFrame, sFeature) { var op = window.open(sUrl, sFrame, sFeature); return op; } var ctrlDown = false; //숫자만 입력 Input Key Event //params> //return> //$("#userName").attr("onkeydown", "onlyNumberI...
.push(hp1); hpArray.push(hp2); hpArray.push(hp3); return hpArray; } //메인 화면으로 이동 한다. //params> //return> goToMain = function () { $(location).attr(
conditional_block
renderer.rs
32); let number_of_cameras = self.scene.cameras.len(); self.renderer_output_pixels.push(RendererOutputPixel::new(y, x)); let last_pos = self.renderer_output_pixels.len()-1; let mut pcg: Pcg32 = Pcg32::from_entropy(); let mut colors: Vec<[f64; 3]> = Vec::new(); let mut converged = false; // Loop over this ...
(&self, colors: &[[f64; 3]], number_of_batches: usize, batch_size: usize) -> Vec<[f64; 3]> { let mut averages: Vec<[f64; 3]> = vec![[0.0, 0.0, 0.0]; number_of_batches]; for i in 0..colors.len() { averages[i/batch_size] = add(averages[i/batch_size], colors[i]); } for average in &mut averages { *average = m...
averages
identifier_name
renderer.rs
32); let number_of_cameras = self.scene.cameras.len(); self.renderer_output_pixels.push(RendererOutputPixel::new(y, x)); let last_pos = self.renderer_output_pixels.len()-1; let mut pcg: Pcg32 = Pcg32::from_entropy(); let mut colors: Vec<[f64; 3]> = Vec::new(); let mut converged = false; // Loop over this ...
} } let max_r_distance = (largest[0]-smallest[0]).abs(); let max_g_distance = (largest[1]-smallest[1]).abs(); let max_b_distance = (largest[2]-smallest[2]).abs(); max_r_distance+max_g_distance+max_b_distance } fn create_hitpoint_path(&mut self, mut ray: &mut Ray, color: &mut [f64; 3], hitpoint_path: &m...
{ largest[j] = average[j]; }
conditional_block
renderer.rs
y, error, self.maximum_error); } } } // @TODO: Fix so that it works even if colors.len()%batch_size != 0. fn averages(&self, colors: &[[f64; 3]], number_of_batches: usize, batch_size: usize) -> Vec<[f64; 3]> { let mut averages: Vec<[f64; 3]> = vec![[0.0, 0.0, 0.0]; number_of_batches]; for i in 0..colors.l...
} let distance = cylinder.distance(&ray); if distance < min_distance { min_distance = distance; closest_renderer_shape_index = Some(i);
random_line_split
renderer.rs
_of_batches, batch_size); self.gamma_correct_averages(&mut averages); let use_standard_deviation = true; let error = if use_standard_deviation { self.standard_deviation(&averages) } else { self.maximum_distance(&averages) }; if error < self.maximum_error || iterations*self.spp_per_iteration >=...
{ self.renderer_output_pixels[last_pos].pixel.color = add(self.renderer_output_pixels[last_pos].pixel.color, color); self.renderer_output_pixels[last_pos].color = add(self.renderer_output_pixels[last_pos].color, color); self.renderer_output_pixels[last_pos].number_of_bin_elements += 1; if self.perform_post_proc...
identifier_body
de.rs
(&self) -> &str { "aa" //self.msg.as_str() } } pub fn from_bytes<'de, T>(s: &'de [u8]) -> Result<T> where T: Deserialize<'de>, { let mut de: Deserializer = Deserializer::new(s); T::deserialize(&mut de) } pub fn from_bytes_with_hash<'de, T>(s: &'de [u8]) -> Result<(T, Vec<u8>)> where ...
description
identifier_name
de.rs
&[u8]) -> Result<Torrent> { let (meta, info_hash): (MetaTorrent, Vec<u8>) = from_bytes_with_hash(s)?; if meta.info.pieces.len() % 20 != 0 { return Err(DeserializeError::UnalignedPieces); } match &meta.info.files { InfoFile::Multiple { files, .. } => { if files.is_empty() {...
{ #[derive(Deserialize, PartialEq, Debug)] struct Dict<'b> { a: i64, b: &'b str, c: &'b str, X: &'b str, } let bc: Dict = from_bytes(b"d1:ai12453e1:b3:aaa1:c3:bbb1:X10:0123456789e").unwrap(); assert_eq!( bc, ...
identifier_body
de.rs
description(&self) -> &str { "aa" //self.msg.as_str() } } pub fn from_bytes<'de, T>(s: &'de [u8]) -> Result<T> where T: Deserialize<'de>, { let mut de: Deserializer = Deserializer::new(s); T::deserialize(&mut de) } pub fn from_bytes_with_hash<'de, T>(s: &'de [u8]) -> Result<(T, Vec<u8...
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { // println!("NEXT: {:?}", self.peek()); match self.peek().ok_or(DeserializeError::UnexpectedEOF)? { b'i' => { // println!("FOUND NUMBER", ); visitor.visit...
#[doc(hidden)] impl<'a, 'de> serde::de::Deserializer<'de> for &'a mut Deserializer<'de> { type Error = DeserializeError;
random_line_split
main.rs
let device_extensions = DeviceExtensions { khr_swapchain: true, ..DeviceExtensions::empty() }; let (physical_device, queue_family_index) = instance .enumerate_physical_devices() .unwrap() .filter(|p| p.supported_extensions().contains(&device_extensions)) .fil...
{ // The start of this example is exactly the same as `triangle`. You should read the `triangle` // example if you haven't done so yet. let event_loop = EventLoop::new(); let library = VulkanLibrary::new().unwrap(); let required_extensions = Surface::required_extensions(&event_loop); let insta...
identifier_body
main.rs
() { // The start of this example is exactly the same as `triangle`. You should read the `triangle` // example if you haven't done so yet. let event_loop = EventLoop::new(); let library = VulkanLibrary::new().unwrap(); let required_extensions = Surface::required_extensions(&event_loop); let in...
main
identifier_name
main.rs
as `triangle`. You should read the `triangle` // example if you haven't done so yet. let event_loop = EventLoop::new(); let library = VulkanLibrary::new().unwrap(); let required_extensions = Surface::required_extensions(&event_loop); let instance = Instance::new( library, Instance...
event_loop.run(move |event, _, control_flow| { match event { Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { *control_flow = ControlFlow::Exit; } Event::WindowEvent { event: Wi...
let descriptor_set_allocator = StandardDescriptorSetAllocator::new(device.clone()); let command_buffer_allocator = StandardCommandBufferAllocator::new(device.clone(), Default::default());
random_line_split
c8.go
else { cmd = Next{} } case 0x5: log.Println("5xy0 - SE") if vx == vy { cmd = Skip{} } else { cmd = Next{} } case 0x6: log.Println("6xkk - LD") cpu.v[x] = kk cmd = Next{} case 0x7: log.Println("7xkk - ADD") cpu.v[x] += kk cmd = Next{} case 0x8: switch o4 { case 0x0: log.Println...
{ cmd = Skip{} }
conditional_block
c8.go
func keytohex(key ebiten.Key) uint16 { if key >= 43 && key <= 52 { return uint16(key) - 43 } else { return uint16(key) + 0x10 } } type Cpu struct { v [64]uint8 i uint16 stack [16]uint16 sp uint16 pc uint16 dt uint16 st uint16 rnd *rand.Rand lastd time.Time lasts time.Time } fu...
{ kb.queue = []uint16{} }
identifier_body
c8.go
log.Println("Fx29 - LD F") cpu.i = vx * 5 cmd = Next{} case 0x3: log.Println("Fx33 - LD B") mem.buf[cpu.i] = (uint8(vx) / 100) % 10 mem.buf[cpu.i+1] = (uint8(vx) / 10) % 10 mem.buf[cpu.i+2] = uint8(vx) % 10 cmd = Next{} case 0x5: log.Println("Fx55 - LD [I]") for n := 0; n <= int(x); n+...
NewUI
identifier_name
c8.go
= Skip{} } else { cmd = Next{} } case 0xA: log.Println("Annn - LD I") cpu.i = nnn cmd = Next{} case 0xB: log.Println("Bnnn - JP") cmd = Jump{nnn + uint16(cpu.v[0])} case 0xC: log.Println("Cxkk - RND") cpu.v[x] = cpu.rand() & kk cmd = Next{} case 0xD: log.Println("DRW - Vx, Vy, nibble") n...
// Check collision.
random_line_split
fmlrc2.rs
() { //initialize logging for our benefit later env_logger::from_env(env_logger::Env::default().default_filter_or("info")).init(); //non-cli parameters const JOB_SLOTS: u64 = 10000; const UPDATE_INTERVAL: u64 = 10000; //this is the CLI block, params that get populated appear before let...
main
identifier_name
fmlrc2.rs
= 10000; //this is the CLI block, params that get populated appear before let bwt_fn: String; let long_read_fn: String; let corrected_read_fn: String; let mut kmer_sizes: Vec<usize> = vec![21, 59]; let mut threads: usize = 1; let mut begin_id: u64 = 0; let mut end_id: u64 = 0xFFFFF...
.help("The FASTA file to write corrected reads to") .required(true) .index(3)) .get_matches(); //pull out required values bwt_fn = matches.value_of("COMP_MSBWT.NPY").unwrap().to_string(); long_read_fn = matches.value_of("LONG_READS.FA").unwrap().to_string(); ...
.index(2)) .arg(Arg::with_name("CORRECTED_READS.FA")
random_line_split
fmlrc2.rs
f64 = 0.1; let mut branch_factor: f64 = 4.0; let mut cache_size: usize = 8; let verbose_mode: bool; let matches = App::new("FMLRC2") .version(VERSION.unwrap_or("?")) .author("J. Matthew Holt <jholt@hudsonalpha.org>") .about("FM-index Long Read Corrector - Rust implementatio...
{ let rx_value: CorrectionResults = rx.recv().unwrap(); if verbose_mode { info!("Job #{:?}: {:.2} -> {:.2}", rx_value.read_index, rx_value.avg_before, rx_value.avg_after); } match fasta_writer.wri...
conditional_block
fmlrc2.rs
let verbose_mode: bool; let matches = App::new("FMLRC2") .version(VERSION.unwrap_or("?")) .author("J. Matthew Holt <jholt@hudsonalpha.org>") .about("FM-index Long Read Corrector - Rust implementation") .arg(Arg::with_name("verbose_mode") .short("v") ....
{ //initialize logging for our benefit later env_logger::from_env(env_logger::Env::default().default_filter_or("info")).init(); //non-cli parameters const JOB_SLOTS: u64 = 10000; const UPDATE_INTERVAL: u64 = 10000; //this is the CLI block, params that get populated appear before let bw...
identifier_body
flask_main.py
not in flask.session: init_session_values() return render_template('index.html') @app.route("/choose") def choose(): ## We'll need authorization to list calendars ## I wanted to put what follows into a function, but had ## to pull it back here because the redirect has to be a ## 'return' a...
return credentials def get_gcal_service(credentials): """ We need a Google calendar 'service' object to obtain list of calendars, busy times, etc. This requires authorization. If authorization is already in effect, we'll just return with the authorization. Otherwise, control flow will be interrupted...
return None
conditional_block
flask_main.py
not in flask.session: init_session_values() return render_template('index.html') @app.route("/choose") def choose(): ## We'll need authorization to list calendars ## I wanted to put what follows into a function, but had ## to pull it back here because the redirect has to be a ## 'return' a...
service = discovery.build('calendar', 'v3', http=http_auth) app.logger.debug("Returning service") return service @app.route('/oauth2callback') def oauth2callback(): """ The 'flow' has this one place to call back to. We'll enter here more than once as steps in the flow are completed, and need to keep tra...
random_line_split
flask_main.py
not in flask.session: init_session_values() return render_template('index.html') @app.route("/choose") def choose(): ## We'll need authorization to list calendars ## I wanted to put what follows into a function, but had ## to pull it back here because the redirect has to be a ## 'return' a...
( text ): """ Read time in a human-compatible format and interpret as ISO format with local timezone. May throw exception if time can't be interpreted. In that case it will also flash a message explaining accepted formats. """ app.logger.debug("Decoding time '{}'".format(text)) time_form...
interpret_time
identifier_name
flask_main.py
.session: init_session_values() return render_template('index.html') @app.route("/choose") def choose(): ## We'll need authorization to list calendars ## I wanted to put what follows into a function, but had ## to pull it back here because the redirect has to be a ## 'return' app.logger.deb...
""" Convert text of date to ISO format used internally, with the local time zone. """ try: as_arrow = arrow.get(text, "MM/DD/YYYY").replace( tzinfo=tz.tzlocal()) except: flask.flash("Date '{}' didn't fit expected format 12/31/2001") raise return as_arrow.isoformat...
identifier_body
root.go
// Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := RootCmd.Execute(); err != nil { fatal(err.Error(), 1) } } var varApiKey = "CRONITOR_API_KEY" var varHostname = "CRONITOR_HOS...
() string { if runtime.GOOS == "windows" { return fmt.Sprintf("%s\\ProgramData\\Cronitor", os.Getenv("SYSTEMDRIVE")) } return "/etc/cronitor" } func truncateString(s string, length int) string { if len(s) <= length { return s } return s[:length] } func printSuccessText(message string, indent bool) { if i...
defaultConfigFileDirectory
identifier_name
root.go
// Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := RootCmd.Execute(); err != nil { fatal(err.Error(), 1) } } var varApiKey = "CRONITOR_API_KEY" var varHostname = "CRONITOR_HOS...
color := color.New(color.FgHiGreen) if indent { color.Println(fmt.Sprintf(" |--► %s", message)) } else { color.Println(fmt.Sprintf("----► %s", message)) } } } func printDoneText(message string, indent bool) { if isAuto
func printSuccessText(message string, indent bool) { if isAutoDiscover || isSilent { log(message) } else {
random_line_split
root.go
CRONITOR_LOG" var varPingApiKey = "CRONITOR_PING_API_KEY" var varExcludeText = "CRONITOR_EXCLUDE_TEXT" var varConfig = "CRONITOR_CONFIG" func init() { userAgent = fmt.Sprintf("CronitorCLI/%s", Version) cobra.OnInitialize(initConfig) // Here you will define your flags and configuration settings. // Cobra supports ...
olor.Println(fmt.Sprintf(" |--► %s", message)) } else {
conditional_block
root.go
// Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := RootCmd.Execute(); err != nil { fatal(err.Error(), 1) } } var varApiKey = "CRONITOR_API_KEY" var varHostname = "CRONITOR_HOS...
func printSuccessText(message string, indent bool) { if isAutoDiscover || isSilent { log(message) } else { color := color.New(color.FgHiGreen) if indent { color.Println(fmt.Sprintf(" |--► %s", message)) } else { color.Println(fmt.Sprintf("----► %s", message)) } } } func printDoneText(message stri...
{ if len(s) <= length { return s } return s[:length] }
identifier_body
browser.rs
page pub async fn new_page(&self, params: impl Into<CreateTargetParams>) -> Result<Page> { let (tx, rx) = oneshot_channel(); let mut params = params.into(); if let Some(id) = self.browser_context.id() { if params.browser_context_id.is_none() { params.browser_cont...
self.args.push(arg.into());
random_line_split
browser.rs
_timeout: config.request_timeout, }; let fut = Handler::new(conn, rx, handler_config); let browser_context = fut.default_browser_context().clone(); let browser = Self { sender: tx, config: Some(config), child: Some(child), debug_ws_url, ...
} } else { line = String::new(); } } } cfg_if::cfg_if! { if #[cfg(feature = "async-std-runtime")] { async_std::task::spawn_blocking(|| read_debug_url(stdout)).await } else if #[cfg(feature = "tokio-runtime")] { ...
{ return ws.trim().to_string(); }
conditional_block
browser.rs
height. window_size: Option<(u32, u32)>, /// Launch the browser with a specific debugging port. port: u16, /// Path for Chrome or Chromium. /// /// If unspecified, the create will try to automatically detect a suitable /// binary. executable: std::path::PathBuf, /// A list of Chrom...
{ if let Ok(path) = std::env::var("CHROME") { if std::path::Path::new(&path).exists() { return Ok(path.into()); } } for app in &[ "google-chrome-stable", "chromium", "chromium-browser", "chrome", "chrome-browser", ] { if let Ok...
identifier_body
browser.rs
(config: BrowserConfig) -> Result<(Self, Handler)> { // launch a new chromium instance let mut child = config.launch()?; // extract the ws: let get_ws_url = ws_url_from_output(&mut child); let dur = Duration::from_secs(20); cfg_if::cfg_if! { if #[cfg(featur...
launch
identifier_name
pybatch_mast.py
None, ]: # NOTE n_genes is always assumed as covariate if bys is None: if min_perc is not None: adata = adata.copy() if on_total: total_cells = adata.shape[0] else: total_cells = adata.obs[group].val...
( self, adata: AnnData, remote_dir: str, keys: Sequence[str], group: str, covs: str = '', ready: Optional[Sequence[str]] = None, jobs: int = 1, ) -> str: s3 = bt.resource('s3') if ready is None: ready = [] with tempf...
_mast_prep
identifier_name
pybatch_mast.py
s, group, keys, jobs=jobs, ) else: print('Not enough genes, computation skipped') try: de, top = self.mast_prep_output(job_collection, lfc, fdr) except ClientError as e: raise MASTCollectionError(e, job_collection) from ...
content = None if remote_dir is None: remote_dir = os.path.join('mast', str(uuid.uuid4())) ready = [] else: ready = ['mat', 'cdat'] manifest = self._mast_prep( adata, remote_dir, keys, group, covs=covs, ready=ready, jobs=jobs, ) job...
identifier_body
pybatch_mast.py
None, ]: # NOTE n_genes is always assumed as covariate if bys is None: if min_perc is not None: adata = adata.copy() if on_total: total_cells = adata.shape[0] else: total_cells = adata.obs[group].val...
local_manifest, self.bucket, remote_manifest, ) return remote_manifest def _mast_submit( self, manifest: str, block: bool = False, job_name: str = 'mast', ) -> str: batch = bt.client('batch') job_manifest = f's3://{os.path.join...
print('Uploading manifest to s3...') s3.meta.client.upload_file(
random_line_split
pybatch_mast.py
None, ]: # NOTE n_genes is always assumed as covariate if bys is None: if min_perc is not None: adata = adata.copy() if on_total: total_cells = adata.shape[0] else: total_cells = adata.obs[group].val...
try: de, top = self.mast_prep_output(job_collection, lfc, fdr) except ClientError as e: raise MASTCollectionError(e, job_collection) from e except Exception as e: raise MASTCollectionError(e.message, job_collection) from e ...
print('Not enough genes, computation skipped')
conditional_block
imap-client.js
: function(){ this.parser = null; }, onEvent: function(event, message, data, request){ log("onEvent: " + event); log(data); this.block(false); switch(event){ case "onLogin": this.onLogin(true); //this.select(); break; case "onLoginFailed": this.onLogin(false); ...
parseEnvelope: function(matches){ var fields = qw("id flags date subject from to"); var data = {}; Every(fields, function(k, i){ if(k == "from" || k == "to"){ var m = /(NIL|\".*?\")\s+(NIL|\".*?\")\s+(NIL|\".*?\")\s+(NIL|\".*?\")/ .exec(matches[i]).slice(1); Every(m, function(v, i){ ...
} return result; },
random_line_split
kubernetes.go
// Get services p.log.Debugf("fetching kubernetes services") services, servicesErr := p.client.ListServices("", nil) if nodesErr != nil || servicesErr != nil { if nodesErr != nil { p.log.Warningf("Failed to fetch kubernetes nodes: %#v (using previous ones)", nodesErr) } if servicesErr != nil { p.log.Wa...
{ continue }
conditional_block