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
gen_mike_input_rf_linux.py
import connection as con_params from db_adapter.base import get_Pool, destroy_Pool from db_adapter.constants import CURW_SIM_DATABASE, CURW_SIM_PASSWORD, CURW_SIM_USERNAME, CURW_SIM_PORT, CURW_SIM_HOST from db_adapter.curw_sim.timeseries import Timeseries from db_adapter.constants import COMMON_DATE_TIME_FORMAT ROOT...
(file_name, data): with open(file_name, 'a+') as f: f.write('\n'.join(data)) def append_file_to_file(file_name, file_content): with open(file_name, 'a+') as f: f.write('\n') f.write(file_content) def makedir_if_not_exist_given_filepath(filename): if not os.path.exists(os.path.dir...
append_to_file
identifier_name
debug.rs
at_core::{HasSchema, SQLValueType, TxReport}; /// Represents a *datom* (assertion) in the store. #[derive(Clone, Debug, Eq, Hash, Ord, PartialOrd, PartialEq)] pub struct Datom { // TODO: generalize this. pub e: EntidOrIdent, pub a: EntidOrIdent, pub v: edn::Value, pub tx: i64, pub added: Option...
; let typed_value = TypedValue::from_sql_value_pair(v, value_type_tag)?.map_ident(borrowed_schema); let (value, _) = typed_value.to_edn_value_pair(); let tx: i64 = row.get(4)?; let added: bool = row.get(5)?; Ok(Datom { e: Ent...
{ ValueType::Long.value_type_tag() }
conditional_block
debug.rs
)) } else { self } } } /// Convert a numeric entid to an ident `Entid` if possible, otherwise a numeric `Entid`. pub fn to_entid(schema: &Schema, entid: i64) -> EntidOrIdent { schema .get_ident(entid) .map_or(EntidOrIdent::Entid(entid), |ident| { EntidOrI...
transact_simple_terms
identifier_name
debug.rs
<bool>, } /// Represents a set of datoms (assertions) in the store. /// /// To make comparision easier, we deterministically order. The ordering is the ascending tuple /// ordering determined by `(e, a, (value_type_tag, v), tx)`, where `value_type_tag` is an internal /// value that is not exposed but is deterministic...
sql: &str,
random_line_split
sub_files.py
Rrbs.as' % encValData], ('bed', 'enhancerAssay'): ['-type=bed9+1', chromInfo, '-as=%s/as/enhancerAssay.as' % encValData], ('bigBed', 'enhancerAssay'): ['-type=bigBed9+1', chromInfo, '-as=%s/as/enhancerAssay.as' % encValData], ('bed', 'modPepMap'): ['-type=bed9+7', chromInfo, '-as=%s/as/modPepMap.as' % encValData]...
main()
conditional_block
sub_files.py
(): import argparse parser = argparse.ArgumentParser( description=__doc__, epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('infile', help='CSV file metadata to POST', nargs='?', type=argparse.FileType('rU'), default=sys.stdin) parser.add_argument('--outfile', help='CSV...
get_args
identifier_name
sub_files.py
1024*1024), b''): md5sum.update(chunk) return md5sum.hexdigest() # This does not depend on hashlib # if 'md5_command' not in globals(): # global md5_command # if subprocess.check_output('which md5', shell=True): # md5_command = 'md5 -q' # elif subprocess.check_output('which md5sum', shell=True): # md...
def input_csv(fh): csv_args = CSV_ARGS input_fieldnames = csv.reader(fh, **csv_args).next() return csv.DictReader(fh, fieldnames=input_fieldnames, **csv_args) def output_csv(fh,fieldnames): csv_args = CSV_ARGS additional_fields = ['accession','aws_return'] output_fieldnames = [fn for fn in fieldnames if fn] + ...
test_URI = "ENCBS000AAA" url = urlparse.urljoin(server,test_URI) r = requests.get(url, auth=keypair, headers=GET_HEADERS) try: r.raise_for_status() except: logger.debug('test_encode_keys got response %s' %(r.text)) return False else: return True
identifier_body
sub_files.py
Methyl'): ['-type=bigBed9+2', chromInfo, '-as=%s/as/bedMethyl.as' % encValData], ('bed', 'broadPeak'): ['-type=bed6+3', chromInfo, '-as=%s/as/broadPeak.as' % encValData], ('bigBed', 'broadPeak'): ['-type=bigBed6+3', chromInfo, '-as=%s/as/broadPeak.as' % encValData], ('bed', 'gappedPeak'): ['-type=bed12+3', chromI...
try: json_payload.update({key:json.loads('"%s"' %(value))}) except: logger.warning('Could not convert field %s value %s to JSON' %(n,key,value))
random_line_split
plugin.go
p.ReporterClient != nil { return p.killGrpcProcess() } if isProcessRunning(p) { defer p.connection.Close() p.killTimer = time.NewTimer(config.PluginKillTimeout()) err := conn.SendProcessKillMessage(p.connection) if err != nil { logger.Warningf(true, "Error while killing plugin %s : %s ", p.descriptor.Na...
} func startPluginsForExecution(m *manifest.Manifest) (Handler, []string) { var warnings []string handler := &GaugePlugins{} envProperties := make(map[string]string) for _, pluginID := range m.Plugins { pd, err := GetPluginDescriptor(pluginID, "") if err != nil { warnings = append(warnings, fmt.Sprintf("Un...
return false
random_line_split
plugin.go
port), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(1024*1024*1024), grpc.MaxCallRecvMsgSize(1024*1024*1024)), grpc.WithBlock()) if err != nil { return nil, err } plugin := &plugin{ pluginCmd: cmd, descriptor: pd, gRPCConn: gRPCConn, ...
{ if p.gRPCConn != nil { return p.invokeService(message) } messageID := common.GetUniqueID() message.MessageId = messageID messageBytes, err := proto.Marshal(message) if err != nil { return err } err = conn.Write(p.connection, messageBytes) if err != nil { return fmt.Errorf("[Warning] Failed to send mess...
identifier_body
plugin.go
: &sync.Mutex{}, } if pd.hasScope(docScope) { plugin.DocumenterClient = gauge_messages.NewDocumenterClient(gRPCConn) } else { plugin.ReporterClient = gauge_messages.NewReporterClient(gRPCConn) } logger.Debugf(true, "Successfully made the connection with plugin with port: %s", port) return plugin, nil } ...
{ infos = append(infos, p) }
conditional_block
plugin.go
p.ReporterClient != nil { return p.killGrpcProcess() } if isProcessRunning(p) { defer p.connection.Close() p.killTimer = time.NewTimer(config.PluginKillTimeout()) err := conn.SendProcessKillMessage(p.connection) if err != nil { logger.Warningf(true, "Error while killing plugin %s : %s ", p.descriptor.Na...
(m *manifest.Manifest) (Handler, []string) { var warnings []string handler := &GaugePlugins{} envProperties := make(map[string]string) for _, pluginID := range m.Plugins { pd, err := GetPluginDescriptor(pluginID, "") if err != nil { warnings = append(warnings, fmt.Sprintf("Unable to start plugin %s. %s. To ...
startPluginsForExecution
identifier_name
hkdf.rs
// =8160 /// pub struct Test<'a> { ikm: &'a [u8], salt: &'a [u8], info: &'a [u8], okm: &'a [u8], } /// data taken from sample code in Readme of crates.io page pub fn basic_test_hkdf<C: CryptoProvider>(_: PhantomData<C>) { let ikm = hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); let sal...
34007208d5b887185865 "), }, Test { // Test Case 2 ikm: &hex!(" 000102030405060708090a0b0c0d0e0f 101112131415161718191a1b1c1d1e1f 202122232425262728292a2b2c2d2e2f ...
random_line_split
hkdf.rs
<C: CryptoProvider>(#[case] testcase: CryptoProviderTestCase<C>) {} const MAX_SHA256_LENGTH: usize = 255 * (256 / 8); // =8160 /// pub struct Test<'a> { ikm: &'a [u8], salt: &'a [u8], info: &'a [u8], okm: &'a [u8], } /// data taken from sample code in Readme of crates.io page pub fn basic_test_hkdf<C...
hkdf_test_cases
identifier_name
hkdf.rs
hex!(" b0b1b2b3b4b5b6b7b8b9babbbcbdbebf c0c1c2c3c4c5c6c7c8c9cacbcccdcecf d0d1d2d3d4d5d6d7d8d9dadbdcdddedf e0e1e2e3e4e5e6e7e8e9eaebecedeeef f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff "), okm: &hex!("...
{ panic!( "\n\ Failed test {tc_id}: {desc}\n\ ikm:\t{ikm:?}\n\ salt:\t{salt:?}\n\ info:\t{info:?}\n\ okm:\t{okm:?}\n" ); }
conditional_block
msg.rs
run, 10 => MinType, i => UserDefined(i), } } } #[derive(Clone, Copy, Debug)] enum Flags { /// It is request message. Request, /// Multipart message, terminated by NLMSG_DONE Multi, /// Reply with ack, with zero or error code Ack, /// Echo this request ...
(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Dump.into(); self } } /* http://linux.die.net/include/linux/netlink.h /* Flags values */ #define NLM_F_REQUEST 1 /* It is request message. */ #define NLM_F_MULTI 2 /* Multipart message, terminated by NLMSG_DONE */ #define NL...
dump
identifier_name
msg.rs
run, 10 => MinType, i => UserDefined(i), } } } #[derive(Clone, Copy, Debug)] enum Flags { /// It is request message. Request, /// Multipart message, terminated by NLMSG_DONE Multi, /// Reply with ack, with zero or error code Ack, /// Echo this request ...
nl_type: u16, flags: u16, seq: u32, pid: u32, } impl fmt::Debug for NlMsgHeader { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "<NlMsgHeader len={} {:?} flags=[ ", self.msg_length, MsgType::from(self.nl_typ...
random_line_split
msg.rs
run, 10 => MinType, i => UserDefined(i), } } } #[derive(Clone, Copy, Debug)] enum Flags { /// It is request message. Request, /// Multipart message, terminated by NLMSG_DONE Multi, /// Reply with ack, with zero or error code Ack, /// Echo this request ...
pub fn done() -> NlMsgHeader { NlMsgHeader { msg_length: nlmsg_header_length() as u32, nl_type: MsgType::Done.into(), flags: Flags::Multi.into(), seq: 0, pid: 0, } } pub fn error() -> NlMsgHeader { NlMsgHeader { ...
{ NlMsgHeader { msg_length: nlmsg_header_length() as u32, nl_type: MsgType::Request.into(), flags: Flags::Request.into(), seq: 0, pid: 0, } }
identifier_body
model_infer.py
sigmoid_loss = FLAGS.sigmoid identity_dim = FLAGS.identity_dim class SupervisedGraphsage(object): """Implementation
self.activations = [] self.inputs = None self.outputs = None self.loss = 0 self.accuracy = 0 self.optimizer = None self.opt_op = None # === set aggregator === # 增加了两个cross, cross geniepath if aggregator_type == 'cross': self....
of supervised GraphSAGE.""" def __init__(self, **kwargs): # === from model.py === allowed_kwargs = {'name', 'logging', 'model_size'} for kwarg in kwargs.keys(): assert kwarg in allowed_kwargs, 'Invalid keyword argument: ' + kwarg name = kwargs.get('name') if not...
identifier_body
model_infer.py
.learning_rate) self.build() self.var_list = tf.trainable_variables() self.saver = tf.train.Saver(var_list=self.var_list) self.sess = tf.Session(config=sess_config) self.sess.run(tf.global_variables_initializer()) self.load(self.sess) def construct_placeholders(s...
# saver = tf.train.Saver(var_list=self.var_list)
random_line_split
model_infer.py
# self.support_size = placeholders['support_size'] # self.features = placeholders['features'] sampled_weight = [self.placeholders['sampled_weight_0'], self.placeholders['sampled_weight_1'], self.placeholders['sampled_weight_2']] sampled_colu...
elf, feed_dict): preds = self.sess.
conditional_block
model_infer.py
sigmoid_loss = FLAGS.sigmoid identity_dim = FLAGS.identity_dim class SupervisedGraphsage(object): """Implementation of supervised GraphSAGE.""" def __init__(self, **kwargs): # === from model.py === allowed_kwargs = {'name', 'logging', 'model_size'} for kwarg in kwargs.keys(): ...
atch_size=None, aggregators=None, name='aggregate', concat=False, model_size="small"): if batch_size is None: batch_size = self.batch_size # length: number of layers + 1 # hidden = [tf.nn.embedding_lookup(input_features, node_samples) for node_samples in samples] ...
_sizes, b
identifier_name
plot2DlimitsAll.py
2HDM}" if model=="BARY": txt1 = "#bf{Baryonic Z'}" txt1 += "#bf{, Z' #rightarrow DM + h" if which=='gg': txt1 += "(#gamma#gamma)}" if which=='tt': txt1 += "(#tau#tau)} " if which=='combo': txt1 += "(#gamma#gamma + #tau#tau)}" if model=="2HDM": txt2 = "#bf{Dirac DM, m_{DM} = 100 GeV}" if model=="BA...
random_line_split
plot2DlimitsAll.py
Text("") white.SetFillColor(0) white.Draw("SAME") # --- latex if model=="2HDM": txt1 = "#bf{Z'-2HDM}" if model=="BARY": txt1 = "#bf{Baryonic Z'}" txt1 += "#bf{, Z' #rightarrow DM + h" if which=='gg': txt1 += "(#gamma#gamma)}" if which=='tt': txt1 += "(#tau#tau)} " if which=='combo': txt1 += "(...
parser = OptionParser("usage: %prog [options]") parser.add_option("-O",action="store",dest="outdir",type="string", default="",help="Output directory [default = %default]"), parser.add_option("-m",action="store",dest="model",type="string", default="",help="Which model (2HDM or...
identifier_body
plot2DlimitsAll.py
(opts): # --- read in options model = opts.model which = opts.which outdir = opts.outdir do90 = opts.do90 dowgt = opts.dowgt dosmth = opts.dosmth smthfnc = opts.smthfnc #if dosmth: addtxt = '_smth' # --- read in files indir = '/eos/cms/store/group/phys_exotica/MonoHgg/MonoH-COMBO-2...
run
identifier_name
plot2DlimitsAll.py
BinningA = [0.5,1.5] BinAAxis = [1.0,47.5] for i in range(1, len(A)-1): BinningA.append( (A[i] + A[i+1])/2.0 ) BinAAxis.append( (A[i] + A[i+1])/2.0 ) BinningA.append( (A[-1] + A[-1] - ((A[-1] + A[-2])/2.0)) ) BinAAxis.append( (A[-1] + A[-1] - ((A[-1] + A[-2])/2.0)) ) # X axis BinningZ = [9,1...
# --- average plots to make smooth contours fillAvg(limitPlotObs, A, Z, doFillAvgLow, False, False) fillAvg(limitPlotObs, A, Z, False, doFillAvgHigh, False) fillAvg(limitPlotObs, A, Z, False, False, doFillAvgRest) if doFillAvgAll: fillAvg(limitPlot, A, Z, doFillAvgLow, False, False) fillAvg(...
for z in Z: data = {} filename = indir+'Zprime'+str(z)+'A'+str(a)+'.json' if which=='gg' and model=='BARY': # BARY gg ONLY has DM instead of A in filename filename = indir+'Zprime'+str(z)+'DM'+str(a)+'.json' scale = 1. if dowgt: scale = scaleXS(model,z,a) if os.path.isfile(...
conditional_block
reidtools.py
, optional): resized image width. Default is 128. height (int, optional): resized image height. Default is 256. save_dir (str): directory to save output images. topk (int, optional): denoting top-k images in the rank list to be visualized. Default is 10. """ num_q, num_g = di...
(src, dst, rank, prefix, matched=False): """ Args: src: image path or tuple (for vidreid) dst: target directory rank: int, denoting ranked position, starting from 1 prefix: string matched: bool """ if isinstance(src, tuple) or i...
_cp_img_to
identifier_name
reidtools.py
, optional): resized image width. Default is 128. height (int, optional): resized image height. Default is 256. save_dir (str): directory to save output images. topk (int, optional): denoting top-k images in the rank list to be visualized. Default is 10. """ num_q, num_g = di...
for q_idx in range(num_q): item = query[q_idx] qimg_path, qpid, qcamid = item[:3] # qsegment_path = item[6] qpid, qcamid = int(qpid), int(qcamid) num_cols = topk + 1 # grid_img = 255 * np.ones((2*height+GRID_SPACING, num_cols*width+(topk-1)*GRID_SPACING+QUERY_EXTRA_...
""" Args: src: image path or tuple (for vidreid) dst: target directory rank: int, denoting ranked position, starting from 1 prefix: string matched: bool """ if isinstance(src, tuple) or isinstance(src, list): if prefix == 'g...
identifier_body
reidtools.py
, optional): resized image width. Default is 128. height (int, optional): resized image height. Default is 256. save_dir (str): directory to save output images. topk (int, optional): denoting top-k images in the rank list to be visualized. Default is 10. """ num_q, num_g = di...
# forward to get convolutional feature maps try: # outputs = model(segments, imgs, return_featuremaps=True) outputs = model(imgs, contours, return_featuremaps=True) except TypeError: raise TypeError('forward() got unexpected keyword argument "return_featurem...
imgs = imgs.cuda() contours = contours.cuda()
conditional_block
reidtools.py
distmat.shape mkdir_if_missing(save_dir) print('# query: {}\n# gallery {}'.format(num_q, num_g)) print('Visualizing top-{} ranks ...'.format(topk)) query, gallery = dataset assert num_q == len(query) assert num_g == len(gallery) indices = np.argsort(distmat, axis=1) def _cp_...
# compute activation maps
random_line_split
mqtt.go
params.DeviceName iot.ProductKey = params.ProductKey iot.Host = params.ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com:1883" opts := mqtt.NewClientOptions().AddBroker(iot.Host).SetClientID(iot.ClientId).SetUsername(iot.Username).SetPassword(iot.Password) opts.SetPingTimeout(5 * time.Second) opts.SetKeepAlive...
.Check(msg.MsgId) { this.writeLog("warning", "msgId "+msg.MsgId+" Topic"+topic+" 重复消息") return } event := common_types.NewEvent(msg.MsgId ,message.Payload()) this.App.Pub(event) } /*** * 订阅get消息 */ func (this *Iot) SubscribeGet() { topic := "/" + this.ProductKey + "/" + this.DeviceName + "/get" this.Subscri...
{ this.writeLog("error", "Topic "+topic+" 消息解密失败 "+err.Error()+" Payload: "+string(message.Payload())) return } if !msgIds
conditional_block
mqtt.go
ProductKey string ClientId string Username string Password string Sign string Conn mqtt.Client logOut interfaces.ModuleLogger App interfaces.App SubDevices []Device } type Params struct { ProductKey string DeviceName string DeviceSecret string On...
DeviceName string
random_line_split
mqtt.go
productKey, _ := deviceInfo["productKey"].(string) deviceName, _ := deviceInfo["deviceName"].(string) this.writeLog("info", "SubRegister_reply 注册成功: "+deviceName) go this.SubDeviceLogin(productKey, deviceName, deviceSecret) } }) } func (this *Iot) SubDeviceLogin(productKey, deviceName, deviceSecret stri...
return }
identifier_name
mqtt.go
params.DeviceName iot.ProductKey = params.ProductKey iot.Host = params.ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com:1883" opts := mqtt.NewClientOptions().AddBroker(iot.Host).SetClientID(iot.ClientId).SetUsername(iot.Username).SetPassword(iot.Password) opts.SetPingTimeout(5 * time.Second) opts.SetKeepAlive...
*Iot) SubscribeSubGet(subProductKey, subDeviceName string) { topic := "/" + subProductKey + "/" + subDeviceName + "/get" this.SubscribeAndCheck(topic, 0) } /*** * 子设备注册 */ func (this *Iot) PublishSubRegister(subProductKey, subDeviceName string) { data := "{'id': '%s', 'version':'1.0','params':[{'deviceName':'%s'...
ctKey + "/" + this.DeviceName + "/get" this.SubscribeAndCheck(topic, 1) } /*** * 子设备 */ func (this
identifier_body
MapTilingScheme.ts
createFromContentId(stringId: string) { const idParts = stringId.split("_"); if (3 !== idParts.length) { assert(false, "Invalid quad tree ID"); return new QuadId(-1, -1, -1); } return new QuadId(parseInt(idParts[0], 10), parseInt(idParts[1], 10), parseInt(idParts[2], 10)); } pub...
public tileYToFraction(y: number, level: number): number { let yFraction = y / this.getNumberOfYTilesAtLevel(level); if (this._rowZeroAtTop) yFraction = 1.0 - yFraction; return yFraction; } public tileXToLongitude(x: number, level: number) { return this.xFractionToLongitude(th...
public tileXToFraction(x: number, level: number): number { return x / this.getNumberOfXTilesAtLevel(level); }
random_line_split
MapTilingScheme.ts
() { return this.level >= 0; } private static _scratchCartographic = new Cartographic(); public static createFromContentId(stringId: string) { const idParts = stringId.split("_"); if (3 !== idParts.length) { assert(false, "Invalid quad tree ID"); return new QuadId(-1, -1, -1); } ...
isValid
identifier_name
MapTilingScheme.ts
* Angle.degreesPerRadian, QuadId._scratchCartographic.latitude * Angle.degreesPerRadian); return range; } } /** @internal */ export class MapTileRectangle extends Range2d { public constructor(west = 0, south = 0, east = 0, north = 0) { super(west, south, east, north); } public static creat...
{ super(numberOfLevelZeroTilesX, numberOfLevelZeroTilesY, rowZeroAtTop); }
identifier_body
exceptions.py
MODULE_CODE = ErrorCode.BKDATA_AUTH class AuthCode: # 错误码映射表,目前以三元组定义,包含了错误码、描述和处理方式(可选) SDK_PERMISSION_DENIED_ERR = ("001", _("资源访问权限不足")) SDK_PARAM_MISS_ERR = ("002", _("认证参数缺失"), _("请查看API请求文档")) SDK_AUTHENTICATION_ERR = ("003", _("认证不通过,请提供合法的 BKData 认证信息"), _("请查看API请求文档")) SDK_INVALID_S...
class AuthAPIError(BaseAPIError):
random_line_split
exceptions.py
无更新权限")) OBJECT_CLASS_ERR = ("106", _("object类型错误")) SUBJECT_CHECK_ERR = ("107", _("主体校验失败")) SCOPE_CHECK_ERR = ("108", _("申请范围校验失败")) HAS_ALREADY_EXISTS_ERR = ("109", _("已提交过此权限申请,请勿重复提交")) OBJECT_NOT_EXIST_ERR = ("110", _("object不存在")) ACTION_CHECK_ERR = ("111", _("action校验错误")) NO_PROCESS...
Error): CODE
identifier_name
exceptions.py
= ("002", _("认证参数缺失"), _("请查看API请求文档")) SDK_AUTHENTICATION_ERR = ("003", _("认证不通过,请提供合法的 BKData 认证信息"), _("请查看API请求文档")) SDK_INVALID_SECRET_ERR = ( "004", _("内部模块调用请传递准确的 bk_app_code 和 bk_app_secret"), _("传递给的变量需要与 dataapi_settings.py 保持一致"), ) SDK_INVALID_TOKEN_ERR = ("005", _(...
MESSAGE = AuthCode.DATA_SCOPE_VALID_ERR[1] class AppNotMatchErr(AuthAPIError): CODE = AuthCode.APP_NOT_MATCH_ERR[0] MESSAGE = AuthCode.APP_NOT_MATCH_ERR[1] class PermissionObjectDoseNotExistError(AuthAPIError): CODE = AuthCode.PERMISSION_OBJECT_DOSE_NOT_EXIST_ERR[0] MESSAGE = AuthCode.PERMISSION_OB...
] class DataScopeValidErr(AuthAPIError): CODE = AuthCode.DATA_SCOPE_VALID_ERR[0]
identifier_body
main.rs
err_write!("bkp: Destination '{}' already exists", name); std::process::exit(1); } // parse the target URL let url = Url::parse(&url) .unwrap_or_fail("Cannot parse given URL"); // build the new target let tgt = config::Backup...
(args: &clap::ArgMatches, opts: &GlobalOptions) { unimplemented!() } fn do_clean(args: &clap::ArgMatches, opts: &GlobalOptions) { unimplemented!() } fn do_snap(args: &clap::ArgMatches, opts: &GlobalOptions) { let remote = args.value_of("remote").unwrap().to_owned(); let snap_paths: Vec<&str> = args.va...
do_stat
identifier_name
main.rs
} }; if abort { println!("aborted"); return; } } let objects: Vec<_> = objects.into_iter() .filter_map(|(p,o)| o.map(|v| (p, v))) .collect(); // actually reconstruct them let ...
random_line_split
main.rs
destinations let max_left_col = opts.cfg.targets.iter() .map(|ref x| x.name.len()) .max().unwrap_or(0); for t in opts.cfg.targets.iter() { println!("{1:0$} {2}", max_left_col, t.name, t.url.as_str()); } }, ("re...
{ let opt_matches = clap_app!(bkp => (version: "0.1") (author: "Noah Zentzis <nzentzis@gmail.com>") (about: "Automated system backup utility") (@arg CONFIG: -c --config +takes_value "Specifies a config file to use") (@arg DATADIR: -D --data-dir +takes_value "Specify the local...
identifier_body
show_solution.py
figure_utils.configure_latex_fonts_latex() data_vns_sop = orienteering_utils.parse_op_log(RESULT_FILE) print("using the last results") record = data_vns_sop[-1] print("record", record) problem_type = ProblemType.UNKNOWN PROBLEM_FILE = record['PROBLEM_FILE'] PROBLEM_FILE = os.path.join(this_script_path, PROBLEM_FILE...
alpha = 0.0 concave_hull = figure_utils.alpha_shape(points, alpha=alpha) color = mycmapScalarMap.to_rgba(set_rew) figure_utils.plot_polygon(concave_hull.buffer(25), fc=color) else: for set_idx in reversed(sorted(sets.keys())): points = [] s...
node1 = nodes_w_rewards[nidx1, :] points.append([node1[0], node1[1]]) for nidx2 in sets[set_idx]: if(nidx1 != nidx2): node2 = nodes_w_rewards[nidx2, :] # plt.plot([node1[0], node2[0] ], [node1[1], node2[1] ], '-k', lw=0.2)
conditional_block
show_solution.py
figure_utils.configure_latex_fonts_latex() data_vns_sop = orienteering_utils.parse_op_log(RESULT_FILE) print("using the last results") record = data_vns_sop[-1] print("record", record) problem_type = ProblemType.UNKNOWN PROBLEM_FILE = record['PROBLEM_FILE'] PROBLEM_FILE = os.path.join(this_script_path, PROBLEM_FILE...
elif "datasets/dop_sop_dataset/" in PROBLEM_FILE: print("showing DOP") problem_type = ProblemType.DOP SAVE_TO_FIGURE = "solution_dop.png" elif "datasets/opn_sop_dataset/" in PROBLEM_FILE: print("showing OPN") problem_type = ProblemType.OPN SAVE_TO_FIGURE = "solution_opn.png" else: err...
print("showing SOP") problem_type = ProblemType.SOP SAVE_TO_FIGURE = "solution_sop.png"
random_line_split
pager.py
out += "\nPrimary: " + str(list[primary]) out += "\nBackup: " + str(list[backup]) return out def Info(self): print(self._InfoString()) def MailInfo(self, sender, receiver): import smtplib # sending html email described here: # http://stackoverflow.com/questions/882712/sending-html-ema...
pager.Init() pager.offset_days = args.offset_days pager.monitor_email = args.monitor_email
random_line_split
pager.py
status_file = status_dir + "pager_status.json" monitor_email = "" monitor_pass = "" monitor_phone = "" alert_match_pattern = ".*ALARM.*" reply_match_pattern = "^R[eE]:.*ALARM.*" dry_run = 0 offset_days = 0 _status = dict() _active_list = [] _sent_one = 0 class Status: NEW = "new" OLD =...
def Run(self): if not os.path.exists(self.status_dir): os.makedirs(self.status_dir) self._ReadStatusFile() return self._FetchMails() def main(): # Fill in the default values relevant for you to avoid adding the flags for each run. parser
import code from googlevoice import Voice voice = Voice() voice.login(self.monitor_email, self.monitor_pass) voice.send_sms(phone, msg) # Send an SMS. voice.call(phone, self.monitor_phone, 3) # Call the person as well. self._sent_one = 1
conditional_block
pager.py
status_file = status_dir + "pager_status.json" monitor_email = "" monitor_pass = "" monitor_phone = "" alert_match_pattern = ".*ALARM.*" reply_match_pattern = "^R[eE]:.*ALARM.*" dry_run = 0 offset_days = 0 _status = dict() _active_list = [] _sent_one = 0 class Status: NEW = "new" OLD =...
def _SendAlertToPhone(self, phone, msg): if not self._sent_one: import code from googlevoice import Voice voice = Voice() voice.login(self.monitor_email, self.monitor_pass) voice.send_sms(phone, msg) # Send an SMS. voice.call(phone, self.monitor_phone, 3) # Ca...
days = (datetime.datetime.today() - datetime.datetime.utcfromtimestamp(0)).days + 3 + offset_days return days // 7 % len(self._active_list)
identifier_body
pager.py
status_file = status_dir + "pager_status.json" monitor_email = "" monitor_pass = "" monitor_phone = "" alert_match_pattern = ".*ALARM.*" reply_match_pattern = "^R[eE]:.*ALARM.*" dry_run = 0 offset_days = 0 _status = dict() _active_list = [] _sent_one = 0 class Status: NEW = "new" OLD =...
(self): if not os.path.exists(self.status_dir): os.makedirs(self.status_dir) self._ReadStatusFile() return self._FetchMails() def main(): # Fill in the default values relevant for you to avoid adding the flags for each run.
Run
identifier_name
main.go
13/pflag" "github.com/optakt/flow-dps/codec/zbor" "github.com/optakt/flow-dps/metrics/output" "github.com/optakt/flow-dps/metrics/rcrowley" "github.com/optakt/flow-dps/models/dps" "github.com/optakt/flow-dps/service/chain" "github.com/optakt/flow-dps/service/feeder" "github.com/optakt/flow-dps/service/forest" ...
) { os.Exit(run()) } func run() int { // Signal catching for clean shutdown. sig := make(chan os.Signal, 1) signal.Notify(sig, os.Interrupt) // Command line parameter initialization. var ( flagCheckpoint string flagData string flagForce bool flagIndex string ...
ain(
identifier_name
main.go
f13/pflag" "github.com/optakt/flow-dps/codec/zbor" "github.com/optakt/flow-dps/metrics/output" "github.com/optakt/flow-dps/metrics/rcrowley" "github.com/optakt/flow-dps/models/dps" "github.com/optakt/flow-dps/service/chain" "github.com/optakt/flow-dps/service/feeder" "github.com/optakt/flow-dps/service/forest" ...
storage := storage.New(codec) // Check if index already exists. _, err = index.NewReader(db, storage).First() indexExists := err == nil if indexExists && !flagForce { log.Error().Err(err).Msg("index already exists, manually delete it or use (-f, --force) to overwrite it") return failure } // The loader com...
size := rcrowley.NewSize("store") mout.Register(size) codec = metrics.NewCodec(codec, size) }
conditional_block
main.go
13/pflag" "github.com/optakt/flow-dps/codec/zbor" "github.com/optakt/flow-dps/metrics/output" "github.com/optakt/flow-dps/metrics/rcrowley" "github.com/optakt/flow-dps/models/dps" "github.com/optakt/flow-dps/service/chain" "github.com/optakt/flow-dps/service/feeder" "github.com/optakt/flow-dps/service/forest" ...
func run() int { // Signal catching for clean shutdown. sig := make(chan os.Signal, 1) signal.Notify(sig, os.Interrupt) // Command line parameter initialization. var ( flagCheckpoint string flagData string flagForce bool flagIndex string flagIndexAll ...
os.Exit(run()) }
identifier_body
main.go
" "github.com/optakt/flow-dps/service/chain" "github.com/optakt/flow-dps/service/feeder" "github.com/optakt/flow-dps/service/forest" "github.com/optakt/flow-dps/service/index" "github.com/optakt/flow-dps/service/loader" "github.com/optakt/flow-dps/service/mapper" "github.com/optakt/flow-dps/service/metrics" "gi...
) // This section launches the main executing components in their own
random_line_split
fixtures.go
success { tb.Fail() exportLogs(tb, testData, "afterSetupTest", true) } }() tb.Logf("Creating '%s' K8s Namespace", testNamespace) if err := ensureAntreaRunning(testData); err != nil { return nil, err } if err := testData.createTestNamespace(); err != nil { return nil, err } success = true return test...
teardownTest
identifier_name
fixtures.go
Collector(tb testing.TB) (*TestData, bool, bool, error) { v4Enabled := clusterInfo.podV4NetworkCIDR != "" v6Enabled := clusterInfo.podV6NetworkCIDR != "" testData, err := setupTest(tb) if err != nil { return testData, v4Enabled, v6Enabled, err } // Create pod using ipfix collector image if err = testData.creat...
random_line_split
fixtures.go
range requiredModules { // modprobe with "--dry-run" does not require root privileges cmd := fmt.Sprintf("modprobe --dry-run %s", module) rc, stdout, stderr, err := RunCommandOnNode(nodeName, cmd) if err != nil { tb.Skipf("Skipping test as modprobe could not be run to confirm the presence of module '%s': %v...
tb.Logf("Checking CoreDNS deployment") if err = testData.checkCoreDNSPods(defaultTimeout); err != nil { return testData, v4Enabled, v6Enabled, err } return testData, v4Enabled, v6Enabled, nil } func exportLogs(tb testing.TB, data *TestData, logsSubDir string, writeNodeLogs bool) { if tb.Skipped() { return ...
{ return testData, v4Enabled, v6Enabled, err }
conditional_block
fixtures.go
func skipIfNotIPv6Cluster(tb testing.TB) { if clusterInfo.podV6NetworkCIDR == "" { tb.Skipf("Skipping test as it requires IPv6 addresses but the IPv6 network CIDR is not set") } } func skipIfMissingKernelModule(tb testing.TB, nodeName string, requiredModules []string) { for _, module := range requiredModules { ...
{ if clusterInfo.podV6NetworkCIDR != "" { tb.Skipf("Skipping test as it is not supported in IPv6 cluster") } }
identifier_body
lineChart.component.ts
total?:number; } @Component({ selector: 'line-chart', template: `<div id="{{controlUid}}"></div>` }) export class LineChartComponent extends ViewComponent implements OnInit, AfterViewInit, OnDestroy, HandleDataFunc { @Input() dataList: DataListItem[]; /** First element is Name of the Field a string * ...
// This is the time portion of the API call. this._lineChartService.getData(this, this.dataList, rrdOptions); } public convertTo(value, conversion){ let result; switch(conversion){ case 'bytesToGigabytes': result = value / 1073741824; break; case 'percentFloatToInteger': ...
{ rrdOptions.end = Math.floor(rrdOptions.end / 1000); }
conditional_block
lineChart.component.ts
total?:number; } @Component({ selector: 'line-chart', template: `<div id="{{controlUid}}"></div>` }) export class LineChartComponent extends ViewComponent implements OnInit, AfterViewInit, OnDestroy, HandleDataFunc { @Input() dataList: DataListItem[]; /** First element is Name of the Field a string *...
(){ let conf = { interaction: { enabled:this.interactive }, bindto: '#' + this.controlUid, /*color: { pattern: this.colorPattern },*/ data: { columns: this.columns, //colors: this.createColorObject(), x: 'xValues', //xFormat: '%H:%M'...
makeConfig
identifier_name
lineChart.component.ts
= 'Label Y'; @Input() interactive: boolean; public chart:any; public conf:any; public columns:any; public linechartData:any; public units: string = ''; public showLegendValues: boolean = false; public legendEvents: BehaviorSubject<any>; public legendLabels: BehaviorSubject<any>; public legendAnal...
{ return 1 }
identifier_body
lineChart.component.ts
total?:number; } @Component({ selector: 'line-chart', template: `<div id="{{controlUid}}"></div>` }) export class LineChartComponent extends ViewComponent implements OnInit, AfterViewInit, OnDestroy, HandleDataFunc { @Input() dataList: DataListItem[]; /** First element is Name of the Field a string *...
dataSeriesArray = newArray; } this.data.series.push(dataSeriesArray); }); const columns: any[][] = []; let legendLabels: string[] = []; // xColumn const xValues: any[] = []; xValues.push('xValues'); this.data.labels.forEach((label) => { xValues.push(label); ...
});
random_line_split
micro_updater.py
Sending end "END" message') message = self.mqtt_client.publish(self.topic, payload='END', retain=True) self.mqtt_wait_publish(message) if not message.is_published(): self.mqtt_client.reconnect() message = self.mqtt_client.publish(self.topic, payload='END', retain=True) self.mqtt_wait_publish(message) ...
with open(file.path, 'r') as file_opened: content = file_opened.read() size = os.stat(file.path) hasher = hashlib.sha1(f'blob {len(content)}\x00{content}'.encode("utf-8")) hash = hasher.hexdigest() if hash == file.sha: logger.debug('File integrity OK') return True else: logger....
logger.debug(f'Verifying {file.name} integrity...') if self.trusted: logger.warning(f'Skipping {file.name} integrity check') return True try:
random_line_split
micro_updater.py
self.identity()}]: Message not sent') return logger.debug(f'[{self.identity()}]: Message sent') def send_new_release(self, release_json): logger.debug(f"[{self.identity()}]: Sending {release_json} on {self.topic}...") message = self.mqtt_client.publish(self.topic, payload='', retain=True) self.mqtt_wait_p...
self.config[section] = {} for key in CONFIGURATION_LAYOUT[section]: self.config[section][key] = f'<{key}>'
conditional_block
micro_updater.py
]: Message not sent') return logger.debug(f'[{self.identity()}]: Message sent') def send_new_release(self, release_json): logger.debug(f"[{self.identity()}]: Sending {release_json} on {self.topic}...") message = self.mqtt_client.publish(self.topic, payload='', retain=True) self.mqtt_wait_publish(message) ...
logger.debug(f'Reading configuration file "{config_path}"') try: self.config.read(config_path) except Exception as e: logger.critical(f'Error reading configuration file; {e}') logger.critical('Closing...') exit(1) try: sections = self.config.sections() for section in CONFIGURATION_LAYOUT: as...
identifier_body
micro_updater.py
Sending end "END" message') message = self.mqtt_client.publish(self.topic, payload='END', retain=True) self.mqtt_wait_publish(message) if not message.is_published(): self.mqtt_client.reconnect() message = self.mqtt_client.publish(self.topic, payload='END', retain=True) self.mqtt_wait_publish(message) ...
(self, file: RepoFile, download_path) -> bool: logger.debug(f'Downloading {file.name} into {download_path}...') try: file_path = os.path.join(download_path, file.name) wget.download(file.download_link, out=file_path) file.path = file_path return True except Exception as e: logger.error(f"Can't down...
_download_file
identifier_name
WaterHeaterClass.py
CarbonPrice=20): #$20/ton is the default rate for Carbon...if not specified when calling the func result = {} for i in range(vint, vint+self.lt): if self.hasRefrigerant == True: result[i] = UnitCarbonPrice * (self.AnnualEmissions(i) ) else: ...
def payback(self, WHx,yr): X = WHx.IC - self.IC Y = (self.OM[0] + self.AnnualEngCost(yr)) - (WHx.OM[0] + WHx.AnnualEngCost(yr)) #print "#", X, Y, "#" if self == WHx: return 0 elif (X>=0 and Y<=0): return max(self.lt, W...
return ( (self.NPVEmissions(yr)*UnitCarbonPrice + self.calcNPV(yr) ) /self.lt)
identifier_body
WaterHeaterClass.py
CarbonPrice=20): #$20/ton is the default rate for Carbon...if not specified when calling the func result = {} for i in range(vint, vint+self.lt): if self.hasRefrigerant == True: result[i] = UnitCarbonPrice * (self.AnnualEmissions(i) ) else: ...
elif yr >= self.vintage + self.lt + UltimYr: return self.OrigNum else: return 0 def numAlive(self,yr): return (self.OrigNum - self.deadsofar(yr)) def age(self, yr): return (yr - self.vintage) def annualreplacemen...
return self.weib()[yr-self.vintage]
conditional_block
WaterHeaterClass.py
CarbonPrice=20): #$20/ton is the default rate for Carbon...if not specified when calling the func result = {} for i in range(vint, vint+self.lt): if self.hasRefrigerant == True: result[i] = UnitCarbonPrice * (self.AnnualEmissions(i) ) else: ...
def weib(self): x = range(0, self.lt+UltimYr+1) w = weibull_min.cdf(x,3,loc=2.5,scale = self.lt) * self.OrigNum #print w return(w) def deadsofar(self, yr): if yr > self.vintage and yr < self.vintage+ self.lt + UltimYr: # print yr, self.vin...
def CCBreakEven(self, WH2, yr): #breakeven carbon cost breakeven = (self.calcNPV(yr)/self.lt- WH2.calcNPV(yr)/WH2.lt)/( WH2.NPVEmissions(yr)/WH2.lt - self.NPVEmissions(yr)/self.lt ) return breakeven
random_line_split
WaterHeaterClass.py
(self,yr): #in tons of CO2 eq result = {} avgleak = 0 if (self.hasRefrigerant == True): result = self.RefLeaks(yr) #for i in range(vint, vint+ self.lt): # avgleak = avgleak + result[i]/(1+CCDiscRate)**(i-vint+1) avgleak = sum(result.valu...
AvgRefLeaks
identifier_name
indexed_set.rs
_of::<Word>() * 8; impl<T: Idx> fmt::Debug for IdxSet<T> { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { w.debug_list() .entries(self.iter()) .finish() } } impl<T: Idx> IdxSet<T> { fn new(init: Word, domain_size: usize) -> Self { let num_words = (domain_size + (B...
new_empty
identifier_name
indexed_set.rs
a, T: Idx> { cur: Option<(Word, usize)>, iter: iter::Enumerate<slice::Iter<'a, Word>>, _pd: PhantomData<fn(&T)>, } impl<'a, T: Idx> Iterator for Iter<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { loop { if let Some((ref mut word, offset)) = self.cur { ...
assert_eq!(elems, expected); } } }
random_line_split
source_contributions.rs
#[fail(display = "No more retries.")] NoRetriesLeft, } impl From<std::io::Error> for AppError { fn from(err: std::io::Error) -> AppError { AppError::IOError(err) } } impl From<std::env::VarError> for AppError { fn from(err: std::env::VarError) -> AppError { AppError::GithubTokenNot...
(repo_url: &str) -> Result<(&str, &str), AppError> { match repo_url.split('/').collect::<Vec<&str>>().as_slice() { [_, "", "github.com", owner, repo] => Ok((owner, repo)), _ => Err(AppError::MetadataExtractionFailed { repo_url: repo_url.to_string(), }), } } // Extract the co...
extract_github_owner_and_repo
identifier_name
source_contributions.rs
#[fail(display = "No more retries.")] NoRetriesLeft, } impl From<std::io::Error> for AppError { fn from(err: std::io::Error) -> AppError { AppError::IOError(err) } } impl From<std::env::VarError> for AppError { fn from(err: std::env::VarError) -> AppError { AppError::GithubTokenNot...
// We retry. reqwest::StatusCode::ACCEPTED => { println!("Retrying, only {} retries left ...", retries_left); thread::sleep(time::Duration::from_secs(1)); call_github( http_client,...
{ let retries_left = retries.retries_num; if retries_left == 0 { Err(AppError::NoRetriesLeft) } else { let bearer = format!("Bearer {}", token); match http_method { HttpMethod::Get => { let url: Url = format!("{}{}", GITHUB_BASE_URL, url_path) ...
identifier_body
source_contributions.rs
#[fail(display = "No more retries.")] NoRetriesLeft, } impl From<std::io::Error> for AppError { fn from(err: std::io::Error) -> AppError { AppError::IOError(err) } } impl From<std::env::VarError> for AppError { fn from(err: std::env::VarError) -> AppError { AppError::GithubTokenNot...
match repo_url.split('/').collect::<Vec<&str>>().as_slice() { [_, "", "github.com", owner, repo] => Ok((owner, repo)), _ => Err(AppError::MetadataExtractionFailed { repo_url: repo_url.to_string(), }), } } // Extract the contribution relative to this project. For now only Git...
fn extract_github_owner_and_repo(repo_url: &str) -> Result<(&str, &str), AppError> {
random_line_split
shanten_improve.go
// } else if j < 7 { // needCheck34[idx-2] = true // needCheck34[idx-1] = true // needCheck34[idx] = true // needCheck34[idx+1] = true // needCheck34[idx+2] = true // } else if j == 7 { // needCheck34[idx-2] = true // needCheck34[idx-1] = true // needCheck34[idx] = true // needCheck34[idx+...
heck34[idx] = true // } // } //} //for i := 27; i < 34; i++ { // if tiles34[i] > 0 { // needCheck34[i] = true // } //} waits = Waits{} for i := 0; i < 34; i++ { //if !needCheck34[i] { // continue //} if tiles34[i] == 4 { // 无法摸到这张牌 continue } // 摸牌 tiles34[i]++ if newShanten := Calc...
dx-2] = true // needCheck34[idx-1] = true // needC
conditional_block
shanten_improve.go
// map[进张牌]向听前进后的进张数(这里让向听前进的切牌选择的是使「向听前进后的进张数最大」的切牌) NextShantenWaitsCountMap map[int]int // 向听前进后的进张数的加权均值 AvgNextShantenWaitsCount float64 // 综合了进张与向听前进后进张的评分 MixedWaitsScore float64 // 改良:摸到这张牌虽不能让向听数前进,但可以让进张变多 // len(Improves) 即为改良的牌的种数 Improves Improves // 改良情况数,这里计算的是有多少种使进张增加的切牌方式 ImproveWayCou...
// 若某个进张牌 4 枚都可见,则该进张的 value 值为 0 Waits Waits // TODO: 鸣牌进张:他家打出这张牌,可以鸣牌,且能让向听数前进 //MeldWaits Waits
random_line_split
shanten_improve.go
// } else if j < 7 { // needCheck34[idx-2] = true // needCheck34[idx-1] = true // needCheck34[idx] = true // needCheck34[idx+1] = true // needCheck34[idx+2] = true // } else if j == 7 { // needCheck34[idx-2] = true // needC
needCheck34[idx] = true // needCheck34[idx+1] = true // } else { // needCheck34[idx-2] = true // needCheck34[idx-1] = true // needCheck34[idx] = true // } // } //} //for i := 27; i < 34; i++ { // if tiles34[i] > 0 { // needCheck34[i] = true // } //} waits = Waits{} for i := 0; i < 34; i++ { ...
heck34[idx-1] = true //
identifier_name
shanten_improve.go
len(rj.Improves) //} //if ri.ImproveWayCount != rj.ImproveWayCount { // return ri.ImproveWayCount > rj.ImproveWayCount //} }) } func (l *WaitsWithImproves14List) filterOutDiscard(cantDiscardTile int) { newResults := WaitsWithImproves14List{} for _, r := range *l { if r.DiscardTile != cantDiscardTile { ...
ilterOutDiscard(cannotDiscardTile) } } // 添加副露信息,用于输出 _waitsWithImproves.addOpenTile(c.SelfTiles) _incShantenResults.addOpenTile(c.SelfTiles) // 整理副露结果 if _shanten == minShanten { waitsWithImproves = append(waitsWithImproves, _waitsWithImproves...) incShantenResults = append(incShantenResults, _i...
identifier_body
pod_driver.go
// checkAnnotations // 1. check refs in mount pod annotation // 2. delete ref that target pod is not found func (p *PodDriver) checkAnnotations(ctx context.Context, pod *corev1.Pod) error { // check refs in mount pod, the corresponding pod exists or not lock := config.GetPodLock(pod.Name) lock.Lock() defer lock.U...
{ if pod == nil { return podError } if pod.DeletionTimestamp != nil { return podDeleted } if util.IsPodError(pod) { return podError } if util.IsPodReady(pod) { return podReady } return podPending }
identifier_body
pod_driver.go
if err != nil { klog.Errorf("create pod:%s err:%v", pod.Name, err) } } else { klog.V(5).Infof("mountPod PodResourceError, but pod no resource, do nothing.") } } return nil } // podDeletedHandler handles mount pod that will be deleted func (p *PodDriver) podDeletedHandler(ctx context.Context, pod *core...
} } }
random_line_split
pod_driver.go
(client *k8sclient.K8sClient, mounter mount.SafeFormatAndMount) *PodDriver { driver := &PodDriver{ Client: client, handlers: map[podStatus]podHandler{}, SafeFormatAndMount: mounter, } driver.handlers[podReady] = driver.podReadyHandler driver.handlers[podError] = driver.podErrorHandler d...
newPodDriver
identifier_name
pod_driver.go
if err != nil { klog.Errorf("create pod:%s err:%v", pod.Name, err) } } else { klog.V(5).Infof("mountPod PodResourceError, but pod no resource, do nothing.") } } return nil } // podDeletedHandler handles mount pod that will be deleted func (p *PodDriver) podDeletedHandler(ctx context.Context, pod *co...
{ mi := p.mit.resolveTarget(target) if mi == nil { klog.Errorf("pod %s target %s resolve fail", pod.Name, target) continue } p.recoverTarget(pod.Name, mntPath, mi.baseTarget, mi) for _, ti := range mi.subPathTarget { p.recoverTarget(pod.Name, mntPath, ti, mi) } }
conditional_block
kitti_sem_data_loader.py
self.get_dataset() self.K = self.dataset.calib.K_cam0 self.load_extrinsics() self.get_GroundTruth() if object_label_status == 'tracklet_label': self.load_tracklet() elif object_label_status == 'detection_label': self.load_detection() else: ...
def generate_object_eval_path(self): self.pr_table_dir = self.cache_path + self.kitti_dir + '/evaluation/' if not os.path.exists(self.pr_table_dir): os.makedirs(self.pr_table_dir) def load_tracklet(self): """ # load tracklet # to show 3D bounding box ...
self.gt_bbox_results_path = self.cache_path + self.kitti_dir + '/gt_bboxes_results/' if not os.path.exists(self.gt_bbox_results_path): os.makedirs(self.gt_bbox_results_path)
identifier_body
kitti_sem_data_loader.py
self.get_dataset() self.K = self.dataset.calib.K_cam0 self.load_extrinsics() self.get_GroundTruth() if object_label_status == 'tracklet_label': self.load_tracklet() elif object_label_status == 'detection_label': self.load_detection() else: ...
(self): self.pr_table_dir = self.cache_path + self.kitti_dir + '/evaluation/' if not os.path.exists(self.pr_table_dir): os.makedirs(self.pr_table_dir) def load_tracklet(self): """ # load tracklet # to show 3D bounding box # need to use the groundtruth t...
generate_object_eval_path
identifier_name
kitti_sem_data_loader.py
self.get_dataset() self.K = self.dataset.calib.K_cam0 self.load_extrinsics() self.get_GroundTruth() if object_label_status == 'tracklet_label': self.load_tracklet() elif object_label_status == 'detection_label': self.load_detection() else:...
# first_pose_inv = src.se3.inversePose(first_pose) # do not correct the orientation # first_pose_inv[:3, :3] = np.eye(3) # do not set first pose to identity first_pose_inv = np.eye(4) for o in self.dataset.oxts: normalized_pose_original = first_pose_inv @ o...
# set first pose to identity # first_pose = self.dataset.oxts[0].T_w_imu
random_line_split
kitti_sem_data_loader.py
self.get_dataset() self.K = self.dataset.calib.K_cam0 self.load_extrinsics() self.get_GroundTruth() if object_label_status == 'tracklet_label': self.load_tracklet() elif object_label_status == 'detection_label': self.load_detection() else: ...
def generate_object_eval_path(self): self.pr_table_dir = self.cache_path + self.kitti_dir + '/evaluation/' if not os.path.exists(self.pr_table_dir): os.makedirs(self.pr_table_dir) def load_tracklet(self): """ # load tracklet # to show 3D bounding box ...
os.makedirs(self.gt_bbox_results_path)
conditional_block
vspheremachine_controller.go
Reconcile ensures the back-end state reflects the Kubernetes resource state intent. func (r machineReconciler) Reconcile(req ctrl.Request) (_ ctrl.Result, reterr error) { // Get the VSphereMachine resource for this request. vsphereMachine := &infrav1.VSphereMachine{} if err := r.Client.Get(r, req.NamespacedName, v...
{ // If the VSphereMachine is in an error state, return early. if ctx.VSphereMachine.Status.ErrorReason != nil || ctx.VSphereMachine.Status.ErrorMessage != nil { ctx.Logger.Info("Error state detected, skipping reconciliation") return reconcile.Result{}, nil } // If the VSphereMachine doesn't have our finalizer...
identifier_body
vspheremachine_controller.go
(controlledTypeName) controllerNameShort = fmt.Sprintf("%s-controller", strings.ToLower(controlledTypeName)) controllerNameLong = fmt.Sprintf("%s/%s/%s", ctx.Namespace, ctx.Name, controllerNameShort) ) // Build the controller context. controllerContext := &context.ControllerContext{ ControllerManagerContext...
{ return reconcile.Result{}, errors.Wrapf(err, "failed to destroy VM") }
conditional_block
vspheremachine_controller.go
corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/util/wait" clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha3" clusterutilv1 "sigs.k8s.io/cluster-api/util" "sigs.k8s.io/cluster-api/util/patch" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/...
"github.com/google/go-cmp/cmp/cmpopts" "github.com/pkg/errors"
random_line_split
vspheremachine_controller.go
For(controlledType). // Watch the CAPI resource that owns this infrastructure resource. Watches( &source.Kind{Type: &clusterv1.Machine{}}, &handler.EnqueueRequestsFromMapFunc{ ToRequests: clusterutilv1.MachineToInfrastructureMapFunc(controlledTypeGVK), }, ). // Watch a GenericEvent channel for the...
reconcileNormal
identifier_name
scrape.py
_TODAY_HEADER = ["district"] ACTIVE_TODAY_HEADER.extend(CASE_HEADER) CSV_HEADER = copy.deepcopy(QUARANTINE_HEADER) CSV_HEADER.extend(CASE_HEADER) TESTING_HEADER = [ "date", "total_sent", "sent_on_date", "processed_in_one_day", "total_positive", "new_positive", ] TEST_DATA_JSON = "./testData.json...
(): testing_data = {} sess = init_sess() response = run_req(sess, TESTING_REQ_URL, None, HEADERS, "GET") if not response: print("response failed for today's active case details") return if len(response.content) < 1000: print(len(response.content), " Actual response not reciev...
get_testing_details
identifier_name
scrape.py
")[0] for row in table.find_all("tr")[1:]: cols = [i.text for i in row.find_all("td")] district = cols[0] data_dict = dict(zip(QUARANTINE_HEADER, cols)) data_dict["dist_code"] = district data_dict["district"] = district_map[district] csv_data.append(data_dict) ret...
active = active_data_pivot[d]
random_line_split
scrape.py
_all("td")] district = cols[0] data_dict = dict(zip(QUARANTINE_HEADER, cols)) data_dict["dist_code"] = district data_dict["district"] = district_map[district] csv_data.append(data_dict) return csv_data def extract_datewise_active(soup, district): datalist = [] # ass...
kd, active_today, updated_date = get_active_details_today() if not get_only_curr: active_data = get_bulk_active_details() else: assert dates[0] == updated_date, "Date mismatch. Site updated till {}".format( updated_date ) active_data = active_today time.sleep(2) ...
identifier_body
scrape.py
_TODAY_HEADER = ["district"] ACTIVE_TODAY_HEADER.extend(CASE_HEADER) CSV_HEADER = copy.deepcopy(QUARANTINE_HEADER) CSV_HEADER.extend(CASE_HEADER) TESTING_HEADER = [ "date", "total_sent", "sent_on_date", "processed_in_one_day", "total_positive", "new_positive", ] TEST_DATA_JSON = "./testData.json...
if len(response.content) < 1000: print(len(response.content), " Actual response not recieved") return print("Processing testing data") soup = BeautifulSoup(response.content, "html.parser") case_report = soup.find_all(text=re.compile("Daily Case Reports from", re.I))[0] table = case_...
print("response failed for today's active case details") return
conditional_block
vck.py
their pixel-by-pixel AND, OR or # XOR as appropriate. def AND(*args): return boolean(lambda a,b:a&b, args) def OR(*args): return boolean(lambda a,b:a|b, args) def XOR(*args): return boolean(lambda a,b:a^b, args) def NOT(bmp): """Take a bitmap and return its negative (obtained by swopping white and black at e...
(_viewer): """A toplevel window with a canvas, suitable for viewing a moonfield.""" R = 9 # default radius def __init__(self, root, mf, title="Unnamed moonfield", radius=R): """Precondition: the moonfield mf must be filled.""" xmax, ymax = mf.size() _viewer.__init__(self, root, xm...
moonfieldViewer
identifier_name
vck.py
postscript representation of the canvas to the specified file.""" # The portrait A4 page is, in mm, WxH=210x297. Let's have a safety # margin of 7mm all around it, and the usable area becomes 196x283. W = 196.0 H = 283.0 x1, y1, x2, y2 = self._c.bbox("all") opti...
canvas.create_arc( radius*2*x, radius*2*y, radius*2*(x+1)-1, radius*2*(y+1)-1, start = self.__data[(x,y)] * self.i2d, extent = 180.0,
random_line_split
vck.py
return result # Doc string for the following three functions: # Take an arbitrary number (>=1) of bitmap arguments, all of the same size, # and return another bitmap resulting from their pixel-by-pixel AND, OR or # XOR as appropriate. def AND(*args): return boolean(lambda a,b:a&b, args) def OR(*args): return bool...
for y in range(maxY): pixel = bitmaps[0].get(x,y) for b in bitmaps[1:]: pixel = apply(operation, (pixel, b.get(x,y))) result.set(x,y,pixel)
conditional_block
vck.py
their pixel-by-pixel AND, OR or # XOR as appropriate. def AND(*args): return boolean(lambda a,b:a&b, args) def OR(*args): return boolean(lambda a,b:a|b, args) def XOR(*args): return boolean(lambda a,b:a^b, args) def NOT(bmp): """Take a bitmap and return its negative (obtained by swopping white and black at e...
def __init__(self, size, filler=None): """Make a moonfield of the specified size. If a filler function is specified, fill it with it, otherwise leave the data uninitialised.""" self.__data = {} self.__xmax, self.__ymax = size if filler: self.fill(filler)...
"""A 2d array of angles. Items in the array are indexed by integers in 0..xmax, 0..ymax, with 0,0 being the NW corner. Each angle specifies the phase (rotation) of a black halfmoon around its centre (determined by its place in the array) and is represented by an integer in the range 0..509""" # Why...
identifier_body
lib.rs
} } /** Forces the parser to interpret this macro's argument as an item, even in the presence of `tt` substitutions. See [TLBoRM: AST Coercion](https://danielkeep.github.io/tlborm/book/blk-ast-coercion.html). ## Examples ```rust # #[macro_use(as_item, tlborm_util)] extern crate tlborm; macro_rules! enoom { ($na...
This is typically used to replace elements of an arbitrary token sequence with some fixed expression. See [TLBoRM: Repetition replacement](https://danielkeep.github.io/tlborm/book/pat-repetition-replacement.html). ## Examples ```rust # #[macro_use(replace_expr, tlborm_util)] extern crate tlborm; # fn main() { macro...
/** Utility macro that takes a token tree and an expression, expanding to the expression.
random_line_split
athena_cli.py
csv.QUOTE_ALL) if self.format == 'CSV_HEADER': csv_writer.writerow(headers) csv_writer.writerows([[text.encode("utf-8") for text in row] for row in self.athena.yield_rows(results, headers)]) elif self.format == 'TSV': print(tabulate([row fo...
} if self.encryption: result_configuration['EncryptionConfiguration'] = { 'EncryptionOption': 'SSE_S3' } return self.athena.start_query_execution( QueryString=query, ClientRequestToken=str(uuid.uuid4...
if not db: raise ValueError('Schema must be specified when session schema is not set') result_configuration = { 'OutputLocation': self.bucket,
random_line_split