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 |
|---|---|---|---|---|
size_cache_fs.go | ()
// check if we aren't already inside
node := u.files.GetByKey(info.Path)
if node != nil {
file := node.Value.(*cacheFile)
u.currSize -= file.Size
}
// while we can pop files and the cache is full..
for u.currSize > 0 && u.currSize+info.Size > u.cacheSize {
node := u.files.PopMin()
// node CAN'T be nil... | OpenFile | identifier_name | |
ikey.js | 8-4360
*/
/**
* Allows you to resort elements within a sortable container by using the keyboard. Requires
* the Draggables, Droppables and Sortables interface plugins. The container and each item inside
* the container must have an ID. Sortables are especially useful for lists.
*
* @see Plugins/Interface/Dragga... |
else if (!wrap) {
jQuery(target).after(jQuery.iKey.focusedNode);
}
else {
jQuery(target).before(jQuery.iKey.focusedNode);
}
},
/**
* Process up arrow events
*/
handleUpAction : function(isCtrl, event) {
var target = jQuery(jQuery.iKey.focusedNode).prev();
var wrap = false;
if (!target ||... | {
this.focusNode(target, event);
} | conditional_block |
ikey.js | 78-4360
*/
/**
* Allows you to resort elements within a sortable container by using the keyboard. Requires
* the Draggables, Droppables and Sortables interface plugins. The container and each item inside
* the container must have an ID. Sortables are especially useful for lists.
*
* @see Plugins/Interface/Dragg... | dhe.css('-khtml-user-select', 'none');
| }
else {
dhe.css('-moz-user-select', 'none');
dhe.css('user-select', 'none'); | random_line_split |
b_get_data.py | pd.set_option('display.width', 200)
def get_data(file):
'file = full path of the original file. obter os dataframes dos ficheiros'
df = pd.read_csv(file, sep=';')
df = time_transform(df)
df = timestamp_round_down(df)
df = df.bfill()
return df
def logs_cols_uniform(df):
'A partir de uma lis... | from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import roc_auc_score, accuracy_score, log_loss, roc_curve, precision_score, recall_score,confusion_matrix,f1_score,fbeta_score, make_scorer
| random_line_split | |
b_get_data.py | =[]
for i in col:
if component in i:
pair_comp_col.append(i)
return pair_comp_col
def component_df_creation(df):
# Retornar dataframes por tipo de componente
time_id = ['Timestamp', 'Turbine_ID']
pair_hyd = component('Hyd', df.columns)
pair_trafo = component('Trafo', df.colu... | rbines_list):
df_ = pd.DataFrame(columns=df.columns, dtype='int64')
for turbine in turbines_list:
df1 = df.loc[df['Turbine_ID']==turbine]
if df1['Component'].nunique()>1:
index = df1[df1['Component']==1]
index['date'] = index['Timestamp']
index = index[['date'... | _by_turbine(df, tu | identifier_name |
b_get_data.py | =[]
for i in col:
if component in i:
pair_comp_col.append(i)
return pair_comp_col
def component_df_creation(df):
# Retornar dataframes por tipo de componente
time_id = ['Timestamp', 'Turbine_ID']
pair_hyd = component('Hyd', df.columns)
pair_trafo = component('Trafo', df.colu... | or_av_cols = [nm+'_av' for nm in sensor_cols]
sensor_sd_cols = [nm+'_sd' for nm in sensor_cols]
df_out = pd.DataFrame()
ws = rolling_win_size
#calculate rolling stats for each engine id
for m_id in pd.unique(df_in.Turbine_ID):
# get a subset for each engine sensors
df_engine = d... | s.append(i)
sens | conditional_block |
b_get_data.py | _col=[]
for i in col:
if component in i:
pair_comp_col.append(i)
return pair_comp_col
def component_df_creation(df):
# Retornar dataframes por tipo de componente
time_id = ['Timestamp', 'Turbine_ID']
pair_hyd = component('Hyd', df.columns)
pair_trafo = component('Trafo', df.... | features(df_in, rolling_win_size=15):
"""Add rolling average and rolling standard deviation for sensors readings using fixed rolling window size.
"""
cols =['Turbine_ID', 'Date', 'TTF', '60_days', 'Component']
other_cols = []
for i in df_in.columns:
if i not in cols:
other_cols.a... | para agregar o data-frame pela medida de tempo pretendida, periodo _Dia_ ou _Hora_'
if period == 'Dia':
df['Date'] = df['Timestamp'].dt.date
elif period == 'Hora':
df['Date'] = df.apply(lambda x: x['Timestamp'] - datetime.timedelta(hours=x['Timestamp'].hour % -1, minutes=x['Timestamp'].minute, ... | identifier_body |
main.go | .Values["user"]
fmt.Println("val",val)
user, ok := val.(User)
if !ok {
fmt.Println("did not find user session")
return User{Authenticated: false}
}
fmt.Println(val.(User))
fmt.Println("user.username",user.Username)
return user
}
//if basic auth headers exists, proceed to pass request to services
//if not, ch... |
func AddUser( w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
res , _ := database.Exec("INSERT INTO users(username,password) VALUES (?,?)",username,password)
fmt.Println(res)
fmt.Fprintf(w, "User successfully added")
http.Redirect(w, r, "/", http.... | {
session, err := store.Get(r, "cookie-name")
if err != nil {
}
user := getUser(session)
fmt.Println("[serving main page]",user)
tpl.ExecuteTemplate(w, "index.gohtml", user)
} | identifier_body |
main.go | //w.Header().Set("WWW-Authenticate", `Basic realm="Please enter your username and password for this site"`)
//w.WriteHeader(401)
//w.Write([]byte("Unauthorised.\n"))
//w.Write([]byte("checking session instead.\n"))
session, err := store.Get(r, "cookie-name")
if err != nil {
http.Error(w, err.Error... | }
return dbUser.Password
} | random_line_split | |
main.go | correctPassword
}
func index(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, "cookie-name")
if err != nil {
}
user := getUser(session)
fmt.Println("[serving main page]",user)
tpl.ExecuteTemplate(w, "index.gohtml", user)
}
func AddUser( w http.ResponseWriter, r *http.Request) {
username :=... | initDB | identifier_name | |
main.go | (w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Printf("You don't have access!")
http.Redirect(w, r, "/forbidden", http.StatusFound)
return
}
fmt.Println("authenticated via user session")
handler(w, r)
return
}
fmt.Println("authenticated via basic auth")
handler(w, r... | {
if b == a {
return true
}
} | conditional_block | |
alpha_beta.py | pe = self.coupeSuivante(idCoupe)
if (idCoupe != coupeInitiale): #On ne redistribue pas dans la coupelle initiale
self.plateau[idCoupe] += 1
nGraines -= 1
coupeFinale = idCoupe
joueurCoupeFinale = self.joueurCoupe(coupeFinale)
if (joueu... | #si aucun coup n'est possible cette fonction arrête aussi la partie
coupesPossibles = self.coupesAdmissibles(self.tour)
if (self.profondeur == self.profondeurMinimax or self.finie): #cas de base
self.value = self.evaluation(joueurMaximisant)
return self.valu... | identifier_body | |
alpha_beta.py | /zoom/cours/Cours/IA_Jeux/IAEtJeux2.pdf
#Code par Léo et Paul
#Pb: le jeu peut boucler à l'infini à la fin d'une partie (souvent lorsqu'il reste 2 graines disposées symétriquement)
# -> se pencher sur la fonction "partieFinie" et peut-être essayer d'intégrer cette fonction dans l'algo récursif minimax..
#Pb: struct... | #on commence par la coupe la plus proche de l'adversaire (dans le sens trigo)
idCoupe = (self.nCoupes*(joueur+1))-1
distance = 1
while (self.joueurCoupe(idCoupe)==joueur):
#s'il y a plus de graines dans idCoupe que la distance qui la sépare aux coupes de l'adversaire
... | coupesAdmissibles = []
| random_line_split |
alpha_beta.py | .fr/zoom/cours/Cours/IA_Jeux/IAEtJeux2.pdf
#Code par Léo et Paul
#Pb: le jeu peut boucler à l'infini à la fin d'une partie (souvent lorsqu'il reste 2 graines disposées symétriquement)
# -> se pencher sur la fonction "partieFinie" et peut-être essayer d'intégrer cette fonction dans l'algo récursif minimax..
#Pb: str... | .grainesRestantesJoueur(adversaire) == 0:
coupesAdmissibles = self.coupesAdmissiblesNourrir(joueur)
#si aucun coup ne peut être joué pour nourrir l'adversaire
if len(coupesAdmissibles)==0:
self.scores[joueur] += self.grainesRestantes()
self.platea... |
if self | identifier_name |
alpha_beta.py | /zoom/cours/Cours/IA_Jeux/IAEtJeux2.pdf
#Code par Léo et Paul
#Pb: le jeu peut boucler à l'infini à la fin d'une partie (souvent lorsqu'il reste 2 graines disposées symétriquement)
# -> se pencher sur la fonction "partieFinie" et peut-être essayer d'intégrer cette fonction dans l'algo récursif minimax..
#Pb: struct... | mpte le nombre de graines restantes sur le plateau
def grainesRestantes(self):
return np.sum(self.plateau)
#on compte le nombre de graines restantes sur le plateau pour les coupes de joueur
def grainesRestantesJoueur(self,joueur):
if joueur==0:
return np.sum(self.plateau[0... | while (self.joueurCoupe(idCoupe)==joueurCoupeFinale and self.coupePrenable(idCoupe)):
self.scores[joueur]+=self.plateau[idCoupe]
self.plateau[idCoupe]=0
idCoupe = self.coupePrecedente(idCoupe)
#si on va affamer l'adversaire :
... | conditional_block |
minilab.py | ed_dirs = []
Host.__init__(self, name, inNamespace, **kwargs)
def list_processes(self):
process_list = []
my_ns_symlink = '/proc/%s/ns/net' % self.pid
for symlink in glob.glob('/proc/[1-9]*/ns/net'):
pid = None
try:
if os.path.samefile(my_ns_... |
def copy_auth_keys(self):
ssh_dir = os.path.join(self.root_dir, 'root/.ssh')
if not os.path.exists(ssh_dir):
os.mkdir(ssh_dir, 0700)
key_file = open(self.auth_keys)
destination = open(os.path.join(ssh_dir, 'authorized_keys'), 'wb')
destination.write(key_file.rea... | return self.ssh_template.render(pid_file=self.ssh_pid_file,
host_dir=self.root_dir) | random_line_split |
minilab.py | ed_dirs = []
Host.__init__(self, name, inNamespace, **kwargs)
def list_processes(self):
process_list = []
my_ns_symlink = '/proc/%s/ns/net' % self.pid
for symlink in glob.glob('/proc/[1-9]*/ns/net'):
pid = None
try:
if os.path.samefile(my_ns_... |
def set_oob_switch_standalone(topology):
if 'nat' in topology:
switch = topology['nat']['switch']['name']
cmd = shlex.split("ovs-vsctl set-fail-mode %s standalone " % switch)
subprocess.call(cmd)
cmd2 = shlex.split("ovs-vsctl del-controller %s" % switch)
subprocess.call(c... | """ force protocols versions as mininet < 2.2.0 is not doing its job"""
for switch in topology['switches']:
if 'protocols' in switch:
protocols = ','.join(switch['protocols'])
else:
protocols = 'OpenFlow10'
cmd = "ovs-vsctl set Bridge %s protocols=%s" % (switch['nam... | identifier_body |
minilab.py | ed_dirs = []
Host.__init__(self, name, inNamespace, **kwargs)
def list_processes(self):
process_list = []
my_ns_symlink = '/proc/%s/ns/net' % self.pid
for symlink in glob.glob('/proc/[1-9]*/ns/net'):
pid = None
try:
if os.path.samefile(my_ns_... | (net, topology):
switches = {}
info('*** Adding switches\n')
# first loop : create switches
for switch in topology['switches']:
if 'protocols' in switch:
protocols = ','.join(switch['protocols'])
else:
protocols = 'OpenFlow10'
switches[switch['name']] = n... | setup_switches | identifier_name |
minilab.py | ed_dirs = []
Host.__init__(self, name, inNamespace, **kwargs)
def list_processes(self):
process_list = []
my_ns_symlink = '/proc/%s/ns/net' % self.pid
for symlink in glob.glob('/proc/[1-9]*/ns/net'):
pid = None
try:
if os.path.samefile(my_ns_... |
ssh_config = self.create_ssh_config()
host_config_path = os.path.join(self.root_dir,
'etc/ssh/sshd_config')
sshf = open(host_config_path, 'wb')
sshf.write(ssh_config)
sshf.close()
info('**** Starting ssh server on %s\n' % self.n... | self.copy_auth_keys() | conditional_block |
get_samples.py | .csv', 'r', encoding='utf8').readlines()[1:]]
capacity_dict = {}
for e1 in capacity_txt:
for e in e1:
if e == '0': continue
capacity_dict[e] = 0
ca = set(capacity_dict.keys())
intents = set(json.loads(open('./data/intents.txt', 'r', encoding='utf8').readlines()[0]))
diff = intents ^ ca
de... | 0: return m
dp = [[0] * (n + 1) for _ in range(m + 1)] # 初始化dp和边界
for i in range(1, m + 1): dp[i][0] = i
for j in range(1, n + 1): dp[0][j] = j
for i in range(1, m + 1): # 计算dp
for j in range(1, n + 1):
a=word1[i - 1];b=word2[j - 1]
if word1[i - 1] == word2[j - ... | rn n
if n == | identifier_name |
get_samples.py | .csv', 'r', encoding='utf8').readlines()[1:]]
capacity_dict = {}
for e1 in capacity_txt:
for e in e1:
if e == '0': continue
capacity_dict[e] = 0
ca = set(capacity_dict.keys())
intents = set(json.loads(open('./data/intents.txt', 'r', encoding='utf8').readlines()[0]))
diff = intents ^ ca
de... | le(r'\s*[-\*+]\s*(.+)')
txt = open(src_file, 'r', encoding='utf8').readlines()
for line in txt:
if '## intent:' in line:
label = line.strip().split(':')[-1]
else:
match = re.match(item_regex, line)
if match:
item = match.group(1)
... | open(des_file, 'w', encoding='utf8') as f:
for e in txt:
split_text = e.split('\t')
question = filterHtmlTag(split_text[2])
labels = json.loads((split_text[4]))
if len(labels) == 0 or question.strip() == '': continue
qes_set.add(question)
... | identifier_body |
get_samples.py | .csv', 'r', encoding='utf8').readlines()[1:]]
capacity_dict = {}
for e1 in capacity_txt:
for e in e1:
if e == '0': continue
capacity_dict[e] = 0
ca = set(capacity_dict.keys())
intents = set(json.loads(open('./data/intents.txt', 'r', encoding='utf8').readlines()[0]))
diff = intents ^ ca
de... | ))
intersection = set(w1).intersection(w2)
union = set(w1).union(set(w2))
if len(intersection) == 0:
return None
dice_dist = 2 * len(intersection) / len(union)
#edit_distance = min_edit_distance(word1, word2)
return dice_dist #/ (edit_distance + 1e-8)
def get_sample(src_file, d... | d2[j - 1]:
d = 0
else:
d = 1
dp[i][j] = min(dp[i - 1][j - 1] + d, dp[i][j - 1] + 1, dp[i - 1][j] + 1)
return dp[m][n]
def words_sim(word1, word2):
w1 = char_cut(word1); w2 = set(char_cut(word2 | conditional_block |
get_samples.py | id:
label2id[label] = index
index += 1
if label not in label_cnt: label_cnt[label] = 0
label_cnt[label] += 1
qes2label[question].append(label)
if label not in label2qes:
label2qes[label] = []
label2qes[label].append(question)
sorte... | #min_edit_distance('求职', '求职应聘')
#get_sample('./data/q1.res', './data/sen_class_corp666.md')
| random_line_split | |
foreign.rs | py to ALL receive operations
static ref RECV_ACCOUNT: RwLock<Option<String>> = RwLock::new(None);
}
/// get current receive account name
pub fn get_receive_account() -> Option<String> {
RECV_ACCOUNT.read().unwrap().clone()
}
/// get tor proof address
pub fn get_proof_address<'a, T: ?Sized, C, K>(
w: &mut T,
ke... |
/// verify slate messages
pub fn verify_slate_messages(slate: &Slate) -> Result<(), Error> {
slate.verify_messages()
}
/// Receive a tx as recipient
/// Note: key_id & output_amounts needed for secure claims, mwc713.
pub fn receive_tx<'a, T: ?Sized, C, K>(
w: &mut T,
keychain_mask: Option<&SecretKey>,
slate: &Sl... | {
updater::build_coinbase(&mut *w, keychain_mask, block_fees, test_mode)
} | identifier_body |
foreign.rs | allpy to ALL receive operations
static ref RECV_ACCOUNT: RwLock<Option<String>> = RwLock::new(None);
}
/// get current receive account name
pub fn get_receive_account() -> Option<String> {
RECV_ACCOUNT.read().unwrap().clone()
}
/// get tor proof address
pub fn get_proof_address<'a, T: ?Sized, C, K>(
w: &mut T,... | pub fn build_coinbase<'a, T: ?Sized, C, K>(
w: &mut T,
keychain_mask: Option<&SecretKey>,
block_fees: &BlockFees,
test_mode: bool,
) -> Result<CbData, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
updater::build_coinbase(&mut *w, keychain_mask, block_fees, test_mode)
}
/// ve... | })
}
/// Build a coinbase transaction | random_line_split |
foreign.rs | py to ALL receive operations
static ref RECV_ACCOUNT: RwLock<Option<String>> = RwLock::new(None);
}
/// get current receive account name
pub fn get_receive_account() -> Option<String> {
RECV_ACCOUNT.read().unwrap().clone()
}
/// get tor proof address
pub fn get_proof_address<'a, T: ?Sized, C, K>(
w: &mut T,
ke... | () -> Result<VersionInfo, Error> {
// Proof address will be the onion address (Dalec Paublic Key). It is exactly what we need
Ok(VersionInfo {
foreign_api_version: FOREIGN_API_VERSION,
supported_slate_versions: SlateVersion::iter().collect(),
})
}
/// Build a coinbase transaction
pub fn build_coinbase<'a, T: ?S... | check_version | identifier_name |
foreign.rs | py to ALL receive operations
static ref RECV_ACCOUNT: RwLock<Option<String>> = RwLock::new(None);
}
/// get current receive account name
pub fn get_receive_account() -> Option<String> {
RECV_ACCOUNT.read().unwrap().clone()
}
/// get tor proof address
pub fn get_proof_address<'a, T: ?Sized, C, K>(
w: &mut T,
ke... |
tx::update_message(&mut *w, keychain_mask, &ret_slate)?;
let excess = ret_slate.calc_excess(Some(&keychain))?;
if let Some(ref mut p) = ret_slate.payment_proof {
if p.sender_address
.public_key
.eq(&p.receiver_address.public_key)
{
debug!("file proof, replace the receiver address with its address");... | {
// Add our contribution to the offset
ret_slate.adjust_offset(&keychain, &mut context)?;
} | conditional_block |
inventory.pb.go | }
func (m *PkgGroup) String() string { return proto.CompactTextString(m) }
func (*PkgGroup) ProtoMessage() {}
func (*PkgGroup) Descriptor() ([]byte, []int) {
return fileDescriptor_7173caedb7c6ae96, []int{1}
}
func (m *PkgGroup) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_PkgGroup.Unmarshal(m, b)
}
fun... |
func (m *Inventory) GetBootImageName() string {
if m != nil {
return m.BootImageName
}
return ""
}
func (m *Inventory) GetLoadPath() []*PkgInfo {
if m != nil {
return m.LoadPath
}
return nil
}
func (m *Inventory) GetNodeType() uint64 {
if m != nil {
return m.NodeType
}
return 0
}
func (m *Inventory)... | {
if m != nil {
return m.Minor
}
return 0
} | identifier_body |
inventory.pb.go | func (m *Inventory_KEYS) String() string { return proto.CompactTextString(m) }
func (*Inventory_KEYS) ProtoMessage() {}
func (*Inventory_KEYS) Descriptor() ([]byte, []int) {
return fileDescriptor_7173caedb7c6ae96, []int{0}
}
func (m *Inventory_KEYS) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Inventory... | XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Inventory_KEYS) Reset() { *m = Inventory_KEYS{} } | random_line_split | |
inventory.pb.go | }
func (m *PkgGroup) String() string { return proto.CompactTextString(m) }
func (*PkgGroup) ProtoMessage() {}
func (*PkgGroup) Descriptor() ([]byte, []int) {
return fileDescriptor_7173caedb7c6ae96, []int{1}
}
func (m *PkgGroup) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_PkgGroup.Unmarshal(m, b)
}
fun... |
return ""
}
func (m *PkgInfo) GetBuildInformation() string {
if m != nil {
return m.BuildInformation
}
return ""
}
type Inventory struct {
Major uint32 `protobuf:"varint,50,opt,name=major,proto3" json:"major,omitempty"`
Minor uint32 `protobuf:"varint,51,opt,name=mino... | {
return m.Version
} | conditional_block |
inventory.pb.go | {} }
func (m *PkgGroup) String() string { return proto.CompactTextString(m) }
func (*PkgGroup) ProtoMessage() {}
func (*PkgGroup) Descriptor() ([]byte, []int) {
return fileDescriptor_7173caedb7c6ae96, []int{1}
}
func (m *PkgGroup) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_PkgGroup.Unmarshal(m, b)
}
f... | (src proto.Message) {
xxx_messageInfo_PkgGroup.Merge(m, src)
}
func (m *PkgGroup) XXX_Size() int {
return xxx_messageInfo_PkgGroup.Size(m)
}
func (m *PkgGroup) XXX_DiscardUnknown() {
xxx_messageInfo_PkgGroup.DiscardUnknown(m)
}
var xxx_messageInfo_PkgGroup proto.InternalMessageInfo
func (m *PkgGroup) GetDeviceName... | XXX_Merge | identifier_name |
Serigne.py | ".format(train.shape))
print("The test data size after dropping Id feature is : {} ".format(test.shape))
############################################
############ Data Processing ############
################################################
############## Outliers ############
# fig, ax = plt.subplots(... |
############################################################
############## Features engineering ############
# let's first concatenate the train and test data in the same dataframe
ntrain = train.shape[0]
ntest = test.shape[0]
y_train = train.SalePrice.values
all_data = pd.concat((train, test)).reset_index(dro... | # #Get also the QQ-plot
# fig = plt.figure()
# res = stats.probplot(train['SalePrice'], plot=plt)
# plt.show() | random_line_split |
Serigne.py |
warnings.warn = ignore_warn # ignore annoying warning (from sklearn and seaborn)
pd.set_option('display.float_format', lambda x: '{:.3f}'.format(x)) # Limiting floats output to 3 decimal points
# print(check_output(["ls", "../data"]).decode("utf8")) # check the files available in the directory
##########... | pass | identifier_body | |
Serigne.py | (train.shape))
print("The test data size after dropping Id feature is : {} ".format(test.shape))
############################################
############ Data Processing ############
################################################
############## Outliers ############
# fig, ax = plt.subplots()
# ax.sc... |
# BsmtQual, BsmtCond, BsmtExposure, BsmtFinType1 and BsmtFinType2 :
# For all these categorical basement-related features, NaN means that there is no basement
for col in ('BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2'):
all_data[col] = all_data[col].fillna('None')
# MasVnrArea and MasVnr... | all_data[col] = all_data[col].fillna(0) | conditional_block |
Serigne.py | (*args, **kwargs):
pass
warnings.warn = ignore_warn # ignore annoying warning (from sklearn and seaborn)
pd.set_option('display.float_format', lambda x: '{:.3f}'.format(x)) # Limiting floats output to 3 decimal points
# print(check_output(["ls", "../data"]).decode("utf8")) # check the files available ... | ignore_warn | identifier_name | |
main.py | eme zmenit clazz[3] nepojde to lebo tuple sa neda zmenit
den_string = clazz[3]
if not clazz[3] is None:
if den_string == u'štvrtok':
den_string = 'stvrtok'
day = root.find(den_string)
else:
if clazz[0] is not None:
print "Nepodarilo sa ziskat den pre " + clazz... | enerate_xmls( | identifier_name | |
main.py | # Keby chceme zmenit clazz[3] nepojde to lebo tuple sa neda zmenit
den_string = clazz[3]
if not clazz[3] is None:
if den_string == u'štvrtok':
den_string = 'stvrtok'
day = root.find(den_string)
else:
if clazz[0] is not None:
print "Nepodarilo sa ziskat den... |
def get_class_start(title):
# title obsahuje nieco ako "* streda : 14-15 *" - potrebujem dostat len prve cislo
# pretoze aka dlha hodina bude viem z ineho atributu (pozri funkciu get_lessons_of_class, colspan)
# toto mi vrati pole obsahujuce ['streda', '14-15'], vezmem prvy index cize cisla 14-15
zac_... | eturn title['colspan']
| identifier_body |
main.py |
# Keby chceme zmenit clazz[3] nepojde to lebo tuple sa neda zmenit
den_string = clazz[3]
if not clazz[3] is None:
if den_string == u'štvrtok':
den_string = 'stvrtok'
day = root.find(den_string)
else:
if clazz[0] is not None:
print "Nepodarilo sa ziskat de... | zac_hod = title['title'].partition('*')[-1].rpartition('*')[0].replace(" ", "").split(':')[1]
# 1 alebo 15 to je v poriadku
# 1-2 a 9-10 -> v oboch pripadoch chcem len prve cislo (dlzka 3 a 4)
# 12-13 -> tu chcem prve dve cisla (dlzka 5)
if len(zac_hod) == 3 or len(zac_hod) == 4:
return za... | # title obsahuje nieco ako "* streda : 14-15 *" - potrebujem dostat len prve cislo
# pretoze aka dlha hodina bude viem z ineho atributu (pozri funkciu get_lessons_of_class, colspan)
# toto mi vrati pole obsahujuce ['streda', '14-15'], vezmem prvy index cize cisla 14-15 | random_line_split |
main.py | # Keby chceme zmenit clazz[3] nepojde to lebo tuple sa neda zmenit
den_string = clazz[3]
if not clazz[3] is None:
if den_string == u'štvrtok':
den_string = 'stvrtok'
day = root.find(den_string)
else:
if clazz[0] is not None:
print "Nepodarilo sa ziskat den... | return zac_hod
def get_lessons_of_class(url_class):
global hlavicka_dni
print "Ziskavam rozvrh z URL " + url_class
src = requests.get(url_class)
txt = src.text
bsoup = BeautifulSoup(txt, "html.parser")
predmety = []
ucitelia = []
ucebne = []
dni = []
zacina_hod = []
... | eturn zac_hod[0:2]
| conditional_block |
renderer.rs | Vec<PodComplex>;
type PodSlice = [PodComplex];
fn fft_as_pod(my_slice: &FftSlice) -> &PodSlice {
unsafe { std::slice::from_raw_parts(my_slice.as_ptr() as *const _, my_slice.len()) }
}
/// Sent to GPU. Controls FFT layout and options.
#[repr(C)]
#[derive(Copy, Clone)]
struct GpuRenderParameters {
/// Screen s... | sc_desc,
swap_chain,
size,
render_pipeline,
render_parameters,
fft_vec,
render_parameters_buffer: render_param_buffer,
fft_vec_buffer,
bind_group,
})
}
pub fn resize(&mut self, new_size: winit::d... | device,
queue, | random_line_split |
renderer.rs | inclusive.
/// Equals nsamp/2 + 1.
fft_out_size: u32,
}
unsafe impl bytemuck::Zeroable for GpuRenderParameters {}
unsafe impl bytemuck::Pod for GpuRenderParameters {}
/// The longest allowed FFT is ???.
/// The real FFT produces ??? complex bins.
fn fft_out_size(fft_input_size: usize) -> usize {
fft_inpu... | {
self.render_parameters = GpuRenderParameters {
screen_wx: self.size.width,
screen_hy: self.size.height,
..self.render_parameters
};
self.queue.write_buffer(
&self.render_parameters_buffer,
0,
bytemuck::cast_slice(slice::fr... | identifier_body | |
renderer.rs | Vec<PodComplex>;
type PodSlice = [PodComplex];
fn fft_as_pod(my_slice: &FftSlice) -> &PodSlice {
unsafe { std::slice::from_raw_parts(my_slice.as_ptr() as *const _, my_slice.len()) }
}
/// Sent to GPU. Controls FFT layout and options.
#[repr(C)]
#[derive(Copy, Clone)]
struct GpuRenderParameters {
/// Screen s... | (&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
self.size = new_size;
self.sc_desc.width = new_size.width;
self.sc_desc.height = new_size.height;
self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc);
}
pub fn input(&mut self, event: &WindowEvent) ... | resize | identifier_name |
error.rs | trying to open a new connection.
///
/// [`Pool::acquire`]: crate::pool::Pool::acquire
PoolTimedOut(Option<Box<dyn StdError + Send + Sync>>),
/// [`Pool::close`] was called while we were waiting in [`Pool::acquire`].
///
/// [`Pool::acquire`]: crate::pool::Pool::acquire
/// [`Pool::close`]... | #[doc(hidden)]
fn into_box_err(self: Box<Self>) -> Box<dyn StdError + Send + Sync + 'static>;
}
impl dyn DatabaseError {
/// Downcast this `&dyn DatabaseError` to a specific database error type:
///
/// * [PgError][crate::postgres::PgError] (if the `postgres` feature is active)
/// * [MySqlErro... | #[doc(hidden)]
fn as_mut_err(&mut self) -> &mut (dyn StdError + Send + Sync + 'static);
| random_line_split |
error.rs | Error {
#[inline]
fn from(err: async_native_tls::Error) -> Self {
Error::Tls(err.into())
}
}
impl From<TlsError<'_>> for Error {
#[inline]
fn from(err: TlsError<'_>) -> Self {
Error::Tls(err.args.to_string().into())
}
}
impl From<&str> for Error {
fn from(arg: &str) -> Se... | {
Ok(v.to_string())
} | identifier_body | |
error.rs | trying to open a new connection.
///
/// [`Pool::acquire`]: crate::pool::Pool::acquire
PoolTimedOut(Option<Box<dyn StdError + Send + Sync>>),
/// [`Pool::close`] was called while we were waiting in [`Pool::acquire`].
///
/// [`Pool::acquire`]: crate::pool::Pool::acquire
/// [`Pool::close`]... | <DB: Database, T>(expected: DB::TypeInfo) -> Self
where
T: Type<DB>,
{
let ty_name = type_name::<T>();
return decode_err!(
"mismatched types; Rust type `{}` (as SQL type {}) is not compatible with SQL type {}",
ty_name,
T::type_info(),
... | mismatched_types | identifier_name |
emitter.rs | ();
let mut vert_b = verts.next();
let first_point = vert_a.unwrap();
let emit_shape = |a: &[f64; 2], b: &[f64; 2]|
println!(
"{}->addShape(PhysicsShapeEdgeSegment::create(Vec2({:.10}f, {:.10}f), Vec2({:.10}f, {:.10}f)));",
Emitter::varname(id, physi... | parse_rect | identifier_name | |
emitter.rs | "{}->addShape(PhysicsShapeEdgeSegment::create(Vec2({:.10}f, {:.10}f), Vec2({:.10}f, {:.10}f)));",
Emitter::varname(id, physicsbody),
a[0], a[1],
b[0], b[1]
);
while let (Some(a), Some(b)) = (vert_a, vert_b) {
emit_shape(&a, &b);
... | /// Parse a rect with origin at the bottom right (??)
///
pub fn parse_rect(&mut self, attributes: &Vec<xml::attribute::OwnedAttribute>) -> Rect {
// x, y, w, h, style
let mut params = (None, None, None, None, None); | random_line_split | |
emitter.rs | to draw the shape on a cocos2dx DrawNode
fn emit_graphics(&self, id: &str, drawnode: &str, color: Option<&str>);
/// Should generate code for edge segments, and an encompassing shape
///
/// TODO probably also make those generated shapes have certain categories
/// and the encompassing should be a ... |
fn emit_physics(&self, id: &str, physicsbody: &str) {
println!("// Physics for {}", id);
let emit_shape = |a: &[f64; 2], b: &[f64; 2]|
println!(
"{}->addShape(PhysicsShapeEdgeSegment::create(Vec2({:.10}f, {:.10}f), Vec2({:.10}f, {:.10}f)));",
Emitter::v... | {
println!("// Rect for {}", id);
// arguments: origin, destination, color
println!(
"{}->drawSolidRect(Vec2({:.10}f,{:.10}f), Vec2({:.10}f,{:.10}f), {});",
Emitter::varname(id, drawnode),
self.x, self.y,
self.x+self.w, self.y+self.h,
... | identifier_body |
suicidegirls.py | .argument_lists) != 0:
if len(SuicideGirls.argument_lists) != 0:
print("Argument list found! Dispatching...")
argument_list = SuicideGirls.argument_lists.pop(0)
pool = multiprocessing.Pool(self.process_limit)
pool.map(self.download_image, argument_list)
# Girls: Riae (36), Fishball (28... | t(girl.title() + "/" + title.title() + " Img" + str(i).zfill(3) + " already exists, skipping...")
| conditional_block | |
suicidegirls.py | elif self.__type == "all":
print("All!")
self.__rip_all_photos()
SuicideGirls.stop_dispatching = True
SuicideGirls.dispatcher_thread.join()
print("Rip completed.")
print("Total girls/hopefuls ripped: " + str(self.girls_completed))
print("Total sets ripped: " + str(self.sets_completed))
de... | his file is meant to be imported by other Python files, not run directly. Exiting now.")
if __n | identifier_body | |
suicidegirls.py | print("Beginning dispatcher thread...")
while not SuicideGirls.stop_dispatching or len(SuicideGirls.argument_lists) != 0:
if len(SuicideGirls.argument_lists) != 0:
print("Argument list found! Dispatching...")
argument_list = SuicideGirls.argument_lists.pop(0)
pool = multiprocessing.Pool(self.process_... | (self, type_xpath):
time_period_xpath = "//li[@class='dropdown'][3]//ul/li/a[text() = '" + self.time_period + "']"
girl_name_xpath = "//article/header//h2/a"
load_more_xpath = "//a[@id='load-more']"
choice = SuicideGirls.driver.find_element_by_xpath(type_xpath)
SuicideGirls.driver.get(choice.get_attribute(... | __rip_all | identifier_name |
suicidegirls.py | print("Beginning dispatcher thread...")
while not SuicideGirls.stop_dispatching or len(SuicideGirls.argument_lists) != 0:
if len(SuicideGirls.argument_lists) != 0:
print("Argument list found! Dispatching...")
argument_list = SuicideGirls.argument_lists.pop(0)
pool = multiprocessing.Pool(self.process_... | if len(lmb) > 0 and lmb[0].is_displayed():
lmb[0].click()
time.sleep(10)
else:
break
set_links = list(set(set_links))
for link in set_links:
SuicideGirls.driver.get(link)
self.__rip_set()
self.girls_completed += 1
def __rip_set(self):
girl_xpath = "//h1/a"
title_xpath = ... | time.sleep(2)
lmb = SuicideGirls.driver.find_elements_by_xpath(load_more_xpath) | random_line_split |
app.go | /" + slot + "/ads/" + ad.Id)
} else {
r.JSON(404, map[string]string{"error": "not_found"})
}
}
func routeGetAdWithId(r render.Render, req *http.Request, params martini.Params) {
slot := params["slot"]
id := params["id"]
ad := getAd(req, slot, id)
if ad != nil {
r.JSON(200, ad)
} else {
r.JSON(404, map[str... | {
http.Error(w, err.Error(), http.StatusInternalServerError)
} | conditional_block | |
app.go | "})
}
}
func routeGetAdAsset(r render.Render, res http.ResponseWriter, req *http.Request, params martini.Params) {
slot := params["slot"]
id := params["id"]
ad := getAd(req, slot, id)
if ad == nil {
r.JSON(404, map[string]string{"error": "not_found"})
return
}
content_type := "application/octet-stream"
if ... | {
path := FSRoot + strings.TrimPrefix(r.URL.Path, FSPathPrefix)
http.ServeFile(w, r, path)
return
} | identifier_body | |
app.go | ["title"]; a != nil {
title = a[0]
}
destination := ""
if a := req.Form["destination"]; a != nil {
destination = a[0]
}
rd.HMSet(key,
"slot", slot,
"id", id,
"title", title,
"type", content_type,
"advertiser", advrId,
"destination", destination,
"impressions", "0",
)
f, _ := asset.Open()
def... |
var FSPathPrefix = "/fs"
var FSRoot = "/"
var FSDirPermission os.FileMode = 0777 | random_line_split | |
app.go | (path string, id string) string {
i, _ := strconv.Atoi(id)
host := internalIP[i%3]
if host != "" {
return "http://" + host + path
} else {
return path
}
}
func fetch(hash map[string]string, key string, defaultValue string) string {
if hash[key] == "" {
return defaultValue
} else {
return hash[key]
}
}
... | urlFor2 | identifier_name | |
tk.py | (self):
# Setup number pad screen
self.number_pad = Toplevel(root)
self.keypad_entery = Entry(self.number_pad,width=5,font=("Helvetica", 55))
self.keypad_entery.grid(row=0, column=0, columnspan=3, ipady=5)
self.number_pad.attributes('-fullscreen',True)
# Variables of keys to loop though
self.keys... | __init__ | identifier_name | |
tk.py |
timer_recurrence_string = str(arg)
timer_set_run_text.set(
"The timer will run at {} every {} day(s) for {} Minutes {} Seconds".format(
timer_time_string, timer_recurrence_string, minute, sec))
def __timer_return(self, arg):
global timer_set_run_text
global timer_recurrence_string
global ti... | total_seconds = (days - 1) * 86400
countdown = total_seconds - int(round(seconds_since_last_run))
if countdown <= 1:
total_seconds = days * 86400
countdown = total_seconds - int(round(seconds_since_last_run)) | conditional_block | |
tk.py | # add number to `entry`
self.keypad_entery.insert('end', arg)
self.pad_val = self.keypad_entery.get()
daily_timer_input_value.set(self.pad_val)
timer_input_value.set(self.pad_val)
# Set calculate the minuets and seconds for the label
minute, sec = divmod(int(self.pad_val), 60)
hours,... |
self.timer_set_page.attributes('-fullscreen', True)
# Strings for all recurrence rate
self.recurrence = ["1 Day", "2 Day", "3 Day", "4 Day", "5 Day", "6 Day","7 Day"]
self.timer_reoc_text = Label(
self.timer_set_page, text="Please choose how often you would like to run the timer.",
font=('Helve... | self.b = Button(self.timer_set_page, text=self.key, command=lambda val=self.z:self.__timer_return(val))
self.b.grid(row=self.y + 1, column=self.x, ipadx=20, ipady=10)
| random_line_split |
tk.py | # add number to `entry`
self.keypad_entery.insert('end', arg)
self.pad_val = self.keypad_entery.get()
daily_timer_input_value.set(self.pad_val)
timer_input_value.set(self.pad_val)
# Set calculate the minuets and seconds for the label
minute, sec = divmod(int(self.pad_val), 60)
hours, ... | self.timer_set_page,
textvariable=daily_timer_input_value,
width=23).grid(row=9, columnspan=3, column=0)
# Entery box for run time
daily_timer_input_value.set("") # Set the eatery to blank
self.keyboard_button = Button(self.timer_set_page,command=NumPad) # Button Ima... | def __init__(self):
global timer_set_run_text
global daily_timer_input_value
global timer_status
global timer_error_string
global keyboard_img
self.timer_set_page = Toplevel(root)
# Setup the window for the timer selections
# Strings for all of the buttons
self.timer_run_text = Label(... | identifier_body |
graphql-client.js | Cursor: []}
}
if (limit) {
if (cursor) {
if (cursor.filter) {
if (!filterResource || deepEqual(filterResource, cursor.filter))
cursor = {endCursor: []}
}
}
cursor.endCursor = cursor.endCursor || []
cursor.modelName = modelName
... | id
title
}` | random_line_split | |
graphql-client.js | ] || p.charAt(0) === '_')
// continue
let val = filterResource[p]
// if (p === TYPE) {
// if (!Array.isArray(val))
// continue
// else {
// let s = `${p}: [`
// val.forEach((r, i) => {
// if (i)
// s += ', ... | getChat | identifier_name | |
graphql-client.js | s += ']'
// inClause.push(s)
// }
// }
// if (p.charAt(0) === '_')
// debugger
if (!props[p] && val) {
if (p.charAt(0) === '_') {
if (Array.isArray(val)) {
let s = `${p}: [`
val.forEach((r, i) => {
... | {
let { author, recipient, client, context } = params
let table = `rl_${MESSAGE.replace(/\./g, '_')}`
let inbound = true
let query =
`query {
rl_tradle_Message(
first:20,
filter:{
EQ: {
_inbound: true
context: "${c... | identifier_body | |
greader.go | // GReader is an implementation of the GReader API.
type GReader struct {
d *storage.Database
}
// GReaderHandler returns a new GReader handler.
func GReaderHandler(d *storage.Database) http.HandlerFunc {
return GReader{d}.Handler()
}
// Handler returns a handler function that implements the GReader API.
func (a GR... | Alternate: []greaderCanonical{
{Href: article.Link},
},
Summary: greaderContent{
Content: article.GetContents(*serveParsedArticles),
},
Origin: greaderOrigin{
StreamId: greaderFeedId(article.FeedID),
},
})
}
a.returnSuccess(w, streamItemContents)
}
func (a GReader) handleEditTag(w ht... | Published: article.Date.Unix(),
Canonical: []greaderCanonical{
{Href: article.Link},
}, | random_line_split |
greader.go | GReader is an implementation of the GReader API.
type GReader struct {
d *storage.Database
}
// GReaderHandler returns a new GReader handler.
func GReaderHandler(d *storage.Database) http.HandlerFunc {
return GReader{d}.Handler()
}
// Handler returns a handler function that implements the GReader API.
func (a GRea... |
subList := greaderSubscriptionList{}
for _, feed := range feeds {
subList.Subscriptions = append(subList.Subscriptions, greaderSubscription{
Title: feed.Title,
// No client seems to use this field, so let it as zero
FirstItemMsec: "0",
HtmlUrl: feed.Link,
IconUrl: fmt.Sprintf("data:%s"... | {
folderMap[folder.ID] = folder.Name
} | conditional_block |
greader.go | GReader is an implementation of the GReader API.
type GReader struct {
d *storage.Database
}
// GReaderHandler returns a new GReader handler.
func GReaderHandler(d *storage.Database) http.HandlerFunc {
return GReader{d}.Handler()
}
// Handler returns a handler function that implements the GReader API.
func (a GRea... |
func (a GReader) route(w http.ResponseWriter, r *http.Request) {
// Record the total server latency of each call.
defer a.recordLatency(time.Now(), "server")
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/greader/accounts/ClientLogin":
a.handleLogin(w, r)
case "/greader/reader... | {
utils.Elapsed(t, func(d time.Duration) {
// Record latency measurements in microseconds.
greaderLatencyMetric.WithLabelValues(label).Observe(float64(d) / float64(time.Microsecond))
})
} | identifier_body |
greader.go | }
ok := bcrypt.CompareHashAndPassword([]byte(user.HashPass), []byte(formPass))
if ok == nil {
token, err := createAuthToken(user.HashPass, formUser)
if err != nil {
a.returnError(w, http.StatusInternalServerError)
return
}
a.returnSuccess(w, greaderHandlelogin{Auth: token})
} else {
a.returnError(w,... | greaderFeedId | identifier_name | |
locale.js | линарен сайт с множество избрани рецепти, любопитни факти и полезни приложения.",
"IT PRESENTS IN THE MOST":"Представя максимално достъпно най-добрите рецепти като акцентът е върху здравословното хранене и начин на живот. Аудиорията е предимно от жени, от добрата кухня и здраве.",
"KIDAMOM IS A FUN":"<strong>Ki... | random_line_split | ||
__init__.py | self.sudo = sudo
self.hostname = hostname
self.ssh_options = ssh_options
self.logger = logger or basic_remote_logger()
self.remote_module = None
self.channel = None
self.use_ssh = use_ssh
self.global_timeout = None # wait for ever
self.interprete... |
return 'popen//python=%s' % interpreter
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.group.terminate(timeout=1.0)
return False
def cmd(self, cmd):
"""
In the base connection class, this method just returns the ``cmd`... | if self.ssh_options:
return 'ssh=%s %s//python=%s' % (
self.ssh_options, hostname, interpreter
)
else:
return 'ssh=%s//python=%s' % (hostname, interpreter) | conditional_block |
__init__.py | self.hostname = hostname
self.ssh_options = ssh_options
self.logger = logger or basic_remote_logger()
self.remote_module = None
self.channel = None
self.use_ssh = use_ssh
self.global_timeout = None # wait for ever
self.interpreter = interpreter or 'pytho... |
def __init__(self, hostname, logger=None, sudo=False, threads=1, eager=True,
detect_sudo=False, use_ssh=False, interpreter=None, ssh_options=None):
self.sudo = sudo | random_line_split | |
__init__.py | host so that we can reliably ensure that ``getuser()`` will return the
right information.
After getting the user info it closes the connection and returns
a boolean
"""
exc = _execnet or execnet
gw = exc.makegateway(
self._make_connection_string(self.hostnam... | """
Try to determine the remote Python version so that it can be used
when executing. Avoids the problem of different Python versions, or distros
that do not use ``python`` but do ``python3``
"""
# executables in order of preference:
executables = ['python3', 'python', 'python2.7']
for execu... | identifier_body | |
__init__.py | self.sudo = sudo
self.hostname = hostname
self.ssh_options = ssh_options
self.logger = logger or basic_remote_logger()
self.remote_module = None
self.channel = None
self.use_ssh = use_ssh
self.global_timeout = None # wait for ever
self.interprete... | ():
logging.basicConfig()
logger = logging.getLogger(socket.gethostname())
logger.setLevel(logging.DEBUG)
return logger
def needs_ssh(hostname, _socket=None):
"""
Obtains remote hostname of the socket and cuts off the domain part
of its FQDN.
"""
if hostname.lower() in ['localhost'... | basic_remote_logger | identifier_name |
user_controller.py | = ret.to_hash()
ret = User.getNewest()
nuPic = ret.get_avatar(200)
nUser = ret.to_hash()
ret = User.find_by_id(8)
mfPic = ret.get_avatar(200)
mFollowed = ret.to_hash()
w = {"Result":"OK", "nUser":nUser, "nuPic": nuPic,"nWorkout":nWorkout, "mostFollowed":mFollowe... |
@app.route("/user_feeds/")
@app.route('/user_feeds/<int:page>', methods = ['GET'])
def user_feeds(page=1):
user = g.user
if user.is_anonymous():
return jsonify(result="")
posts = g.user.followed_posts().paginate(request.args.get('page', '', type=int), 10, False)
if not p... | user = g.user
posts = g.user.followed_posts().paginate(page, POSTS_PER_PAGE, False)
return render_template("users/followers.html",user = user) | identifier_body |
user_controller.py | = ret.to_hash()
ret = User.getNewest()
nuPic = ret.get_avatar(200)
nUser = ret.to_hash()
ret = User.find_by_id(8)
mfPic = ret.get_avatar(200)
mFollowed = ret.to_hash()
w = {"Result":"OK", "nUser":nUser, "nuPic": nuPic,"nWorkout":nWorkout, "mostFollowed":mFollowe... |
@login_manager.user_loader
@app.route("/user/find/", methods=['GET'])
def load_user(id):
return User.find_by_id(int(id))
@app.route("/user/<username>")
@app.route('/user/<username>/<int:page>', methods = ['GET'])
def display_user_profile(username, page=1):
user = User.find_by_username(username)
... | if form.validate():
user = User(form.username.data,
form.password.data)
User.save_to_db(user)
user = user.follow(user)
User.add_newsfeed(user,"Has joined Lumberjack.")
flash("Registration Successful!")
if request.head... | conditional_block |
user_controller.py | ", methods=["POST"])
def get_users():
"""
"""
result = []
userids = []
usernames = []
if 'username' in request.form:
usernames = User.find_all_by_username(request.form['username'])
if usernames is not None:
for username in usernames:
r... | search_for_key | identifier_name | |
user_controller.py | = ret.to_hash()
ret = User.getNewest()
nuPic = ret.get_avatar(200)
nUser = ret.to_hash()
ret = User.find_by_id(8)
mfPic = ret.get_avatar(200)
mFollowed = ret.to_hash()
w = {"Result":"OK", "nUser":nUser, "nuPic": nuPic,"nWorkout":nWorkout, "mostFollowed":mFollowe... | """
result = []
userids = []
usernames = []
if 'username' in request.form:
usernames = User.find_all_by_username(request.form['username'])
if usernames is not None:
for username in usernames:
result.append(username.to_hash())
elif 'email... | random_line_split | |
block.rs | ::execute;
const UPPER_HALF_BLOCK: &str = "\u{2580}";
const LOWER_HALF_BLOCK: &str = "\u{2584}";
const CHECKERBOARD_BACKGROUND_LIGHT: (u8, u8, u8) = (153, 153, 153);
const CHECKERBOARD_BACKGROUND_DARK: (u8, u8, u8) = (102, 102, 102);
pub struct BlockPrinter {}
impl Printer for BlockPrinter {
fn print(&self, img... |
}
// enum used to keep track where the current line of pixels processed should be displayed - as
// background or foreground color
#[derive(PartialEq)]
enum Mode {
Top,
Bottom,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_block_printer_small() {
| {
Color::Ansi256(ansi256_from_rgb(rgb))
} | conditional_block |
block.rs | ::execute;
const UPPER_HALF_BLOCK: &str = "\u{2580}";
const LOWER_HALF_BLOCK: &str = "\u{2584}";
const CHECKERBOARD_BACKGROUND_LIGHT: (u8, u8, u8) = (153, 153, 153);
const CHECKERBOARD_BACKGROUND_DARK: (u8, u8, u8) = (102, 102, 102);
pub struct BlockPrinter {}
impl Printer for BlockPrinter {
fn print(&self, img... | if let Some(bg) = c.bg() {
new_color.set_fg(Some(*bg));
out_char = UPPER_HALF_BLOCK;
} else {
execute!(out_buffer, MoveRight(1))?;
continue;
}
out_color = &new_color;
} else {
match (c.fg(... | new_color = ColorSpec::new(); | random_line_split |
block.rs | DynamicImage, config: &Config) -> ViuResult<(u32, u32)> {
// there are two types of buffers in this function:
// - stdout: Buffer, which is from termcolor crate. Used to buffer all writing
// required to print a single image or frame. Flushed on every line
// - row_buffer: Vec<ColorSpe... | test_block_printer_large | identifier_name | |
immutable.rs | <U: ArrowNativeType, T: AsRef<[U]>>(items: &T) -> Self {
let slice = items.as_ref();
let capacity = slice.len() * std::mem::size_of::<U>();
let mut buffer = MutableBuffer::with_capacity(capacity);
buffer.extend_from_slice(slice);
buffer.into()
}
/// Creates a buffer from... | from_slice_ref | identifier_name | |
immutable.rs | of bytes in the buffer
pub fn len(&self) -> usize {
self.data.len() - self.offset
}
/// Returns the capacity of this buffer.
/// For externally owned buffers, this returns zero
pub fn capacity(&self) -> usize {
self.data.capacity()
}
/// Returns whether the buffer is empty... |
/// Returns a slice of this buffer starting at a certain bit offset.
/// If the offset is byte-aligned the returned buffer is a shallow clone,
/// otherwise a new buffer is allocated and filled with a copy of the bits in the range.
pub fn bit_slice(&self, offset: usize, len: usize) -> Self {
i... | {
// JUSTIFICATION
// Benefit
// Many of the buffers represent specific types, and consumers of `Buffer` often need to re-interpret them.
// Soundness
// * The pointer is non-null by construction
// * alignment asserted below.
let (prefix, offsets... | identifier_body |
immutable.rs | }
/// Returns the number of 1-bits in this buffer.
pub fn count_set_bits(&self) -> usize {
let len_in_bits = self.len() * 8;
// self.offset is already taken into consideration by the bit_chunks implementation
self.count_set_bits_offset(0, len_in_bits)
}
/// Returns the number ... | assert_eq!(buffer2, buffer_copy.ok().unwrap());
}
| random_line_split | |
ZH.js | summary_footer_tip: '飞呀辅助订购为你提供快捷预订通道,无需跳转到第三方平台。但出票和退改签服务仍由第三方机票服务平台提供。',
summary_no_result: '暂无平台报价',
summary_research: '重新搜索',
summary_timeout_tips1: '航班价格可能发生变化,将为你刷新',
summary_timeout_tips2: '以获取最新价格',
summary_quick_login: '动态码登录',
summary_quick_login_tip: '下单前先花10秒登录账号哦',
summary_other_login: '其他登... | summary_price: '各大平台实时价格', | random_line_split | |
surface.rs | Mark nonsendable.
#[allow(missing_copy_implementations)]
pub struct NativePaintingGraphicsContext {
pub display: *mut Display,
visual_info: *mut XVisualInfo,
}
impl NativePaintingGraphicsContext {
pub fn from_metadata(metadata: &NativeGraphicsMetadata) -> NativePaintingGraphicsContext {
// FIXME(p... | (&self,
native_context: &NativeCompositingGraphicsContext,
texture: &Texture,
size: Size2D<isize>) {
// Create the GLX pixmap.
//
// FIXME(pcwalton): RAII for exception | bind_to_texture | identifier_name |
surface.rs | Mark nonsendable.
#[allow(missing_copy_implementations)]
pub struct NativePaintingGraphicsContext {
pub display: *mut Display,
visual_info: *mut XVisualInfo,
}
impl NativePaintingGraphicsContext {
pub fn from_metadata(metadata: &NativeGraphicsMetadata) -> NativePaintingGraphicsContext {
// FIXME(p... | /// Creates graphics metadata from a metadata descriptor.
pub fn from_descriptor(descriptor: &NativeGraphicsMetadataDescriptor)
-> NativeGraphicsMetadata {
// WARNING: We currently rely on the X display connection being the
// same in both the Painting and Compositing ... | unsafe impl Send for NativeGraphicsMetadata {}
impl NativeGraphicsMetadata { | random_line_split |
surface.rs | (mem::transmute(visual), Some(config));
}
// NVidia (and AMD/ATI) drivers have RGBA configurations that use 24-bit
// XVisual, not capable of representing an alpha-channel in Pixmap form,
// so we look for the configuration with a full set of 32 bits.
for i ... | {
self.will_leak = true;
} | identifier_body | |
surface.rs | Mark nonsendable.
#[allow(missing_copy_implementations)]
pub struct NativePaintingGraphicsContext {
pub display: *mut Display,
visual_info: *mut XVisualInfo,
}
impl NativePaintingGraphicsContext {
pub fn from_metadata(metadata: &NativeGraphicsMetadata) -> NativePaintingGraphicsContext {
// FIXME(p... |
}
}
impl PixmapNativeSurface {
fn from_pixmap(pixmap: Pixmap) -> PixmapNativeSurface {
PixmapNativeSurface {
pixmap: pixmap,
will_leak: true,
}
}
pub fn from_skia_shared_gl_context(context: SkiaSkNativeSharedGLContextRef)
... | {
panic!("You should have disposed of the pixmap properly with destroy()! This pixmap \
will leak!");
} | conditional_block |
mountfs.go | mpathUtils, mpathRRs = mfs.ios.GetAllMpathUtils(now)
objutil, ok = mpathUtils[objmpath]
rr, _ = mpathRRs[objmpath] // GET round-robin counter (zeros out every iostats refresh i-val)
util = objutil
r = rr
)
fqn = objfqn
if !ok {
cmn.DassertMsg(fals... | {
var (
availablePaths = (*MPI)(mfs.available.Load())
disabledPaths = (*MPI)(mfs.disabled.Load())
)
if availablePaths == nil {
tmp := make(MPI, 10)
availablePaths = &tmp
}
if disabledPaths == nil {
tmp := make(MPI, 10)
disabledPaths = &tmp
}
return *availablePaths, *disabledPaths
} | identifier_body | |
mountfs.go | ) {
return nil
}
if err := cmn.CreateDir(filepath.Dir(tmpDir)); err != nil {
return err
}
if err := os.Rename(dir, tmpDir); err != nil {
if os.IsExist(err) {
// Slow path - `tmpDir` (or rather `nonExistingDir`) for some reason already exists...
//
// Even though `nonExistingDir` should not exist we c... | // the counter will catch up with counter of the previous mountpath.
// If the directories from the previous mountpath were not yet removed
// (slow disk or filesystem) we can end up with the same name.
// For now we try to fight this with randomizing the initial counter.
// In backgroun... | // There are at least two cases when this might not be true:
// 1. `nonExistingDir` is leftover after target crash.
// 2. Mountpath was removed and then added again. The counter
// will be reset and if we will be removing dirs quickly enough | random_line_split |
mountfs.go | {
return nil
}
if err := cmn.CreateDir(filepath.Dir(tmpDir)); err != nil {
return err
}
if err := os.Rename(dir, tmpDir); err != nil {
if os.IsExist(err) {
// Slow path - `tmpDir` (or rather `nonExistingDir`) for some reason already exists...
//
// Even though `nonExistingDir` should not exist we ca... |
return nil
}
// Add adds new mountpath to the target's mountpaths.
// FIXME: unify error messages for original and clean mountpath
func (mfs *MountedFS) Add(mpath string) error {
cleanMpath, err := cmn.ValidateMpath(mpath)
if err != nil {
return err
}
if err := Access(cleanMpath); err != nil {
return fmt.Er... | {
if err := mfs.Add(path); err != nil {
return err
}
} | conditional_block |
mountfs.go | = ioutil.TempDir(mi.Path, nonExistingDir)
if err != nil {
return err
}
// Retry renaming - hopefully it should succeed now.
err = os.Rename(dir, tmpDir)
}
// Someone removed dir before os.Rename, nothing more to do.
if os.IsNotExist(err) {
return nil
}
if err != nil {
return err
}
}... | Remove | identifier_name | |
webmux.py | _list['ivolethe']['global_ip'] == 'webmux.cflo.at':
try:
findTags = re.compile(r'<.*?>')
findIP = re.compile(r'\d+\.\d+\.\d+\.\d+')
html = requests.get('http://checkip.dyndns.org' ).text()
ipaddress = findIP.search(findTags.sub('', html))
if ipaddress... |
return ssh_procs
class WebmuxTermManager(terminado.NamedTermManager):
"""Share terminals between websockets connected to the same endpoint.
"""
def __init__(self, max_terminals=None, **kwargs):
super(WebmuxTermManager, self).__init__(**kwargs)
def get_terminal(self, port_number):
... | subprocess.call(["kill", p]) | conditional_block |
webmux.py | server_list['ivolethe']['global_ip'] == 'webmux.cflo.at':
try:
findTags = re.compile(r'<.*?>')
findIP = re.compile(r'\d+\.\d+\.\d+\.\d+')
html = requests.get('http://checkip.dyndns.org' ).text()
ipaddress = findIP.search(findTags.sub('', html))
if ip... | # Log out a little bit
logging.info("Registered %s at %s:%d on webmux port %d"%(data['hostname'], data['global_ip'], data['host_port'], data['webmux_port']))
self.write(str(data['webmux_port']))
class ResetPageHandler(tornado.web.RequestHandler):
"""Reset all SSH connections forwarding port... | server_list[data['hostname']].update(data)
data = server_list[data['hostname']]
| random_line_split |
webmux.py | ():
global server_list
while server_list['ivolethe']['global_ip'] == 'webmux.cflo.at':
try:
findTags = re.compile(r'<.*?>')
findIP = re.compile(r'\d+\.\d+\.\d+\.\d+')
html = requests.get('http://checkip.dyndns.org' ).text()
ipaddress = findIP.search(findT... | get_global_ip | identifier_name | |
webmux.py | server_list['ivolethe']['global_ip'] == 'webmux.cflo.at':
try:
findTags = re.compile(r'<.*?>')
findIP = re.compile(r'\d+\.\d+\.\d+\.\d+')
html = requests.get('http://checkip.dyndns.org' ).text()
ipaddress = findIP.search(findTags.sub('', html))
if ip... |
# Create new terminal
logging.info("Attempting to connect to: %s@%s:%d", s['user'], name, s['webmux_port'])
self.shell_command = ["ssh", "-C", "-o", "UserKnownHostsFile /dev/null", "-o", "StrictHostKeyChecking no", "-p", port_number, s['user']+"@webmux.cflo.at"]
term = self.new_terminal... | """Share terminals between websockets connected to the same endpoint.
"""
def __init__(self, max_terminals=None, **kwargs):
super(WebmuxTermManager, self).__init__(**kwargs)
def get_terminal(self, port_number):
from terminado.management import MaxTerminalsReached
# This is importan... | identifier_body |
server.py | % 8 == 0:
smaller_key.append("8")
counter = 1
else:
|
# Apply the IP Key encryption algorithm
final_list = []
next_index = 56
for i in range(28):
final_list.append(smaller_key[next_index])
next_index = ((next_index - 8) % 65)
next_index = 62
for i in range(28, 52):
final_list.append(smaller_key[next_index])
nex... | smaller_key.append(my_key_list[i])
counter += 1 | conditional_block |
server.py | (K_List):
new_list = []
# Convert to bits
for i in range(len(K_List)):
new_list.append(format(ord(K_List[i]), '07b'))
if K_List[i].count("1") % 2 == 0:
new_list.append("0")
else:
new_list.append("1")
return "".join(new_list)
def apply_IP(M):
rev_M... | convert_K | identifier_name | |
server.py |
def apply_IPKey(my_key):
my_key_list = list(my_key)
smaller_key = []
counter = 1
# Convert every 8th bit from the key to an "8", to be removed later
for i in range(len(my_key_list)):
if counter % 8 == 0:
smaller_key.append("8")
counter = 1
else:
... | final_list = [C[39], C[7], C[47], C[15], C[55], C[23], C[63], C[31], C[38], C[6], C[46], C[14], C[54], C[22], C[62],
C[30],
C[37], C[5], C[45], C[13], C[53], C[21], C[61], C[29], C[36], C[4], C[44], C[12], C[52], C[20], C[60],
C[28],
C[35], C[3], C... | identifier_body | |
server.py | return "".join(new_list)
def apply_IP(M):
rev_M = list(M[len(M)::-1])
my_mat = [["0", "0", "0", "0", "0", "0", "0", "0"], ["0", "0", "0", "0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0", "0", "0", "0"], ["0", "0", "0", "0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0", "0",... | new_list.append("1")
| random_line_split | |
read.go | ) {
s.Nodes[0].Data = "p"
}
}
})
// Loop through all paragraphs, and assign a score to them based on how content-y they look.
// Then add their score to their parent node.
// A score is determined by things like number of commas, class names, etc. Maybe eventually link density.
r.candidates = make(map[st... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.