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
box.py
so no break item, penalty is # zero. Not actually sure this is a real case, because \hfil is always # inserted right? if break_item is None: return 0 # "Each potential breakpoint has an associated 'penalty,' which # represents the 'aesthetic cost' of breaking at that place." # "In cases...
self.offset = offset def __repr__(self): a = [] a.append(f'naturally {dimrep(self.natural_length)}') a.append(f'minimally {dimrep(self.min_length)}') if self.to is not None: a.append(f'to {dimrep(self.to)}') elif self.spread is not None: a.ap...
self.scale_and_set()
conditional_block
box.py
if glue_order == 0: glue_ratio = min(glue_ratio, 1.0) return line_state, glue_ratio, glue_order def get_penalty(pre_break_conts, break_item): # Will assume if breaking at end of paragraph, so no break item, penalty is # zero. Not actually sure this is a real case, because \hfil...
random_line_split
box.py
(self, *args, **kwargs): self.contents.extend(*args, **kwargs) def copy(self, *args, **kwargs): # If glue is set, need to tell the constructor that set_glue should be # True, but that the glue is already set. if self.set_glue: raise NotImplementedError('Can only copy un-...
Rule
identifier_name
twine.py
(self, **kwargs): for name, strand in self._load_twine(**kwargs).items(): setattr(self, name, strand) self._available_strands = set(trim_suffix(name, "_schema") for name in vars(self)) self._available_manifest_strands = self._available_strands & set(MANIFEST_STRANDS) def _load_...
__init__
identifier_name
twine.py
(self, kind, source, **kwargs): """Load data from either a *.json file, an open file pointer or a json string. Directly returns any other data.""" if source is None: raise exceptions.invalid_json_map[kind](f"Cannot load {kind} - no data source specified.") # Decode the json string a...
# version consistency... schema_path = "schema/children_schema.json" elif strand in MANIFEST_STRANDS: # The data is a manifest of files. The "*_manifest" strands of the twine describe matching criteria used to # filter files appropriate for consumption by the dig...
random_line_split
twine.py
data is a list of children. The "children" strand of the twine describes matching criteria for # the children, not the schema of the "children" data, which is distributed with this package to ensure # version consistency... schema_path = "schema/children_schema.json" elif s...
"""Validate the input manifest, passed as either a file or a json string.""" return self._validate_manifest("configuration_manifest", source, **kwargs)
identifier_body
twine.py
, kind, source, **kwargs): """Load data from either a *.json file, an open file pointer or a json string. Directly returns any other data.""" if source is None: raise exceptions.invalid_json_map[kind](f"Cannot load {kind} - no data source specified.") # Decode the json string and de...
# TODO Additional validation that the children match what is set as required in the Twine return children def validate_credentials(self, *args, dotenv_path=None, **kwargs): """Validate that all credentials required by the twine are present. Credentials must be set as environment ...
child_key = child["key"] if not strand_keys.get(child_key, False): raise exceptions.InvalidValuesContents( f"Child with key '{child_key}' found but no such key exists in the 'children' strand of the twine." )
conditional_block
config.rs
pub fn config_file() -> PathBuf { std::env::var("SILICON_CONFIG_PATH") .ok() .map(PathBuf::from) .filter(|config_path| config_path.is_file()) .unwrap_or_else(|| PROJECT_DIRS.config_dir().join("config")) } pub fn get_args_from_config_file() -> Vec<OsString>
fn parse_str_color(s: &str) -> Result<Rgba<u8>, Error> { s.to_rgba() .map_err(|_| format_err!("Invalid color: `{}`", s)) } fn parse_font_str(s: &str) -> Vec<(String, f32)> { let mut result = vec![]; for font in s.split(';') { let tmp = font.split('=').collect::<Vec<_>>(); let font...
{ let args = std::fs::read_to_string(config_file()) .ok() .and_then(|content| { content .split('\n') .map(|line| line.trim()) .filter(|line| !line.starts_with('#') && !line.is_empty()) .map(shell_words::split) ...
identifier_body
config.rs
parse_font_str(s: &str) -> Vec<(String, f32)> { let mut result = vec![]; for font in s.split(';') { let tmp = font.split('=').collect::<Vec<_>>(); let font_name = tmp[0].to_owned(); let font_size = tmp .get(1) .map(|s| s.parse::<f32>().unwrap()) .unwr...
get_expanded_output
identifier_name
config.rs
}; pub fn config_file() -> PathBuf { std::env::var("SILICON_CONFIG_PATH") .ok() .map(PathBuf::from) .filter(|config_path| config_path.is_file()) .unwrap_or_else(|| PROJECT_DIRS.config_dir().join("config")) } pub fn get_args_from_config_file() -> Vec<OsString> { let args = std::...
pub struct Config { /// Background image #[structopt(long, value_name = "IMAGE", conflicts_with = "background")] pub background_image: Option<PathBuf>, /// Background color of the image #[structopt( long, short, value_name = "COLOR", default_value = "#aaaaff", ...
type Lines = Vec<u32>; #[derive(StructOpt, Debug)] #[structopt(name = "silicon")] #[structopt(global_setting(ColoredHelp))]
random_line_split
config.rs
pub fn config_file() -> PathBuf { std::env::var("SILICON_CONFIG_PATH") .ok() .map(PathBuf::from) .filter(|config_path| config_path.is_file()) .unwrap_or_else(|| PROJECT_DIRS.config_dir().join("config")) } pub fn get_args_from_config_file() -> Vec<OsString> { let args = std::fs::...
let mut stdin = stdin(); let mut s = String::new(); stdin.read_to_string(&mut s)?; let language = possible_language.unwrap_or_else(|| { ps.find_syntax_by_first_line(&s) .ok_or_else(|| format_err!("Failed to detect the language")) })?; Ok((l...
{ let mut s = String::new(); let mut file = File::open(path)?; file.read_to_string(&mut s)?; let language = possible_language.unwrap_or_else(|| { ps.find_syntax_for_file(path)? .ok_or_else(|| format_err!("Failed to detect the language"...
conditional_block
evaluator_test.go
", true}, {" (1 > 2) == true", false}, {"true == true", true}, {"false != true", true}, {"false != false", false}, } for _, bb := range tests{ evaluated := testEval(bb.input) testBooleanObject(t, evaluated, bb.expected) } } func testEval (input string) object.Object{ l := lexer.New(input) p := parser...
if result.Bool != expected{ t.Errorf("Expected %t but got %t", expected, result.Bool) return false } return true } func testIntegerObject(t *testing.T, obj object.Object, expected int64) bool{ result, ok := obj.(*object.Integer) if !ok { t.Errorf("Evaluated value is suppose to be of object.Integer Type by ...
{ t.Errorf("expected value was object.Boolean but got %T",obj) }
conditional_block
evaluator_test.go
fn(x) {x}];`, "unusable as hash key: FUNCTION"}, } for _, tt :=range tests{ evaluated := testEval(tt.input) errObj, ok := evaluated.(*object.Error) if ! ok{ t.Errorf("no error object returned. got= %T(%+v)", evaluated, evaluated) continue } if errObj.Message != tt.expectedMessage{ t.Errorf("wrong ...
random_line_split
evaluator_test.go
", true}, {" (1 > 2) == true", false}, {"true == true", true}, {"false != true", true}, {"false != false", false}, } for _, bb := range tests{ evaluated := testEval(bb.input) testBooleanObject(t, evaluated, bb.expected) } } func testEval (input string) object.Object{ l := lexer.New(input) p := parser...
} func TestFunctionApplication(t *testing.T){ tests := []struct{ input string expected int64 }{ { "let identity = fn(x) {x;} identity(5);", 5}, {"let identity = fn(x) { return x;}; identity(5)", 5}, {"let double = fn(x) { x*2;}; double(5); ",10}, {"let add = fn(x, y) { x + y; }; add(4, 6);", 10}, {"l...
{ input := "fn(x) {x+2;};" evaluated := testEval(input) fn, ok := evaluated.(*object.Function) if !ok{ t.Fatalf("object is not a function. got: %T(%+v)", evaluated, evaluated) } if len(fn.Parameters) != 1 { t.Fatalf("function has wrong number of parameters %+v", fn.Parameters) } if fn.Parameters[0].String...
identifier_body
evaluator_test.go
", true}, {" (1 > 2) == true", false}, {"true == true", true}, {"false != true", true}, {"false != false", false}, } for _, bb := range tests{ evaluated := testEval(bb.input) testBooleanObject(t, evaluated, bb.expected) } } func testEval (input string) object.Object{ l := lexer.New(input) p := parser...
(t *testing.T){ input := `"Hello"+" "+"World!"` evaluated := testEval(input) str, ok := evaluated.(*object.String) if !ok { t.Fatalf("Object is not String. got= %T", evaluated) } if str.Value != "Hello World!" { t.Fatalf("The expected value of concatenated string %s but got %s", "Hello World!",str.Value) } }...
TestStringConcatenation
identifier_name
main.go
// DefaultAddress is the default address to serve from. DefaultAddress string = ":8877" // PrimoDomain is the domain at which Primo instances are hosted. PrimoDomain string = "primo.exlibrisgroup.com" // subDomain is the institution domain subDomain string = "ocul-qu" // instVID is the institution vid ...
// EnvPrefix is the prefix for the environment variables. EnvPrefix string = "PERMANENTDETOUR_"
random_line_split
main.go
vid parameter on all redirects. setParamInURL(redirectTo, "vid", d.vid) // Send the redirect to the client. // http.Redirect(w, r, redirectTo.String(), http.StatusMovedPermanently) http.Redirect(w, r, redirectTo.String(), http.StatusTemporaryRedirect) } // buildRecordRedirect updates redirectTo to the correct Pr...
{ // Split the input line into fields on commas. splitLine := strings.Split(line, ",") if len(splitLine) < 2 { return bibID, exlID, fmt.Errorf("Line has incorrect number of fields, 2 expected, %v found.\n", len(splitLine)) } // The bibIDs look like this: a1234-instid // We need to strip off the first character ...
identifier_body
main.go
ParamInURL(redirectTo, "query", fmt.Sprintf("title,contains,%v", q.Get("searchArg"))) case "NAME": redirectTo.Path = "/discovery/browse" setParamInURL(redirectTo, "browseScope", "author") setParamInURL(redirectTo, "browseQuery", q.Get("searchArg")) case "CALL": redirectTo.Path = "/discovery/browse" s...
setParamInURL
identifier_name
main.go
"/vwebv/search" ) // A version flag, which should be overwritten when building using ldflags. var version = "devel" // Detourer is a struct which stores the data needed to perform redirects. type Detourer struct { idMap map[uint32]uint64 // The map of BibIDs to ExL IDs. primo string // The domain name (...
else { log.Fatalln(err) } } // SearchAuthorIndexPrefix string = "/vwebv/search?searchArg=XXX&searchCode=NAME" // SearchCallNumberIndexPrefix string = "/vwebv/search?searchArg=XXX&searchCode=CALL" // SearchTitleIndexPrefix string = "/vwebv/search?searchArg=XXX&searchCode=T" // SearchJournalIndexPrefix string = "/vw...
{ bibID := uint32(bibID64) exlID, present := idMap[bibID] if present { redirectTo.Path = "/discovery/fulldisplay" setParamInURL(redirectTo, "docid", fmt.Sprintf("alma%v", exlID)) } else { log.Printf("Not found: %v", bibID64) } }
conditional_block
import.rs
ST_T: "fstT" = 180; thm FST_DEF: "FST_DEF" = 181; term SND: "snd" = 37; thm SND_T: "sndT" = 184; thm SND_DEF: "SND_DEF" = 185; term IND: "ind" = 40; term ONE_ONE: "one_one" = 38; thm ONE_ONE_T: "one_one_T" = 188; thm ONE_ONE_BD: "one_one_BD" = 189; thm ONE_ONE_DEF: "one_one_DEF" = 191; term ONTO...
Aligned
identifier_name
import.rs
"SND_DEF" = 185; term IND: "ind" = 40; term ONE_ONE: "one_one" = 38; thm ONE_ONE_T: "one_one_T" = 188; thm ONE_ONE_BD: "one_one_BD" = 189; thm ONE_ONE_DEF: "one_one_DEF" = 191; term ONTO: "onto" = 39; thm ONTO_T: "onto_T" = 193; thm ONTO_BD: "onto_BD" = 194; thm ONTO_DEF: "onto_DEF" = 196; thm ...
let mmb = MmbFile::parse(&HOL_MMB.0).unwrap(); #[cfg(debug_assertions)] check_consts(&mmb);
random_line_split
main.go
{} filepath.Walk(o.directory, func(path string, f os.FileInfo, err error) error { fileList = append(fileList, path) return nil }) for _, file := range fileList { collectFiles = append(collectFiles, file) } dirFiles := searchFiles("edits", collectFiles) for stuff := 0; stuff < len(dirFiles); stuff++ { e...
{ cmd := exec.Command("convert", pngFile, "-format", "%c", "histogam:info:", histo1File) cmd.Run() }
identifier_body
main.go
csv != false { fmt.Println("generating csv analysis file~~~~~~~") generateCSV(dirFiles) } } func generateCSV(input []string) { var matrix [][]string for i := 0; i < len(input); i++ { // fmt.Println(input[i] + "s\n") editName := strings.SplitAfter(input[i], "/edits/") // fmt.Println(editName) data, er...
searchFiles
identifier_name
main.go
var collectFiles, jj, result []string fileList := []string{} filepath.Walk(o.directory, func(path string, f os.FileInfo, err error) error { fileList = append(fileList, path) return nil }) for _, file := range fileList
dirFiles := searchFiles("edits", collectFiles) for stuff := 0; stuff < len(dirFiles); stuff++ { editName := strings.SplitAfter(dirFiles[stuff], "/edits/") // fmt.Println(editName) jj = append(jj, editName[0][:len(editName[0])-7]) if stuff == len(dirFiles)-1 { encountered := map[string]bool{} for v :=...
{ collectFiles = append(collectFiles, file) }
conditional_block
main.go
{ var collectFiles, jj, result []string
return nil }) for _, file := range fileList { collectFiles = append(collectFiles, file) } dirFiles := searchFiles("edits", collectFiles) for stuff := 0; stuff < len(dirFiles); stuff++ { editName := strings.SplitAfter(dirFiles[stuff], "/edits/") // fmt.Println(editName) jj = append(jj, editName[0][:len...
fileList := []string{} filepath.Walk(o.directory, func(path string, f os.FileInfo, err error) error { fileList = append(fileList, path)
random_line_split
repository.go
{ f, err := os.Open(file) if err != nil { return reflow.File{}, err } defer f.Close() w := reflow.Digester.NewWriter() n, err := io.Copy(w, f) if err != nil { return reflow.File{}, err } d := w.Digest() return reflow.File{ID: d, Size: n}, r.InstallDigest(d, file) } // InstallDigest installs a file at th...
// URL returns the url of this repository. func (r *Repository) URL() *url.URL { return r.RepoURL } // Contains tells whether the repository has an object with a digest. func (r *Repository) Contains(id digest.Digest) (bool, error) { _, path := r.Path(id) _, err := os.Stat(path) if os.IsNotExist(err) { return f...
return nil, nil }) return err }
random_line_split
repository.go
{ f, err := os.Open(file) if err != nil { return reflow.File{}, err } defer f.Close() w := reflow.Digester.NewWriter() n, err := io.Copy(w, f) if err != nil { return reflow.File{}, err } d := w.Digest() return reflow.File{ID: d, Size: n}, r.InstallDigest(d, file) } // InstallDigest installs a file at th...
(d digest.Digest, file string) error { file, err := filepath.EvalSymlinks(file) if err != nil { return err } dir, path := r.Path(d) if err := os.MkdirAll(dir, 0777); err != nil { return err } err = os.Link(file, path) if os.IsExist(err) { err = nil } if err != nil { // Copy if file was reported to be ...
InstallDigest
identifier_name
repository.go
int64, error) } if gf, ok := repo.(getFiler); ok { temp, err := r.TempFile("getfile-") if err != nil { return nil, err } defer os.Remove(temp.Name()) _, err = gf.GetFile(ctx, id, temp) if err != nil { _ = temp.Close() return nil, err } err = temp.Close() if err != nil { re...
{ if live != nil && live.Contains(w.Digest()) { continue } size += w.Info().Size() if err := os.Remove(w.Path()); err != nil { r.Log.Errorf("remove %q: %v", w.Path(), err) } // Clean up object subdirectories. (Ignores failure when nonempty.) os.Remove(filepath.Dir(w.Path())) n++ }
conditional_block
repository.go
{ f, err := os.Open(file) if err != nil { return reflow.File{}, err } defer f.Close() w := reflow.Digester.NewWriter() n, err := io.Copy(w, f) if err != nil { return reflow.File{}, err } d := w.Digest() return reflow.File{ID: d, Size: n}, r.InstallDigest(d, file) } // InstallDigest installs a file at th...
case err := <-done: if err != nil { return digest.Digest{}, err } dgst := dw.Digest() return dgst, r.InstallDigest
{ temp, err := r.TempFile("create-") if err != nil { return digest.Digest{}, err } defer os.Remove(temp.Name()) dw := reflow.Digester.NewWriter() done := make(chan error, 1) // This is a workaround to make sure that copies respect // context cancellations. Note that the underlying copy is // not actually can...
identifier_body
pre_train.py
# # next_sentence_labels = features['next_sentence_labels'] # else: masked_lm_positions = features['masked_lm_positions'] masked_lm_ids = features['masked_lm_ids'] masked_lm_weights = features['masked_lm_weights'] if bert_config.train_type == 'seq2seq': ...
# num_train_steps, # end_learning_rate=0.0, # power=1.0, # cycle=False) # optimi...
# tf.train.get_or_create_global_step(),
random_line_split
pre_train.py
# # next_sentence_labels = features['next_sentence_labels'] # else: masked_lm_positions = features['masked_lm_positions'] masked_lm_ids = features['masked_lm_ids'] masked_lm_weights = features['masked_lm_weights'] if bert_config.train_type == 'seq2seq': ...
eval_metrics = metric_fn(loss, masked_lm_ids, logits, is_real_example) output_spec = tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metrics) return output_spec return model_fn def get_masked_lm_output(bert_config, input_tens...
""" Args: loss: tf.float32. label_ids: [b, s]. logits: [b, s, v]. """ # [b * s, v] logits = tf.reshape(logits, [-1, logits.shape[-1]]) # [b * s, 1] ...
identifier_body
pre_train.py
# # next_sentence_labels = features['next_sentence_labels'] # else: masked_lm_positions = features['masked_lm_positions'] masked_lm_ids = features['masked_lm_ids'] masked_lm_weights = features['masked_lm_weights'] if bert_config.train_type == 'seq2seq': _...
(loss, label_ids, logits, is_real_example): """ Args: loss: tf.float32. label_ids: [b, s]. logits: [b, s, v]. """ # [b * s, v] logits = tf.reshape(l...
metric_fn
identifier_name
pre_train.py
# # next_sentence_labels = features['next_sentence_labels'] # else: masked_lm_positions = features['masked_lm_positions'] masked_lm_ids = features['masked_lm_ids'] masked_lm_weights = features['masked_lm_weights'] if bert_config.train_type == 'seq2seq':
elif bert_config.train_type == 'lm': _info('Training language model task.') # build model is_training = (mode == tf.estimator.ModeKeys.TRAIN) model = BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, ...
_info('Training seq2seq task.')
conditional_block
layer.go
. discard this. done() r.blobCacheMu.Lock() r.blobCache.Remove(name) r.blobCacheMu.Unlock() } httpCache, err := newCache(filepath.Join(r.rootDir, "httpcache"), r.config.HTTPCacheType, r.config) if err != nil { return nil, fmt.Errorf("failed to create http cache: %w", err) } defer func() { if retErr !=...
isClosed
identifier_name
layer.go
*reader.VerifiableReader, ) *layer { return &layer{ resolver: resolver, desc: desc, blob: blob, verifiableReader: vr, prefetchWaiter: newWaiter(), } } type layer struct { resolver *Resolver desc ocispec.Descriptor blob *blobRef verifiab...
{ w.isDoneMu.Lock() w.isDone = true w.isDoneMu.Unlock() w.completionCond.Broadcast() }
identifier_body
layer.go
FdEntry := dcc.MaxCacheFds if maxFdEntry == 0 { maxFdEntry = defaultMaxCacheFds } bufPool := &sync.Pool{ New: func() interface{} { return new(bytes.Buffer) }, } dCache, fCache := cacheutil.NewLRUCache(maxDataEntry), cacheutil.NewLRUCache(maxFdEntry) dCache.OnEvicted = func(key string, value interface{})...
{ return }
conditional_block
layer.go
.Spec, ocispec.Descriptor) []metadata.Decompressor } // NewResolver returns a new layer resolver. func NewResolver(root string, backgroundTaskManager *task.BackgroundTaskManager, cfg config.Config, resolveHandlers map[string]remote.Handler, metadataStore metadata.Store, overlayOpaqueType OverlayOpaqueType, additionalD...
} log.G(ctx).Debugf("resolving") // Resolve the blob. blobR, err := r.resolveBlob(ctx, hosts, refspec, desc) if err != nil { return nil, fmt.Errorf("failed to resolve the blob: %w", err) } defer func() { if retErr != nil { blobR.done() } }() fsCache, err := newCache(filepath.Join(r.rootDir, "fscach...
r.layerCacheMu.Unlock()
random_line_split
app.py
Exclude beers user doesn't like at all if known beers can be recommended dislike_beers = melt_df[melt_df['rating'] < 1]['product'].to_list() for dislike_beer in dislike_beers: if dislike_beer in recommendable_beers: recommendable_beers.remove(dislike_beer...
send_mail(email, name, markdown_list, image_list) st.success('Enviado! Confira sua caixa de entrada e lixo eletrônico.') if accept_beer_offers or allow_data_usage: # Try to send answers to database db = DBFunctions() try: ...
conditional_block
app.py
{ 'Cerveja Blonde': 'Blonde Ale', 'Cerveja Trigo': 'Weiss (Trigo)', 'Cerveja APA': 'American Pale Ale', 'Cerveja IPA': 'India Pale Ale', 'Cerveja Session IPA': 'Session IPA', 'Cerveja NEIPA': 'New England IPA', 'Cerveja Porter':...
beginning to fix rollbacks.""" # Ensure to rerun only once to avoid infinite loops # caused by a constantly changing state value at each run. # # Example: state.value += 1 if self._state["is_rerun"]: self._state["is_rerun"] = False elif self._state[...
identifier_body
app.py
erveja Blonde': 'Blonde Ale', 'Cerveja Trigo': 'Weiss (Trigo)', 'Cerveja APA': 'American Pale Ale', 'Cerveja IPA': 'India Pale Ale', 'Cerveja Session IPA': 'Session IPA', 'Cerveja NEIPA': 'New England IPA', 'Cerveja Porter': 'Porter/Stout', ...
id sess
identifier_name
app.py
("") st.text("") st.text("") if st.button('Gerar recomendações'): model = load_model('data/recommending_system') if len(recommendable_beers) == 0: st.error('Não temos nenhuma cerveja para te recomendar :/') else: with st...
"hasher": _CodeHasher(hash_funcs), "is_rerun": False, "session": session, }
random_line_split
packet_decoder.py
(self): p = Packet() p.direction = self.direction p.ident = self.ident p.data = self.data.copy() return p SLOT_EXTRA_DATA_IDS = [ 0x103, 0x105, 0x15A, 0x167, 0x10C, 0x10D, 0x10E, 0x10F, 0x122, 0x110, 0x111, 0x112, 0x113, 0x123, 0x10B, 0x100, 0x101, 0x102, 0x124, 0x114, 0x115, 0x116, 0x117, 0x125, 0x11...
copy
identifier_name
packet_decoder.py
mtype != 127: mtype2 = mtype >> 5 t = 0 if mtype2 == 0: t = self.unpack('byte') if mtype2 == 1: t = self.unpack('short') if mtype2 == 2: t = self.unpack('int') if mtype2 == 3: t = self.unpack('float') if mtype2 == 4: t = self.unpack('string16') if mtype2 == 5: t = {} t["id...
"""A wrapper about the normal objects, that lets you pack decoded packets easily. Returns the bytestring that represents the packet.""" decoder = PacketDecoder(to_server) return decoder.encode_packet(packet)
identifier_body
packet_decoder.py
("short", "y_velocity"), ("short", "z_velocity")), #Destroy entity 0x1D: ("int", "entity_id"), #Entity 0x1E: ("int", "entity_id"), #Entity relative move 0x1F: ( ("int", "entity_id"), ("byte", "x_change"), ("byte", "y_change"), ("byte", "z_change")), #Entity look 0x20: ( ("int", "entity_id"), ("byt...
o += self.pack('byte', val)
conditional_block
packet_decoder.py
('byte', val['count']) o += self.pack('short', val['damage']) if mtype2 == 6: for i in range(3): o += self.pack('int', val[i]) o += self.pack('byte', 127) return o def unpack(self, data_type): """Reads buff (consuming bytes) and returns the unpacked value according to the given type.""" ...
# coords = [] # btypes = [] # metadata = [] # for i in packet.data['blocks']: # coords.append(i['x'] << 12 | i['z'] << 8 | i['y'])
random_line_split
lib.rs
from_millis(100)).await; // avoid deadlock //! map1.cancel("Voltairine de Cleyre"); //! }); //! //! task::block_on(handle); //! # Ok(()) //! # } //! ``` mod wait; mod waker_set; use std::borrow::Borrow; use std::collections::hash_map::RandomState; use std::future::Future; use std::hash::{BuildHasher, Hash}; use s...
/// let emma = "Emma Goldman".to_string(); /// /// map.insert(emma.clone(), 0); /// let kv: Ref<String, i32, _> = map.get(&emma).unwrap(); ///
random_line_split
lib.rs
Duration; //! # use std::sync::Arc; //! # use waitmap::WaitMap; //! # #[async_std::main] //! # async fn main() -> std::io::Result<()> { //! let map: Arc<WaitMap<String, String>> = Arc::new(WaitMap::new()); //! let map1 = map.clone(); //! //! let handle = task::spawn(async move { //! let result = map.wait("Voltairin...
} enum WaitEntry<V> { Waiting(WakerSet), Filled(V), } /// A shared reference to a
{ self.map.retain(|_, entry| { if let Waiting(wakers) = entry { // NB: In theory, there is a deadlock risk: if a task is awoken before the // retain is completed, it may see a waiting entry with an empty waker set, // rather than a missing entry. ...
identifier_body
lib.rs
use std::collections::hash_map::RandomState; /// # #[async_std::main] /// # async fn main() -> std::io::Result<()> { /// let map: WaitMap<i32, String> = WaitMap::with_hasher(RandomState::new()); /// # Ok(()) /// # } /// ``` pub fn with_hasher(hasher: S) -> WaitMap<K, V, S> { WaitMap...
value_mut
identifier_name
lib.rs
Duration; //! # use std::sync::Arc; //! # use waitmap::WaitMap; //! # #[async_std::main] //! # async fn main() -> std::io::Result<()> { //! let map: Arc<WaitMap<String, String>> = Arc::new(WaitMap::new()); //! let map1 = map.clone(); //! //! let handle = task::spawn(async move { //! let result = map.wait("Voltairin...
else { false }); } pub fn len(&self) -> usize { self.map.len() } /// Cancels all outstanding `waits` on the map. /// ``` /// # extern crate async_std; /// # extern crate waitmap; /// # use async_std::{main, stream, prelude::*}; /// # use waitmap::WaitMap; /// # #[async...
{ true }
conditional_block
controller_test.go
Equals, name) c.Assert(app.ID, Not(Equals), "") if id != "" { c.Assert(app.ID, Equals, id) } c.Assert(app.Protected, Equals, true) c.Assert(app.Meta["foo"], Equals, "bar") gotApp := &ct.App{} res, err := s.Get("/apps/"+app.ID, gotApp) c.Assert(err, IsNil) c.Assert(gotApp, DeepEquals, app) res,...
res, err = s.Get("/releases/fail"+out.ID, gotRelease) c.Assert(res.StatusCode, Equals, 404) } } func (s *S) TestCreateFormation(c *C) { for i, useName := range []bool{false, true} { release := s.createTestRelease(c, &ct.Release{}) app := s.createTestApp(c, &ct.App{Name: fmt.Sprintf("create-formation-%d", i)}...
c.Assert(gotRelease, DeepEquals, out)
random_line_split
controller_test.go
c.Assert(err, IsNil) c.Assert(gotApp, DeepEquals, app) res, err = s.Get("/apps/fail"+app.ID, gotApp) c.Assert(res.StatusCode, Equals, 404) } } func (s *S) TestUpdateApp(c *C) { meta := map[string]string{"foo": "bar"} app := s.createTestApp(c, &ct.App{Name: "update-app", Meta: meta}) c.Assert(app.Protected,...
{ release := s.createTestRelease(c, &ct.Release{}) app := s.createTestApp(c, &ct.App{Name: fmt.Sprintf("delete-formation-%d", i)}) out := s.createTestFormation(c, &ct.Formation{ReleaseID: release.ID, AppID: app.ID}) var path string if useName { path = formationPath(app.Name, release.ID) } else { path...
conditional_block
controller_test.go
ct.Formation{ReleaseID: release.ID, AppID: app.ID, Processes: map[string]int{"web": 1}} if useName { in.AppID = app.Name } out := s.createTestFormation(c, in) c.Assert(out.AppID, Equals, app.ID) c.Assert(out.ReleaseID, Equals, release.ID) c.Assert(out.Processes["web"], Equals, 1) gotFormation := &ct.F...
{ s.createTestApp(c, &ct.App{Name: "list-test"}) var list []ct.App res, err := s.Get("/apps", &list) c.Assert(err, IsNil) c.Assert(res.StatusCode, Equals, 200) c.Assert(len(list) > 0, Equals, true) c.Assert(list[0].ID, Not(Equals), "") }
identifier_body
controller_test.go
Equals, name) c.Assert(app.ID, Not(Equals), "") if id != "" { c.Assert(app.ID, Equals, id) } c.Assert(app.Protected, Equals, true) c.Assert(app.Meta["foo"], Equals, "bar") gotApp := &ct.App{} res, err := s.Get("/apps/"+app.ID, gotApp) c.Assert(err, IsNil) c.Assert(gotApp, DeepEquals, app) res,...
(appID, releaseID string) string { return "/apps/" + appID + "/formations/" + releaseID } func (s *S) TestDeleteFormation(c *C) { for i, useName := range []bool{false, true} { release := s.createTestRelease(c, &ct.Release{}) app := s.createTestApp(c, &ct.App{Name: fmt.Sprintf("delete-formation-%d", i)}) out
formationPath
identifier_name
colores-empresa.component.ts
'@angular/material/core'; import { ProgressSpinnerMode } from '@angular/material/progress-spinner'; import { MatRadioChange } from '@angular/material/radio'; @Component({ selector: 'app-colores-empresa', templateUrl: './colores-empresa.component.html', styleUrls: ['./colores-empresa.component.css'] })
export class ColoresEmpresaComponent implements OnInit { selec1 = false; selec2 = false; selec3 = false; selec4 = false; ingresarOtro = false; verOtro: any; fraseReporte = new FormControl(''); nuevaF = new FormControl(''); public fraseForm = new FormGroup({ fraseReporteF: this.fraseReporte, ...
random_line_split
colores-empresa.component.ts
angular/material/core'; import { ProgressSpinnerMode } from '@angular/material/progress-spinner'; import { MatRadioChange } from '@angular/material/radio'; @Component({ selector: 'app-colores-empresa', templateUrl: './colores-empresa.component.html', styleUrls: ['./colores-empresa.component.css'] }) export class...
ngOnInit(): void { this.VerFormularios(); this.obtenerColores(); this.ObtenerEmpleados(this.idEmpleado); this.ObtenerLogo(); } VerFormularios() { if (this.data.ventana === 'colores') { this.verColores = true; } else { this.verFrase = true; this.ImprimirFrase(); } ...
{ this.idEmpleado = parseInt(localStorage.getItem('empleado')); }
identifier_body
colores-empresa.component.ts
this.idEmpleado = parseInt(localStorage.getItem('empleado')); } ngOnInit(): void { this.VerFormularios(); this.obtenerColores(); this.ObtenerEmpleados(this.idEmpleado); this.ObtenerLogo(); } VerFormularios() { if (this.data.ventana === 'colores') { this.verColores = true; } e...
tana() {
identifier_name
SuggestionManagerFRS.py
def makeFriendshipScore(self,email,friend): """ score friendship """ # * the total score will be out of 100 % # * weight for chat frequencey is 60% # * weight for duration from last chat 40% friendMgr =FriendshipManagerFRS() array = friendMgr.selectRelationship(email,frie...
SuggestionManagerFRS =self
identifier_body
SuggestionManagerFRS.py
(object): def __init__(self): SuggestionManagerFRS =self def makeFriendshipScore(self,email,friend): """ score friendship """ # * the total score will be out of 100 % # * weight for chat frequencey is 60% # * weight for duration from last chat 40% friendMgr =Friendshi...
SuggestionManagerFRS
identifier_name
SuggestionManagerFRS.py
40% friendMgr =FriendshipManagerFRS() array = friendMgr.selectRelationship(email,friend) c=0 try: if len(array)==5: c+=1 #print "\n Id:"+str(c) #print"User: %s"% str(i['email']) #print "Dur:%s days from last cha...
return score #score Duration def scoreDur(self,dur): "duration represents time decay" dur =int(dur) if 730 <dur: #more than 2 years return 0 if dur ==0: # today return 40 if 0<dur and dur<=182: #less than 6 months ...
score-=5
conditional_block
SuggestionManagerFRS.py
for duration from last chat 40% friendMgr =FriendshipManagerFRS() array = friendMgr.selectRelationship(email,friend) c=0 try: if len(array)==5: c+=1 #print "\n Id:"+str(c) #print"User: %s"% str(i['email']) #prin...
#update all the relationship strength of user def upgradeRelationshipStrength(self,user): fMgr = FriendshipManagerFRS() user =str(user) allFriends = fMgr.selectAllFriends(user) for friend in allFriends: score=0 try: ...
maxCat ={maxIndex:maxValue} return maxCat
random_line_split
proxy.go
log.Info("service is deleted, cleanup service and endpoints") p.cleanupService(request.NamespacedName) return Result{}, nil } return Result{}, err } // if service is updated to a invalid service, we take it as deleted and cleanup related resources if p.shouldSkipService(&service) { log.Info("service ...
{ node, ok := p.nodeSet[nodeName] if !ok { node = newEdgeNode(nodeName) } endpointSet := node.EndpointMap[spn] if endpointSet.Contains(endpoint) { return false } endpointSet.Add(endpoint) node.EndpointMap[spn] = endpointSet p.nodeSet[nodeName] = node return true }
identifier_body
proxy.go
:= p.serviceMap[key] if !ok { return } p.syncServiceChangesToAgent(serviceInfo) } func (p *proxy) syncServiceChangesToAgent(serviceInfo ServiceInfo) { for _, name := range serviceInfo.EndpointToNodes { node, ok := p.nodeSet[name] if !ok { continue } p.keeper.AddNode(node) } } func (p *proxy) OnEnd...
func (p *proxy) shouldSkipService(svc *corev1.Service) bool { if svc.Spec.Type != corev1.ServiceTypeClusterIP { return true
random_line_split
proxy.go
EndpointSliceUpdate(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { log := p.log.WithValues("request", request) var es EndpointSlice err := p.client.Get(ctx, request.NamespacedName, &es) if err != nil { if errors.IsNotFound(err) { log.Info("endpointslice is deleted, cleanup related...
== corev1.Serv
identifier_name
proxy.go
[name] if !ok { continue } p.keeper.AddNode(node) } } func (p *proxy) OnEndpointSliceUpdate(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { log := p.log.WithValues("request", request) var es EndpointSlice err := p.client.Get(ctx, request.NamespacedName, &es) if err != nil { ...
lse } func makeSe
conditional_block
maimemo_client.rs
brief: String, created_time: Option<String>, updated_time: Option<String>, contents: Option<String>, } impl Notepad { pub fn get_notepad_id(&self) -> &str { &self.notepad_id } pub fn set_contents(&mut self, contents: Option<String>) { self.contents = contents; } pu...
is_private: u8, notepad_id: String, title: String,
random_line_split
maimemo_client.rs
) -> fmt::Result { let mut temp = self.clone(); // 仅输出第一行 与 total length let contents = temp.contents.as_mut().unwrap(); let total_len = contents.len(); contents.drain(contents.find("\n").unwrap_or(total_len)..); contents.push_str("... total length: "); contents.p...
_selector) .next() .map(|e| e.inner_html()) .ok_or_else(|| { error!("not found element {} in html: \n{}", id, html); format!("not found element {} in html", id) }) } } #[cfg(test)] mod tests { use super::*; const CONFIG_PATH: &...
identifier_body
maimemo_client.rs
impl fmt::Display for Notepad { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut temp = self.clone(); // 仅输出第一行 与 total length let contents = temp.contents.as_mut().unwrap(); let total_len = contents.len(); contents.drain(contents.find("\n").unwrap_or(total_len)...
ser_token = self.get_user_token_val().expect("not found user token"); url.to_string() + user_token }; let payload = serde_json::json!({"keyword":null,"scope":"MINE","recommend":false,"offset":0,"limit":30,"total":-1}); let resp = send_request( &self.config, &s...
token} let url_handler = |url: &str| { let u
conditional_block
maimemo_client.rs
)] struct ResponseResult { error: String, valid: i32, total: usize, notepad: Option<Vec<Notepad>>, } /// maimemo提供一些访问操作。 pub struct MaimemoClient { client: Client, config: AppConfig, cookie_store: CookieStore, user_token_name: String, } impl std::ops::Drop for MaimemoClient { /// ...
?; asser
identifier_name
note.py
0]) #sl=cl.getstrlist() # self.strl=self.strl+sl def getnexturl(self, nexturllist, cl): for i in range(len(nexturllist)): nul=nexturllist[i] self.nustr=self.nustr+nul[1]+nul[0]+"\n" cl.gethtml("http://gz.58.com"+nul[0]) uls...
omboBox_2.currentText ()=="前程无忧": t=Tnuls(5)
conditional_block
note.py
self.textEdit_get.setText(self.strl) self.textEdit_getstr.setText(self.ustr) def crawling(self, url): cl=crawler.crawler() cl.gethtml(url) self.urllist=cl.geturllist() nexturllist=cl.getnexturl() self.getnexturl(nexturllist, cl) for i in range(len(se...
#self.drawRect(pt) self.drawclock(pt) pt.end() def drawRect(self, pt): pen1=QPen(QColor(225, 225, 225, 225)) rec=QRect(500, 500,500, 500) pt.setPen(pen1) pt.drawRect(rec) pt.setBrush(QColor(0, 0, 0, 255)) pt.drawRect(300, 300, 300, 600) def...
n(self)
identifier_name
note.py
self.textEdit_get.setText(self.strl) self.textEdit_getstr.setText(self.ustr) def crawling(self, url): cl=crawler.crawler() cl.gethtml(url) self.urllist=cl.geturllist() nexturllist=cl.getnexturl() self.getnexturl(nexturllist, cl) for i in range...
import threading import time from ui_paint import Window def bigin_click(self): if not source.isbigan: if self.comboBox_2.currentText ()=="58同城": t=Tnuls(0) t.start() source.isbigan=True if self.comboBox_2.currentText ()=="中华英才网": ...
#**********************************************************************8 from PyQt5 import QtCore, QtGui, QtWidgets from source import source from threadings import Tnuls
random_line_split
note.py
self.textEdit_get.setText(self.strl) self.textEdit_getstr.setText(self.ustr) def crawling(self, url): cl=crawler.crawler() cl.gethtml(url) self.urllist=cl.geturllist() nexturllist=cl.getnexturl() self.getnexturl(nexturllist, cl) for i in range(len(se...
minPoints=[QPointF(50,25), QPointF(48,50), QPointF(52,50)] #时钟坐标点 hourPoints=[QPointF(50,35), QPointF(48,50), QPointF(52,50)] side=min(self.width(),self.height()) painter.setViewport((2*se...
tRenderHint(QPainter.Antialiasing) #设置表盘中的文字字体 font=QFont("Times",6) fm=QFontMetrics(font) fontRect=fm.boundingRect("99")#获取绘制字体的矩形范围 #分针坐标点
identifier_body
app.js
592000'); } // Enable CORS preflight across the board. app.options('*', cors()); app.use(cors()); /////////// Configure Webserver /////////// app.use(function(req, res, next){ var keys; console.log('silly', '------------------------------------------ incoming request ------------------------------------------'); ...
{ console.log('starting websocket'); obc.save('./cc_summaries'); //save it here for chaincode investigator wss = new ws.Server({server: server}); //start the websocket now wss.on('connection', function connection(ws) { //ws_cons.push(ws); ws.on('message', function incoming(message) { ...
identifier_body
app.js
')); app.set('view engine', 'jade'); app.engine('.html', require('jade').__express); app.use(compression()); app.use(morgan('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); app.use('/cc/summary', serve_static(path.join(__dirname, 'cc_summaries')) ); //for chain...
obc.load(options, cb_ready); //parse/load chain
{ console.log('\n[!] looks like you are in bluemix, I am going to clear out the deploy_name so that it deploys new cc.\n[!] hope that is ok budddy\n'); options.deployed_name = ""; }
conditional_block
app.js
serve_static(path.join(__dirname, 'public')) ); app.use(session({secret:'Somethignsomething1234!test', resave:true, saveUninitialized:true})); function setCustomCC(res, path) { if (serve_static.mime.lookup(path) === 'image/jpeg') res.setHeader('Cache-Control', 'public, max-age=2592000'); //30 days cache else if (s...
cb_deployed
identifier_name
app.js
')); app.set('view engine', 'jade'); app.engine('.html', require('jade').__express); app.use(compression()); app.use(morgan('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); app.use('/cc/summary', serve_static(path.join(__dirname, 'cc_summaries')) ); //for chain...
else if (serve_static.mime.lookup(path) === 'image/x-icon') res.setHeader('Cache-Control', 'public, max-age=2592000'); } // Enable CORS preflight across the board. app.options('*', cors()); app.use(cors()); /////////// Configure Webserver /////////// app.use(function(req, res, next){ var keys; console.log('silly'...
app.use( serve_static(path.join(__dirname, 'public')) ); app.use(session({secret:'Somethignsomething1234!test', resave:true, saveUninitialized:true})); function setCustomCC(res, path) { if (serve_static.mime.lookup(path) === 'image/jpeg') res.setHeader('Cache-Control', 'public, max-age=2592000'); //30 days cache el...
random_line_split
process_packet.rs
_packet(&mut self, ip_pkt: Ipv4Packet, frame_len: usize) { // Ignore packets that aren't TCP if ip_pkt.get_next_level_protocol() != IpNextHeaderProtocols::Tcp { return; } let tcp_pkt = match TcpPacket::new(ip_pkt.payload()) { Some(pkt) => pkt, None...
} pub fn establish_bidi(&mut self, tcp_pkt: &TcpPacket, flow: &Flow, tag_payload: &Vec<u8>, wscale_and_mss: WscaleAndMSS) -> bool { let (_, master_key, server_random, client_random, session_id) = parse_tag_pa...
{ // upload-only eavesdropped TLS // (don't mark as TD in FlowTracker until you have the Rc<RefCell>) self.establish_upload_only(tcp_pkt, flow, &tag_payload) }
conditional_block
process_packet.rs
4_packet(&mut self, ip_pkt: Ipv4Packet, frame_len: usize) { // Ignore packets that aren't TCP if ip_pkt.get_next_level_protocol() != IpNextHeaderProtocols::Tcp { return; } let tcp_pkt = match TcpPacket::new(ip_pkt.payload()) { Some(pkt) => pkt, Non...
return false; } td.expect_bidi_reconnect = false; if let Some(cov_err) = cov_error { td.end_whole_session_error(cov_err
{ let (_, master_key, server_random, client_random, session_id) = parse_tag_payload(tag_payload); let (tcp_ts, tcp_ts_ecr) = util::get_tcp_timestamps(tcp_pkt); let mut client_ssl = BufferableSSL::new(session_id); let ssl_success = client_ssl.construct_forged_ssl...
identifier_body
process_packet.rs
}, EtherTypes::Ipv4 => &eth_payload[0..], _ => return, }; match Ipv4Packet::new(ip_data) { Some(pkt) => global.process_ipv4_packet(pkt, rust_view_len), None => return, } } fn is_tls_app_pkt(tcp_pkt: &TcpPacket) -> bool { let payload = tcp_pkt.payload(); paylo...
// + (eth_payload[1] as u16); &eth_payload[4..] } else { return }
random_line_split
process_packet.rs
_packet(&mut self, ip_pkt: Ipv4Packet, frame_len: usize) { // Ignore packets that aren't TCP if ip_pkt.get_next_level_protocol() != IpNextHeaderProtocols::Tcp { return; } let tcp_pkt = match TcpPacket::new(ip_pkt.payload()) { Some(pkt) => pkt, None...
(&mut self, flow: &Flow, tcp_pkt: &TcpPacket) -> bool { let tag_payload = elligator::extract_telex_tag(&self.priv_key, &tcp_pkt.payload()); self.stats.elligator_this_period += 1; ...
try_establish_tapdance
identifier_name
shard.go
FlushTimer = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "shard_memory_database_flush_duration", Help: "Flush memory data duration(ms).", Buckets: monitoring.DefaultHistogramBuckets, }, []string{"db", "shard"}, ) ) func init() { monitoring.StorageRegistry.MustRegister(buildIndexT...
(familyTime int64) (memdb.MemoryDatabase, error) { var memDB memdb.MemoryDatabase s.rwMutex.RLock() defer s.rwMutex.RUnlock() memDB, ok := s.families[familyTime] if !ok { memDB, err := s.createMemoryDatabase() if err != nil { return nil, err } s.families[familyTime] = memDB } return memDB, nil } // W...
MemoryDatabase
identifier_name
shard.go
FlushTimer = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "shard_memory_database_flush_duration", Help: "Flush memory data duration(ms).", Buckets: monitoring.DefaultHistogramBuckets, }, []string{"db", "shard"}, ) ) func init() { monitoring.StorageRegistry.MustRegister(buildIndexT...
databaseName string id int32 path string option option.DatabaseOption sequence ReplicaSequence families map[int64]memdb.MemoryDatabase // memory database for each family time indexDB indexdb.IndexDatabase metadata metadb.Metadata // write accept time range interval timeutil.Inte...
// xx/shard/1/index/inverted/ // xx/shard/1/data/20191012/ // xx/shard/1/data/20191013/ type shard struct {
random_line_split
shard.go
util.Interval _ = interval.ValueOf(option.Interval) if err := mkDirIfNotExist(shardPath); err != nil { return nil, err } replicaSequence, err := newReplicaSequenceFunc(filepath.Join(shardPath, replicaDir)) if err != nil { return nil, err } shardIDStr := strconv.Itoa(int(shardID)) createdShard := &shard{ ...
{ var err error storeOption := kv.DefaultStoreOption(filepath.Join(s.path, indexParentDir)) s.indexStore, err = newKVStoreFunc(storeOption.Path, storeOption) if err != nil { return err } s.forwardFamily, err = s.indexStore.CreateFamily( forwardIndexDir, kv.FamilyOption{ CompactThreshold: 0, Merger: ...
identifier_body
shard.go
// GetOrCreateSequence gets the replica sequence by given remote peer if exist, else creates a new sequence GetOrCreateSequence(replicaPeer string) (replication.Sequence, error) // Close releases shard's resource, such as flush data, spawned goroutines etc. io.Closer // Flush flushes index and memory data to disk ...
{ return err }
conditional_block
agent.rs
recover(handle_errors) .unify() } fn endpoint_config( caps: Capabilities, data: Arc<Data>, auth: AuthDetails, ) -> Fallible<Response<Body>> { data.agents.add_capabilities(&auth.name, &caps)?; Ok(ApiResponse::Success { result: AgentConfig { agent_name: auth.name, ...
{ let error = if let Some(compat) = err.find::<Compat<HttpError>>() { Some(*compat.get_ref()) } else if err.is_not_found() { Some(HttpError::NotFound) } else { None }; match error { Some(HttpError::NotFound) => Ok(ApiResponse::not_found().into_response().unwrap()), ...
identifier_body
agent.rs
Error = Rejection> + Clone { let data_cloned = data.clone(); let data_filter = warp::any().map(move || data_cloned.clone()); let mutex_filter = warp::any().map(move || mutex.clone()); let github_data_filter = warp::any().map(move || github_data.clone()); let config = warp::post() .and(warp...
.1 .wait_while( self.in_flight_requests .0 .lock() .unwrap_or_else(|l| l.into_inner()), |g| *g != 0, ) .unwrap_or_else(|g| g.into_inner()), ...
// Ignore the mutex guard (see above). drop( self.in_flight_requests
random_line_split
agent.rs
= Rejection> + Clone { let data_cloned = data.clone(); let data_filter = warp::any().map(move || data_cloned.clone()); let mutex_filter = warp::any().map(move || mutex.clone()); let github_data_filter = warp::any().map(move || github_data.clone()); let config = warp::post() .and(warp::path...
; Ok(ApiResponse::Success { result }.into_response()?) } #[derive(Clone)] pub struct RecordProgressThread { // String is the worker name queue: Sender<(ExperimentData<ProgressData>, String)>, in_flight_requests: Arc<(Mutex<usize>, Condvar)>, } impl RecordProgressThread { pub fn new( db: c...
{ None }
conditional_block
agent.rs
= Rejection> + Clone { let data_cloned = data.clone(); let data_filter = warp::any().map(move || data_cloned.clone()); let mutex_filter = warp::any().map(move || mutex.clone()); let github_data_filter = warp::any().map(move || github_data.clone()); let config = warp::post() .and(warp::path...
{ thread: RecordProgressThread, } impl Drop for RequestGuard { fn drop(&mut self) { *self .thread .in_flight_requests .0 .lock() .unwrap_or_else(|l| l.into_inner()) -= 1; self.thread.in_flight_requests.1.notify_one(); } } // This...
RequestGuard
identifier_name
message.rs
size. const MAX_MESSAGE_SIZE: u32 = 2^27; /// A message consists of a header and a body. If you think of a message as a package, /// the header is the address, and the body contains the package contents. /// Both header and body use the D-Bus [type system](https://dbus.freedesktop.org/doc/dbus-specification.html#type...
<T1, T2>(&self, writer: &mut DbusWriter<T1>) -> Result<(), io::Error> where T1: io::Write, T2: ByteOrder { writer.write_u8(self.0) } } bitflags! { struct HeaderFlags: u8 { /// This message does not expect method return replies or error replies, /// even if it i...
write
identifier_name
message.rs
size. const MAX_MESSAGE_SIZE: u32 = 2^27; /// A message consists of a header and a body. If you think of a message as a package, /// the header is the address, and the body contains the package contents. /// Both header and body use the D-Bus [type system](https://dbus.freedesktop.org/doc/dbus-specification.html#type...
/// The body of the message is made up of zero or more arguments, /// which are typed values, such as an integer or a byte array. body: Body, } impl Message { fn write<T>(&self, writer:T) -> Result<(), io::Error> where T: io::Write { let mut writer = DbusWriter::new(writer); mat...
struct Message { /// The message delivery system uses the header information to figure out /// where to send the message and how to interpret it. header: Header,
random_line_split
message.rs
= format!("Invalid endianess `{}`", x); Err(io::Error::new(io::ErrorKind::InvalidData, str_err)) }, } } } /// Message type. Unknown types must be ignored. #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum MessageType { /// This is an invalid type. Invalid = 0,...
{ writer.write_u8(self.endianess_flag as u8)?; writer.write_u8(self.message_type as u8)?; writer.write_u8(self.flags.bits())?; writer.write_u8(self.major_protocol_version.0)?; writer.write_u32::<T2>(self.length_message_body)?; writer.write_u32::<T2>(self.serial.0)?...
identifier_body
genotype.go
} func logm(level string, msg string, verbose bool) { if verbose || level != "DEBUG" { fmt.Fprintf(os.Stderr, "%s: %s: %s\n", time.Now().String(), level, msg) } } func checkResult(e error) { if e != nil { log.Fatal(e) } } // joinAlleles takes a list of alleles and returns a comma separated list of them func ...
position := 0 kmer := content[position : position+db.SeedSize] kmerHash := stringToHash(kmer) entry := QueryPos{Name: sequence, Pos: position, Content: content} query, ok := db.Index[kmerHash] if !ok { query = make([]QueryPos, 0) } query = append(query, entry) db.Index[kmerHash] = query } // searchSequence...
{ logm("WARN", fmt.Sprintf("sequence %v is length %v, shorter than seed size %v", sequence, len(content), db.SeedSize), false) return }
conditional_block
genotype.go
} func logm(level string, msg string, verbose bool) { if verbose || level != "DEBUG" { fmt.Fprintf(os.Stderr, "%s: %s: %s\n", time.Now().String(), level, msg) } } func checkResult(e error) { if e != nil { log.Fatal(e) } } // joinAlleles takes a list of alleles and returns a comma separated list of them func ...
// searchSequence iterates over content and populates result with genes and matching func searchSequence(content string, db QueryList, result GenomeAlleleResult, verbose bool, reverseComplement bool) { // populates result with a map from gene name to list of found alleles for position := 0; position <= len(content)...
{ // for an exact match we only have to hash the start of the query if len(content) < db.SeedSize { logm("WARN", fmt.Sprintf("sequence %v is length %v, shorter than seed size %v", sequence, len(content), db.SeedSize), false) return } position := 0 kmer := content[position : position+db.SeedSize] kmerHash := s...
identifier_body
genotype.go
} func
(level string, msg string, verbose bool) { if verbose || level != "DEBUG" { fmt.Fprintf(os.Stderr, "%s: %s: %s\n", time.Now().String(), level, msg) } } func checkResult(e error) { if e != nil { log.Fatal(e) } } // joinAlleles takes a list of alleles and returns a comma separated list of them func joinAlleles(...
logm
identifier_name
genotype.go
() } func logm(level string, msg string, verbose bool) { if verbose || level != "DEBUG" { fmt.Fprintf(os.Stderr, "%s: %s: %s\n", time.Now().String(), level, msg) } } func checkResult(e error) { if e != nil { log.Fatal(e) } } // joinAlleles takes a list of alleles and returns a comma separated list of them fu...
} // addSearchableSequence adds an allele sequence to the hash func addSearchableSequence(content string, sequence int, db QueryList) { // for an exact match we only have to hash the start of the query if len(content) < db.SeedSize { logm("WARN", fmt.Sprintf("sequence %v is length %v, shorter than seed size %v", s...
random_line_split
lib.rs
type ContinueRunning = bool; ///Game to use with server must implement this trait. pub trait Game { /// delta_time: time elapsed from last call. /// command: ordered commands commands from server. /// from: Address of command sender. /// Returns bool value indicating /// should server continue run...
(&mut self, client: &SocketAddr) { self.servers.remove(&client); } pub fn add(&mut self, client: &SocketAddr) { if !self.servers.contains_key(client) { self.servers.insert(client.clone(), bll::Server::new()); } } pub fn send_to_all(&mut self, state: Vec<u8>) -> Vec<...
remove
identifier_name
lib.rs
type ContinueRunning = bool; ///Game to use with server must implement this trait. pub trait Game { /// delta_time: time elapsed from last call. /// command: ordered commands commands from server. /// from: Address of command sender. /// Returns bool value indicating /// should server continue run...
} struct ServerSocket { socket: TypedServerSocket, servers: HashMap<SocketAddr, bll::Server>, } impl ServerSocket { pub fn new(port: u16) -> Result<ServerSocket, Exception> { Ok(ServerSocket { socket: TypedServerSocket::new(port)?, servers: HashMap::new(), }) }...
{ let state = self.socket.read()?; let (state, lost) = self.client.recv(state)?; for command in lost { self.socket.write(&command)?; } Ok(state) }
identifier_body
lib.rs
type ContinueRunning = bool; ///Game to use with server must implement this trait. pub trait Game { /// delta_time: time elapsed from last call. /// command: ordered commands commands from server. /// from: Address of command sender. /// Returns bool value indicating /// should server continue run...
} pub fn send_to_all(&mut self, state: Vec<u8>) -> Vec<(SocketAddr, Exception)> { let mut exceptions = Vec::new(); for (a, s) in &mut self.servers { let _ = self .socket .write(a, &s.send(state.clone())) .map_err(|e| exceptions.push((...
{ self.servers.insert(client.clone(), bll::Server::new()); }
conditional_block
lib.rs
type ContinueRunning = bool; ///Game to use with server must implement this trait. pub trait Game { /// delta_time: time elapsed from last call. /// command: ordered commands commands from server. /// from: Address of command sender. /// Returns bool value indicating /// should server continue run...
exceptions } } const DRAW_PERIOD_IN_MILLIS: u64 = 30; ///Game server to run [`Game`] pub struct GameServer<T: Game> { game: T, socket: ServerSocket, is_running: bool, draw_timer: bll::timer::WaitTimer, update_timer: bll::timer::ElapsedTimer, after_draw_elapsed_timer: bll::timer::El...
let _ = self .socket .write(a, &s.send(state.clone())) .map_err(|e| exceptions.push((*a, e))); }
random_line_split
dicer.py
2, cv2.LINE_AA) pos_img = np.zeros(shape=[100, 100, 1], dtype=np.uint8) cv2.imshow('Press any key to exit', grey) print('Error - stopping') cv2.waitKey() # Taste drücken, zum beenden elif GPIO.input(18) == 0 and gpios == True: # Temperaturreais prüfen wenn RPi vorhanden print('Temperature relay i...
2.imwrite('frame.png',frame) # Bildausschnitte von Würfel und Positionserkennung y = 160 h = 240 x = 220 w = 240 dice_image = frame[y:y + h, x:x + w] grey = cv2.cvtColor(dice_image, cv2.COLOR_BGR2GRAY) #cv2.imshow('input', grey) #cv2.imwrite('real_image.png',frame) y = 120 ...
e = cap.read() #cv
conditional_block