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
mod.rs
#[structopt(long, global = true)] pub verbose: bool, /// Path to configuration file. #[structopt(long, short = "c", default_value = "wrangler.toml", global = true)] pub config: PathBuf, /// Environment to perform a command on. #[structopt(name = "env", long, short = "e", global = true)] ...
{ /// Interact with your Workers KV Namespaces #[structopt(name = "kv:namespace", setting = AppSettings::SubcommandRequiredElseHelp)] KvNamespace(kv::KvNamespace), /// Individually manage Workers KV key-value pairs #[structopt(name = "kv:key", setting = AppSettings::SubcommandRequiredElseHelp)] ...
Command
identifier_name
mod.rs
structopt(name = "type", long, short = "t")] target_type: Option<TargetType>, /// Initializes a Workers Sites project. Overrides `type` and `template` #[structopt(long, short = "s")] site: bool, }, /// Build your worker Build, /// Preview your code temporarily on cloud...
{ match input { "self" => Ok(String::from("self")), address => match IpAddr::from_str(address) { Ok(_) => Ok(address.to_owned()), Err(err) => anyhow::bail!("{}: {}", err, input), }, } }
identifier_body
mod.rs
pub mod exec { pub use super::build::build; pub use super::config::configure; pub use super::dev::dev; pub use super::generate::generate; pub use super::init::init; pub use super::kv::kv_bulk; pub use super::kv::kv_key; pub use super::kv::kv_namespace; pub use super::login::login; ...
pub mod subdomain; pub mod tail; pub mod whoami;
random_line_split
models.py
ifiableFields = ('cdateTime', 'ctype', 'desc', 'beat', 'addr','point', 'crimeCat') fieldName = models.CharField(max_length=20) prevVal = models.CharField(max_length=200) newVal = models.CharField(max_length=200) # HACK null=True required for legacy testing OCUpdate prevSocDT = models.DateTimeField(null=True) ne...
idx = models.AutoField(primary_key=True) name = models.CharField(max_length=100) boxidx = models.BigIntegerField(db_index=True) boxModDT = models.DateTimeField() # boxType = models.CharField(max_length=10) # folder,file kids = models.ManyToManyField('self', symmetrical=False,related_name='parent') froot = models...
identifier_body
models.py
0) # NULL ok fields ctype = models.CharField(max_length=100,blank=True,null=True) desc = models.CharField(max_length=200,blank=True,null=True) # beat from OPD (vs. geobeat determined by geo query) beat = models.CharField(max_length=20,blank=True,null=True) addr = models.CharField(max_length=100,blank=True,null=T...
(self): return '%s' % (self.desc) # 170329 # python manage.py ogrinspect /Data/sharedData/c4a_oakland/OAK_data/maps_oakland/tl_2010_06_zcta510/tl_2010_06_zcta510.shp Zip5Geo --multi --mapping class Zip5Geo(models.Model): statefp10 = models.CharField(max_length=2) zcta5ce10 = models.CharField(max_length=5) geoid1...
__unicode__
identifier_name
models.py
00) # NULL ok fields ctype = models.CharField(max_length=100,blank=True,null=True) desc = models.CharField(max_length=200,blank=True,null=True) # beat from OPD (vs. geobeat determined by geo query) beat = models.CharField(max_length=20,blank=True,null=True) addr = models.CharField(max_length=100,blank=True,null=...
nsuspect = models.IntegerField(blank=True,null=True) nvictim = models.IntegerField(blank=True,null=True) nhospital = models.IntegerField(blank=True,null=True) roList = models.CharField(max_length=200,blank=True,null=True) pcList = models.CharField(max_length=200,blank=True,null=True) def __unicode__(self): re...
random_line_split
test.rs
being pruned, this function should return the final /// 'result' of the computation or some value that can only be determined after /// the computation is done. pub trait TimingLeakTestCaseRunner<T, R> = Fn(&T) -> Result<R>; /// Test wrapper for executing some caller provided code to ensure that it /// 'probably' exe...
{ let mut out = vec![]; // All zeros. out.push(vec![0u8; length]); // All 0xFF. out.push(vec![0xFFu8; length]); // First byte set to value #1 out.push({ let mut v = vec![0u8; length]; v[0] = 0xAB; v }); // First byte set to value #2 out.push({ l...
identifier_body
test.rs
test cases. fn next_test_case(&mut self, out: &mut TimingLeakTestCase<Self::Data>) -> bool; } /// Function which runs some code being profiled once in the calling thread. /// /// To avoid computations being pruned, this function should return the final /// 'result' of the computation or some value that can only b...
/// code being profiled. /// /// NOTE: This can not track any work performed on other threads. pub struct TimingLeakTest<R, Gen, Runner> { test_case_generator: Gen, test_case_runner: Runner, options: TimingLeakTestOptions, r: PhantomData<R>, } pub struct TimingLeakTestOptions { /// Number of separa...
/// 2. A TimingLeakTestCaseRunner which takes a test case as input and runs the
random_line_split
test.rs
pub fn new( test_case_generator: Gen, test_case_runner: Runner, options: TimingLeakTestOptions, ) -> Self { Self { test_case_generator, test_case_runner, options, r: PhantomData, } } #[must_use] pub fn run(&mut sel...
RollingMean
identifier_name
registry-manager.ts
') throw new JspmUserError(`Path ${sourcePath} is not a valid file or directory.`); throw e; } } sourcePath = path.relative(projectPath, sourcePath) + '/'; if (isWindows) sourcePath = sourcePath.replace(winSepRegEx, '/'); source = sourceProtocol + s...
visitFileOrDir
identifier_name
registry-manager.ts
fetch.getCredentials.bind(fetch) }; this.fetch = fetch; // note which installs have been verified in this session // so we only have to perform verification once per package this.verifiedCache = {}; this.endpoints = new Map<string, { endpoint: RegistryEndpoint, cache: Cache }>(); this.cach...
// relative file path installs that are not for the top-level project are relative to their package real path if (packagePath !== process.cwd()) { if ((isWindows && (source[0] === '/' || source[0] === '\\')) ||
random_line_split
registry-manager.ts
= offline; this.preferOffline = preferOffline; this.cacheDir = cacheDir; this.strictSSL = strictSSL; this.timeouts = timeouts; this.defaultRegistry = defaultRegistry; this.instanceId = Math.round(Math.random() * 10**10); this.registries = registries; this.util = { encodeVersion: ...
async auth (url: URL, method: string, credentials: Credentials, unauthorizedHeaders?: Record<string, string>): Promise<string> { for (let [registry, { endpoint }] of this.endpoints.entries()) { if (!endpoint.auth) continue; if (await endpoint.auth(url, method, credentials, unauthorizedHeader...
{ const { endpoint } = this.getEndpoint(registryName); if (!endpoint.configure) throw new JspmUserError(`The ${registryName} registry doesn't have any configuration hook.`); await endpoint.configure(); }
identifier_body
client.go
sets replaces the current config with a new one in athread safe way // and returns the old config. func (s *ClientState) SetConfig(config *Config) *Config { s.mutex.Lock() defer s.mutex.Unlock() oldconfig := s.opts.Config s.opts.Config = config return oldconfig } // ServerUrl constructs the webesocker URL to con...
() { path := s.GetConfig().RedisMasterFile if !MasterFileExists(path) { s.UpdateMasterFile() return } masters := RedisMastersFromMasterFile(path) invalidSystems := make([]string, 0) for system, server := range masters { rs := s.RegisterSystem(system) if server != "" { rs.NewMaster(server) } if rs.c...
DetermineInitialMasters
identifier_name
client.go
sets replaces the current config with a new one in athread safe way // and returns the old config. func (s *ClientState) SetConfig(config *Config) *Config { s.mutex.Lock() defer s.mutex.Unlock() oldconfig := s.opts.Config s.opts.Config = config return oldconfig } // ServerUrl constructs the webesocker URL to con...
return nil } // RedeemToken checks the validity of the given token. func (s *RedisSystem) RedeemToken(token string) bool { if s.currentToken == "" || token > s.currentToken { s.currentToken = token } tokenValid := token >= s.currentToken if !tokenValid { logInfo("invalid token: %s is not greater or equal to ...
{ return s.SendPong(rs) }
conditional_block
client.go
Token if !tokenValid { logInfo("invalid token: %s is not greater or equal to %s", token, s.currentToken) } return tokenValid } // SendPong sends a PONG message to the server. func (s *ClientState) SendPong(rs *RedisSystem) error { return s.send(MsgBody{System: rs.system, Name: PONG, Id: s.opts.Id, Token: rs.curr...
}
random_line_split
client.go
sets replaces the current config with a new one in athread safe way // and returns the old config. func (s *ClientState) SetConfig(config *Config) *Config { s.mutex.Lock() defer s.mutex.Unlock() oldconfig := s.opts.Config s.opts.Config = config return oldconfig } // ServerUrl constructs the webesocker URL to con...
// Invalidate sets the current master for the given system to nil, removes the // corresponding line from the the redis master file and sends a // CLIENT_INVALIDATED message to the server, provided the token sent with the // message is valid. func (s *ClientState) Invalidate(msg MsgBody) error { rs := s.RegisterSyst...
{ rs := s.redisSystems[system] if rs == nil { rs = &RedisSystem{system: system} s.redisSystems[system] = rs } return rs }
identifier_body
indexer.pb.go
2 { if m != nil { return m.Partition } return 0 } type ResolveResponse struct { Ids []string `protobuf:"bytes,1,rep,name=ids" json:"ids,omitempty"` } func (m *ResolveResponse) Reset() { *m = ResolveResponse{} } func (m *ResolveResponse) String() string { return proto.CompactTextStr...
in := new(ValuesRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ResolverServer).Values(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/indexer.Resolver/Values", } handler := func(ctx context.Context, req interface{}) (interface{}, e...
func _Resolver_Values_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
random_line_split
indexer.pb.go
2 { if m != nil { return m.Partition } return 0 } type ResolveResponse struct { Ids []string `protobuf:"bytes,1,rep,name=ids" json:"ids,omitempty"` } func (m *ResolveResponse) Reset() { *m = ResolveResponse{} } func (m *ResolveResponse) String() string { return proto.CompactTextStr...
return MatcherType_Equal } func (m *Matcher) GetName() string { if m != nil { return m.Name } return "" } func (m *Matcher) GetValue() string { if m != nil { return m.Value } return "" } type ValuesRequest struct { Field string `protobuf:"bytes,1,opt,name=field" json:"field,omitempty"` Partition in...
{ return m.Type }
conditional_block
indexer.pb.go
2 { if m != nil { return m.Partition } return 0 } type ResolveResponse struct { Ids []string `protobuf:"bytes,1,rep,name=ids" json:"ids,omitempty"` } func (m *ResolveResponse) Reset() { *m = ResolveResponse{} } func (m *ResolveResponse) String() string { return proto.CompactTextStr...
func (c *resolverClient) Resolve(ctx context.Context, in *ResolveRequest, opts ...grpc.CallOption) (*ResolveResponse, error) { out := new(ResolveResponse) err := grpc.Invoke(ctx, "/indexer.Resolver/Resolve", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *resolverClient) V...
{ return &resolverClient{cc} }
identifier_body
indexer.pb.go
2 { if m != nil { return m.Partition } return 0 } type ResolveResponse struct { Ids []string `protobuf:"bytes,1,rep,name=ids" json:"ids,omitempty"` } func (m *ResolveResponse) Reset() { *m = ResolveResponse{} } func (m *ResolveResponse) String() string { return proto.CompactTextStr...
() ([]byte, []int) { return fileDescriptor0, []int{4} } func (m *ValuesResponse) GetValues() []string { if m != nil { return m.Values } return nil } func init() { proto.RegisterType((*ResolveRequest)(nil), "indexer.ResolveRequest") proto.RegisterType((*ResolveResponse)(nil), "indexer.ResolveResponse") proto.R...
Descriptor
identifier_name
tags.rs
public reexports of external crates. If /// that's the case, then the tags of the public reexported external /// crates are merged into the tags of the library. pub fn
(config: &Config, source: &SourceKind, dependencies: &Vec<SourceKind>) -> AppResult<Tags> { let lib_tags = try!(update_tags(config, source)); if lib_tags.is_up_to_date(&config.tags_k...
update_tags_and_check_for_reexports
identifier_name
tags.rs
!(""); } let mut crate_tags = Vec::<PathBuf>::new(); for rcrate in reexp_crates.iter() { if let Some(crate_dep) = dependencies.iter().find(|d| d.get_lib_name() == *rcrate) { crate_tags.push(try!(update_tags(config, crate_dep)).tags_file.clone()); } } if crate_tags.is_em...
{ let mut lib_file = src_dir.to_path_buf(); lib_file.push("src"); lib_file.push("lib.rs"); if ! lib_file.is_file() { return Ok(Vec::new()); } let contents = { let mut file = try!(File::open(&lib_file)); let mut contents = String::new(); try!(file.read_to_string(...
identifier_body
tags.rs
reexports of external crates. If /// that's the case, then the tags of the public reexported external /// crates are merged into the tags of the library. pub fn update_tags_and_check_for_reexports(config: &Config, source: &SourceKind, ...
merged_lines.sort(); merged_lines.dedup(); let mut tag_file = try!( OpenOptions::new() .create(true) .truncate(true) .read(true) .write(true) .open(into_tag_file) ); ...
{ let mut file_contents: Vec<String> = Vec::new(); for file in tag_files.iter() { let mut file = try!(File::open(file)); let mut contents = String::new(); try!(file.read_to_string(&mut contents)); file_contents.push(contents); ...
conditional_block
tags.rs
} merged_lines.sort(); merged_lines.dedup(); let mut tag_file = try!( OpenOptions::new() .create(true) .truncate(true) .read(true) .write(true) .open(into_tag_file) ...
/// get the commit hash of the current `HEAD` of the git repository located at `git_dir` fn get_commit_hash(git_dir: &Path) -> AppResult<String> {
random_line_split
auction.py
from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier from .metrics import compute_auc, compute_model_auc def run_selection(seed, n_samples, auction_size, n_auctions): seed +=1 np.random.seed(seed) ind = np.random.randint(0, n_samples, size=auction_s...
import argparse import numpy as np import operator import pandas
random_line_split
auction.py
'] x_te = dataset['X'] y_te = dataset['y'] ind = dataset['ind'] auction_type = dataset['auction_type'] reserve = dataset['reserve'] # Copy our sampled data x, y = x_te[ind, :].copy(), y_te[ind].copy() # True PClicks, with some noise pclick = model.predict_proba(x)[:, 1] ...
else: df['RankingPClick'] = df['PClick'] df = df[df['RankingPClick'] >= reserve].reset_index(drop=True) # Rank by pclick, then get position and layout. Apply max_slate here. df = df.sort_values(['AuctionId', 'RankingPClick'], ascending=False) df['Position'] = df.groupby('AuctionI...
df['RankingPClick'] = np.random.permutation(df['PClick'])
conditional_block
auction.py
def run_auction(dataset, seed, model, epsilon, auction_size, n_auctions, max_slate, position_effect=0): seed += 1 np.random.seed(seed) name = dataset['name'] x_te = dataset['X'] y_te = dataset['y'] ind = dataset['ind'] auction_type = dataset['auction_type'] reserve = ...
if any(x): return np.random.choice(np.where(x)[0]) else: return np.random.choice(np.where(x==False)[0])
identifier_body
auction.py
(seed, n_samples, auction_size, n_auctions): seed +=1 np.random.seed(seed) ind = np.random.randint(0, n_samples, size=auction_size*n_auctions) return ind, seed+1 def sample_true(x): if any(x): return np.random.choice(np.where(x)[0]) else: return np.random.choice(np.wh...
run_selection
identifier_name
base.py
'kind', 'blog', 'id', 'url', 'draft') HEADER_FMT = '%s: %s' PREFIX_HEAD = '' PREFIX_END = '' RE_SPLIT = re.compile(r'^(?:([^\n]*?!b.*?)\n\n)?(.*)', re.DOTALL | re.MULTILINE) RE_HEADER = re.compile(r'.*?([a-zA-Z0-9_-]+)\s*[=:]\s*(.*)\s*') SUPPORT_EMBED_IMAGES = True RE_IMG = re.c...
logging.warning('found no header')
conditional_block
base.py
True """ for k, v in header.items(): if k not in self.MERGE_HEADERS: continue if k == 'blog': v = v['id'] elif k == 'kind': v = v.replace('blogger#', '') self.set_header(k, v) @property def markup(self): """Return markup with markup_prefix and markup_suf...
"""Embed images on local filesystem as data URI >>> class Handler(BaseHandler): ... def _generate(self, source=None): return source >>> handler = Handler(None) >>> html = '<img src="http://example.com/example.png"/>' >>> print(handler.embed_images(html)) <img src="http://example.com/example.p...
identifier_body
base.py
from __future__ import print_function, unicode_literals import codecs import logging import re import warnings from abc import ABCMeta, abstractmethod from base64 import b64encode from hashlib import md5 from os.path import basename, exists, splitext HAS_SMARTYPANTS = False try: import smartypants HAS_SMARTYPAN...
# THE SOFTWARE.
random_line_split
base.py
= False try: import smartypants HAS_SMARTYPANTS = True except ImportError: pass class BaseHandler(): """The base clase of markup handler""" __metaclass__ = ABCMeta # default handler options OPTIONS = { 'markup_prefix': '', 'markup_suffix': '', 'smartypants': False, 'id_affix': None, ...
(self, header=None): """Generate header in text for writing back to the file >>> class Handler(BaseHandler): ... PREFIX_HEAD = 'foo ' ... PREFIX_END = 'bar' ... HEADER_FMT = '--- %s: %s' ... def _generate(self, source=None): pass >>> handler = Handler(None) >>> print(handler.gen...
generate_header
identifier_name
process_all_day_long.py
0 Initial Analysis on raw data detect the related words label the sentiment @author: ciciwang """ import time import couchdb import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer import json import re """ nltk function declaration """ nltk.download('stopwords') nltk.download('wordnet') nltk.down...
(processed_text, keyword_list) ->bool: for word in keyword_list: if word in processed_text: return True return False #SentimentIntensityAnalyzer def IdentifySentiment( sentence ): sia = SentimentIntensityAnalyzer() ps = sia.polarity_scores( sentence ) sentiment = max(ps, key = ...
keyword_exist
identifier_name
process_all_day_long.py
0 Initial Analysis on raw data detect the related words label the sentiment @author: ciciwang """ import time import couchdb import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer import json import re """ nltk function declaration """ nltk.download('stopwords') nltk.download('wordnet') nltk.down...
pov_percent = pov_data["pov_rt_exc_hc_syn"] inc_median = pov_data["inc_median_syn"] iloc = pov_data["sa2_name16"] loc = sub_name_normalized(iloc) poverty_rate.update({ loc : pov_percent }) houshold_income.update({ loc : inc_median}) """ Load data from CouchDB... Create new database ""...
pov_data["inc_median_syn"] = 0
conditional_block
process_all_day_long.py
20 Initial Analysis on raw data detect the related words label the sentiment @author: ciciwang """ import time import couchdb import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer import json import re """ nltk function declaration """ nltk.download('stopwords') nltk.download('wordnet') nltk.dow...
while True: """ Load data from CouchDB... Create new database or save updated data """ couch = couchdb.Server("http://user:pass@172.26.133.141:5984") db = couch['melb'] #couch.delete('tweets_analyzed') if "tweets_analyzed" in couch: db2 = couch["tweets_analyzed"] ...
""" Load data from CouchDB... Create new database """ id_list = []
random_line_split
process_all_day_long.py
0 Initial Analysis on raw data detect the related words label the sentiment @author: ciciwang """ import time import couchdb import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer import json import re """ nltk function declaration """ nltk.download('stopwords') nltk.download('wordnet') nltk.down...
# check whether the keyword in the text or not def keyword_exist(processed_text, keyword_list) ->bool: for word in keyword_list: if word in processed_text: return True return False #SentimentIntensityAnalyzer def IdentifySentiment( sentence ): sia = SentimentIntensityAnalyzer() p...
text = text.lower() # tokenized words = tokenizer.tokenize(text) # check if word is alphabetic words = [w for w in words if w.isalpha()] # lemmatized words = [lemmatisation(w) for w in words] init_processed_text = " ".join(words) return init_processed_text
identifier_body
app.js
(this.g, 90); this.size = Math.max(this.size + this.sizeinc, 0); this.spd += this.spdinc; this.g += this.grav; this.d += this.dinc; this.r += this.rinc; } render() { Draw.setAlpha(this.a); Draw.setColor(this.c); Draw.circle(this.x, this.y, this.size); Draw.setAlpha(1); } } const Emitter = { depth...
mid
identifier_name
app.js
this.list[this.classes.indexOf(cls)].push(n); n.start(); return n; }, update() { for (const o of this.list) { for (const i of o) { if (i) { if (i.active) { i.earlyUpdate(); i.update(); } } } } }, render() { for (const o of this.list) { for (const i of o) { if (i...
start() {} earlyUpdate() {} update() {} render() {} renderUI() {} } class BranthParticle extends BranthObject { constructor(x, y, spd, spdinc, size, sizeinc, d, dinc, r, rinc, a, c, life, grav) { super(x, y); this.spd = spd; this.spdinc = spdinc; this.size = size; this.sizeinc = sizeinc; this.d = d;...
{ this.id = OBJ.ID++; this.active = true; this.visible = true; this.x = x; this.y = y; }
identifier_body
app.js
} }, clear(cls) { this.list[this.classes.indexOf(cls)] = []; }, clearAll() { for (const i in this.list) { this.list[i] = []; } } }; class BranthObject { constructor(x, y) { this.id = OBJ.ID++; this.active = true; this.visible = true; this.x = x; this.y = y; } start() {} earlyUpdate() {} up...
{ i.renderUI(); }
conditional_block
app.js
(0, 0); this.setAlpha(0.2, 0.2); this.setColor(C.fireBrick); this.setLife(3000, 4000); this.setGravity(0, 0); break; case 'sparkle': this.setSpeed(2, 5); this.setSpeedInc(-0.1, -0.1); this.setSize(5, 10); this.setSizeInc(-0.1, -0.1); this.setDirection(0, 360); this.setDire...
let isMeet = true;
random_line_split
app.go
{ app.msg.Debugf("configuring [%s]...\n", tsk.Name()) cfg, ok := tsk.(Configurer) if !ok { continue } err = cfg.Configure(tsks[i]) if err != nil { return err } } err = app.printDataFlow() if err != nil { return err } app.ctxs[0] = tsks app.ctxs[1] = svcs app.state = fsm.Configured app.m...
var err error defer app.msg.flush() app.comps = nil app.tsks = nil app.svcs = nil app.state = fsm.Offline app.props = nil app.dflow = nil app.store = nil return err }
identifier_body
app.go
type appmgr struct { state fsm.State name string props map[string]map[string]interface{} dflow *dflowsvc store *datastore msg msgstream evtmax int64 nprocs int comps map[string]Component tsks []Task svcs []Svc istream Task ctxs [2][]ctxType } // NewApp creates a (default) fwk application...
"go-hep.org/x/hep/fwk/fsm" )
random_line_split
app.go
) []Component { comps := make([]Component, 0, len(app.comps)) for _, c := range app.comps { comps = append(comps, c) } return comps } func (app *appmgr) AddTask(tsk Task) error { var err error app.tsks = append(app.tsks, tsk) app.comps[tsk.Name()] = tsk return err } func (app *appmgr) DelTask(tsk Task) erro...
omponents(
identifier_name
app.go
[tsk.Name()] = tsk return err } func (app *appmgr) DelTask(tsk Task) error { var err error tsks := make([]Task, 0, len(app.tsks)) for _, t := range app.tsks { if t.Name() != tsk.Name() { tsks = append(tsks, t) } } app.tsks = tsks return err } func (app *appmgr) HasTask(n string) bool { for _, t := rang...
if app.state == fsm.Started { err = app.run(ctx) if err != nil && err != io.EOF { return err } } if app.state == fsm.Running { err = app.stop(ctx) if err != nil { return err } } if app.state == fsm.Stopped { err = app.shutdown(ctx) if err != nil { return err } } app.msg.Infof("cpu:...
err = app.start(ctx) if err != nil { return err } }
conditional_block
Step.py
Stats as statclass from pySDC import Hooks as hookclass import copy as cp import sys class step(): """ Step class, referencing most of the structure needed for the time-stepping This class bundles multiple levels and the corresponding transfer operators and is used by the methods (e.g. SDC and MLSDC...
# generate list of dictionaries out of the description descr_list = self.__dict_to_list(descr_new) # sanity check: is there a transfer class? is there one even if only a single level is specified? if len(descr_list) > 1: assert 'transfer_class' in descr_new asser...
random_line_split
Step.py
as statclass from pySDC import Hooks as hookclass import copy as cp import sys class step(): """ Step class, referencing most of the structure needed for the time-stepping This class bundles multiple levels and the corresponding transfer operators and is used by the methods (e.g. SDC and MLSDC). Sta...
# set params and status self.params = pars(params) self.status = status() # empty attributes self.__transfer_dict = {} self.levels = [] self.__prev = None def generate_hierarchy(self,descr): """ Routine to generate the level hierarchy for a...
self.iter = None self.stage = None self.slot = None self.first = None self.last = None self.pred_cnt = None self.done = None self.time = None self.dt = None self.step = None
identifier_body
Step.py
as statclass from pySDC import Hooks as hookclass import copy as cp import sys class step(): """ Step class, referencing most of the structure needed for the time-stepping This class bundles multiple levels and the corresponding transfer operators and is used by the methods (e.g. SDC and MLSDC). Sta...
return ld def register_level(self,L): """ Routine to register levels This routine will append levels to the level list of the step instance and link the step to the newly registered level (Level 0 will be considered as the finest level). It will also allocate the tau corr...
ld[d][k] = v[d]
conditional_block
Step.py
as statclass from pySDC import Hooks as hookclass import copy as cp import sys class step(): """ Step class, referencing most of the structure needed for the time-stepping This class bundles multiple levels and the corresponding transfer operators and is used by the methods (e.g. SDC and MLSDC). Sta...
(self): """ Getter for previous step Returns: prev """ return self.__prev @prev.setter def
prev
identifier_name
cubicbez.rs
2.midpoint(self.p3), self.p3, ), ) } } impl ParamCurveDeriv for CubicBez { type DerivResult = QuadBez; #[inline] fn deriv(&self) -> QuadBez { QuadBez::new( (3.0 * (self.p1 - self.p0)).to_point(), (3.0 * (self.p2 - self.p1)).to_point()...
z_arclen() {
identifier_name
cubicbez.rs
let p0 = self.eval(t0); let p3 = self.eval(t1); let d = self.deriv(); let scale = (t1 - t0) * (1.0 / 3.0); let p1 = p0 + scale * d.eval(t0).to_vec2(); let p2 = p3 - scale * d.eval(t1).to_vec2(); CubicBez { p0, p1, p2, p3 } } /// Subdivide into halves, usi...
fn subsegment(&self, range: Range<f64>) -> CubicBez { let (t0, t1) = (range.start, range.end);
random_line_split
cubicbez.rs
((self.p0.to_vec2() + self.p1.to_vec2() * 2.0 + self.p2.to_vec2()) * 0.25) .to_point(), pm, ), CubicBez::new( pm, ((self.p1.to_vec2() + self.p2.to_vec2() * 2.0 + self.p3.to_vec2()) * 0.25) .to...
0.999_999 * libm::pow(self.max_hypot2 / err, 1. / 6.0) //// ////0.999_999 * (self.max_hypot2 / err).powf(1. / 6.0) }; t1 = t0 + shrink * (t1 - t0); } } } } #[cfg(test)] mod tests { use crate::{ Affine, CubicBez...
0.5 } else {
conditional_block
cubicbez.rs
((self.p0.to_vec2() + self.p1.to_vec2() * 2.0 + self.p2.to_vec2()) * 0.25) .to_point(), pm, ), CubicBez::new( pm, ((self.p1.to_vec2() + self.p2.to_vec2() * 2.0 + self.p3.to_vec2()) * 0.25) .to...
l ParamCurveNearest for CubicBez { /// Find nearest point, using subdivision. fn nearest(&self, p: Point, accuracy: f64) -> (f64, f64) { let mut best_r = None; let mut best_t = 0.0; for (t0, t1, q) in self.to_quads(accuracy) { let (t, r) = q.nearest(p, accuracy); ...
(self.p0.x * (6.0 * self.p1.y + 3.0 * self.p2.y + self.p3.y) + 3.0 * (self.p1.x * (-2.0 * self.p0.y + self.p2.y + self.p3.y) - self.p2.x * (self.p0.y + self.p1.y - 2.0 * self.p3.y)) - self.p3.x * (self.p0.y + 3.0 * self.p1.y + 6.0 * self.p2.y)) ...
identifier_body
logs.go
.Duration maxEventsPerRequest int nextStartTime time.Time groupRequests []groupRequest autodiscover *AutodiscoverConfig logger *zap.Logger client client consumer consumer.Logs wg *sync.WaitGroup doneChan chan bool } const maxL...
if nextToken != "" { base.NextToken = aws.String(nextToken) } return base } func (sn *streamNames) groupName() string { return sn.group } type streamPrefix struct { group string prefix *string } func (sp *streamPrefix) request(limit int, nextToken string, st, et *time.Time) *cloudwatchlogs.FilterLogEventsI...
{ base.LogStreamNames = sn.names }
conditional_block
logs.go
.Duration maxEventsPerRequest int nextStartTime time.Time groupRequests []groupRequest autodiscover *AutodiscoverConfig logger *zap.Logger client client consumer consumer.Logs wg *sync.WaitGroup doneChan chan bool } const maxL...
func (sp *streamPrefix) groupName() string { return sp.group } type groupRequest interface { request(limit int, nextToken string, st, et *time.Time) *cloudwatchlogs.FilterLogEventsInput groupName() string } func newLogsReceiver(cfg *Config, logger *zap.Logger, consumer consumer.Logs) *logsReceiver { groups := [...
{ base := &cloudwatchlogs.FilterLogEventsInput{ LogGroupName: &sp.group, StartTime: aws.Int64(st.UnixMilli()), EndTime: aws.Int64(et.UnixMilli()), Limit: aws.Int64(int64(limit)), LogStreamNamePrefix: sp.prefix, } if nextToken != "" { base.NextToken = aws.String(...
identifier_body
logs.go
.Duration maxEventsPerRequest int nextStartTime time.Time groupRequests []groupRequest autodiscover *AutodiscoverConfig logger *zap.Logger client client consumer consumer.Logs wg *sync.WaitGroup doneChan chan bool } const maxL...
func (l *logsReceiver) poll(ctx context.Context) error { var errs error startTime := l.nextStartTime endTime := time.Now() for _, r := range l.groupRequests { if err := l.pollForLogs(ctx, r, startTime, endTime); err != nil { errs = errors.Join(errs, err) } } l.nextStartTime = endTime return errs } func ...
random_line_split
logs.go
.Duration maxEventsPerRequest int nextStartTime time.Time groupRequests []groupRequest autodiscover *AutodiscoverConfig logger *zap.Logger client client consumer consumer.Logs wg *sync.WaitGroup doneChan chan bool } const maxL...
(ctx context.Context) error { var errs error startTime := l.nextStartTime endTime := time.Now() for _, r := range l.groupRequests { if err := l.pollForLogs(ctx, r, startTime, endTime); err != nil { errs = errors.Join(errs, err) } } l.nextStartTime = endTime return errs } func (l *logsReceiver) pollForLog...
poll
identifier_name
compliancescan_types.go
ebuilder:default={"ReadWriteOnce"} PVAccessModes []corev1.PersistentVolumeAccessMode `json:"pvAccessModes,omitempty"` // By setting this, it's possible to configure where the result server instances // are run. These instances will mount a Persistent Volume to store the raw // results, so special care should be tak...
GetScanType
identifier_name
compliancescan_types.go
ating] = 3 orderedStates[PhaseDone] = 4 if orderedStates[lowPhase] > orderedStates[scanPhase] { return scanPhase } return lowPhase } // Represents the result of the compliance scan type ComplianceScanStatusResult string // CmScanResultAnnotation holds the processed scanner result const CmScanResultAnnotation =...
// Is the path to the file that contains the content (the data stream). // Note that the path needs to be relative to the `/` (root) directory, as // it is in the ContentImage Content string `json:"content,omitempty"` // By setting this, it's possible to only run the scan on certain nodes in // the cluster. Note ...
random_line_split
compliancescan_types.go
will be created with. // The persistent volume will hold the raw results of the scan. // +kubebuilder:default={"ReadWriteOnce"} PVAccessModes []corev1.PersistentVolumeAccessMode `json:"pvAccessModes,omitempty"` // By setting this, it's possible to configure where the result server instances // are run. These inst...
{ if strings.ToLower(string(cs.Spec.ScanType)) == strings.ToLower(string(ScanTypePlatform)) { return ScanTypePlatform, nil } if strings.ToLower(string(cs.Spec.ScanType)) == strings.ToLower(string(ScanTypeNode)) { return ScanTypeNode, nil } return "", ErrUnkownScanType }
identifier_body
compliancescan_types.go
// Specifies the access modes that the PersistentVolume will be created with. // The persistent volume will hold the raw results of the scan. // +kubebuilder:default={"ReadWriteOnce"} PVAccessModes []corev1.PersistentVolumeAccessMode `json:"pvAccessModes,omitempty"` // By setting this, it's possible to configure w...
{ return ScanTypeNode, nil }
conditional_block
tf_train.py
.abspath(ABS_PATH+"/"+DATA_DIR), filename) cPickle.dump(data, open(filename, 'w')) def get_features(requests): vectorizer = PolitenessFeatureVectorizer() fks = False X, y = [], [] for req in requests: # get unigram, bigram features + politeness strategy features # in this s...
elif train_size < CURR_BATCH + batch_size: end_batch = train_size batch_xs = X[CURR_BATCH:end_batch] batch_ys = y[CURR_BATCH:end_batch] CURR_BATCH = CURR_BATCH + batch_size return batch_xs, batch_ys, CURR_BATCH def hidden_layers(_X, _weights, _biases, params): if params["n_layers"] =...
return
conditional_block
tf_train.py
.abspath(ABS_PATH+"/"+DATA_DIR), filename) cPickle.dump(data, open(filename, 'w')) def get_features(requests): vectorizer = PolitenessFeatureVectorizer() fks = False X, y = [], [] for req in requests: # get unigram, bigram features + politeness strategy features # in this s...
(): print "Starting grid_search for TF in /tensorflow" params = {} lr_options = [ 0.0015, 0.01, 0.005, 0.001 ] te_options = [ 10, 50, 80, 100, 150 ] bs_options = [ 100 ] n_hidden_1 = [ 562 ] n_hidden_2 = [ 562 ] l1_functions = [ tf.nn.relu ] l2_functions = [ tf.nn.relu ] # numb...
grid_search
identifier_name
tf_train.py
, _weights['out']) + _biases['out'] # return tf.nn.softmax(tf.matmul(hidden, _weights['out']) + _biases['out']) def weights_and_biases(params): if params["n_layers"] == 1: weights = { 'h1': tf.Variable(tf.random_normal([params["n_input"], params["n_hidden_1"]])), 'out': tf.Varia...
import matplotlib.pyplot as plt # for plotting plt.plot(errors) plt.xlabel('#epochs') plt.ylabel('MSE') import pylab pylab.show()
identifier_body
tf_train.py
2'])) return tf.matmul(hidden, _weights['out']) + _biases['out'] # return tf.nn.softmax(tf.matmul(hidden, _weights['out']) + _biases['out']) def weights_and_biases(params): if params["n_layers"] == 1: weights = { 'h1': tf.Variable(tf.random_normal([params["n_input"], params["n_hidden_...
random_line_split
core1500.js
きこえます。I hear a strange sound.', id: 28 }, { kan: '一生懸命', tran: 'いっしょうけんめい', english: 'hard-working, doing one\'s best', sentences: '彼は毎日一生懸命働いている。かれ は まいにち いっしょうけんめい はたらいて いる。He works hard every day.', id: 29 }, { kan: '間違う', tran: 'まちがう', english: 'make a mistake, be wrong', sentences: 'あなたは間違っている。...
id: 56 }, { kan: '真っ直ぐ',
random_line_split
ha_tracker.go
UpdateTimeoutJitterMax = errors.New("HA tracker max update timeout jitter shouldn't be negative") errInvalidFailoverTimeout = "HA Tracker failover timeout (%v) must be at least 1s greater than update timeout - max jitter (%v)" ) // ProtoReplicaDescFactory makes new InstanceDescs func ProtoReplicaDescFactory()...
} // There was either invalid or no data for the key, so we now accept samples
random_line_split
ha_tracker.go
ReplicaDesc() } // NewReplicaDesc returns an empty *distributor.ReplicaDesc. func NewReplicaDesc() *ReplicaDesc { return &ReplicaDesc{} } // Track the replica we're accepting samples from // for each HA cluster we know about. type haTracker struct { logger log.Logger cfg HATrackerConfi...
replicasNotMatchError
identifier_name
ha_tracker.go
:"enable_ha_tracker,omitempty"` // We should only update the timestamp if the difference // between the stored timestamp and the time we received a sample at // is more than this duration. UpdateTimeout time.Duration `yaml:"ha_tracker_update_timeout"` UpdateTimeoutJitterMax time.Duration `yaml:"ha_tracker...
{ if pair.Name == replicaLabel { replica = string(pair.Value) } if pair.Name == clusterLabel { cluster = string(pair.Value) } }
conditional_block
ha_tracker.go
} // Track the replica we're accepting samples from // for each HA cluster we know about. type haTracker struct { logger log.Logger cfg HATrackerConfig client kv.Client updateTimeoutJitter time.Duration // Replicas we are accepting samples from. electedLock sync.RWMutex...
{ return httpgrpc.Errorf(http.StatusAccepted, "replicas did not mach, rejecting sample: replica=%s, elected=%s", replica, elected) }
identifier_body
file.go
fid := range fs.Pool { if fid.file == file { fid.Path = new_path } else if other_file != nil && fid.file == other_file { // Since we hold at least one reference // to other_file, this should never trigger // a full cleanup of other_file. It's safe // to call DecRef here while locking the lock. fi...
unlock
identifier_name
file.go
, backing_paths := range fs.Read { if strings.HasPrefix(filepath, prefix) && (!file.read_exists || len(prefix) > len(read_prefix)) { for _, backing_path := range backing_paths { // Does this file exist? test_path := path.Join(backing_path, filepath[len(prefix):]) err := syscall.Lstat(test_path...
var stat syscall.Stat_t err := syscall.Lstat(file.write_path, &stat) if err == nil { if stat.Mode&syscall.S_IFDIR != 0 { err = syscall.Rmdir(file.write_path) if err != nil { return err } } else { err = syscall.Unlink(file.write_path) if err != nil { return err } } } file.write_ex...
{ err := cleardelattr(file.write_path) if err != nil { return err } }
conditional_block
file.go
file.write_exists = true file.write_deleted, _ = readdelattr(file.write_path) if !file.write_deleted { file.mode = stat.Mode } } else { file.write_exists = false file.write_deleted = false } // Figure out our read path. read_prefix := write_prefix read_backing_path := write_backing_path file.read_...
{ // Figure out our write path first. write_prefix := "" write_backing_path := "." for prefix, backing_path := range fs.Write { if strings.HasPrefix(filepath, prefix) && len(prefix) > len(write_prefix) { write_prefix = prefix write_backing_path = backing_path } } file.write_path = path.Join( writ...
identifier_body
file.go
(filepath, prefix) && (!file.read_exists || len(prefix) > len(read_prefix)) { for _, backing_path := range backing_paths { // Does this file exist? test_path := path.Join(backing_path, filepath[len(prefix):]) err := syscall.Lstat(test_path, &stat) if err == nil { // Check if it's delete...
return err } }
random_line_split
controller.rs
ileContext, ReconcileStatus}, }; use self::collect::ControllerDescriptionCollector; use crate::controller::reconcile_queue::QueueConfig; use anyhow::Context as _; use async_trait::async_trait; use futures::future::FutureExt; use k8s_openapi::{ apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDe...
}; tokio::time::sleep(Duration::from_secs(sleep_timeout)).await; } } }; tokio::task::spawn(version_skew_check_fut); //tracing::info!("Discovering cluster APIs"); //let discovery = Arc::new(Discovery::new(&client).aw...
{ tracing::warn!("Failed to validate api server version: {:#}", e); 10 }
conditional_block
controller.rs
ileContext, ReconcileStatus}, }; use self::collect::ControllerDescriptionCollector; use crate::controller::reconcile_queue::QueueConfig; use anyhow::Context as _; use async_trait::async_trait; use futures::future::FutureExt; use k8s_openapi::{ apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDe...
(&self) { if let Some(crd) = self.meta.crd.as_ref() { let res = (self.vtable.api_resource)(); assert_eq!(crd.spec.names.plural, res.plural); assert_eq!(crd.spec.names.kind, res.kind); assert_eq!(crd.spec.group, res.group); let has_version = crd.spec.ve...
validate
identifier_name
controller.rs
ileContext, ReconcileStatus}, }; use self::collect::ControllerDescriptionCollector; use crate::controller::reconcile_queue::QueueConfig; use anyhow::Context as _; use async_trait::async_trait; use futures::future::FutureExt; use k8s_openapi::{ apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDe...
} Ok(()) } } /// Description of a controller #[derive(Clone)] struct ControllerDescription { name: String, crd: Option<CustomResourceDefinition>, watches: Vec<ApiResource>, } #[derive(Clone)] pub(crate) struct DynController { meta: ControllerDescription, vtable: ControllerVtabl...
random_line_split
fileopenmodeenum.go
Mode values may be or'd with a FileOpenType // code in order to control behavior. // // In addition, one of the three codes may be or'd with // zero or more of the following File Open Modes (Type: 'FileOpenMode') // to better control file open behavior. // // FileOpenMode has been adapted to function as an enumeration...
// None - No File Open Mode is active func (fOpenMode FileOpenMode) ModeNone() FileOpenMode { return FileOpenMode(-1) } // Append - append data to the file when writing. func (fOpenMode FileOpenMode) ModeAppend() FileOpenMode { return FileOpenMode(os.O_APPEND) } // Create - create a new file if none exists. func (fOp...
// Reference CONSTANTS: https://golang.org/pkg/os/ // type FileOpenMode int
random_line_split
fileopenmodeenum.go
Mode values may be or'd with a FileOpenType // code in order to control behavior. // // In addition, one of the three codes may be or'd with // zero or more of the following File Open Modes (Type: 'FileOpenMode') // to better control file open behavior. // // FileOpenMode has been adapted to function as an enumeration...
// Exclusive - used with FileOpenControlMode(0).Create(), file must not exist. func (fOpenMode FileOpenMode) ModeExclusive() FileOpenMode { return FileOpenMode(os.O_EXCL) } // Sync - open for synchronous I/O. func (fOpenMode FileOpenMode) ModeSync() FileOpenMode { return FileOpenMode(os.O_SYNC) } // Truncate - if p...
{ return FileOpenMode(os.O_CREATE) }
identifier_body
fileopenmodeenum.go
Mode values may be or'd with a FileOpenType // code in order to control behavior. // // In addition, one of the three codes may be or'd with // zero or more of the following File Open Modes (Type: 'FileOpenMode') // to better control file open behavior. // // FileOpenMode has been adapted to function as an enumeration...
() FileOpenMode { return FileOpenMode(os.O_SYNC) } // Truncate - if possible, truncate file when opened. func (fOpenMode FileOpenMode) ModeTruncate() FileOpenMode { return FileOpenMode(os.O_TRUNC) } // IsValid - If the value of the current FileOpenMode is 'invalid', // this method will return an error. If the FileOpe...
ModeSync
identifier_name
fileopenmodeenum.go
Mode values may be or'd with a FileOpenType // code in order to control behavior. // // In addition, one of the three codes may be or'd with // zero or more of the following File Open Modes (Type: 'FileOpenMode') // to better control file open behavior. // // FileOpenMode has been adapted to function as an enumeration...
result = FileOpenMode(idx) } else { valueString = strings.ToLower(valueString) if !strings.HasPrefix(valueString, "mode") { valueString = "mode" + valueString } idx, ok = mFileOpenModeLwrCaseStringToInt[valueString] if !ok { return FileOpenMode(0), fmt.Errorf(ePrefix...
{ return FileOpenMode(0), fmt.Errorf(ePrefix+ "'valueString' did NOT MATCH a FileOpenMode. valueString='%v' ", valueString) }
conditional_block
partner.py
self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id return user_company.partner_id and user_company.partner_id.country_id \ and user_company.partner_id.country_id.code or 'XX' def default_get(self, cr, uid, fields, context=None): """ Load the country code of...
es_vat_check(s
identifier_name
partner.py
as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PUR...
continue return True def _check_vat_mandatory(self, cr, uid, ids, context=None): """ This method will check the vat mandatoriness in partners for those user logged on with a Venezuelan Company The method will return True when: *) The user's co...
turn False
conditional_block
partner.py
of the user company. """ context = context or {} res= {}.fromkeys(ids,self._get_country_code(cr,uid,context=context)) return res _columns = { 'seniat_updated': fields.boolean('Seniat Updated', help="This field indicates if partner was updated using SENIAT button"...
" Load the rif and name of the partner from the database seniat """ if context is None: context = {} su_obj = self.pool.get('seniat.url') return su_obj.update_rif(cr, uid, ids, context=context)
identifier_body
partner.py
as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PUR...
""" context = context or {} user_company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id return user_company.partner_id and user_company.partner_id.country_id \ and user_company.partner_id.country_id.code or 'XX' def default_get(self, cr...
""" Return the country code of the user company. If not exists, return XX.
random_line_split
flex.rs
parameters, which will simplify your code considerably. use druid::text::format::ParseFormatter; use druid::widget::prelude::*; use druid::widget::{ Button, Checkbox, CrossAxisAlignment, Flex, Label, MainAxisAlignment, ProgressBar, RadioGroup, SizedBox, Slider, Stepper, Switch, TextBox, WidgetExt, }; use drui...
} fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &AppState, env: &Env, ) -> Size { self.inner.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &AppState, env: &Env) { self.inner.paint(ctx, dat...
{ self.inner.update(ctx, old_data, data, env); }
conditional_block
flex.rs
these parameters, which will simplify your code considerably. use druid::text::format::ParseFormatter; use druid::widget::prelude::*; use druid::widget::{ Button, Checkbox, CrossAxisAlignment, Flex, Label, MainAxisAlignment, ProgressBar, RadioGroup, SizedBox, Slider, Stepper, Switch, TextBox, WidgetExt, }; us...
( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &AppState, env: &Env, ) -> Size { self.inner.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &AppState, env: &Env) { self.inner.paint(ctx, data, env) } fn...
layout
identifier_name
flex.rs
these parameters, which will simplify your code considerably. use druid::text::format::ParseFormatter; use druid::widget::prelude::*; use druid::widget::{ Button, Checkbox, CrossAxisAlignment, Flex, Label, MainAxisAlignment, ProgressBar, RadioGroup, SizedBox, Slider, Stepper, Switch, TextBox, WidgetExt, }; us...
const MAIN_AXIS_ALIGNMENT_OPTIONS: [(&str, MainAxisAlignment); 6] = [ ("Start", MainAxisAlignment::Start), ("Center", MainAxisAlignment::Center), ("End", MainAxisAlignment::End), ("Between", MainAxisAlignment::SpaceBetween), ("Evenly", MainAxisAlignment::SpaceEvenly), ("Around", MainAxisAlignmen...
("Fixed:", Spacers::Fixed), ];
random_line_split
fona_3g.py
= "https://github.com/adafruit/Adafruit_CircuitPython_FONA.git" FONA_MAX_SOCKETS = const(10) class FONA3G(FONA): """FONA 3G module interface. :param ~busio.UART uart: FONA UART connection. :param ~digitalio.DigitalInOut rst: FONA RST pin. :param ~digitalio.DigitalInOut ri: Optional FONA Ring Interr...
(self, sock_num: int) -> str: """Returns the IP address of the remote connection. :param int sock_num: Desired socket number """ self._read_line() assert ( sock_num < FONA_MAX_SOCKETS ), "Provided socket exceeds the maximum number of \ ...
remote_ip
identifier_name
fona_3g.py
__ = "https://github.com/adafruit/Adafruit_CircuitPython_FONA.git" FONA_MAX_SOCKETS = const(10) class FONA3G(FONA): """FONA 3G module interface. :param ~busio.UART uart: FONA UART connection. :param ~digitalio.DigitalInOut rst: FONA RST pin. :param ~digitalio.DigitalInOut ri: Optional FONA Ring Inte...
state = self._buf if gps_on and not state: self._read_line() if not self._send_check_reply(b"AT+CGPS=1", reply=REPLY_OK): return False else: if not self._send_check_reply(b"AT+CGPS=0", reply=REPLY_OK): return False ...
return False
conditional_block
fona_3g.py
__ = "https://github.com/adafruit/Adafruit_CircuitPython_FONA.git" FONA_MAX_SOCKETS = const(10) class FONA3G(FONA):
if not self._send_check_reply( b"AT+IPREX=" + str(baudrate).encode(), reply=REPLY_OK ): return False return True @property def gps(self) -> bool: """Module's GPS status.""" if not self._send_check_reply(b"AT+CGPS?", reply=b"+CGPS: 1,1"): ...
"""FONA 3G module interface. :param ~busio.UART uart: FONA UART connection. :param ~digitalio.DigitalInOut rst: FONA RST pin. :param ~digitalio.DigitalInOut ri: Optional FONA Ring Interrupt (RI) pin. :param bool debug: Enable debugging output. """ def __init__( self, uart: UART...
identifier_body
fona_3g.py
__ = "https://github.com/adafruit/Adafruit_CircuitPython_FONA.git" FONA_MAX_SOCKETS = const(10) class FONA3G(FONA): """FONA 3G module interface. :param ~busio.UART uart: FONA UART connection. :param ~digitalio.DigitalInOut rst: FONA RST pin. :param ~digitalio.DigitalInOut ri: Optional FONA Ring Inte...
"""Returns the IP address of the remote connection. :param int sock_num: Desired socket number """ self._read_line() assert ( sock_num < FONA_MAX_SOCKETS ), "Provided socket exceeds the maximum number of \ sockets ...
random_line_split
circuit_drawer.py
-many-branches,too-many-arguments,too-many-return-statements,too-many-statements,consider-using-enumerate,too-many-instance-attributes def _remove_duplicates(input_list): """Remove duplicate entries from a list. This operation preserves the order of the list's elements. Args: input_list (list[Ha...
# translate wires to their indices on the device wire_indices = self.active_wires.indices(op.wires) if len(op.wires) > 1: sorted_wires = wire_indices.copy() sorted_wires.sort() blocked_wires = list(range(sorte...
"""Move multi-wire gates so that there are no interlocking multi-wire gates in the same layer. Args: operator_grid (pennylane.circuit_drawer.Grid): Grid that holds the circuit information and that will be edited. """ n = operator_grid.num_layers i = -1 while i < n - ...
identifier_body
circuit_drawer.py
-many-branches,too-many-arguments,too-many-return-statements,too-many-statements,consider-using-enumerate,too-many-instance-attributes def _remove_duplicates(input_list): """Remove duplicate entries from a list. This operation preserves the order of the list's elements. Args: input_list (list[Ha...
def move_multi_wire_gates(self, operator_grid): """Move multi-wire gates so that there are no interlocking multi-wire gates in the same layer. Args: operator_grid (pennylane.circuit_drawer.Grid): Grid that holds the circuit information and that will be edited. """ n = ...
layer = representation_grid.layer(i) max_width = max(map(len, layer)) if i in skip_indices: continue # Take the current layer and pad it with the pad_str # and also prepend with prepend_str and append the suffix_str # pylint: disable=cell-var...
conditional_block
circuit_drawer.py
-many-branches,too-many-arguments,too-many-return-statements,too-many-statements,consider-using-enumerate,too-many-instance-attributes def
(input_list): """Remove duplicate entries from a list. This operation preserves the order of the list's elements. Args: input_list (list[Hashable]): The list whose duplicate entries shall be removed Returns: list[Hashable]: The input list without duplicate entries """ return l...
_remove_duplicates
identifier_name
circuit_drawer.py
-many-branches,too-many-arguments,too-many-return-statements,too-many-statements,consider-using-enumerate,too-many-instance-attributes def _remove_duplicates(input_list): """Remove duplicate entries from a list. This operation preserves the order of the list's elements. Args: input_list (list[Ha...
all_wires_with_duplicates = [op.wires for op in all_operators if op is not None] # make Wires object containing all used wires all_wires = Wires.all_wires(all_wires_with_duplicates) # shared wires will observe the ordering of the device's wires shared_wires = Wires.shared_wires([...
random_line_split
eventlog.go
eventLogInstance := EventLog{ eventChannel: make(chan string, 2), noOfHistoryFiles: maxRollsDay, schemaVersion: "1", eventLogPath: filepath.Join(logFilePath, AuditFolderName), eventLogName: logFileName, datePattern: "2006-01-02", fileSystem: filesystem.NewFileSystem(), timePa...
{ maxRollsDay = config.Agent.AuditExpirationDay }
conditional_block
eventlog.go
func (e *EventLog) init() { e.currentFileName = "" e.fileDelimiter = "-" e.nextFileName = e.eventLogName + e.fileDelimiter + time.Now().Format(e.datePattern) if err := e.fileSystem.MkdirAll(e.eventLogPath, appconfig.ReadWriteExecuteAccess); err != nil { fmt.Println("Failed to create directory for audits", err) }...
() filesystem.IFileSystem { return e.fileSystem } // loadEvent loads the event to the channel to be passed to the write file go routine func (e *EventLog) loadEvent(eventType string, agentVersion string, eventContent string) { // Time appended to the message in the format HH:MM:SS if agentVersion == "" { agentVer...
GetFileSystem
identifier_name
eventlog.go
func (e *EventLog) init() { e.currentFileName = "" e.fileDelimiter = "-" e.nextFileName = e.eventLogName + e.fileDelimiter + time.Now().Format(e.datePattern) if err := e.fileSystem.MkdirAll(e.eventLogPath, appconfig.ReadWriteExecuteAccess); err != nil { fmt.Println("Failed to create directory for audits", err) }...
// GetAuditFilePath will return the file system instance func (e *EventLog) GetFileSystem() filesystem.IFileSystem { return e.fileSystem } // loadEvent loads the event to the channel to be passed to the write file go routine func (e *EventLog) loadEvent(eventType string, agentVersion string, eventContent string) { ...
{ return e.eventLogPath }
identifier_body
eventlog.go
func (e *EventLog) init() { e.currentFileName = "" e.fileDelimiter = "-" e.nextFileName = e.eventLogName + e.fileDelimiter + time.Now().Format(e.datePattern) if err := e.fileSystem.MkdirAll(e.eventLogPath, appconfig.ReadWriteExecuteAccess); err != nil { fmt.Println("Failed to create directory for audits", err) ...
if eventCounterObj.AgentVersion != "" && (version != eventCounterObj.AgentVersion || eventChunkType != eventCounterObj.EventChunkType || eventChunkType == AgentUpdateResultMessage) { newlyCreated = true eventCounterObj = &EventCounter{ AuditFileName: eventCounterObj.AuditFileName, AuditDate: eventCou...
} // Will create a new object and load data for it from new chunk. For now, the chunks are divided based on version and Update events. newlyCreated := false
random_line_split
main.js
)' ); gradient.addColorStop( 0.2, 'rgba(255,255,255,1)' ); gradient.addColorStop( 0.4, 'rgba(200,200,200,1)' ); gradient.addColorStop( 1, 'rgba(0,0,0,1)' ); context.fillStyle = gradient; context.fill(); return canvas; } var shaderMaterial = new THREE.ShaderMaterial( { ...
seX - mouseXOnMouseDown ) * 0.02; } function onDocumentTouchStart( event ) { if ( event.touches.length === 1 ) { event.p
identifier_body