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
test_framework.py
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Copyright (c) 2014-2019 The Dash Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Base class for RPC testing.""" from collections imp...
def run_test(self): raise NotImplementedError # Main function. This should not be overridden by the subclass test scripts. def main(self): parser = optparse.OptionParser(usage="%prog [options]") parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true...
extra_args = None if hasattr(self, "extra_args"): extra_args = self.extra_args self.nodes = _start_nodes(self.num_nodes, self.options.tmpdir, extra_args, stderr=stderr)
identifier_body
mod.rs
pub mod build; pub mod config; pub mod dev; pub mod generate; pub mod init; pub mod kv; pub mod login; pub mod logout; pub mod preview; pub mod publish; pub mod r2; pub mod route; pub mod secret; pub mod subdomain; pub mod tail; pub mod whoami; pub mod exec { pub use super::build::build; pub use super::config:...
{ /// 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
pub mod build; pub mod config; pub mod dev; pub mod generate; pub mod init; pub mod kv; pub mod login; pub mod logout; pub mod preview; pub mod publish; pub mod r2; pub mod route; pub mod secret; pub mod subdomain; pub mod tail; pub mod whoami; pub mod exec { pub use super::build::build; pub use super::config:...
#[cfg(test)] mod tests { use super::*; fn rename_class(tag: &str) -> RenameClass { RenameClass { from: format!("renameFrom{}", tag), to: format!("renameTo{}", tag), } } fn transfer_class(tag: &str) -> TransferClass { TransferClass { from: f...
{ 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 build; pub mod config; pub mod dev; pub mod generate; pub mod init; pub mod kv; pub mod login; pub mod logout; pub mod preview; pub mod publish; pub mod r2; pub mod route; pub mod secret;
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
"""showCrime.dailyIncid.models.py: updated 23 Mar 17: include GIS, updated 20 Jun 17: combine dateTime, add source updated 17 Oct 17: incorporate dailyLog incident data updated 14 Jul 18: add OPDBeats, CensusTracts updated 8 Aug 19: add new CrimeCatCDMatch, PC2CC updated 15 Aug 19: add new OCUpdate for audit ca...
# capture results of daily log file's parse # cf. collectDailyLogs() class DailyParse(models.Model): idx = models.AutoField(primary_key=True) boxobj = models.ForeignKey('boxid',on_delete=models.CASCADE) froot = models.CharField(max_length=100,db_index=True) parseDT = models.DateTimeField(null=True) parseOrder =...
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
"""showCrime.dailyIncid.models.py: updated 23 Mar 17: include GIS, updated 20 Jun 17: combine dateTime, add source updated 17 Oct 17: incorporate dailyLog incident data updated 14 Jul 18: add OPDBeats, CensusTracts updated 8 Aug 19: add new CrimeCatCDMatch, PC2CC updated 15 Aug 19: add new OCUpdate for audit ca...
(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
"""showCrime.dailyIncid.models.py: updated 23 Mar 17: include GIS, updated 20 Jun 17: combine dateTime, add source updated 17 Oct 17: incorporate dailyLog incident data updated 14 Jul 18: add OPDBeats, CensusTracts updated 8 Aug 19: add new CrimeCatCDMatch, PC2CC updated 15 Aug 19: add new OCUpdate for audit ca...
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
// Utilities for creating test cases. use core::marker::PhantomData; use std::time::{Duration, Instant}; use std::vec::Vec; use common::errors::*; use crate::random::Rng; /* To verify no timing leaks: - Run any many different input sizes. - Verify compiler optimizations aren't making looping over many iterations to...
pub struct StatisticsTracker<T> { min: Option<T>, max: Option<T>, } impl<T: Ord + Copy> StatisticsTracker<T> { pub fn new() -> Self { Self { min: None, max: None, } } pub fn update(&mut self, value: T) { self.min = Some(match self.min { ...
{ 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
// Utilities for creating test cases. use core::marker::PhantomData; use std::time::{Duration, Instant}; use std::vec::Vec; use common::errors::*; use crate::random::Rng; /* To verify no timing leaks: - Run any many different input sizes. - Verify compiler optimizations aren't making looping over many iterations to...
/// 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
// Utilities for creating test cases. use core::marker::PhantomData; use std::time::{Duration, Instant}; use std::vec::Vec; use common::errors::*; use crate::random::Rng; /* To verify no timing leaks: - Run any many different input sizes. - Verify compiler optimizations aren't making looping over many iterations to...
{ sum: u64, n: usize, }
RollingMean
identifier_name
registry-manager.ts
/* * Copyright 2014-2019 Guy Bedford (http://guybedford.com) * * 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...
(fileOrDir) { cnt++; fs.stat(fileOrDir, async (err, stats) => { if (err || errored) return handleError(err); try { if (await visit(fileOrDir, stats)) return resolve(); } catch (err) { return handleError(err); } if (st...
visitFileOrDir
identifier_name
registry-manager.ts
/* * Copyright 2014-2019 Guy Bedford (http://guybedford.com) * * 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...
sourcePath[0] === '.' && (sourcePath[1] === '/' || sourcePath[1] === '\\' || ( sourcePath[1] === '.' && (sourcePath[2] === '/' || sourcePath[2] === '\\')))) { const realPackagePath = await new Promise<string>((resolve, reject) => fs.realpath(packagePath, (err, realpath) => err ? reject...
// 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
/* * Copyright 2014-2019 Guy Bedford (http://guybedford.com) * * 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...
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
package main import ( "encoding/json" "fmt" "net/url" "os" "sync" "sync/atomic" "time" "github.com/gorilla/websocket" "github.com/xing/beetle/consul" ) // ClientOptions consist of the id by which the client identifies itself with // the server, the overall configuration and pointer to a ConsulClient. type C...
() { 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
package main import ( "encoding/json" "fmt" "net/url" "os" "sync" "sync/atomic" "time" "github.com/gorilla/websocket" "github.com/xing/beetle/consul" ) // ClientOptions consist of the id by which the client identifies itself with // the server, the overall configuration and pointer to a ConsulClient. type C...
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
package main import ( "encoding/json" "fmt" "net/url" "os" "sync" "sync/atomic" "time" "github.com/gorilla/websocket" "github.com/xing/beetle/consul" ) // ClientOptions consist of the id by which the client identifies itself with // the server, the overall configuration and pointer to a ConsulClient. type C...
} logInfo("client terminated") return nil }
}
random_line_split
client.go
package main import ( "encoding/json" "fmt" "net/url" "os" "sync" "sync/atomic" "time" "github.com/gorilla/websocket" "github.com/xing/beetle/consul" ) // ClientOptions consist of the id by which the client identifies itself with // the server, the overall configuration and pointer to a ConsulClient. type C...
// 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
// Code generated by protoc-gen-go. // source: indexer.proto // DO NOT EDIT! /* Package indexer is a generated protocol buffer package. It is generated from these files: indexer.proto It has these top-level messages: ResolveRequest ResolveResponse Matcher ValuesRequest ValuesResponse */ package indexer import...
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
// Code generated by protoc-gen-go. // source: indexer.proto // DO NOT EDIT! /* Package indexer is a generated protocol buffer package. It is generated from these files: indexer.proto It has these top-level messages: ResolveRequest ResolveResponse Matcher ValuesRequest ValuesResponse */ package indexer import...
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
// Code generated by protoc-gen-go. // source: indexer.proto // DO NOT EDIT! /* Package indexer is a generated protocol buffer package. It is generated from these files: indexer.proto It has these top-level messages: ResolveRequest ResolveResponse Matcher ValuesRequest ValuesResponse */ package indexer import...
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
// Code generated by protoc-gen-go. // source: indexer.proto // DO NOT EDIT! /* Package indexer is a generated protocol buffer package. It is generated from these files: indexer.proto It has these top-level messages: ResolveRequest ResolveResponse Matcher ValuesRequest ValuesResponse */ package indexer import...
() ([]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
use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; use std::process::Command; use std::collections::HashSet; use std::path::{PathBuf, Path}; use app_result::{AppResult, app_err_msg, app_err_missing_src}; use types::{Tags, TagsKind, SourceKind}; use path_ext::PathExt; use config::Config; use dirs::{ rus...
(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
use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; use std::process::Command; use std::collections::HashSet; use std::path::{PathBuf, Path}; use app_result::{AppResult, app_err_msg, app_err_missing_src}; use types::{Tags, TagsKind, SourceKind}; use path_ext::PathExt; use config::Config; use dirs::{ rus...
/// 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> { let mut cmd = Command::new("git"); cmd.current_dir(git_dir) .arg("rev-parse") .arg("HEAD"); let out = try!(cmd.output()); String::from_utf...
{ 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
use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; use std::process::Command; use std::collections::HashSet; use std::path::{PathBuf, Path}; use app_result::{AppResult, app_err_msg, app_err_missing_src}; use types::{Tags, TagsKind, SourceKind}; use path_ext::PathExt; use config::Config; use dirs::{ rus...
, TagsKind::Emacs => { let mut tag_file = try!( OpenOptions::new() .create(true) .append(true) .read(true) .write(true) .open(into_tag_file) ); for file in tag_files.iter() { ...
{ 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
use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; use std::process::Command; use std::collections::HashSet; use std::path::{PathBuf, Path}; use app_result::{AppResult, app_err_msg, app_err_missing_src}; use types::{Tags, TagsKind, SourceKind}; use path_ext::PathExt; use config::Config; use dirs::{ rus...
let mut cmd = Command::new("git"); cmd.current_dir(git_dir) .arg("rev-parse") .arg("HEAD"); let out = try!(cmd.output()); String::from_utf8(out.stdout) .map(|s| s.trim().to_string()) .map_err(|_| app_err_msg("Couldn't convert 'git rev-parse HEAD' output to utf8!".to_stri...
/// 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
import argparse import numpy as np import operator import pandas 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.rand...
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
import argparse import numpy as np import operator import pandas 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.rand...
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
import argparse import numpy as np import operator import pandas from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier from .metrics import compute_auc, compute_model_auc def
(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
# Copyright (C) 2013-2015 Yu-Jie Lin # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, dis...
if not markup: logging.warning('markup is empty') logging.debug('markup length = %d' % len(markup)) _header = {} if header: for item in header.split('\n'): m = self.RE_HEADER.match(item) if not m: continue k, v = list(map(type('').strip, m.groups())) ...
logging.warning('found no header')
conditional_block
base.py
# Copyright (C) 2013-2015 Yu-Jie Lin # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, dis...
@staticmethod def _embed_image(match): src = match.group('src') if not exists(src): print('%s is not found.' % src) return match.group(0) with open(src, 'rb') as f: data = b64encode(f.read()).decode('ascii') return '%ssrc="%s"%s' % ( match.group('prefix'), 'data:im...
"""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
# Copyright (C) 2013-2015 Yu-Jie Lin # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, dis...
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
# Copyright (C) 2013-2015 Yu-Jie Lin # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, dis...
(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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Team 16: COMP90024-Assignment2 # Team Members: # Qingmeng Xu, 969413 # Tingqian Wang, 1043988 # Zhong Liao, 1056020 # Cheng Qian, 962539 # Zongcheng Du, 1096319 """ Created on Sun May 24 21:41:09 2020 @author: ciciwang """ #!/usr/bin/env python3 # -*- coding: utf-8 ...
(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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Team 16: COMP90024-Assignment2 # Team Members: # Qingmeng Xu, 969413 # Tingqian Wang, 1043988 # Zhong Liao, 1056020 # Cheng Qian, 962539 # Zongcheng Du, 1096319 """ Created on Sun May 24 21:41:09 2020 @author: ciciwang """ #!/usr/bin/env python3 # -*- coding: utf-8 ...
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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Team 16: COMP90024-Assignment2 # Team Members: # Qingmeng Xu, 969413 # Tingqian Wang, 1043988 # Zhong Liao, 1056020 # Cheng Qian, 962539 # Zongcheng Du, 1096319 """ Created on Sun May 24 21:41:09 2020 @author: ciciwang """ #!/usr/bin/env python3 # -*- coding: utf-8 ...
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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Team 16: COMP90024-Assignment2 # Team Members: # Qingmeng Xu, 969413 # Tingqian Wang, 1043988 # Zhong Liao, 1056020 # Cheng Qian, 962539 # Zongcheng Du, 1096319 """ Created on Sun May 24 21:41:09 2020 @author: ciciwang """ #!/usr/bin/env python3 # -*- coding: utf-8 ...
# 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
Math.range = (min, max) => min + Math.random() * (max - min); Math.degtorad = (d) => d * Math.PI / 180; Math.lendirx = (l, d) => l * Math.cos(Math.degtorad(d)); Math.lendiry = (l, d) => l * Math.sin(Math.degtorad(d)); const CANVAS = document.createElement('canvas'); const CTX = CANVAS.getContext('2d'); const CANVAS_SC...
() { return { w: this.w * 0.5, h: this.h * 0.5 }; } }; const World = { get x() { return Room.mid.w; }, get y() { return Room.mid.h - this.mid.h; }, get w() { return Grid.c * Tile.w; }, get h() { return Grid.r * Tile.h; }, get mid() { return { w: this.w * 0.5, h: this.h * 0.5 }; }...
mid
identifier_name
app.js
Math.range = (min, max) => min + Math.random() * (max - min); Math.degtorad = (d) => d * Math.PI / 180; Math.lendirx = (l, d) => l * Math.cos(Math.degtorad(d)); Math.lendiry = (l, d) => l * Math.sin(Math.degtorad(d)); const CANVAS = document.createElement('canvas'); const CTX = CANVAS.getContext('2d'); const CANVAS_SC...
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
Math.range = (min, max) => min + Math.random() * (max - min); Math.degtorad = (d) => d * Math.PI / 180; Math.lendirx = (l, d) => l * Math.cos(Math.degtorad(d)); Math.lendiry = (l, d) => l * Math.sin(Math.degtorad(d)); const CANVAS = document.createElement('canvas'); const CTX = CANVAS.getContext('2d'); const CANVAS_SC...
} } } } }; const RAF = window.requestAnimationFrame || window.msRequestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function(f) { return setTimeout(f, Time.fixedDeltaTime) } const BRANTH = { start() { document.body.appendChild(CANVAS); window.onkeyup = ...
{ i.renderUI(); }
conditional_block
app.js
Math.range = (min, max) => min + Math.random() * (max - min); Math.degtorad = (d) => d * Math.PI / 180; Math.lendirx = (l, d) => l * Math.cos(Math.degtorad(d)); Math.lendiry = (l, d) => l * Math.sin(Math.degtorad(d)); const CANVAS = document.createElement('canvas'); const CTX = CANVAS.getContext('2d'); const CANVAS_SC...
while (isMeet) { this.move(); isMeet = false; for (let i = 0; i < s.tails.length; i++) { const t = s.tails[i]; if (this.meet(t)) { isMeet = true; } for (let i = 0; i < OBJ.take(Food).length; i++) { const a = OBJ.take(Food)[i]; this.meet(a.c, a.r); } } i-...
let isMeet = true;
random_line_split
app.go
// Copyright ©2017 The go-hep Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package fwk import ( "context" "fmt" "io" "math" "reflect" "runtime" "sort" "time" "go-hep.org/x/hep/fwk/fsm" ) type appmgr struct { state fsm...
func (app *appmgr) Msg() MsgStream { return app.msg } func (app *appmgr) printDataFlow() error { var err error app.msg.Debugf(">>> --- [data flow] --- nodes...\n") for tsk, node := range app.dflow.nodes { app.msg.Debugf(">>> ---[%s]---\n", tsk) app.msg.Debugf(" in: %v\n", node.in) app.msg.Debugf(" o...
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
// Copyright ©2017 The go-hep Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package fwk import ( "context" "fmt" "io" "math" "reflect" "runtime" "sort" "time"
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
// Copyright ©2017 The go-hep Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package fwk import ( "context" "fmt" "io" "math" "reflect" "runtime" "sort" "time" "go-hep.org/x/hep/fwk/fsm" ) type appmgr struct { state fsm...
) []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
// Copyright ©2017 The go-hep Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package fwk import ( "context" "fmt" "io" "math" "reflect" "runtime" "sort" "time" "go-hep.org/x/hep/fwk/fsm" ) type appmgr struct { state fsm...
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
from pySDC import Level as levclass from pySDC import 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 operato...
# 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
from pySDC import Level as levclass from pySDC import 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 operato...
# 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
from pySDC import Level as levclass from pySDC import 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 operato...
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
from pySDC import Level as levclass from pySDC import 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 operato...
(self): """ Getter for previous step Returns: prev """ return self.__prev @prev.setter def prev(self,p): """ Setter for previous step Args: p: new previous step """ assert type(p) is type(self) self...
prev
identifier_name
cubicbez.rs
//! Cubic Bézier segments. use libm; //// use core::ops::{Mul, Range}; //// ////use std::ops::{Mul, Range}; use introsort; //// use crate::MAX_EXTREMA; use arrayvec::ArrayVec; use crate::common::solve_quadratic; use crate::common::GAUSS_LEGENDRE_COEFFS_9; use crate::{ Affine, ParamCurve, ParamCurveArclen, ParamC...
// y = x^2 let c = CubicBez::new( (0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0 / 3.0), (1.0, 1.0), ); let true_arclen = 0.5 * libm::sqrt(5.0f64) + 0.25 * (2.0 + libm::sqrt(5.0f64)).ln(); for i in 0..12 { let accuracy = 0....
z_arclen() {
identifier_name
cubicbez.rs
//! Cubic Bézier segments. use libm; //// use core::ops::{Mul, Range}; //// ////use std::ops::{Mul, Range}; use introsort; //// use crate::MAX_EXTREMA; use arrayvec::ArrayVec; use crate::common::solve_quadratic; use crate::common::GAUSS_LEGENDRE_COEFFS_9; use crate::{ Affine, ParamCurve, ParamCurveArclen, ParamC...
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
//! Cubic Bézier segments. use libm; //// use core::ops::{Mul, Range}; //// ////use std::ops::{Mul, Range}; use introsort; //// use crate::MAX_EXTREMA; use arrayvec::ArrayVec; use crate::common::solve_quadratic; use crate::common::GAUSS_LEGENDRE_COEFFS_9; use crate::{ Affine, ParamCurve, ParamCurveArclen, ParamC...
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
//! Cubic Bézier segments. use libm; //// use core::ops::{Mul, Range}; //// ////use std::ops::{Mul, Range}; use introsort; //// use crate::MAX_EXTREMA; use arrayvec::ArrayVec; use crate::common::solve_quadratic; use crate::common::GAUSS_LEGENDRE_COEFFS_9; use crate::{ Affine, ParamCurve, ParamCurveArclen, ParamC...
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
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package awscloudwatchreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/awscloudwatchreceiver" import ( "context" "errors" "fmt" "sync" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-s...
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
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package awscloudwatchreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/awscloudwatchreceiver" import ( "context" "errors" "fmt" "sync" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-s...
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
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package awscloudwatchreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/awscloudwatchreceiver" import ( "context" "errors" "fmt" "sync" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-s...
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
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package awscloudwatchreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/awscloudwatchreceiver" import ( "context" "errors" "fmt" "sync" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-s...
(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
package v1alpha1 import ( "errors" "strings" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +genclient // ComplianceScanRescanAnnotation indicates that a ComplianceScan // should be re-run const ComplianceScanRescanAnnotation = "compliance.openshift.io/rescan" // ComplianceScanL...
() ComplianceScanType { scantype, err := cs.GetScanTypeIfValid() if err != nil { // This shouldn't happen panic(err) } return scantype } // Returns whether remediation enforcement is off or not func (cs *ComplianceScan) RemediationEnforcementIsOff() bool { return (strings.EqualFold(cs.Spec.RemediationEnforcem...
GetScanType
identifier_name
compliancescan_types.go
package v1alpha1 import ( "errors" "strings" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +genclient // ComplianceScanRescanAnnotation indicates that a ComplianceScan // should be re-run const ComplianceScanRescanAnnotation = "compliance.openshift.io/rescan" // ComplianceScanL...
// 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
package v1alpha1 import ( "errors" "strings" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +genclient // ComplianceScanRescanAnnotation indicates that a ComplianceScan // should be re-run const ComplianceScanRescanAnnotation = "compliance.openshift.io/rescan" // ComplianceScanL...
// GetScanType get's the scan type for a scan func (cs *ComplianceScan) GetScanType() ComplianceScanType { scantype, err := cs.GetScanTypeIfValid() if err != nil { // This shouldn't happen panic(err) } return scantype } // Returns whether remediation enforcement is off or not func (cs *ComplianceScan) Remedi...
{ 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
package v1alpha1 import ( "errors" "strings" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +genclient // ComplianceScanRescanAnnotation indicates that a ComplianceScan // should be re-run const ComplianceScanRescanAnnotation = "compliance.openshift.io/rescan" // ComplianceScanL...
return "", ErrUnkownScanType } // GetScanType get's the scan type for a scan func (cs *ComplianceScan) GetScanType() ComplianceScanType { scantype, err := cs.GetScanTypeIfValid() if err != nil { // This shouldn't happen panic(err) } return scantype } // Returns whether remediation enforcement is off or not ...
{ return ScanTypeNode, nil }
conditional_block
tf_train.py
import tensorflow as tf import random import cPickle import numpy as np import os #change current directory os.chdir("..") ABS_PATH = os.path.abspath(os.curdir) import sys sys.path.append(os.path.join(os.path.dirname(__file__), ABS_PATH)) from sklearn import svm from scipy.sparse import csr_matrix from features.vectori...
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
import tensorflow as tf import random import cPickle import numpy as np import os #change current directory os.chdir("..") ABS_PATH = os.path.abspath(os.curdir) import sys sys.path.append(os.path.join(os.path.dirname(__file__), ABS_PATH)) from sklearn import svm from scipy.sparse import csr_matrix from features.vectori...
(): 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
import tensorflow as tf import random import cPickle import numpy as np import os #change current directory os.chdir("..") ABS_PATH = os.path.abspath(os.curdir) import sys sys.path.append(os.path.join(os.path.dirname(__file__), ABS_PATH)) from sklearn import svm from scipy.sparse import csr_matrix from features.vectori...
############################################################################## if __name__ == "__main__": """ train the politeness model, using tensorflow """ grid_search()
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
import tensorflow as tf import random import cPickle import numpy as np import os #change current directory os.chdir("..") ABS_PATH = os.path.abspath(os.curdir) import sys sys.path.append(os.path.join(os.path.dirname(__file__), ABS_PATH)) from sklearn import svm from scipy.sparse import csr_matrix from features.vectori...
import pylab pylab.show() ############################################################################## if __name__ == "__main__": """ train the politeness model, using tensorflow """ grid_search()
random_line_split
core1500.js
export default [{ kan: '出口', tran: 'でぐち', english: 'exit', sentences: '出口はあそこです。でぐち は あそこ です。The exit\'s over there.', id: 1 }, { kan: '登る', tran: 'のぼる', english: 'climb, ascend', sentences: '私たちは昨年、富士山に登りました。わたし たち は さくねん、ふじさん に のぼりました。We climbed Mount Fuji last year.', id: 2 }, { kan: '真っ白', t...
tran: 'まっすぐ', english: 'straight', sentences: 'この道を真っ直ぐ行ってください。この みち を まっすぐ いって ください。Please go straight along this road.', id: 57 }, { kan: 'レモン', tran: 'null', english: 'lemon', sentences: '紅茶にレモンを入れて飲んだ。こうちゃ に レモン を いれて のんだ。I put lemon in my tea and drank it.', id: 58 }, { kan: '上着', tran: 'うわぎ'...
id: 56 }, { kan: '真っ直ぐ',
random_line_split
ha_tracker.go
package distributor import ( "context" "errors" "flag" "fmt" "math/rand" "net/http" "strings" "sync" "time" "github.com/weaveworks/common/httpgrpc" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/golang/protobuf/proto" "github.com/prometheus/client_golang/prometheus" "github....
// from this replica. Invalid could mean that the timestamp in the KV store was // out of date based on the update and failover timeouts when compared to now. return &ReplicaDesc{ Replica: replica, ReceivedAt: timestamp.FromTime(now), }, true, nil }) } func replicasNotMatchError(replica, elected string) er...
} // There was either invalid or no data for the key, so we now accept samples
random_line_split
ha_tracker.go
package distributor import ( "context" "errors" "flag" "fmt" "math/rand" "net/http" "strings" "sync" "time" "github.com/weaveworks/common/httpgrpc" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/golang/protobuf/proto" "github.com/prometheus/client_golang/prometheus" "github....
(replica, elected string) error { return httpgrpc.Errorf(http.StatusAccepted, "replicas did not mach, rejecting sample: replica=%s, elected=%s", replica, elected) } // Modifies the labels parameter in place, removing labels that match // the replica or cluster label and returning their values. Returns an error // if ...
replicasNotMatchError
identifier_name
ha_tracker.go
package distributor import ( "context" "errors" "flag" "fmt" "math/rand" "net/http" "strings" "sync" "time" "github.com/weaveworks/common/httpgrpc" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/golang/protobuf/proto" "github.com/prometheus/client_golang/prometheus" "github....
return cluster, replica }
{ if pair.Name == replicaLabel { replica = string(pair.Value) } if pair.Name == clusterLabel { cluster = string(pair.Value) } }
conditional_block
ha_tracker.go
package distributor import ( "context" "errors" "flag" "fmt" "math/rand" "net/http" "strings" "sync" "time" "github.com/weaveworks/common/httpgrpc" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/golang/protobuf/proto" "github.com/prometheus/client_golang/prometheus" "github....
// Modifies the labels parameter in place, removing labels that match // the replica or cluster label and returning their values. Returns an error // if we find one but not both of the labels. func findHALabels(replicaLabel, clusterLabel string, labels []client.LabelAdapter) (string, string) { var cluster, replica s...
{ return httpgrpc.Errorf(http.StatusAccepted, "replicas did not mach, rejecting sample: replica=%s, elected=%s", replica, elected) }
identifier_body
file.go
// Copyright 2014 Google Inc. All rights reserved. // // 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...
() { file.RWMutex.RUnlock() } func (file *File) IncRef(fs *Fs) { fs.filesLock.RLock() atomic.AddInt32(&file.refs, 1) fs.filesLock.RUnlock() } func (file *File) DecRef(fs *Fs, path string) { new_refs := atomic.AddInt32(&file.refs, -1) if new_refs == 0 { fs.filesLock.Lock() if file.refs != 0 { // Race co...
unlock
identifier_name
file.go
// Copyright 2014 Google Inc. All rights reserved. // // 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...
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
// Copyright 2014 Google Inc. All rights reserved. // // 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...
func (fs *Fs) lookup(path string) (*File, error) { // Normalize path. if len(path) > 0 && path[len(path)-1] == '/' { path = path[:len(path)-1] } fs.filesLock.RLock() file, ok := fs.files[path] if ok { atomic.AddInt32(&file.refs, 1) fs.filesLock.RUnlock() return file, nil } fs.filesLock.RUnlock() /...
{ // 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
// Copyright 2014 Google Inc. All rights reserved. // // 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...
// Make sure the parent exists. err := file.makeTree(fs, path) if err != nil { file.RWMutex.Unlock() return err } // Make this directory. err = syscall.Mkdir(file.write_path, mode) if err != nil { file.RWMutex.Unlock() return err } // Fill out type. err = file.fillType(file.write_path)...
return err } }
random_line_split
controller.rs
mod cli; mod collect; mod detector; mod init; mod reconcile_queue; mod reconciler; mod supervisor; mod validate_api_server; pub use self::{ collect::Collect, reconciler::{ReconcileContext, ReconcileStatus}, }; use self::collect::ControllerDescriptionCollector; use crate::controller::reconcile_queue::QueueConf...
}; 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
mod cli; mod collect; mod detector; mod init; mod reconcile_queue; mod reconciler; mod supervisor; mod validate_api_server; pub use self::{ collect::Collect, reconciler::{ReconcileContext, ReconcileStatus}, }; use self::collect::ControllerDescriptionCollector; use crate::controller::reconcile_queue::QueueConf...
(&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
mod cli; mod collect; mod detector; mod init; mod reconcile_queue; mod reconciler; mod supervisor; mod validate_api_server; pub use self::{ collect::Collect, reconciler::{ReconcileContext, ReconcileStatus}, }; use self::collect::ControllerDescriptionCollector; use crate::controller::reconcile_queue::QueueConf...
} 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
package pathfileops import ( "fmt" "os" "reflect" "strings" ) // mFileOpenModeIntToString - This map is used to map enumeration values // to enumeration names stored as strings for Type FileOpenMode. var mFileOpenModeIntToString = map[int]string{} // mFileOpenModeStringToInt - This map is used to map enumera...
// 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
package pathfileops import ( "fmt" "os" "reflect" "strings" ) // mFileOpenModeIntToString - This map is used to map enumeration values // to enumeration names stored as strings for Type FileOpenMode. var mFileOpenModeIntToString = map[int]string{} // mFileOpenModeStringToInt - This map is used to map enumera...
// 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
package pathfileops import ( "fmt" "os" "reflect" "strings" ) // mFileOpenModeIntToString - This map is used to map enumeration values // to enumeration names stored as strings for Type FileOpenMode. var mFileOpenModeIntToString = map[int]string{} // mFileOpenModeStringToInt - This map is used to map enumera...
() 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
package pathfileops import ( "fmt" "os" "reflect" "strings" ) // mFileOpenModeIntToString - This map is used to map enumeration values // to enumeration names stored as strings for Type FileOpenMode. var mFileOpenModeIntToString = map[int]string{} // mFileOpenModeStringToInt - This map is used to map enumera...
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
# -*- coding: utf-8 -*- ############################################################################## # # # Programmed by: Alexander Olivares <olivaresa@gmail.com> # # This the script to connect with Seniat website # for consult the rif asociated with a partner was taken from: # # http://siv.cendi...
elf, cr, uid, country_code, vat_number, context=None): """ Validate against VAT Information Exchange System (VIES) """ if country_code.upper() != "VE": return super(res_partner, self).vies_vat_check(cr, uid, country_code, vat_number,context=context) else: ...
es_vat_check(s
identifier_name
partner.py
# -*- coding: utf-8 -*- ############################################################################## # # # Programmed by: Alexander Olivares <olivaresa@gmail.com> # # This the script to connect with Seniat website # for consult the rif asociated with a partner was taken from: # # http://siv.cendi...
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
# -*- coding: utf-8 -*- ############################################################################## # # # Programmed by: Alexander Olivares <olivaresa@gmail.com> # # This the script to connect with Seniat website # for consult the rif asociated with a partner was taken from: # # http://siv.cendi...
def button_check_vat(self, cr, uid, ids, context=None): """ Is called by the button that load information of the partner from database SENIAT """ if context is None: context = {} context.update({'update_fiscal_information':True}) super(res_partner, self).check_vat(cr...
" 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
# -*- coding: utf-8 -*- ############################################################################## # # # Programmed by: Alexander Olivares <olivaresa@gmail.com> # # This the script to connect with Seniat website # for consult the rif asociated with a partner was taken from: # # http://siv.cendi...
""" 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
// Copyright 2020 The Druid 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...
} 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
// Copyright 2020 The Druid 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...
( &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
// Copyright 2020 The Druid 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...
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
# SPDX-FileCopyrightText: Limor Fried/Ladyada for Adafruit Industries # SPDX-FileCopyrightText: 2020 Brent Rubell for Adafruit Industries # # SPDX-License-Identifier: MIT """ `fona_3g` ================================================================================ FONA3G cellular module instance. * Author(s): ladya...
(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
# SPDX-FileCopyrightText: Limor Fried/Ladyada for Adafruit Industries # SPDX-FileCopyrightText: 2020 Brent Rubell for Adafruit Industries # # SPDX-License-Identifier: MIT """ `fona_3g` ================================================================================ FONA3G cellular module instance. * Author(s): ladya...
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
# SPDX-FileCopyrightText: Limor Fried/Ladyada for Adafruit Industries # SPDX-FileCopyrightText: 2020 Brent Rubell for Adafruit Industries # # SPDX-License-Identifier: MIT """ `fona_3g` ================================================================================ FONA3G cellular module instance. * Author(s): ladya...
"""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
# SPDX-FileCopyrightText: Limor Fried/Ladyada for Adafruit Industries # SPDX-FileCopyrightText: 2020 Brent Rubell for Adafruit Industries # # SPDX-License-Identifier: MIT """ `fona_3g` ================================================================================ FONA3G cellular module instance. * Author(s): ladya...
"""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
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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...
def draw(self): """Draw the circuit diagram. Returns: str: The circuit diagram """ rendered_string = "" # extract the wire labels as strings and get their maximum length wire_names = [] padding = 0 for i in range(self.full_representatio...
"""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
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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...
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
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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...
(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
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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...
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
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" fil...
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
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" fil...
() 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
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" fil...
// 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
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" fil...
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