file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
path.rs | //! This module contains code for abstracting object locations that work
//! across different backing implementations and platforms.
use itertools::Itertools;
use percent_encoding::{percent_decode_str, percent_encode, AsciiSet, CONTROLS};
use std::path::PathBuf;
/// Universal interface for handling paths and location... | fn push_encodes() {
let mut location = ObjectStorePath::default();
location.push("foo/bar");
location.push("baz%2Ftest");
let converted = CloudConverter::convert(&location);
assert_eq!(converted, "foo%2Fbar/baz%252Ftest");
}
#[test]
fn push_all_encodes() {
... | }
#[test] | random_line_split |
mod.rs | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! The device layer.
pub(crate) mod arp;
pub(crate) mod ethernet;
pub(crate) mod ndp;
use std::fmt::{self, Debug, Display, Formatter};
use log::{debug,... | /// # 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 | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! The device layer.
pub(crate) mod arp;
pub(crate) mod ethernet;
pub(crate) mod ndp;
use std::fmt::{self, Debug, Display, Formatter};
use log::{debug,... |
/// Borrow the content which is stored inside.
pub(crate) fn inner(&self) -> &T {
&self.0
}
/// Similar to `Option::map`.
pub(crate) fn map<U, F>(self, f: F) -> Tentative<U>
where
F: FnOnce(T) -> U,
{
Tentative(f(self.0), self.1)
}
/// Make the tentative v... | {
if self.is_tentative() {
None
} else {
Some(self.into_inner())
}
} | identifier_body |
mod.rs | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! The device layer.
pub(crate) mod arp;
pub(crate) mod ethernet;
pub(crate) mod ndp;
use std::fmt::{self, Debug, Display, Formatter};
use log::{debug,... | <D: EventDispatcher, A: IpAddress>(
ctx: &Context<D>,
device: DeviceId,
) -> Option<Tentative<AddrSubnet<A>>> {
match device.protocol {
DeviceProtocol::Ethernet => {
self::ethernet::get_ip_addr_subnet_with_tentative(ctx, device.id)
}
}
}
/// Set the IP address and subnet ass... | get_ip_addr_subnet_with_tentative | identifier_name |
aula-principal.js | /*Arquivo principal com os testes feitos juntos com a aula iniciante de Javascript
Aula: https://www.youtube.com/watch?v=i6Oi-YtXnAU&feature=youtu.be
Anotações/explicações: https://drive.google.com/file/d/1WXCz5PgXpumV59kG_m1KnmHIsIcCuTd8/view?usp=sharing*/
//Exercício 01 variáveis:
let nome = 'Mariana';
let sobren... | );
//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 | /*Arquivo principal com os testes feitos juntos com a aula iniciante de Javascript
Aula: https://www.youtube.com/watch?v=i6Oi-YtXnAU&feature=youtu.be
Anotações/explicações: https://drive.google.com/file/d/1WXCz5PgXpumV59kG_m1KnmHIsIcCuTd8/view?usp=sharing*/
//Exercício 01 variáveis:
let nome = 'Mariana';
let sobren... | 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 | /*Arquivo principal com os testes feitos juntos com a aula iniciante de Javascript
Aula: https://www.youtube.com/watch?v=i6Oi-YtXnAU&feature=youtu.be
Anotações/explicações: https://drive.google.com/file/d/1WXCz5PgXpumV59kG_m1KnmHIsIcCuTd8/view?usp=sharing*/
//Exercício 01 variáveis:
let nome = 'Mariana';
let sobren... | 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 | /*Arquivo principal com os testes feitos juntos com a aula iniciante de Javascript
Aula: https://www.youtube.com/watch?v=i6Oi-YtXnAU&feature=youtu.be
Anotações/explicações: https://drive.google.com/file/d/1WXCz5PgXpumV59kG_m1KnmHIsIcCuTd8/view?usp=sharing*/
//Exercício 01 variáveis:
let nome = 'Mariana';
let sobren... | 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 | import os
import time
import numpy as np
import tensorflow as tf
from tree_model import CNNModel
import logging
flags = tf.app.flags
flags.DEFINE_string("data_dir", "data", "data directory")
flags.DEFINE_string("relation_file", "RE/relation2id.txt", "")
flags.DEFINE_string("out_dir", "preprocess", "")
flags.DEFINE_s... |
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 | import os
import time
import numpy as np
import tensorflow as tf
from tree_model import CNNModel
import logging
flags = tf.app.flags
flags.DEFINE_string("data_dir", "data", "data directory")
flags.DEFINE_string("relation_file", "RE/relation2id.txt", "")
flags.DEFINE_string("out_dir", "preprocess", "")
flags.DEFINE_s... | (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 | import os
import time
import numpy as np
import tensorflow as tf
from tree_model import CNNModel
import logging
flags = tf.app.flags
flags.DEFINE_string("data_dir", "data", "data directory")
flags.DEFINE_string("relation_file", "RE/relation2id.txt", "")
flags.DEFINE_string("out_dir", "preprocess", "")
flags.DEFINE_s... |
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 | import os
import time
import numpy as np
import tensorflow as tf
from tree_model import CNNModel
import logging
flags = tf.app.flags
flags.DEFINE_string("data_dir", "data", "data directory")
flags.DEFINE_string("relation_file", "RE/relation2id.txt", "")
flags.DEFINE_string("out_dir", "preprocess", "")
flags.DEFINE_s... |
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 | String.prototype.replaceAll = function (oldChar, newChar) {
return this.replace(new RegExp(oldChar, "gm"), newChar);
}
function getCtxPath() {
var path = window.location.pathname;
return path.substring(0, path.indexOf("/", 1));
}
var ctxPath = "";
var ZENG = ZENG || null;
if (ZENG != null) {
ZENG.msgb... | }
}).show();
}, 100);
}
function dialog(id, width, buttons) {
if (buttons == null) {
buttons = width;
width = 400;
}
buttons["关 闭"] = function () {
$(this).dialog("close");
}
$("#" + id).dialog({
resizable: false,
height: "auto",
... | } | random_line_split |
utils.js | String.prototype.replaceAll = function (oldChar, newChar) {
return this.replace(new RegExp(oldChar, "gm"), newChar);
}
function getCtxPath() {
var path = window.location.pathname;
return path.substring(0, path.indexOf("/", 1));
}
var ctxPath = "";
var ZENG = ZENG || null;
if (ZENG != null) {
ZENG.msgb... | : data[mapping[this.name]];
// if(v == null || v == undefined){
// this.value = "";
// return;
// }
// this.value = v;
// });
// $("#"+id).find("select").each(function(){
// var v = mapping == null ? data[this.name] : data[mapping[this.name]];
// if(v == null || v == undefined){
// $(this).val("");
// ret... | .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 | String.prototype.replaceAll = function (oldChar, newChar) {
return this.replace(new RegExp(oldChar, "gm"), newChar);
}
function getCtxPath() {
var path = window.location.pathname;
return path.substring(0, path.indexOf("/", 1));
}
var ctxPath = "";
var ZENG = ZENG || null;
if (ZENG != null) {
ZENG.msgb... | 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 | String.prototype.replaceAll = function (oldChar, newChar) {
return this.replace(new RegExp(oldChar, "gm"), newChar);
}
function getCtxPath() {
var path = window.location.pathname;
return path.substring(0, path.indexOf("/", 1));
}
var ctxPath = "";
var ZENG = ZENG || null;
if (ZENG != null) {
ZENG.msgb... |
_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 | import time
import pandas as pd
import numpy as np
from datetime import datetime
#from collections import Counter
def main():
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
#start of program after title, loo... | ():
#to add time delay to slow down the bombard of text to the user (and for fun!)
time.sleep(1)
print('...executing task...')
time.sleep(1)
print('....................Complete!\n')
time.sleep(1)
get_filters()
print('\nThe bike data will now be filtered by the follow... | time_delay_short | identifier_name |
bikeshare.py | import time
import pandas as pd
import numpy as np
from datetime import datetime
#from collections import Counter
def main():
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
#start of program after title, loo... | 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 | import time
import pandas as pd
import numpy as np
from datetime import datetime
#from collections import Counter
def main():
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
#start of program after title, loo... |
# 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 | import time
import pandas as pd
import numpy as np
from datetime import datetime
#from collections import Counter
def main():
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
#start of program after title, loo... |
def time_stats(df):
#Displays statistics on the most frequent times of travel.
print('\nCalculating The Most Frequent Times of Travel for: \n City: {}\n Month: {}\n Day: {}'.format(city,month,day))
start_time = time.time()
time_delay_short()
#display the most common mon... | 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 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 23 01:33:42 2017
@author: miguelrocha
"""
## Graph represented as adjacency list using a dictionary
## keys are vertices
## values of the dictionary represent the list of adjacent vertices of the key node
class MyGraph:
def __init__(self, g = {}):
''' C... | 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 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 23 01:33:42 2017
@author: miguelrocha
"""
## Graph represented as adjacency list using a dictionary
## keys are vertices
## values of the dictionary represent the list of adjacent vertices of the key node
class MyGraph:
def __init__(self, g = {}):
''' C... | l:
if val == x: return True
return res
if __name__ == "__main__":
gr = MyGraph()
gr.add_vertex(1)
gr.add_vertex(2)
gr.add_vertex(3)
gr.add_vertex(4)
gr.add_edge(1,2)
gr.add_edge(2,3)
gr.add_edge(3,2)
gr.add_edge(3,4)
gr.add_edge(4,2)
gr.print_graph()
pri... | 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 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 23 01:33:42 2017
@author: miguelrocha
"""
## Graph represented as adjacency list using a dictionary
## keys are vertices
## values of the dictionary represent the list of adjacent vertices of the key node
class MyGraph:
def __init__(self, g = {}):
''' C... | 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 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 23 01:33:42 2017
@author: miguelrocha
"""
## Graph represented as adjacency list using a dictionary
## keys are vertices
## values of the dictionary represent the list of adjacent vertices of the key node
class MyGraph:
def __init__(self, g = {}):
''' C... | ccs = self.all_clustering_coefs()#vai buscar um dicionario com {no: coeficiente}
return sum(ccs.values()) / float(len(ccs))# soma dos values/total de elemntos em ccs
def mean_clustering_perdegree(self, deg_type = "inout"):#nova função
'''Média dos coeficientes considerando nós d... |
def mean_clustering_coef(self):#nova função
'''Média sobre todos os nós''' | random_line_split |
queries.py | # Copyright 2018 Jose Cambronero and Phillip Stanley-Marbell
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, mod... | (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 2018 Jose Cambronero and Phillip Stanley-Marbell
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, mod... |
# 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 2018 Jose Cambronero and Phillip Stanley-Marbell
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, mod... |
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 | # Copyright 2018 Jose Cambronero and Phillip Stanley-Marbell
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, mod... | """
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 | package retryable
import (
"bytes"
"context"
"sync"
// crypto libraries included for go-digest
_ "crypto/sha256"
_ "crypto/sha512"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
digest "github.com/opencontainers/go-digest"
"github.com/sirupsen/logrus"
)
// Retryable is... |
// 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 | package retryable
import (
"bytes"
"context"
"sync"
// crypto libraries included for go-digest
_ "crypto/sha256"
_ "crypto/sha512"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
digest "github.com/opencontainers/go-digest"
"github.com/sirupsen/logrus"
)
// Retryable is... |
// 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()
if httpErr != nil {
req.r.backoffSet(nil)
req.nextURL(true)
continue
}
// check the response
lastURL ... | {
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 | package retryable
import (
"bytes"
"context"
"sync"
// crypto libraries included for go-digest
_ "crypto/sha256"
_ "crypto/sha512"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
digest "github.com/opencontainers/go-digest"
"github.com/sirupsen/logrus"
)
// Retryable is... | () error {
// if no responses, error
if req.reader == nil || len(req.responses) == 0 {
return ErrNotFound
}
// pass through close to last request, mark as done
lastResp := req.responses[len(req.responses)-1]
req.done = true
return lastResp.Body.Close()
}
func (req *request) HTTPResponse() *http.Response {
if... | Close | identifier_name |
retryable.go | package retryable
import (
"bytes"
"context"
"sync"
// crypto libraries included for go-digest
_ "crypto/sha256"
_ "crypto/sha512"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
digest "github.com/opencontainers/go-digest"
"github.com/sirupsen/logrus"
)
// Retryable is... | }).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 | #!/usr/bin/env python
# coding: utf-8
# # Analysis on Telcom Customer Churn
# Context:
# -----------
#
# "Predict behavior to retain customers. You can analyze all relevant customer data and develop focused customer retention programs."
#
# Content:
# ------------
#
# Each row represents a customer, each column c... | 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 | #!/usr/bin/env python
# coding: utf-8
# # Analysis on Telcom Customer Churn
# Context:
# -----------
#
# "Predict behavior to retain customers. You can analyze all relevant customer data and develop focused customer retention programs."
#
# Content:
# ------------
#
# Each row represents a customer, each column c... | 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 | #!/usr/bin/env python
# coding: utf-8
# # Analysis on Telcom Customer Churn
# Context:
# -----------
#
# "Predict behavior to retain customers. You can analyze all relevant customer data and develop focused customer retention programs."
#
# Content:
# ------------
#
# Each row represents a customer, each column c... | ted the services, the churning rate(shown in pink) is not higher with respect to the
#churning rate of people who haven't opted in an overall view
# In[42]:
#univariate crosstab
df_service=df[['OnlineSecurity', 'OnlineBackup', 'DeviceProtection', 'TechSupport',
'StreamingTV', 'StreamingMovies']]
#def crosstab(df_s... | 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 | #!/usr/bin/env python
# coding: utf-8
# # Analysis on Telcom Customer Churn
# Context:
# -----------
#
# "Predict behavior to retain customers. You can analyze all relevant customer data and develop focused customer retention programs."
#
# Content:
# ------------
#
# Each row represents a customer, each column c... |
# 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 | # coding=utf-8
# Copyright 2023 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
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 | # coding=utf-8
# Copyright 2023 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | (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 | # coding=utf-8
# Copyright 2023 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
return tf.concat(boxes_all, axis=0)
def unpack_labels(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 un... | 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 | # coding=utf-8
# Copyright 2023 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | 3),
dtype=tf.bfloat16,
name='image'),
'text':
tf.TensorSpec(
shape=(serving_batch_size, num_classes, text_dim),
dtype=tf.float32,
name='queries'),
}
return predict_fn, input_signatures
def restore_checkpoint... | 'image':
tf.TensorSpec(
shape=(serving_batch_size, _IMAGE_SIZE.value, _IMAGE_SIZE.value, | random_line_split |
old_main.rs | use std::rc::Rc;
use std::slice::Iter;
use glutin_window::GlutinWindow;
use graphics::{Context, line_from_to, triangulation};
use graphics::character::CharacterCache;
use graphics::color::{BLACK, WHITE};
use graphics::Transformed;
use graphics::math::{identity, Matrix2d, Vec2d, scale, translate};
use graphics::types::... | {
current: Option<FloorNodeId>,
last_pointer: Option<Point>
}
impl PointedRoom {
fn new() -> Self {
PointedRoom {
current: None,
last_pointer: None,
}
}
fn forget(&mut self) {
self.current = None;
self.last_pointer = None;
}
fn update(... | PointedRoom | identifier_name |
old_main.rs | use std::rc::Rc;
use std::slice::Iter;
use glutin_window::GlutinWindow;
use graphics::{Context, line_from_to, triangulation};
use graphics::character::CharacterCache;
use graphics::color::{BLACK, WHITE};
use graphics::Transformed;
use graphics::math::{identity, Matrix2d, Vec2d, scale, translate};
use graphics::types::... |
// 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 | use std::rc::Rc;
use std::slice::Iter;
use glutin_window::GlutinWindow;
use graphics::{Context, line_from_to, triangulation};
use graphics::character::CharacterCache;
use graphics::color::{BLACK, WHITE};
use graphics::Transformed;
use graphics::math::{identity, Matrix2d, Vec2d, scale, translate};
use graphics::types::... | 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 | # © Copyright Databand.ai, an IBM Company 2022
# << should be run before import to airflow >>
# otherwise airflow.configuration will fail
# fix AIRFLOW_HOME for all runs
import os
from configparser import ConfigParser
from contextlib import contextmanager
from typing import Optional
from dbnd._core.configuration.p... |
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 | # © Copyright Databand.ai, an IBM Company 2022
# << should be run before import to airflow >>
# otherwise airflow.configuration will fail
# fix AIRFLOW_HOME for all runs
import os
from configparser import ConfigParser
from contextlib import contextmanager
from typing import Optional
from dbnd._core.configuration.p... | 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 = _process_cfg(fo... | has_marker_file( | identifier_name |
environ_config.py | # © Copyright Databand.ai, an IBM Company 2022
# << should be run before import to airflow >>
# otherwise airflow.configuration will fail
# fix AIRFLOW_HOME for all runs
import os
from configparser import ConfigParser
from contextlib import contextmanager
from typing import Optional
from dbnd._core.configuration.p... | return False, None
def __find_dbnd_home_at(folder):
dbnd_home, config_file = _process_cfg(folder)
if dbnd_home:
dbnd_log_init_msg(
"Found dbnd home by at %s, by config file: %s" % (dbnd_home, config_file)
)
return dbnd_home
dbnd_home, marker_file = _has_marker_file... | return folder, file_path
| random_line_split |
environ_config.py | # © Copyright Databand.ai, an IBM Company 2022
# << should be run before import to airflow >>
# otherwise airflow.configuration will fail
# fix AIRFLOW_HOME for all runs
import os
from configparser import ConfigParser
from contextlib import contextmanager
from typing import Optional
from dbnd._core.configuration.p... | 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 | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use std::fmt::{Displa... | (os error 8)"
.to_string()
);
init_vcpu(&vcpu.fd, vm.fd());
let state = vcpu.save_state().expect("Cannot save state of vcpu");
assert!(!state.regs.is_empty());
vcpu.restore_state(&state)
.expect("Cannot restore state of vcpu");
le... | "Failed to restore the state of the vcpu: Failed to set register: Exec format error \ | random_line_split |
aarch64.rs | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use std::fmt::{Displa... | (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 | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use std::fmt::{Displa... |
/// 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 | // Copyright (c) 2021 Thomas J. Otterson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Note that the imports for std::rc::Rc, std::cell::RefCell, and
// crate::components::pin::Pin are only necessary because of the demo non-macro constructor
// function.
/// Pin assi... | assert!(low!(tr[Y6]), "Y6 should be low when A6 is high");
}
#[test]
fn input_low() {
let (_, tr) = before_each();
clear!(tr[A1]);
assert!(high!(tr[Y1]), "Y1 should be high when A1 is low");
clear!(tr[A2]);
assert!(high!(tr[Y2]), "Y2 should be high when A2 ... | assert!(low!(tr[Y5]), "Y5 should be low when A5 is high");
set!(tr[A6]); | random_line_split |
ic7406.rs | // Copyright (c) 2021 Thomas J. Otterson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Note that the imports for std::rc::Rc, std::cell::RefCell, and
// crate::components::pin::Pin are only necessary because of the demo non-macro constructor
// function.
/// Pin assi... |
}
}
}
#[cfg(test)]
mod test {
use crate::{components::trace::Trace, test_utils::make_traces};
use super::*;
fn before_each() -> (DeviceRef, RefVec<Trace>) {
let chip = Ic7406::new();
let tr = make_traces(&chip);
(chip, tr)
}
#[test]
fn input_high() {
... | {} | conditional_block |
ic7406.rs | // Copyright (c) 2021 Thomas J. Otterson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Note that the imports for std::rc::Rc, std::cell::RefCell, and
// crate::components::pin::Pin are only necessary because of the demo non-macro constructor
// function.
/// Pin assi... |
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 | // Copyright (c) 2021 Thomas J. Otterson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Note that the imports for std::rc::Rc, std::cell::RefCell, and
// crate::components::pin::Pin are only necessary because of the demo non-macro constructor
// function.
/// Pin assi... | () {
let (_, tr) = before_each();
set!(tr[A1]);
assert!(low!(tr[Y1]), "Y1 should be low when A1 is high");
set!(tr[A2]);
assert!(low!(tr[Y2]), "Y2 should be low when A2 is high");
set!(tr[A3]);
assert!(low!(tr[Y3]), "Y3 should be low when A3 is high");
... | input_high | identifier_name |
render.go | package mustache
import (
"fmt"
"html"
"math"
"reflect"
"strconv"
"strings"
"github.com/eriklott/mustache/internal/ast"
"github.com/eriklott/mustache/internal/parse"
)
const maxPartialDepth = 100000
// renderer represents the state of the rendering of a single template.
type renderer struct {
template *Tem... | (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 | package mustache
import (
"fmt"
"html"
"math"
"reflect"
"strconv"
"strings"
"github.com/eriklott/mustache/internal/ast"
"github.com/eriklott/mustache/internal/parse"
)
const maxPartialDepth = 100000
// renderer represents the state of the rendering of a single template.
type renderer struct {
template *Tem... |
}
return v
}
// lookup returns a value by key from the context. If a value
// was not found, the reflect.Value zero type is returned.
func lookupKeyContext(key string, ctx reflect.Value) reflect.Value {
if key == "." {
return ctx
}
// check context for method by name
if ctx.IsValid() {
method := ctx.Method... | {
break
} | conditional_block |
render.go | package mustache
import (
"fmt"
"html"
"math"
"reflect"
"strconv"
"strings"
"github.com/eriklott/mustache/internal/ast"
"github.com/eriklott/mustache/internal/parse"
)
const maxPartialDepth = 100000
// renderer represents the state of the rendering of a single template.
type renderer struct {
template *Tem... |
// lookup a key in the context stack. If a value was not found, the reflect.Value zero
// type is returned.
func (r *renderer) lookup(name string, ln, col int, key []string) (reflect.Value, error) {
v := lookupKeysStack(key, r.stack)
if !v.IsValid() && r.template.ContextErrorsEnabled {
return v, fmt.Errorf("%s:%d... | {
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 | package mustache
import (
"fmt"
"html"
"math"
"reflect"
"strconv"
"strings"
"github.com/eriklott/mustache/internal/ast"
"github.com/eriklott/mustache/internal/parse"
)
const maxPartialDepth = 100000
// renderer represents the state of the rendering of a single template.
type renderer struct {
template *Tem... | case reflect.Map:
return ctx.MapIndex(reflect.ValueOf(key))
case reflect.Struct:
return ctx.FieldByName(key)
default:
return reflect.Value{}
}
} | return lookupKeyContext(key, indirect(ctx)) | random_line_split |
utils.go | /*
Copyright 2015-2020 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,... |
// 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 | /*
Copyright 2015-2020 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,... | () 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 | /*
Copyright 2015-2020 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,... | 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 | /*
Copyright 2015-2020 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,... |
return trace.ConvertSystemError(err)
}
return nil
}
// ReadOrMakeHostUUID looks for a hostid file in the data dir. If present,
// returns the UUID from it, otherwise generates one
func ReadOrMakeHostUUID(dataDir string) (string, error) {
id, err := ReadHostUUID(dataDir)
if err == nil {
return id, nil
}
if !... | {
//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 | use std::collections::HashMap;
use std::fs;
use wgpu::util::DeviceExt;
use crate::texture::Texture;
pub struct Graphics {
pub surface: wgpu::Surface,
pub device: wgpu::Device,
pub queue: wgpu::Queue,
pub swap_chain_descriptor: wgpu::SwapChainDescriptor,
pub swap_chain: wgpu::SwapChain,
pub size... |
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 | use std::collections::HashMap;
use std::fs;
use wgpu::util::DeviceExt;
use crate::texture::Texture;
pub struct Graphics {
pub surface: wgpu::Surface,
pub device: wgpu::Device,
pub queue: wgpu::Queue,
pub swap_chain_descriptor: wgpu::SwapChainDescriptor,
pub swap_chain: wgpu::SwapChain,
pub size... | let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Texture {
... | };
let swap_chain = device.create_swap_chain(&surface, &swap_chain_descriptor);
| random_line_split |
graphics.rs | use std::collections::HashMap;
use std::fs;
use wgpu::util::DeviceExt;
use crate::texture::Texture;
pub struct Graphics {
pub surface: wgpu::Surface,
pub device: wgpu::Device,
pub queue: wgpu::Queue,
pub swap_chain_descriptor: wgpu::SwapChainDescriptor,
pub swap_chain: wgpu::SwapChain,
pub size... | {
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 | /* Timetable for Lille local transport Module */
/* Module: MMM-Ilevia-Lille
*
* By Jérémy PALAFFRE (Jilano5)
* based on a script from normyx (https://github.com/normyx/MMM-Nantes-TAN)
* MIT Licensed.
*/
Module.register("MMM-Ilevia-Lille",{
// Define module defaults
defaults: {
updateInterval: 2 * 60 * 1000,... | 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 | /* Timetable for Lille local transport Module */
/* Module: MMM-Ilevia-Lille
*
* By Jérémy PALAFFRE (Jilano5)
* based on a script from normyx (https://github.com/normyx/MMM-Nantes-TAN)
* MIT Licensed.
*/
Module.register("MMM-Ilevia-Lille",{
// Define module defaults
defaults: {
updateInterval: 2 * 60 * 1000,... | 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 | import argparse
import os
import sys
import shutil
import time
import random
import glob
import logging
import copy
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.... | (loader, model, lenlist, num):
model.train()
for m in model.modules():
if isinstance(m, torch.nn.BatchNorm2d):
m.running_mean.data.fill_(0)
m.running_var.data.fill_(0)
m.num_batches_tracked.data.zero_()
m.momentum = None
for i, (input, _) in enumerate(... | calibrate_bn | identifier_name |
test_supernet.py | import argparse
import os
import sys
import shutil
import time
import random
import glob
import logging
import copy
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.... |
return new_loader
def calibrate_bn(loader, model, lenlist, num):
model.train()
for m in model.modules():
if isinstance(m, torch.nn.BatchNorm2d):
m.running_mean.data.fill_(0)
m.running_var.data.fill_(0)
m.num_batches_tracked.data.zero_()
m.momentum =... | new_loader.append((x.cuda(), y.cuda())) | conditional_block |
test_supernet.py | import argparse
import os
import sys
import shutil
import time
import random
import glob
import logging
import copy
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.... | def validate(valid_queue, model, lenlist):
"""
Run evaluation
"""
# switch to evaluate mode
top1 = AverageMeter()
model.eval()
with torch.no_grad():
for i, (input, target) in enumerate(valid_queue):
input_var = input
target_var = target
# comput... | random_line_split | |
test_supernet.py | import argparse
import os
import sys
import shutil
import time
import random
import glob
import logging
import copy
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.... |
def validate(valid_queue, model, lenlist):
"""
Run evaluation
"""
# switch to evaluate mode
top1 = AverageMeter()
model.eval()
with torch.no_grad():
for i, (input, target) in enumerate(valid_queue):
input_var = input
target_var = target
# com... | 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 | /**
* Created by cp on 2017/8/14.
*/
var pageSize = 8; //每页显示的记录条数
var curPage = 1; //显示第curPage页
var len; //总行数
var page; //总页数
var arry = {};
var saveUrl = "orderSave";
var updateUrl = "orderUpdate";
var deleteUrl = "orderDelete";
var listUrl ="orders";
$(function () {
;
//获取表头及搜索
//get... | =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 | /**
* Created by cp on 2017/8/14.
*/
var pageSize = 8; //每页显示的记录条数
var curPage = 1; //显示第curPage页
var len; //总行数
var page; //总页数
var arry = {};
var saveUrl = "orderSave";
var updateUrl = "orderUpdate";
var deleteUrl = "orderDelete";
var listUrl ="orders";
$(function () {
;
//获取表头及搜索
//get... | success: function (contact) {
var page=contact % pageSize==0 ? contact/pageSize : Math.floor(contact/pageSize)+1;
countpage = page;
$("#pageSum").val(countpage);
}
})
data[ "pagenow"] = pagenow;
data[ "pagesize"] = pageSize;
$.ajax({
url: list... | // // 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 | /**
* Created by cp on 2017/8/14.
*/
var pageSize = 8; //每页显示的记录条数
var curPage = 1; //显示第curPage页
var len; //总行数
var page; //总页数
var arry = {};
var saveUrl = "orderSave";
var updateUrl = "orderUpdate";
var deleteUrl = "orderDelete";
var listUrl ="orders";
$(function () {
;
//获取表头及搜索
//get... | 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 | /**
* Created by cp on 2017/8/14.
*/
var pageSize = 8; //每页显示的记录条数
var curPage = 1; //显示第curPage页
var len; //总行数
var page; //总页数
var arry = {};
var saveUrl = "orderSave";
var updateUrl = "orderUpdate";
var deleteUrl = "orderDelete";
var listUrl ="orders";
$(function () {
;
//获取表头及搜索
//get... | //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 | //! [](https://docs.rs/petgraph-graphml/)
//! [](https://crates.io/crates/petgraph-graphml/)
//! [](htt... | .attr("id", &*attr.name)
.attr("for", attr.for_.to_str())
.attr("attr.name", &*attr.name)
.attr("attr.type", "string"),
)?;
writer.write(XmlEvent::end_element())?; // end key
}
Ok(())
}
}
impl<G>... | XmlEvent::start_element("key") | random_line_split |
lib.rs | //! [](https://docs.rs/petgraph-graphml/)
//! [](https://crates.io/crates/petgraph-graphml/)
//! [](htt... | else {
"undirected"
},
))?;
// Emit nodes
for node in self.graph.node_references() {
writer.write(XmlEvent::start_element("node").attr("id", &*node2str_id(node.id())))?;
// Print weights
if let Some(ref node_labels) = self.export_... | {
"directed"
} | conditional_block |
lib.rs | //! [](https://docs.rs/petgraph-graphml/)
//! [](https://crates.io/crates/petgraph-graphml/)
//! [](htt... |
/// 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 | //! [](https://docs.rs/petgraph-graphml/)
//! [](https://crates.io/crates/petgraph-graphml/)
//! [](htt... | (&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GraphMl")
.field("graph", &self.graph)
.field("pretty_print", &self.pretty_print)
.field("export_edges", &self.export_edges.is_some())
.field("export_nodes", &self.export_nodes.is_some(... | fmt | identifier_name |
main.rs | #![feature(rustc_private)]
extern crate im;
extern crate pretty;
extern crate rustc_ast;
extern crate rustc_driver;
extern crate rustc_errors;
extern crate rustc_hir;
extern crate rustc_interface;
extern crate rustc_metadata;
extern crate rustc_middle;
extern crate rustc_session;
extern crate rustc_span;
mod ast_to_ru... | .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 | #![feature(rustc_private)]
extern crate im;
extern crate pretty;
extern crate rustc_ast;
extern crate rustc_driver;
extern crate rustc_errors;
extern crate rustc_hir;
extern crate rustc_interface;
extern crate rustc_metadata;
extern crate rustc_middle;
extern crate rustc_session;
extern crate rustc_span;
mod ast_to_ru... | {
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 | #![feature(rustc_private)]
extern crate im;
extern crate pretty;
extern crate rustc_ast;
extern crate rustc_driver;
extern crate rustc_errors;
extern crate rustc_hir;
extern crate rustc_interface;
extern crate rustc_metadata;
extern crate rustc_middle;
extern crate rustc_session;
extern crate rustc_span;
mod ast_to_ru... | , usize> {
pretty_env_logger::init();
log::debug!(" --- hacspec");
let mut args = env::args().collect::<Vec<String>>();
log::trace!(" args: {:?}", args);
// Args to pass to the compiler
let mut compiler_args = Vec::new();
// Drop and pass along binary name.
compiler_args.push(args.... | {
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 | package local_get
import (
"fmt"
"github.com/creativesoftwarefdn/weaviate/database/schema"
"github.com/creativesoftwarefdn/weaviate/database/schema/kind"
common "github.com/creativesoftwarefdn/weaviate/graphqlapi/common_resolver"
"github.com/creativesoftwarefdn/weaviate/graphqlapi/local/common_filters"
"github.c... |
// Builds the classes below a Local -> Get -> (k kind.Kind)
func buildGetClasses(dbSchema *schema.Schema, k kind.Kind, semanticSchema *models.SemanticSchema, knownClasses *map[string]*graphql.Object) (*graphql.Object, error) {
classFields := graphql.Fields{}
var kindName string
switch k {
case kind.THING_KIND:
... | {
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 | package local_get
import (
"fmt"
"github.com/creativesoftwarefdn/weaviate/database/schema"
"github.com/creativesoftwarefdn/weaviate/database/schema/kind"
common "github.com/creativesoftwarefdn/weaviate/graphqlapi/common_resolver"
"github.com/creativesoftwarefdn/weaviate/graphqlapi/local/common_filters"
"github.c... | 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 | package local_get
import (
"fmt"
"github.com/creativesoftwarefdn/weaviate/database/schema"
"github.com/creativesoftwarefdn/weaviate/database/schema/kind"
common "github.com/creativesoftwarefdn/weaviate/graphqlapi/common_resolver"
"github.com/creativesoftwarefdn/weaviate/graphqlapi/local/common_filters"
"github.c... | (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 | package local_get
import (
"fmt"
"github.com/creativesoftwarefdn/weaviate/database/schema"
"github.com/creativesoftwarefdn/weaviate/database/schema/kind"
common "github.com/creativesoftwarefdn/weaviate/graphqlapi/common_resolver"
"github.com/creativesoftwarefdn/weaviate/graphqlapi/local/common_filters"
"github.c... |
properties = append(properties, property)
}
return properties, nil
}
| {
// 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 | // Copyright 2016-2018 The grok_exporter Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law o... |
if !found {
return fmt.Errorf("Invalid metric configuration: '%v' cannot be used as a delete_label, because the metric does not have a label named '%v'.", deleteLabelTemplate.Name(), deleteLabelTemplate.Name())
}
}
// InitTemplates() validates that labels/delete_labels/value are present as grok_fields in the ... | {
if deleteLabelTemplate.Name() == labelTemplate.Name() {
found = true
break
}
} | conditional_block |
configV2.go | // Copyright 2016-2018 The grok_exporter Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law o... |
func (cfg *Config) marshalToString() string {
out, err := yaml.Marshal(cfg)
if err != nil {
return fmt.Sprintf("ERROR: Failed to marshal config: %v", err.Error())
}
result := string(out)
// Pretend fail_on_missing_logfile is a boolean, remove quotes
result = strings.Replace(result, "fail_on_missing_logfile: \... | {
result, _ := Unmarshal([]byte(cfg.marshalToString()))
return result
} | identifier_body |
configV2.go | // Copyright 2016-2018 The grok_exporter Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law o... | case "histogram":
hasValue, cumulativeAllowed, bucketsAllowed, quantilesAllowed = true, false, true, false
case "summary":
hasValue, cumulativeAllowed, bucketsAllowed, quantilesAllowed = true, false, false, true
default:
return fmt.Errorf("Invalid 'metrics.type': '%v'. We currently only support 'counter' and '... | 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 | // Copyright 2016-2018 The grok_exporter Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law o... | () 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 | /**日期比较
支持两个日期之间的比较(>,<,=),支持直接传入固定日期进行对比
param:string || {type:"<",format:"ymd",object:null} || json
*/
jQuery.validator.addMethod("compareDate", function (value, element, param) {
var elseDate = $.type(param) == "object" ? param.object : param;
if (!value) return true;
var _type = param.type == "... | validator.prepareElement(element);
validator.formSubmitted = submitted;
validator.successList.push(element);
validator.showErrors();
} else {
var errors = {};
if (!param.objID)
... | var valid = response === true;
if (valid) {
var submitted = validator.formSubmitted; | random_line_split |
jQuery-Validate-Extend.js | /**日期比较
支持两个日期之间的比较(>,<,=),支持直接传入固定日期进行对比
param:string || {type:"<",format:"ymd",object:null} || json
*/
jQuery.validator.addMethod("compareDate", function (value, element, param) {
var elseDate = $.type(param) == "object" ? param.object : param;
if (!value) return true;
var _type = param.type == "... | ;
} 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 | """
Skimmer for ParticleNet tagger inputs.
Author(s): Cristina Mantilla Suarez, Raghav Kansal
"""
import os
import pathlib
import warnings
from typing import Dict
import awkward as ak
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import uproot
from coffea.analysis_tools impo... |
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 | """
Skimmer for ParticleNet tagger inputs.
Author(s): Cristina Mantilla Suarez, Raghav Kansal
"""
import os
import pathlib
import warnings
from typing import Dict
import awkward as ak
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import uproot
from coffea.analysis_tools impo... |
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 | """
Skimmer for ParticleNet tagger inputs.
Author(s): Cristina Mantilla Suarez, Raghav Kansal
"""
import os
import pathlib
import warnings
from typing import Dict
import awkward as ak
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import uproot
from coffea.analysis_tools impo... | (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 | """
Skimmer for ParticleNet tagger inputs.
Author(s): Cristina Mantilla Suarez, Raghav Kansal
"""
import os
import pathlib
import warnings
from typing import Dict
import awkward as ak
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import uproot
from coffea.analysis_tools impo... |
# 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 | /**
* @module system-npm/utils
*
* Helpers that are used by npm-extension and the npm plugin.
* This should be kept small and not have helpers exclusive to npm.
* However, it can have all npm-extension helpers.
*/
// A regex to test if a moduleName is npm-like.
var slice = Array.prototype.slice;
var npmModuleReg... | 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 | /**
* @module system-npm/utils
*
* Helpers that are used by npm-extension and the npm plugin.
* This should be kept small and not have helpers exclusive to npm.
* However, it can have all npm-extension helpers.
*/
// A regex to test if a moduleName is npm-like.
var slice = Array.prototype.slice;
var npmModuleReg... |
module.exports = utils;
| {
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 | /**
* @module system-npm/utils
*
* Helpers that are used by npm-extension and the npm plugin.
* This should be kept small and not have helpers exclusive to npm.
* However, it can have all npm-extension helpers.
*/
// A regex to test if a moduleName is npm-like.
var slice = Array.prototype.slice;
var npmModuleReg... |
// 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 | /**
* @module system-npm/utils
*
* Helpers that are used by npm-extension and the npm plugin.
* This should be kept small and not have helpers exclusive to npm.
* However, it can have all npm-extension helpers.
*/
// A regex to test if a moduleName is npm-like.
var slice = Array.prototype.slice;
var npmModuleReg... | (input) {
var output = [];
input.replace(/^(\.\.?(\/|$))+/, '')
.replace(/\/(\.(\/|$))+/g, '/')
.replace(/\/\.\.$/, '/../')
.replace(/\/?[^\/]*/g, function (p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
return output.join('').replace... | removeDotSegments | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.