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
contacts-details.component.ts
=> { }; @Component({ selector: 'app-contacts-details', templateUrl: './contacts-details.component.html', styleUrls: ['./contacts-details.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: forwardRef(() => ContactsDetailsComponent), } ], changeDe...
this.inputForm.patchValue({ address1: doc.address1, address2: doc.address2, phone1: doc.phone1, phone2:doc.phone2, email: doc.email, mobile: doc.mobile, fax: doc.fax, name: doc.name }) } populate(){ this.listS.getdoctorinformation().subscribe(data => { ...
{ this.inputForm.patchValue({ address1: '', address2: '', phone1: '', phone2:'', email: '', mobile: '', fax: '', name: '' }) return; }
conditional_block
contacts-details.component.ts
=> { }; @Component({ selector: 'app-contacts-details', templateUrl: './contacts-details.component.html', styleUrls: ['./contacts-details.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: forwardRef(() => ContactsDetailsComponent), } ], changeDe...
(changes: SimpleChanges) { for (let property in changes) { console.log('run contacts') this.searchKin(this.user); } } doctorChangeEvent(data: any){ var doc = this.doctors.filter(x => x.name == data).shift(); if(!doc){ this.inputForm.patchValue({ address1: '', ...
ngOnChanges
identifier_name
jobs_contracts.go
deploy.Gas = useDefault(deploy.Gas, do.DefaultGas) // assemble contract var contractPath string if _, err := os.Stat(deploy.Contract); err != nil { if _, secErr := os.Stat(filepath.Join(do.BinPath, deploy.Contract)); secErr != nil { if _, thirdErr := os.Stat(filepath.Join(do.BinPath, filepath.Base(deploy.Cont...
(objectName, deployInstance string) bool { if objectName == "" { return false } // Ignore the filename component that newer versions of Solidity include in object name objectNameParts := strings.Split(objectName, ":") return strings.ToLower(objectNameParts[len(objectNameParts)-1]) == strings.ToLower(deployInsta...
matchInstanceName
identifier_name
jobs_contracts.go
) deploy.Gas = useDefault(deploy.Gas, do.DefaultGas) // assemble contract var contractPath string if _, err := os.Stat(deploy.Contract); err != nil { if _, secErr := os.Stat(filepath.Join(do.BinPath, deploy.Contract)); secErr != nil { if _, thirdErr := os.Stat(filepath.Join(do.BinPath, filepath.Base(deploy.Co...
response := resp.Objects[0] log.WithField("=>", response.ABI).Info("Abi") log.WithField("=>", response.Bytecode).Info("Bin") if response.Bytecode != "" { result, err = deployContract(deploy, do, response) if err != nil { return "", err } } case deploy.Instance == "all": log.WithFiel...
} // loop through objects returned from compiler switch { case len(resp.Objects) == 1: log.WithField("path", contractPath).Info("Deploying the only contract in file")
random_line_split
jobs_contracts.go
deploy.Gas = useDefault(deploy.Gas, do.DefaultGas) // assemble contract var contractPath string if _, err := os.Stat(deploy.Contract); err != nil { if _, secErr := os.Stat(filepath.Join(do.BinPath, deploy.Contract)); secErr != nil { if _, thirdErr := os.Stat(filepath.Join(do.BinPath, filepath.Base(deploy.Cont...
log.WithField("=>", abiLocation).Warn("Saving ABI") if err := ioutil.WriteFile(abiLocation, []byte(compilersResponse.ABI), 0664); err != nil { return "", err } } else { log.Debug("Objectname from compilers is blank. Not saving abi.") } // additional data may be sent along with the contract // these are ...
{ log.WithField("=>", string(compilersResponse.ABI)).Debug("ABI Specification (From Compilers)") contractCode := compilersResponse.Bytecode // Save ABI if _, err := os.Stat(do.ABIPath); os.IsNotExist(err) { if err := os.Mkdir(do.ABIPath, 0775); err != nil { return "", err } } if _, err := os.Stat(do.BinPa...
identifier_body
jobs_contracts.go
deploy.Gas = useDefault(deploy.Gas, do.DefaultGas) // assemble contract var contractPath string if _, err := os.Stat(deploy.Contract); err != nil { if _, secErr := os.Stat(filepath.Join(do.BinPath, deploy.Contract)); secErr != nil { if _, thirdErr := os.Stat(filepath.Join(do.BinPath, filepath.Base(deploy.Cont...
} } } } return result, nil } func matchInstanceName(objectName, deployInstance string) bool { if objectName == "" { return false } // Ignore the filename component that newer versions of Solidity include in object name objectNameParts := strings.Split(objectName, ":") return strings.ToLower(object...
{ return "", err }
conditional_block
client.d.ts
offline status: string, //"ok", "async", "failed" data: object | null, error?: RetError | null, } ////////// export interface VipInfo { readonly user_id?: number, readonly nickname?: string, readonly level?: number, readonly level_speed?: number, readonly vip_level?: number, readon...
getCookies(domain?: string): Promise<RetCommon>; getCsrfToken(): Promise<RetCommon>;
random_line_split
client.d.ts
秒) //瞬间的断线重连不会触发此事件,通常你的机器真的没有网络而导致断线时才会触发 //设置为0则不会自动重连,然后你可以监听此事件自己处理 reconn_interval?: number, //手动指定ip和port //默认使用msfwifi.3g.qq.com:8080进行连接,若要修改建议优先更改该域名hosts指向而不是手动指定ip //@link https://site.ip138.com/msfwifi.3g.qq.com/ 端口通常以下四个都会开放:80,443,8080,14000 remote_ip?: string, remote_port...
tring): void; terminate(): void; //直接关闭连接 logout(): Promise<void>; //先下线再关闭连接 isOnline(): boolean; setOnlineStatus(status: number): Promise<RetCommon>; //11我在线上 31离开 41隐身 50忙碌 60Q我吧 70请勿打扰 getFriendList(): RetFriendList; getStrangerList(): RetStrangerList; getGroupList(): RetGroupList; ...
cha: s
identifier_name
utils.py
able IMmean_ibn = th.tensor([0.502, 0.4588, 0.4078]) IMstd_ibn = th.tensor([0.0039, 0.0039, 0.0039]) def renorm(im): return im.sub(IMmean[:, None, None].to( im.device)).div(IMstd[:, None, None].to(im.device)) def renorm_ibn(im): return im.sub(IMmean_ibn[:, None, None].to( im.device)).div(IMstd_ibn[:, None, ...
return highlight(code, PythonLexer
raise ValueError('does not know how to deal with such datatype')
conditional_block
utils.py
able IMmean_ibn = th.tensor([0.502, 0.4588, 0.4078]) IMstd_ibn = th.tensor([0.0039, 0.0039, 0.0039]) def renorm(im): return im.sub(IMmean[:, None, None].to( im.device)).div(IMstd[:, None, None].to(im.device)) def renorm_ibn(im): return im.sub(IMmean_ibn[:, None, None].to( im.device)).div(IMstd_ibn[:, None, ...
def xdnorm(im): return im.div(IMstd[:, None, None].to( im.device)).add(IMmean[:, None, None].to(im.device)) def chw2hwc(im): return im.transpose((0, 2, 3, 1)) if len( im.shape) == 4 else im.transpose((1, 2, 0)) def metric_get_nmi(valvecs: th.Tensor, vallabs: th.Tensor, ncls: int) -> float: ''' wr...
return im[:, range(3)[::-1], :, :].mul(IMmean_ibn[:, None, None].to( im.device)).add(IMstd_ibn[:, None, None].to(im.device))
identifier_body
utils.py
able IMmean_ibn = th.tensor([0.502, 0.4588, 0.4078]) IMstd_ibn = th.tensor([0.0039, 0.0039, 0.0039]) def renorm(im): return im.sub(IMmean[:, None, None].to( im.device)).div(IMstd[:, None, None].to(im.device)) def renorm_ibn(im): return im.sub(IMmean_ibn[:, None, None].to( im.device)).div(IMstd_ibn[:, None, ...
(im): return im[:, range(3)[::-1], :, :].mul(IMmean_ibn[:, None, None].to( im.device)).add(IMstd_ibn[:, None, None].to(im.device)) def xdnorm(im): return im.div(IMstd[:, None, None].to( im.device)).add(IMmean[:, None, None].to(im.device)) def chw2hwc(im): return im.transpose((0, 2, 3, 1)) if len( im.sha...
denorm_ibn
identifier_name
utils.py
if 'faiss' in globals(): if use_cuda: gpu_resource = faiss.StandardGpuResources() cluster_idx = faiss.IndexFlatL2(npvecs.shape[1]) if not th.distributed.is_initialized(): cluster_idx = faiss.index_cpu_to_gpu( gpu_resource, 0, cluster_idx) ...
epoch=2.ckpt
random_line_split
tree_based_retrieval.py
0, mode = 'FAN_AVG', uniform = True) class TreeModel():
query, doc = input_fields[0], input_fields[1] else: query, doc = input_fields[0][0], input_fields[1][0] query_vec = self.vector_generation(query, 'Q') doc_id = self.tree_index.lookup(doc) doc_vec = self.vector_generation(doc, 'D', doc_id) ...
def __init__(self): TreeHeight = lambda x: int(math.log(x-1)/math.log(2)) + 2 indexCnt = count_idx(FLAGS.input_previous_model_path + "/" + FLAGS.tree_index_file) self.tree_height = TreeHeight(indexCnt+1) self.tree_index = lookup_ops.index_table_from_file(FLAGS.input_previous_model_path +...
identifier_body
tree_based_retrieval.py
0, mode = 'FAN_AVG', uniform = True) class TreeModel(): def __init__(self): TreeHeight = lambda x: int(math.log(x-1)/math.log(2)) + 2 indexCnt = count_idx(FLAGS.input_previous_model_path + "/" + FLAGS.tree_index_file) self.tree_height = TreeHeight(indexCnt+1) self.tree_index = looku...
if FLAGS.use_mstf_ops == 1: self.op_dict = mstf.dssm_dict(FLAGS.xletter_dict) elif FLAGS.use_mstf_ops == -1: self.op_dict = XletterPreprocessor(FLAGS.xletter_dict, FLAGS.xletter_win_size) else: self.op_dict = None def inference(self, input_fields, mode):...
self.leaf_embedding = tf.get_variable(name='leaf_node_emb', shape = [pow(2, self.tree_height -1) ,self.dims[-1]])
conditional_block
tree_based_retrieval.py
mode = 'FAN_AVG', uniform = True) class TreeModel(): def __init__(self): TreeHeight = lambda x: int(math.log(x-1)/math.log(2)) + 2 indexCnt = count_idx(FLAGS.input_previous_model_path + "/" + FLAGS.tree_index_file) self.tree_height = TreeHeight(indexCnt+1) self.tree_index = lookup_...
calc_score
identifier_name
tree_based_retrieval.py
0, mode = 'FAN_AVG', uniform = True)
TreeHeight = lambda x: int(math.log(x-1)/math.log(2)) + 2 indexCnt = count_idx(FLAGS.input_previous_model_path + "/" + FLAGS.tree_index_file) self.tree_height = TreeHeight(indexCnt+1) self.tree_index = lookup_ops.index_table_from_file(FLAGS.input_previous_model_path + "/" + FLAGS.tree_in...
class TreeModel(): def __init__(self):
random_line_split
run.py
accu_prob_N1 = K.cumsum(prob_item_ratings[:, :, ::-1], axis=2)[:, :, ::-1] mask1N = K.cumsum(true_ratings[:, :, ::-1], axis=2)[:, :, ::-1] maskN1 = K.cumsum(true_ratings, axis=2) cost_ordinal_1N = -K.sum( (K.log(prob_item_ratings) - K.log(accu_prob_1N)) * mask1N, axis=2) cost_ordinal_N1 = -K...
else: print("validation set RMSE for epoch %d is %f" % (epoch, score)) self.rmses.append(score) def _train(args): if K.backend() != 'tensorflow': print("This repository only support tensorflow backend.") raise NotImplementedError() batch_size = 64 num_users =...
print("training set RMSE for epoch %d is %f" % (epoch, score))
conditional_block
run.py
(x): # x.shape = (?,6040,5) x_cumsum = K.cumsum(x, axis=2) # x_cumsum.shape = (?,6040,5) output = K.softmax(x_cumsum) # output = (?,6040,5) return output def prediction_output_shape(input_shape): return input_shape def d_layer(x): return K.sum(x, axis=1) def d_output_shape(input_sh...
prediction_layer
identifier_name
run.py
def d_output_shape(input_shape): return (input_shape[0], ) def D_layer(x): return K.sum(x, axis=1) def D_output_shape(input_shape): return (input_shape[0], ) def rating_cost_lambda_func(args): alpha = 1. std = 0.01 pred_score, true_ratings, input_masks, output_masks, D, d = args pre...
return K.sum(x, axis=1)
identifier_body
run.py
epoch, score)) else: print("validation set RMSE for epoch %d is %f" % (epoch, score)) self.rmses.append(score) def _train(args): if K.backend() != 'tensorflow': print("This repository only support tensorflow backend.") raise NotImplementedError() batch_size = 64 ...
# '--data_seed', type=int, default=1, help='the seed for dataset') args = parser.parse_args()
random_line_split
service.go
/zap" "github.com/open-telemetry/opentelemetry-collector/component" "github.com/open-telemetry/opentelemetry-collector/config" "github.com/open-telemetry/opentelemetry-collector/config/configcheck" "github.com/open-telemetry/opentelemetry-collector/config/configmodels" "github.com/open-telemetry/opentelemetry-col...
} func (app *Application) notifyPipelineReady() { for i, ext := range app.extensions { if pw, ok := ext.(extension.PipelineWatcher); ok { if err := pw.Ready(); err != nil { log.Fatalf( "Error notifying extension %q that the pipeline was started: %v", app.config.Service.Extensions[i], err, ...
{ log.Fatalf("Cannot start receivers: %v", err) }
conditional_block
service.go
.org/zap" "github.com/open-telemetry/opentelemetry-collector/component" "github.com/open-telemetry/opentelemetry-collector/config" "github.com/open-telemetry/opentelemetry-collector/config/configcheck" "github.com/open-telemetry/opentelemetry-collector/config/configmodels" "github.com/open-telemetry/opentelemetry...
// Context returns a context provided by the host to be used on the receiver // operations. func (app *Application) Context() context.Context { // For now simply the background context. return context.Background() } // New creates and returns a new instance of Application. func New( factories config.Factories, ap...
// Git hash of the source code. GitHash string } var _ component.Host = (*Application)(nil)
random_line_split
service.go
.org/zap" "github.com/open-telemetry/opentelemetry-collector/component" "github.com/open-telemetry/opentelemetry-collector/config" "github.com/open-telemetry/opentelemetry-collector/config/configcheck" "github.com/open-telemetry/opentelemetry-collector/config/configmodels" "github.com/open-telemetry/opentelemetry...
() error { for _, extName := range app.config.Service.Extensions { extCfg, exists := app.config.Extensions[extName] if !exists { return fmt.Errorf("extension %q is not configured", extName) } factory, exists := app.factories.Extensions[extCfg.Type()] if !exists { return fmt.Errorf("extension factory f...
setupExtensions
identifier_name
service.go
.org/zap" "github.com/open-telemetry/opentelemetry-collector/component" "github.com/open-telemetry/opentelemetry-collector/config" "github.com/open-telemetry/opentelemetry-collector/config/configcheck" "github.com/open-telemetry/opentelemetry-collector/config/configmodels" "github.com/open-telemetry/opentelemetry...
log.Fatalf("Cannot build pipelines: %v", err) } app.logger.Info("Starting processors...") err = app.builtPipelines.StartProcessors(app.logger, app) if err != nil { log.Fatalf("Cannot start processors: %v", err) } // Create receivers and plug them into the start of the pipelines. app.builtReceivers, err = b...
{ // Pipeline is built backwards, starting from exporters, so that we create objects // which are referenced before objects which reference them. // First create exporters. var err error app.exporters, err = builder.NewExportersBuilder(app.logger, app.config, app.factories.Exporters).Build() if err != nil { lo...
identifier_body
NLP_V3_SVD_XGBM_HyperParamCV.py
L1(New)'].value_counts() #Multi class NLP Classification #create a column where each class has a unique id called category id dataframe['category_id'] = dataframe['RMED FaultCode L1(New)'].factorize()[0] category_id_dataframe = dataframe[['RMED FaultCode L1(New)', 'category_id']].drop_duplicates().sort_values('c...
#sns.boxplot(x='model_name', y='accuracy', data=cv_df) #sns.stripplot(x='model_name', y='accuracy', data=cv_df,size=8, jitter=True, edgecolor="gray", linewidth=2) #plt.show() # #cv_df.groupby('model_name').accuracy.mean() # ##continue with the best model further ## may be due to imbalance class - balance it fur...
#import seaborn as sns
random_line_split
NLP_V3_SVD_XGBM_HyperParamCV.py
L1(New)'].value_counts() #Multi class NLP Classification #create a column where each class has a unique id called category id dataframe['category_id'] = dataframe['RMED FaultCode L1(New)'].factorize()[0] category_id_dataframe = dataframe[['RMED FaultCode L1(New)', 'category_id']].drop_duplicates().sort_values('c...
from sklearn.feature_extraction.text import TfidfVectorizer #min_df = When building the vocabulary ignore terms that have a document frequency strictly lower than the given threshold. #norm='l2' = The cosine similarity between two vectors is their dot product when l2 norm has been applied. tfidf = TfidfVectorize...
words = re.sub(r"[^A-Za-z0-9\-]", " ", str_input).lower().split() words = [porter_stemmer.stem(word) for word in words] return words
identifier_body
NLP_V3_SVD_XGBM_HyperParamCV.py
1(New)'].value_counts() #Multi class NLP Classification #create a column where each class has a unique id called category id dataframe['category_id'] = dataframe['RMED FaultCode L1(New)'].factorize()[0] category_id_dataframe = dataframe[['RMED FaultCode L1(New)', 'category_id']].drop_duplicates().sort_values('cat...
(str_input): words = re.sub(r"[^A-Za-z0-9\-]", " ", str_input).lower().split() words = [porter_stemmer.stem(word) for word in words] return words from sklearn.feature_extraction.text import TfidfVectorizer #min_df = When building the vocabulary ignore terms that have a document frequency strictly low...
stemming_tokenizer
identifier_name
manager.py
( ApiKey, ApiSecret, ExchangeApiCredentials, ExchangeAuthCredentials, Location, LocationEventMappingType, ) from rotkehlchen.user_messages import MessagesAggregator from .constants import SUPPORTED_EXCHANGES if TYPE_CHECKING: from rotkehlchen.db.dbhandler import DBHandler from rotkehl...
module_name = module.__name__.split('.')[-1] exchange_ctor = getattr(module, module_name.capitalize()) if credentials.passphrase is not None: kwargs['passphrase'] = credentials.passphrase elif credentials.location == Location.BINANCE: kwargs['uri'] = BINANCE_BAS...
return maybe_exchange # already initialized
conditional_block
manager.py
( ApiKey, ApiSecret, ExchangeApiCredentials, ExchangeAuthCredentials, Location, LocationEventMappingType, ) from rotkehlchen.user_messages import MessagesAggregator from .constants import SUPPORTED_EXCHANGES if TYPE_CHECKING: from rotkehlchen.db.dbhandler import DBHandler from rotkehl...
def get_exchange(self, name: str, location: Location) -> Optional[ExchangeInterface]: """Get the exchange object for an exchange with a given name and location Returns None if it can not be found """ exchanges_list = self.connected_exchanges.get(location) if exchanges_list...
return len(list(self.iterate_exchanges()))
identifier_body
manager.py
( ApiKey, ApiSecret, ExchangeApiCredentials, ExchangeAuthCredentials, Location, LocationEventMappingType, ) from rotkehlchen.user_messages import MessagesAggregator from .constants import SUPPORTED_EXCHANGES if TYPE_CHECKING: from rotkehlchen.db.dbhandler import DBHandler from rotkehl...
(self) -> int: return len(list(self.iterate_exchanges())) def get_exchange(self, name: str, location: Location) -> Optional[ExchangeInterface]: """Get the exchange object for an exchange with a given name and location Returns None if it can not be found """ exchanges_list =...
connected_and_syncing_exchanges_num
identifier_name
manager.py
( ApiKey, ApiSecret, ExchangeApiCredentials, ExchangeAuthCredentials, Location, LocationEventMappingType, ) from rotkehlchen.user_messages import MessagesAggregator from .constants import SUPPORTED_EXCHANGES if TYPE_CHECKING: from rotkehlchen.db.dbhandler import DBHandler from rotkehl...
module: ModuleType, credentials: ExchangeApiCredentials, database: 'DBHandler', **kwargs: Any, ) -> ExchangeInterface: maybe_exchange = self.get_exchange(name=credentials.name, location=credentials.location) if maybe_exchange: return maybe_...
def initialize_exchange( self,
random_line_split
interrupt.rs
match INTERRUPT_CONTROLLER.get_unchecked().model { InterruptModel::Pic(ref pics) => { pics.lock().end_interrupt(Idt::PIC_PS2_KEYBOARD as u8) } InterruptModel::Apic { ref local, .. } => local.end_interrupt(), ...
registers_is_correct_size
identifier_name
interrupt.rs
t::Idt> = spin::Mutex::new(idt::Idt::new()); static INTERRUPT_CONTROLLER: InitOnce<Controller> = InitOnce::uninitialized(); impl Controller { // const DEFAULT_IOAPIC_BASE_PADDR: u64 = 0xFEC00000; pub fn idt() -> spin::MutexGuard<'static, idt::Idt> { IDT.lock() } #[tracing::instrument(level = ...
fn debug_error_code(&self) -> &dyn fmt::Debug { &self.code } fn display_error_code(&self) -> &dyn fmt::Display { &self.code } } impl<'a> ctx::CodeFault for Context<'a, CodeFault<'a>> { fn is_user_mode(&self) -> bool { false // TODO(eliza) } fn instruction_ptr(&se...
{ crate::control_regs::Cr2::read() }
identifier_body
interrupt.rs
interrupt! unsafe { crate::cpu::intrinsics::sti(); } controller } /// Starts a periodic timer which fires the `timer_tick` interrupt of the /// provided [`Handlers`] every time `interval` elapses. pub fn start_periodic_timer( &self, interval: Durati...
code, }); } extern "x86-interrupt" fn gpf_isr<H: Handlers<Registers>>(
random_line_split
node.rs
use std::sync::mpsc; use std::sync; use std::fmt; use std::collections::HashMap; use std::ops::{Deref, DerefMut}; use checktable; use flow::data::DataType; use ops::{Record, Datas}; use flow::domain; use flow::{Ingredient, NodeAddress, Edge}; use flow::payload::Packet; use flow::migrate::materialization::Tag; use ...
random_line_split
node.rs
{ pub streamers: sync::Arc<sync::Mutex<Vec<mpsc::Sender<Vec<StreamUpdate>>>>>, pub state: Option<backlog::ReadHandle>, pub token_generator: Option<checktable::TokenGenerator>, } impl Reader { pub fn get_reader (&self) -> Option<Box<Fn(&DataType) -> Result<Vec<Vec<DataType>>, ()> + Sen...
(&mut self) -> Node { let inner = match *self.inner { Type::Egress { ref tags, ref txs } => { // egress nodes can still be modified externally if subgraphs are added // so we just make a new one with a clone of the Mutex-protected Vec Type::Egress { ...
take
identifier_name
node.rs
NodeHandle::Taken(_) => unreachable!("cannot mutate taken node"), } } } pub enum Type { Ingress, Internal(Box<Ingredient>), Egress { txs: sync::Arc<sync::Mutex<Vec<(NodeAddress, NodeAddress, mpsc::SyncSender<Packet>)>>>, tags: sync::Arc<sync::Mutex<HashMap<Tag, NodeAddress>>>, ...
true } el
conditional_block
node.rs
{ pub streamers: sync::Arc<sync::Mutex<Vec<mpsc::Sender<Vec<StreamUpdate>>>>>, pub state: Option<backlog::ReadHandle>, pub token_generator: Option<checktable::TokenGenerator>, } impl Reader { pub fn get_reader (&self) -> Option<Box<Fn(&DataType) -> Result<Vec<Vec<DataType>>, ()> + Sen...
pub fn mirror(&self, n: Type) -> Node { let mut n = Self::new(&*self.name, &self.fields, n); n.domain = self.domain; n } pub fn name(&self) -> &str { &*self.name } pub fn fields(&self) -> &[String] { &self.fields[..] } pub fn domain(&self) -> doma...
{ Node { name: name.to_string(), domain: None, addr: None, fields: fields.into_iter().map(|s| s.to_string()).collect(), inner: NodeHandle::Owned(inner), } }
identifier_body
create-contact.component.ts
+ JSON.stringify( c.value )); const entriesThatHaveBeenProcessed = {}; for (const phoneAndTypeEntry of c.value) { if (!phoneAndTypeEntry.phone_number || phoneAndTypeEntry.phone_number.trim() === '') { continue; } // don't bother if no phone if (entriesThatHaveBeenProcessed[phoneAndTypeEntry....
this._algoliaKeyManagementService.GetSecureApiKey(this.securityContext.GetCurrentTenant(), 'rolodex-organizations').subscribe( key => {// populate the index this.alogliaClient = algoliasearch(key.application_id, key.api_key); this.algoliaOrganizationIndex = this.alogliaClient.initIndex(key.ind...
this.initAlgolia(); } initAlgolia(): void {
random_line_split
create-contact.component.ts
+ JSON.stringify( c.value )); const entriesThatHaveBeenProcessed = {}; for (const phoneAndTypeEntry of c.value) { if (!phoneAndTypeEntry.phone_number || phoneAndTypeEntry.phone_number.trim() === '') { continue; } // don't bother if no phone if (entriesThatHaveBeenProcessed[phoneAndTypeEntry....
() { if (this.phone_numbers.length >= this.MAX_PHONE_NUMBER_TYPES) { alert('No more phone number types are available.'); return; } this.phone_numbers.push(this.buildPhoneNumberGroup()); } formatPhoneNumber(index: number) { const phone = this.phone_numbers.controls[index].get('phone_num...
addPhoneNumber
identifier_name
create-contact.component.ts
JSON.stringify( c.value )); const entriesThatHaveBeenProcessed = {}; for (const phoneAndTypeEntry of c.value) { if (!phoneAndTypeEntry.phone_number || phoneAndTypeEntry.phone_number.trim() === '') { continue; } // don't bother if no phone if (entriesThatHaveBeenProcessed[phoneAndTypeEntry.ph...
addPhoneNumber() { if (this.phone_numbers.length >= this.MAX_PHONE_NUMBER_TYPES) { alert('No more phone number types are available.'); return; } this.phone_numbers.push(this.buildPhoneNumberGroup()); } formatPhoneNumber(index: number) { const phone = this.phone_numbers.controls[ind...
{ return this.fb.group({ phone_number: '', phone_number_type: 'mobile' }); }
identifier_body
deployment.go
/BASEDIR/APPNAME/release/VERSION1 /BASEDIR/APPNAME/release/VERSION2 /BASEDIR/APPNAME/release/VERSION3 Releasing a version points the "current" symlink to the specified release directory. */ package deployment import ( "crypto/hmac" "errors" "fmt" "io" "io/ioutil" "os" "os/user" "path" "strconv" "string...
"release" directory.
random_line_split
deployment.go
this deployment gid int // The numeric GID to own all files for this deployment baseDir string // The derived top-level directory for this app's files artifactDir string // The derived subdirectory for fetched build artifacts releaseDir string ...
else { return nil, fmt.Errorf("Deployment initialization error: invalid ArtifactType %q", d.cfg.ArtifactType) } // Derive the UID/GID from the username/groupname. // NOTE: Go doesn't yet support looking up a GID from a name, so // we use the gid from the user. if d.cfg.User != "" { if user, err := user...
{ d.acfg = *ac }
conditional_block
deployment.go
artifactDir string // The derived subdirectory for fetched build artifacts releaseDir string // The derived subdirectory for extracted build artifacts } // New returns a new Deployment. func New(appName string, pdcfg pdconfig.PDConfig, cfg *pdconfig.AppConfig) (*Deployment, error)...
{ versionDir, exists := makeReleasePath(d.releaseDir, version) if !exists { return fmt.Errorf("Release directory does not exist: %q", versionDir) } symlinkPath := path.Join(d.baseDir, kCURRENTDIR) os.Remove(symlinkPath) return os.Symlink(versionDir, symlinkPath) }
identifier_body
deployment.go
this deployment gid int // The numeric GID to own all files for this deployment baseDir string // The derived top-level directory for this app's files artifactDir string // The derived subdirectory for fetched build artifacts releaseDir string ...
(version string) bool { // Generate the filename, and check whether file already exists. _, exists := makeArtifactPath(d.artifactDir, d.appName, version, d.acfg.Extension) return exists } // Write creates a file in the artifact area from the given stream. func (d *Deployment) WriteArtifact(version string, rc io.Re...
ArtifactPresent
identifier_name
mod.rs
コールバック終了後に Listener が Dispatcher に指示する動作を表す列挙型です。 pub enum DispatcherAction { /// 特に何も行わないで処理を続行することを示します。 Continue, /// 指定された Interest フラグに変更することを指定します。 ChangeFlag(Interest), /// イベントの発生元となるソケットなどの Source の破棄を指定します。 Dispose, } // ############################################################################...
spatcherAction::Dispose => self.close(id), } } fn on_tcp_stream( &mut self, event: &Event, stream: &mut TcpStream, listener: &mut Box<dyn TcpStreamListener>, ) {
est).unwrap(); } Di
conditional_block
mod.rs
fn run_in_event_loop<E>(&self, exec: Box<E>) -> Box<dyn Future<Output=Result<SocketId>>> where E: (FnOnce(&mut PollingLoop) -> Result<SocketId>) + Send + 'static, { let task = Task::new(exec); let future = TaskFuture { state: task.state.clone() }; self.sender.send(task).unwrap(); self.waker...
i
identifier_name
mod.rs
へのコールバック終了後に Listener が Dispatcher に指示する動作を表す列挙型です。 pub enum DispatcherAction { /// 特に何も行わないで処理を続行することを示します。 Continue, /// 指定された Interest フラグに変更することを指定します。 ChangeFlag(Interest), /// イベントの発生元となるソケットなどの Source の破棄を指定します。 Dispose, } // ##########################################################################...
Future<Output=Result<SocketId>>>; } impl DispatcherRegister<TcpListener, Box<dyn TcpListenerListener>> for Dispatcher { fn register( &self, mut listener: TcpListener, event_listener: Box<dyn TcpListenerListener>, ) -> Box<dyn Future<Output=Result<SocketId>>> { self.run_in_event_loop(Box::new(move ...
Ok(0usize) })); } } trait DispatcherRegister<S, L> { fn register(&self, source: S, listener: L) -> Box<dyn
identifier_body
mod.rs
へのコールバック終了後に Listener が Dispatcher に指示する動作を表す列挙型です。 pub enum DispatcherAction { /// 特に何も行わないで処理を続行することを示します。 Continue, /// 指定された Interest フラグに変更することを指定します。 ChangeFlag(Interest), /// イベントの発生元となるソケットなどの Source の破棄を指定します。 Dispose, } // ##########################################################################...
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> std::task::Poll<Self::Output> { use std::task::Poll; let mut state = self.state.lock().unwrap(); if let Some(result) = state.result.take() { Poll::Ready(result) } else { state.waker = Some(cx.waker().clone()); Poll::Pending ...
type Output = R;
random_line_split
autoencoder.py
self._latent_dim = 64 self._epochs = 500 self.encoder = tf.keras.Sequential([ layers.Flatten(), layers.Dense(self._latent_dim, activation='relu'), ]) self.decoder = tf.keras.Sequential([ layers.Dense(10800, activation='sigmoid'), layers.Reshape((60, 60, 3)) ]) def call(se...
def display_output(self, decoded, num_images): ''' Display output image(s). ''' pass class ViewImages(View): ''' Display the input images and their output after going through the autoencoder. ''' def display_input(self, images, num_images): ''' Display original input image(s). ...
''' Display original input image(s). ''' pass
identifier_body
autoencoder.py
._latent_dim = 64 self._epochs = 500 self.encoder = tf.keras.Sequential([ layers.Flatten(), layers.Dense(self._latent_dim, activation='relu'), ]) self.decoder = tf.keras.Sequential([ layers.Dense(10800, activation='sigmoid'), layers.Reshape((60, 60, 3)) ]) def call(self, x...
else: train_num = int(train_num) # Get the path for the folder of the user image(s). test_folder_input = input( "Enter the folder path for the image(s) you want to transform: ") test_folder = test_folder_input.strip() # Get the name of the image(s) to transform. test...
self._invalid_input()
conditional_block
autoencoder.py
""" import PIL from PIL import Image import numpy as np import sys from matplotlib import image from matplotlib import pyplot as plt #from google.colab import files import os.path from os import path import pandas as pd ''' import tensorflow as tf from sklearn.metrics import accuracy_score, precision_score, recall_sc...
Original file is located at https://colab.research.google.com/drive/1SFG3__AoM7dvKI06qiu76tW-mtbZDsxn
random_line_split
autoencoder.py
self._latent_dim = 64 self._epochs = 500 self.encoder = tf.keras.Sequential([ layers.Flatten(), layers.Dense(self._latent_dim, activation='relu'), ]) self.decoder = tf.keras.Sequential([ layers.Dense(10800, activation='sigmoid'), layers.Reshape((60, 60, 3)) ]) def call(se...
(self, image): ''' Crop image into a squre with the dimentions defined by _image_size. Arguments: image: A Pillow image. Returns: A square Pillow image with the specified pixel dimentions. ''' width, height = image.size # Determine if width or height is smaller. if width >=...
_square_image
identifier_name
client.go
16 // TODO: Public keys of trusted monitors. ) var ( // ErrRetry occurs when an update has been queued, but the // results of the update differ from the one requested. // This indicates that a separate update was in-flight while // this update was being submitted. To continue, the client // should make a fresh ...
(ctx context.Context, u *tpb.User, signers []signatures.Signer) (*entry.Mutation, error) { if got, want := u.DomainId, c.domainID; got != want { return nil, fmt.Errorf("u.DomainID: %v, want %v", got, want) } // 1. pb.User + ExistingEntry -> Mutation. m, err := c.newMutation(ctx, u) if err != nil { return nil, ...
Update
identifier_name
client.go
16 // TODO: Public keys of trusted monitors. ) var ( // ErrRetry occurs when an update has been queued, but the // results of the update differ from the one requested. // This indicates that a separate update was in-flight while // this update was being submitted. To continue, the client // should make a fresh ...
if len(u.AuthorizedKeys) != 0 { if err := mutation.ReplaceAuthorizedKeys(u.AuthorizedKeys); err != nil { return nil, err } } return mutation, nil } // WaitForUserUpdate waits for the mutation to be applied or the context to timeout or cancel. func (c *Client) WaitForUserUpdate(ctx context.Context, m *entr...
{ return nil, err }
conditional_block
client.go
16 // TODO: Public keys of trusted monitors. ) var ( // ErrRetry occurs when an update has been queued, but the // results of the update differ from the one requested. // This indicates that a separate update was in-flight while // this update was being submitted. To continue, the client // should make a fresh ...
func (c *Client) updateTrusted(newTrusted *trillian.SignedLogRoot) { if newTrusted.TimestampNanos > c.trusted.TimestampNanos && newTrusted.TreeSize >= c.trusted.TreeSize { c.trusted = *newTrusted } } // GetEntry returns an entry if it exists, and nil if it does not. func (c *Client) GetEntry(ctx context.Contex...
{ return &Client{ Verifier: ktVerifier, cli: ktClient, domainID: domainID, mutator: entry.New(), RetryDelay: 3 * time.Second, } }
identifier_body
client.go
16 // TODO: Public keys of trusted monitors. ) var ( // ErrRetry occurs when an update has been queued, but the // results of the update differ from the one requested. // This indicates that a separate update was in-flight while // this update was being submitted. To continue, the client // should make a fresh ...
if err != nil { return nil, err } return New(ktClient, config.DomainId, ktVerifier), nil } // New creates a new client. // TODO(gbelvin): set retry delay. func New(ktClient pb.KeyTransparencyClient, domainID string, ktVerifier *Verifier) *Client { return &Client{ Verifier: ktVerifier, cli: ktClien...
// NewFromConfig creates a new client from a config func NewFromConfig(ktClient pb.KeyTransparencyClient, config *pb.Domain) (*Client, error) { ktVerifier, err := NewVerifierFromDomain(config)
random_line_split
LyftDataAnalysis.py
4]: ''' Nan value inspection ''' print('driver ids info:------------------------------') driver_df.info() print('ride ids info:--------------------------------') ride_df.info() print('ride timestamps info:-------------------------') ride_timestamps_df.info() ''' ride_timestamps has one Nan value in the column timesta...
return total_fare # In[27]: merged_big_df = pd.read_csv('merged_big_driver_ride_df.csv') print(merged_big_df.shape) display(merged_big_df.head()) # In[19]: # ''' # validate the correctness of combined df by randomly selecting ride ids to verify (random checking) # ''' # ids = test1.ride_id # i = np.random....
total_fare += (1 + prime/100)*(min(max(5,(2 + 1.15*distance*0.00062 + 0.22*duration/60 + 1.75)),400))
conditional_block
LyftDataAnalysis.py
4]: ''' Nan value inspection ''' print('driver ids info:------------------------------') driver_df.info() print('ride ids info:--------------------------------') ride_df.info() print('ride timestamps info:-------------------------') ride_timestamps_df.info() ''' ride_timestamps has one Nan value in the column timesta...
(driver_rides): total_fare = 0 # if one single ride if driver_rides.ndim == 1: total_fare = (1 + driver_rides['ride_prime_time']/100)*(min(max(5,(2 + 1.15*driver_rides['ride_distance'] *0.00062 + 0.22 ...
get_fare
identifier_name
LyftDataAnalysis.py
4]: ''' Nan value inspection ''' print('driver ids info:------------------------------') driver_df.info() print('ride ids info:--------------------------------') ride_df.info() print('ride timestamps info:-------------------------') ride_timestamps_df.info() ''' ride_timestamps has one Nan value in the column timesta...
# In[27]: merged_big_df = pd.read_csv('merged_big_driver_ride_df.csv') print(merged_big_df.shape) display(merged_big_df.head()) # In[19]: # ''' # validate the correctness of combined df by randomly selecting ride ids to verify (random checking) # ''' # ids = test1.ride_id # i = np.random.choice(ids,10) # for x...
total_fare = 0 # if one single ride if driver_rides.ndim == 1: total_fare = (1 + driver_rides['ride_prime_time']/100)*(min(max(5,(2 + 1.15*driver_rides['ride_distance'] *0.00062 + 0.22 ...
identifier_body
LyftDataAnalysis.py
4]: ''' Nan value inspection ''' print('driver ids info:------------------------------') driver_df.info() print('ride ids info:--------------------------------') ride_df.info() print('ride timestamps info:-------------------------') ride_timestamps_df.info() ''' ride_timestamps has one Nan value in the column timesta...
rides_added_vars_df = merged_big_df.apply(add_vars,axis=1) print('duration:',(time.time() - start)/60,'minutes') # In[29]: print(rides_added_vars_df.shape) display(rides_added_vars_df.head()) # In[30]: # saved for future use rides_added_vars_df.to_csv('added_variables_rides_info.csv',index=False) # ## Get new...
start = time.time()
random_line_split
lib.rs
entially quantified variable. BNode(BlankNode<TD>), /// An RDF literal. Literal(Literal<TD>), /// A universally quantified variable like in SPARQL or Notation3. Variable(Variable<TD>), } /// Trait alias for types holding the textual data of terms. pub trait TermData: AsRef<str> + Clone + Eq + Hash ...
U: AsRef<str>, T: From<U>, { Iri::<T>::new(iri).map(Into::into) } /// Return a new IRI term from the two given parts (prefix and suffix). /// /// May fail if the concatenation of `ns` and `suffix` /// does not produce a valid IRI. pub fn new_iri_suffixed<U, V>(ns: U,...
pub fn new_iri<U>(iri: U) -> Result<Term<T>> where
random_line_split
lib.rs
language tag. /// /// May fail if the language tag is not a valid BCP47 language tag. pub fn new_literal_lang<U, V>(txt: U, lang: V) -> Result<Self> where V: AsRef<str>, T: From<U> + From<V>, { Literal::<T>::new_lang(txt, lang).map(Into::into) } /// Return a new lit...
partial_cmp
identifier_name
custom_insts.rs
of the disambiguating suffixes added for specific revisions. /// /// This **should not** be changed (if possible), to ensure version mismatches /// can be detected (i.e. starting with this prefix, but the full name differs). /// /// See `CUSTOM_EXT_INST_SET`'s docs for further constraints on the full name. pub const C...
/// These considerations are relevant to the specific choice of name: /// * does *not* start with `NonSemantic.`, as: /// * some custom instructions may need to be semantic /// * these custom instructions are not meant for the final SPIR-V /// (so no third-party support is *technically* requ...
} lazy_static! { /// `OpExtInstImport` "instruction set" name for all Rust-GPU instructions. ///
random_line_split
custom_insts.rs
_version_major_minor_patch { ($sep:literal) => { concat!( env!("CARGO_PKG_VERSION_MAJOR"), $sep, env!("CARGO_PKG_VERSION_MINOR"), $sep, env!("CARGO_PKG_VERSION_PATCH"), ) }; } lazy_static! { /// `OpExtInstImport` "instruction set" ...
{ match self { CustomOp::SetDebugSrcLoc | CustomOp::ClearDebugSrcLoc | CustomOp::PushInlinedCallFrame | CustomOp::PopInlinedCallFrame => true, CustomOp::Abort => false, } }
identifier_body
custom_insts.rs
starting with this prefix, but the full name differs). /// /// See `CUSTOM_EXT_INST_SET`'s docs for further constraints on the full name. pub const CUSTOM_EXT_INST_SET_PREFIX: &str = concat!("Rust.", env!("CARGO_PKG_NAME"), "."); macro_rules! join_cargo_pkg_version_major_minor_patch { ($sep:literal) => { ...
is_debuginfo
identifier_name
mod.rs
uf_feedback_v1, wayland_server::{protocol::wl_surface::WlSurface, Display}, }, wayland::dmabuf::{ DmabufFeedback, DmabufFeedbackBuilder, DmabufGlobal, DmabufHandler, DmabufState, ImportError, }, }; use self::drm::{BackendData, SurfaceComposition, UdevOutputId}; use crate::{cursor::C...
() { let mut event_loop = EventLoop::try_new().expect("Unable to initialize event loop"); let (session, mut _notifier) = match LibSeatSession::new() { Ok((session, notifier)) => (session, notifier), Err(err) => { tracing::error!("Error in creating libseat session: {}", err); ...
initialize_backend
identifier_name
mod.rs
uf_feedback_v1, wayland_server::{protocol::wl_surface::WlSurface, Display}, }, wayland::dmabuf::{ DmabufFeedback, DmabufFeedbackBuilder, DmabufGlobal, DmabufHandler, DmabufState, ImportError, }, }; use self::drm::{BackendData, SurfaceComposition, UdevOutputId}; use crate::{cursor::C...
#[cfg_attr(not(feature = "egl"), allow(unused_mut))] let mut renderer = state .backend_data .gpu_manager .single_renderer(&primary_gpu) .unwrap(); #[cfg(feature = "egl")] { match renderer.bind_wl_display(&state.display_handle) { Ok(_) => tracing::info...
});
random_line_split
mod.rs
_feedback_v1, wayland_server::{protocol::wl_surface::WlSurface, Display}, }, wayland::dmabuf::{ DmabufFeedback, DmabufFeedbackBuilder, DmabufGlobal, DmabufHandler, DmabufState, ImportError, }, }; use self::drm::{BackendData, SurfaceComposition, UdevOutputId}; use crate::{cursor::Cur...
fn reset_buffers(&mut self, output: &smithay::output::Output) { if let Some(id) = output.user_data().get::<UdevOutputId>() { if let Some(gpu) = self.backends.get_mut(&id.device_id) { if let Some(surface) = gpu.surfaces.get_mut(&id.crtc) { surface.compositor....
{ &self.loop_signal }
identifier_body
mod.rs
run<F>(future: F) where F: Future<Item = (), Error = ()> + Send + 'static, { let mut runtime = Runtime::new().unwrap(); runtime.spawn(future); enter().expect("nested tokio::run") .block_on(runtime.shutdown_on_idle()) .unwrap(); } impl Runtime { /// Create a new runtime instance with de...
{ let shutdown = Shutdown::shutdown_now(inner); let _ = shutdown.wait(); }
conditional_block
mod.rs
Task execution pool. pool: threadpool::ThreadPool, } // ===== impl Runtime ===== /// Start the Tokio runtime using the supplied future to bootstrap execution. /// /// This function is used to bootstrap the execution of a Tokio application. It /// does the following: /// /// * Start the Tokio runtime using a defa...
{ let inner = self.inner.take().unwrap(); let inner = inner.pool.shutdown_on_idle(); Shutdown { inner } }
identifier_body
mod.rs
) -> Box<Future<Item = (), Error = ()> + Send> { //! # unimplemented!(); //! # } //! # fn dox() { //! # let addr = "127.0.0.1:8080".parse().unwrap(); //! let listener = TcpListener::bind(&addr).unwrap(); //! //! let server = listener.incoming() //! .map_err(|e| println!("error = {:?}", e)) //! .for_each(|socket...
random_line_split
mod.rs
.for_each(|socket| { //! tokio::spawn(process(socket)) //! }); //! //! tokio::run(server); //! # } //! # pub fn main() {} //! ``` //! //! In this function, the `run` function blocks until the runtime becomes idle. //! See [`shutdown_on_idle`][idle] for more shutdown details. //! //! From within the con...
() -> io::Result<Self> { Builder::new().build() } #[deprecated(since = "0.1.5", note = "use `reactor` instead")] #[doc(hidden)] pub fn handle(&self) -> &Handle { #[allow(deprecated)] self.reactor() } /// Return a reference to the reactor handle for this runtime instance...
new
identifier_name
manager.py
initiating the ``setup`` stage of the lifecycle. This module provides the default implementation and interface. The :class:`ComponentManager` is the first plugin loaded by the :class:`SimulationContext <vivarium.framework.engine.SimulationContext>` and managers and components are given to it by the context. It is cal...
def __iter__(self) -> Iterator: return iter(self.components) def __len__(self) -> int: return len(self.components) def __bool__(self) -> bool: return bool(self.components) def __add__(self, other: "OrderedComponentSet") -> "OrderedComponentSet": return OrderedCompone...
if not hasattr(component, "name"): raise ComponentConfigError(f"Component {component} has no name attribute") return component.name in [c.name for c in self.components]
identifier_body
manager.py
initiating the ``setup`` stage of the lifecycle. This module provides the default implementation and interface. The :class:`ComponentManager` is the first plugin loaded by the :class:`SimulationContext <vivarium.framework.engine.SimulationContext>` and managers and components are given to it by the context. It is cal...
(self, component: Any) -> bool: if not hasattr(component, "name"): raise ComponentConfigError(f"Component {component} has no name attribute") return component.name in [c.name for c in self.components] def __iter__(self) -> Iterator: return iter(self.components) def __len__(...
__contains__
identifier_name
manager.py
initiating the ``setup`` stage of the lifecycle. This module provides the default implementation and interface. The :class:`ComponentManager` is the first plugin loaded by the :class:`SimulationContext <vivarium.framework.engine.SimulationContext>` and managers and components are given to it by the context. It is cal...
return out @staticmethod def _setup_components(builder: "Builder", components: OrderedComponentSet): for c in components: if hasattr(c, "setup"): c.setup(builder) def __repr__(self): return "ComponentManager()" class ComponentInterface: """The bui...
current = components.pop() if isinstance(current, (list, tuple)): components.extend(current[::-1]) else: if hasattr(current, "sub_components"): components.extend(current.sub_components[::-1]) out.append(current)
conditional_block
manager.py
initiating the ``setup`` stage of the lifecycle. This module provides the default implementation and interface. The :class:`ComponentManager` is the first plugin loaded by the :class:`SimulationContext <vivarium.framework.engine.SimulationContext>` and managers and components are given to it by the context. It is cal...
""" for c in self._flatten(components): self.apply_configuration_defaults(c) self._components.add(c) def get_components_by_type( self, component_type: Union[type, Tuple[type, ...]] ) -> List[Any]: """Get all components that are an instance of ``component...
Instantiated components to register.
random_line_split
digest.py
_contigs_path = os.path.join(output_dir, output_contigs) frag_list_path = os.path.join(output_dir, output_frags) except TypeError: info_contigs_path = output_contigs frag_list_path = output_frags with open(info_contigs_path, "w") as info_contigs: info_contigs.write("contig\tlen...
(pairs_file, idx_pairs_file, restriction_table): """ Writes the indexed pairs file, which has two more columns than the input pairs file corresponding to the restriction fragment index of each read. Note that pairs files have 1bp point positions whereas restriction table has 0bp point poisitions. ...
attribute_fragments
identifier_name
digest.py
) pairs_writer = csv.DictWriter( idx_pairs, fieldnames=idx_cols, delimiter="\t" ) for pair in pairs_reader: # Get the 0-based indices of corresponding restriction fragments # Deducing 1 from pair position to get it into 0bp point pair["frag1"] = ...
site = enz.elucidate() fw_cut = site.find("^") rev_cut = site.find("_") # Process "give" site. Remove N on the left (useless). give_site = site[:rev_cut].replace("^", "") while give_site[0] == "N": give_site = give_site[1:] give_list.append(give_site) ...
conditional_block
digest.py
records: contig_seq = record.seq contig_name = record.id contig_length = len(contig_seq) if contig_length < int(min_size): continue sites = get_restriction_table( contig_seq, enzyme, circular=circul...
""" Use binary search to find the index of a chromosome restriction fragment corresponding to an input genomic position. Parameters ---------- pos : int Genomic position, in base pairs. r_sites : list List of genomic positions corresponding to restriction sites. Returns -...
identifier_body
digest.py
_contigs_path = os.path.join(output_dir, output_contigs) frag_list_path = os.path.join(output_dir, output_frags) except TypeError: info_contigs_path = output_contigs frag_list_path = output_frags with open(info_contigs_path, "w") as info_contigs: info_contigs.write("contig\tlen...
n_frags, total_frags, ) total_frags += n_frags info_contigs.write(current_contig_line) def attribute_fragments(pairs_file, idx_pairs_file, restriction_table): """ Writes the indexed pairs file, which has two more columns t...
current_contig_line = "%s\t%s\t%s\t%s\n" % ( contig_name, contig_length,
random_line_split
mod.rs
service in services { let id = service.service_id() as usize; if service_map.contains_key(id) { panic!( "Services have already contain service with id={}, please change it.", id ); } service_map.inse...
else { panic!("Could not set database version.") } } /// Checks if storage version is supported. /// /// # Panics /// /// Panics if version is not supported or is not specified. fn assert_storage_version(&self) { match storage::StorageMetadata::read(self.db.snap...
{ info!( "Storage version successfully initialized with value [{}].", storage::StorageMetadata::read(&self.db.snapshot()).unwrap(), ) }
conditional_block
mod.rs
service in services { let id = service.service_id() as usize; if service_map.contains_key(id) { panic!( "Services have already contain service with id={}, please change it.", id ); } service_map.inse...
/// Returns the hash of the latest committed block. /// /// # Panics /// /// If the genesis block was not committed. pub fn last_hash(&self) -> Hash { Schema::new(&self.snapshot()) .block_hashes_by_height() .last() .unwrap_or_else(Hash::default) ...
{ self.db.merge(patch) }
identifier_body
mod.rs
_patch())?; self.create_patch(ValidatorId::zero(), Height::zero(), &[]) .1 }; self.merge(patch)?; Ok(()) } /// Helper function to map a tuple (`u16`, `u16`) of service table coordinates /// to a 32-byte value to be used as the `ProofMapIndex` key (it curr...
self.merge(fork.into_patch()) .expect("Unable to save peer to the peers cache"); } /// Removes from the cache the `Connect` message from a peer.
random_line_split
mod.rs
pub fn create_patch( &self, proposer_id: ValidatorId, height: Height, tx_hashes: &[Hash], ) -> (Hash, Patch) { // Create fork let mut fork = self.fork(); let block_hash = { // Get last hash. let last_hash = self.last_hash(); ...
before_commit
identifier_name
setup.py
CYTHON_MIN_VER = "0.29.26" # released 2020 EXTRAS_REQUIRE = { "build": ["cython>=" + CYTHON_MIN_VER], "develop": ["cython>=" + CYTHON_MIN_VER] + DEVELOP_REQUIRES, "docs": [ "sphinx", "nbconvert", "jupyter_client", "ipykernel", "matplotlib", "nbformat", ...
(source_name): """Runs pyx.in files through tempita is needed""" if source_name.endswith("pyx.in"): with open(source_name, "r", encoding="utf-8") as templated: pyx_template = templated.read() pyx = Tempita.sub(pyx_template) pyx_filename = source_name[:-3] with open(py...
process_tempita
identifier_name
setup.py
"true", '"true"') CYTHON_TRACE_NOGIL = str(int(CYTHON_COVERAGE)) if CYTHON_COVERAGE: print("Building with coverage for Cython code") COMPILER_DIRECTIVES = {"linetrace": CYTHON_COVERAGE} DEFINE_MACROS = [ ("CYTHON_TRACE_NOGIL", CYTHON_TRACE_NOGIL), ("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION"), ] exts ...
project_urls=PROJECT_URLS,
random_line_split
setup.py
test*.mat"], STATESPACE_RESULTS + ".frbny_nowcast.Nowcasting.data.US": ["*.csv"], } ############################################################################## # Extension Building ############################################################################## CYTHON_COVERAGE = os.environ.get("SM_CYTHON_COVERAGE...
return False
identifier_body
setup.py
CYTHON_MIN_VER = "0.29.26" # released 2020 EXTRAS_REQUIRE = { "build": ["cython>=" + CYTHON_MIN_VER], "develop": ["cython>=" + CYTHON_MIN_VER] + DEVELOP_REQUIRES, "docs": [ "sphinx", "nbconvert", "jupyter_client", "ipykernel", "matplotlib", "nbformat", ...
STATESPACE_RESULTS = "statsmodels.tsa.statespace.tests.results" ADDITIONAL_PACKAGE_DATA = { "statsmodels": FILES_TO_INCLUDE_IN_PACKAGE, "statsmodels.datasets.tests": ["*.zip"], "statsmodels.iolib.tests.results": ["*.dta"], "statsmodels.stats.tests.results": ["*.json"], "statsmodels.tsa.stl.tests....
dest = os.path.join("statsmodels", filename) shutil.copy2(filename, dest) FILES_COPIED_TO_PACKAGE.append(dest)
conditional_block
cpu.go
even when // test execution exceeds the maximum time allowed. ctx, cancel := ctxutil.Shorten(ctx, cleanupTime) defer cancel() // CPU frequency scaling and thermal throttling might influence our test results. if restoreScaling, err = disableCPUFrequencyScaling(ctx); err != nil { return nil, errors.Wrap(err, "fa...
getThermalThrottlingJob
identifier_name
cpu.go
context. This ensures // thermal throttling and CPU frequency scaling get re-enabled, even when // test execution exceeds the maximum time allowed. ctx, cancel := ctxutil.Shorten(ctx, cleanupTime) defer cancel() // CPU frequency scaling and thermal throttling might influence our test results. if restoreScaling,...
random_line_split
cpu.go
cleanupTime = 5 * time.Second // time reserved for cleanup after measuring. ) for _, t := range ts { // Start the process asynchronously by calling the provided startup function. cmd, err := t.Start(ctx) if err != nil { return nil, errors.Wrap(err, "failed to run binary") } // Clean up the process u...
powerConsumption, err := strconv.ParseFloat(match[0], 64) if err != nil { return 0.0, err } return powerConsumption, nil } // cpuConfigEntry holds a single CPU config entry. If ignoreErrors is true // failure to apply the config will result in a warning, rather than an error. // This is needed as on some platf...
{ return 0.0, errors.Errorf("failed to parse output of %s", raplExec) }
conditional_block
cpu.go
!= nil { return nil, errors.Wrap(err, "failed to disable thermal throttling") } // Disarm running the cleanUp function now that we expect the caller to do it. doCleanup = nil return cleanUp, nil } // MeasureUsage measures the average utilization across all CPUs and the // average SoC 'pkg' power consumption du...
{ // List of possible thermal throttling jobs that should be disabled: // - dptf for intel >= baytrail // - temp_metrics for link // - thermal for daisy, snow, pit,... for _, job := range []string{"dptf", "temp_metrics", "thermal"} { if upstart.JobExists(ctx, job) { return job } } return "" }
identifier_body
manage.py
Partial shade, ambient humidity # Zone D: Full sun, ambient humidity @manager.command def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) @manager.command def recreate_db(): """ Recreates a loc...
except IntegrityError: dprint('uh oh') db.session.rollback() else: dprint("Day {}: Order[{}] Item[{}]".format( dayNum, invoice.id, invoice.item)) @manager.command def updateLog(plantSKU, waterDate, dayNum): water = WaterLog( plant = plantSKU, ...
newOrder = Orders() plants = Plant.generate_fake( numPlants ) for i in plants: invoice = Orders( supplier = 'TGKmf', date = orderDate, date_received = orderDate + timedelta(days=2), item = i.sku, price = i.price/randrange(2, 5, 1), ...
identifier_body
manage.py
.session.execute('DROP TABLE IF EXISTS genera;') db.session.execute('DROP TABLE IF EXISTS families;') db.drop_all() db.create_all() db.session.commit() fakePlant = Plant(living = True) db.session.add(fakePlant) db.session.commit() db.session.delete(fakePlant) db.session.execute('SET ...
simDay += timedelta(days=1) dayNum += 1
random_line_split
manage.py
12.99, 'D'), ('Peat moss - 10L', 6.00, 19.99, 'D'), ('Perlite - 5L', 3.50, 10.99, 'D'), ('Perlite - 10L', 5.00, 16.99, 'D'), ('Hydroton - 10L', 7.31, 14.99, 'D'), ('Vermiculite - 5L', 3.75, 9.99, 'D'), ('Vermiculite - 10L', 5.75, 13.99, 'D'), ('"Premium" dirt - 5...
user = Employee(first_name='Admin', last_name='Account', password=Config.ADMIN_PASSWORD, email=Config.ADMIN_EMAIL) db.session.add(user) db.session.commit() print('Added administrator {}'.format(user.full_name()))
conditional_block
manage.py
Partial shade, ambient humidity # Zone D: Full sun, ambient humidity @manager.command def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) @manager.command def recreate_db(): """ Recreates a loc...
( numItems, orderDate, dayNum ): # Simulation # Generate fake order and add to inventory newOrder = Orders() StuffWeSell = [ ('Shovel', 14.30, 24.99, 'B'), ('Peat moss - 5L', 4.75, 12.99, 'D'), ('Peat moss - 10L', 6.00, 19.99, 'D'), ('Perlite - 5L', 3.50, 10.99, 'D'), ...
OrderMerchandise
identifier_name
lambda.rs
X_COMMUNITY_KEYGEN_POLICY_ID").unwrap(); static ref SMTP_SERVER: String = env::var("SMTP_SERVER").unwrap(); static ref SMTP_USERNAME: String = env::var("SMTP_USERNAME").unwrap(); static ref SMTP_PASSWORD: String = env::var("SMTP_PASSWORD").unwrap(); } fn router(req: Request, c: Context) -> Result<Response<...
Ok(Response::builder() .status(http::StatusCode::OK) .body(Body::default()) .unwrap()) } /// Patreon pledge create trigger fn patreon_handle_pledge_create( client: &reqwest::Client, body: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_pledge_creat...
} else if trigger == "pledges:delete" { patreon_handle_pledge_delete(client, &body)?; }
random_line_split
lambda.rs
_COMMUNITY_KEYGEN_POLICY_ID").unwrap(); static ref SMTP_SERVER: String = env::var("SMTP_SERVER").unwrap(); static ref SMTP_USERNAME: String = env::var("SMTP_USERNAME").unwrap(); static ref SMTP_PASSWORD: String = env::var("SMTP_PASSWORD").unwrap(); } fn router(req: Request, c: Context) -> Result<Response<B...
fn handle_patreon_webhook( client: &reqwest::Client, req: Request, _c: Context, ) -> Result<Response<Body>, HandlerError> { if !patreon::authentify_web_hook(&req) { return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) ...
{ code.split('.').nth(1) }
identifier_body
lambda.rs
X_COMMUNITY_KEYGEN_POLICY_ID").unwrap(); static ref SMTP_SERVER: String = env::var("SMTP_SERVER").unwrap(); static ref SMTP_USERNAME: String = env::var("SMTP_USERNAME").unwrap(); static ref SMTP_PASSWORD: String = env::var("SMTP_PASSWORD").unwrap(); } fn
(req: Request, c: Context) -> Result<Response<Body>, HandlerError> { debug!("router request={:?}", req); debug!("path={:?}", req.uri().path()); debug!("query={:?}", req.query_string_parameters()); let client = reqwest::Client::new(); match req.uri().path() { "/fastspring-keygen-integration...
router
identifier_name