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
box.py
import math from enum import Enum from functools import lru_cache from .feedback import printable_ascii_codes, drep, truncate_list, dimrep from .utils import InfiniteDimension, sum_infinities, LogicError class LineState(Enum): naturally_good = 1 should_stretch = 2 should_shrink = 3 class GlueRatio(Enum...
@property def height(self): if not self.set_glue: raise AttributeError('VBox is not set yet, does not have a height') return self.desired_length # TODO: This is wrong. Correct rules are in TeXbook page 80. @property def depth(self): if self.contents: ...
return max(self.widths)
identifier_body
box.py
import math from enum import Enum from functools import lru_cache from .feedback import printable_ascii_codes, drep, truncate_list, dimrep from .utils import InfiniteDimension, sum_infinities, LogicError class LineState(Enum): naturally_good = 1 should_stretch = 2 should_shrink = 3 class GlueRatio(Enum...
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
import math from enum import Enum from functools import lru_cache from .feedback import printable_ascii_codes, drep, truncate_list, dimrep from .utils import InfiniteDimension, sum_infinities, LogicError class LineState(Enum): naturally_good = 1 should_stretch = 2 should_shrink = 3 class GlueRatio(Enum...
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
import math from enum import Enum from functools import lru_cache from .feedback import printable_ascii_codes, drep, truncate_list, dimrep from .utils import InfiniteDimension, sum_infinities, LogicError class LineState(Enum): naturally_good = 1 should_stretch = 2 should_shrink = 3 class GlueRatio(Enum...
(ListElement): discardable = False def __init__(self, width, height, depth): self.width = width self.height = height self.depth = depth # /Boxes. # Miscellanea. class WhatsIt(ListElement): discardable = False width = height = depth = 0 class Glue(ListElement): ...
Rule
identifier_name
twine.py
import json as jsonlib import logging import os import pkg_resources from dotenv import load_dotenv from jsonschema import ValidationError, validate as jsonschema_validate from . import exceptions from .utils import load_json, trim_suffix logger = logging.getLogger(__name__) SCHEMA_STRANDS = ("input_values", "conf...
(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
import json as jsonlib import logging import os import pkg_resources from dotenv import load_dotenv from jsonschema import ValidationError, validate as jsonschema_validate from . import exceptions from .utils import load_json, trim_suffix logger = logging.getLogger(__name__) SCHEMA_STRANDS = ("input_values", "conf...
# 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
import json as jsonlib import logging import os import pkg_resources from dotenv import load_dotenv from jsonschema import ValidationError, validate as jsonschema_validate from . import exceptions from .utils import load_json, trim_suffix logger = logging.getLogger(__name__) SCHEMA_STRANDS = ("input_values", "conf...
def validate_input_manifest(self, source, **kwargs): """Validate the input manifest, passed as either a file or a json string.""" return self._validate_manifest("input_manifest", source, **kwargs) def validate_output_manifest(self, source, **kwargs): """Validate the output manifest, p...
"""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
import json as jsonlib import logging import os import pkg_resources from dotenv import load_dotenv from jsonschema import ValidationError, validate as jsonschema_validate from . import exceptions from .utils import load_json, trim_suffix logger = logging.getLogger(__name__) SCHEMA_STRANDS = ("input_values", "conf...
# 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
use anyhow::{Context, Error}; use clipboard::{ClipboardContext, ClipboardProvider}; use image::Rgba; use silicon::directories::PROJECT_DIRS; use silicon::formatter::{ImageFormatter, ImageFormatterBuilder}; use silicon::utils::{Background, ShadowAdder, ToRgba}; use std::ffi::OsString; use std::fs::File; use std::io::{st...
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
use anyhow::{Context, Error}; use clipboard::{ClipboardContext, ClipboardProvider}; use image::Rgba; use silicon::directories::PROJECT_DIRS; use silicon::formatter::{ImageFormatter, ImageFormatterBuilder}; use silicon::utils::{Background, ShadowAdder, ToRgba}; use std::ffi::OsString; use std::fs::File; use std::io::{st...
(&self) -> Option<PathBuf> { let need_expand = self.output.as_ref().map(|p| p.starts_with("~")) == Some(true); if let (Ok(home_dir), true) = (std::env::var("HOME"), need_expand) { self.output .as_ref() .map(|p| p.to_string_lossy().replacen('~', &home_dir, 1)....
get_expanded_output
identifier_name
config.rs
use anyhow::{Context, Error}; use clipboard::{ClipboardContext, ClipboardProvider}; use image::Rgba; use silicon::directories::PROJECT_DIRS; use silicon::formatter::{ImageFormatter, ImageFormatterBuilder}; use silicon::utils::{Background, ShadowAdder, ToRgba}; use std::ffi::OsString; use std::fs::File; use std::io::{st...
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
use anyhow::{Context, Error}; use clipboard::{ClipboardContext, ClipboardProvider}; use image::Rgba; use silicon::directories::PROJECT_DIRS; use silicon::formatter::{ImageFormatter, ImageFormatterBuilder}; use silicon::utils::{Background, ShadowAdder, ToRgba}; use std::ffi::OsString; use std::fs::File; use std::io::{st...
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
package evaluator import ( "testing" "go-interpreter-lexer/object" "go-interpreter-lexer/lexer" "go-interpreter-lexer/parser" ) func TestEvaluateIntegerExpression(t *testing.T){ tests := []struct{ input string expected int64 }{ {"5", 5}, {"10", 10}, {"-10", -10}, {"-39", -39}, {"5 + 5 + 5", 15}, ...
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
package evaluator import ( "testing" "go-interpreter-lexer/object" "go-interpreter-lexer/lexer" "go-interpreter-lexer/parser" ) func TestEvaluateIntegerExpression(t *testing.T){ tests := []struct{ input string expected int64 }{ {"5", 5}, {"10", 10}, {"-10", -10}, {"-39", -39}, {"5 + 5 + 5", 15}, ...
}
random_line_split
evaluator_test.go
package evaluator import ( "testing" "go-interpreter-lexer/object" "go-interpreter-lexer/lexer" "go-interpreter-lexer/parser" ) func TestEvaluateIntegerExpression(t *testing.T){ tests := []struct{ input string expected int64 }{ {"5", 5}, {"10", 10}, {"-10", -10}, {"-39", -39}, {"5 + 5 + 5", 15}, ...
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}, {"let...
{ 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
package evaluator import ( "testing" "go-interpreter-lexer/object" "go-interpreter-lexer/lexer" "go-interpreter-lexer/parser" ) func TestEvaluateIntegerExpression(t *testing.T){ tests := []struct{ input string expected int64 }{ {"5", 5}, {"10", 10}, {"-10", -10}, {"-39", -39}, {"5 + 5 + 5", 15}, ...
(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
// Copyright 2019 Carleton University Library All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package main import ( "bufio" "context" "flag" "fmt" "log" "net/http" "net/url" "os" "os/signal" "path/filepath" "strconv" "strings" "sysc...
// 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
// Copyright 2019 Carleton University Library All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package main import ( "bufio" "context" "flag" "fmt" "log" "net/http" "net/url" "os" "os/signal" "path/filepath" "strconv" "strings" "sysc...
// If any flags are not set, use environment variables to set them. func overrideUnsetFlagsFromEnvironmentVariables() error { // A map of pointers to unset flags. listOfUnsetFlags := make(map[*flag.Flag]bool) // flag.Visit calls a function on "only those flags that have been set." // flag.VisitAll calls a funct...
{ // 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
// Copyright 2019 Carleton University Library All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package main import ( "bufio" "context" "flag" "fmt" "log" "net/http" "net/url" "os" "os/signal" "path/filepath" "strconv" "strings" "sysc...
(redirectTo *url.URL, param, value string) { q := redirectTo.Query() q.Set(param, value) redirectTo.RawQuery = q.Encode() } // addParamInURL is a helper function which adds a parameter in the query of a url. func addParamInURL(redirectTo *url.URL, param, value string) { q := redirectTo.Query() q.Add(param, value)...
setParamInURL
identifier_name
main.go
// Copyright 2019 Carleton University Library All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package main import ( "bufio" "context" "flag" "fmt" "log" "net/http" "net/url" "os" "os/signal" "path/filepath" "strconv" "strings" "sysc...
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
use std::{io, path::PathBuf}; use std::collections::HashMap; use crate::mm0::{SortId, TermId, ThmId}; #[cfg(debug_assertions)] use mm0b_parser::BasicMmbFile as MmbFile; #[cfg(not(debug_assertions))] use mm0b_parser::BareMmbFile as MmbFile; use super::Mm0Writer; macro_rules! const_assert { ($cond:expr) => { let _ = [...
<T: ?Sized>(T); static HOL_MMB: &Aligned<[u8]> = &Aligned(*include_bytes!("../../hol.mmb")); let mmb = MmbFile::parse(&HOL_MMB.0).unwrap(); #[cfg(debug_assertions)] check_consts(&mmb); Mm0Writer::new(out, temp, &mmb) }
Aligned
identifier_name
import.rs
use std::{io, path::PathBuf}; use std::collections::HashMap; use crate::mm0::{SortId, TermId, ThmId}; #[cfg(debug_assertions)] use mm0b_parser::BasicMmbFile as MmbFile; #[cfg(not(debug_assertions))] use mm0b_parser::BareMmbFile as MmbFile; use super::Mm0Writer; macro_rules! const_assert { ($cond:expr) => { let _ = [...
Mm0Writer::new(out, temp, &mmb) }
let mmb = MmbFile::parse(&HOL_MMB.0).unwrap(); #[cfg(debug_assertions)] check_consts(&mmb);
random_line_split
main.go
package main import ( "encoding/csv" "encoding/json" "fmt" "log" "os" "os/exec" "path/filepath" "strings" "time" "github.com/vansante/go-ffprobe" ) var ( fileInfo os.FileInfo err error ) type Ffprobe struct { Format struct { Filename string `json:"filename"` NbStreams int `json:"...
func main() { globalDir := "/Users/csk/Documents/_REPO/1987-06-may/" runSuite(globalDir) } func runSuite(globalDir string) { var br operations // // PNG test // br.directory = globalDir // br.outputtype = "/png" // br.optype = "png" // var i1 BroadcastResearch = br // i1.DefineTargets() // // GIF test //...
{ cmd := exec.Command("convert", pngFile, "-format", "%c", "histogam:info:", histo1File) cmd.Run() }
identifier_body
main.go
package main import ( "encoding/csv" "encoding/json" "fmt" "log" "os" "os/exec" "path/filepath" "strings" "time" "github.com/vansante/go-ffprobe" ) var ( fileInfo os.FileInfo err error ) type Ffprobe struct { Format struct { Filename string `json:"filename"` NbStreams int `json:"...
(typer string, rmDups []string) []string { var savePng []string // Receive a type switch typer { case "gifs": // iterate over the incoming array i := 0 for i < len(rmDups)-1 { i++ // If the string contains the incoming type of directory h := strings.Contains(rmDups[i], typer+"/") switch h { ca...
searchFiles
identifier_name
main.go
package main import ( "encoding/csv" "encoding/json" "fmt" "log" "os" "os/exec" "path/filepath" "strings" "time" "github.com/vansante/go-ffprobe" ) var ( fileInfo os.FileInfo err error ) type Ffprobe struct { Format struct { Filename string `json:"filename"` NbStreams int `json:"...
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
package main import ( "encoding/csv" "encoding/json" "fmt" "log" "os" "os/exec" "path/filepath" "strings" "time" "github.com/vansante/go-ffprobe" ) var ( fileInfo os.FileInfo err error ) type Ffprobe struct { Format struct { Filename string `json:"filename"` NbStreams int `json:"...
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
// Copyright 2016 GRAIL, Inc. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. // Package filerepo implements a filesystem-backed repository. It stores // objects in a directory on disk; the objects are named by the // string representation...
// 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
// Copyright 2016 GRAIL, Inc. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. // Package filerepo implements a filesystem-backed repository. It stores // objects in a directory on disk; the objects are named by the // string representation...
(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
// Copyright 2016 GRAIL, Inc. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. // Package filerepo implements a filesystem-backed repository. It stores // objects in a directory on disk; the objects are named by the // string representation...
if live != nil { r.Log.Printf("collected %v objects (%s)", n, data.Size(size)) } return w.Err() } // TempFile creates and returns a new temporary file adjacent to the // repository. Files created by TempFile can be efficiently ingested // by Repository.Install. The caller is responsible for cleaning up // tempor...
{ 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
// Copyright 2016 GRAIL, Inc. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. // Package filerepo implements a filesystem-backed repository. It stores // objects in a directory on disk; the objects are named by the // string representation...
// Materialize takes a mapping of path-to-object, and hardlinks the // corresponding objects from the repository into the given root. func (r *Repository) Materialize(root string, binds map[string]digest.Digest) error { dirsMade := map[string]bool{} for path, id := range binds { path = filepath.Join(root, path) ...
{ 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
# coding:utf-8 # Produced by Andysin Zhang # 23_Oct_2019 # Inspired By the original Bert, Appreciate for the wonderful work # # Copyright 2019 TCL Inc. All Rights Reserverd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
# 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
# coding:utf-8 # Produced by Andysin Zhang # 23_Oct_2019 # Inspired By the original Bert, Appreciate for the wonderful work # # Copyright 2019 TCL Inc. All Rights Reserverd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
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
# coding:utf-8 # Produced by Andysin Zhang # 23_Oct_2019 # Inspired By the original Bert, Appreciate for the wonderful work # # Copyright 2019 TCL Inc. All Rights Reserverd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
(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
# coding:utf-8 # Produced by Andysin Zhang # 23_Oct_2019 # Inspired By the original Bert, Appreciate for the wonderful work # # Copyright 2019 TCL Inc. All Rights Reserverd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
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
/* Copyright The containerd Authors. 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...
() bool { l.closedMu.Lock() closed := l.closed l.closedMu.Unlock() return closed } // blobRef is a reference to the blob in the cache. Calling `done` decreases the reference counter // of this blob in the underlying cache. When nobody refers to the blob in the cache, resources bound // to this blob will be discard...
isClosed
identifier_name
layer.go
/* Copyright The containerd Authors. 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...
func (w *waiter) wait(timeout time.Duration) error { wait := func() <-chan struct{} { ch := make(chan struct{}) go func() { w.isDoneMu.Lock() isDone := w.isDone w.isDoneMu.Unlock() w.completionCond.L.Lock() if !isDone { w.completionCond.Wait() } w.completionCond.L.Unlock() ch <- stru...
{ w.isDoneMu.Lock() w.isDone = true w.isDoneMu.Unlock() w.completionCond.Broadcast() }
identifier_body
layer.go
/* Copyright The containerd Authors. 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...
l.r = l.verifiableReader.SkipVerify() } func (l *layer) Prefetch(prefetchSize int64) (err error) { l.prefetchOnce.Do(func() { ctx := context.Background() l.resolver.backgroundTaskManager.DoPrioritizedTask() defer l.resolver.backgroundTaskManager.DonePrioritizedTask() err = l.prefetch(ctx, prefetchSize) if...
{ return }
conditional_block
layer.go
/* Copyright The containerd Authors. 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...
} 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
from data.db_functions import DBFunctions from functions.email_functions import send_mail from data.create_recommender import get_beer_columns, melt_user_item_matrix import numpy as np import pandas as pd import streamlit as st from streamlit.hashing import _CodeHasher from streamlit.report_thread import get_rep...
n, hash_funcs): """Initialize SessionState instance.""" self.__dict__["_state"] = { "data": {}, "hash": None, "hasher": _CodeHasher(hash_funcs), "is_rerun": False, "session": session, } def __call__(self, **kwargs): ...
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
from data.db_functions import DBFunctions from functions.email_functions import send_mail from data.create_recommender import get_beer_columns, melt_user_item_matrix import numpy as np import pandas as pd import streamlit as st from streamlit.hashing import _CodeHasher from streamlit.report_thread import get_rep...
).session_id session_info = Server.get_current()._get_session_info(session_id) if session_info is None: raise RuntimeError("Couldn't get your Streamlit Session object.") return session_info.session def _get_state(hash_funcs=None): session = _get_session() if not hasattr(sess...
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
from data.db_functions import DBFunctions from functions.email_functions import send_mail from data.create_recommender import get_beer_columns, melt_user_item_matrix import numpy as np import pandas as pd import streamlit as st from streamlit.hashing import _CodeHasher from streamlit.report_thread import get_rep...
ion_info = Server.get_current()._get_session_info(session_id) if session_info is None: raise RuntimeError("Couldn't get your Streamlit Session object.") return session_info.session def _get_state(hash_funcs=None): session = _get_session() if not hasattr(session, "_custom_session_...
id sess
identifier_name
app.py
from data.db_functions import DBFunctions from functions.email_functions import send_mail from data.create_recommender import get_beer_columns, melt_user_item_matrix import numpy as np import pandas as pd import streamlit as st from streamlit.hashing import _CodeHasher from streamlit.report_thread import get_rep...
def __call__(self, **kwargs): """Initialize state data once.""" for item, value in kwargs.items(): if item not in self._state["data"]: self._state["data"][item] = value def __getitem__(self, item): """Return a saved state value, None if item is undefin...
"hasher": _CodeHasher(hash_funcs), "is_rerun": False, "session": session, }
random_line_split
packet_decoder.py
#!/usr/bin/python import struct import sys #TODO: Review which of these we actually need SERVER_TO_CLIENT = 0x01 CLIENT_TO_SERVER = 0x02 PROTOCOL_VERSION = 28 class Packet: def __init__(self, packet_type=0, **data): self.direction = 0 if type(packet_type) == str: packet_type = dict((v,k) for k,v in names.it...
(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
#!/usr/bin/python import struct import sys #TODO: Review which of these we actually need SERVER_TO_CLIENT = 0x01 CLIENT_TO_SERVER = 0x02 PROTOCOL_VERSION = 28 class Packet: def __init__(self, packet_type=0, **data): self.direction = 0 if type(packet_type) == str: packet_type = dict((v,k) for k,v in names.it...
class IncompleteData(Exception): pass
"""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
#!/usr/bin/python import struct import sys #TODO: Review which of these we actually need SERVER_TO_CLIENT = 0x01 CLIENT_TO_SERVER = 0x02 PROTOCOL_VERSION = 28 class Packet: def __init__(self, packet_type=0, **data): self.direction = 0 if type(packet_type) == str: packet_type = dict((v,k) for k,v in names.it...
if mtype2 == 1: o += self.pack('short', val) if mtype2 == 2: o += self.pack('int', val) if mtype2 == 3: o += self.pack('float', val) if mtype2 == 4: o += self.pack('string16', val) if mtype2 == 5: o += self.pack('short', val['id']) o += self.pack('byte', val['count']) o += self....
o += self.pack('byte', val)
conditional_block
packet_decoder.py
#!/usr/bin/python import struct import sys #TODO: Review which of these we actually need SERVER_TO_CLIENT = 0x01 CLIENT_TO_SERVER = 0x02 PROTOCOL_VERSION = 28 class Packet: def __init__(self, packet_type=0, **data): self.direction = 0 if type(packet_type) == str: packet_type = dict((v,k) for k,v in names.it...
# btypes.append(i['type']) # metadata.append(i['metadata']) # # packet.data['data_size'] = len(coords) # append += self.pack_array_fast('short', coords) # append += self.pack_array_fast('byte', btypes) # append += self.pack_array_fast('byte', metadata) #0x3C if packet.ident == 0x3C: ...
# coords = [] # btypes = [] # metadata = [] # for i in packet.data['blocks']: # coords.append(i['x'] << 12 | i['z'] << 8 | i['y'])
random_line_split
lib.rs
//! Async concurrent hashmap built on top of [dashmap](https://docs.rs/dashmap/). //! //! # Wait //! [`WaitMap`](crate::WaitMap) is a concurrent hashmap with an asynchronous `wait` operation. //! ``` //! # extern crate async_std; //! # extern crate waitmap; //! # use async_std::main; //! # use waitmap::WaitMap; //! # #...
/// assert!(*kv.key() == emma); /// assert!(*kv.value() == 0); /// assert!(kv.pair() == (&"Emma Goldman".to_string(), &0)); /// # Ok(()) /// # } /// ``` pub struct Ref<'a, K, V, S> { inner: one::Ref<'a, K, WaitEntry<V>, S>, } impl<'a, K: Eq + Hash, V, S: BuildHasher> Ref<'a, K, V, S> { pub fn key(&self) -> &K ...
/// 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
//! Async concurrent hashmap built on top of [dashmap](https://docs.rs/dashmap/). //! //! # Wait //! [`WaitMap`](crate::WaitMap) is a concurrent hashmap with an asynchronous `wait` operation. //! ``` //! # extern crate async_std; //! # extern crate waitmap; //! # use async_std::main; //! # use waitmap::WaitMap; //! # #...
} enum WaitEntry<V> { Waiting(WakerSet), Filled(V), } /// A shared reference to a `WaitMap` key-value pair. /// ``` /// # extern crate async_std; /// # extern crate waitmap; /// # use async_std::main; /// # use waitmap::{Ref, WaitMap}; /// # #[async_std::main] /// # async fn main() -> std::io::Result<()> { /...
{ 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
//! Async concurrent hashmap built on top of [dashmap](https://docs.rs/dashmap/). //! //! # Wait //! [`WaitMap`](crate::WaitMap) is a concurrent hashmap with an asynchronous `wait` operation. //! ``` //! # extern crate async_std; //! # extern crate waitmap; //! # use async_std::main; //! # use waitmap::WaitMap; //! # #...
(&mut self) -> &mut V { match self.inner.value_mut() { Filled(value) => value, _ => panic!(), } } pub fn pair(&self) -> (&K, &V) { (self.key(), self.value()) } pub fn pair_mut(&mut self) -> (&K, &mut V) { match self.inner.pair_mut() { ...
value_mut
identifier_name
lib.rs
//! Async concurrent hashmap built on top of [dashmap](https://docs.rs/dashmap/). //! //! # Wait //! [`WaitMap`](crate::WaitMap) is a concurrent hashmap with an asynchronous `wait` operation. //! ``` //! # extern crate async_std; //! # extern crate waitmap; //! # use async_std::main; //! # use waitmap::WaitMap; //! # #...
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
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "strings" "testing" "github.com/flynn/go-sql" "github.com/flynn/rpcplus" "github.com/go-martini/martini" tu "github.com/flynn/flynn-controller/testutils" ct "github.com/flynn/flynn-controller/types" "gi...
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
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "strings" "testing" "github.com/flynn/go-sql" "github.com/flynn/rpcplus" "github.com/go-martini/martini" tu "github.com/flynn/flynn-controller/testutils" ct "github.com/flynn/flynn-controller/types" "gi...
} func (s *S) TestCreateKey(c *C) { in := &ct.Key{Key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC5r1JfsAYIFi86KBa7C5nqKo+BLMJk29+5GsjelgBnCmn4J/QxOrVtovNcntoRLUCRwoHEMHzs3Tc6+PdswIxpX1l3YC78kgdJe6LVb962xUgP6xuxauBNRO7tnh9aPGyLbjl9j7qZAcn2/ansG1GBVoX1GSB58iBsVDH18DdVzlGwrR4OeNLmRQj8kuJEuKOoKEkW55CektcXjV08K3QSQID7aRNHg...
{ 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
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "strings" "testing" "github.com/flynn/go-sql" "github.com/flynn/rpcplus" "github.com/go-martini/martini" tu "github.com/flynn/flynn-controller/testutils" ct "github.com/flynn/flynn-controller/types" "gi...
func (s *S) TestReleaseList(c *C) { s.createTestRelease(c, &ct.Release{}) var list []ct.Release res, err := s.Get("/releases", &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), "") } func (s *S) TestKeyList(c *C) { s.cr...
{ 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
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "strings" "testing" "github.com/flynn/go-sql" "github.com/flynn/rpcplus" "github.com/go-martini/martini" tu "github.com/flynn/flynn-controller/testutils" ct "github.com/flynn/flynn-controller/types" "gi...
(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
import { Component, OnInit, Inject } from '@angular/core'; import { FormControl, Validators, FormGroup } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { ToastrService } from 'ngx-toastr'; import { Router } from '@angular/router'; import { Location } from '@angul...
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
import { Component, OnInit, Inject } from '@angular/core'; import { FormControl, Validators, FormGroup } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { ToastrService } from 'ngx-toastr'; import { Router } from '@angular/router'; import { Location } from '@angul...
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
import { Component, OnInit, Inject } from '@angular/core'; import { FormControl, Validators, FormGroup } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { ToastrService } from 'ngx-toastr'; import { Router } from '@angular/router'; import { Location } from '@angul...
this.dialogRef.close({ actualizar: false }); } }
tana() {
identifier_name
SuggestionManagerFRS.py
#This class implements methods which measure friendship between two users and make appropriate suggestion lists of users #to add in chat sessions and add as friends #The friendship is measured based on no of interactions between users against time #Therefore following class implements a scoring model to measure friend-...
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
#This class implements methods which measure friendship between two users and make appropriate suggestion lists of users #to add in chat sessions and add as friends #The friendship is measured based on no of interactions between users against time #Therefore following class implements a scoring model to measure friend-...
(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
#This class implements methods which measure friendship between two users and make appropriate suggestion lists of users #to add in chat sessions and add as friends #The friendship is measured based on no of interactions between users against time #Therefore following class implements a scoring model to measure friend-...
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
#This class implements methods which measure friendship between two users and make appropriate suggestion lists of users #to add in chat sessions and add as friends #The friendship is measured based on no of interactions between users against time #Therefore following class implements a scoring model to measure friend-...
#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
// Copyright 2021 BoCloud // // 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...
func (p *proxy) removeEndpointFromNode(nodeName string, spn ServicePortName, endpoint Endpoint) { node, ok := p.nodeSet[nodeName] if !ok { return } eps := node.EndpointMap[spn] eps.Remove(endpoint) if len(eps) == 0 { delete(node.EndpointMap, spn) } p.nodeSet[nodeName] = node } func (p *proxy) addServic...
{ 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
// Copyright 2021 BoCloud // // 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...
} if svc.Spec.ClusterIP == corev1.ClusterIPNone || svc.Spec.ClusterIP == "" { return true } if svc.Spec.Selector == nil || len(svc.Spec.Selector) == 0 { return true } return false } func makeServiceInfo(svc *corev1.Service) ServiceInfo { var stickyMaxAgeSeconds int32 if svc.Spec.SessionAffinity == corev...
func (p *proxy) shouldSkipService(svc *corev1.Service) bool { if svc.Spec.Type != corev1.ServiceTypeClusterIP { return true
random_line_split
proxy.go
// Copyright 2021 BoCloud // // 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...
iceAffinityClientIP { // Kube-apiserver side guarantees SessionAffinityConfig won't be nil when session affinity type is ClientIP stickyMaxAgeSeconds = *svc.Spec.SessionAffinityConfig.ClientIP.TimeoutSeconds } return ServiceInfo{ ClusterIP: svc.Spec.ClusterIP, SessionAffinity: svc.Spec.SessionA...
== corev1.Serv
identifier_name
proxy.go
// Copyright 2021 BoCloud // // 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...
rviceInfo(svc *corev1.Service) ServiceInfo { var stickyMaxAgeSeconds int32 if svc.Spec.SessionAffinity == corev1.ServiceAffinityClientIP { // Kube-apiserver side guarantees SessionAffinityConfig won't be nil when session affinity type is ClientIP stickyMaxAgeSeconds = *svc.Spec.SessionAffinityConfig.ClientIP.Time...
lse } func makeSe
conditional_block
maimemo_client.rs
use crate::client::*; use crate::config::*; use chrono::Local; use cookie_store::CookieStore; use reqwest::Client; use scraper::{Html, Selector}; use serde::{Deserialize, Serialize}; use std::fmt; /// notepad包含必要的header info和内容detail #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Notepad {
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
use crate::client::*; use crate::config::*; use chrono::Local; use cookie_store::CookieStore; use reqwest::Client; use scraper::{Html, Selector}; use serde::{Deserialize, Serialize}; use std::fmt; /// notepad包含必要的header info和内容detail #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Notepad { is_private: ...
gin().await.map_err(|e| format!("{:?}", e))?; Ok(()) } #[tokio::test] async fn get_notepad_list() -> Result<(), String> { init_log(); let config = Config::from_yaml_file(CONFIG_PATH).unwrap(); let mut client = MaimemoClient::new(config.maimemo.unwrap())?; if !client....
_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
use crate::client::*; use crate::config::*; use chrono::Local; use cookie_store::CookieStore; use reqwest::Client; use scraper::{Html, Selector}; use serde::{Deserialize, Serialize}; use std::fmt; /// notepad包含必要的header info和内容detail #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Notepad { is_private: ...
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
use crate::client::*; use crate::config::*; use chrono::Local; use cookie_store::CookieStore; use reqwest::Client; use scraper::{Html, Selector}; use serde::{Deserialize, Serialize}; use std::fmt; /// notepad包含必要的header info和内容detail #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Notepad { is_private: ...
t!(notepads.len() > 0); Ok(()) } #[tokio::test] async fn get_notepad_contents() -> Result<(), String> { init_log(); let config = Config::from_yaml_file(CONFIG_PATH).unwrap(); let mut client = MaimemoClient::new(config.maimemo.unwrap())?; if !client.has_logged() { ...
?; asser
identifier_name
note.py
import threading import time from DataBase import database from source import source from threadings import Tnuls from threads import qthreadt import threading import crawler ustr="" strl="" nustr="" bool=True urllist="" def bigin_click(self): # starttime=time.time(); #记录开始时间 if se...
t.start() source.isbigan=True if source.isbigan: t1 = threading.Thread(target=self.threadcl) #创建第一个子线程,子线程的任务 t1.setDaemon(True) t1.start() MainWindow.update() def show_click(self): MainWindow.getdata() MainW...
omboBox_2.currentText ()=="前程无忧": t=Tnuls(5)
conditional_block
note.py
import threading import time from DataBase import database from source import source from threadings import Tnuls from threads import qthreadt import threading import crawler ustr="" strl="" nustr="" bool=True urllist="" def bigin_click(self): # starttime=time.time(); #记录开始时间 if 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
import threading import time from DataBase import database from source import source from threadings import Tnuls from threads import qthreadt import threading import crawler ustr="" strl="" nustr="" bool=True urllist="" def bigin_click(self): # starttime=time.time(); #记录开始时间 if se...
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
import threading import time from DataBase import database from source import source from threadings import Tnuls from threads import qthreadt import threading import crawler ustr="" strl="" nustr="" bool=True urllist="" def bigin_click(self): # starttime=time.time(); #记录开始时间 if 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
"use strict"; /* global process */ /* global __dirname */ /******************************************************************************* * Copyright (c) 2015 IBM Corp. * * All rights reserved. * * Contributors: * David Huffman - Initial implementation ********************************************************...
/* ignore this code - 2/1/2016 var ws_cons = []; function broadcast(data){ for(var i in ws_cons){ try{ console.log('sending', i);//, ws); ws_cons[i].send(JSON.stringify(data)); } catch(e){ console.log('error ws', e); } } }*/ /* CCI improvements - [x] simpilify chaincode.json, remove discovery and...
{ 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
"use strict"; /* global process */ /* global __dirname */ /******************************************************************************* * Copyright (c) 2015 IBM Corp. * * All rights reserved. * * Contributors: * David Huffman - Initial implementation ********************************************************...
obc.load(options, cb_ready); //parse/load chaincode function cb_ready(err, cc){ //response has chaincode functions app1.setup(obc, cc); app2.setup(obc, cc); if(cc.details.deployed_name === ""){ //decide if i need to deploy cc.deploy('init', ['99'], './cc_summaries', cb_dep...
{ 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
"use strict"; /* global process */ /* global __dirname */ /******************************************************************************* * Copyright (c) 2015 IBM Corp. * * All rights reserved. * * Contributors: * David Huffman - Initial implementation ********************************************************...
(){ 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) { ...
cb_deployed
identifier_name
app.js
"use strict"; /* global process */ /* global __dirname */ /******************************************************************************* * Copyright (c) 2015 IBM Corp. * * All rights reserved. * * Contributors: * David Huffman - Initial implementation ********************************************************...
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
use libc::size_t; use std::cell::RefCell; use std::net::{IpAddr,SocketAddr}; use std::os::raw::c_void; use std::panic; use std::rc::Rc; use std::slice; use std::str::FromStr; use time::precise_time_ns; use mio::PollOpt; use pnet::packet::Packet; use pnet::packet::ethernet::{EthernetPacket, EtherTypes}; use pnet::packe...
} 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
use libc::size_t; use std::cell::RefCell; use std::net::{IpAddr,SocketAddr}; use std::os::raw::c_void; use std::panic; use std::rc::Rc; use std::slice; use std::str::FromStr; use time::precise_time_ns; use mio::PollOpt; use pnet::packet::Packet; use pnet::packet::ethernet::{EthernetPacket, EtherTypes}; use pnet::packe...
pub fn establish_upload_only(&mut self, tcp_pkt: &TcpPacket, flow: &Flow, tag_payload: &Vec<u8>) -> bool { let (_, master_key, server_random, client_random, session_id) = parse_tag_payload(tag_payload); let mut passive_ssl = EventedSSLEavesdropper::...
{ 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
use libc::size_t; use std::cell::RefCell; use std::net::{IpAddr,SocketAddr}; use std::os::raw::c_void; use std::panic; use std::rc::Rc; use std::slice; use std::str::FromStr; use time::precise_time_ns; use mio::PollOpt; use pnet::packet::Packet; use pnet::packet::ethernet::{EthernetPacket, EtherTypes}; use pnet::packe...
}, 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
use libc::size_t; use std::cell::RefCell; use std::net::{IpAddr,SocketAddr}; use std::os::raw::c_void; use std::panic; use std::rc::Rc; use std::slice; use std::str::FromStr; use time::precise_time_ns; use mio::PollOpt; use pnet::packet::Packet; use pnet::packet::ethernet::{EthernetPacket, EtherTypes}; use pnet::packe...
(&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
// Licensed to LinDB under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. LinDB licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compli...
(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
// Licensed to LinDB under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. LinDB licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compli...
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
// Licensed to LinDB under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. LinDB licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compli...
// createMemoryDatabase creates a new memory database for writing data points func (s *shard) createMemoryDatabase() (memdb.MemoryDatabase, error) { return newMemoryDBFunc(memdb.MemoryDatabaseCfg{ Name: s.databaseName, Metadata: s.metadata, TempPath: filepath.Join(s.path, filepath.Join(tempDir, fmt.Sprintf...
{ 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
// Licensed to LinDB under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. LinDB licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compli...
} s.ackReplicaSeq() return s.sequence.Close() } // IsFlushing checks if this shard is in flushing func (s *shard) IsFlushing() bool { return s.isFlushing.Load() } // NeedFlush checks if shard need to flush memory data func (s *shard) NeedFlush() bool { if s.IsFlushing() { return false } for _, memDB := rang...
{ return err }
conditional_block
agent.rs
use crate::agent::Capabilities; use crate::experiments::{Assignee, Experiment}; use crate::prelude::*; use crate::results::{DatabaseDB, EncodingType, ProgressData}; use crate::server::api_types::{AgentConfig, ApiResponse}; use crate::server::auth::{auth_filter, AuthDetails, TokenType}; use crate::server::messages::Mess...
{ 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
use crate::agent::Capabilities; use crate::experiments::{Assignee, Experiment}; use crate::prelude::*; use crate::results::{DatabaseDB, EncodingType, ProgressData}; use crate::server::api_types::{AgentConfig, ApiResponse}; use crate::server::auth::{auth_filter, AuthDetails, TokenType}; use crate::server::messages::Mess...
.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
use crate::agent::Capabilities; use crate::experiments::{Assignee, Experiment}; use crate::prelude::*; use crate::results::{DatabaseDB, EncodingType, ProgressData}; use crate::server::api_types::{AgentConfig, ApiResponse}; use crate::server::auth::{auth_filter, AuthDetails, TokenType}; use crate::server::messages::Mess...
; 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
use crate::agent::Capabilities; use crate::experiments::{Assignee, Experiment}; use crate::prelude::*; use crate::results::{DatabaseDB, EncodingType, ProgressData}; use crate::server::api_types::{AgentConfig, ApiResponse}; use crate::server::auth::{auth_filter, AuthDetails, TokenType}; use crate::server::messages::Mess...
{ 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
//! https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling use byteorder::{LittleEndian, BigEndian, ReadBytesExt, ByteOrder, WriteBytesExt}; use crate::names::{BusName, InterfaceName, ErrorName, MemberName}; use crate::writer::{DbusWriter, DbusWrite}; use crate::reader::{DbusReader, DbusR...
<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
//! https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling use byteorder::{LittleEndian, BigEndian, ReadBytesExt, ByteOrder, WriteBytesExt}; use crate::names::{BusName, InterfaceName, ErrorName, MemberName}; use crate::writer::{DbusWriter, DbusWrite}; use crate::reader::{DbusReader, DbusR...
/// 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
//! https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling use byteorder::{LittleEndian, BigEndian, ReadBytesExt, ByteOrder, WriteBytesExt}; use crate::names::{BusName, InterfaceName, ErrorName, MemberName}; use crate::writer::{DbusWriter, DbusWrite}; use crate::reader::{DbusReader, DbusR...
} struct Body { } impl DbusWrite for Body { fn write<T1, T2>(&self, writer: &mut DbusWriter<T1>) -> Result<(), io::Error> where T1: io::Write, T2: ByteOrder { unimplemented!(); } }
{ 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
package genotype // // this package implements // import ( "bufio" "bytes" "compress/gzip" "encoding/gob" "fmt" "hash/fnv" "log" "os" "strings" "time" ) const ( NO_CGST = "NA" ) // QueryList contains indexed queries and the names of all sequences type QueryList struct { Index QueryIndex Names []string ...
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
package genotype // // this package implements // import ( "bufio" "bytes" "compress/gzip" "encoding/gob" "fmt" "hash/fnv" "log" "os" "strings" "time" ) const ( NO_CGST = "NA" ) // QueryList contains indexed queries and the names of all sequences type QueryList struct { Index QueryIndex Names []string ...
// 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
package genotype // // this package implements // import ( "bufio" "bytes" "compress/gzip" "encoding/gob" "fmt" "hash/fnv" "log" "os" "strings" "time" ) const ( NO_CGST = "NA" ) // QueryList contains indexed queries and the names of all sequences type QueryList struct { Index QueryIndex Names []string ...
(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
package genotype // // this package implements // import ( "bufio" "bytes" "compress/gzip" "encoding/gob" "fmt" "hash/fnv" "log" "os" "strings" "time" ) const ( NO_CGST = "NA" ) // QueryList contains indexed queries and the names of all sequences type QueryList struct { Index QueryIndex Names []string ...
} // 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
mod business_logic_layer; mod data_access_layer; mod entities; use crate::business_logic_layer as bll; pub use crate::data_access_layer::MAX_DATAGRAM_SIZE; use crate::data_access_layer::{TypedClientSocket, TypedServerSocket}; pub use crate::entities::Exception; use std::collections::HashMap; use std::net::{SocketAddr,...
(&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
mod business_logic_layer; mod data_access_layer; mod entities; use crate::business_logic_layer as bll; pub use crate::data_access_layer::MAX_DATAGRAM_SIZE; use crate::data_access_layer::{TypedClientSocket, TypedServerSocket}; pub use crate::entities::Exception; use std::collections::HashMap; use std::net::{SocketAddr,...
} 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
mod business_logic_layer; mod data_access_layer; mod entities; use crate::business_logic_layer as bll; pub use crate::data_access_layer::MAX_DATAGRAM_SIZE; use crate::data_access_layer::{TypedClientSocket, TypedServerSocket}; pub use crate::entities::Exception; use std::collections::HashMap; use std::net::{SocketAddr,...
} 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
mod business_logic_layer; mod data_access_layer; mod entities; use crate::business_logic_layer as bll; pub use crate::data_access_layer::MAX_DATAGRAM_SIZE; use crate::data_access_layer::{TypedClientSocket, TypedServerSocket}; pub use crate::entities::Exception; use std::collections::HashMap; use std::net::{SocketAddr,...
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