file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
mod.rs
, then broadcast addresses should use the /// `Broadcast` variant. Broadcast, } impl FrameDestination { /// Is this `FrameDestination::Multicast`? pub(crate) fn is_multicast(self) -> bool { self == FrameDestination::Multicast } /// Is this `FrameDestination::Broadcast`? pub(crate) ...
/// # Panics /// /// Panics if `device` is not initialized. pub fn receive_frame<B: BufferMut, D: BufferDispatcher<B>>( ctx: &mut Context<D>, device: DeviceId, buffer: B, ) { // `device` must be initialized. assert!(is_device_initialized(ctx.state(), device)); match device.protocol { De...
random_line_split
mod.rs
.protocol { DeviceProtocol::Ethernet => { ndp::start_soliciting_routers::<_, ethernet::EthernetNdpDevice>(ctx, device.id) } } } /// Send an IP packet in a device layer frame. /// /// `send_ip_frame` accepts a device ID, a local IP address, and a /// `SerializationRequest`. It computes t...
{ if self.is_tentative() { None } else { Some(self.into_inner()) } }
identifier_body
mod.rs
) -> bool { self == FrameDestination::Broadcast } } /// Builder for a [`DeviceLayerState`]. #[derive(Clone)] pub struct DeviceStateBuilder { /// Default values for NDP's configurations for new interfaces. /// /// See [`ndp::NdpConfigurations`]. default_ndp_configs: ndp::NdpConfigurations, }...
get_ip_addr_subnet_with_tentative
identifier_name
aula-principal.js
amy[0]); //mostra o que está na posição 0 desse array //function let corSite = "azul"; function resetaCor(cor, tonalidade){ corSite = cor + ' ' + tonalidade; return corSite; }; console.log(corSite); resetaCor('verde', 'escuro'); console.log(corSite); //incremento e decremento console.log(idade++); // imprim...
); //Constructor function: mesmo objetivo que a factory function function Celular (marcaCel, bateriaCel, tamanhoTela) { this.marcaCel = marcaCel, this.tamanhoTela = tamanhoTela, this.bateriaCel = bateriaCel, this.ligar = function() { console.log('Fazendo ligação...'); } } //instanciando o ...
ela, ligar(){ console.log('Fazendo ligação...'); } } } const cel1 = criarCelular('Samsung A10', 5000, 5.5); console.log(cel1
identifier_body
aula-principal.js
amy[0]); //mostra o que está na posição 0 desse array //function let corSite = "azul"; function resetaCor(cor, tonalidade){ corSite = cor + ' ' + tonalidade; return corSite; }; console.log(corSite); resetaCor('verde', 'escuro'); console.log(corSite); //incremento e decremento console.log(idade++); // imprim...
i++; //incremento } //A única diferença é que ele executa pelo menos uma vez antes de verificar o índice i = 0; do{ console.log(i); i++; }while(i < 5); //For in for(let chave in pessoa){ console.log(chave, pessoa[chave]); } //For of for(let indice of camy){ console.log(indice); } //Factory Function...
eira (i<5) e realiza o incremento console.log(i); } let i = 0; //indice while (i < 5){ console.log(i);
conditional_block
aula-principal.js
amy[0]); //mostra o que está na posição 0 desse array //function let corSite = "azul"; function resetaCor(cor, tonalidade){ corSite = cor + ' ' + tonalidade; return corSite; }; console.log(corSite); resetaCor('verde', 'escuro'); console.log(corSite); //incremento e decremento console.log(idade++); // imprim...
bateriaCel, tamanhoTela, ligar(){ console.log('Fazendo ligação...'); } } } const cel1 = criarCelular('Samsung A10', 5000, 5.5); console.log(cel1); //Constructor function: mesmo objetivo que a factory function function Celular (marcaCel, bateriaCel, tamanhoTela) { th...
marcaCel,
identifier_name
aula-principal.js
amy[0]); //mostra o que está na posição 0 desse array //function let corSite = "azul"; function resetaCor(cor, tonalidade){ corSite = cor + ' ' + tonalidade; return corSite; }; console.log(corSite); resetaCor('verde', 'escuro'); console.log(corSite); //incremento e decremento console.log(idade++); // imprim...
console.log(mouse); //clonando objetos //nesse exemplo o novo objeto receberá o objeto já criado celular com a adição da propriedade temDigital const objCopia = Object.assign({temDigital: true}, cel1); console.log(objCopia); //Math console.log(Math.random()); // -> gera um número aleatório de 0 a 1 console.log(Math....
//deletando propriedades e funções do objeto existente: delete mouse.trocarDPI; delete mouse.velocidade;
random_line_split
tree_estimator.py
"max_len" : FLAGS.max_len, "num_rels" : 53, "batch_size" : FLAGS.batch_size, "l2_coef" : 1e-4, } def load_vocab(): vocab_file = os.path.join(FLAGS.out_dir, FLAGS.vocab_file) vocab = [] vocab2id = {} with open(vocab_file) as f: for id, line in enumerate(f): token ...
def after_run(self, run_context, run_values): prob, label = run_values.results self.all_prob.append(prob) self.all_labels.append(label) def end(self, session): all_prob = np.concatenate(self.all_prob, axis=0) all_labels = np.concatenate(self.all_labels,axis=0) np.save('prob.npy', all_p...
return tf.train.SessionRunArgs([self.prob_tensor, self.labels_tensor])
identifier_body
tree_estimator.py
"max_len" : FLAGS.max_len, "num_rels" : 53, "batch_size" : FLAGS.batch_size, "l2_coef" : 1e-4, } def load_vocab(): vocab_file = os.path.join(FLAGS.out_dir, FLAGS.vocab_file) vocab = [] vocab2id = {} with open(vocab_file) as f: for id, line in enumerate(f): token ...
(n_sent, seq_len, n_channel=1): ''' [ [ 0 0] [ 0 1] [ 0 2] [ 0 3] [ 0 4] [ 0 5] [ 1 0] [ 1 1] [ 1 2] [ 1 3] [ 1 4] [ 1 5] [ 1 6] [ 1 7] ] ''' idx0 = tf.constant([], dtype=tf.int64) idx1 = tf.constant([], dtype=tf.int64) i = tf.constant(0, dtype=tf.int64) shape_invariants=[i.get_shape(...
batch_sparse_idx
identifier_name
tree_estimator.py
def load_vocab(): vocab_file = os.path.join(FLAGS.out_dir, FLAGS.vocab_file) vocab = [] vocab2id = {} with open(vocab_file) as f: for id, line in enumerate(f): token = line.strip() vocab.append(token) vocab2id[token] = id tf.logging.info("load vocab, size: %d" % len(vocab)) retur...
"max_len" : FLAGS.max_len, "num_rels" : 53, "batch_size" : FLAGS.batch_size, "l2_coef" : 1e-4, }
random_line_split
tree_estimator.py
"max_len" : FLAGS.max_len, "num_rels" : 53, "batch_size" : FLAGS.batch_size, "l2_coef" : 1e-4, } def load_vocab(): vocab_file = os.path.join(FLAGS.out_dir, FLAGS.vocab_file) vocab = [] vocab2id = {} with open(vocab_file) as f: for id, line in enumerate(f): token ...
tf.logging.info("load relation, relation size %d" % len(relations)) return relations, relation2id def _parse_example(example_proto): context_features = { 'e1': tf.FixedLenFeature([], tf.int64), 'e2': tf.FixedLenFeature([], tf.int64), 'label': tf.FixedLenFeature([], tf.int64),...
parts = line.strip().split() rel, id = parts[0], int(parts[1]) relations.append(rel) relation2id[rel] = id
conditional_block
utils.js
{ location.href = expect; } } function tryLogin() { $geta("/isUserLogined.htm?r=" + Math.random(), function (d) { if (d == true) { redirectIndex(); } }); } function tryLogout() { $geta("/isUserLogined.htm?r=" + Math.random(), function (d) { if (d != true) {...
}
random_line_split
utils.js
小时 "m+": this.getMinutes(), // 分 "s+": this.getSeconds(), // 秒 "q+": Math.floor((this.getMonth() + 3) / 3), // 季度 "S": this.getMilliseconds() // 毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "") .substr(4 - RegExp.$1.l...
.val(); }); return map; } function setInputValues(id, data, mapping) { // $("#"+id).find("input").each(function(){ // if(this.type == "button"){ // return; // } // var v = mapping == null ? data[this.name]
identifier_body
utils.js
: meizz var o = { "M+": this.getMonth() + 1, // 月份 "d+": this.getDate(), // 日 "h+": this.getHours(), // 小时 "m+": this.getMinutes(), // 分 "s+": this.getSeconds(), // 秒 "q+": Math.floor((this.getMonth() + 3) / 3), // 季度 "S": this.getMilliseconds() // 毫秒 ...
validateNotNullForm(form) { var v = true; $("#" + form).find("input,select").each(function () { if (this.type == "button") { return; } if (!$(this).attr("hint") == "none") { if (!$(this).val()) { v = false; errorMsgbox(this.name || ...
e; } function
identifier_name
utils.js
author: meizz var o = { "M+": this.getMonth() + 1, // 月份 "d+": this.getDate(), // 日 "h+": this.getHours(), // 小时 "m+": this.getMinutes(), // 分 "s+": this.getSeconds(), // 秒 "q+": Math.floor((this.getMonth() + 3) / 3), // 季度 "S": this.getMilliseconds() ...
_parent = _this.parent; } return _parent; } function redirectLogin() { var expect = ctxPath + "/login.html"; var location = getRootParent().location; if (location.pathname != expect) { location.href = expect; } } function redirectIndex() { var expect = ctxPath + "/index.ht...
tion getRootParent() { var _this = window; var _parent = window.parent; for (; _this != _parent;) { _this = _parent;
conditional_block
bikeshare.py
? y/n?\n").lower() if restart_month == 'y': get_filters() else: exit() # Get user input for day of the week global day day=() day_choice = input("which day of the week are you interested in?\n\nChoose a day by entering the followin...
time_delay_short
identifier_name
bikeshare.py
* 24 * 7 * 30 ('weeks', 604800), # 60 * 60 * 24 * 7 ('days', 86400), # 60 * 60 * 24 ('hours', 3600), # 60 * 60 ('minutes', 60), ('seconds', 1), ) #function to convert seconds to years,months,weeks,days,hours,seconds def display_time(seconds, granularity=6...
restart = input("Do you wish to reselect filters? y/n?\n").lower() if restart == 'y': get_filters() else: exit() # TO DO: get user input for month (all, january, february, ... , june) # Month Choice Input global month m...
else: print('This does not seem to be a valid choice!')
random_line_split
bikeshare.py
* 24 * 7 * 30 ('weeks', 604800), # 60 * 60 * 24 * 7 ('days', 86400), # 60 * 60 * 24 ('hours', 3600), # 60 * 60 ('minutes', 60), ('seconds', 1), ) #function to convert seconds to years,months,weeks,days,hours,seconds def display_time(seconds, granularity=6...
# TO DO: get user input for month (all, january, february, ... , june) # Month Choice Input global month month =() month_choice = input("Which month are you interested in?\n\nChoose a month by entering the following choices:\n (all, january, february, march, april, may, june) "...
print('This does not seem to be a valid choice!') restart = input("Do you wish to reselect filters? y/n?\n").lower() if restart == 'y': get_filters() else: exit()
conditional_block
bikeshare.py
0 * 24 * 7 * 30 ('weeks', 604800), # 60 * 60 * 24 * 7 ('days', 86400), # 60 * 60 * 24 ('hours', 3600), # 60 * 60 ('minutes', 60), ('seconds', 1), ) #function to convert seconds to years,months,weeks,days,hours,seconds def display_time(seconds, granularity=...
df = df[df['month'] == month] # filter by day of week if applicable if day != 'all': # filter by day of week to create the new dataframe df = df[df['day_of_week'] == day.title()] return df def time_stats(df): #Displays statistics on the most fr...
global df df = pd.read_csv(CITY_DATA[city],index_col=0, infer_datetime_format=True) # convert the Start Time and end Time column to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) df['End Time'] = pd.to_datetime(df['End Time']) # extract month and day of week from S...
identifier_body
MyGraph.py
o incidentes #self.get_adjacents(v) -> ver os sucessores e os predecessores para dar lista de adjacentes return len(self.get_adjacents(v))#contar os adjacentes da lista def all_degrees(self, deg_type = "inout"):#tudo o que sai e tudo o que entra ''' Cálculo de graus de entrada e saí...
n res.keys(): res[k] /= float(len(degs))#probabilidade dos graus return res '''EXEMPLO: c ={'a':1,'b':1,'c':3} v={} for k in c.keys(): if c[k] in v.keys(): v[c[k]] += 1 else: v[c[k]] =1 v ={1: 2, 3: 1} ''' ...
#adicionar ao dicionario esse k(grau) = 1 #degs[k]= key e res[degs[k]] = value for k i
conditional_block
MyGraph.py
ignoring unreachable nodes def mean_distances(self): tot = 0 #total num_reachable = 0 #numero de vetores ligados entre si for k in self.graph.keys(): distsk = self.reachable_with_dist(k)#[(no,dist)]->lista de nos atingiveis a partir de s com respetiva distancia for ...
egs = self.all_degrees(deg_type)#dicionario com as keys com os seus respetivos graus (entrada + saida) -> {no: graus(entrada + saida)} ccs = self.all_clustering_coefs()#vai buscar um dicionario com {no: coeficiente} degs_k = {}#{grau: no} for k in degs.keys():#percorrer os no if degs...
identifier_body
MyGraph.py
incidentes #self.get_adjacents(v) -> ver os sucessores e os predecessores para dar lista de adjacentes return len(self.get_adjacents(v))#contar os adjacentes da lista def all_degrees(self, deg_type = "inout"):#tudo o que sai e tudo o que entra ''' Cálculo de graus de entrada e saíd...
is curto entre s e d (lista de nos por onde passa) '''Retorna caminho mais curto entre s e d (lista de nós por onde passa)''' if s == d: return 0 l = [(s,[])]#lista de nos por onde passa que comeca na de origem visited = [s]#vertices visitados (nos atingidos) while len(l) > 0: ...
na caminho ma
identifier_name
MyGraph.py
s == d: return 0 l = [(s,[])]#lista de nos por onde passa que comeca na de origem visited = [s]#vertices visitados (nos atingidos) while len(l) > 0: node, preds = l.pop(0)#removes the item at the given index from the list and returns the removed item for elem in self.gra...
def mean_clustering_coef(self):#nova função '''Média sobre todos os nós'''
random_line_split
queries.py
COPYRIGHT HOLDERS BE LIABLE FOR # ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import numpy as np import pandas as pd import sqlite3 as db import dbtypes from spec...
(self, vals, table_name='_ref'): """ Create a temporary reference table by inserting values. This is used to speed up sqlite queries that are too slow when given the list directly in the query text (most likely a parsing issue?). """ # remove existing self._drop_t...
create_reference_ids_table
identifier_name
queries.py
COPYRIGHT HOLDERS BE LIABLE FOR # ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import numpy as np import pandas as pd import sqlite3 as db import dbtypes from spec...
# userid for unknown user unknown_user_id = self._get_unknown_userid() # can only return country info if userid is known cursor.execute( """ CREATE TEMP TABLE user_country_freqs AS select userid, country, count(*) as ct from sessions whe...
self._drop_tables(['user_country_freqs', 'user_and_likely_country'])
conditional_block
queries.py
COPYRIGHT HOLDERS BE LIABLE FOR # ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import numpy as np import pandas as pd import sqlite3 as db import dbtypes from spec...
def _get_unknown_userid(self): """ Retrieve user id associated with unknown user """ cursor = self.conn.cursor() unknown_user_str = dbtypes.User.null cursor.execute("select id from users where uniqueid='%s'" % unknown_user_str) return cursor.fetchone()[0] ...
""" Drop a set of tables from db (often used to materialize intermediate tables for ease of querying and then removing these to avoid affecting db state) :param tables: list of tables to drop :return: drops if they exist, ignores otherwise """ cursor = self.conn.cursor()...
identifier_body
queries.py
OR COPYRIGHT HOLDERS BE LIABLE FOR # ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import numpy as np import pandas as pd import sqlite3 as db import dbtypes from s...
""" key = 'user_and_countries' if use_cache and key in self.cache: return self.cache[key].copy() cursor = self.conn.cursor() if not use_cache: self._drop_tables(['user_country_freqs', 'user_and_likely_country']) # userid for unknown user ...
random_line_split
retryable.go
Config = tlsc r.httpClient.Transport = t } } return r } // WithAuth adds authentication to retryable methods func WithAuth(auth Auth) Opts { return func(r *retryable) { r.auth = auth } } // WithCerts adds certificates func WithCerts(certs [][]byte) Opts { return func(r *retryable) { for _, c := range ce...
// WithChunking allows content to be divided into multiple smaller chunks func WithChunking() OptsReq { return func(req *request) { req.chunking = true } } // WithContentLen sets the content length func WithContentLen(l int64) OptsReq { return func(req *request) { req.contentLen = l } } // WithDigest verifi...
{ return func(req *request) { req.getBody = getbody } }
identifier_body
retryable.go
Config = tlsc r.httpClient.Transport = t } } return r } // WithAuth adds authentication to retryable methods func WithAuth(auth Auth) Opts { return func(r *retryable) { r.auth = auth } } // WithCerts adds certificates func WithCerts(certs [][]byte) Opts { return func(r *retryable) { for _, c := range ce...
// close any previous responses before making a new request if len(req.responses) > 0 { req.responses[len(req.responses)-1].Body.Close() } // send the new request httpErr = req.httpDo()
{ sleepTime := time.Until(req.r.backoffUntil) req.log.WithFields(logrus.Fields{ "Host": req.urls[req.curURL].Host, "Seconds": sleepTime.Seconds(), }).Warn("Sleeping for backoff") select { case <-req.context.Done(): return ErrCanceled case <-time.After(sleepTime): } }
conditional_block
retryable.go
req.header.Add(key, v) } } } // WithHeaders includes a header object func WithHeaders(headers http.Header) OptsReq { return func(req *request) { for key := range headers { for _, val := range headers.Values(key) { req.header.Add(key, val) } } } } // WithProgressCB calls the CB function as data i...
Close
identifier_name
retryable.go
}).Warn("Failed to load root certificate") } } t.TLSClientConfig = tlsc r.httpClient.Transport = t } } return r } // WithAuth adds authentication to retryable methods func WithAuth(auth Auth) Opts { return func(r *retryable) { r.auth = auth } } // WithCerts adds certificates func WithCerts(c...
"cert": string(ca),
random_line_split
Telecom_customer_churn.py
= df[i].replace('No internet service' , 'No') df["MultipleLines"]=df["MultipleLines"].replace("No phone service","No") # In[16]: #to check if duplicated rows are present df.duplicated().sum() # In[17]: y = pd.crosstab(df["Churn"],columns = "Frequency") print(y) #no: of customers churned = 1869 #no: of custome...
hlyCharges") kde("TotalCharges") # # Tenure # In[21]: #Univariate Analysis #histogram sns.distplot(df["tenure"]) # In[22]: # there is a good no: of people with less than 10 months of tenure approximately 26% df[df["tenure"]<10]["tenure"].count()/len(df)*100 # In[23]: #summary of tenure df["tenure"].describ...
) plt.title("kde plot for {}".format(feature)) ax0=sns.kdeplot(df[df["Churn"]=="Yes"][feature],color="red",label= "Churn - Yes") ax1=sns.kdeplot(df[df["Churn"]=="No"][feature],color="green",label="Churn - No") kde("tenure") kde("Mont
identifier_body
Telecom_customer_churn.py
= df[i].replace('No internet service' , 'No') df["MultipleLines"]=df["MultipleLines"].replace("No phone service","No") # In[16]: #to check if duplicated rows are present df.duplicated().sum() # In[17]: y = pd.crosstab(df["Churn"],columns = "Frequency") print(y) #no: of customers churned = 1869 #no: of custome...
e(figsize=(9,4)) plt.title("kde plot for {}".format(feature)) ax0=sns.kdeplot(df[df["Churn"]=="Yes"][feature],color="red",label= "Churn - Yes") ax1=sns.kdeplot(df[df["Churn"]=="No"][feature],color="green",label="Churn - No") kde("tenure") kde("MonthlyCharges") kde("TotalCharges") # # Tenure # In[21]: #...
gur
identifier_name
Telecom_customer_churn.py
27% churned #73% not churned # In[19]: #categorical columns and numerical columns categorical_cols = ["gender","Partner","Dependents","PhoneService","MultipleLines","InternetService","OnlineSecurity","OnlineBackup","DeviceProtection","TechSupport","StreamingTV","StreamingMovies","Contract","PaperlessBilling","Payme...
sns.countplot(x=replace_cols[num],data=df,hue = "Churn",ax=axes[x,y],palette="coolwarm") num +=1 #for people who have op
conditional_block
Telecom_customer_churn.py
] = df[i].replace('No internet service' , 'No') df["MultipleLines"]=df["MultipleLines"].replace("No phone service","No") # In[16]: #to check if duplicated rows are present df.duplicated().sum() # In[17]: y = pd.crosstab(df["Churn"],columns = "Frequency") print(y) #no: of customers churned = 1869 #no: of custom...
# In[38]: #senior citizen vs payment method # In[39]: #senior citizens have opted electronic check more when compared to other payment methods. #So we need to know if there was any issue regarding electronic check sns.barplot(x="SeniorCitizen",y="PaymentMethod",data=df) # In[40]: #The average monthly charges...
SeniorCitizen_Crosstab_prop.plot(kind = 'bar' ,rot=0 , figsize = [16,5])
random_line_split
export_saved_model.py
load the JAX model.' ) _OUTPUT_DIR = flags.DEFINE_string( 'output_dir', None, 'Path under which to save the SavedModel.' ) _MODEL_NAME = flags.DEFINE_string( 'model_name', 'resnet_50', 'The name of the backbone model to export.' ) _IMAGE_SIZE = flags.DEFINE_integer( 'image_size', 1024, 'Image size to serve...
def generate_anchors_info(): """Generate anchors and image info.""" original_height, original_width = 512, 640 input_anchor = Anchor( min_level=2, max_level=6, num_scales=1, aspect_ratios=[1.0, 2.0, 0.5], anchor_size=8, image_size=(_IMAGE_SIZE.value, _IMAGE_SIZE.value)) an...
return self.unpack_labels(self.boxes, is_box=True)
identifier_body
export_saved_model.py
load the JAX model.' ) _OUTPUT_DIR = flags.DEFINE_string( 'output_dir', None, 'Path under which to save the SavedModel.' ) _MODEL_NAME = flags.DEFINE_string( 'model_name', 'resnet_50', 'The name of the backbone model to export.' ) _IMAGE_SIZE = flags.DEFINE_integer( 'image_size', 1024, 'Image size to serve...
(self, labels, is_box = False): """Unpacks an array of labels into multiscales labels. Args: labels: labels to unpack. is_box: to unpack anchor boxes or not. If it is true, will unpack to 2D, otherwise, will unpack to 3D. Returns: unpacked_labels: a dictionary...
unpack_labels
identifier_name
export_saved_model.py
load the JAX model.' ) _OUTPUT_DIR = flags.DEFINE_string( 'output_dir', None, 'Path under which to save the SavedModel.' ) _MODEL_NAME = flags.DEFINE_string( 'model_name', 'resnet_50', 'The name of the backbone model to export.' ) _IMAGE_SIZE = flags.DEFINE_integer( 'image_size', 1024, 'Image size to serve...
# Concat anchors on the same level to tensor shape NxAx4. boxes_l = tf.stack(boxes_l, axis=1) boxes_l = tf.reshape(boxes_l, [-1, 4]) boxes_all.append(boxes_l) return tf.concat(boxes_all, axis=0) def unpack_labels(self, labels, is_box = False): """Unpacks an array ...
boxes_l = [] for scale in range(self.num_scales): for aspect_ratio in self.aspect_ratios: stride = 2 ** level intermidate_scale = 2 ** (scale / float(self.num_scales)) base_anchor_size = self.anchor_size * stride * intermidate_scale aspect_x = aspect_ratio ** 0.5 ...
conditional_block
export_saved_model.py
TRAIN = 1 EVAL = 2 PREDICT = 3 class Anchor: """Anchor class for anchor-based object detectors.""" def __init__(self, min_level, max_level, num_scales, aspect_ratios, anchor_size, image_size): """Constructs multis...
'image': tf.TensorSpec( shape=(serving_batch_size, _IMAGE_SIZE.value, _IMAGE_SIZE.value,
random_line_split
old_main.rs
{ // `pos` has reached the current target, so we can update the `progress`, // then recurse to spend the remaining `step` to progress to the next waypoint *pos = target; self.progress += 1; self.advance_by(step - dist, pos) } e...
PointedRoom
identifier_name
old_main.rs
should_update = match self.last_goal { Some(g) => !point_eq(&goal, &g), None => true, }; if should_update { self.current = graph.find_route(player_pos, &goal).map(|route| Nav::new(route)); self.last_goal = Some(goal); } } } struct Nav { w...
// DEBUG: cursor { let [cx, cy] = cursor; let vertical = rectangle::centered([cx, cy, 1.0, 4.0]); let horizontal = rectangle::centered([cx, cy, 4.0, 1.0]); rectangle(CURSOR_COLOR, vertical, c.transform, gl); rectan...
{ let start = Some(player_pos.clone()); let lines = start.iter().chain(nav.waypoints().iter().skip(nav.progress)).sliding(); for (from, to) in lines { line_from_to(PATH_COLOR, 1.0, *from, *to, c.transform, gl); } }
conditional_block
old_main.rs
e.update(|args| { app.update(args.dt); }); // handle keyboard/button presses e.press(|button| { if let Button::Keyboard(key) = button { if key == Key::Space { app.generate_requested = true; } pri...
app.render(args); });
random_line_split
environ_config.py
" DBND_RUN_UID = "DBND_RUN_UID" DBND_RESUBMIT_RUN = "DBND_RESUBMIT_RUN" DBND_TASK_RUN_ATTEMPT_UID = "DBND_TASK_RUN_ATTEMPT_UID" DBND_TRACE_ID = "DBND_TRACE_ID" DBND_MAX_CALLS_PER_RUN = "DBND_MAX_CALL_PER_FUNC" ENV_DBND_DISABLE_SCHEDULED_DAGS_LOAD = "DBND_DISABLE_SCHEDULED_DAGS_LOAD" ENV_DBND__ENV_MACHINE = "DBND__ENV_...
def dbnd_lib_path(self, *path): return abs_join(_databand_package, *path) def dbnd_config_path(self, *path): return self.dbnd_lib_path("conf", *path) def dbnd_system_path(self, *path): dbnd_system = os.environ.get(ENV_DBND_SYSTEM) or self.dbnd_home() return abs_join(dbnd_s...
eturn os.environ.get(ENV_DBND_HOME) or os.curdir
identifier_body
environ_config.py
" DBND_RUN_UID = "DBND_RUN_UID" DBND_RESUBMIT_RUN = "DBND_RESUBMIT_RUN" DBND_TASK_RUN_ATTEMPT_UID = "DBND_TASK_RUN_ATTEMPT_UID" DBND_TRACE_ID = "DBND_TRACE_ID" DBND_MAX_CALLS_PER_RUN = "DBND_MAX_CALL_PER_FUNC" ENV_DBND_DISABLE_SCHEDULED_DAGS_LOAD = "DBND_DISABLE_SCHEDULED_DAGS_LOAD" ENV_DBND__ENV_MACHINE = "DBND__ENV_...
folder): # dbnd home is where 'marker' files are located in for file in _MARKER_FILES: file_path = os.path.join(folder, file) if os.path.exists(file_path): return folder, file_path return False, None def __find_dbnd_home_at(folder): dbnd_home, config_file = _
has_marker_file(
identifier_name
environ_config.py
" DBND_RUN_UID = "DBND_RUN_UID" DBND_RESUBMIT_RUN = "DBND_RESUBMIT_RUN" DBND_TASK_RUN_ATTEMPT_UID = "DBND_TASK_RUN_ATTEMPT_UID" DBND_TRACE_ID = "DBND_TRACE_ID" DBND_MAX_CALLS_PER_RUN = "DBND_MAX_CALL_PER_FUNC" ENV_DBND_DISABLE_SCHEDULED_DAGS_LOAD = "DBND_DISABLE_SCHEDULED_DAGS_LOAD" ENV_DBND__ENV_MACHINE = "DBND__ENV_...
return False, None def __find_dbnd_home_at(folder): dbnd_home, config_file = _process
return folder, file_path
random_line_split
environ_config.py
" DBND_RUN_UID = "DBND_RUN_UID" DBND_RESUBMIT_RUN = "DBND_RESUBMIT_RUN" DBND_TASK_RUN_ATTEMPT_UID = "DBND_TASK_RUN_ATTEMPT_UID" DBND_TRACE_ID = "DBND_TRACE_ID" DBND_MAX_CALLS_PER_RUN = "DBND_MAX_CALL_PER_FUNC" ENV_DBND_DISABLE_SCHEDULED_DAGS_LOAD = "DBND_DISABLE_SCHEDULED_DAGS_LOAD" ENV_DBND__ENV_MACHINE = "DBND__ENV_...
config_value = parser.get("databand", config_key) config_value = os.path.abspath(os.path.join(config_root, config_value)) set_env_dir(config_key, config_value) dbnd_log_init_msg("%s: %s=%s" % (source, config_key, config_value)) except Exception as...
ontinue
conditional_block
aarch64.rs
, } pub type KvmVcpuConfigureError = Error; impl KvmVcpu { /// Constructs a new kvm vcpu with arch specific functionality. /// /// # Arguments /// /// * `index` - Represents the 0-based CPU index between [0, max vcpus). /// * `vm` - The vm to which this vcpu will get attached. pub fn new(ind...
"Failed to restore the state of the vcpu: Failed to set register: Exec format error \
random_line_split
aarch64.rs
Arm. GetPreferredTarget(kvm_ioctls::Error), /// Error doing Vcpu Init on Arm. Init(kvm_ioctls::Error), /// Failed to set value for some arm specific register. RestoreState(arch::aarch64::regs::Error), /// Failed to fetch value for some arm specific register. SaveState(arch::aarch64::regs::E...
(index: u8, vm: &Vm) -> Result<Self> { let kvm_vcpu = vm.fd().create_vcpu(index.into()).map_err(Error::CreateFd)?; Ok(KvmVcpu { index, fd: kvm_vcpu, mmio_bus: None, mpidr: 0, }) } /// Gets the MPIDR register value. pub fn get_mpidr(&s...
new
identifier_name
aarch64.rs
Arm. GetPreferredTarget(kvm_ioctls::Error), /// Error doing Vcpu Init on Arm. Init(kvm_ioctls::Error), /// Failed to set value for some arm specific register. RestoreState(arch::aarch64::regs::Error), /// Failed to fetch value for some arm specific register. SaveState(arch::aarch64::regs::E...
/// Initializes an aarch64 specific vcpu for booting Linux. /// /// # Arguments /// /// * `vm_fd` - The kvm `VmFd` for this microvm. pub fn init(&self, vm_fd: &VmFd) -> Result<()> { let mut kvi: kvm_bindings::kvm_vcpu_init = kvm_bindings::kvm_vcpu_init::default(); // This read...
{ arch::aarch64::regs::setup_boot_regs( &self.fd, self.index, kernel_load_addr.raw_value(), guest_mem, ) .map_err(Error::ConfigureRegisters)?; self.mpidr = arch::aarch64::regs::read_mpidr(&self.fd).map_err(Error::ConfigureRegis...
identifier_body
ic7406.rs
/// | H | **L** | /// /// The chip comes in a 14-pin dual in-line package with the following pin assignments. /// ```txt /// +---+--+---+ /// A1 |1 +--+ 14| Vcc /// Y1 |2 13| A6 /// A2 |3 12| Y6 /// Y2 |4 7406 11| A5 /// A3 |5 10| Y5 /// Y3 |6 9| A4 /...
assert!(low!(tr[Y5]), "Y5 should be low when A5 is high"); set!(tr[A6]);
random_line_split
ic7406.rs
pin assignment for the +5V power supply. pub const VCC: usize = 14; /// The pin assignment for the ground. pub const GND: usize = 7; } use std::{cell::RefCell, rc::Rc}; use crate::{ components::{ device::{Device, DeviceRef, LevelChange, DUMMY}, pin::{ Mode::{Input, Output,...
} }
{}
conditional_block
ic7406.rs
pin assignment for the +5V power supply. pub const VCC: usize = 14; /// The pin assignment for the ground. pub const GND: usize = 7; } use std::{cell::RefCell, rc::Rc}; use crate::{ components::{ device::{Device, DeviceRef, LevelChange, DUMMY}, pin::{ Mode::{Input, Output,...
fn update(&mut self, event: &LevelChange) { match event { LevelChange(pin) if INPUTS.contains(&number!(pin)) => { let o = output_for(number!(pin)); if high!(pin) { clear!(self.pins[o]); } else { set!(self.p...
{ Vec::new() }
identifier_body
ic7406.rs
, Output, Unconnected}, Pin, }, }, vectors::RefVec, }; use self::constants::*; const INPUTS: [usize; 6] = [A1, A2, A3, A4, A5, A6]; /// An emulation of the 7406 hex inverter. /// /// The 7406 is one of the 7400-series TTL logic chips, consisting of six single-input /// inverters. An inver...
input_high
identifier_name
render.go
(tree *ast.Tree) (string, error) { subRenderer := &renderer{ template: r.template, stack: r.stack, depth: 0, w: strings.Builder{}, indent: "", indentNext: false, } err := subRenderer.walk(tree.Name, tree) s := subRenderer.String() // the subRenderer may have pushed and popped ...
renderToString
identifier_name
render.go
} r.write(s, t.Unescaped) case *ast.Section: v, err := r.lookup(treeName, t.Line, t.Column, t.Key) if err != nil { return err } v, err = r.toTruthyValue(v) if err != nil { return err } isTruthy := v.IsValid() if !t.Inverted && isTruthy { switch v.Kind() { case reflect.Slice, reflect.Arra...
{ break }
conditional_block
render.go
Next { r.indentNext = false r.w.WriteString(r.indent) } if !unescaped { s = html.EscapeString(s) } r.w.WriteString(s) } // conceptually shifts a context onto the stack. Since the stack is actually in // reverse order, the context is pushed. func (r *renderer) push(context reflect.Value) { r.stack = append(r...
{ loop: for v.IsValid() { switch av := v; av.Kind() { case reflect.Ptr: v = av.Elem() case reflect.Interface: v = av.Elem() default: break loop } } return v }
identifier_body
render.go
range t.Nodes { err := r.walk(treeName, t.Nodes[j]) if err != nil { return err } } r.pop() } case reflect.Func: s := v.Call([]reflect.Value{reflect.ValueOf(t.Text)})[0].String() tree, err := parse.Parse("lambda", s, t.LDelim, t.RDelim) if err != nil { return n...
return lookupKeyContext(key, indirect(ctx))
random_line_split
utils.go
Value returns value of the string func (s *SyncString) Value() string
// Set sets the value of the string func (s *SyncString) Set(v string) { s.Lock() defer s.Unlock() s.string = v } // ClickableURL fixes address in url to make sure // it's clickable, e.g. it replaces "undefined" address like // 0.0.0.0 used in network listeners format with loopback 127.0.0.1 func ClickableURL(in ...
{ s.Lock() defer s.Unlock() return s.string }
identifier_body
utils.go
Value returns value of the string func (s *SyncString) Value() string { s.Lock() defer s.Unlock() return s.string } // Set sets the value of the string func (s *SyncString) Set(v string) { s.Lock() defer s.Unlock() s.string = v } // ClickableURL fixes address in url to make sure // it's clickable, e.g. it repl...
() string { p.Lock() defer p.Unlock() if len(p.ports) == 0 { panic("list is empty") } val := p.ports[len(p.ports)-1] p.ports = p.ports[:len(p.ports)-1] return val } // PopInt returns a value from the list, it panics if not enough values // were allocated func (p *PortList) PopInt() int { i, err := strconv.At...
Pop
identifier_name
utils.go
// Value returns value of the string func (s *SyncString) Value() string {
s.Lock() defer s.Unlock() return s.string } // Set sets the value of the string func (s *SyncString) Set(v string) { s.Lock() defer s.Unlock() s.string = v } // ClickableURL fixes address in url to make sure // it's clickable, e.g. it replaces "undefined" address like // 0.0.0.0 used in network listeners format...
random_line_split
utils.go
could be empty // if not specified func ParseAdvertiseAddr(advertiseIP string) (string, string, error) { advertiseIP = strings.TrimSpace(advertiseIP) host := advertiseIP port := "" if len(net.ParseIP(host)) == 0 && strings.Contains(advertiseIP, ":") { var err error host, port, err = net.SplitHostPort(advertise...
{ //do not convert to system error as this loses the ability to compare that it is a permission error return err }
conditional_block
graphics.rs
{ offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress, shader_location: 1, format: wgpu::VertexFormat::Float32x3, }, wgpu::VertexAttribute { offset: std::mem::size_of::<[f32; 6]>() as wgpu::Buffer...
pub fn load_shader(shader_name: &str) -> Vec<u8> { let mut shader_dir = std::env::current_dir().unwrap(); shader_dir.push("src\\resources\\shaders"); shader_dir.push(shader_name); match fs::read(&shader_dir) { Ok(v) => v, Err(error) => panic!("Failed to read the file: {:?}. Error: {}"...
{ let texture = Texture::load_texture(texture_name, &device, &queue).unwrap(); device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &texture_bind_group_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Te...
identifier_body
graphics.rs
gpu::VertexAttribute { offset: std::mem::size_of::<[f32; 6]>() as wgpu::BufferAddress, shader_location: 2, format: wgpu::VertexFormat::Float32x2, } ] } } } pub struct Mesh { pub vertices: Vec<Vertex>, pub indice...
}; let swap_chain = device.create_swap_chain(&surface, &swap_chain_descriptor);
random_line_split
graphics.rs
Attribute { offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress, shader_location: 1, format: wgpu::VertexFormat::Float32x3, }, wgpu::VertexAttribute { offset: std::mem::size_of::<[f32; 6]>() as wgp...
{ pub model_matrix: [[f32; 4]; 4], } fn create_quad() -> Mesh { let mut vertices = Vec::new(); let vertexA = Vertex { position: [-0.5, 0.5, 0.0], normal: [0.0, 0.0, 1.0], tex_coords: [0.0, 0.0], }; let vertexB = Vertex { position: [0.5, 0.5, 0.0], normal: ...
ModelProperties
identifier_name
MMM-Ilevia-Lille.js
rgb(0, 118,125)", Yellow: "rgb(253,197,16)", Purple: "rgb(153,51,255)", White: "rgb(255,255,255)", Orange: "rgb(236,114,0)" }, size: "medium", // Text size, for example small, medium or large stacked: true, // Show multiple buses on same row, if same route and destination showTimeLimit: 45, // If n...
stackedBuses.push({ from: buses[len - 1].fields.nomstation, number: buses[len - 1].fields.codeligne, to: buses[len - 1].fields.sensligne, times: stackedTimes }); } return stackedBuses; }, formatBuses: function (bu...
stackvalue = '' + buses[i].fields.nomstation + buses[i].fields.codeligne + buses[i].fields.sensligne; if (stackvalue == previousStackvalue) { stackedTimes.push(buses[i].fields.heureestimeedepart); } else { stackedBuses.push({ ...
conditional_block
MMM-Ilevia-Lille.js
rgb(0, 118,125)", Yellow: "rgb(253,197,16)", Purple: "rgb(153,51,255)", White: "rgb(255,255,255)", Orange: "rgb(236,114,0)" }, size: "medium", // Text size, for example small, medium or large stacked: true, // Show multiple buses on same row, if same route and destination showTimeLimit: 45, // If n...
if (colorHEX != null) { element.style="color:"+colorHEX+";"; } } }, stackBuses: function (buses) { stackedBuses = []; var len = buses.length; var previousStackvalue = ''; var stackedTimes = []; if (len > 0) { previousStackvalue = '' + buses[0].fiel...
random_line_split
test_supernet.py
=str) parser.add_argument('--arch_start', default=1, type=int, metavar='N', help='the start index of eval archs') parser.add_argument('--arch_num', default=101, type=int, metavar='N', help='the num of eval archs') parser.add_argument('--workers', default=1, type=int, metavar='N',...
calibrate_bn
identifier_name
test_supernet.py
/model.th', help='model checkpoint', type=str) parser.add_argument('--arch_start', default=1, type=int, metavar='N', help='the start index of eval archs') parser.add_argument('--arch_num', default=101, type=int, metavar='N', help='the num of eval archs') parse...
new_loader.append((x.cuda(), y.cuda()))
conditional_block
test_supernet.py
train on supernet') parser.add_argument('--train_batch_size', type=int, default=128, help='train epoch on supernet') parser.add_argument('--train_epochs', type=int, default=1, help='train epoch on supernet') parser.add_argument('--train_lr', type=float, default=1e-3, ...
random_line_split
test_supernet.py
_channel or sample_sepmask_channel or sample_sepproject_channel or sample_localfree_channel') parser.add_argument('--alpha_type', default='sample_uniform', type=str, help='how to cal alpha in forward process: mix, sample_uniform, sample_fair, sample_flops_uniform, sample_flops_fair, sample_sandwich'...
model = copy.deepcopy(model) criterion = nn.CrossEntropyLoss().cuda() optimizer = torch.optim.SGD(model.parameters( ), args.train_lr, momentum=args.train_momentum, weight_decay=args.train_weight_decay) lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( optimizer, args.train_epochs, eta_m...
identifier_body
order.js
fenye({description:"", clientid:"", pagenow:1}); $(".Preservation").click(function () { var add = {}; // arry.pkey; // arry["pkey"]; // arry[html]; $(".zeng").children().each(function (idx, ele) { // if (idx < 1) { // return; // } ...
=contact % pageSize==0 ? contact/pageSize : Math.floor(contact/pageSize)+1; countpage = page; $("#pageSum").val(countpage); } }) data[ "pagenow"] = pagenow; data[ "pagesize"] = pageSize; $.ajax({ url: listUrl, data: data, type: "Post", //c...
var page
identifier_name
order.js
fenye({description:"", clientid:"", pagenow:1}); $(".Preservation").click(function () { var add = {}; // arry.pkey; // arry["pkey"]; // arry[html]; $(".zeng").children().each(function (idx, ele) { // if (idx < 1) { // return; // } ...
arry.pagenow=pagenow; getTable(arry); } //alert(pagenow); }); $("#lastpage").click(function () {//上一页 var arry = setarry(); //alert(pagenow); if (pagenow != 1) { pagenow -= 1; document.getElementById("curPage").value = p...
// // arry.pagenow = "1"; pagenow = 1; document.getElementById("curPage").value = pagenow; // getTable();//显示第一页 $("#nextpage").click(function () {//下一页 var arry = setarry(); //alert(page); if (pagenow < countpage) { pagenow += 1; document.getElementById(...
identifier_body
order.js
ye({description:"", clientid:"", pagenow:1}); $(".Preservation").click(function () { var add = {}; // arry.pkey; // arry["pkey"]; // arry[html]; $(".zeng").children().each(function (idx, ele) { // if (idx < 1) { // return; // } ...
untpage || npage < 1) { alert("请输入1-" + countpage + "页"); } else { pagenow = npage; } if (arry["description"] == "" && arry["clientid"] == "") { getTable(); } else { arry.pagenow=pagenow; getTable(arry); } ...
age").value); if (npage > co
conditional_block
order.js
ye({description:"", clientid:"", pagenow:1}); $(".Preservation").click(function () { var add = {}; // arry.pkey; // arry["pkey"]; // arry[html]; $(".zeng").children().each(function (idx, ele) { // if (idx < 1) { // return; // } ...
//alert(pagenow); }); $("#lastpage").click(function () {//上一页 var arry = setarry(); //alert(pagenow); if (pagenow != 1) { pagenow -= 1; document.getElementById("curPage").value = pagenow; } else { pagenow = 1 alert("已是首页")...
}
random_line_split
lib.rs
a> Fn(&'a W) -> Vec<(Cow<'static, str>, Cow<'a, str>)>; /// GraphML output printer /// /// See the [main crate documentation](index.html) for usage instructions and examples. pub struct GraphMl<G> where G: IntoEdgeReferences, G: IntoNodeReferences, { graph: G, pretty_print: bool, export_edges: Opti...
XmlEvent::start_element("key")
random_line_split
lib.rs
graphml.graphdrawing.org/ //! [petgraph]: https://docs.rs/petgraph/ #![deny( missing_debug_implementations, missing_copy_implementations, missing_docs, trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_qualifications, variant_size_differences )...
{ "directed" }
conditional_block
lib.rs
_graph(); //! // Configure output settings //! // Enable pretty printing and exporting of node weights. //! // Use the Display implementation of NodeWeights for exporting them. //! let graphml = GraphMl::new(&graph) //! .pretty_print(true) //! .export_node_weights_display(); //! //! assert_eq!( //! graphml....
/// Export the node weights to GraphML. /// /// This uses the [`Display`] implementation of the node weight type. /// The attribute name defaults to "weight". /// /// Once set this option cannot be disabled anymore. /// /// [`Display`]: ::std::fmt::Display pub fn export_node_weight...
{ self.export_edges = Some(edge_weight); self }
identifier_body
lib.rs
<G::NodeWeight>>>, } impl<G> GraphMl<G> where G: GraphProp, G: IntoNodeReferences, G: IntoEdgeReferences, G: NodeIndexable, { /// Create a new GraphML printer for the graph. pub fn new(graph: G) -> Self { Self { graph, pretty_print: true, export_edges...
fmt
identifier_name
main.rs
env; use std::ffi::OsStr; use std::fs::File; use std::path::Path; use std::process::Command; use util::APP_USAGE; struct HacspecCallbacks { output_file: Option<String>, target_directory: String, } const ERROR_OUTPUT_CONFIG: ErrorOutputType = ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(C...
.find(|p| p.name == package_name) .expect(&format!( " ⚠️ Can't find the package {} in the Cargo.toml\n\n{}", package_name, APP_USAGE, )) } else { &manifest.packages[0] }; log::trace!("Typechecking '{:?}' ...", package); // Tak...
.iter()
random_line_split
main.rs
env; use std::ffi::OsStr; use std::fs::File; use std::path::Path; use std::process::Command; use util::APP_USAGE; struct
{ output_file: Option<String>, target_directory: String, } const ERROR_OUTPUT_CONFIG: ErrorOutputType = ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(ColorConfig::Auto)); trait HacspecErrorEmitter { fn span_rustspec_err<S: Into<MultiSpan>>(&self, s: S, msg: &str); fn span_rustsp...
HacspecCallbacks
identifier_name
main.rs
; use std::ffi::OsStr; use std::fs::File; use std::path::Path; use std::process::Command; use util::APP_USAGE; struct HacspecCallbacks { output_file: Option<String>, target_directory: String, } const ERROR_OUTPUT_CONFIG: ErrorOutputType = ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(Colo...
} let json_string = String::from_utf8(stdout).expect(" ⚠️ Failed reading cargo output"); serde_json::from_str(&json_string).expect(" ⚠️ Error reading to manifest") }; // Pick the package of the given name or the only package available. let package = if let Some(package_name) = pac...
{ let manifest: Manifest = { let mut output = Command::new("cargo"); let mut output_args = if let Some(manifest_path) = manifest { vec!["--manifest-path".to_string(), manifest_path] } else { Vec::<String>::new() }; output_args.extend_from_slice(&[ ...
identifier_body
get.go
fmt.Printf("- LocalGetActions (pass on Source)\n") // Does nothing; pass through the filters return p.Source, nil }, } } if len(dbSchema.Things.Classes) > 0 { localGetThings, err := buildGetClasses(dbSchema, kind.THING_KIND, dbSchema.Things, &knownClasses) if err != nil { return nil, err } ...
{ getKinds := graphql.Fields{} if len(dbSchema.Actions.Classes) == 0 && len(dbSchema.Things.Classes) == 0 { return nil, fmt.Errorf("There are not any Actions or Things classes defined yet.") } knownClasses := map[string]*graphql.Object{} if len(dbSchema.Actions.Classes) > 0 { localGetActions, err := buildGe...
identifier_body
get.go
getKinds["Actions"] = &graphql.Field{ Name: "WeaviateLocalGetActions", Description: "Get Actions on the Local Weaviate", Type: localGetActions, Resolve: func(p graphql.ResolveParams) (interface{}, error) { fmt.Printf("- LocalGetActions (pass on Source)\n") // Does nothing; pass throu...
if err != nil { return nil, err } getKinds["Things"] = &graphql.Field{ Name: "WeaviateLocalGetThings", Description: "Get Things on the Local Weaviate", Type: localGetThings, Resolve: func(p graphql.ResolveParams) (interface{}, error) { fmt.Printf("- LocalGetThings (pass on Source...
if len(dbSchema.Things.Classes) > 0 { localGetThings, err := buildGetClasses(dbSchema, kind.THING_KIND, dbSchema.Things, &knownClasses)
random_line_split
get.go
(dbSchema *schema.Schema) (*graphql.Field, error) { getKinds := graphql.Fields{} if len(dbSchema.Actions.Classes) == 0 && len(dbSchema.Things.Classes) == 0 { return nil, fmt.Errorf("There are not any Actions or Things classes defined yet.") } knownClasses := map[string]*graphql.Object{} if len(dbSchema.Action...
Build
identifier_name
get.go
: "Type of Get function to get Things or Actions on the Local Weaviate", }), Resolve: func(p graphql.ResolveParams) (interface{}, error) { fmt.Printf("- LocalGet (extract resolver from source, parse filters )\n") resolver := p.Source.(map[string]interface{})["Resolver"].(Resolver) filters, err := common_fi...
{ // We can interpret this property in different ways for _, subSelection := range field.SelectionSet.Selections { // Is it a field with the name __typename? subsectionField, ok := subSelection.(*graphql_ast.Field) if ok { if subsectionField.Name.Value == "__typename" { property.IncludeType...
conditional_block
configV2.go
[j] = os.ExpandEnv(p) } for j, p := range m.Excludes { m.Excludes[j] = os.ExpandEnv(p) } } cfg.Input.PositionFile = os.ExpandEnv(cfg.Input.PositionFile) } func (cfg *Config) addDefaults() { cfg.Global.addDefaults() cfg.Input.addDefaults() cfg.Grok.addDefaults() if cfg.Metrics == nil { cfg.Metrics = Me...
{ if deleteLabelTemplate.Name() == labelTemplate.Name() { found = true break } }
conditional_block
configV2.go
} } if c.SyncInterval < time.Second { return errors.New("expected sync_interval more than 1s") } case c.Type == inputTypeWebhook: if c.WebhookPath == "" { return fmt.Errorf("invalid input configuration: 'input.webhook_path' is required for input type \"webhook\"") } else if c.WebhookPath[0] != '/' { ...
{ result, _ := Unmarshal([]byte(cfg.marshalToString())) return result }
identifier_body
configV2.go
:"webhook_text_bulk_separator,omitempty"` } type GrokConfig struct { PatternsDir string `yaml:"patterns_dir,omitempty"` AdditionalPatterns []string `yaml:"additional_patterns,omitempty"` } type MetricConfig struct { Type string `yaml:",omitempty"` Name string ...
case "counter": hasValue, cumulativeAllowed, bucketsAllowed, quantilesAllowed = false, false, false, false case "gauge": hasValue, cumulativeAllowed, bucketsAllowed, quantilesAllowed = true, true, false, false
random_line_split
configV2.go
yaml:"max_line_size,omitempty"` MaxLinesRatePerFile uint16 `yaml:"max_lines_rate_per_file,omitempty"` IdleTimeout time.Duration `yaml:"idle_timeout,omitempty"` WebhookPath string `yaml:"webhook_path,omitempty"` WebhookFormat string `yaml:"webhook_format...
() error { if len(*c) == 0 { return fmt.Errorf("Invalid metrics configuration: 'metrics' must not be empty.") } metricNames := make(map[string]bool) for _, metric := range *c { err := metric.validate() if err != nil { return err } _, exists := metricNames[metric.Name] if exists { return fmt.Errorf...
validate
identifier_name
jQuery-Validate-Extend.js
]).rules("add", { cantempty: newElements }); //eleresult = $(param[i]).valid(); //break; } } var result = (value || eleresult) ? true : false; return result; }, "This fields can not be empty."); /* 判断负数 */ jQuery.validator.addMethod("negativeCheck", function (value, element...
var valid = response === true; if (valid) { var submitted = validator.formSubmitted;
random_line_split
jQuery-Validate-Extend.js
; } else if (_type.match("<")) { _elseRule.type = _type.replace("<", ">"); } else { _elseRule.type = _type } _elseRule.object = "#" + element.id; $elseDate.rules("add", { compareDate: _elseRule }); } } var result...
_elseRule.type = _type.replace(">", "<")
conditional_block
inputprocessor.py
import runInferenceTriton from .utils import FILL_NONE_VALUE, add_selection_no_cutflow, bkgs, sigs, tagger_gen_matching warnings.filterwarnings("ignore", message="Found duplicate branch ") warnings.filterwarnings("ignore", category=DeprecationWarning) warnings.filterwarnings("ignore", message="Missing cross-reference...
skimmed_vars = {**skimmed_vars, **scores, **reg_mass, **hidNeurons} for key in skimmed_vars: skimmed_vars[key] = skimmed_vars[key].squeeze() # convert output to pandas df = pd.DataFrame(skimmed_vars) df = df.dropna() # very few events would have genjetma...
if "hidNeuron" in key: hidNeurons[key] = pnet_vars[key]
conditional_block
inputprocessor.py
import runInferenceTriton from .utils import FILL_NONE_VALUE, add_selection_no_cutflow, bkgs, sigs, tagger_gen_matching warnings.filterwarnings("ignore", message="Found duplicate branch ") warnings.filterwarnings("ignore", category=DeprecationWarning) warnings.filterwarnings("ignore", message="Missing cross-reference...
def save_dfs_parquet(self, df, fname): if self._output_location is not None: PATH = f"{self._output_location}/parquet/" if not os.path.exists(PATH): os.makedirs(PATH) table = pa.Table.from_pandas(df) if len(table) != 0: # skip dataframes wi...
return self._accumulator
identifier_body
inputprocessor.py
import runInferenceTriton from .utils import FILL_NONE_VALUE, add_selection_no_cutflow, bkgs, sigs, tagger_gen_matching warnings.filterwarnings("ignore", message="Found duplicate branch ") warnings.filterwarnings("ignore", category=DeprecationWarning) warnings.filterwarnings("ignore", message="Missing cross-reference...
(self, output_collection: ak.Array) -> pd.DataFrame: output = pd.DataFrame() for field in ak.fields(output_collection): output[field] = ak.to_numpy(output_collection[field]) return output def dump_root(self, skimmed_vars: Dict[str, np.array], fname: str) -> None: """ ...
ak_to_pandas
identifier_name
inputprocessor.py
import runInferenceTriton from .utils import FILL_NONE_VALUE, add_selection_no_cutflow, bkgs, sigs, tagger_gen_matching warnings.filterwarnings("ignore", message="Found duplicate branch ") warnings.filterwarnings("ignore", category=DeprecationWarning) warnings.filterwarnings("ignore", message="Missing cross-reference...
# selection selection = PackedSelection() add_selection_no_cutflow("fjselection", (fatjet.pt > 200), selection) if np.sum(selection.all(*selection.names)) == 0: return {} # variables FatJetVars = { f"fj_{key}": ak.fill_none(fatjet[var], FILL_NON...
candidatelep_p4 = build_p4(ak.firsts(leptons)) fj_idx_lep = ak.argmin(fatjets.delta_r(candidatelep_p4), axis=1, keepdims=True) fatjet = ak.firsts(fatjets[fj_idx_lep])
random_line_split
npm-utils.js
else { set = []; } } if(supportsSet) { if(set.has(s)) { return s; } else { set.add(s); } } else { if(set.indexOf(s) !== -1) { return s; } else { set.push(s); } } } for(var prop in s) { val = s[prop]; if(deep) { if(utils.isArray(val)) { ...
{ set = new Set(); }
conditional_block
npm-utils.js
Slash(name)) { // Todo .. first part of name var curPackage = utils.path.depPackageDir(refPackage.fileUrl, name); while(curPackage) { var pkg = loader.npmPaths[curPackage]; if(pkg) { return pkg; } var parentAddress = utils.path.parentNodeModuleAddress(curPackage); if(!parentAd...
{ var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/); // authority = '//' + user + ':' + pass '@' + hostname + ':' port return (m ? { href : m[0] || '', protocol : m[1] || '', authority: m[2] || '', h...
identifier_body
npm-utils.js
moduleName includes a condition. * @return {Boolean} */ isConditional: function(moduleName){ return conditionalModuleRegEx.test(moduleName); }, /** * @function moduleName.isFullyConvertedModuleName * Determines whether a moduleName is a fully npm name, not npm-like * With a parsed module name w...
// if the module name is relative // use the currentPackageName if (currentPackageName && utils.path.isRelative(moduleName)) { packageName = currentPackageName; modulePath = versionParts[0]; // if the module name starts with the ~ (tilde) operator // use the currentPackageName } else if (c...
random_line_split
npm-utils.js
we check this against various configs var mapName = utils.moduleName.create(parsedModuleName), refSteal = utils.pkg.config(refPkg), mappedName; // The refPkg might have a browser [https://github.com/substack/node-browserify#browser-field] mapping. // Perform that mapping here. if(refPkg.browser...
removeDotSegments
identifier_name
utils.py
from .products.builders import products from .responses import response, make_identity, make_error from .static.builders import codevalues from .users.builders import users def fill_cache(cache, values_dict): """ Fill a mock cache object with some keys and values. """ cache.get.side_effect = lambda ...
(): cache = get_cache("django.core.cache.backends.locmem.LocMemCache") cache.clear() patcher = patch("ccui.core.cache.cache", cache) patcher.start() yield cache patcher.stop() class CachingFunctionalTestMixin(object): def setUp(self): self.cache = get_cache("django.core.cache.back...
locmem_cache
identifier_name