uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
c61a0ffd471c964c32b34d7b
train
function
def gen_data(vocabxid, dummy_symbols, ignore, corpus, tm_sent_len, lm_sent_len, verbose, remove_short): sents = ([], []) #tuple of (tm_sents, lm_sents); each element is [(doc_id, seq_id, seq)] docs = ([], []) #tuple of (tm_docs, lm_docs); each element is [ [[doc1seq1], [doc2seq2]], [doc2_seqs] ] sent_len...
def gen_data(vocabxid, dummy_symbols, ignore, corpus, tm_sent_len, lm_sent_len, verbose, remove_short):
sents = ([], []) #tuple of (tm_sents, lm_sents); each element is [(doc_id, seq_id, seq)] docs = ([], []) #tuple of (tm_docs, lm_docs); each element is [ [[doc1seq1], [doc2seq2]], [doc2_seqs] ] sent_lens = [] #original sentence lengths doc_lens = [] #original document lengths docids = [] #origina...
for topic model stopwords = set([item.strip().lower() for item in open(stopwords)]) freqwords = set([item[0] for item in sorted(vocab_freq.items(), key=operator.itemgetter(1), \ reverse=True)[:int(float(len(vocab_freq))*vocab_maxfreq)]]) #ignore top N% most frequent words for topic model alpha_...
233
233
778
28
204
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
gen_data
gen_data
71
130
71
71
e3f79be564e700bc256bc3c3e4c8efee1a4c3f0d
bigcode/the-stack
train
2f6515975e0e49e635afa294
train
function
def Get_TM_vocab(idxvocab,tm_ignore): TM_vocab = np.delete(idxvocab, list(tm_ignore)) return TM_vocab
def Get_TM_vocab(idxvocab,tm_ignore):
TM_vocab = np.delete(idxvocab, list(tm_ignore)) return TM_vocab
+ " processed\r") sys.stdout.flush() return sents, docs, docids, (np.mean(sent_lens), max(sent_lens), min(sent_lens), np.mean(doc_lens), max(doc_lens), min(doc_lens)) def Get_TM_vocab(idxvocab,tm_ignore):
64
64
30
11
53
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
Get_TM_vocab
Get_TM_vocab
132
134
132
132
c7ef3a34e49d3cff63ed45184430831f5cf30775
bigcode/the-stack
train
13c2bdcf67f5fc51b567447f
train
function
def get_doc_sent(sents, docbow, sent_num, sent_J, pad_id=0): index = 0 D = [] for id_doc in range(len(sent_num)): doc = sents[index : index + sent_num[id_doc]] J = int(np.ceil(float(sent_num[id_doc]) / sent_J )) for s_id in range(J * sent_J - sent_num[id_doc]): doc...
def get_doc_sent(sents, docbow, sent_num, sent_J, pad_id=0):
index = 0 D = [] for id_doc in range(len(sent_num)): doc = sents[index : index + sent_num[id_doc]] J = int(np.ceil(float(sent_num[id_doc]) / sent_J )) for s_id in range(J * sent_J - sent_num[id_doc]): doc.append((id_doc, s_id + sent_num[id_doc], [pad_id] * cf.lm_sen...
_num = np.zeros([doc_lenth,]) for docid, seqid, seq in sents: sent_num[docid] += 1 return np.int32(sent_num) def get_doc_sent(sents, docbow, sent_num, sent_J, pad_id=0):
63
64
178
21
42
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
get_doc_sent
get_doc_sent
315
327
315
315
9927338ddbdc1452497b65e0cb2610a26e1305e3
bigcode/the-stack
train
b7f5dd58ce30a0b9caffbace
train
function
def get_sent_num(sents,doc_lenth): sent_num = np.zeros([doc_lenth,]) for docid, seqid, seq in sents: sent_num[docid] += 1 return np.int32(sent_num)
def get_sent_num(sents,doc_lenth):
sent_num = np.zeros([doc_lenth,]) for docid, seqid, seq in sents: sent_num[docid] += 1 return np.int32(sent_num)
for padingnum in range((max(batch_ids) + 1) * cf.batch_size - docbow.shape[1]): d.append(np.array([pad_id] * docbow.shape[0])) D.append(d) return D def get_sent_num(sents,doc_lenth):
64
64
55
11
52
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
get_sent_num
get_sent_num
307
311
307
307
3187610ac301ad4d134e9404ba43c7a16654c8eb
bigcode/the-stack
train
d25b75adfe9b0458be573008
train
function
def get_batch_tm_lm_pre_fix_next(Doc, V, tm_ignore, Batch_Size, pad_id = 0 ): x, y, d, m, n = [], [], [], [], [] Doc_len = [len(Doc[id].copy()) for id in range(Batch_Size)] for idx_sent in range(Batch_Size): xx, yy, dd, mm, nn = [], [], [], [], [] s_pre_bow = np.zeros([V-len(tm_ignore)]...
def get_batch_tm_lm_pre_fix_next(Doc, V, tm_ignore, Batch_Size, pad_id = 0 ):
x, y, d, m, n = [], [], [], [], [] Doc_len = [len(Doc[id].copy()) for id in range(Batch_Size)] for idx_sent in range(Batch_Size): xx, yy, dd, mm, nn = [], [], [], [], [] s_pre_bow = np.zeros([V-len(tm_ignore)]) for docid, seqid, seq in Doc[idx_sent]: xx.append(pad(s...
len(seq) - 1) + [0.0] * (cf.lm_sent_len - len(seq) + 1)) x.append(xx) y.append(yy) d.append(dd) m.append(mm) return np.array(x), np.array(y), np.array(d), np.array(m) def get_batch_tm_lm_pre_fix_next(Doc, V, tm_ignore, Batch_Size, pad_id = 0 ):
94
94
315
27
67
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
get_batch_tm_lm_pre_fix_next
get_batch_tm_lm_pre_fix_next
379
402
379
379
8fb2791acf7c06e4c7b403aaa2831bbfc1f54385
bigcode/the-stack
train
6e15d1d038b2f75085742b9c
train
function
def init_embedding(model, idxvocab): word_emb = [] for vi, v in enumerate(idxvocab): if v in model: word_emb.append(model[v]) else: word_emb.append(np.random.uniform(-0.5/model.vector_size, 0.5/model.vector_size, [model.vector_size,])) return np.array(word_emb)...
def init_embedding(model, idxvocab):
word_emb = [] for vi, v in enumerate(idxvocab): if v in model: word_emb.append(model[v]) else: word_emb.append(np.random.uniform(-0.5/model.vector_size, 0.5/model.vector_size, [model.vector_size,])) return np.array(word_emb)
ow2[word][ep * num + sent_index] += 1 # sent_bow2 = np.delete(sent_bow2, list(tm_ignore), axis=0) # sent_bow.append(sent_bow2) # return sent_bow def init_embedding(model, idxvocab):
64
64
77
9
54
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
init_embedding
init_embedding
171
178
171
171
e06d40dcd46c36261fca8d753b3a4b4bffb059cb
bigcode/the-stack
train
2aec6cf85e8515bf5c7716fa
train
function
def get_batches_tm_lm(sents,docbow,V, pad_id = 0 ): lm_num_batches = int(math.ceil(float(len(sents)) / cf.batch_size)) batch_ids = [item for item in range(lm_num_batches)] sent_len = cf.lm_sent_len batch_size = cf.batch_size random.shuffle(batch_ids) random.shuffle(sents) X = [] ...
def get_batches_tm_lm(sents,docbow,V, pad_id = 0 ):
lm_num_batches = int(math.ceil(float(len(sents)) / cf.batch_size)) batch_ids = [item for item in range(lm_num_batches)] sent_len = cf.lm_sent_len batch_size = cf.batch_size random.shuffle(batch_ids) random.shuffle(sents) X = [] Y = [] D = [] M = [] for idx in batch_...
) + 1)) t.append(Theta[:, docid]) for padingnum in range((max(batch_ids)+1)*batch_size - len(sents)): x.append([pad_id] * sent_len) y.append([pad_id] * sent_len) m.append([0.0] * sent_len) t.append([pad_id] * cf.topic_embe...
129
129
431
20
108
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
get_batches_tm_lm
get_batches_tm_lm
221
255
221
221
cc21690ab39dbea5656cd0a342cfdc37210d83d0
bigcode/the-stack
train
47bdd22e01d2e8ec60dd4fca
train
function
def get_batches_tm(docbow,pad_id=0.0): tm_num_batches = int(math.ceil(float(docbow.shape[1]) / cf.batch_size)) batch_ids = [item for item in range(tm_num_batches)] random.shuffle(batch_ids) D = [] for idx in batch_ids: d = [] if idx != max(batch_ids): for docid in...
def get_batches_tm(docbow,pad_id=0.0):
tm_num_batches = int(math.ceil(float(docbow.shape[1]) / cf.batch_size)) batch_ids = [item for item in range(tm_num_batches)] random.shuffle(batch_ids) D = [] for idx in batch_ids: d = [] if idx != max(batch_ids): for docid in range((idx * cf.batch_size),((idx+1) * ...
_id] * sent_len) y.append([pad_id] * sent_len) m.append([0.0] * sent_len) X.append(x) Y.append(y) M.append(m) return X,Y,M def get_batches_tm(docbow,pad_id=0.0):
64
64
195
14
49
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
get_batches_tm
get_batches_tm
288
304
288
288
95098985a2478020e4bb9eb4e89c7906eef136a7
bigcode/the-stack
train
c72e8feb7e6789cf758d458e
train
function
def Bow_sents(s,V,tm_ignore): s_b = np.zeros(V) for w in s: s_b[w] += 1 s_b = np.delete(s_b, list(tm_ignore), axis=0) return s_b
def Bow_sents(s,V,tm_ignore):
s_b = np.zeros(V) for w in s: s_b[w] += 1 s_b = np.delete(s_b, list(tm_ignore), axis=0) return s_b
the doc which is less than 8 sentences for id_sent in range(J): sent = doc[id_sent * sent_J : (id_sent+1)*sent_J] D.append(sent) index += sent_num[id_doc] return D def Bow_sents(s,V,tm_ignore):
64
64
55
10
53
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
Bow_sents
Bow_sents
329
334
329
329
bc161dee3d07126aa32f32eee6ff500c7ac46c44
bigcode/the-stack
train
0eab45ff6af7941e8a1ea127
train
function
def get_batch_tm_lm_all(Doc, docbow, V, tm_ignore, Batch_Size, pad_id = 0 ): x, y, d, m,n = [], [], [], [],[] for idx_sent in range(Batch_Size): xx, yy, dd, mm = [], [], [], [] for docid, seqid, seq in Doc[idx_sent]: xx.append(pad(seq[:-1], cf.lm_sent_len, pad_id)) ...
def get_batch_tm_lm_all(Doc, docbow, V, tm_ignore, Batch_Size, pad_id = 0 ):
x, y, d, m,n = [], [], [], [],[] for idx_sent in range(Batch_Size): xx, yy, dd, mm = [], [], [], [] for docid, seqid, seq in Doc[idx_sent]: xx.append(pad(seq[:-1], cf.lm_sent_len, pad_id)) yy.append(pad(seq[1:], cf.lm_sent_len, pad_id)) dd.append(docbow[...
s_b = np.zeros(V) for w in s: s_b[w] += 1 s_b = np.delete(s_b, list(tm_ignore), axis=0) return s_b def get_batch_tm_lm_all(Doc, docbow, V, tm_ignore, Batch_Size, pad_id = 0 ):
73
73
244
29
43
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
get_batch_tm_lm_all
get_batch_tm_lm_all
336
354
336
336
0417a588e4a0a99e36d977e29efcd871bd07ab04
bigcode/the-stack
train
6c667e47df77fc11c44dd010
train
function
def get_batches(sents,Theta,pad_id = 0): lm_num_batches = int(math.ceil(float(len(sents)) / cf.batch_size)) batch_ids = [item for item in range(lm_num_batches)] sent_len = cf.lm_sent_len batch_size = cf.batch_size random.shuffle(batch_ids) random.shuffle(sents) X = [] Y = [] ...
def get_batches(sents,Theta,pad_id = 0):
lm_num_batches = int(math.ceil(float(len(sents)) / cf.batch_size)) batch_ids = [item for item in range(lm_num_batches)] sent_len = cf.lm_sent_len batch_size = cf.batch_size random.shuffle(batch_ids) random.shuffle(sents) X = [] Y = [] M = [] T = [] for idx in batch...
2) # return sent_bow def init_embedding(model, idxvocab): word_emb = [] for vi, v in enumerate(idxvocab): if v in model: word_emb.append(model[v]) else: word_emb.append(np.random.uniform(-0.5/model.vector_size, 0.5/model.vector_size, [model.vector_si...
126
126
421
14
112
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
get_batches
get_batches
183
217
183
183
03b11afd886498c92658a70088dd1c133bb44865
bigcode/the-stack
train
bb0979ea165fa9b3b3189e80
train
function
def pad(lst, max_len, pad_symbol): return lst + [pad_symbol] * (max_len - len(lst))
def pad(lst, max_len, pad_symbol):
return lst + [pad_symbol] * (max_len - len(lst))
ocab): if v in model: word_emb.append(model[v]) else: word_emb.append(np.random.uniform(-0.5/model.vector_size, 0.5/model.vector_size, [model.vector_size,])) return np.array(word_emb) def pad(lst, max_len, pad_symbol):
64
64
26
10
54
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
pad
pad
180
181
180
180
23c4fc1dea5f4dfd93c8142f709e7b166c2862e4
bigcode/the-stack
train
96e8d5d35cbe523e36b19820
train
function
def gen_vocab(dummy_symbols, corpus, stopwords, vocab_minfreq, vocab_maxfreq, verbose): # corpus = corpus.lower() idxvocab = [] vocabxid = defaultdict(int) vocab_freq = defaultdict(int) for line_id, line in enumerate(codecs.open(corpus, "r", "utf-8")): for word in line.strip().split():...
def gen_vocab(dummy_symbols, corpus, stopwords, vocab_minfreq, vocab_maxfreq, verbose): # corpus = corpus.lower()
idxvocab = [] vocabxid = defaultdict(int) vocab_freq = defaultdict(int) for line_id, line in enumerate(codecs.open(corpus, "r", "utf-8")): for word in line.strip().split(): vocab_freq[word] += 1 if line_id % 1000 == 0 and verbose: sys.stdout.write(str(line_...
import codecs import sys import operator import math import re import numpy as np from collections import defaultdict import config as cf import random def update_vocab(symbol, idxvocab, vocabxid): idxvocab.append(symbol) vocabxid[symbol] = len(idxvocab) - 1 def gen_vocab(dummy_symbols, corpus, sto...
98
205
685
28
69
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
gen_vocab
gen_vocab
15
69
15
16
a6477b1136aecb761f5dbbfb782986d0a8380885
bigcode/the-stack
train
9c0d788a44579af962a79e8b
train
function
def get_batch_tm_lm_all_pre_sentence(Doc, docbow, V, tm_ignore, Batch_Size, pad_id=0): x, y, d, m = [], [], [], [] for idx_sent in range(Batch_Size): xx, yy, dd, mm = [], [], [], [] s_pre_bow = np.zeros([V-len(tm_ignore)]) for docid, seqid, seq in Doc[idx_sent]: xx.appe...
def get_batch_tm_lm_all_pre_sentence(Doc, docbow, V, tm_ignore, Batch_Size, pad_id=0):
x, y, d, m = [], [], [], [] for idx_sent in range(Batch_Size): xx, yy, dd, mm = [], [], [], [] s_pre_bow = np.zeros([V-len(tm_ignore)]) for docid, seqid, seq in Doc[idx_sent]: xx.append(pad(seq[:-1], cf.lm_sent_len, pad_id)) yy.append(pad(seq[1:], cf.lm_sent...
] * (cf.lm_sent_len - len(seq) + 1)) x.append(xx) y.append(yy) d.append(dd) m.append(mm) return np.array(x), np.array(y), np.array(d), np.array(m) def get_batch_tm_lm_all_pre_sentence(Doc, docbow, V, tm_ignore, Batch_Size, pad_id=0):
84
84
280
28
56
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
get_batch_tm_lm_all_pre_sentence
get_batch_tm_lm_all_pre_sentence
357
377
357
357
04c729a0e16dd85984edafb7ae2225ce8e5183e9
bigcode/the-stack
train
443ee9ab8e29023e29aeea84
train
function
def update_vocab(symbol, idxvocab, vocabxid): idxvocab.append(symbol) vocabxid[symbol] = len(idxvocab) - 1
def update_vocab(symbol, idxvocab, vocabxid):
idxvocab.append(symbol) vocabxid[symbol] = len(idxvocab) - 1
import codecs import sys import operator import math import re import numpy as np from collections import defaultdict import config as cf import random def update_vocab(symbol, idxvocab, vocabxid):
46
64
37
13
32
BoChenGroup/rGBN_RNN
1rgbn-rnn/data_process_all.py
Python
update_vocab
update_vocab
11
13
11
11
f0205b972067890a4720f745e1d119810f21e186
bigcode/the-stack
train
01615376db3fb6ce065a2500
train
function
@pipe def ev_sinews(*args, **kwargs): return eval_sinews(*args, **kwargs)
@pipe def ev_sinews(*args, **kwargs):
return eval_sinews(*args, **kwargs)
_warnings(): warnings.simplefilter("ignore") df_res._plot_info = { "type": "sinew_outputs", "var": model.var_rand, "out": model.out, } return df_res @pipe def ev_sinews(*args, **kwargs):
64
64
26
14
49
natalia-rubio/py_grama
grama/eval_random.py
Python
ev_sinews
ev_sinews
260
262
260
261
2b14a2325c586fc65202edf991211186138b7c65
bigcode/the-stack
train
47e8e782e5f9545eebbb8d03
train
function
@pipe def ev_hybrid(*args, **kwargs): return eval_hybrid(*args, **kwargs)
@pipe def ev_hybrid(*args, **kwargs):
return eval_hybrid(*args, **kwargs)
.simplefilter("ignore") df_res._meta = dict( type="eval_hybrid", varname=varname, plan=plan, var_rand=model.var_rand, out=model.out, ) return df_res @pipe def ev_hybrid(*args, **kwargs):
64
64
24
13
50
natalia-rubio/py_grama
grama/eval_random.py
Python
ev_hybrid
ev_hybrid
388
390
388
389
a3c324e97c5f41c266514e3d347f46f42e3627bf
bigcode/the-stack
train
06f76119bba25549d8d5cbbe
train
function
@curry def eval_hybrid( model, n=1, plan="first", df_det=None, varname="hybrid_var", seed=None, append=True, skip=False, ): r"""Hybrid points for Sobol' indices Use the "hybrid point" design (Sobol', 1999) to support estimating Sobol' indices. Use gr.tran_sobol() to post-pro...
@curry def eval_hybrid( model, n=1, plan="first", df_det=None, varname="hybrid_var", seed=None, append=True, skip=False, ):
r"""Hybrid points for Sobol' indices Use the "hybrid point" design (Sobol', 1999) to support estimating Sobol' indices. Use gr.tran_sobol() to post-process the results and compute estimates. Args: model (gr.Model): Model to evaluate; must have CopulaIndependence n (numeric): Number...
format( model.name, runtime_est ) ) else: print("Design runtime estimates unavailable; model has no timing data.") ## For autoplot with warnings.catch_warnings(): warnings.simplefilter("ignore") df_samp._plot_in...
256
256
942
48
208
natalia-rubio/py_grama
grama/eval_random.py
Python
eval_hybrid
eval_hybrid
267
385
267
277
974ab478b9de9324d3300d73f5196b5812f6f0e2
bigcode/the-stack
train
9236bb8d523f4ac723b1285b
train
function
@curry def eval_monte_carlo(model, n=1, df_det=None, seed=None, append=True, skip=False): r"""Monte Carlo evaluation Evaluates a given model at a given dataframe. Generates outer product with deterministic samples. Args: model (gr.Model): Model to evaluate n (numeric): number of Monte ...
@curry def eval_monte_carlo(model, n=1, df_det=None, seed=None, append=True, skip=False):
r"""Monte Carlo evaluation Evaluates a given model at a given dataframe. Generates outer product with deterministic samples. Args: model (gr.Model): Model to evaluate n (numeric): number of Monte Carlo samples to draw df_det (DataFrame): Deterministic levels for evaluation; use...
", "eval_sinews", "ev_sinews", "eval_hybrid", "ev_hybrid", ] from numpy import tile, linspace, zeros, isfinite from numpy.random import random from numpy.random import seed as set_seed from pandas import DataFrame import warnings import grama as gr from grama import pipe, custom_formatwarning from sc...
156
156
522
29
127
natalia-rubio/py_grama
grama/eval_random.py
Python
eval_monte_carlo
eval_monte_carlo
28
99
28
29
8cefb7e1b477261127e28552b1a834cc5edc22ef
bigcode/the-stack
train
9b47cc3f91d154bbb133a07c
train
function
@pipe def ev_monte_carlo(*args, **kwargs): return eval_monte_carlo(*args, **kwargs)
@pipe def ev_monte_carlo(*args, **kwargs):
return eval_monte_carlo(*args, **kwargs)
append) ## Attach metadata with warnings.catch_warnings(): warnings.simplefilter("ignore") df_res._plot_info = {"type": "monte_carlo_outputs", "out": model.out} return df_res @pipe def ev_monte_carlo(*args, **kwargs):
64
64
28
15
48
natalia-rubio/py_grama
grama/eval_random.py
Python
ev_monte_carlo
ev_monte_carlo
102
104
102
103
0790e647037c8328c983c8479ebfa4ab4ea7eacf
bigcode/the-stack
train
b443e0361db341b5e9aa74a5
train
function
@curry def eval_sinews( model, n_density=10, n_sweeps=3, seed=None, df_det=None, varname="sweep_var", indname="sweep_ind", append=True, skip=False, ): r"""Sweep study Perform coordinate sweeps over each model random variable ("sinew" design). Use random starting points d...
@curry def eval_sinews( model, n_density=10, n_sweeps=3, seed=None, df_det=None, varname="sweep_var", indname="sweep_ind", append=True, skip=False, ):
r"""Sweep study Perform coordinate sweeps over each model random variable ("sinew" design). Use random starting points drawn from the joint density. Use gr.plot_auto() to construct a quick visualization of the output dataframe. Use `skip` version to visualize the design, and non-skipped versio...
sec".format( model.name, runtime_est ) ) else: print("Design runtime estimates unavailable; model has no timing data.") ## Attach metadata with warnings.catch_warnings(): warnings.simplefilter("ignore") df_samp...
256
256
1,336
61
195
natalia-rubio/py_grama
grama/eval_random.py
Python
eval_sinews
eval_sinews
109
257
109
120
1057a5fb1fe53a1649b0496075ffabb6fb562302
bigcode/the-stack
train
757506dea3651df9aae75cf5
train
function
def flash(led, duration): GPIO.output(led, GPIO.HIGH) sleep(duration) GPIO.output(led, GPIO.LOW) sleep(duration)
def flash(led, duration):
GPIO.output(led, GPIO.HIGH) sleep(duration) GPIO.output(led, GPIO.LOW) sleep(duration)
pi.gpio import RPi.GPIO as GPIO from time import sleep GPIO.setwarnings(False) # Ignore Warnings GPIO.setmode(GPIO.BOARD) # Use Physical Pin Numbering GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) def flash(led, duration):
64
64
35
7
57
gits00/raspberry-pi-computer-vision-programming
Chapter03/programs/02_SOS.py
Python
flash
flash
9
13
9
9
90d135c7100cbf1de1e4cdce5722cf24f0a9dfeb
bigcode/the-stack
train
f3e69ab32b62a1e4c58f2963
train
class
class TestTlacuilo: def test_script_can_be_configured(self): mocked_args_parser = Mock() mocked_args_parser.add_parser = Mock(return_value=mocked_args_parser) mocked_args_parser.add_argument = Mock(return_value=True) Tlacuilo(mocked_args_parser).configure() assert 6 == mock...
class TestTlacuilo:
def test_script_can_be_configured(self): mocked_args_parser = Mock() mocked_args_parser.add_parser = Mock(return_value=mocked_args_parser) mocked_args_parser.add_argument = Mock(return_value=True) Tlacuilo(mocked_args_parser).configure() assert 6 == mocked_args_parser.add_a...
import logging import pytest from mock import Mock from slippinj.cli.scripts.tlacuilo import Tlacuilo from slippinj.cli.objects.wf_configuration_object import WfConfigurationObject class TestTlacuilo:
51
256
892
7
43
scm-spain/slippin-jimmy
tests/slippinj/cli/scripts/test_tlacuilo.py
Python
TestTlacuilo
TestTlacuilo
10
121
10
10
a9053a280be61b54e88cd4c46a52413c9203632f
bigcode/the-stack
train
bd9fdd6b68eaf0d33a5ae88b
train
function
def decipher(message): words = message.split(' ') decipher_message = [] for word in words: decipher_word = '' for letter in word: for key, value in KEYS.iteritems(): if value == letter: decipher_word += key decipher_mes...
def decipher(message):
words = message.split(' ') decipher_message = [] for word in words: decipher_word = '' for letter in word: for key, value in KEYS.iteritems(): if value == letter: decipher_word += key decipher_message.append(decipher_wor...
= message.split(' ') cypher_message = [] for word in words: cypher_word = '' for letter in word: cypher_word += KEYS[letter] cypher_message.append(cypher_word) return ' '.join(cypher_message) def decipher(message):
64
64
74
4
60
ZeroGuess/Platzi-Curso-de-Python-2019
solutions/18_Criptografia.py
Python
decipher
decipher
86
101
86
86
f9800f7e27d25dd5db3a3abce34d6e4fc94e5985
bigcode/the-stack
train
4f6006fad68ee15551831075
train
function
def cypher(message): words = message.split(' ') cypher_message = [] for word in words: cypher_word = '' for letter in word: cypher_word += KEYS[letter] cypher_message.append(cypher_word) return ' '.join(cypher_message)
def cypher(message):
words = message.split(' ') cypher_message = [] for word in words: cypher_word = '' for letter in word: cypher_word += KEYS[letter] cypher_message.append(cypher_word) return ' '.join(cypher_message)
'5': 'v', '6': 'T', '7': 'V', '8': 'y', '9': 'K', '.': 'Z', ',': 'D', '?': 'F', '!': 'B', } def cypher(message):
64
64
67
5
59
ZeroGuess/Platzi-Curso-de-Python-2019
solutions/18_Criptografia.py
Python
cypher
cypher
72
83
72
72
c413af7392d6d519c53f473aba1eb645577055d8
bigcode/the-stack
train
8f6148d44e05b390dc3ae464
train
function
def run(): while True: command = str(raw_input('''--- * --- * --- * --- * --- * --- * --- * --- Bienvenido a criptografía. ¿Qué deseas hacer? [c]ifrar mensaje [d]ecifrar mensaje [s]alir ''')) if command == 'c': ...
def run():
while True: command = str(raw_input('''--- * --- * --- * --- * --- * --- * --- * --- Bienvenido a criptografía. ¿Qué deseas hacer? [c]ifrar mensaje [d]ecifrar mensaje [s]alir ''')) if command == 'c': message = str...
= [] for word in words: decipher_word = '' for letter in word: for key, value in KEYS.iteritems(): if value == letter: decipher_word += key decipher_message.append(decipher_word) return ' '.join(decipher_message) def run(...
64
64
181
4
60
ZeroGuess/Platzi-Curso-de-Python-2019
solutions/18_Criptografia.py
Python
run
run
104
129
104
105
7c4aa5f2001d39448d9d2a37b07f44efe70ec3b2
bigcode/the-stack
train
724258027a65ac3db3628f05
train
function
def test_hello_lib(): assert hello_lib.ohai('anthony') == 'ohai, anthony'
def test_hello_lib():
assert hello_lib.ohai('anthony') == 'ohai, anthony'
import hello_lib def test_hello_lib():
10
64
25
6
3
asottile/setuptools-golang-examples
tests/hello_lib_test.py
Python
test_hello_lib
test_hello_lib
4
5
4
4
280ac75bed5bf61dec002af4a8140cb3c3e23c02
bigcode/the-stack
train
b10167064d229498e32df445
train
function
def magisto_download(url, output_dir='.', merge=True, info_only=False, **kwargs): html = get_html(url) video_hash = r1(r'video\/([a-zA-Z0-9]+)', url) api_url = 'https://www.magisto.com/api/video/{}'.format(video_hash) content = get_html(api_url) data = json.loads(content) title1 = data['tit...
def magisto_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
html = get_html(url) video_hash = r1(r'video\/([a-zA-Z0-9]+)', url) api_url = 'https://www.magisto.com/api/video/{}'.format(video_hash) content = get_html(api_url) data = json.loads(content) title1 = data['title'] title2 = data['creator'] title = "%s - %s" % (title1, title2) url...
#!/usr/bin/env python __all__ = ['magisto_download'] from ..common import * import json def magisto_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
43
64
178
20
22
Garefield/webdecode
you_get/extractors/magisto.py
Python
magisto_download
magisto_download
8
23
8
8
012818912419ce5a917ce33d48a35b378561342e
bigcode/the-stack
train
3b4dba1ce538d5ce0d5a0fce
train
class
class Exchange(BaseExchange): def __init__(self, config={}): if 'asyncio_loop' in config: self.asyncio_loop = config['asyncio_loop'] self.asyncio_loop = self.asyncio_loop or asyncio.get_event_loop() self.aiohttp_trust_env = config.get('aiohttp_trust_env', self.aiohttp_trust_env)...
class Exchange(BaseExchange):
def __init__(self, config={}): if 'asyncio_loop' in config: self.asyncio_loop = config['asyncio_loop'] self.asyncio_loop = self.asyncio_loop or asyncio.get_event_loop() self.aiohttp_trust_env = config.get('aiohttp_trust_env', self.aiohttp_trust_env) self.verify = config.g...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- __version__ = '1.27.91' # ----------------------------------------------------------------------------- import asyncio import concurrent import socket import certifi import aiohttp import ssl import sys import ya...
146
256
2,384
5
141
milansar/ccxt
python/ccxt/async_support/base/exchange.py
Python
Exchange
Exchange
43
299
43
44
da259b5b23d5813d9a28e1584593f693f780a5eb
bigcode/the-stack
train
9731fc5cdc969c3867a559f3
train
function
def linfit(x,a,b): return a*x +b
def linfit(x,a,b):
return a*x +b
]'] dpdx = data['dpdx[Pa/km]'] dpdy = data['dpdy[Pa/km]'] hours = np.arange(len(u_vel)) dpdx_mean = np.mean(dpdx) # find linear fit to the observed - mean pressure gradient def linfit(x,a,b):
64
64
14
7
56
pjp4weather/sea_breeze_model
realcase.py
Python
linfit
linfit
31
32
31
31
5014b62937803c9ebd9806943e16f4d78be04fa5
bigcode/the-stack
train
626943cd9ad0bfe5a8a94569
train
function
def func(hours,A,phase): return A/sbm.rho*np.cos(2*np.pi*hours/24.+ phase)
def func(hours,A,phase):
return A/sbm.rho*np.cos(2*np.pi*hours/24.+ phase)
dpdx_synoptic # interpolation function for the y pressure gradient f_dpdy = interp.interp1d(np.arange(dpdy.size),dpdy) #%% ============================================================================= # Estimate A and phi # ============================================================================= # fit functio...
64
64
27
7
56
pjp4weather/sea_breeze_model
realcase.py
Python
func
func
48
49
48
48
b776d8051ba3528e6ff0f911be60a7625891f341
bigcode/the-stack
train
d47c52faba4d767227d88880
train
function
def print_stats(map): np.set_printoptions(precision=2, suppress=True) print(f"ALPHA = {ALPHA}, NUM_CLIENTS = 100") print("Class counter per user -> Row: USERS, Col: CLASS") print(map) print("Size dataset per user") print(map.sum(axis=1)) print("Size dataset per class") print(map.sum(axis...
def print_stats(map):
np.set_printoptions(precision=2, suppress=True) print(f"ALPHA = {ALPHA}, NUM_CLIENTS = 100") print("Class counter per user -> Row: USERS, Col: CLASS") print(map) print("Size dataset per user") print(map.sum(axis=1)) print("Size dataset per class") print(map.sum(axis=0)) print("Total ...
import sys import csv import numpy as np NUM_CLASSES = 10 ALPHA = 1 def print_stats(map):
28
64
129
5
22
Fra98/fed-learning-AML
utility/split_google.py
Python
print_stats
print_stats
8
20
8
8
238f0396de3b19b398159df96874a40f11e3759b
bigcode/the-stack
train
85e61358ec0b7bea2a1d1ae3
train
function
def main(): map = np.zeros((100, NUM_CLASSES), dtype=np.int64) with open(f"./utility/CIFAR_google/CIFAR{NUM_CLASSES}_splits/federated_train_alpha_{ALPHA:.2f}.csv", "r") as f: reader = csv.reader(f) next(reader) # header for line in reader: user_id, image_id, class_label =...
def main():
map = np.zeros((100, NUM_CLASSES), dtype=np.int64) with open(f"./utility/CIFAR_google/CIFAR{NUM_CLASSES}_splits/federated_train_alpha_{ALPHA:.2f}.csv", "r") as f: reader = csv.reader(f) next(reader) # header for line in reader: user_id, image_id, class_label = line ...
(axis=1)) print("Size dataset per class") print(map.sum(axis=0)) print("Total size") print(map.sum()) print("Percentage of classes for each user") print(100 * map / map.sum(axis=1).reshape(100, 1)) def main():
64
64
110
3
61
Fra98/fed-learning-AML
utility/split_google.py
Python
main
main
23
33
23
23
c2a21656587017581226343a1c8cfbc789b7918c
bigcode/the-stack
train
13f6382f9c1fc0d716a9d758
train
class
class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation): order = graphene.Field(Order, description="Related order.") class Arguments: id = graphene.ID(description="ID of the order line to update.", required=True) input = OrderLineInput( required=True, description="Fields ...
class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation):
order = graphene.Field(Order, description="Related order.") class Arguments: id = graphene.ID(description="ID of the order line to update.", required=True) input = OrderLineInput( required=True, description="Fields required to update an order line." ) class Meta: ...
import ValidationError from django.db import transaction from ....core.exceptions import InsufficientStock from ....core.permissions import OrderPermissions from ....core.tracing import traced_atomic_transaction from ....order import models from ....order.error_codes import OrderErrorCode from ....order.fetch import ...
142
142
475
13
128
eanknd/saleor
saleor/graphql/order/mutations/order_line_update.py
Python
OrderLineUpdate
OrderLineUpdate
19
93
19
19
ba922e2e955ced264a21fe39529a84cf5737d566
bigcode/the-stack
train
f73b2b8cf4a10b702bc0cf4d
train
function
@bot.event async def on_ready(): print('Logged in as') print(f'name: {bot.user.name}') print(f'id: {bot.user.id}') print('------')
@bot.event async def on_ready():
print('Logged in as') print(f'name: {bot.user.name}') print(f'id: {bot.user.id}') print('------')
otCog"] bot = commands.Bot(command_prefix="!", description='ScrumBot') ## @brief Sends a message to the terminal stating that the Discord bot is ready to use. # @details When ScrumBot is ready, it sends the terminal its name and id. @bot.event async def on_ready():
64
64
41
9
55
LeonSo7/ScrumBot
src/scrumbot.py
Python
on_ready
on_ready
19
24
19
20
0ffaaa1195dc5d912a6764618e45059bbf359d36
bigcode/the-stack
train
81ac495000c35da0e4399579
train
class
class Graph: def __init__(self,Nodes): self.nodes = Nodes self.adj_list = {} for node in self.nodes: self.adj_list[node] = [] def add_egde(self,v,u): self.adj_list[u].append(v) self.adj_list[v].append(u) def print_graph(self...
class Graph:
def __init__(self,Nodes): self.nodes = Nodes self.adj_list = {} for node in self.nodes: self.adj_list[node] = [] def add_egde(self,v,u): self.adj_list[u].append(v) self.adj_list[v].append(u) def print_graph(self): fo...
class Graph:
3
64
99
3
0
mukul20-21/python_datastructure
Graph/implement_adj_list_using_dict.py
Python
Graph
Graph
1
16
1
1
389ba2e12a876781193258abbc1fc55988702a36
bigcode/the-stack
train
7a4d7a67c8c3944905fae5cf
train
class
class SnowflakeInspector(interface.EngineInterface): """Access Snowflake database metadata. """ sys_schemas = [ 'information_schema', 'account_usage', ] table_properties = [] definitions_sql = SNOWFLAKE_DEFINITIONS_QUERY connect_timeout_attr = 'login_timeout' @classme...
class SnowflakeInspector(interface.EngineInterface):
"""Access Snowflake database metadata. """ sys_schemas = [ 'information_schema', 'account_usage', ] table_properties = [] definitions_sql = SNOWFLAKE_DEFINITIONS_QUERY connect_timeout_attr = 'login_timeout' @classmethod def has_indexes(self): return False ...
ON c.table_schema = t.table_schema AND c.table_name = t.table_name AND c.table_catalog = t.table_catalog LEFT JOIN information_schema.columns ic ON c.table_schema = ic.table_schema AND c.table_name = ic.table_name AND c.column_name = ic.column_name AND c.table_catalog = ic.table_catalog WHERE UPPER(t.t...
138
138
462
8
130
getmetamapper/metamapper
app/inspector/engines/snowflake_inspector.py
Python
SnowflakeInspector
SnowflakeInspector
45
123
45
45
2cc22f6d962287ce8088d74d73cbf0fc7d70e1dc
bigcode/the-stack
train
cf342549895dd281fe7c5caa
train
class
class IPTimeMonitorPacket(UsagePacket): """ Base usage packet parser and handler """ def __init__(self, address, packet): """ Initialize a usagepacket from a binary string containing the UDP packet contents. Arguments: self -- The new usagepacket.usagepacket obje...
class IPTimeMonitorPacket(UsagePacket):
""" Base usage packet parser and handler """ def __init__(self, address, packet): """ Initialize a usagepacket from a binary string containing the UDP packet contents. Arguments: self -- The new usagepacket.usagepacket object packet -- The binary packet c...
# Copyright 1999-2009 University of Chicago # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
183
183
612
9
173
jtfrey/globus-toolkit
usage/python/tools/source/globus/usage/iptimemonitorpacket.py
Python
IPTimeMonitorPacket
IPTimeMonitorPacket
25
101
25
25
0f7cb826a8c7c5bfb3f83519cfbc191b6e7beb9b
bigcode/the-stack
train
ed741de9083b80dfce801282
train
class
class EncodeError(Error): pass
class EncodeError(Error):
pass
"pure-virtual" and move # all implementation out, into reflection.py for now. """Contains an abstract base class for protocol messages.""" __author__ = 'robinson@google.com (Will Robinson)' class Error(Exception): pass class DecodeError(Error): pass class EncodeError(Error):
64
64
7
6
57
Dornbi/brickmesh
work/src/py/google/protobuf/message.py
Python
EncodeError
EncodeError
41
41
41
41
b392ed60a22b2602951a8a07cd9b5185b39419c4
bigcode/the-stack
train
9623eb0a42fb8fbf98952aae
train
class
class DecodeError(Error): pass
class DecodeError(Error):
pass
We should just make these methods all "pure-virtual" and move # all implementation out, into reflection.py for now. """Contains an abstract base class for protocol messages.""" __author__ = 'robinson@google.com (Will Robinson)' class Error(Exception): pass class DecodeError(Error):
64
64
7
6
57
Dornbi/brickmesh
work/src/py/google/protobuf/message.py
Python
DecodeError
DecodeError
40
40
40
40
41ae93da65003dca7a83a0c20dc6395a52194325
bigcode/the-stack
train
580403f7d0f5839e825317ff
train
class
class Error(Exception): pass
class Error(Exception):
pass
. # TODO(robinson): We should just make these methods all "pure-virtual" and move # all implementation out, into reflection.py for now. """Contains an abstract base class for protocol messages.""" __author__ = 'robinson@google.com (Will Robinson)' class Error(Exception):
63
64
6
5
58
Dornbi/brickmesh
work/src/py/google/protobuf/message.py
Python
Error
Error
39
39
39
39
02aa4587579faa8899fc9eae7c83ed43bbeed895
bigcode/the-stack
train
b416fac6f4202a94c3486e22
train
class
class Message(object): """Abstract base class for protocol messages. Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below. TODO(robinson): Link to an HTML document here. TODO(robinson): Document that ...
class Message(object):
"""Abstract base class for protocol messages. Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below. TODO(robinson): Link to an HTML document here. TODO(robinson): Document that instances of this class ...
derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIM...
256
256
1,921
4
251
Dornbi/brickmesh
work/src/py/google/protobuf/message.py
Python
Message
Message
44
292
44
45
000135b8a710573d783dbc480af9c1af83618b49
bigcode/the-stack
train
a2f0dbee8cfb62b3c968441b
train
class
class MATS: ''' 読み込み材質データ ''' def __init__(self): self.name='' self.comment='' self.entries=[] @staticmethod def parse(assets_dir, lines): ''' PMCA Materials list v2.0 をパースする。 ''' parts_dir = assets_dir active=...
class MATS:
''' 読み込み材質データ ''' def __init__(self): self.name='' self.comment='' self.entries=[] @staticmethod def parse(assets_dir, lines): ''' PMCA Materials list v2.0 をパースする。 ''' parts_dir = assets_dir active=MATS() f...
# coding: utf-8 from logging import getLogger logger = getLogger(__name__) class MATS_ENTRY: def __init__(self, name, parts_dir): self.name=name self.parts_dir=parts_dir self.tex=None self.toon=None self.diff_rgb=None self.spec_rgb=None self.mirr_rgb=None # ...
116
135
450
5
111
ousttrue/PMCAplus
PyPMCA/material_entry.py
Python
MATS
MATS
22
85
22
22
5a713fedf19ca3f39036f53c019b68945c4e8d53
bigcode/the-stack
train
cdd8f9aab323298c8efdbff0
train
class
class MATS_ENTRY: def __init__(self, name, parts_dir): self.name=name self.parts_dir=parts_dir self.tex=None self.toon=None self.diff_rgb=None self.spec_rgb=None self.mirr_rgb=None # ambien self.author=None def get_tex_path(self): if self....
class MATS_ENTRY:
def __init__(self, name, parts_dir): self.name=name self.parts_dir=parts_dir self.tex=None self.toon=None self.diff_rgb=None self.spec_rgb=None self.mirr_rgb=None # ambien self.author=None def get_tex_path(self): if self.tex: r...
# coding: utf-8 from logging import getLogger logger = getLogger(__name__) class MATS_ENTRY:
25
64
91
5
20
ousttrue/PMCAplus
PyPMCA/material_entry.py
Python
MATS_ENTRY
MATS_ENTRY
6
19
6
6
e719ebc9661e46e8a66c7a9802a50a10c49c8243
bigcode/the-stack
train
1d8fc66ce0764c3efae894f6
train
class
class ValidateLookIdReferenceEdits(pyblish.api.InstancePlugin): """Validate nodes in look have no reference edits to cbId. Note: This only validates the cbId edits on the referenced nodes that are used in the look. For example, a transform can have its cbId changed without being invalid...
class ValidateLookIdReferenceEdits(pyblish.api.InstancePlugin):
"""Validate nodes in look have no reference edits to cbId. Note: This only validates the cbId edits on the referenced nodes that are used in the look. For example, a transform can have its cbId changed without being invalidated when it is not used in the look's assignment. """ ...
from collections import defaultdict from maya import cmds import pyblish.api import pype.api import pype.hosts.maya.action class ValidateLookIdReferenceEdits(pyblish.api.InstancePlugin):
44
178
595
14
29
kalisp/pype
pype/plugins/maya/publish/validate_look_id_reference_edits.py
Python
ValidateLookIdReferenceEdits
ValidateLookIdReferenceEdits
9
98
9
9
2fd4811c52f865301f5bd08a3e745992a60ad889
bigcode/the-stack
train
619ec519c9b05a4b4d0ac1c7
train
function
def solve_quadratic(a, b, c): """Returns the two solutions of the quadratic equation ax^2 + bx + c = 0.""" D = b ** 2 - 4 * a * c assert D >= 0 return (-b + np.sqrt(D)) / (2 * a), (-b - np.sqrt(D)) / (2 * a)
def solve_quadratic(a, b, c):
"""Returns the two solutions of the quadratic equation ax^2 + bx + c = 0.""" D = b ** 2 - 4 * a * c assert D >= 0 return (-b + np.sqrt(D)) / (2 * a), (-b - np.sqrt(D)) / (2 * a)
h, y[n] + k3 * h) y[n+1] = y[n] + h * (k1 + 2 * k2 + 2 * k3 + k4) / 6 return t, y def solve_quadratic(a, b, c):
64
64
82
11
52
MarkBebawy/PCS
code/tools.py
Python
solve_quadratic
solve_quadratic
39
43
39
39
af4f71a73a67c0bda9e4b1afb9a3f23a049960d1
bigcode/the-stack
train
dc32d7620ea5276b4e88f522
train
function
def rk4(f, t0, y0, h, N): """"Solve IVP given by y' = f(t, y), y(t_0) = y_0 with step size h > 0, for N steps, using the Runge-Kutta 4 method. Also works if y is an n-vector and f is a vector-valued function.""" t = t0 + np.array([i * h for i in range(N+1)]) m = len(y0) y = np.zeros((N+1, m)) ...
def rk4(f, t0, y0, h, N):
""""Solve IVP given by y' = f(t, y), y(t_0) = y_0 with step size h > 0, for N steps, using the Runge-Kutta 4 method. Also works if y is an n-vector and f is a vector-valued function.""" t = t0 + np.array([i * h for i in range(N+1)]) m = len(y0) y = np.zeros((N+1, m)) y[0] = y0 # Repeate...
0) y = np.zeros((N+1, m)) y[0] = y0 # Repeatedly approximate next value. for n in range(N): y[n+1] = y[n] + h*f(t[n], y[n]) return t, y def rk4(f, t0, y0, h, N):
79
79
266
15
63
MarkBebawy/PCS
code/tools.py
Python
rk4
rk4
20
37
20
20
ccd034d70a497cae760ec707adfd69d75c863d33
bigcode/the-stack
train
773f26ea8f4b645c6d9139d1
train
function
def fe(f, t0, y0, h, N): """"Solve IVP given by y' = f(t, y), y(t_0) = y_0 with step size h > 0, for N steps, using the Forward-Euler method. Also works if y is an n-vector and f is a vector-valued function.""" t = t0 + np.array([i * h for i in range(N+1)]) m = len(y0) y = np.zeros((N+1, m)) ...
def fe(f, t0, y0, h, N):
""""Solve IVP given by y' = f(t, y), y(t_0) = y_0 with step size h > 0, for N steps, using the Forward-Euler method. Also works if y is an n-vector and f is a vector-valued function.""" t = t0 + np.array([i * h for i in range(N+1)]) m = len(y0) y = np.zeros((N+1, m)) y[0] = y0 # Repeate...
## Tools for solving differential equations. Also includes a solver for quadratic ## equations and a simple implementation of the bisection method. import numpy as np def fe(f, t0, y0, h, N):
47
64
166
14
32
MarkBebawy/PCS
code/tools.py
Python
fe
fe
6
18
6
6
a9fcd89a41e38ce95f83e65badb02bba18e02572
bigcode/the-stack
train
98a3a5ab89f8f42b5df90f8b
train
function
def bisect(f, x_low, x_high, n): """Apply bisection method n times to function f.""" s = np.sign(f(x_low)) t = np.sign(f(x_high)) assert s != t for _ in range(n): x = (x_low + x_high) / 2 y = f(x) if y == 0: return x elif np.sign(y) == s: x_lo...
def bisect(f, x_low, x_high, n):
"""Apply bisection method n times to function f.""" s = np.sign(f(x_low)) t = np.sign(f(x_high)) assert s != t for _ in range(n): x = (x_low + x_high) / 2 y = f(x) if y == 0: return x elif np.sign(y) == s: x_low = x else: x...
.""" D = b ** 2 - 4 * a * c assert D >= 0 return (-b + np.sqrt(D)) / (2 * a), (-b - np.sqrt(D)) / (2 * a) def bisect(f, x_low, x_high, n):
64
64
125
13
51
MarkBebawy/PCS
code/tools.py
Python
bisect
bisect
45
60
45
45
3da08b6d5a4e429779f86db8410323b2253aeb16
bigcode/the-stack
train
0f843738675e1de45f4d03fe
train
function
def test_notepad(): if os.path.exists('test.txt'): os.remove('test.txt') # 打开一个记事本(如果已经打开,可以忽略) app = Application().start("notepad.exe") # 绑定进程,class_name和title是可选的,可以灵活使用,如果找到多个货没有找到该程序,程序会报错 app = Application().connect(class_name="Notepad", title="无标题 - 记事本") # 得到可操作的窗口,可以传入标题,类名,或者将...
def test_notepad():
if os.path.exists('test.txt'): os.remove('test.txt') # 打开一个记事本(如果已经打开,可以忽略) app = Application().start("notepad.exe") # 绑定进程,class_name和title是可选的,可以灵活使用,如果找到多个货没有找到该程序,程序会报错 app = Application().connect(class_name="Notepad", title="无标题 - 记事本") # 得到可操作的窗口,可以传入标题,类名,或者将标题传入键值 win = app...
import os from pywinauto.application import Application def test_notepad():
17
81
273
5
11
laashub-sua/demo-pywinauto
old/test.py
Python
test_notepad
test_notepad
6
29
6
6
1adf0569f0690596207ddfba2b484b1b983bf780
bigcode/the-stack
train
d8be32b2a0b6797c56bbcebd
train
class
class XenapiInspector(virt_inspector.Inspector): def __init__(self): super(XenapiInspector, self).__init__() self.session = get_api_session() def _get_host_ref(self): """Return the xenapi host on which nova-compute runs on.""" return self.session.xenapi.session.get_this_host(se...
class XenapiInspector(virt_inspector.Inspector):
def __init__(self): super(XenapiInspector, self).__init__() self.session = get_api_session() def _get_host_ref(self): """Return the xenapi host on which nova-compute runs on.""" return self.session.xenapi.session.get_this_host(self.session.handle) def _call_xenapi(self, met...
=True), cfg.IntOpt('login_timeout', default=10, help='Timeout in seconds for XenAPI login.'), ] CONF = cfg.CONF CONF.register_group(opt_group) CONF.register_opts(OPTS, group=opt_group) class XenapiException(virt_inspector.InspectorException): pass def get_api_session(): if...
256
256
1,013
12
243
rdo-management/ceilometer
ceilometer/compute/virt/xenapi/inspector.py
Python
XenapiInspector
XenapiInspector
78
175
78
79
2b9ae943984fe91f4e09faf3389029b05cdb8cd0
bigcode/the-stack
train
550cdc2bb2405e162b791116
train
class
class XenapiException(virt_inspector.InspectorException): pass
class XenapiException(virt_inspector.InspectorException):
pass
=True), cfg.IntOpt('login_timeout', default=10, help='Timeout in seconds for XenAPI login.'), ] CONF = cfg.CONF CONF.register_group(opt_group) CONF.register_opts(OPTS, group=opt_group) class XenapiException(virt_inspector.InspectorException):
64
64
16
13
51
rdo-management/ceilometer
ceilometer/compute/virt/xenapi/inspector.py
Python
XenapiException
XenapiException
51
52
51
51
8fa8c1a6ea5402743c2ca8143c12471cfa891bcd
bigcode/the-stack
train
da9729ec3229e4375720983e
train
function
def get_api_session(): if not api: raise ImportError(_('XenAPI not installed')) url = CONF.xenapi.connection_url username = CONF.xenapi.connection_username password = CONF.xenapi.connection_password if not url or password is None: raise XenapiException(_('Must specify connection_url...
def get_api_session():
if not api: raise ImportError(_('XenAPI not installed')) url = CONF.xenapi.connection_url username = CONF.xenapi.connection_username password = CONF.xenapi.connection_password if not url or password is None: raise XenapiException(_('Must specify connection_url, and ' ...
_timeout', default=10, help='Timeout in seconds for XenAPI login.'), ] CONF = cfg.CONF CONF.register_group(opt_group) CONF.register_opts(OPTS, group=opt_group) class XenapiException(virt_inspector.InspectorException): pass def get_api_session():
64
64
177
5
58
rdo-management/ceilometer
ceilometer/compute/virt/xenapi/inspector.py
Python
get_api_session
get_api_session
55
75
55
55
8724e41e00338b1c7f1ff74cf4f122011964c391
bigcode/the-stack
train
d5e33d3b18b47078069995bf
train
function
def in_sorted_array(e: int, array: np.ndarray) -> bool: pos = np.searchsorted(array, e) if pos == len(array) or pos == -1: return False else: return array[pos] == e
def in_sorted_array(e: int, array: np.ndarray) -> bool:
pos = np.searchsorted(array, e) if pos == len(array) or pos == -1: return False else: return array[pos] == e
) dataloders['val'] = DataLoader(datasets['val'], batch_sampler=val_sampler, collate_fn=val_collate_fn, num_workers=params.num_workers, pin_memory=True) return dataloders def in_sorted_array(e: int, array: np.ndarray) -> bool:
64
64
54
16
47
jac99/MinkLoc3D
datasets/dataset_utils.py
Python
in_sorted_array
in_sorted_array
94
99
94
94
564a2ed3e9f61a72d654a2eeafae56aa178b218a
bigcode/the-stack
train
b724a37f054f20a9a0d522ca
train
function
def make_collate_fn(dataset: OxfordDataset, mink_quantization_size=None): # set_transform: the transform to be applied to all batch elements def collate_fn(data_list): # Constructs a batch object clouds = [e[0] for e in data_list] labels = [e[1] for e in data_list] batch = torch....
def make_collate_fn(dataset: OxfordDataset, mink_quantization_size=None): # set_transform: the transform to be applied to all batch elements
def collate_fn(data_list): # Constructs a batch object clouds = [e[0] for e in data_list] labels = [e[1] for e in data_list] batch = torch.stack(clouds, dim=0) # Produces (batch_size, n_points, 3) tensor if dataset.set_transform is not None: # Apply the same...
datasets = {} train_transform = TrainTransform(params.aug_mode) train_set_transform = TrainSetTransform(params.aug_mode) datasets['train'] = OxfordDataset(params.dataset_folder, params.train_file, train_transform, set_transform=train_set_transform) val_transfor...
123
123
412
31
91
jac99/MinkLoc3D
datasets/dataset_utils.py
Python
make_collate_fn
make_collate_fn
28
62
28
29
66ae9bce8a58f21c352479c68184435860bb5153
bigcode/the-stack
train
ccc5c9ee39e69f8a9f23493a
train
function
def make_datasets(params: MinkLocParams, debug=False): # Create training and validation datasets datasets = {} train_transform = TrainTransform(params.aug_mode) train_set_transform = TrainSetTransform(params.aug_mode) datasets['train'] = OxfordDataset(params.dataset_folder, params.train_file, train...
def make_datasets(params: MinkLocParams, debug=False): # Create training and validation datasets
datasets = {} train_transform = TrainTransform(params.aug_mode) train_set_transform = TrainSetTransform(params.aug_mode) datasets['train'] = OxfordDataset(params.dataset_folder, params.train_file, train_transform, set_transform=train_set_transform) val_transfor...
import DataLoader import MinkowskiEngine as ME from datasets.oxford import OxfordDataset, TrainTransform, TrainSetTransform from datasets.samplers import BatchSampler from misc.utils import MinkLocParams def make_datasets(params: MinkLocParams, debug=False): # Create training and validation datasets
64
64
113
21
42
jac99/MinkLoc3D
datasets/dataset_utils.py
Python
make_datasets
make_datasets
14
25
14
15
f64eb638540b3410bc80d01ed18c1df7c359b429
bigcode/the-stack
train
5f7b463014d87410e9d961fc
train
function
def make_dataloaders(params: MinkLocParams, debug=False): """ Create training and validation dataloaders that return groups of k=2 similar elements :param train_params: :param model_params: :return: """ datasets = make_datasets(params, debug=debug) dataloders = {} train_sampler = Ba...
def make_dataloaders(params: MinkLocParams, debug=False):
""" Create training and validation dataloaders that return groups of k=2 similar elements :param train_params: :param model_params: :return: """ datasets = make_datasets(params, debug=debug) dataloders = {} train_sampler = BatchSampler(datasets['train'], batch_size=params.batch_size...
_negatives) for e in labels] for label in labels] positives_mask = torch.tensor(positives_mask) negatives_mask = torch.tensor(negatives_mask) # Returns (batch_size, n_points, 3) tensor and positives_mask and # negatives_mask which are batch_size x batch_size boolean tensors retu...
99
99
333
15
83
jac99/MinkLoc3D
datasets/dataset_utils.py
Python
make_dataloaders
make_dataloaders
65
91
65
65
88825fcb12871d23b88f52c46dc551705545dc48
bigcode/the-stack
train
e8bf62ac04a9a5e5bdc4b9d3
train
function
def score(fname, picker, width=500, images=False): """Run the treescoring process on an image. Usage:: >>> import treescore.judge as judge >>> scores = judge.score(fname, picker) >>> scores, images, composite = judge.score(fname, picker, images=True) :param fname: A string, the full path to t...
def score(fname, picker, width=500, images=False):
"""Run the treescoring process on an image. Usage:: >>> import treescore.judge as judge >>> scores = judge.score(fname, picker) >>> scores, images, composite = judge.score(fname, picker, images=True) :param fname: A string, the full path to the image file :param picker: A :class:`ColorPic...
""" Runs the Treescore judging process """ from . import utils from . import leds from . import shape from . import colors from . import draw import numpy as np from collections import namedtuple Scores = namedtuple('Scores', 'overall led shape color area') Images = namedtuple( 'Images', 'original leds contour o...
93
139
465
13
80
christianreimer/treescore
treescore/judge/__init__.py
Python
score
score
19
66
19
19
d93c5a1cf9ce272f19ef3f071eccf82220da4af7
bigcode/the-stack
train
2bcc5b6f555e705ab4f6c0c1
train
function
def concat_img(images): row1 = np.concatenate((images.original, images.gray_sketched), axis=1) row1 = utils.resize(row1, width=880) row2 = np.concatenate( (images.contour, images.leds, images.outline, images.sketched), axis=1) row2 = utils.resize(row2, width=880) img = np.concatenate...
def concat_img(images):
row1 = np.concatenate((images.original, images.gray_sketched), axis=1) row1 = utils.resize(row1, width=880) row2 = np.concatenate( (images.contour, images.leds, images.outline, images.sketched), axis=1) row2 = utils.resize(row2, width=880) img = np.concatenate((row1, row2), axis=0) ...
point_lst, corners) img_tup = Images( img_original, img_leds, img_contour, img_outline, img_sketched, img_gray_sketched) return score_tup, img_tup, concat_img(img_tup) def concat_img(images):
64
64
103
5
59
christianreimer/treescore
treescore/judge/__init__.py
Python
concat_img
concat_img
69
77
69
69
cd5f66d04137cd31265f5d9030818f140dc1fa9b
bigcode/the-stack
train
157483bf43fa0524315813a2
train
function
async def historical_command(ctx, signal="", start=""): """Displays historical price comparison between similar companies [Yahoo Finance]""" try: # Debug user input if cfg.DEBUG: print(f"!stocks.scr.historical {signal} {start}") # Check for argument if signal == "" ...
async def historical_command(ctx, signal="", start=""):
"""Displays historical price comparison between similar companies [Yahoo Finance]""" try: # Debug user input if cfg.DEBUG: print(f"!stocks.scr.historical {signal} {start}") # Check for argument if signal == "" or signal not in list(so.d_signals_desc.keys): ...
import os import random from datetime import datetime, timedelta import configparser import discord from matplotlib import pyplot as plt import yfinance as yf from pandas.plotting import register_matplotlib_converters from finvizfinance.screener import ticker from gamestonk_terminal.config_plot import PLOT_DPI from ga...
149
256
1,039
11
137
DidierRLopes/GST-discordbot
discordbot/stocks/screener/historical.py
Python
historical_command
historical_command
22
164
22
22
4569dea865d61027a30b8178bb011138f5c2f803
bigcode/the-stack
train
ffbde09267b8db2c4b38d65e
train
class
class BaseDataConnection: _DATA_DIRECTORY = files_utils.get_data_dir() _STATEMENT_DIRECTORY = files_utils.get_statements_data_dir() _PRICES_DIRECTORY = files_utils.get_price_data_dir() _FX_DIRECTORY = files_utils.get_fx_data_dir() _FILE_PREFIX: str _NAME: str _URL: str @property de...
class BaseDataConnection:
_DATA_DIRECTORY = files_utils.get_data_dir() _STATEMENT_DIRECTORY = files_utils.get_statements_data_dir() _PRICES_DIRECTORY = files_utils.get_price_data_dir() _FX_DIRECTORY = files_utils.get_fx_data_dir() _FILE_PREFIX: str _NAME: str _URL: str @property def data_dir(self): ...
from datetime import datetime import pandas as pd from ..utils import files_utils, dates_utils class BaseDataConnection:
25
124
416
5
19
phil-lo/pyportlib
pyportlib/market_data_sources/base_data_connection.py
Python
BaseDataConnection
BaseDataConnection
7
71
7
7
267bcbdd5d1923670b3e6b350898adeab4e209c7
bigcode/the-stack
train
402dcf4b1d2407d14ed3708c
train
function
def segment_user_data(request, segment_id): if request.user.has_perm('wagtailadmin.access_admin'): segment = get_object_or_404(Segment, pk=segment_id) response = HttpResponse(content_type='text/csv; charset=utf-8') response['Content-Disposition'] = \ 'attachment;filename=segment...
def segment_user_data(request, segment_id):
if request.user.has_perm('wagtailadmin.access_admin'): segment = get_object_or_404(Segment, pk=segment_id) response = HttpResponse(content_type='text/csv; charset=utf-8') response['Content-Disposition'] = \ 'attachment;filename=segment-%s-users.csv' % str(segment_id) he...
= variant_metadata.first() else: variant = metadata.copy_for_segment(segment) edit_url = reverse('wagtailadmin_pages:edit', args=[variant.id]) return HttpResponseRedirect(edit_url) return HttpResponseForbidden() # CSV download views def segment_user_data(request, segment_id)...
64
64
174
9
54
ixc/wagtail-personalisation
src/wagtail_personalisation/views.py
Python
segment_user_data
segment_user_data
188
213
188
188
93ecf0aef1c23dc35e06b76ea9f11dff2a8d02c7
bigcode/the-stack
train
6d19351e2018f8b26c6914c0
train
class
class SegmentModelDashboardView(IndexView): """Additional dashboard functionality.""" def media(self): return forms.Media( css={'all': ['css/dashboard.css']}, js=['js/commons.js', 'js/dashboard.js'] ) def get_template_names(self): return [ 'modela...
class SegmentModelDashboardView(IndexView):
"""Additional dashboard functionality.""" def media(self): return forms.Media( css={'all': ['css/dashboard.css']}, js=['js/commons.js', 'js/dashboard.js'] ) def get_template_names(self): return [ 'modeladmin/wagtail_personalisation/segment/dashboa...
import DeleteView, IndexView from wagtail.core.models import Page from wagtail_personalisation.models import Segment from wagtail_personalisation.utils import can_delete_pages class SegmentModelIndexView(IndexView): """Placeholder for additional list functionality.""" pass class SegmentModelDashboardView(In...
64
64
84
8
55
ixc/wagtail-personalisation
src/wagtail_personalisation/views.py
Python
SegmentModelDashboardView
SegmentModelDashboardView
26
38
26
26
124ba7b199ae29d7a9c538a278d1c7d2b0723583
bigcode/the-stack
train
670a80853a2c50099f430576
train
function
def toggle(request, segment_id): """Toggle the status of the selected segment. :param request: The http request :type request: django.http.HttpRequest :param segment_id: The primary key of the segment :type segment_id: int :returns: A redirect to the original page :rtype: django.http.HttpRe...
def toggle(request, segment_id):
"""Toggle the status of the selected segment. :param request: The http request :type request: django.http.HttpRequest :param segment_id: The primary key of the segment :type segment_id: int :returns: A redirect to the original page :rtype: django.http.HttpResponseRedirect """ if re...
': request.session['segment_view'] = 'list' elif request.session['segment_view'] != 'dashboard': request.session['segment_view'] = 'dashboard' return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) return HttpResponseForbidden() def toggle(request, segment_id):...
64
64
136
7
57
ixc/wagtail-personalisation
src/wagtail_personalisation/views.py
Python
toggle
toggle
135
153
135
135
1e44bf19d2d495157464a2d18d1e06da9b81f612
bigcode/the-stack
train
f0a17bad83f1fa94ad16ff48
train
class
class SegmentModelDeleteView(DeleteView): def get_affected_page_objects(self): return Page.objects.filter(pk__in=( self.instance.get_used_pages().values_list('variant_id', flat=True) )) def get_template_names(self): return [ 'modeladmin/wagtail_personalisation/se...
class SegmentModelDeleteView(DeleteView):
def get_affected_page_objects(self): return Page.objects.filter(pk__in=( self.instance.get_used_pages().values_list('variant_id', flat=True) )) def get_template_names(self): return [ 'modeladmin/wagtail_personalisation/segment/delete.html', 'modeladmi...
media(self): return forms.Media( css={'all': ['css/dashboard.css']}, js=['js/commons.js', 'js/dashboard.js'] ) def get_template_names(self): return [ 'modeladmin/wagtail_personalisation/segment/dashboard.html', 'modeladmin/index.html' ...
76
77
258
8
68
ixc/wagtail-personalisation
src/wagtail_personalisation/views.py
Python
SegmentModelDeleteView
SegmentModelDeleteView
41
74
41
41
338a1bcf577d0ce0c2d8c4a59477e0b66afb7a39
bigcode/the-stack
train
daf4ba8e84c6892247dad032
train
function
def toggle_segment_view(request): """Toggle between the list view and dashboard view. :param request: The http request :type request: django.http.HttpRequest :returns: A redirect to the original page :rtype: django.http.HttpResponseRedirect """ if request.user.has_perm('wagtailadmin.access...
def toggle_segment_view(request):
"""Toggle between the list view and dashboard view. :param request: The http request :type request: django.http.HttpRequest :returns: A redirect to the original page :rtype: django.http.HttpResponseRedirect """ if request.user.has_perm('wagtailadmin.access_admin'): if request.sessi...
len(obj.get_used_pages()) def variant_count(self, obj): return len(obj.get_created_variants()) def statistics(self, obj): return _("{visits} visits in {days} days").format( visits=obj.visit_count, days=obj.get_active_days()) def toggle_segment_view(request):
64
64
141
6
58
ixc/wagtail-personalisation
src/wagtail_personalisation/views.py
Python
toggle_segment_view
toggle_segment_view
114
132
114
114
78562430a125a1db8101d756c35c7ff4f5e95693
bigcode/the-stack
train
310e903fac4ec3a28cc2cb7d
train
class
class SegmentModelIndexView(IndexView): """Placeholder for additional list functionality.""" pass
class SegmentModelIndexView(IndexView):
"""Placeholder for additional list functionality.""" pass
.contrib.modeladmin.options import ModelAdmin, modeladmin_register from wagtail.contrib.modeladmin.views import DeleteView, IndexView from wagtail.core.models import Page from wagtail_personalisation.models import Segment from wagtail_personalisation.utils import can_delete_pages class SegmentModelIndexView(IndexView)...
64
64
19
8
55
ixc/wagtail-personalisation
src/wagtail_personalisation/views.py
Python
SegmentModelIndexView
SegmentModelIndexView
21
23
21
21
8f73fbd769cfafc0fd3540625282e8a3307a0996
bigcode/the-stack
train
752c8165524ec5c9374cece4
train
function
def copy_page_view(request, page_id, segment_id): """Copy page with selected segment. If the page for the selected segment already exists the user will be redirected to that particular page. :param request: The http request :type request: django.http.HttpRequest :param page_id: The primary key of t...
def copy_page_view(request, page_id, segment_id):
"""Copy page with selected segment. If the page for the selected segment already exists the user will be redirected to that particular page. :param request: The http request :type request: django.http.HttpRequest :param page_id: The primary key of the page :type segment_id: int :param segme...
.HttpResponseRedirect """ if request.user.has_perm('wagtailadmin.access_admin'): segment = get_object_or_404(Segment, pk=segment_id) segment.toggle() return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) return HttpResponseForbidden() def copy_page_view(request, page...
74
74
249
12
62
ixc/wagtail-personalisation
src/wagtail_personalisation/views.py
Python
copy_page_view
copy_page_view
156
184
156
156
a0a4bfef2dc014a989abe6a9a9a18be9f523f734
bigcode/the-stack
train
c45b5a947ea761c08778b507
train
class
@modeladmin_register class SegmentModelAdmin(ModelAdmin): """The model admin for the Segments administration interface.""" model = Segment index_view_class = SegmentModelIndexView dashboard_view_class = SegmentModelDashboardView delete_view_class = SegmentModelDeleteView menu_icon = 'fa-snowflak...
@modeladmin_register class SegmentModelAdmin(ModelAdmin):
"""The model admin for the Segments administration interface.""" model = Segment index_view_class = SegmentModelIndexView dashboard_view_class = SegmentModelDashboardView delete_view_class = SegmentModelDeleteView menu_icon = 'fa-snowflake-o' add_to_settings_menu = False list_display = (...
() super().delete_instance() def post(self, request, *args, **kwargs): if not can_delete_pages(self.get_affected_page_objects(), self.request.user): context = self.get_context_data( cannot_delete_page_variants_error=True, )...
90
90
300
12
78
ixc/wagtail-personalisation
src/wagtail_personalisation/views.py
Python
SegmentModelAdmin
SegmentModelAdmin
77
111
77
78
2fa5455fb7a3b83690ac54ebeb717d152bfb94ea
bigcode/the-stack
train
31c6501672ea78960fe641cb
train
function
def async_delete(path): """ Asynchronously delete a file or a directory. This functionality is handy for deleting large directories. For example, in ClusterRunner, deleting the results directory can take up to half an hour. With async_delete(), the delete call will return almost immediately. Under ...
def async_delete(path):
""" Asynchronously delete a file or a directory. This functionality is handy for deleting large directories. For example, in ClusterRunner, deleting the results directory can take up to half an hour. With async_delete(), the delete call will return almost immediately. Under the covers, this is impl...
import os import shutil import tarfile import tempfile import zipfile from app.util.process_utils import Popen_with_delayed_expansion def async_delete(path):
36
64
202
5
30
rsennewald/ClusterRunner
app/util/fs.py
Python
async_delete
async_delete
10
26
10
10
2ea343003aba5e1ff9bf6ac1aa6d132da70b7fc0
bigcode/the-stack
train
a5f6605b473078a126a121f6
train
function
def zip_directory(target_dir: str, archive_filename: str) -> str: """ Zip up the specified directory and stick the resulting zip file in that directory. :param target_dir: the directory to zip and the location of the resulting zip file :param archive_filename: filename for the created zip file :retu...
def zip_directory(target_dir: str, archive_filename: str) -> str:
""" Zip up the specified directory and stick the resulting zip file in that directory. :param target_dir: the directory to zip and the location of the resulting zip file :param archive_filename: filename for the created zip file :return: the full path to the created zip archive file """ # Cr...
archive file :return: """ with tarfile.open(tarfile_path, 'w:gz') as tar: for dir_path, archive_name in target_dirs_to_archive_paths.items(): target_dir = os.path.normpath(dir_path) tar.add(target_dir, arcname=archive_name) def zip_directory(target_dir: str, archive_filename...
81
81
271
16
65
rsennewald/ClusterRunner
app/util/fs.py
Python
zip_directory
zip_directory
126
146
126
126
c63d542ee3cc2bf8c95e181388cf19f6cc453835
bigcode/the-stack
train
0ea579da8103e97b35231b96
train
function
def tar_directory(target_dir: str, archive_filename: str) -> str: """ Tar up the specified directory. :param target_dir: directory whose contents to tar up and where the tar file will be created :param archive_filename: name of the tar file :return: path to the created tar file """ tar_file ...
def tar_directory(target_dir: str, archive_filename: str) -> str:
""" Tar up the specified directory. :param target_dir: directory whose contents to tar up and where the tar file will be created :param archive_filename: name of the tar file :return: path to the created tar file """ tar_file = os.path.join( target_dir, archive_filename )...
to same directory as tar file try: with tarfile.open(archive_file, 'r:gz') as f: f.extractall(target_dir) finally: if delete: os.remove(archive_file) def tar_directory(target_dir: str, archive_filename: str) -> str:
64
64
121
16
48
rsennewald/ClusterRunner
app/util/fs.py
Python
tar_directory
tar_directory
94
109
94
94
ae0ad1c851fdd8804786cd19f07af68ccdf7f0f8
bigcode/the-stack
train
e0061956561af5ce8547560a
train
function
def tar_directories(target_dirs_to_archive_paths, tarfile_path): """ Tar up the specified directories. :param target_dirs_to_archive_paths: mapping of directories to their intended path in the archive file. :type target_dirs_to_archive_paths: dict :param tarfile_path: the path of the resulting archi...
def tar_directories(target_dirs_to_archive_paths, tarfile_path):
""" Tar up the specified directories. :param target_dirs_to_archive_paths: mapping of directories to their intended path in the archive file. :type target_dirs_to_archive_paths: dict :param tarfile_path: the path of the resulting archive file :return: """ with tarfile.open(tarfile_path, ...
tar_file = os.path.join( target_dir, archive_filename ) tar_directories( target_dirs_to_archive_paths={target_dir: '.'}, tarfile_path=tar_file, ) return tar_file def tar_directories(target_dirs_to_archive_paths, tarfile_path):
64
64
132
14
49
rsennewald/ClusterRunner
app/util/fs.py
Python
tar_directories
tar_directories
112
123
112
112
bc95486fb96eac59af3dc7ad537a7692c9b13639
bigcode/the-stack
train
af6d8bd344c9e9bf05cc441a
train
function
def unzip_directory(archive_file: str, target_dir: str=None, delete: bool=False): """ Extract the specified zip file. :param archive_file: the zip archive file to extract :param target_dir: the directory in which to extract; defaults to same as archive file :param delete: whether to delete the zip a...
def unzip_directory(archive_file: str, target_dir: str=None, delete: bool=False):
""" Extract the specified zip file. :param archive_file: the zip archive file to extract :param target_dir: the directory in which to extract; defaults to same as archive file :param delete: whether to delete the zip archive file after unpacking """ if not target_dir: target_dir, _ =...
if os.path.isfile(path): relpath = os.path.relpath(path, target_dir) zf.write(path, relpath) shutil.move(tmp_zip_filename, target_path) return target_path def unzip_directory(archive_file: str, target_dir: str=None, delete: bool=False):
64
64
134
20
43
rsennewald/ClusterRunner
app/util/fs.py
Python
unzip_directory
unzip_directory
149
162
149
149
17bcb76cac34ebe0782b67e1c1f2ae4d2c9386fb
bigcode/the-stack
train
2dad6b792e487698959d85f6
train
function
def extract_tar(archive_file, target_dir=None, delete=False): """ :param archive_file: :type archive_file: :param target_dir: :type target_dir: :param delete: :type delete: :return: :rtype: """ if not target_dir: target_dir, _ = os.path.split(archive_file) # default...
def extract_tar(archive_file, target_dir=None, delete=False):
""" :param archive_file: :type archive_file: :param target_dir: :type target_dir: :param delete: :type delete: :return: :rtype: """ if not target_dir: target_dir, _ = os.path.split(archive_file) # default to same directory as tar file try: with tarfile....
utf-8'} # This is necessary since UTF-8 is not the default on all systems. file_mode = 'w' with open(file_path, file_mode, **open_kwargs) as f: f.write(file_contents) def extract_tar(archive_file, target_dir=None, delete=False):
64
64
130
14
50
rsennewald/ClusterRunner
app/util/fs.py
Python
extract_tar
extract_tar
71
91
71
71
1ad29d73e43b6df6b02e5a25c205d25f6241707e
bigcode/the-stack
train
df2e9d46c79bea36e4f5192d
train
function
def create_dir(dir_path, mode=None): """ Create a directory. If it already exists, allow it and swallow the exception. :param dir_path: the directory to create :type dir_path: str :param mode: the permissions to set dir_path to (ie: 0o700) :type mode: int(octal)|None """ try: # ...
def create_dir(dir_path, mode=None):
""" Create a directory. If it already exists, allow it and swallow the exception. :param dir_path: the directory to create :type dir_path: str :param mode: the permissions to set dir_path to (ie: 0o700) :type mode: int(octal)|None """ try: # Unfortunately, the exists_ok paramete...
""" new_temp_path = tempfile.mkdtemp(prefix='async_delete_directory') shutil.move(path, new_temp_path) # TODO: make the following command cross-platform. Popen_with_delayed_expansion(['rm', '-rf', new_temp_path]) def create_dir(dir_path, mode=None):
64
64
135
9
55
rsennewald/ClusterRunner
app/util/fs.py
Python
create_dir
create_dir
29
45
29
29
37b2129124f0c20a0bed03a2d10323d37b0a0d77
bigcode/the-stack
train
fd1ab16951a1418e14f397a1
train
function
def write_file(file_contents, file_path): """ Write a string or byte string to a file. :param file_contents: The string or byte string to write :type file_contents: str | bytes :param file_path: The path of the file to write :type file_path: str """ file_dir, _ = os.path.split(file_path...
def write_file(file_contents, file_path):
""" Write a string or byte string to a file. :param file_contents: The string or byte string to write :type file_contents: str | bytes :param file_path: The path of the file to write :type file_path: str """ file_dir, _ = os.path.split(file_path) create_dir(file_dir) if isinsta...
try: # Unfortunately, the exists_ok parameter does not do what it's supposed to do. os.makedirs(dir_path, exist_ok=True) except FileExistsError: pass if mode is not None: os.chmod(dir_path, mode) def write_file(file_contents, file_path):
64
64
169
9
55
rsennewald/ClusterRunner
app/util/fs.py
Python
write_file
write_file
48
68
48
48
241314d6b7e268d5fece15239fc842b90b894a66
bigcode/the-stack
train
db8bbed2d8167fdd661e521e
train
class
class ManifestNotFoundException(Exception): """ Exception class when request Manifest file return 404. """
class ManifestNotFoundException(Exception):
""" Exception class when request Manifest file return 404. """
mtree_callback LOG = logging.getLogger(__name__) class CloneRepoException(Exception): """ Exception class when clone repo fails. """ class CloneRepoUnstableStateException(CloneRepoException): """ Exception class when clone repo enters an unstable state. """ class ManifestNotFoundException(E...
63
64
22
7
56
praneetap/aws-sam-cli
samcli/lib/utils/git_repo.py
Python
ManifestNotFoundException
ManifestNotFoundException
33
36
33
33
9db66a75678014b452f2d2ba28a2ead5296cb723
bigcode/the-stack
train
3af27499b5d097a256e6f1f6
train
class
class GitRepo: """ Class for managing a Git repo, currently it has a clone functionality only Attributes ---------- url: str The URL of this Git repository, example "https://github.com/aws/aws-sam-cli" local_path: Path The path of the last local clone of this Git repository. Can...
class GitRepo:
""" Class for managing a Git repo, currently it has a clone functionality only Attributes ---------- url: str The URL of this Git repository, example "https://github.com/aws/aws-sam-cli" local_path: Path The path of the last local clone of this Git repository. Can be used in con...
""" Manage Git repo """ import logging import os import platform import shutil import subprocess from pathlib import Path # import check_output alone so that it can be patched without affecting # other parts of subprocess. from subprocess import check_output from typing import Optional from samcli.lib.utils import o...
157
256
1,573
4
153
praneetap/aws-sam-cli
samcli/lib/utils/git_repo.py
Python
GitRepo
GitRepo
39
199
39
39
83972aa2c7d2f132a8ed6adae7323dac6506a3bc
bigcode/the-stack
train
a12cd324b61a04930d6c2d75
train
class
class CloneRepoUnstableStateException(CloneRepoException): """ Exception class when clone repo enters an unstable state. """
class CloneRepoUnstableStateException(CloneRepoException):
""" Exception class when clone repo enters an unstable state. """
from typing import Optional from samcli.lib.utils import osutils from samcli.lib.utils.osutils import rmtree_callback LOG = logging.getLogger(__name__) class CloneRepoException(Exception): """ Exception class when clone repo fails. """ class CloneRepoUnstableStateException(CloneRepoException):
63
64
26
11
52
praneetap/aws-sam-cli
samcli/lib/utils/git_repo.py
Python
CloneRepoUnstableStateException
CloneRepoUnstableStateException
27
30
27
27
70652e6594c3d46df2f01db7d80bedbac1fa517a
bigcode/the-stack
train
fd8281166c4df12a2077a410
train
class
class CloneRepoException(Exception): """ Exception class when clone repo fails. """
class CloneRepoException(Exception):
""" Exception class when clone repo fails. """
check_output alone so that it can be patched without affecting # other parts of subprocess. from subprocess import check_output from typing import Optional from samcli.lib.utils import osutils from samcli.lib.utils.osutils import rmtree_callback LOG = logging.getLogger(__name__) class CloneRepoException(Exception):
64
64
18
6
58
praneetap/aws-sam-cli
samcli/lib/utils/git_repo.py
Python
CloneRepoException
CloneRepoException
21
24
21
21
753af8448cd0ab13fb885cb7a8e6df9168c08873
bigcode/the-stack
train
d5d3ff5bc69a4a36fc7fa2b8
train
class
class Migration(migrations.Migration): dependencies = [ ('pets', '0002_like'), ('common', '0003_auto_20210622_1131'), ] operations = [ migrations.RenameModel( old_name='CommentNew', new_name='Comment', ), ]
class Migration(migrations.Migration):
dependencies = [ ('pets', '0002_like'), ('common', '0003_auto_20210622_1131'), ] operations = [ migrations.RenameModel( old_name='CommentNew', new_name='Comment', ), ]
# Generated by Django 3.2.3 on 2021-06-22 08:32 from django.db import migrations class Migration(migrations.Migration):
36
64
65
7
28
PetkoAndreev/Python-Web-Petstagram
petstagram/petstagram/common/migrations/0004_rename_commentnew_comment.py
Python
Migration
Migration
6
18
6
7
5b08d948aac1782fd37917274df646b357f9a5e4
bigcode/the-stack
train
0d2f6c6af9e96a864c1da646
train
function
def choose_activity(update, context): query = update.callback_query user_id = update.effective_user.id query.answer() # This can be 'back' in some occassions but we'll see :) activity_idx = query.data activities = context.chat_data[user_id] context.user_data['cur_activity_idx'] = activity...
def choose_activity(update, context):
query = update.callback_query user_id = update.effective_user.id query.answer() # This can be 'back' in some occassions but we'll see :) activity_idx = query.data activities = context.chat_data[user_id] context.user_data['cur_activity_idx'] = activity_idx context.user_data['username']...
participating in BP's Game of Life, @{user_name}!</b>\n\nDid you manage to balance the meters by the end of the game? We hope you did! There are no right or wrong answers, but we hope you managed to reach a compromise and prevent all four meters from falling below the threshold! In the same way, we hope that you'll be...
217
217
724
7
209
RussellDash332/usp-telegram-bot
activities_menu.py
Python
choose_activity
choose_activity
51
147
51
51
428ac7a642a45bcc20ad18794cd2207cd045ed98
bigcode/the-stack
train
bc4a542cf8a9870bc52413d7
train
function
def check_answer(update, context): user_id = update.message.from_user.id activities = context.chat_data[user_id] activity_idx = context.user_data['cur_activity_idx'] user_name = context.user_data['username'] right_answers = activities[activity_idx].answers # Caps lock everything user_answer...
def check_answer(update, context):
user_id = update.message.from_user.id activities = context.chat_data[user_id] activity_idx = context.user_data['cur_activity_idx'] user_name = context.user_data['username'] right_answers = activities[activity_idx].answers # Caps lock everything user_answer = update.message.text.upper() ...
activity_idx = context.user_data['cur_activity_idx'] activities = context.chat_data[user_id] name = activities[activity_idx].name query.edit_message_text(text=f'Trying "{name}", type the answer') return CHECK_ANSWER # This will only run if the activity is a trivia def check_answer(update, context...
72
72
241
7
64
RussellDash332/usp-telegram-bot
activities_menu.py
Python
check_answer
check_answer
183
212
183
183
64950f0e574b8059e998163fb07bf3bdfff4b26a
bigcode/the-stack
train
df4d47d6f28e385c29c1bc17
train
function
def ending(user_name, long_version): if long_version: return f"<b>Thank you for participating in BP's Game of Life, @{user_name}!</b>\n\nDid you manage to balance the meters by the end of the game? We hope you did! There are no right or wrong answers, but we hope you managed to reach a compromise and preven...
def ending(user_name, long_version):
if long_version: return f"<b>Thank you for participating in BP's Game of Life, @{user_name}!</b>\n\nDid you manage to balance the meters by the end of the game? We hope you did! There are no right or wrong answers, but we hope you managed to reach a compromise and prevent all four meters from falling below ...
0) == 1): result.append(category) params = [social, academic, happiness, health] categories = ['social','academic','happiness','health'] for i in range(4): helper(params[i], categories[i]) return result def ending(user_name, long_version):
64
64
148
8
55
RussellDash332/usp-telegram-bot
activities_menu.py
Python
ending
ending
33
37
33
33
2b61fad800870f3aba15a99dc6510f8540005935
bigcode/the-stack
train
cf7da37d45a0427e73c45d17
train
function
def yes(update, context): user_id = update['callback_query'].from_user['id'] activities = context.chat_data[user_id] activity_idx = context.user_data['cur_activity_idx'] user_name = update['callback_query'].from_user['username'] query = update.callback_query query.answer() keyboard = [ ...
def yes(update, context):
user_id = update['callback_query'].from_user['id'] activities = context.chat_data[user_id] activity_idx = context.user_data['cur_activity_idx'] user_name = update['callback_query'].from_user['username'] query = update.callback_query query.answer() keyboard = [ [ InlineK...
only run if the activity is a trivia def check_answer(update, context): user_id = update.message.from_user.id activities = context.chat_data[user_id] activity_idx = context.user_data['cur_activity_idx'] user_name = context.user_data['username'] right_answers = activities[activity_idx].answers ...
256
256
1,113
6
249
RussellDash332/usp-telegram-bot
activities_menu.py
Python
yes
yes
214
324
214
214
5bc6c61d97a982372994680ede85b1eae51acd04
bigcode/the-stack
train
444ab35a8d0734f12f2f9a33
train
function
def answer_activity(update, context): query = update.callback_query user_id = update.effective_user.id query.answer() activity_idx = context.user_data['cur_activity_idx'] activities = context.chat_data[user_id] name = activities[activity_idx].name query.edit_message_text(text=f'Trying "{n...
def answer_activity(update, context):
query = update.callback_query user_id = update.effective_user.id query.answer() activity_idx = context.user_data['cur_activity_idx'] activities = context.chat_data[user_id] name = activities[activity_idx].name query.edit_message_text(text=f'Trying "{name}", type the answer') return C...
pass bot.delete_message(chat_id=user_id, message_id=query.message.message_id) reply_markup = get_options_keyboard(context.chat_data, user_id) query.message.reply_text('Choose an activity to view...', reply_markup=reply_markup) return CHOOSE_ACTIVITY def answer_activity(update, context):
64
64
81
7
56
RussellDash332/usp-telegram-bot
activities_menu.py
Python
answer_activity
answer_activity
168
180
168
168
ed16141476c81d2c400cd5deb8966114e3d31eed
bigcode/the-stack
train
4a110b356367a7f2acbc4dfa
train
function
def leave_activities_menu(update, context): query = update.callback_query query.answer() user_id = update.effective_user.id bot = context.bot try: last_description = context.user_data['last_description'] bot.delete_message(chat_id=user_id, message_id=last_description.message_id) ...
def leave_activities_menu(update, context):
query = update.callback_query query.answer() user_id = update.effective_user.id bot = context.bot try: last_description = context.user_data['last_description'] bot.delete_message(chat_id=user_id, message_id=last_description.message_id) except: pass query.edit_messa...
_text(result, reply_markup=reply_markup) return CHOOSE_CONTINUE_OPTION def try_again(update, context): query = update.callback_query query.answer() query.edit_message_text('Trying question again, type the answer') return CHECK_ANSWER def leave_activities_menu(update, context):
64
64
93
9
54
RussellDash332/usp-telegram-bot
activities_menu.py
Python
leave_activities_menu
leave_activities_menu
503
517
503
503
6bed6c9d066abf3ed6bec0dcfe2a676658942c0f
bigcode/the-stack
train
f63c0d0340456cdfc6f8b42e
train
function
def return_to_activities_menu(update, context): query = update.callback_query user_id = update.effective_user.id query.answer() bot = context.bot try: last_description = context.user_data['last_description'] bot.delete_message(chat_id=user_id, message_id=last_description.message_id...
def return_to_activities_menu(update, context):
query = update.callback_query user_id = update.effective_user.id query.answer() bot = context.bot try: last_description = context.user_data['last_description'] bot.delete_message(chat_id=user_id, message_id=last_description.message_id) except: pass bot.delete_messag...
reply_markup = get_options_keyboard(context.chat_data, user_id) try: query.edit_message_text('Activity still locked! Complete all previous activities first!', reply_markup=reply_markup) except: pass # unmodified message return CHOOSE_ACTIVITY def return_to_activities_me...
64
64
128
10
53
RussellDash332/usp-telegram-bot
activities_menu.py
Python
return_to_activities_menu
return_to_activities_menu
149
166
149
149
f0f3307fdd634f604c36cc6fa85fae26e638b74f
bigcode/the-stack
train
85723c7fc6db2c91d93d405c
train
function
def no(update, context): user_id = update['callback_query'].from_user['id'] activities = context.chat_data[user_id] activity_idx = context.user_data['cur_activity_idx'] user_name = update['callback_query'].from_user['username'] query = update.callback_query query.answer() keyboard = [ ...
def no(update, context):
user_id = update['callback_query'].from_user['id'] activities = context.chat_data[user_id] activity_idx = context.user_data['cur_activity_idx'] user_name = update['callback_query'].from_user['username'] query = update.callback_query query.answer() keyboard = [ [ InlineK...
'happiness': str(user_hap), 'health': str(user_hlth), 'forfeits': user_forf }, indent=2) write_dp(str(user_id), user_data_str) result = [ 'You chose <b>"Yes"</b> for this scenario.\n', 'Your choice affects your mete...
256
256
1,113
6
249
RussellDash332/usp-telegram-bot
activities_menu.py
Python
no
no
326
436
326
326
a90899bfa481f66d89f5c642fd9cdaec97850412
bigcode/the-stack
train
1096c3912b9ae91f3e4c78e0
train
function
def forfeits(data, social, academic, happiness, health): # type(data) = dict, stores how many forfeits you have encountered before result = [] def helper(param, category): if (param <= 1 and data.get(category,0) == 0) or (param <= 0 and data.get(category,0) == 1): result.append(category...
def forfeits(data, social, academic, happiness, health): # type(data) = dict, stores how many forfeits you have encountered before
result = [] def helper(param, category): if (param <= 1 and data.get(category,0) == 0) or (param <= 0 and data.get(category,0) == 1): result.append(category) params = [social, academic, happiness, health] categories = ['social','academic','happiness','health'] for i in range(4...
DATA_PATH = path.join(DATA_DIR, 'forfeits.json') with open(DATA_PATH, 'r') as f: forfeit_data = load(f) def forfeits(data, social, academic, happiness, health): # type(data) = dict, stores how many forfeits you have encountered before
64
64
127
31
33
RussellDash332/usp-telegram-bot
activities_menu.py
Python
forfeits
forfeits
17
31
17
18
97ff3a7340584f7dcd9a4a47973f9c15d57c43cf
bigcode/the-stack
train
97b3f77594f6a102667e7ae4
train
function
def show_activities_menu(update, context): msg = update.message user_id = msg.from_user.id reply_markup = get_options_keyboard(context.chat_data, user_id) msg.reply_text('Choose an activity to view ...', reply_markup=reply_markup) return CHOOSE_ACTIVITY
def show_activities_menu(update, context):
msg = update.message user_id = msg.from_user.id reply_markup = get_options_keyboard(context.chat_data, user_id) msg.reply_text('Choose an activity to view ...', reply_markup=reply_markup) return CHOOSE_ACTIVITY
a good academic experience." else: return f"\n<b>Thank you for participating in BP's Game of Life, @{user_name}!</b>" def sgn(x): return '+'+str(x) if x > 0 else str(x) def show_activities_menu(update, context):
64
64
62
9
55
RussellDash332/usp-telegram-bot
activities_menu.py
Python
show_activities_menu
show_activities_menu
42
49
42
42
c5333bcc888de82dc6d13d213d780d1f8f70f6f7
bigcode/the-stack
train
17e69e14a52385bb626e2ca1
train
function
def try_again(update, context): query = update.callback_query query.answer() query.edit_message_text('Trying question again, type the answer') return CHECK_ANSWER
def try_again(update, context):
query = update.callback_query query.answer() query.edit_message_text('Trying question again, type the answer') return CHECK_ANSWER
# Update: add ending message if len(user_progress) == 18: result = ending(user_name, True) reply_markup = InlineKeyboardMarkup(keyboard) query.edit_message_text(result, reply_markup=reply_markup) return CHOOSE_CONTINUE_OPTION def try_again(update, context):
64
64
38
7
56
RussellDash332/usp-telegram-bot
activities_menu.py
Python
try_again
try_again
495
501
495
495
e7d35dff01bdc64120d7fc8bcef1affa9832ea7c
bigcode/the-stack
train
91e344e8294a8372abe258af
train
function
def complete(update, context): user_id = update.effective_user.id activities = context.chat_data[user_id] activity_idx = context.user_data['cur_activity_idx'] user_name = update['callback_query'].from_user['username'] query = update.callback_query query.answer() keyboard = [ [ ...
def complete(update, context):
user_id = update.effective_user.id activities = context.chat_data[user_id] activity_idx = context.user_data['cur_activity_idx'] user_name = update['callback_query'].from_user['username'] query = update.callback_query query.answer() keyboard = [ [ InlineKeyboardButton(te...
>', f'Happiness: <b>{sgn(activities[activity_idx].happiness[1])}</b>', f'Health: <b>{sgn(activities[activity_idx].health[1])}</b>\n', f'----------\n<b>{activities[activity_idx].information[1]}</b>\n----------', '\nYou can always check your current meter score with the /me...
132
132
442
6
125
RussellDash332/usp-telegram-bot
activities_menu.py
Python
complete
complete
438
493
438
438
75022b612cf46e856fbfc023b94bb087dfb218b6
bigcode/the-stack
train
449e1609563b96cf46f32289
train
function
def sgn(x): return '+'+str(x) if x > 0 else str(x)
def sgn(x):
return '+'+str(x) if x > 0 else str(x)
, we hope that you'll be able to get through university healthily, happily, with a good social circle, as well as a good academic experience." else: return f"\n<b>Thank you for participating in BP's Game of Life, @{user_name}!</b>" def sgn(x):
63
64
21
5
58
RussellDash332/usp-telegram-bot
activities_menu.py
Python
sgn
sgn
39
40
39
39
cfb44c49ce8f30f72f46222e5127cdb384ba02d8
bigcode/the-stack
train
d369959a1fef4011364ddf9f
train
function
def demo(): """Shows demo to use the library to download papers""" callgetpapers = Pygetpapers() query = "artificial intelligence" numberofpapers = 210 callgetpapers.europe_pmc.eupmc_apipaperdownload(query, numberofpapers)
def demo():
"""Shows demo to use the library to download papers""" callgetpapers = Pygetpapers() query = "artificial intelligence" numberofpapers = 210 callgetpapers.europe_pmc.eupmc_apipaperdownload(query, numberofpapers)
("Final query is %s", args.query) if args.noexecute: self.handle_noexecute(args) sys.exit(1) elif args.update: self.handle_update(args) sys.exit(1) else: if args.query: self.handle_query_download(args) def demo():
64
64
61
3
61
ShweataNHegde/pygetpapers
pygetpapers/pygetpapers.py
Python
demo
demo
572
577
572
572
34f66af72cc6c47c853e656d68d76f20696dc38c
bigcode/the-stack
train
dbfd7f446dd02cd3cb801afb
train
class
class Pygetpapers: """[summary]""" def __init__(self): """This function makes all the constants""" self.crossref = CrossRef() self.arxiv = Arxiv() self.europe_pmc = EuropePmc() self.rxiv = Rxiv() self.rxivist = Rxivist() self.download_tools = DownloadTool...
class Pygetpapers:
"""[summary]""" def __init__(self): """This function makes all the constants""" self.crossref = CrossRef() self.arxiv = Arxiv() self.europe_pmc = EuropePmc() self.rxiv = Rxiv() self.rxivist = Rxivist() self.download_tools = DownloadTools("europepmc") ...
import os import logging import sys from time import gmtime, strftime import configargparse import configparser import coloredlogs from tqdm import tqdm from functools import partialmethod from pygetpapers.download_tools import DownloadTools from pygetpapers.europe_pmc import EuropePmc from pygetpapers.crossref import ...
112
256
3,940
5
106
ShweataNHegde/pygetpapers
pygetpapers/pygetpapers.py
Python
Pygetpapers
Pygetpapers
18
569
18
18
d6b80528a8588be114b0869ff932997945b0401d
bigcode/the-stack
train
84cd8fe28f9b55bafda60ae2
train
function
def main(): """Runs the CLI""" callpygetpapers = Pygetpapers() callpygetpapers.handlecli()
def main():
"""Runs the CLI""" callpygetpapers = Pygetpapers() callpygetpapers.handlecli()
def demo(): """Shows demo to use the library to download papers""" callgetpapers = Pygetpapers() query = "artificial intelligence" numberofpapers = 210 callgetpapers.europe_pmc.eupmc_apipaperdownload(query, numberofpapers) def main():
64
64
27
3
61
ShweataNHegde/pygetpapers
pygetpapers/pygetpapers.py
Python
main
main
580
583
580
580
c7dcb38346aef60b772132b4f64533882bbbf410
bigcode/the-stack
train
fc4e823a0a647efbf7856482
train
function
def knight_dataset(data_dir: str = 'data', cache_dir: str = 'cache', split: dict = None, \ reset_cache: bool = False, post_cache_processing_func: Optional[Callable] = None, \ rand_gen = None, batch_size=8, resize_to=(256,256,110), task_num=1, \ target_name='data.gt.gt_global.task_1_label', num_c...
def knight_dataset(data_dir: str = 'data', cache_dir: str = 'cache', split: dict = None, \ reset_cache: bool = False, post_cache_processing_func: Optional[Callable] = None, \ rand_gen = None, batch_size=8, resize_to=(256,256,110), task_num=1, \ target_name='data.gt.gt_global.task_1_label', num_c...
augmentation_pipeline = [ [ ("data.input.image",), rotation_in_3d, { "z_rot": Uniform(-5.0, 5.0), "y_rot": Uniform(-5.0, 5.0), "x_rot": Uniform(-5.0, 5.0), }, {"apply": RandBool(0.5)}, ], ...
IDITIES_INDEX)) if comorbidities in COMORBIDITIES_INDEX.values(): comorbidities_one_hot[comorbidities] = 1 smoking_history = FuseUtilsHierarchicalDict.get(sample_dict, 'data.input.clinical.smoking_history') smoking_history_one_hot = torch.zeros(len(SMOKE_HISTORY_INDEX)) if smoking_history i...
256
256
1,451
91
164
IBM/fuse-med-ml
fuse_examples/classification/knight/baseline/dataset.py
Python
knight_dataset
knight_dataset
72
235
72
76
2061a51d69e007f5339b8080095597beb82e44de
bigcode/the-stack
train
b75d5bbbec03ef9eeaa4fdb9
train
function
def prepare_clinical(sample_dict: dict) -> dict: age = FuseUtilsHierarchicalDict.get(sample_dict, 'data.input.clinical.age_at_nephrectomy') if age!=None and age > 0 and age < 120: age = torch.tensor(age / 120.0).reshape(-1) else: age = torch.tensor(-1.0).reshape(-1) bmi = FuseUtilsH...
def prepare_clinical(sample_dict: dict) -> dict:
age = FuseUtilsHierarchicalDict.get(sample_dict, 'data.input.clinical.age_at_nephrectomy') if age!=None and age > 0 and age < 120: age = torch.tensor(age / 120.0).reshape(-1) else: age = torch.tensor(-1.0).reshape(-1) bmi = FuseUtilsHierarchicalDict.get(sample_dict, 'data.input.clin...
Int from fuse.utils.utils_param_sampler import FuseUtilsParamSamplerRandBool as RandBool from fuse_examples.tutorials.multimodality_image_clinical.download import download_and_extract_isic from torch.utils.data.dataloader import DataLoader from .input_processor import KiTSBasicInputProcessor from fuse_examples.tutorial...
184
184
616
13
170
IBM/fuse-med-ml
fuse_examples/classification/knight/baseline/dataset.py
Python
prepare_clinical
prepare_clinical
27
70
27
27
72dfb233585e7d33ba5ff12668b3fe806533df39
bigcode/the-stack
train