file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
lib.rs
//! # docker-bisect //! `docker-bisect` create assumes that the docker daemon is running and that you have a //! docker image with cached layers to probe. extern crate colored; extern crate dockworker; extern crate indicatif; extern crate rand; use std::clone::Clone; use std::fmt; use std::io::{prelude::*, Error, Erro...
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
//! # docker-bisect //! `docker-bisect` create assumes that the docker daemon is running and that you have a //! docker image with cached layers to probe. extern crate colored; extern crate dockworker; extern crate indicatif; extern crate rand; use std::clone::Clone; use std::fmt; use std::io::{prelude::*, Error, Erro...
} fn lay(id: usize) -> Layer { Layer { height: id, image_name: id.to_string(), creation_command: id.to_string(), } } #[test] fn if_output_always_same_return_earliest_command() { let results = get_changes( vec![lay(1), lay(2),...
{}
identifier_body
meanS1.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Dec 3 17:41:11 2019 @author: catherine """ import numpy as np #from sklearn.model_selection import train_test_split import random from interval import Interval #m is the number of anchors #p is the dimension of every X_ti #Theta is a low rank matrix o...
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
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Dec 3 17:41:11 2019 @author: catherine """ import numpy as np #from sklearn.model_selection import train_test_split import random from interval import Interval #m is the number of anchors #p is the dimension of every X_ti #Theta is a low rank matrix o...
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
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Dec 3 17:41:11 2019 @author: catherine """ import numpy as np #from sklearn.model_selection import train_test_split import random from interval import Interval #m is the number of anchors #p is the dimension of every X_ti #Theta is a low rank matrix o...
(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
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Dec 3 17:41:11 2019 @author: catherine """ import numpy as np #from sklearn.model_selection import train_test_split import random from interval import Interval #m is the number of anchors #p is the dimension of every X_ti #Theta is a low rank matrix o...
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
use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::fmt::Debug; /// `InputCellID` is a unique identifier for an input cell. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct InputCellID(usize); /// `ComputeCellID` is a unique identifier for a compute cell. /// Values of type ...
} // 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
use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::fmt::Debug; /// `InputCellID` is a unique identifier for an input cell. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct InputCellID(usize); /// `ComputeCellID` is a unique identifier for a compute cell. /// Values of type ...
} 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
use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::fmt::Debug; /// `InputCellID` is a unique identifier for an input cell. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct InputCellID(usize); /// `ComputeCellID` is a unique identifier for a compute cell. /// Values of type ...
() -> 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
import os from typing import List import numpy from aubio import notes, source, pitch, tempo from midiutil import MIDIFile from midiutil.MidiFile import TICKSPERQUARTERNOTE, NoteOn from pydub import AudioSegment from model.channel import channel_map, CHANNEL_NAME_DRUM_KIT from model.note import Note, drum_map def c...
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
import os from typing import List import numpy from aubio import notes, source, pitch, tempo from midiutil import MIDIFile from midiutil.MidiFile import TICKSPERQUARTERNOTE, NoteOn from pydub import AudioSegment from model.channel import channel_map, CHANNEL_NAME_DRUM_KIT from model.note import Note, drum_map def c...
REF_BPM = 90 BOTTOM_BPM = 50 def normalize_bpm(bpm: int): """ presume that general bpm of voice result is in range of 50 - 200 and we may want to center speed to 90 as reference. so the algorithm could be: gap = abs(90 - x) result = 50 + gap :param bpm: :return: """ return ab...
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
import os from typing import List import numpy from aubio import notes, source, pitch, tempo from midiutil import MIDIFile from midiutil.MidiFile import TICKSPERQUARTERNOTE, NoteOn from pydub import AudioSegment from model.channel import channel_map, CHANNEL_NAME_DRUM_KIT from model.note import Note, drum_map def c...
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
import os from typing import List import numpy from aubio import notes, source, pitch, tempo from midiutil import MIDIFile from midiutil.MidiFile import TICKSPERQUARTERNOTE, NoteOn from pydub import AudioSegment from model.channel import channel_map, CHANNEL_NAME_DRUM_KIT from model.note import Note, drum_map def c...
# 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
package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "log" "net/http" "os" "time" _ "github.com/lib/pq" "github.com/jmoiron/sqlx" // _ "github.com/mattn/go-sqlite3" ) // Ия файла базы данных SQLite var dbFileName = "rg.db" // DSN параметры подсоединения к postgresql var DSN = os.Getenv("RGDSN"...
conditional_block
save_articles.go
package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "log" "net/http" "os" "time" _ "github.com/lib/pq" "github.com/jmoiron/sqlx" // _ "github.com/mattn/go-sqlite3" ) // Ия файла базы данных SQLite var dbFileName = "rg.db" // DSN параметры подсоединения к postgresql var DSN = os.Getenv("RGDSN"...
тексты статей 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
package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "log" "net/http" "os" "time" _ "github.com/lib/pq" "github.com/jmoiron/sqlx" // _ "github.com/mattn/go-sqlite3" ) // Ия файла базы данных SQLite var dbFileName = "rg.db" // DSN параметры подсоединения к postgresql var DSN = os.Getenv("RGDSN"...
ные запросы к 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
package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "log" "net/http" "os" "time" _ "github.com/lib/pq" "github.com/jmoiron/sqlx" // _ "github.com/mattn/go-sqlite3" ) // Ия файла базы данных SQLite var dbFileName = "rg.db" // DSN параметры подсоединения к postgresql var DSN = os.Getenv("RGDSN"...
} // Получает количество новых записей в таблице 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
#!/usr/bin/python from bisect import * from copy import * import sys import json import numpy from pylab import * key_time = 'timestamp' key_value = 'value' key_counts = 'counts' key_energies = 'energies' key_lightvar = 'lightvariance' key_id = 'id' key_survey = 'survey' key_interval = 'interval' key_label = 'label...
''' 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
#!/usr/bin/python from bisect import * from copy import * import sys import json import numpy from pylab import * key_time = 'timestamp' key_value = 'value' key_counts = 'counts' key_energies = 'energies' key_lightvar = 'lightvariance' key_id = 'id' key_survey = 'survey' key_interval = 'interval' key_label = 'label...
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
#!/usr/bin/python from bisect import * from copy import * import sys import json import numpy from pylab import * key_time = 'timestamp' key_value = 'value' key_counts = 'counts' key_energies = 'energies' key_lightvar = 'lightvariance' key_id = 'id' key_survey = 'survey' key_interval = 'interval' key_label = 'label...
(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
#!/usr/bin/python from bisect import * from copy import * import sys import json import numpy from pylab import * key_time = 'timestamp' key_value = 'value' key_counts = 'counts' key_energies = 'energies' key_lightvar = 'lightvariance' key_id = 'id' key_survey = 'survey' key_interval = 'interval' key_label = 'label...
return segments ''' build series of observation data at fixed intervals for training HMMs ''' def compute_log_variance(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) ...
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
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup import codecs from time import sleep import re levels = {u'федеральный': 'federal', u'региональный': 'subject', u'административный центр': 'local', u'местное самоуправление': 'local'} PATTERNS_LIN...
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
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup import codecs from time import sleep import re levels = {u'федеральный': 'federal', u'региональный': 'subject', u'административный центр': 'local', u'местное самоуправление': 'local'} PATTERNS_LIN...
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
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup import codecs from time import sleep import re levels = {u'федеральный': 'federal', u'региональный': 'subject', u'административный центр': 'local', u'местное самоуправление': 'local'} PATTERNS_LIN...
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
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup import codecs from time import sleep import re levels = {u'федеральный': 'federal', u'региональный': 'subject', u'административный центр': 'local', u'местное самоуправление': 'local'} PATTERNS_LIN...
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
//! This file will run at build time to autogenerate the WASI regression tests //! It will compile the files indicated in TESTS, to:executable and .wasm //! - Compile with the native rust target to get the expected output //! - Compile with the latest WASI target to get the wasm //! - Generate the test that will compar...
#[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
//! This file will run at build time to autogenerate the WASI regression tests //! It will compile the files indicated in TESTS, to:executable and .wasm //! - Compile with the native rust target to get the expected output //! - Compile with the latest WASI target to get the wasm //! - Generate the test that will compar...
} 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
//! This file will run at build time to autogenerate the WASI regression tests //! It will compile the files indicated in TESTS, to:executable and .wasm //! - Compile with the native rust target to get the expected output //! - Compile with the latest WASI target to get the wasm //! - Generate the test that will compar...
(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
//! This file will run at build time to autogenerate the WASI regression tests //! It will compile the files indicated in TESTS, to:executable and .wasm //! - Compile with the native rust target to get the expected output //! - Compile with the latest WASI target to get the wasm //! - Generate the test that will compar...
} /// The options provied when executed a WASI Wasm program #[derive(Debug, Default, Serialize, Deserialize)] pub struct WasiOptions { /// Mapped pre-opened dirs pub mapdir: Vec<(String, String)>, /// Environment vars pub env: Vec<(String, String)>, /// Program arguments pub args: Vec<String>,...
{ 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
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $.fn.randomize = function(selector){ (selector ? this.find(selector) : this).parent().each(function(){ $(this).children(s...
else { $("#option-" + j).show(); $("#label-" + j).text(option); } } $("#sets")[0].scrollTop = 0; $("#sets").randomize("label"); $("input[name=set]:checked").removeProp("checked"); } function goBack() { $("#content").hide(); $("#animal-selector").show();...
{ $("#option-" + j).hide(); }
conditional_block
biology.js
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $.fn.randomize = function(selector){ (selector ? this.find(selector) : this).parent().each(function(){ $(this).children(s...
] ]; function setOptions(i, k) { 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 { ...
"quadrangularis: A species for grey sea cucumbers with prominent tapering papillae along the corners of their squarish bodies." ]
random_line_split
biology.js
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $.fn.randomize = function(selector){ (selector ? this.find(selector) : this).parent().each(function(){ $(this).children(s...
(i, k) { 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)...
setOptions
identifier_name
biology.js
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $.fn.randomize = function(selector){ (selector ? this.find(selector) : this).parent().each(function(){ $(this).children(s...
function goBack() { $("#content").hide(); $("#animal-selector").show(); $("#toolbar").hide(); } $(window).load(function() { goBack(); $("#check-button").click(function() { var id = parseInt($("input[name=set]:checked").val()); if(isNaN(id) || id > 5 || id < 1) return; ...
{ 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
/* * Register angular module with custom name myapp, all other Angular objects will add it to this custom angular module, * Here Other Anulag objects used are Controller, Service, RouteProvider etc. **/ // TODO: standardize module and function descriptions, maybe using jsdoc 'use strict'; var myapp = angular.mod...
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
/* * Register angular module with custom name myapp, all other Angular objects will add it to this custom angular module, * Here Other Anulag objects used are Controller, Service, RouteProvider etc. **/ // TODO: standardize module and function descriptions, maybe using jsdoc 'use strict'; var myapp = angular.mod...
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
/* * Register angular module with custom name myapp, all other Angular objects will add it to this custom angular module, * Here Other Anulag objects used are Controller, Service, RouteProvider etc. **/ // TODO: standardize module and function descriptions, maybe using jsdoc 'use strict'; var myapp = angular.mod...
(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
/* * Register angular module with custom name myapp, all other Angular objects will add it to this custom angular module, * Here Other Anulag objects used are Controller, Service, RouteProvider etc. **/ // TODO: standardize module and function descriptions, maybe using jsdoc 'use strict'; var myapp = angular.mod...
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
use super::{cmd, Expression}; use std; use std::collections::HashMap; use std::env; use std::env::consts::EXE_EXTENSION; use std::ffi::OsString; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::process::Command; use std::str; use std::sync::{Arc, Once}; // Include a cop...
() { // 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
use super::{cmd, Expression}; use std; use std::collections::HashMap; use std::env; use std::env::consts::EXE_EXTENSION; use std::ffi::OsString; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::process::Command; use std::str; use std::sync::{Arc, Once}; // Include a cop...
else { assert_eq!(output1, "abc123"); } } #[test] fn test_broken_pipe() { // If the input writing thread fills up its pipe buffer, writing will block. If the process // on the other end of the pipe exits while writer is waiting, the write will return an // error. We need to swallow that error,...
{ assert_eq!(output1, ""); }
conditional_block
test.rs
use super::{cmd, Expression}; use std; use std::collections::HashMap; use std::env; use std::env::consts::EXE_EXTENSION; use std::ffi::OsString; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::process::Command; use std::str; use std::sync::{Arc, Once}; // Include a cop...
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
use super::{cmd, Expression}; use std; use std::collections::HashMap; use std::env; use std::env::consts::EXE_EXTENSION; use std::ffi::OsString; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::process::Command; use std::str; use std::sync::{Arc, Once}; // Include a cop...
#[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
package workqueue import ( "bytes" "context" "encoding/hex" "errors" "time" "github.com/apex/log" "github.com/gocraft/work" "github.com/gomodule/redigo/redis" pkgErrors "github.com/pkg/errors" "gopkg.in/tomb.v2" "git.scc.kit.edu/sdm/lsdf-checksum/internal/lifecycle" "git.scc.kit.edu/sdm/lsdf-checksum/med...
() <-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
package workqueue import ( "bytes" "context" "encoding/hex" "errors" "time" "github.com/apex/log" "github.com/gocraft/work" "github.com/gomodule/redigo/redis" pkgErrors "github.com/pkg/errors" "gopkg.in/tomb.v2" "git.scc.kit.edu/sdm/lsdf-checksum/internal/lifecycle" "git.scc.kit.edu/sdm/lsdf-checksum/med...
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
package workqueue import ( "bytes" "context" "encoding/hex" "errors" "time" "github.com/apex/log" "github.com/gocraft/work" "github.com/gomodule/redigo/redis" pkgErrors "github.com/pkg/errors" "gopkg.in/tomb.v2" "git.scc.kit.edu/sdm/lsdf-checksum/internal/lifecycle" "git.scc.kit.edu/sdm/lsdf-checksum/med...
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
package workqueue import ( "bytes" "context" "encoding/hex" "errors" "time" "github.com/apex/log" "github.com/gocraft/work" "github.com/gomodule/redigo/redis" pkgErrors "github.com/pkg/errors" "gopkg.in/tomb.v2" "git.scc.kit.edu/sdm/lsdf-checksum/internal/lifecycle" "git.scc.kit.edu/sdm/lsdf-checksum/med...
w.WriteBacker.fieldLogger.WithFields(log.Fields{ "write_back_pack": writeBackPack, }).Debug("Received and unmarshaled WriteBackPack") for i := range writeBackPack.Files { // Pointer to file in files, don't copy file := &writeBackPack.Files[i] err := w.WriteBacker.batcher.Add(ctx, file) if err != nil { ...
{ 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
#!/usr/bin/env python3 # Licensed under the Apache License, Version 2.0 or the MIT License. # SPDX-License-Identifier: Apache-2.0 OR MIT # Copyright Tock Contributors 2023. # Prints out the source locations of panics in a Tock kernel ELF # # This tool attempts to trace all panic locations in a Tock kernel ELF by # tr...
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
#!/usr/bin/env python3 # Licensed under the Apache License, Version 2.0 or the MIT License. # SPDX-License-Identifier: Apache-2.0 OR MIT # Copyright Tock Contributors 2023. # Prints out the source locations of panics in a Tock kernel ELF # # This tool attempts to trace all panic locations in a Tock kernel ELF by # tr...
if linkage_name: name = matches_panic_funcs(linkage_name_string) if name: within_core_panic_list.append(panicinfo) continue else: no_info_panic...
raise RuntimeError("Unhandled")
conditional_block
find_panics.py
#!/usr/bin/env python3 # Licensed under the Apache License, Version 2.0 or the MIT License. # SPDX-License-Identifier: Apache-2.0 OR MIT # Copyright Tock Contributors 2023. # Prints out the source locations of panics in a Tock kernel ELF # # This tool attempts to trace all panic locations in a Tock kernel ELF by # tr...
(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
#!/usr/bin/env python3 # Licensed under the Apache License, Version 2.0 or the MIT License. # SPDX-License-Identifier: Apache-2.0 OR MIT # Copyright Tock Contributors 2023. # Prints out the source locations of panics in a Tock kernel ELF # # This tool attempts to trace all panic locations in a Tock kernel ELF by # tr...
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
package kgo import ( "sync" "sync/atomic" "github.com/twmb/franz-go/pkg/kerr" ) func newTopicPartitions() *topicPartitions { parts := new(topicPartitions) parts.v.Store(new(topicPartitionsData)) return parts } // Contains all information about a topic's partitions. type topicPartitions struct { v atomic.Valu...
// 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
package kgo import ( "sync" "sync/atomic" "github.com/twmb/franz-go/pkg/kerr" ) func newTopicPartitions() *topicPartitions { parts := new(topicPartitions) parts.v.Store(new(topicPartitionsData)) return parts } // Contains all information about a topic's partitions. type topicPartitions struct { v atomic.Valu...
old.records.sink.addRecBuf(old.records) // add our record source to the new sink // At this point, the new sink will be draining our records. We lastly // need to copy the records pointer to our new topicPartition. new.records = old.records } // migrateCursorTo is called on metadata update if a topic partition'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
package kgo import ( "sync" "sync/atomic" "github.com/twmb/franz-go/pkg/kerr" ) func newTopicPartitions() *topicPartitions { parts := new(topicPartitions) parts.v.Store(new(topicPartitionsData)) return parts } // Contains all information about a topic's partitions. type topicPartitions struct { v atomic.Valu...
(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
package kgo import ( "sync" "sync/atomic" "github.com/twmb/franz-go/pkg/kerr" ) func newTopicPartitions() *topicPartitions { parts := new(topicPartitions) parts.v.Store(new(topicPartitionsData)) return parts } // Contains all information about a topic's partitions. type topicPartitions struct { v atomic.Valu...
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
//! Pretty printing for Javascript values from [wasm-bindgen](https://docs.rs/wasm-bindgen). #![forbid(unsafe_code)] use js_sys::{ Array, Date, Error, Function, JsString, Map, Object, Promise, Reflect, RegExp, Set, Symbol, WeakSet, }; use std::{ collections::{BTreeMap, BTreeSet, HashSet}, fmt::{Debug,...
; 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
//! Pretty printing for Javascript values from [wasm-bindgen](https://docs.rs/wasm-bindgen). #![forbid(unsafe_code)] use js_sys::{ Array, Date, Error, Function, JsString, Map, Object, Promise, Reflect, RegExp, Set, Symbol, WeakSet, }; use std::{ collections::{BTreeMap, BTreeSet, HashSet}, fmt::{Debug,...
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
//! Pretty printing for Javascript values from [wasm-bindgen](https://docs.rs/wasm-bindgen). #![forbid(unsafe_code)] use js_sys::{ Array, Date, Error, Function, JsString, Map, Object, Promise, Reflect, RegExp, Set, Symbol, WeakSet, }; use std::{ collections::{BTreeMap, BTreeSet, HashSet}, fmt::{Debug,...
#[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); root.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
from java.awt import * from java.awt.event import ActionListener, ActionEvent from java.lang import Object from java.lang import Runnable from java.net import URL from java.util import Collection,HashSet,LinkedList,List,Set from javax.swing import * from javax.swing.table import AbstractTableModel from javax.swing.tabl...
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
from java.awt import * from java.awt.event import ActionListener, ActionEvent from java.lang import Object from java.lang import Runnable from java.net import URL from java.util import Collection,HashSet,LinkedList,List,Set from javax.swing import * from javax.swing.table import AbstractTableModel from javax.swing.tabl...
( 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 evaluateNode(self,p,obj): print ...
sameLayers
identifier_name
readfile.py
from java.awt import * from java.awt.event import ActionListener, ActionEvent from java.lang import Object from java.lang import Runnable from java.net import URL from java.util import Collection,HashSet,LinkedList,List,Set from javax.swing import * from javax.swing.table import AbstractTableModel from javax.swing.tabl...
s = s.lower() s=re.sub(pattern, '', s) #remove whitespace if not s in streets : # print "%s is new" % s streets[s]=JythonWay(p) else : streets[s].addsubobject(p) # print streets.values() objs3= sorted(streets.values(),(la...
continue
conditional_block
readfile.py
from java.awt import * from java.awt.event import ActionListener, ActionEvent from java.lang import Object from java.lang import Runnable from java.net import URL from java.util import Collection,HashSet,LinkedList,List,Set from javax.swing import * from javax.swing.table import AbstractTableModel from javax.swing.tabl...
def endTest2(self): for p in self.primitivesToCheck : collection = self.index.search(p.getBBox()) for object in collection: if (not p.equals(object)): if (isinstance(p,Node)): self.evaluateNode(p, object) ...
def evaluateNode(self,p,obj): print "te" # print p # print obj
random_line_split
common.js
/**************************************** * 공통 상수 선언 ****************************************/ $.fn.Global = function () { this.isLoading = false; this.loadingNum = 0; this.Init(); }; $.fn.Global.prototype = { Init: function () { var G = this; }, showLoading: function (showYN, validateR...
때 : 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
/**************************************** * 공통 상수 선언 ****************************************/ $.fn.Global = function () { this.isLoading = false; this.loadingNum = 0; this.Init(); }; $.fn.Global.prototype = { Init: function () { var G = this; }, showLoading: function (showYN, validateR...
//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
/**************************************** * 공통 상수 선언 ****************************************/ $.fn.Global = function () { this.isLoading = false; this.loadingNum = 0; this.Init(); }; $.fn.Global.prototype = { Init: function () { var G = this; }, showLoading: function (showYN, validateR...
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
/**************************************** * 공통 상수 선언 ****************************************/ $.fn.Global = function () { this.isLoading = false; this.loadingNum = 0; this.Init(); }; $.fn.Global.prototype = { Init: function () { var G = this; }, showLoading: function (showYN, validateR...
"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
use std::f64; use pcg_rand::Pcg32; use rand::{Rng, SeedableRng}; use crate::hitpoint::Hitpoint; use crate::math::{add, brdf, dot, elementwise_mul, intensity_to_color, min, mul, norm, random_from_brdf, sub}; use crate::ray::Ray; use crate::renderershape::RendererShape; use crate::rendereroutputpixel::RendererOutputPix...
(&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
use std::f64; use pcg_rand::Pcg32; use rand::{Rng, SeedableRng}; use crate::hitpoint::Hitpoint; use crate::math::{add, brdf, dot, elementwise_mul, intensity_to_color, min, mul, norm, random_from_brdf, sub}; use crate::ray::Ray; use crate::renderershape::RendererShape; use crate::rendereroutputpixel::RendererOutputPix...
} } 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
use std::f64; use pcg_rand::Pcg32; use rand::{Rng, SeedableRng}; use crate::hitpoint::Hitpoint; use crate::math::{add, brdf, dot, elementwise_mul, intensity_to_color, min, mul, norm, random_from_brdf, sub}; use crate::ray::Ray; use crate::renderershape::RendererShape; use crate::rendereroutputpixel::RendererOutputPix...
} } for (i, sphere) in self.scene.renderer_spheres.iter().enumerate() { if !sphere.active { continue; } let distance = sphere.distance(&ray); if distance < min_distance { min_distance = distance; closest_renderer_shape_index = Some(i); renderer_type = RendererType::Sphere; } } ...
} let distance = cylinder.distance(&ray); if distance < min_distance { min_distance = distance; closest_renderer_shape_index = Some(i);
random_line_split
renderer.rs
use std::f64; use pcg_rand::Pcg32; use rand::{Rng, SeedableRng}; use crate::hitpoint::Hitpoint; use crate::math::{add, brdf, dot, elementwise_mul, intensity_to_color, min, mul, norm, random_from_brdf, sub}; use crate::ray::Ray; use crate::renderershape::RendererShape; use crate::rendereroutputpixel::RendererOutputPix...
// Find the closest hitpoint. fn closest_renderer_shape(&self, ray: &mut Ray) -> Option<Hitpoint> { let mut min_distance = f64::MAX; let mut closest_renderer_shape_index: Option<usize> = None; let mut renderer_type = RendererType::Cylinder; for (i, cylinder) in self.scene.renderer_cylinders.iter().enumerat...
{ 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
use serde::{ de::{DeserializeSeed, MapAccess, SeqAccess, Visitor}, forward_to_deserialize_any, }; use serde::Deserialize; use std::{cell::Cell, fmt}; #[derive(Debug, PartialEq)] pub enum DeserializeError { UnexpectedEOF, WrongCharacter(u8), End, InfoHashMissing, TooDeep, NoFile, E...
(&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
use serde::{ de::{DeserializeSeed, MapAccess, SeqAccess, Visitor}, forward_to_deserialize_any, }; use serde::Deserialize; use std::{cell::Cell, fmt}; #[derive(Debug, PartialEq)] pub enum DeserializeError { UnexpectedEOF, WrongCharacter(u8), End, InfoHashMissing, TooDeep, NoFile, E...
#[test] fn test_key_no_value() { #[derive(Deserialize, PartialEq, Debug)] struct Dict<'b> { a: i64, b: &'b str, } let res: Result<Dict> = from_bytes(b"d1:ai1e1:be"); println!("{:?}", res); assert_eq!(res, Err(DeserializeError::WrongChar...
{ #[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
use serde::{ de::{DeserializeSeed, MapAccess, SeqAccess, Visitor}, forward_to_deserialize_any, }; use serde::Deserialize; use std::{cell::Cell, fmt}; #[derive(Debug, PartialEq)] pub enum DeserializeError { UnexpectedEOF, WrongCharacter(u8), End, InfoHashMissing, TooDeep, NoFile, E...
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
// Copyright (c) 2016 The vulkano developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be ...
/// This function is called once during initialization, then again whenever the window is resized. fn window_size_dependent_setup( memory_allocator: &StandardMemoryAllocator, vs: EntryPoint, fs: EntryPoint, images: &[Arc<Image>], render_pass: Arc<RenderPass>, ) -> (Arc<GraphicsPipeline>, Vec<Arc<F...
{ // 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
// Copyright (c) 2016 The vulkano developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be ...
() { // 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
// Copyright (c) 2016 The vulkano developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be ...
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
package main import ( "fmt" "image/color" "log" "math/rand" "os" "strings" "time" "github.com/hajimehoshi/ebiten/v2" "github.com/hajimehoshi/ebiten/v2/audio" "github.com/hajimehoshi/ebiten/v2/ebitenutil" "github.com/hajimehoshi/ebiten/v2/inpututil" "github.com/hajimehoshi/ebiten/v2/text" "golang.org/x/im...
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
package main import ( "fmt" "image/color" "log" "math/rand" "os" "strings" "time" "github.com/hajimehoshi/ebiten/v2" "github.com/hajimehoshi/ebiten/v2/audio" "github.com/hajimehoshi/ebiten/v2/ebitenutil" "github.com/hajimehoshi/ebiten/v2/inpututil" "github.com/hajimehoshi/ebiten/v2/text" "golang.org/x/im...
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
package main import ( "fmt" "image/color" "log" "math/rand" "os" "strings" "time" "github.com/hajimehoshi/ebiten/v2" "github.com/hajimehoshi/ebiten/v2/audio" "github.com/hajimehoshi/ebiten/v2/ebitenutil" "github.com/hajimehoshi/ebiten/v2/inpututil" "github.com/hajimehoshi/ebiten/v2/text" "golang.org/x/im...
() *UI { ROMS := [90]Rom{ {"15Puzzle", "roms/15 Puzzle [Roger Ivie].ch8"}, {"Addition Problems", "roms/Addition Problems [Paul C. Moews].ch8"}, {"Airplane", "roms/Airplane.ch8"}, {"Animal Race", "roms/Animal Race [Brian Astle].ch8"}, {"Astro Dodge", "roms/Astro Dodge [Revival Studios, 2008].ch8"}, {"BMP Vi...
NewUI
identifier_name
c8.go
package main import ( "fmt" "image/color" "log" "math/rand" "os" "strings" "time" "github.com/hajimehoshi/ebiten/v2" "github.com/hajimehoshi/ebiten/v2/audio" "github.com/hajimehoshi/ebiten/v2/ebitenutil" "github.com/hajimehoshi/ebiten/v2/inpututil" "github.com/hajimehoshi/ebiten/v2/text" "golang.org/x/im...
if vme.buf[x][y] == 1 && new == 1 { vf = 1 } else { vf = 0 } vme.buf[x][y] ^= new return vf } type Button struct { text string img *ebiten.Image x int y int onclicked func(*Button) font *font.Face rom Rom } func NewButton(text string, font *font.Face, x, y int, r...
// Check collision.
random_line_split
fmlrc2.rs
extern crate clap; extern crate env_logger; extern crate exitcode; extern crate log; extern crate needletail; use clap::{Arg, App, value_t, values_t}; use log::{info, error}; use needletail::parse_fastx_file; use std::fs::File; use std::sync::{Arc, mpsc}; use threadpool::ThreadPool; use fmlrc::bv_bwt::BitVectorBWT; ...
() { //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
extern crate clap; extern crate env_logger; extern crate exitcode; extern crate log; extern crate needletail; use clap::{Arg, App, value_t, values_t}; use log::{info, error}; use needletail::parse_fastx_file; use std::fs::File; use std::sync::{Arc, mpsc}; use threadpool::ThreadPool; use fmlrc::bv_bwt::BitVectorBWT; u...
.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
extern crate clap; extern crate env_logger; extern crate exitcode; extern crate log; extern crate needletail; use clap::{Arg, App, value_t, values_t}; use log::{info, error}; use needletail::parse_fastx_file; use std::fs::File; use std::sync::{Arc, mpsc}; use threadpool::ThreadPool; use fmlrc::bv_bwt::BitVectorBWT; ...
//clone the transmit channel and submit the pool job let tx = tx.clone(); let arc_bwt = arc_bwt.clone(); let arc_params = arc_params.clone(); let read_data: LongReadFA = LongReadFA { read_index:...
{ 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
extern crate clap; extern crate env_logger; extern crate exitcode; extern crate log; extern crate needletail; use clap::{Arg, App, value_t, values_t}; use log::{info, error}; use needletail::parse_fastx_file; use std::fs::File; use std::sync::{Arc, mpsc}; use threadpool::ThreadPool; use fmlrc::bv_bwt::BitVectorBWT; ...
{ //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
import flask from flask import render_template from flask import request from flask import url_for import uuid import json import logging # Date handling import arrow # Replacement for datetime, based on moment.js # import datetime # But we still need time from dateutil import tz # For interpreting local times # ...
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
import flask from flask import render_template from flask import request from flask import url_for import uuid import json import logging # Date handling import arrow # Replacement for datetime, based on moment.js # import datetime # But we still need time from dateutil import tz # For interpreting local times # ...
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
import flask from flask import render_template from flask import request from flask import url_for import uuid import json import logging # Date handling import arrow # Replacement for datetime, based on moment.js # import datetime # But we still need time from dateutil import tz # For interpreting local times # ...
( 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
import flask from flask import render_template from flask import request from flask import url_for import uuid import json import logging # Date handling import arrow # Replacement for datetime, based on moment.js # import datetime # But we still need time from dateutil import tz # For interpreting local times # ...
def next_day(isotext): """ ISO date + 1 day (used in query to Google calendar) """ as_arrow = arrow.get(isotext) return as_arrow.replace(days=+1).isoformat() #### # # Functions (NOT pages) that return some information # #### def list_calendars(service): """ Given a google 'service' ob...
""" 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
package cmd import ( "cronitor/lib" "errors" "fmt" "io/ioutil" "math/rand" "net/http" "net/url" "os" "os/exec" "regexp" "runtime" "strconv" "strings" "sync" "time" "github.com/fatih/color" "github.com/getsentry/raven-go" "github.com/spf13/cobra" "github.com/spf13/viper" ) var Version string = "25....
() 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
package cmd import ( "cronitor/lib" "errors" "fmt" "io/ioutil" "math/rand" "net/http" "net/url" "os" "os/exec" "regexp" "runtime" "strconv" "strings" "sync" "time" "github.com/fatih/color" "github.com/getsentry/raven-go" "github.com/spf13/cobra" "github.com/spf13/viper" ) var Version string = "25....
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 isAutoDiscover || isSilent { log(message) } else { printSuccessText(message+" ✔", ind...
func printSuccessText(message string, indent bool) { if isAutoDiscover || isSilent { log(message) } else {
random_line_split
root.go
package cmd import ( "cronitor/lib" "errors" "fmt" "io/ioutil" "math/rand" "net/http" "net/url" "os" "os/exec" "regexp" "runtime" "strconv" "strings" "sync" "time" "github.com/fatih/color" "github.com/getsentry/raven-go" "github.com/spf13/cobra" "github.com/spf13/viper" ) var Version string = "25....
color.Println(fmt.Sprintf("----► %s", message)) } } } func printErrorText(message string, indent bool) { if isAutoDiscover || isSilent { log(message) } else { red := color.New(color.FgHiRed) if indent { red.Println(fmt.Sprintf(" |--► %s", message)) } else { red.Println(fmt.Sprintf("----► %s", mes...
olor.Println(fmt.Sprintf(" |--► %s", message)) } else {
conditional_block
root.go
package cmd import ( "cronitor/lib" "errors" "fmt" "io/ioutil" "math/rand" "net/http" "net/url" "os" "os/exec" "regexp" "runtime" "strconv" "strings" "sync" "time" "github.com/fatih/color" "github.com/getsentry/raven-go" "github.com/spf13/cobra" "github.com/spf13/viper" ) var Version string = "25....
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
use std::time::Duration; use std::{ collections::HashMap, io::{self, BufRead, BufReader}, path::{Path, PathBuf}, process::{self, Child, Stdio}, }; use futures::channel::mpsc::{channel, unbounded, Sender}; use futures::channel::oneshot::channel as oneshot_channel; use futures::SinkExt; use chromiumoxid...
} self } pub fn build(self) -> std::result::Result<BrowserConfig, String> { let executable = if let Some(e) = self.executable { e } else { default_executable()? }; Ok(BrowserConfig { headless: self.headless, sandbo...
self.args.push(arg.into());
random_line_split
browser.rs
use std::time::Duration; use std::{ collections::HashMap, io::{self, BufRead, BufReader}, path::{Path, PathBuf}, process::{self, Child, Stdio}, }; use futures::channel::mpsc::{channel, unbounded, Sender}; use futures::channel::oneshot::channel as oneshot_channel; use futures::SinkExt; use chromiumoxid...
} } 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
use std::time::Duration; use std::{ collections::HashMap, io::{self, BufRead, BufReader}, path::{Path, PathBuf}, process::{self, Child, Stdio}, }; use futures::channel::mpsc::{channel, unbounded, Sender}; use futures::channel::oneshot::channel as oneshot_channel; use futures::SinkExt; use chromiumoxid...
#[cfg(windows)] pub(crate) fn get_chrome_path_from_windows_registry() -> Option<std::path::PathBuf> { winreg::RegKey::predef(winreg::enums::HKEY_LOCAL_MACHINE) .open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe") .and_then(|key| key.get_value::<String, _>("")) ...
{ 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
use std::time::Duration; use std::{ collections::HashMap, io::{self, BufRead, BufReader}, path::{Path, PathBuf}, process::{self, Child, Stdio}, }; use futures::channel::mpsc::{channel, unbounded, Sender}; use futures::channel::oneshot::channel as oneshot_channel; use futures::SinkExt; use chromiumoxid...
(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
"""Main module.""" from typing import Optional, Generator, Tuple, List, Sequence, Dict, Any, Union from anndata import AnnData from pandas import DataFrame import boto3 as bt from botocore.exceptions import ClientError import os import pandas as pd import scanpy as sc import tempfile import time import uuid class M...
( 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
"""Main module.""" from typing import Optional, Generator, Tuple, List, Sequence, Dict, Any, Union from anndata import AnnData from pandas import DataFrame import boto3 as bt from botocore.exceptions import ClientError import os import pandas as pd import scanpy as sc import tempfile import time import uuid class M...
def mast_collect( self, collection: Dict[str, Dict[str, str]], wait: int = 30, ) -> Generator[ Tuple[str, str, Dict[str, str], Optional[DataFrame]], None, None, ]: while wait and len(collection) > 0: time.sleep(wait) for job_i...
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
"""Main module.""" from typing import Optional, Generator, Tuple, List, Sequence, Dict, Any, Union from anndata import AnnData from pandas import DataFrame import boto3 as bt from botocore.exceptions import ClientError import os import pandas as pd import scanpy as sc import tempfile import time import uuid class M...
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
"""Main module.""" from typing import Optional, Generator, Tuple, List, Sequence, Dict, Any, Union from anndata import AnnData from pandas import DataFrame import boto3 as bt from botocore.exceptions import ClientError import os import pandas as pd import scanpy as sc import tempfile import time import uuid class M...
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
var IMAP_Client = Extends(TCP_Client, new Class({ USE_BLOCKS: true, mailboxes: { inbox: "inbox", outbox: "inbox.Sent", contacts: "inbox.Contacts" }, contact_fields: ["Name", "Long", "Short", "Type"], initialize: function(URL, port){ this.counter = 0; this.patterns = [ /\*\sO...
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
// Copyright (c) 2017 Pulcy. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in wri...
u := url.URL{ Scheme: "http", Host: net.JoinHostPort(clusterIP, strconv.Itoa(m.ServicePort)), Path: m.RulesPath, } urls = append(urls, u.String()) } } if len(urls) == 0 { return nil, nil } // Fetch rules from URLs rulesChan := make(chan string, len(urls)) wg := sync.WaitGroup{} f...
{ continue }
conditional_block