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 |
|---|---|---|---|---|
contacts-details.component.ts | import { Component, OnInit, Input, forwardRef, ViewChild, OnDestroy, Inject, ChangeDetectionStrategy, ChangeDetectorRef, OnChanges, SimpleChanges } from '@angular/core';
import { FormControl, FormGroup, Validators, FormBuilder, NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { HttpClient, HttpHe... |
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 | import { Component, OnInit, Input, forwardRef, ViewChild, OnDestroy, Inject, ChangeDetectionStrategy, ChangeDetectorRef, OnChanges, SimpleChanges } from '@angular/core';
import { FormControl, FormGroup, Validators, FormBuilder, NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { HttpClient, HttpHe... | (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 | package jobs
import (
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/hyperledger/burrow/crypto"
"github.com/hyperledger/burrow/txs/payload"
"github.com/monax/bosmarmot/bos/abi"
compilers "github.com/monax/bosmarmot/bos/compile"
"github.com/monax/bosmarmot/bos/def"
"github.com/... | (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 | package jobs
import (
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/hyperledger/burrow/crypto"
"github.com/hyperledger/burrow/txs/payload"
"github.com/monax/bosmarmot/bos/abi"
compilers "github.com/monax/bosmarmot/bos/compile"
"github.com/monax/bosmarmot/bos/def"
"github.com/... | 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 | package jobs
import (
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/hyperledger/burrow/crypto"
"github.com/hyperledger/burrow/txs/payload"
"github.com/monax/bosmarmot/bos/abi"
compilers "github.com/monax/bosmarmot/bos/compile"
"github.com/monax/bosmarmot/bos/def"
"github.com/... |
func deployTx(do *def.Packages, deploy *def.Deploy, contractName, contractCode string) (*payload.CallTx, error) {
// Deploy contract
log.WithFields(log.Fields{
"name": contractName,
}).Warn("Deploying Contract")
log.WithFields(log.Fields{
"source": deploy.Source,
"code": contractCode,
"chain-url"... | {
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 | package jobs
import (
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/hyperledger/burrow/crypto"
"github.com/hyperledger/burrow/txs/payload"
"github.com/monax/bosmarmot/bos/abi"
compilers "github.com/monax/bosmarmot/bos/compile"
"github.com/monax/bosmarmot/bos/def"
"github.com/... |
}
}
}
}
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 | // Project: https://github.com/takayama-lily/oicq
/// <reference types="node" />
import * as events from 'events';
import * as log4js from 'log4js';
export type Uin = string | number;
// 大多数情况下你无需关心这些配置项,因为默认配置就是最常用的,除非你需要一些与默认不同的规则
export interface ConfBot {
log_level?: "trace" | "debug" | "info" | "warn" | "e... | cleanCache(type?: string): Promise<RetCommon>; //type: "image" or "record" or undefined
canSendImage(): RetCommon;
canSendRecord(): RetCommon;
getVersionInfo(): RetCommon; //暂时为返回package.json中的信息
getStatus(): RetStatus;
getLoginInfo(): RetLoginInfo;
once(event: "system" | "request" | "messa... |
getCookies(domain?: string): Promise<RetCommon>;
getCsrfToken(): Promise<RetCommon>; | random_line_split |
client.d.ts | // Project: https://github.com/takayama-lily/oicq
/// <reference types="node" />
import * as events from 'events';
import * as log4js from 'log4js';
export type Uin = string | number;
// 大多数情况下你无需关心这些配置项,因为默认配置就是最常用的,除非你需要一些与默认不同的规则
export interface ConfBot {
log_level?: "trace" | "debug" | "info" | "warn" | "e... | 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 | '''
Copyright (C) 2019-2021, Mo Zhou <cdluminate@gmail.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 required by applicable law or agreed t... |
return highlight(code, PythonLexer(), TerminalFormatter())
def pdist(repres: th.Tensor, metric: str) -> th.Tensor:
'''
Helper: compute pairwise distance matrix.
https://github.com/pytorch/pytorch/issues/48306
'''
assert(len(repres.shape) == 2)
with th.no_grad():
if metric == 'C':
... | raise ValueError('does not know how to deal with such datatype') | conditional_block |
utils.py | '''
Copyright (C) 2019-2021, Mo Zhou <cdluminate@gmail.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 required by applicable law or agreed t... |
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 | '''
Copyright (C) 2019-2021, Mo Zhou <cdluminate@gmail.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 required by applicable law or agreed t... | (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 | '''
Copyright (C) 2019-2021, Mo Zhou <cdluminate@gmail.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 required by applicable law or agreed t... | epoch=7.ckpt
'''.strip().split('\n')]
assert(nsort(x, r'version_(\d+)')[0] == 'version_10')
print(nsort(x, r'.*sion_(\d+)')[0] == 'version_10')
assert(nsort(y, r'epoch=(\d+)')[0] == 'epoch=10.ckpt')
print(nsort(y, r'.*ch=(\d+)')[0] == 'epoch=10.ckpt')
if __name__ == '__main__':
test_nsort(... | epoch=2.ckpt | random_line_split |
tree_based_retrieval.py | import sys
import tensorflow as tf
from utils.param import FLAGS
from utils.xletter import XletterPreprocessor
from utils.layers import xletter_feature_extractor, mask_maxpool
import math
from tensorflow.python.ops import lookup_ops
if FLAGS.use_mstf_ops == 1:
import tensorflow.contrib.microsoft as mstf
def parse_... |
if __name__ == '__main__':
from data_reader import InputPipe
m = CDSSMModel()
pred_pipe = InputPipe(FLAGS.input_validation_data_path + "/bleu_data.txt", FLAGS.eval_batch_size,1,2,"",True)
query,keyword = pred_pipe.get_next()
output = m.search(query)
with tf.Session() as sess:
scope =... | 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 | import sys
import tensorflow as tf
from utils.param import FLAGS
from utils.xletter import XletterPreprocessor
from utils.layers import xletter_feature_extractor, mask_maxpool
import math
from tensorflow.python.ops import lookup_ops
if FLAGS.use_mstf_ops == 1:
import tensorflow.contrib.microsoft as mstf
def parse_... |
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 | import sys
import tensorflow as tf
from utils.param import FLAGS
from utils.xletter import XletterPreprocessor
from utils.layers import xletter_feature_extractor, mask_maxpool
import math
from tensorflow.python.ops import lookup_ops
if FLAGS.use_mstf_ops == 1:
import tensorflow.contrib.microsoft as mstf
def parse_... | (self, inference_res):
if FLAGS.mode == 'predict':
query_vec, search_res, score = inference_res
else:
query_vec, doc_vec, doc_id = inference_res
score = tf.reduce_sum(tf.multiply(query_vec, doc_vec), axis = 1)
return score
def get_optimizer(self):
... | calc_score | identifier_name |
tree_based_retrieval.py | import sys
import tensorflow as tf
from utils.param import FLAGS
from utils.xletter import XletterPreprocessor
from utils.layers import xletter_feature_extractor, mask_maxpool
import math
from tensorflow.python.ops import lookup_ops
if FLAGS.use_mstf_ops == 1:
import tensorflow.contrib.microsoft as mstf
def parse_... | 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 | import glob
import os
import random
import numpy as np
from data_gen import DataSet
from nade import NADE
from keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation, Lambda, add
from keras import backend as K
from keras.models import Model
from keras.callbacks import Callback
import keras.regularizers... |
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 | import glob
import os
import random
import numpy as np
from data_gen import DataSet
from nade import NADE
from keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation, Lambda, add
from keras import backend as K
from keras.models import Model
from keras.callbacks import Callback
import keras.regularizers... | (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 | import glob
import os
import random
import numpy as np
from data_gen import DataSet
from nade import NADE
from keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation, Lambda, add
from keras import backend as K
from keras.models import Model
from keras.callbacks import Callback
import keras.regularizers... |
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 | import glob
import os
import random
import numpy as np
from data_gen import DataSet
from nade import NADE
from keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation, Lambda, add
from keras import backend as K
from keras.models import Model
from keras.callbacks import Callback
import keras.regularizers... | _train(args)
if __name__ == '__main__':
main() | # '--data_seed', type=int, default=1, help='the seed for dataset')
args = parser.parse_args() | random_line_split |
service.go | // Copyright 2019, OpenTelemetry 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 ag... |
}
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 | // Copyright 2019, OpenTelemetry 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 ag... |
// 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 | // Copyright 2019, OpenTelemetry 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 ag... | () 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 | // Copyright 2019, OpenTelemetry 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 ag... |
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,
)... | {
// 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 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data=pd.read_excel("C:\ML&AI\TextClassification\RAW DATA(Main Update)#2 (2019-07-02).xlsx", sheet_name="All",skiprows=5)
#data.columns.tolist()
#count... | #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 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data=pd.read_excel("C:\ML&AI\TextClassification\RAW DATA(Main Update)#2 (2019-07-02).xlsx", sheet_name="All",skiprows=5)
#data.columns.tolist()
#count... |
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 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data=pd.read_excel("C:\ML&AI\TextClassification\RAW DATA(Main Update)#2 (2019-07-02).xlsx", sheet_name="All",skiprows=5)
#data.columns.tolist()
#count... | (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 | import logging
from collections import defaultdict
from collections.abc import Iterator
from importlib import import_module
from types import ModuleType
from typing import TYPE_CHECKING, Any, Optional
from rotkehlchen.db.constants import BINANCE_MARKETS_KEY, KRAKEN_ACCOUNT_TYPE_KEY
from rotkehlchen.errors.misc import ... |
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 | import logging
from collections import defaultdict
from collections.abc import Iterator
from importlib import import_module
from types import ModuleType
from typing import TYPE_CHECKING, Any, Optional
from rotkehlchen.db.constants import BINANCE_MARKETS_KEY, KRAKEN_ACCOUNT_TYPE_KEY
from rotkehlchen.errors.misc import ... |
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 | import logging
from collections import defaultdict
from collections.abc import Iterator
from importlib import import_module
from types import ModuleType
from typing import TYPE_CHECKING, Any, Optional
from rotkehlchen.db.constants import BINANCE_MARKETS_KEY, KRAKEN_ACCOUNT_TYPE_KEY
from rotkehlchen.errors.misc import ... | (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 | import logging
from collections import defaultdict
from collections.abc import Iterator
from importlib import import_module
from types import ModuleType
from typing import TYPE_CHECKING, Any, Optional
from rotkehlchen.db.constants import BINANCE_MARKETS_KEY, KRAKEN_ACCOUNT_TYPE_KEY
from rotkehlchen.errors.misc import ... | 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 | use crate::{cpu, mm, segment, PAddr, VAddr};
use core::{arch::asm, marker::PhantomData, time::Duration};
use hal_core::interrupt::Control;
use hal_core::interrupt::{ctx, Handlers};
use mycelium_util::{
bits, fmt,
sync::{spin, InitOnce},
};
pub mod apic;
pub mod idt;
pub mod pic;
use self::apic::{IoApic, Local... | () {
assert_eq!(size_of::<Registers>(), 40);
}
}
| registers_is_correct_size | identifier_name |
interrupt.rs | use crate::{cpu, mm, segment, PAddr, VAddr};
use core::{arch::asm, marker::PhantomData, time::Duration};
use hal_core::interrupt::Control;
use hal_core::interrupt::{ctx, Handlers};
use mycelium_util::{
bits, fmt,
sync::{spin, InitOnce},
};
pub mod apic;
pub mod idt;
pub mod pic;
use self::apic::{IoApic, Local... |
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 | use crate::{cpu, mm, segment, PAddr, VAddr};
use core::{arch::asm, marker::PhantomData, time::Duration};
use hal_core::interrupt::Control;
use hal_core::interrupt::{ctx, Handlers};
use mycelium_util::{
bits, fmt,
sync::{spin, InitOnce},
};
pub mod apic;
pub mod idt;
pub mod pic;
use self::apic::{IoApic, Local... | mut registers: Registers,
code: u64,
) {
unsafe {
// Safety: who cares!
crate::vga::writer().force_unlock();
if let Some(com1) = crate::serial::com1() {
com1.force_unlock();
}
}
... | code,
});
}
extern "x86-interrupt" fn gpf_isr<H: Handlers<Registers>>( | random_line_split |
node.rs | use petgraph;
use petgraph::graph::NodeIndex; |
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 | use petgraph;
use petgraph::graph::NodeIndex;
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;
... | (&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 | use petgraph;
use petgraph::graph::NodeIndex;
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;
... | se {
false
}
}
pub fn is_internal(&self) -> bool {
if let Type::Internal(..) = *self.inner {
true
} else {
false
}
}
/// A node is considered to be an output node if changes to its state are visible outside of
/// its domain.
... | true
} el | conditional_block |
node.rs | use petgraph;
use petgraph::graph::NodeIndex;
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;
... |
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 | import {Component, OnInit} from '@angular/core';
import {ContactsService} from '@rhythmsoftware/rolodex-angular-sdk/api/contacts.service';
import {CertificationsService} from '../../services/certifications/certifications.service';
import {AbstractControl, FormArray, FormBuilder, FormGroup, Validators} from '@angular/fo... | 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 | import {Component, OnInit} from '@angular/core';
import {ContactsService} from '@rhythmsoftware/rolodex-angular-sdk/api/contacts.service';
import {CertificationsService} from '../../services/certifications/certifications.service';
import {AbstractControl, FormArray, FormBuilder, FormGroup, Validators} from '@angular/fo... | () {
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 | import {Component, OnInit} from '@angular/core';
import {ContactsService} from '@rhythmsoftware/rolodex-angular-sdk/api/contacts.service';
import {CertificationsService} from '../../services/certifications/certifications.service';
import {AbstractControl, FormArray, FormBuilder, FormGroup, Validators} from '@angular/fo... |
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 | /*
Package deployment provides methods for managing application deployment and release files.
A deployment resides on the server running PullDeploy in daemon mode. It has the following
directory structure:
/BASEDIR/APPNAME/artifact
/BASEDIR/APPNAME/current (a symlink)
/BASEDIR/APPNAME/release
Artifacts retrieved... |
/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 | /*
Package deployment provides methods for managing application deployment and release files.
A deployment resides on the server running PullDeploy in daemon mode. It has the following
directory structure:
/BASEDIR/APPNAME/artifact
/BASEDIR/APPNAME/current (a symlink)
/BASEDIR/APPNAME/release
Artifacts retrieved... | 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 | /*
Package deployment provides methods for managing application deployment and release files.
A deployment resides on the server running PullDeploy in daemon mode. It has the following
directory structure:
/BASEDIR/APPNAME/artifact
/BASEDIR/APPNAME/current (a symlink)
/BASEDIR/APPNAME/release
Artifacts retrieved... |
// PostDeploy executes the configured PostDeploy command.
func (d *Deployment) PostDeploy(version string) (string, error) {
if os.Geteuid() == 0 && d.cfg.Insecure {
return "", fmt.Errorf(
"Refusing to execute post-deploy command from insecure %q configuration as root",
d.appName)
}
if d.cfg.Scripts["postde... | {
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 | /*
Package deployment provides methods for managing application deployment and release files.
A deployment resides on the server running PullDeploy in daemon mode. It has the following
directory structure:
/BASEDIR/APPNAME/artifact
/BASEDIR/APPNAME/current (a symlink)
/BASEDIR/APPNAME/release
Artifacts retrieved... | (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 | use std::collections::HashMap;
use std::future::Future;
use std::io::{Read, Write};
use std::net::SocketAddr;
use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::task::{Context, Waker};
use std::thread::spawn;
use log;
use mio::{Events, Int... | spatcherAction::Dispose => self.close(id),
}
}
fn on_tcp_stream(
&mut self,
event: &Event,
stream: &mut TcpStream,
listener: &mut Box<dyn TcpStreamListener>,
) {
// 読み込み可能イベント
if event.is_readable() {
let behaviour = listener.on_ready_to_read(stream);
self.action(event.tok... | est).unwrap();
}
Di | conditional_block |
mod.rs | use std::collections::HashMap;
use std::future::Future;
use std::io::{Read, Write};
use std::net::SocketAddr;
use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::task::{Context, Waker};
use std::thread::spawn;
use log;
use mio::{Events, Int... | f self.sockets.get(&id).is_none() {
self.next = if self.next + 1 == max { 0 } else { self.next + 1 };
return Ok(id);
}
}
unreachable!()
}
/// 指定された ID のソケットを新規追加または更新します。
pub fn set(&mut self, id: SocketId, socket: Socket) {
self.sockets.insert(id, Arc::new(Mutex::new(socket)));... | i | identifier_name |
mod.rs | use std::collections::HashMap;
use std::future::Future;
use std::io::{Read, Write};
use std::net::SocketAddr;
use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::task::{Context, Waker};
use std::thread::spawn;
use log;
use mio::{Events, Int... | 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 | use std::collections::HashMap;
use std::future::Future;
use std::io::{Read, Write};
use std::net::SocketAddr;
use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::task::{Context, Waker};
use std::thread::spawn;
use log;
use mio::{Events, Int... |
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 | # -*- coding: utf-8 -*-
"""code_draft.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1SFG3__AoM7dvKI06qiu76tW-mtbZDsxn
"""
import PIL
from PIL import Image
import numpy as np
import sys
from matplotlib import image
from matplotlib import pyplot ... |
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 | # -*- coding: utf-8 -*-
"""code_draft.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1SFG3__AoM7dvKI06qiu76tW-mtbZDsxn
"""
import PIL
from PIL import Image
import numpy as np
import sys
from matplotlib import image
from matplotlib import pyplot ... |
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 | # -*- coding: utf-8 -*-
"""code_draft.ipynb
Automatically generated by Colaboratory.
| """
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 | # -*- coding: utf-8 -*-
"""code_draft.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1SFG3__AoM7dvKI06qiu76tW-mtbZDsxn
"""
import PIL
from PIL import Image
import numpy as np
import sys
from matplotlib import image
from matplotlib import pyplot ... | (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 | // Copyright 2016 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... | (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 | // Copyright 2016 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... |
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 | // Copyright 2016 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 (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 | // Copyright 2016 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... | 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 |
# coding: utf-8
# # Import library
# run two cells below first
# In[2]:
import numpy as np
import pandas as pd
from collections import defaultdict
import time
from datetime import datetime
import sys
import math
# In[2]:
if 'holidays' not in sys.modules:
get_ipython().system('pip install holidays')
import ... |
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 |
# coding: utf-8
# # Import library
# run two cells below first
# In[2]:
import numpy as np
import pandas as pd
from collections import defaultdict
import time
from datetime import datetime
import sys
import math
# In[2]:
if 'holidays' not in sys.modules:
get_ipython().system('pip install holidays')
import ... | (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 |
# coding: utf-8
# # Import library
# run two cells below first
# In[2]:
import numpy as np
import pandas as pd
from collections import defaultdict
import time
from datetime import datetime
import sys
import math
# In[2]:
if 'holidays' not in sys.modules:
get_ipython().system('pip install holidays')
import ... |
# 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 | # coding: utf-8
# # Import library
# run two cells below first
# In[2]:
import numpy as np
import pandas as pd
from collections import defaultdict
import time
from datetime import datetime
import sys
import math
# In[2]:
if 'holidays' not in sys.modules:
get_ipython().system('pip install holidays')
import h... | 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 | //! This crate is part of [Sophia],
//! an [RDF] and [Linked Data] toolkit in Rust.
//!
//! Terms are the building blocks of an [RDF] graph.
//! There are four types of terms: IRIs, blank nodes (BNode for short),
//! literals and variables.
//!
//! NB: variable only exist in [generalized RDF].
//!
//! This module defi... | 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 | //! This crate is part of [Sophia],
//! an [RDF] and [Linked Data] toolkit in Rust.
//!
//! Terms are the building blocks of an [RDF] graph.
//! There are four types of terms: IRIs, blank nodes (BNode for short),
//! literals and variables.
//!
//! NB: variable only exist in [generalized RDF].
//!
//! This module defi... | (&self, other: &TE) -> Option<std::cmp::Ordering> {
Some(term_cmp(self, other))
}
}
impl<TD> Hash for Term<TD>
where
TD: TermData,
{
fn hash<H: Hasher>(&self, state: &mut H) {
term_hash(self, state)
}
}
impl<TD> From<Iri<TD>> for Term<TD>
where
TD: TermData,
{
fn from(iri: Iri<... | partial_cmp | identifier_name |
custom_insts.rs | //! SPIR-V (extended) instructions specific to `rustc_codegen_spirv`, produced
//! during the original codegen of a crate, and consumed by the `linker`.
use lazy_static::lazy_static;
use rspirv::dr::{Instruction, Operand};
use rspirv::spirv::Op;
use smallvec::SmallVec;
/// Prefix for `CUSTOM_EXT_INST_SET` (`OpExtInst... | /// 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 | //! SPIR-V (extended) instructions specific to `rustc_codegen_spirv`, produced
//! during the original codegen of a crate, and consumed by the `linker`.
use lazy_static::lazy_static;
use rspirv::dr::{Instruction, Operand};
use rspirv::spirv::Op;
use smallvec::SmallVec;
/// Prefix for `CUSTOM_EXT_INST_SET` (`OpExtInst... |
/// Returns `true` iff this `CustomOp` is a custom terminator instruction,
/// i.e. semantic and must precede an `OpUnreachable` standard terminator,
/// with at most debuginfo instructions (standard or custom), between the two.
pub fn is_terminator(self) -> bool {
match self {
Cus... | {
match self {
CustomOp::SetDebugSrcLoc
| CustomOp::ClearDebugSrcLoc
| CustomOp::PushInlinedCallFrame
| CustomOp::PopInlinedCallFrame => true,
CustomOp::Abort => false,
}
} | identifier_body |
custom_insts.rs | //! SPIR-V (extended) instructions specific to `rustc_codegen_spirv`, produced
//! during the original codegen of a crate, and consumed by the `linker`.
use lazy_static::lazy_static;
use rspirv::dr::{Instruction, Operand};
use rspirv::spirv::Op;
use smallvec::SmallVec;
/// Prefix for `CUSTOM_EXT_INST_SET` (`OpExtInst... | (self) -> bool {
match self {
CustomOp::SetDebugSrcLoc
| CustomOp::ClearDebugSrcLoc
| CustomOp::PushInlinedCallFrame
| CustomOp::PopInlinedCallFrame => true,
CustomOp::Abort => false,
}
}
/// Returns `true` iff this `CustomOp` is a cu... | is_debuginfo | identifier_name |
mod.rs | use std::collections::{HashMap, HashSet};
#[cfg(feature = "egl")]
use smithay::backend::renderer::ImportEgl;
use smithay::{
backend::{
allocator::{
dmabuf::{AnyError, Dmabuf, DmabufAllocator},
gbm::{GbmAllocator, GbmBufferFlags},
vulkan::{ImageUsageFlags, VulkanAllocator... | () {
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 | use std::collections::{HashMap, HashSet};
#[cfg(feature = "egl")]
use smithay::backend::renderer::ImportEgl;
use smithay::{
backend::{
allocator::{
dmabuf::{AnyError, Dmabuf, DmabufAllocator},
gbm::{GbmAllocator, GbmBufferFlags},
vulkan::{ImageUsageFlags, VulkanAllocator... | #[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 | use std::collections::{HashMap, HashSet};
#[cfg(feature = "egl")]
use smithay::backend::renderer::ImportEgl;
use smithay::{
backend::{
allocator::{
dmabuf::{AnyError, Dmabuf, DmabufAllocator},
gbm::{GbmAllocator, GbmBufferFlags},
vulkan::{ImageUsageFlags, VulkanAllocator... |
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 | //! A batteries included runtime for applications using Tokio.
//!
//! Applications using Tokio require some runtime support in order to work:
//!
//! * A [reactor] to drive I/O resources.
//! * An [executor] to execute tasks that use these I/O resources.
//! * A [timer] for scheduling work to run after a set period of... |
}
}
| {
let shutdown = Shutdown::shutdown_now(inner);
let _ = shutdown.wait();
} | conditional_block |
mod.rs | //! A batteries included runtime for applications using Tokio.
//!
//! Applications using Tokio require some runtime support in order to work:
//!
//! * A [reactor] to drive I/O resources.
//! * An [executor] to execute tasks that use these I/O resources.
//! * A [timer] for scheduling work to run after a set period of... |
/// Signals the runtime to shutdown immediately.
///
/// Returns a future that completes once the shutdown operation has
/// completed.
///
/// This function will forcibly shutdown the runtime, causing any
/// in-progress work to become canceled. The shutdown steps are:
///
/// * D... | {
let inner = self.inner.take().unwrap();
let inner = inner.pool.shutdown_on_idle();
Shutdown { inner }
} | identifier_body |
mod.rs | //! A batteries included runtime for applications using Tokio.
//!
//! Applications using Tokio require some runtime support in order to work:
//!
//! * A [reactor] to drive I/O resources.
//! * An [executor] to execute tasks that use these I/O resources.
//! * A [timer] for scheduling work to run after a set period of... | F: Send + 'static + Future<Item = R, Error = E>,
R: Send + 'static,
E: Send + 'static,
{
let (tx, rx) = futures::sync::oneshot::channel();
self.spawn(future.then(move |r| tx.send(r).map_err(|_| unreachable!())));
rx.wait().unwrap()
}
/// Run a future to compl... | random_line_split | |
mod.rs | //! A batteries included runtime for applications using Tokio.
//!
//! Applications using Tokio require some runtime support in order to work:
//!
//! * A [reactor] to drive I/O resources.
//! * An [executor] to execute tasks that use these I/O resources.
//! * A [timer] for scheduling work to run after a set period of... | () -> 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 | """
============================
The Component Manager System
============================
The :mod:`vivarium` component manager system is responsible for maintaining a
reference to all of the managers and components in a simulation, providing an
interface for adding additional components or managers, and applying def... |
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 | """
============================
The Component Manager System
============================
The :mod:`vivarium` component manager system is responsible for maintaining a
reference to all of the managers and components in a simulation, providing an
interface for adding additional components or managers, and applying def... | (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 | """
============================
The Component Manager System
============================
The :mod:`vivarium` component manager system is responsible for maintaining a
reference to all of the managers and components in a simulation, providing an
interface for adding additional components or managers, and applying def... |
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 | """
============================
The Component Manager System
============================
The :mod:`vivarium` component manager system is responsible for maintaining a
reference to all of the managers and components in a simulation, providing an
interface for adding additional components or managers, and applying def... |
"""
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 | #!/usr/bin/env python3
# coding: utf-8
"""Genome digestion
Functions used to write auxiliary instagraal compatible
sparse matrices.
"""
from Bio import SeqIO, SeqUtils
from Bio.Seq import Seq
from Bio.Restriction import RestrictionBatch, Analysis
import os, sys, csv
import re
import collections
import copy
import ma... | (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 | #!/usr/bin/env python3
# coding: utf-8
"""Genome digestion
Functions used to write auxiliary instagraal compatible
sparse matrices.
"""
from Bio import SeqIO, SeqUtils
from Bio.Seq import Seq
from Bio.Restriction import RestrictionBatch, Analysis
import os, sys, csv
import re
import collections
import copy
import ma... |
# Iterates on the two list to build all the possible HiC ligation sites.
for give_site in give_list:
for accept_site in accept_list:
# Replace "N" by "." for regex searching of the sites
ligation_list.append((give_site + accept_site).replace("N", "."))
ligation_list... | 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 | #!/usr/bin/env python3
# coding: utf-8
"""Genome digestion
Functions used to write auxiliary instagraal compatible
sparse matrices.
"""
from Bio import SeqIO, SeqUtils
from Bio.Seq import Seq
from Bio.Restriction import RestrictionBatch, Analysis
import os, sys, csv
import re
import collections
import copy
import ma... |
def frag_len(
frags_file_name=DEFAULT_FRAGMENTS_LIST_FILE_NAME,
output_dir=None,
plot=False,
fig_path=None,
):
"""
logs summary statistics of fragment length distribution based on an
input fragment file. Can optionally show a histogram instead
of text summary.
Parameters
-----... | """
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 | #!/usr/bin/env python3
# coding: utf-8
"""Genome digestion
Functions used to write auxiliary instagraal compatible
sparse matrices.
"""
from Bio import SeqIO, SeqUtils
from Bio.Seq import Seq
from Bio.Restriction import RestrictionBatch, Analysis
import os, sys, csv
import re
import collections
import copy
import ma... | 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 | // Copyright 2018 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | 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 | // Copyright 2018 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
/// 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 | // Copyright 2018 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | pub fn remove_peer_with_pubkey(&mut self, key: &PublicKey) {
let mut fork = self.fork();
{
let mut schema = Schema::new(&mut fork);
let mut peers = schema.peers_cache_mut();
peers.remove(key);
}
self.merge(fork.into_patch())
.expect("... | 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 | // Copyright 2018 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | (service: &dyn Service, fork: &mut Fork) {
fork.checkpoint();
match panic::catch_unwind(panic::AssertUnwindSafe(|| service.before_commit(fork))) {
Ok(..) => fork.commit(),
Err(err) => {
if err.is::<Error>() {
// Continue panic unwind if the reason is StorageError.
... | before_commit | identifier_name |
setup.py | """
To build with coverage of Cython files
export SM_CYTHON_COVERAGE=1
python -m pip install -e .
pytest --cov=statsmodels statsmodels
coverage html
"""
from setuptools import Command, Extension, find_packages, setup
from setuptools.dist import Distribution
from collections import defaultdict
import fnmatch
import ins... | (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 | """
To build with coverage of Cython files
export SM_CYTHON_COVERAGE=1
python -m pip install -e .
pytest --cov=statsmodels statsmodels
coverage html
"""
from setuptools import Command, Extension, find_packages, setup
from setuptools.dist import Distribution
from collections import defaultdict
import fnmatch
import ins... | long_description=LONG_DESCRIPTION,
classifiers=CLASSIFIERS,
platforms="any",
cmdclass=cmdclass,
packages=find_packages(),
package_data=package_data,
distclass=BinaryDistribution,
include_package_data=False, # True will install all files in repo
install_requires=INSTALL_REQUIRES,
... | project_urls=PROJECT_URLS, | random_line_split |
setup.py | """
To build with coverage of Cython files
export SM_CYTHON_COVERAGE=1
python -m pip install -e .
pytest --cov=statsmodels statsmodels
coverage html
"""
from setuptools import Command, Extension, find_packages, setup
from setuptools.dist import Distribution
from collections import defaultdict
import fnmatch
import ins... |
setup(
name=DISTNAME,
maintainer=MAINTAINER,
ext_modules=extensions,
maintainer_email=MAINTAINER_EMAIL,
description=DESCRIPTION,
license=LICENSE,
url=URL,
download_url=DOWNLOAD_URL,
project_urls=PROJECT_URLS,
long_description=LONG_DESCRIPTION,
classifiers=CLASSIFIERS,
... | return False | identifier_body |
setup.py | """
To build with coverage of Cython files
export SM_CYTHON_COVERAGE=1
python -m pip install -e .
pytest --cov=statsmodels statsmodels
coverage html
"""
from setuptools import Command, Extension, find_packages, setup
from setuptools.dist import Distribution
from collections import defaultdict
import fnmatch
import ins... |
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 | // Copyright 2018 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package cpu measures CPU usage.
package cpu
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"sync"
"time"
"golang.org/x/sys/unix"
"chro... | (ctx context.Context) string {
// 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
}... | getThermalThrottlingJob | identifier_name |
cpu.go | // Copyright 2018 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package cpu measures CPU usage.
package cpu
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"sync"
"time"
"golang.org/x/sys/unix"
"chro... | // job used by the current platform.
func getThermalThrottlingJob(ctx context.Context) string {
// 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", ... | random_line_split | |
cpu.go | // Copyright 2018 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package cpu measures CPU usage.
package cpu
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"sync"
"time"
"golang.org/x/sys/unix"
"chro... |
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 | // Copyright 2018 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package cpu measures CPU usage.
package cpu
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"sync"
"time"
"golang.org/x/sys/unix"
"chro... | {
// 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 | #!/usr/bin/env python
import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell, Server
from redis import Redis
from rq import Connection, Queue, Worker
from sqlalchemy.sql import exists
from sqlalchemy.exc import IntegrityError
from sqlalchemy import desc
... |
@manager.command
def updateLog(plantSKU, waterDate, dayNum):
water = WaterLog(
plant = plantSKU,
water = 1,
date = waterDate
)
f = randrange(0,2,1)
if f == 1:
water.feed = 1
water.notes = "General purpose fertilizer; half-strength"
else:
... | 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 | #!/usr/bin/env python
import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell, Server
from redis import Redis
from rq import Connection, Queue, Worker
from sqlalchemy.sql import exists
from sqlalchemy.exc import IntegrityError
from sqlalchemy import desc
... |
@manager.command
def setup_dev():
"""Runs the set-up needed for local development."""
setup_general()
@manager.command
def setup_prod():
"""Runs the set-up needed for production."""
setup_general()
def setup_general():
"""Runs the set-up needed for both local development and production.
... | simDay += timedelta(days=1)
dayNum += 1 | random_line_split |
manage.py | #!/usr/bin/env python
import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell, Server
from redis import Redis
from rq import Connection, Queue, Worker
from sqlalchemy.sql import exists
from sqlalchemy.exc import IntegrityError
from sqlalchemy import desc
... |
@manager.command
def run_worker():
"""Initializes a slim rq task queue."""
listen = ['default']
conn = Redis(host=app.config['RQ_DEFAULT_HOST'],
port=app.config['RQ_DEFAULT_PORT'],
db=0,
password=app.config['RQ_DEFAULT_PASSWORD'])
with Connection(co... | 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 | #!/usr/bin/env python
import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell, Server
from redis import Redis
from rq import Connection, Queue, Worker
from sqlalchemy.sql import exists
from sqlalchemy.exc import IntegrityError
from sqlalchemy import desc
... | ( 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 | use dotenv;
use fastspring_keygen_integration::fastspring;
use fastspring_keygen_integration::keygen;
use fastspring_keygen_integration::keygen::{generate_licenses, suspend_license};
use fastspring_keygen_integration::util;
use fastspring_keygen_integration::patreon;
use http::header::CONTENT_TYPE;
use lambda_http::{la... | 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 | use dotenv;
use fastspring_keygen_integration::fastspring;
use fastspring_keygen_integration::keygen;
use fastspring_keygen_integration::keygen::{generate_licenses, suspend_license};
use fastspring_keygen_integration::util;
use fastspring_keygen_integration::patreon;
use http::header::CONTENT_TYPE;
use lambda_http::{la... |
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 | use dotenv;
use fastspring_keygen_integration::fastspring;
use fastspring_keygen_integration::keygen;
use fastspring_keygen_integration::keygen::{generate_licenses, suspend_license};
use fastspring_keygen_integration::util;
use fastspring_keygen_integration::patreon;
use http::header::CONTENT_TYPE;
use lambda_http::{la... | (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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.