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
4686c508433d3a822fd51360
train
function
def get_thread_id(): global _g_thread_ids, _g_thread_counter, _g_thread_lock tid = id(threading.currentThread()) try: return _g_thread_ids[tid] except KeyError: _g_thread_lock.acquire() try: _g_thread_counter += 1 ret = _g_thread_ids[tid] = _g_thread_count...
def get_thread_id():
global _g_thread_ids, _g_thread_counter, _g_thread_lock tid = id(threading.currentThread()) try: return _g_thread_ids[tid] except KeyError: _g_thread_lock.acquire() try: _g_thread_counter += 1 ret = _g_thread_ids[tid] = _g_thread_counter finally: ...
* q u3, v3 = v3, u3 - v3 * q if u2 < 0: u2 += m return u2 _g_thread_ids = {} _g_thread_counter = 0 _g_thread_lock = threading.Lock() def get_thread_id():
64
64
97
5
59
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
get_thread_id
get_thread_id
230
242
230
230
314efca62fa63e9f07bd340a783c05a69647ab40
bigcode/the-stack
train
e4938a9acb9c910ed58792d5
train
function
def load_host_keys(filename): """ Read a file of known SSH host keys, in the format used by openssh, and return a compound dict of ``hostname -> keytype ->`` `PKey <paramiko.pkey.PKey>`. The hostname may be an IP address or DNS name. The keytype will be either ``"ssh-rsa"`` or ``"ssh-dss"``. T...
def load_host_keys(filename):
""" Read a file of known SSH host keys, in the format used by openssh, and return a compound dict of ``hostname -> keytype ->`` `PKey <paramiko.pkey.PKey>`. The hostname may be an IP address or DNS name. The keytype will be either ``"ssh-rsa"`` or ``"ssh-dss"``. This type of file unfortunately...
hash_obj.update(digest) hash_obj.update(b(key)) hash_obj.update(salt) digest = hash_obj.digest() size = min(nbytes, len(digest)) keydata += digest[:size] nbytes -= size return keydata def load_host_keys(filename):
64
64
202
6
57
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
load_host_keys
load_host_keys
173
191
173
173
9e9ca293100342a983774d1cd72d68cb320f28cc
bigcode/the-stack
train
ccda6448978d58f27d044cca
train
function
def bit_length(n): try: return n.bit_length() except AttributeError: norm = deflate_long(n, False) hbyte = byte_ord(norm[0]) if hbyte == 0: return 1 bitlen = len(norm) * 8 while not (hbyte & 0x80): hbyte <<= 1 bitlen -= 1 ...
def bit_length(n):
try: return n.bit_length() except AttributeError: norm = deflate_long(n, False) hbyte = byte_ord(norm[0]) if hbyte == 0: return 1 bitlen = len(norm) * 8 while not (hbyte & 0x80): hbyte <<= 1 bitlen -= 1 return bitlen
safe_string(s): out = b"" for c in s: i = byte_ord(c) if 32 <= i <= 127: out += byte_chr(i) else: out += b("%{:02X}".format(i)) return out def bit_length(n):
64
64
94
5
58
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
bit_length
bit_length
123
135
123
123
473c091886e55faa88c78d73a815241c98d0f1a3
bigcode/the-stack
train
ae6bdf62fe06c1b3e1784970
train
function
def inflate_long(s, always_positive=False): """turns a normalized byte string into a long-int (adapted from Crypto.Util.number)""" out = long(0) negative = 0 if not always_positive and (len(s) > 0) and (byte_ord(s[0]) >= 0x80): negative = 1 if len(s) % 4: filler = zero_byte ...
def inflate_long(s, always_positive=False):
"""turns a normalized byte string into a long-int (adapted from Crypto.Util.number)""" out = long(0) negative = 0 if not always_positive and (len(s) > 0) and (byte_ord(s[0]) >= 0x80): negative = 1 if len(s) % 4: filler = zero_byte if negative: filler = max_byt...
struct import traceback import threading import logging from paramiko.common import DEBUG, zero_byte, xffffffff, max_byte from paramiko.py3compat import PY2, long, byte_chr, byte_ord, b from paramiko.config import SSHConfig def inflate_long(s, always_positive=False):
64
64
212
9
54
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
inflate_long
inflate_long
37
55
37
37
e1cd38975dc7fdf193058d7eaf037ca973593fcd
bigcode/the-stack
train
0d0da755bef24f253bb6de97
train
function
def retry_on_signal(function): """Retries function until it doesn't raise an EINTR error""" while True: try: return function() except EnvironmentError as e: if e.errno != errno.EINTR: raise
def retry_on_signal(function):
"""Retries function until it doesn't raise an EINTR error""" while True: try: return function() except EnvironmentError as e: if e.errno != errno.EINTR: raise
class PFilter(object): def filter(self, record): record._threadid = get_thread_id() return True _pfilter = PFilter() def get_logger(name): l = logging.getLogger(name) l.addFilter(_pfilter) return l def retry_on_signal(function):
64
64
51
6
57
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
retry_on_signal
retry_on_signal
276
283
276
276
92c33a71f3f12cea19e8c63f5fbde2c9ce89e395
bigcode/the-stack
train
c08979bcf649d77a9030c876
train
function
def get_logger(name): l = logging.getLogger(name) l.addFilter(_pfilter) return l
def get_logger(name):
l = logging.getLogger(name) l.addFilter(_pfilter) return l
M:%S")) l.addHandler(lh) # make only one filter object, so it doesn't get applied more than once class PFilter(object): def filter(self, record): record._threadid = get_thread_id() return True _pfilter = PFilter() def get_logger(name):
64
64
25
5
59
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
get_logger
get_logger
270
273
270
270
30f478335e205587fd9f6478daef6dd474f99ff1
bigcode/the-stack
train
3017b60b9eae82d95fcb3829
train
function
def format_binary_line(data): left = " ".join(["{:02X}".format(byte_ord(c)) for c in data]) right = "".join( [".{:c}..".format(byte_ord(c))[(byte_ord(c) + 63) // 95] for c in data] ) return "{:50s} {}".format(left, right)
def format_binary_line(data):
left = " ".join(["{:02X}".format(byte_ord(c)) for c in data]) right = "".join( [".{:c}..".format(byte_ord(c))[(byte_ord(c) + 63) // 95] for c in data] ) return "{:50s} {}".format(left, right)
while len(data) > x + 16: out.append(format_binary_line(data[x : x + 16])) x += 16 if x < len(data): out.append(format_binary_line(data[x:])) return [prefix + line for line in out] def format_binary_line(data):
64
64
79
6
58
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
format_binary_line
format_binary_line
104
109
104
104
809ece1982b4326d2ef52c3c9c0b4cbae2792941
bigcode/the-stack
train
f2541be2a5dc5731edb452bd
train
function
def constant_time_bytes_eq(a, b): if len(a) != len(b): return False res = 0 # noinspection PyUnresolvedReferences for i in (xrange if PY2 else range)(len(a)): # noqa: F821 res |= byte_ord(a[i]) ^ byte_ord(b[i]) return res == 0
def constant_time_bytes_eq(a, b):
if len(a) != len(b): return False res = 0 # noinspection PyUnresolvedReferences for i in (xrange if PY2 else range)(len(a)): # noqa: F821 res |= byte_ord(a[i]) ^ byte_ord(b[i]) return res == 0
return l def retry_on_signal(function): """Retries function until it doesn't raise an EINTR error""" while True: try: return function() except EnvironmentError as e: if e.errno != errno.EINTR: raise def constant_time_bytes_eq(a, b):
64
64
81
9
54
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
constant_time_bytes_eq
constant_time_bytes_eq
286
293
286
286
d38f710eaf190d44443f396cef170a4434b77842
bigcode/the-stack
train
c236ca21531dae2afffe47ec
train
function
def log_to_file(filename, level=DEBUG): """send paramiko logs to a logfile, if they're not already going somewhere""" l = logging.getLogger("paramiko") if len(l.handlers) > 0: return l.setLevel(level) f = open(filename, "a") lh = logging.StreamHandler(f) frm = "%(levelname)-.3s [...
def log_to_file(filename, level=DEBUG):
"""send paramiko logs to a logfile, if they're not already going somewhere""" l = logging.getLogger("paramiko") if len(l.handlers) > 0: return l.setLevel(level) f = open(filename, "a") lh = logging.StreamHandler(f) frm = "%(levelname)-.3s [%(asctime)s.%(msecs)03d] thr=%(_threadid...
except KeyError: _g_thread_lock.acquire() try: _g_thread_counter += 1 ret = _g_thread_ids[tid] = _g_thread_counter finally: _g_thread_lock.release() return ret def log_to_file(filename, level=DEBUG):
64
64
146
10
53
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
log_to_file
log_to_file
245
257
245
245
04515a45fe49d107045d7d68b60aed1d543a3e97
bigcode/the-stack
train
9b47662d5ddb7221e1fb8ee9
train
function
def mod_inverse(x, m): # it's crazy how small Python can make this function. u1, u2, u3 = 1, 0, m v1, v2, v3 = 0, 1, x while v3 > 0: q = u3 // v3 u1, v1 = v1, u1 - v1 * q u2, v2 = v2, u2 - v2 * q u3, v3 = v3, u3 - v3 * q if u2 < 0: u2 += m return u2
def mod_inverse(x, m): # it's crazy how small Python can make this function.
u1, u2, u3 = 1, 0, m v1, v2, v3 = 0, 1, x while v3 > 0: q = u3 // v3 u1, v1 = v1, u1 - v1 * q u2, v2 = v2, u2 - v2 * q u3, v3 = v3, u3 - v3 * q if u2 < 0: u2 += m return u2
config.parse(file_obj) return config def lookup_ssh_host_config(hostname, config): """ Provided only as a backward-compatible wrapper around `.SSHConfig`. """ return config.lookup(hostname) def mod_inverse(x, m): # it's crazy how small Python can make this function.
64
64
145
19
45
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
mod_inverse
mod_inverse
210
222
210
211
50fb19614544397b0bcd17af4603cadb15be7f35
bigcode/the-stack
train
bfd0b33aea445412915e8685
train
function
def generate_key_bytes(hash_alg, salt, key, nbytes): """ Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. :param function hash_alg: A function which cre...
def generate_key_bytes(hash_alg, salt, key, nbytes):
""" Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. :param function hash_alg: A function which creates a new hash object, such as ``hashlib.sha...
bitlen = len(norm) * 8 while not (hbyte & 0x80): hbyte <<= 1 bitlen -= 1 return bitlen def tb_strings(): return "".join(traceback.format_exception(*sys.exc_info())).split("\n") def generate_key_bytes(hash_alg, salt, key, nbytes):
77
77
258
14
63
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
generate_key_bytes
generate_key_bytes
142
170
142
142
251cc33705028e80ab64e6803c1bebcb6d7e63b8
bigcode/the-stack
train
9700d327c32b0cd54bc1332e
train
function
def format_binary(data, prefix=""): x = 0 out = [] while len(data) > x + 16: out.append(format_binary_line(data[x : x + 16])) x += 16 if x < len(data): out.append(format_binary_line(data[x:])) return [prefix + line for line in out]
def format_binary(data, prefix=""):
x = 0 out = [] while len(data) > x + 16: out.append(format_binary_line(data[x : x + 16])) x += 16 if x < len(data): out.append(format_binary_line(data[x:])) return [prefix + line for line in out]
and (byte_ord(s[0]) >= 0x80): s = zero_byte + s if (n == -1) and (byte_ord(s[0]) < 0x80): s = max_byte + s return s def format_binary(data, prefix=""):
64
64
77
8
55
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
format_binary
format_binary
93
101
93
93
cfff14e856344dcad6848bb250df722d32908e21
bigcode/the-stack
train
a58580f8e875bb339d1c8b45
train
function
def safe_string(s): out = b"" for c in s: i = byte_ord(c) if 32 <= i <= 127: out += byte_chr(i) else: out += b("%{:02X}".format(i)) return out
def safe_string(s):
out = b"" for c in s: i = byte_ord(c) if 32 <= i <= 127: out += byte_chr(i) else: out += b("%{:02X}".format(i)) return out
(c)) for c in data]) right = "".join( [".{:c}..".format(byte_ord(c))[(byte_ord(c) + 63) // 95] for c in data] ) return "{:50s} {}".format(left, right) def safe_string(s):
64
64
60
5
59
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
safe_string
safe_string
112
120
112
112
719cb4e1f8df6800755e4f5a97231d667eb47001
bigcode/the-stack
train
1a542b5ba0f46f97485e70a9
train
class
class PFilter(object): def filter(self, record): record._threadid = get_thread_id() return True
class PFilter(object):
def filter(self, record): record._threadid = get_thread_id() return True
)-3d" frm += " %(name)s: %(message)s" lh.setFormatter(logging.Formatter(frm, "%Y%m%d-%H:%M:%S")) l.addHandler(lh) # make only one filter object, so it doesn't get applied more than once class PFilter(object):
64
64
26
5
58
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
PFilter
PFilter
261
264
261
261
e82e28d2dd6011f7d2e8161808ad2439395e3a7f
bigcode/the-stack
train
4df4475b743b8640b50b3da0
train
function
def parse_ssh_config(file_obj): """ Provided only as a backward-compatible wrapper around `.SSHConfig`. """ config = SSHConfig() config.parse(file_obj) return config
def parse_ssh_config(file_obj):
""" Provided only as a backward-compatible wrapper around `.SSHConfig`. """ config = SSHConfig() config.parse(file_obj) return config
:param str filename: name of the file to read host keys from :return: nested dict of `.PKey` objects, indexed by hostname and then keytype """ from paramiko.hostkeys import HostKeys return HostKeys(filename) def parse_ssh_config(file_obj):
64
64
41
8
56
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
parse_ssh_config
parse_ssh_config
194
200
194
194
f39aa3f6965d1d02600cd8d942b58537956bfaab
bigcode/the-stack
train
477b77a6d3d3fa0f9789099f
train
class
class ClosingContextManager(object): def __enter__(self): return self def __exit__(self, type, value, traceback): self.close()
class ClosingContextManager(object):
def __enter__(self): return self def __exit__(self, type, value, traceback): self.close()
res = 0 # noinspection PyUnresolvedReferences for i in (xrange if PY2 else range)(len(a)): # noqa: F821 res |= byte_ord(a[i]) ^ byte_ord(b[i]) return res == 0 class ClosingContextManager(object):
64
64
34
6
57
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
ClosingContextManager
ClosingContextManager
296
301
296
296
94fac2179228d96d9e9706b131a8f33249414798
bigcode/the-stack
train
2178d984a97912a1d83aef2b
train
class
class ApiMock(): """Mock an API by saving all calls in a dict""" def __init__(self): self.requests = [] def __nonzero__(self): return True def __getattr__(self, attr): return partial(self._savecall, attr) def _savecall(self, method, target, **kwargs): self.requests.append((method, target, kwargs)) r...
class ApiMock():
"""Mock an API by saving all calls in a dict""" def __init__(self): self.requests = [] def __nonzero__(self): return True def __getattr__(self, attr): return partial(self._savecall, attr) def _savecall(self, method, target, **kwargs): self.requests.append((method, target, kwargs)) return {}
from functools import partial class ApiMock():
9
64
85
4
4
mburgs/asana
test/mocks.py
Python
ApiMock
ApiMock
3
18
3
3
64592bdf696fdaf667bf1f17ea255165fa359f4e
bigcode/the-stack
train
0420d706895f7c93e872d5ae
train
function
def is_chr(value: str) -> bool: """ >>> is_chr('chr1:11,130,540-11,130,751') True >>> is_chr('gtca') False """ try: validate_chr(value) except ValidationError: return False return True
def is_chr(value: str) -> bool:
""" >>> is_chr('chr1:11,130,540-11,130,751') True >>> is_chr('gtca') False """ try: validate_chr(value) except ValidationError: return False return True
: ['"chrA:11,130,540-11,130,751" is not a chromosome location'] """ try: ChrLoc(value) except Exception: raise ValidationError('"{}" is not a chromosome location'.format(value)) def is_chr(value: str) -> bool:
64
64
69
10
54
czbiohub/crispycrunch
utils/validators.py
Python
is_chr
is_chr
89
100
89
89
18408edce00d4c8447a25aec9ee56106800beaf4
bigcode/the-stack
train
8b87eb1b120b9c9633d913a4
train
function
def validate_seq(value: str) -> None: """ See https://en.wikipedia.org/wiki/Nucleic_acid_sequence. Also allows a trailing space separated PAM. >>> validate_seq('gtca') >>> validate_seq('CACTGCAACCTTGGCCTCCC GGG') >>> validate_seq('asdf') Traceback (most recent call last): ... djang...
def validate_seq(value: str) -> None:
""" See https://en.wikipedia.org/wiki/Nucleic_acid_sequence. Also allows a trailing space separated PAM. >>> validate_seq('gtca') >>> validate_seq('CACTGCAACCTTGGCCTCCC GGG') >>> validate_seq('asdf') Traceback (most recent call last): ... django.core.exceptions.ValidationError: ['"...
001_R1_001.fa" is not a valid fastq file'] """ if (not filename.endswith('.fastq') and not filename.endswith('.fastq.gz')): raise ValidationError('"{}" is not a valid fastq file'.format(filename)) def validate_seq(value: str) -> None:
64
64
158
10
54
czbiohub/crispycrunch
utils/validators.py
Python
validate_seq
validate_seq
35
49
35
35
8a79ffe42d3086f3813b6e9d905bf928ca0bdb47
bigcode/the-stack
train
50a271a62334d68350d4bbab
train
function
def validate_fastq(filename: str) -> None: """ >>> validate_fastq('crispresso/fastqs/A1-ATL2-N-sorted-180212_S1_L001_R1_001.fastq') >>> validate_fastq('crispresso/fastqs/A1-ATL2-N-sorted-180212_S1_L001_R1_001.fastq.gz') >>> validate_fastq('crispresso/fastqs/A1-ATL2-N-sorted-180212_S1_L001_R1_001.fa') ...
def validate_fastq(filename: str) -> None:
""" >>> validate_fastq('crispresso/fastqs/A1-ATL2-N-sorted-180212_S1_L001_R1_001.fastq') >>> validate_fastq('crispresso/fastqs/A1-ATL2-N-sorted-180212_S1_L001_R1_001.fastq.gz') >>> validate_fastq('crispresso/fastqs/A1-ATL2-N-sorted-180212_S1_L001_R1_001.fa') Traceback (most recent call last): .....
.org/p/60118/ . # Also covers mouse genes... which are lowercase GENE_REGEX = r'^[A-Za-z0-9-]{3,9}$|^C[0-9XY]+orf[0-9]+$' def validate_fastq(filename: str) -> None:
64
64
209
11
53
czbiohub/crispycrunch
utils/validators.py
Python
validate_fastq
validate_fastq
22
32
22
22
60317d24ef90c721493ef2064762cc98d3725c72
bigcode/the-stack
train
97154b3991d91449769b5f64
train
function
def validate_num_wells(value: dict, max: int = 96) -> None: total = sum(len(seqs) for seqs in value.values()) if total > max: raise ValidationError( '{} items do not fit in a 96-well plate'.format(total))
def validate_num_wells(value: dict, max: int = 96) -> None:
total = sum(len(seqs) for seqs in value.values()) if total > max: raise ValidationError( '{} items do not fit in a 96-well plate'.format(total))
('ATL3') True >>> is_gene('ATL_3') False """ try: validate_gene(value) except ValidationError: return False else: return True def validate_num_wells(value: dict, max: int = 96) -> None:
64
64
62
19
44
czbiohub/crispycrunch
utils/validators.py
Python
validate_num_wells
validate_num_wells
173
177
173
173
314977710ea49214b4c700a4fa22ce156dc7531e
bigcode/the-stack
train
7942e70873e751708918d413
train
function
def validate_chr_or_seq_or_enst_or_gene(value: str) -> None: # skip optional "N" or "C" trailing value = value.split(',')[0].strip() if not any(( is_chr(value), is_seq(value), is_ensemble_transcript(value), is_gene(value))): raise ValidationError( ...
def validate_chr_or_seq_or_enst_or_gene(value: str) -> None: # skip optional "N" or "C" trailing
value = value.split(',')[0].strip() if not any(( is_chr(value), is_seq(value), is_ensemble_transcript(value), is_gene(value))): raise ValidationError( '"{}" is not a chromosome location or nucleic acid sequence or a Ensembl transcript ID or a H...
49') False """ try: validate_ensemble_transcript(value) except ValidationError: return False else: return True def validate_chr_or_seq_or_enst_or_gene(value: str) -> None: # skip optional "N" or "C" trailing
64
64
106
30
33
czbiohub/crispycrunch
utils/validators.py
Python
validate_chr_or_seq_or_enst_or_gene
validate_chr_or_seq_or_enst_or_gene
131
140
131
132
6a1e17c4202eb413a6dc9ceb2980b0d644af3039
bigcode/the-stack
train
74a6b519357d65b4255cbbec
train
function
def is_seq(value: str) -> bool: """ >>> is_seq('gtca') True >>> is_seq('asdf') False """ try: validate_seq(value) except ValidationError: return False else: return True
def is_seq(value: str) -> bool:
""" >>> is_seq('gtca') True >>> is_seq('asdf') False """ try: validate_seq(value) except ValidationError: return False else: return True
.match(r'^[ACGTRYKMSWBDHVN]+( [ACGTRYKMSWBDHVN]{3})?$', value.upper()) is None: raise ValidationError('"{}" is not a nucleic acid sequence'.format(value)) def is_seq(value: str) -> bool:
64
64
59
10
54
czbiohub/crispycrunch
utils/validators.py
Python
is_seq
is_seq
52
64
52
52
a1f7cbe25865cbd62e9e46c2890e579fc4b51804
bigcode/the-stack
train
69ef5379205c037bf92ffa4f
train
function
def validate_unique_set(value: list) -> None: items = list(value) # make copy for v in set(items): items.remove(v) if items: raise ValidationError('Duplicate targets: {}'.format(items))
def validate_unique_set(value: list) -> None:
items = list(value) # make copy for v in set(items): items.remove(v) if items: raise ValidationError('Duplicate targets: {}'.format(items))
max: int = 96) -> None: total = sum(len(seqs) for seqs in value.values()) if total > max: raise ValidationError( '{} items do not fit in a 96-well plate'.format(total)) def validate_unique_set(value: list) -> None:
64
64
50
11
53
czbiohub/crispycrunch
utils/validators.py
Python
validate_unique_set
validate_unique_set
180
185
180
180
851a245fd193e523c9bb8800057906111d82c608
bigcode/the-stack
train
838f1d5afa94d6cbd519a7e1
train
function
def is_ensemble_transcript(value: str) -> bool: """ >>> is_ensemble_transcript('ENST00000330949') True >>> is_ensemble_transcript('ENST00000398844') True >>> is_ensemble_transcript('EENST00000330949') False """ try: validate_ensemble_transcript(value) except ValidationErr...
def is_ensemble_transcript(value: str) -> bool:
""" >>> is_ensemble_transcript('ENST00000330949') True >>> is_ensemble_transcript('ENST00000398844') True >>> is_ensemble_transcript('EENST00000330949') False """ try: validate_ensemble_transcript(value) except ValidationError: return False else: retur...
00330949" is not a Ensembl transcript ID'] """ if re.match(r'^ENST[0-9]+$', value) is None: raise ValidationError('"{}" is not a Ensembl transcript ID'.format(value)) def is_ensemble_transcript(value: str) -> bool:
64
64
99
13
51
czbiohub/crispycrunch
utils/validators.py
Python
is_ensemble_transcript
is_ensemble_transcript
114
128
114
114
b849050bbdbf5dc8553fd94a61a481f24160a73a
bigcode/the-stack
train
0a98b0577e11b2c7fca0dbba
train
function
def validate_chr(value: str) -> None: """ >>> validate_chr('chr1:11,130,540-11,130,751') >>> validate_chr('chrX:153701031-153701090') >>> validate_chr('chr1:11,130,540-11,130,751,') Traceback (most recent call last): ... django.core.exceptions.ValidationError: ['"chr1:11,130,540-11,130,751...
def validate_chr(value: str) -> None:
""" >>> validate_chr('chr1:11,130,540-11,130,751') >>> validate_chr('chrX:153701031-153701090') >>> validate_chr('chr1:11,130,540-11,130,751,') Traceback (most recent call last): ... django.core.exceptions.ValidationError: ['"chr1:11,130,540-11,130,751," is not a chromosome location'] ...
str) -> bool: """ >>> is_seq('gtca') True >>> is_seq('asdf') False """ try: validate_seq(value) except ValidationError: return False else: return True def validate_chr(value: str) -> None:
64
64
201
10
53
czbiohub/crispycrunch
utils/validators.py
Python
validate_chr
validate_chr
67
86
67
67
c4ed8980ce31e2c3e5938489e51d1c6b418ee96c
bigcode/the-stack
train
9051e291c6bd9281faf7d9ea
train
function
def is_gene(value: str) -> bool: """ >>> is_gene('ATL3') True >>> is_gene('ATL_3') False """ try: validate_gene(value) except ValidationError: return False else: return True
def is_gene(value: str) -> bool:
""" >>> is_gene('ATL3') True >>> is_gene('ATL_3') False """ try: validate_gene(value) except ValidationError: return False else: return True
.core.exceptions.ValidationError: ['"atl 2" is not a valid HGNC gene name'] """ if re.match(GENE_REGEX, value) is None: raise ValidationError('"{}" is not a valid HGNC gene name'.format(value)) def is_gene(value: str) -> bool:
64
64
61
10
54
czbiohub/crispycrunch
utils/validators.py
Python
is_gene
is_gene
158
170
158
158
2dce5681fccaf2a10d20ade3d5d545973d76f5ef
bigcode/the-stack
train
6ea69ede0e04fc8b48cd7f7a
train
function
def validate_ensemble_transcript(value: str) -> None: """ >>> validate_ensemble_transcript('EENST00000330949') Traceback (most recent call last): ... django.core.exceptions.ValidationError: ['"EENST00000330949" is not a Ensembl transcript ID'] """ if re.match(r'^ENST[0-9]+$', value) is None:...
def validate_ensemble_transcript(value: str) -> None:
""" >>> validate_ensemble_transcript('EENST00000330949') Traceback (most recent call last): ... django.core.exceptions.ValidationError: ['"EENST00000330949" is not a Ensembl transcript ID'] """ if re.match(r'^ENST[0-9]+$', value) is None: raise ValidationError('"{}" is not a Ensembl ...
1:11,130,540-11,130,751') True >>> is_chr('gtca') False """ try: validate_chr(value) except ValidationError: return False return True def validate_ensemble_transcript(value: str) -> None:
64
64
106
13
50
czbiohub/crispycrunch
utils/validators.py
Python
validate_ensemble_transcript
validate_ensemble_transcript
103
111
103
103
908168ff37213775cff26115fb793a7610c2dbcc
bigcode/the-stack
train
1813b4920ae8d21dbe637a1c
train
function
def validate_gene(value: str) -> None: """ >>> validate_gene('ATL2') is None True >>> validate_gene('ARHGAP11A') is None True >>> validate_gene('atl 2') Traceback (most recent call last): ... django.core.exceptions.ValidationError: ['"atl 2" is not a valid HGNC gene name'] """ ...
def validate_gene(value: str) -> None:
""" >>> validate_gene('ATL2') is None True >>> validate_gene('ARHGAP11A') is None True >>> validate_gene('atl 2') Traceback (most recent call last): ... django.core.exceptions.ValidationError: ['"atl 2" is not a valid HGNC gene name'] """ if re.match(GENE_REGEX, value) is Non...
is_seq(value), is_ensemble_transcript(value), is_gene(value))): raise ValidationError( '"{}" is not a chromosome location or nucleic acid sequence or a Ensembl transcript ID or a HGNC gene name'.format(value)) def validate_gene(value: str) -> None:
64
64
119
10
54
czbiohub/crispycrunch
utils/validators.py
Python
validate_gene
validate_gene
143
155
143
143
833b4e6539eb250182fe01fde2783119af9ff538
bigcode/the-stack
train
73f969160cb35452cb0b145b
train
function
def model_selection(model, X, y, seed=0, title='PCS vs Cross Validation Scores', visualize_variance=False): """ This function helps select a regression model for the input data. For a given polynomial degree model, we need to select the corresponding dimension (K) of the linear subspace (found with PCA) th...
def model_selection(model, X, y, seed=0, title='PCS vs Cross Validation Scores', visualize_variance=False):
""" This function helps select a regression model for the input data. For a given polynomial degree model, we need to select the corresponding dimension (K) of the linear subspace (found with PCA) that provides the low-dimensional regressor input. It generates the following plots: 1. Variance cap...
""" CSCC11 - Introduction to Machine Learning, Winter 2020, Exam E. Franco, B. Chan, D. Fleet =========================================================== COMPLETE THIS TEXT BOX: Student Name: Abhishek Chatterjee Student number: 1004820615 UtorID: chatt114 I hereby certify that the work contained here is my own ...
159
245
819
26
132
AbChatt/Final-Project-C11-Part-1-Python
model_selection.py
Python
model_selection
model_selection
28
108
28
28
fe4421f991b12882e378813534bf8487d6f1b20c
bigcode/the-stack
train
979507b98d431ee7fdb028aa
train
function
@make_recursive_func def to_cuda(vars): if isinstance(vars, torch.Tensor): return vars.cuda() elif isinstance(vars, DataContainer): return DataContainer(to_cuda(vars.data)) elif isinstance(vars, str): return vars elif isinstance(vars, int): return vars else: r...
@make_recursive_func def to_cuda(vars):
if isinstance(vars, torch.Tensor): return vars.cuda() elif isinstance(vars, DataContainer): return DataContainer(to_cuda(vars.data)) elif isinstance(vars, str): return vars elif isinstance(vars, int): return vars else: raise NotImplementedError("invalid input ...
if isinstance(vars, np.ndarray): return vars elif isinstance(vars, torch.Tensor): return vars.detach().cpu().numpy().copy() else: raise NotImplementedError("invalid input type {} for tensor2numpy".format(type(vars))) @make_recursive_func def to_cuda(vars):
63
64
83
10
53
achao2013/DeepRecon
deep3dmap/core/utils/device_transfer.py
Python
to_cuda
to_cuda
43
54
43
44
118317b73949b0df0960ba7c2d5cc8446ca483f8
bigcode/the-stack
train
464cd732ca26ded24408fd68
train
function
def make_recursive_func(func): def wrapper(vars): if isinstance(vars, list): return [wrapper(x) for x in vars] elif isinstance(vars, tuple): return tuple([wrapper(x) for x in vars]) elif isinstance(vars, dict): return {k: wrapper(v) for k, v in vars.items(...
def make_recursive_func(func):
def wrapper(vars): if isinstance(vars, list): return [wrapper(x) for x in vars] elif isinstance(vars, tuple): return tuple([wrapper(x) for x in vars]) elif isinstance(vars, dict): return {k: wrapper(v) for k, v in vars.items()} else: re...
import torch import numpy as np from deep3dmap.parallel.data_container import DataContainer # convert a function into recursive style to handle nested dict/list/tuple variables def make_recursive_func(func):
42
64
83
6
35
achao2013/DeepRecon
deep3dmap/core/utils/device_transfer.py
Python
make_recursive_func
make_recursive_func
6
17
6
6
42f8efb57a2963b60c53878e8cbb647b3f39725f
bigcode/the-stack
train
3c4bb3feca894c2e62cdb459
train
function
@make_recursive_func def tensor2numpy(vars): if isinstance(vars, np.ndarray): return vars elif isinstance(vars, torch.Tensor): return vars.detach().cpu().numpy().copy() else: raise NotImplementedError("invalid input type {} for tensor2numpy".format(type(vars)))
@make_recursive_func def tensor2numpy(vars):
if isinstance(vars, np.ndarray): return vars elif isinstance(vars, torch.Tensor): return vars.detach().cpu().numpy().copy() else: raise NotImplementedError("invalid input type {} for tensor2numpy".format(type(vars)))
if len(vars.shape) == 0: return vars.data.item() else: return [v.data.item() for v in vars] else: raise NotImplementedError("invalid input type {} for tensor2float".format(type(vars))) @make_recursive_func def tensor2numpy(vars):
63
64
64
11
52
achao2013/DeepRecon
deep3dmap/core/utils/device_transfer.py
Python
tensor2numpy
tensor2numpy
33
40
33
34
8b7c70fe36d5b8c67280ad712ae773820845002d
bigcode/the-stack
train
64708c9472db1ada132f8582
train
function
@make_recursive_func def tensor2float(vars): if isinstance(vars, float): return vars elif isinstance(vars, torch.Tensor): if len(vars.shape) == 0: return vars.data.item() else: return [v.data.item() for v in vars] else: raise NotImplementedError("inval...
@make_recursive_func def tensor2float(vars):
if isinstance(vars, float): return vars elif isinstance(vars, torch.Tensor): if len(vars.shape) == 0: return vars.data.item() else: return [v.data.item() for v in vars] else: raise NotImplementedError("invalid input type {} for tensor2float".format(typ...
elif isinstance(vars, tuple): return tuple([wrapper(x) for x in vars]) elif isinstance(vars, dict): return {k: wrapper(v) for k, v in vars.items()} else: return func(vars) return wrapper @make_recursive_func def tensor2float(vars):
64
64
83
11
52
achao2013/DeepRecon
deep3dmap/core/utils/device_transfer.py
Python
tensor2float
tensor2float
20
30
20
21
c13359c9c1d823f4549651237ea0b195546549ca
bigcode/the-stack
train
5ef7a6b1d18a758e9b9e98e5
train
function
def data_need(location,year,select_type): '''Here, two outputs were generated state_waec: The full dataframe for the selected location, consumed by update_graphs state_data: The list of state_waec figures used by metric_compute to generate table cells ''' year = int(year) state_waec = waec_data[...
def data_need(location,year,select_type):
'''Here, two outputs were generated state_waec: The full dataframe for the selected location, consumed by update_graphs state_data: The list of state_waec figures used by metric_compute to generate table cells ''' year = int(year) state_waec = waec_data[["YEAR","SCHOOL_TYPE","METRICS","GENDER",l...
), html.Div(#The summary section className="col-12", style={"padding-top":"20px"}, children= [ dcc.Markdown(id='r-summary-txt'), ], ...
77
77
259
10
67
EwetoyeIbrahim/Waec-Results
main.py
Python
data_need
data_need
189
205
189
189
9d7dee22ff580fabfa0135aa30897d1c10ff5837
bigcode/the-stack
train
7f958672324ff38b5150576e
train
function
def metric_compute(location,year,school_type): '''Here, I generated three outputs output_data: The table cell values summary_txt: A short summary message generated by calling summary_Txt function state_waec: The full dataframe for the selected location, consumed by update_graphs ''' state_waec, ...
def metric_compute(location,year,school_type):
'''Here, I generated three outputs output_data: The table cell values summary_txt: A short summary message generated by calling summary_Txt function state_waec: The full dataframe for the selected location, consumed by update_graphs ''' state_waec, state_data = data_need(location,year,school_typ...
state_waec = state_waec[state_waec.SCHOOL_TYPE==select_type] #state_data = state_waec[state_waec.YEAR==int(year)][location].to_list() else: state_waec = state_waec.groupby(["YEAR","METRICS","GENDER"],sort=False,as_index=False).sum() state_data = state_waec[state_waec.YEAR==int(year)][location].to_l...
127
127
424
10
116
EwetoyeIbrahim/Waec-Results
main.py
Python
metric_compute
metric_compute
207
238
207
207
a81d5febb2936b8a49b764fbd248dd4c3ded6e89
bigcode/the-stack
train
e91d2c6b8c8dc3ee40c5f120
train
function
def update_graphs(location,state_waec,school_type): '''This function concocts the graph''' need_metric = ["TOTAL NUMBER SAT", "5 CREDITS & ABOVE INCLUDING MATHEMATICS & ENGLISH LANG."] state_waec2=state_waec[ (state_waec.METRICS==need_metric[0]) | (state_waec.METRICS==need_metric[1]) ] ...
def update_graphs(location,state_waec,school_type):
'''This function concocts the graph''' need_metric = ["TOTAL NUMBER SAT", "5 CREDITS & ABOVE INCLUDING MATHEMATICS & ENGLISH LANG."] state_waec2=state_waec[ (state_waec.METRICS==need_metric[0]) | (state_waec.METRICS==need_metric[1]) ] num_val=state_waec2[state_waec2.columns[-1]].to_l...
sat__with} with **{state_data[1]/(state_data[0]+state_data[1]) * 100:.1f}%** female and **{state_data[0]/(state_data[0]+state_data[1]) * 100:.1f}%** male candidates. Of the {state_data[0]} male candidates, only **{state_data[-2]/state_data[0] * 100:.1f}%** of them made 5 credits and above incl...
226
226
754
13
212
EwetoyeIbrahim/Waec-Results
main.py
Python
update_graphs
update_graphs
266
324
266
266
6c539881f7f0877af676509dd41f04e1421552d4
bigcode/the-stack
train
9c21ebfd5848c0a00195346c
train
function
def summary_Txt(location,year,school_type,state_data,value): # Generated Markdown text for the summary portion of the view if school_type=='all': sat__with=' for the examination' else: sat__with='as '+ school_type + ' schools students' summary_txt = dedent(f''' #### Summary: {loc...
def summary_Txt(location,year,school_type,state_data,value): # Generated Markdown text for the summary portion of the view
if school_type=='all': sat__with=' for the examination' else: sat__with='as '+ school_type + ' schools students' summary_txt = dedent(f''' #### Summary: {location} | {year} | {school_type.capitalize()} Schools ---------------------- The West African Examinations Counc...
_header[1]:value[i*3], tabl_header[2]:value[i*3+1],tabl_header[3]:value[i*3+2]} for i in range(len(metrics))] summary_txt = summary_Txt(location.capitalize(),year,school_type.lower(),state_data,value) return output_data, summary_txt, state_waec def summary_Txt(location,year,school_type,state_da...
102
102
342
27
74
EwetoyeIbrahim/Waec-Results
main.py
Python
summary_Txt
summary_Txt
240
264
240
241
eee9ed211c82459e80bb20690902988a57f51b69
bigcode/the-stack
train
b88377cdc4148bcf247b63b3
train
function
def view_update(location,year,school_type): # Called other functions to update all the three ouputs at the same time table_data, summary_txt, state_waec = metric_compute(location,year,school_type) fig = None fig = update_graphs(location.capitalize(),state_waec, school_type.capitalize()) if table_dat...
def view_update(location,year,school_type): # Called other functions to update all the three ouputs at the same time
table_data, summary_txt, state_waec = metric_compute(location,year,school_type) fig = None fig = update_graphs(location.capitalize(),state_waec, school_type.capitalize()) if table_data is None: raise dash.exceptions.PreventUpdate return table_data, fig, summary_txt
sizex=0.30, sizey=0.30, xanchor="right", yanchor="bottom")] ) #fig.show() return fig def view_update(location,year,school_type): # Called other functions to update all the three ouputs at the same time
64
64
96
27
36
EwetoyeIbrahim/Waec-Results
main.py
Python
view_update
view_update
326
333
326
327
63eaba3c597162c50edf9399f4f5b1b583e99d27
bigcode/the-stack
train
32c1f7378dc702a3fc302933
train
function
@app.callback( # The right callback [dash.dependencies.Output('right_table', 'data'), dash.dependencies.Output('r-graph', 'figure'), dash.dependencies.Output('r-summary-txt', 'children'),], [dash.dependencies.Input('right_location', 'value'), dash.dependencies.Input('right_year','value'), dash.d...
@app.callback( # The right callback [dash.dependencies.Output('right_table', 'data'), dash.dependencies.Output('r-graph', 'figure'), dash.dependencies.Output('r-summary-txt', 'children'),], [dash.dependencies.Input('right_location', 'value'), dash.dependencies.Input('right_year','value'), dash.d...
return view_update(right_location,right_year,right_type)
@app.callback( # The right callback [dash.dependencies.Output('right_table', 'data'), dash.dependencies.Output('r-graph', 'figure'), dash.dependencies.Output('r-summary-txt', 'children'),], [dash.dependencies.Input('right_location', 'value'), dash.dependencies.Input('right_year','value'), dash.d...
91
64
102
91
0
EwetoyeIbrahim/Waec-Results
main.py
Python
update_right
update_right
346
354
346
353
3565f34a12fc91cf5bd7c18eeee5df20b4a14c38
bigcode/the-stack
train
b99f8e4238274e659045499f
train
function
@app.callback( # The left callback [dash.dependencies.Output('left_table', 'data'), dash.dependencies.Output('l-graph', 'figure'), dash.dependencies.Output('l-summary-txt', 'children'),], [dash.dependencies.Input('left_location', 'value'), dash.dependencies.Input('left_year','value'), dash.depen...
@app.callback( # The left callback [dash.dependencies.Output('left_table', 'data'), dash.dependencies.Output('l-graph', 'figure'), dash.dependencies.Output('l-summary-txt', 'children'),], [dash.dependencies.Input('left_location', 'value'), dash.dependencies.Input('left_year','value'), dash.depen...
return view_update(left_location,left_year,left_type)
@app.callback( # The left callback [dash.dependencies.Output('left_table', 'data'), dash.dependencies.Output('l-graph', 'figure'), dash.dependencies.Output('l-summary-txt', 'children'),], [dash.dependencies.Input('left_location', 'value'), dash.dependencies.Input('left_year','value'), dash.depen...
91
64
102
91
0
EwetoyeIbrahim/Waec-Results
main.py
Python
update_left
update_left
336
344
336
343
a2f534e7732fb1490b7dc69b892bfb8e6b457ef2
bigcode/the-stack
train
ca9d6c3eafba28e1ceebe5c1
train
class
class ParseResponse(): symbol = ['!=', '>=', '<=', '=', '>', '<'] def __init__(self, expected_res, actual_res): self.expected_res = expected_res.strip() self.actual_res = actual_res self.status = '通过' self.reason = '' self.do_check() def do_check(self): # 如果...
class ParseResponse():
symbol = ['!=', '>=', '<=', '=', '>', '<'] def __init__(self, expected_res, actual_res): self.expected_res = expected_res.strip() self.actual_res = actual_res self.status = '通过' self.reason = '' self.do_check() def do_check(self): # 如果预期结果为空 直接返回True通过 ...
# -*- coding: utf-8 -*- # @Author : XiaoGang # @Time : 2020/2/28 13:59 # @File : parse_response.py import jsonpath from config.settings import log class ParseResponse():
55
145
484
4
50
Strugglingrookie/oldboy2
auto/atp/lib/parse_response.py
Python
ParseResponse
ParseResponse
11
57
11
11
a888858cf333c14440dd6307ed294ce40d61e178
bigcode/the-stack
train
3abf8c0a7a7e0f58957b7d0f
train
function
def train(data_dir, model_path=None, vis_port=None, init=None): # loading meta data # ----------------------------------------------------------------------------------------------------- meta_data_path = os.path.join(data_dir, "meta_data.pkl") meta_data = pickle.load(open(meta_data_path, 'rb')) all...
def train(data_dir, model_path=None, vis_port=None, init=None): # loading meta data # -----------------------------------------------------------------------------------------------------
meta_data_path = os.path.join(data_dir, "meta_data.pkl") meta_data = pickle.load(open(meta_data_path, 'rb')) all_videos = [x[0] for x in meta_data] # split train/valid dataset # ----------------------------------------------------------------------------------------------------- train_videos, v...
import torch import torch.nn.functional as F import torch.optim as optim import torchvision.transforms as transforms import torchvision import numpy as np import pandas as pd import os import cv2 import pickle import lmdb import torch.nn as nn import time from torch.autograd import Variable from torch.optim.lr_schedul...
253
256
2,721
26
227
HelloRicky123/Siamese-RPN
net/train.py
Python
train
train
38
295
38
40
ea4c7108a55091d9b19580e8e2c27f275c6d69bc
bigcode/the-stack
train
781c469d4f4f8a8c0daa192f
train
class
class Evolution: def __init__(self, rounds, bc, www, wwl, wpw, wpl, pww, pwl): self.population_size = 5000 # for replicator dynamics self.game = Game(bc, www, wwl, wpw, wpl, pww, pwl) self.rounds = rounds self.players = self.init_all_players() self.alive = list(self.playe...
class Evolution:
def __init__(self, rounds, bc, www, wwl, wpw, wpl, pww, pwl): self.population_size = 5000 # for replicator dynamics self.game = Game(bc, www, wwl, wpw, wpl, pww, pwl) self.rounds = rounds self.players = self.init_all_players() self.alive = list(self.players.keys()) ...
import numpy as np import matplotlib.pyplot as plt import copy from itertools import product from player import Player from game import Game class Evolution:
32
256
1,241
3
28
horken7/game-theory
project/simulation/evolutionary/evolution.py
Python
Evolution
Evolution
10
142
10
10
5f2e48a4ce752fd3a6168318924831c0e9ba8c87
bigcode/the-stack
train
2f665169e5234a912e40b2c1
train
class
class PublicIngredientsApiTests(TestCase): """Test publicl available ingredients API""" def setUp(self): self.client = APIClient() def test_login_required(self): """Test that login is required""" res = self.client.get(INGREDIENTS_URL) self.assertEqual(res.status_code, stat...
class PublicIngredientsApiTests(TestCase):
"""Test publicl available ingredients API""" def setUp(self): self.client = APIClient() def test_login_required(self): """Test that login is required""" res = self.client.get(INGREDIENTS_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Ingredient, Recipe from recipe.serializers import IngredientSerializer INGREDIENTS_URL = reverse('recipe:ingredient-list') class PublicIngredientsApi...
64
64
72
8
56
goryszewskig/recipe-app-api
app/recipe/tests/test_ingredients_api.py
Python
PublicIngredientsApiTests
PublicIngredientsApiTests
16
26
16
16
00d3297de9c15d5cc025fd4f4eaf7ce0788b9b11
bigcode/the-stack
train
39cf80fccdaf7ac032bc7df9
train
class
class PrivateIngredientsApiTests(TestCase): """test ing can be retr by auth user""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( 'test@london.com', 'pass123' ) self.client.force_authenticate(self.user) ...
class PrivateIngredientsApiTests(TestCase):
"""test ing can be retr by auth user""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( 'test@london.com', 'pass123' ) self.client.force_authenticate(self.user) def test_retrieve_ingredient_list(self): ...
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Ingredient, Recipe from recipe.serializers import IngredientSerializer INGREDIENTS_URL = reverse('recip...
144
229
764
8
136
goryszewskig/recipe-app-api
app/recipe/tests/test_ingredients_api.py
Python
PrivateIngredientsApiTests
PrivateIngredientsApiTests
29
130
29
29
d6efa62b7c2846faa6b8f5885cb95e9704bd08a0
bigcode/the-stack
train
88ad0a00d782a46c6caffb5e
train
class
class lexopt_mosek: """ Class contains all the functions for implementing HLP """ def __init__(self, ts = 0.005): self.variables_dot = [] #derivative of the variables self.lb = [] #variable_dot lower bounds self.ub = [] #variable_dot upper bounds self.variables0 = [] #Expression for the current value of th...
class lexopt_mosek:
""" Class contains all the functions for implementing HLP """ def __init__(self, ts = 0.005): self.variables_dot = [] #derivative of the variables self.lb = [] #variable_dot lower bounds self.ub = [] #variable_dot upper bounds self.variables0 = [] #Expression for the current value of the variables self.c...
import sys, os import casadi as cs from casadi import pi, cos, sin import numpy as np import matplotlib.pyplot as plt import math import time # import tkinter from pylab import * import copy from mosek.fusion import * class lexopt_mosek:
64
256
5,317
7
57
AjSat/hqp_l1
lexopt_mosek.py
Python
lexopt_mosek
lexopt_mosek
13
394
13
13
b9242956ffb20c7f76b4ab1c2d7012bd1344c996
bigcode/the-stack
train
47c7d72a6d96676a67c61812
train
function
async def test_media_view(hass, hass_client): """Test media view.""" local_media = hass.config.path("media") await async_process_ha_core_config( hass, {"media_dirs": {"local": local_media, "recordings": local_media}} ) await hass.async_block_till_done() assert await async_setup_componen...
async def test_media_view(hass, hass_client):
"""Test media view.""" local_media = hass.config.path("media") await async_process_ha_core_config( hass, {"media_dirs": {"local": local_media, "recordings": local_media}} ) await hass.async_block_till_done() assert await async_setup_component(hass, const.DOMAIN, {}) await hass.async...
const.DOMAIN}" ) assert media media = await media_source.async_browse_media( hass, f"{const.URI_SCHEME}{const.DOMAIN}/local/." ) assert media media = await media_source.async_browse_media( hass, f"{const.URI_SCHEME}{const.DOMAIN}/recordings/." ) assert media async def t...
90
90
301
11
78
MrDelik/core
tests/components/media_source/test_local_source.py
Python
test_media_view
test_media_view
86
122
86
86
ecccc6b8ca621ca949899b3059153e0612b49f23
bigcode/the-stack
train
63a1769592bcef2cb348cf3d
train
function
async def test_remove_file(hass, hass_ws_client, temp_dir, hass_admin_user): """Allow uploading media.""" msg_count = 0 file_count = 0 def msgid(): nonlocal msg_count msg_count += 1 return msg_count def create_file(): nonlocal file_count file_count += 1 ...
async def test_remove_file(hass, hass_ws_client, temp_dir, hass_admin_user):
"""Allow uploading media.""" msg_count = 0 file_count = 0 def msgid(): nonlocal msg_count msg_count += 1 return msg_count def create_file(): nonlocal file_count file_count += 1 to_delete_path = Path(temp_dir) / f"to_delete_{file_count}.txt" ...
data.guess_filename", return_value="../invalid-filename.png" ): res = await client.post( "/api/media_source/local_source/upload", data={ "media_content_id": "media-source://media_source/test_dir/.", "file": get_file("../invalid-filename.png"), ...
201
201
671
19
182
MrDelik/core
tests/components/media_source/test_local_source.py
Python
test_remove_file
test_remove_file
229
333
229
229
bf240568644c55b9153405414872dbf406148204
bigcode/the-stack
train
953d201ba6e3e21372f6c54a
train
function
async def test_async_browse_media(hass): """Test browse media.""" local_media = hass.config.path("media") await async_process_ha_core_config( hass, {"media_dirs": {"local": local_media, "recordings": local_media}} ) await hass.async_block_till_done() assert await async_setup_component(h...
async def test_async_browse_media(hass):
"""Test browse media.""" local_media = hass.config.path("media") await async_process_ha_core_config( hass, {"media_dirs": {"local": local_media, "recordings": local_media}} ) await hass.async_block_till_done() assert await async_setup_component(hass, const.DOMAIN, {}) await hass.asy...
_api from homeassistant.components.media_source import const from homeassistant.config import async_process_ha_core_config from homeassistant.setup import async_setup_component @pytest.fixture async def temp_dir(hass): """Return a temp dir.""" with TemporaryDirectory() as tmpdirname: target_dir = Path...
135
135
450
10
125
MrDelik/core
tests/components/media_source/test_local_source.py
Python
test_async_browse_media
test_async_browse_media
30
83
30
30
7e9fdbc59dfc425f1641db25c87fb4077322f0e1
bigcode/the-stack
train
8081f64c714235648b47859b
train
function
async def test_upload_view(hass, hass_client, temp_dir, hass_admin_user): """Allow uploading media.""" img = (Path(__file__).parent.parent / "image/logo.png").read_bytes() def get_file(name): pic = io.BytesIO(img) pic.name = name return pic client = await hass_client() # ...
async def test_upload_view(hass, hass_client, temp_dir, hass_admin_user):
"""Allow uploading media.""" img = (Path(__file__).parent.parent / "image/logo.png").read_bytes() def get_file(name): pic = io.BytesIO(img) pic.name = name return pic client = await hass_client() # Test normal upload res = await client.post( "/api/media_source...
resp = await client.get("/media/local/invalid.txt") assert resp.status == HTTPStatus.NOT_FOUND resp = await client.get("/media/recordings/invalid.txt") assert resp.status == HTTPStatus.NOT_FOUND # Protects against non-media files resp = await client.get("/media/local/not_media.txt") assert re...
212
212
709
18
193
MrDelik/core
tests/components/media_source/test_local_source.py
Python
test_upload_view
test_upload_view
125
226
125
125
f4572470dc11cfb333c81e1222c4ba04ca88c34a
bigcode/the-stack
train
0c0522d70295e0c85165c57e
train
function
@pytest.fixture async def temp_dir(hass): """Return a temp dir.""" with TemporaryDirectory() as tmpdirname: target_dir = Path(tmpdirname) / "another_subdir" target_dir.mkdir() await async_process_ha_core_config( hass, {"media_dirs": {"test_dir": str(target_dir)}} ) ...
@pytest.fixture async def temp_dir(hass):
"""Return a temp dir.""" with TemporaryDirectory() as tmpdirname: target_dir = Path(tmpdirname) / "another_subdir" target_dir.mkdir() await async_process_ha_core_config( hass, {"media_dirs": {"test_dir": str(target_dir)}} ) assert await async_setup_component(h...
import TemporaryDirectory from unittest.mock import patch import pytest from homeassistant.components import media_source, websocket_api from homeassistant.components.media_source import const from homeassistant.config import async_process_ha_core_config from homeassistant.setup import async_setup_component @pytest....
64
64
93
10
53
MrDelik/core
tests/components/media_source/test_local_source.py
Python
temp_dir
temp_dir
16
27
16
17
177351fb74914392ea6c99c1b516f7a6807f1493
bigcode/the-stack
train
2bfa987c84f4129caa3ef009
train
class
class MyDataMunger: def do_it_all(self, input_file_path, output_file_path): with open(input_file_path) as inputcsv: reader = csv.reader(inputcsv) with open(output_file_path, 'w', newline='') as outputcsv: writer = csv.writer(outputcsv) for row in reade...
class MyDataMunger:
def do_it_all(self, input_file_path, output_file_path): with open(input_file_path) as inputcsv: reader = csv.reader(inputcsv) with open(output_file_path, 'w', newline='') as outputcsv: writer = csv.writer(outputcsv) for row in reader: ...
import csv class MyDataMunger:
9
64
149
6
2
trcull/generation-data-class
solution_remove_column.py
Python
MyDataMunger
MyDataMunger
4
18
4
4
92c932569d127d1b948bb24bcd7384c9f3be823d
bigcode/the-stack
train
61932673b155ae9849cf1158
train
class
class ns0: targetNamespace = "https://www.google.com/apis/ads/publisher/v201103" class ApiError_Def(ZSI.TCcompound.ComplexType, TypeDefinition): schema = "https://www.google.com/apis/ads/publisher/v201103" type = (schema, "ApiError") def __init__(self, pname, ofwhat=(), attributes=None,...
class ns0:
targetNamespace = "https://www.google.com/apis/ads/publisher/v201103" class ApiError_Def(ZSI.TCcompound.ComplexType, TypeDefinition): schema = "https://www.google.com/apis/ads/publisher/v201103" type = (schema, "ApiError") def __init__(self, pname, ofwhat=(), attributes=None, extend=Fal...
################################################## # CreativeService_services_types.py # generated by ZSI.generate.wsdl2python ################################################## import ZSI import ZSI.TCcompound from ZSI.schema import LocalElementDeclaration, ElementDeclaration, TypeDefinition, GTD, GED ###########...
84
256
17,268
4
80
hockeyprincess/google-api-dfp-python
adspygoogle/dfp/zsi/v201103/CreativeService_services_types.py
Python
ns0
ns0
16
1,151
16
16
fa1331d9cf1c8d1d89827a29c2abbe4fe0755bdb
bigcode/the-stack
train
7820a442c8d9e8524b49ac7e
train
class
class CarInterfaceBase(ABC): def __init__(self, CP, CarController, CarState): self.CP = CP self.VM = VehicleModel(CP) self.frame = 0 self.steering_unpressed = 0 self.low_speed_alert = False self.silent_steer_warning = True if CarState is not None: self.CS = CarState(CP) self....
class CarInterfaceBase(ABC):
def __init__(self, CP, CarController, CarState): self.CP = CP self.VM = VehicleModel(CP) self.frame = 0 self.steering_unpressed = 0 self.low_speed_alert = False self.silent_steer_warning = True if CarState is not None: self.CS = CarState(CP) self.cp = self.CS.get_can_parser(C...
import os import time from abc import abstractmethod, ABC from typing import Dict, Tuple, List from cereal import car from common.kalman.simple_kalman import KF1D from common.realtime import DT_CTRL from selfdrive.car import gen_empty_fingerprint from common.conversions import Conversions as CV from selfdrive.controls...
235
256
1,661
7
227
powerscv1/openpilot
selfdrive/car/interfaces.py
Python
CarInterfaceBase
CarInterfaceBase
29
180
29
29
eab03eb6e125bbd15b0b6b3d85932975f2af7864
bigcode/the-stack
train
81c529097e23706a472e24ad
train
class
class RadarInterfaceBase(ABC): def __init__(self, CP): self.pts = {} self.delay = 0 self.radar_ts = CP.radarTimeStep self.no_radar_sleep = 'NO_RADAR_SLEEP' in os.environ def update(self, can_strings): ret = car.RadarData.new_message() if not self.no_radar_sleep: time.sleep(self.radar_...
class RadarInterfaceBase(ABC):
def __init__(self, CP): self.pts = {} self.delay = 0 self.radar_ts = CP.radarTimeStep self.no_radar_sleep = 'NO_RADAR_SLEEP' in os.environ def update(self, can_strings): ret = car.RadarData.new_message() if not self.no_radar_sleep: time.sleep(self.radar_ts) # radard runs on RI update...
pcm_enable: if cs_out.cruiseState.enabled and not self.CS.out.cruiseState.enabled: events.add(EventName.pcmEnable) elif not cs_out.cruiseState.enabled: events.add(EventName.pcmDisable) return events class RadarInterfaceBase(ABC):
64
64
106
7
56
powerscv1/openpilot
selfdrive/car/interfaces.py
Python
RadarInterfaceBase
RadarInterfaceBase
183
194
183
183
3db5a63925f14751ea98c8139689aaed8d48f40c
bigcode/the-stack
train
a6aa3a422c3982264576ecd0
train
class
class CarStateBase(ABC): def __init__(self, CP): self.CP = CP self.car_fingerprint = CP.carFingerprint self.out = car.CarState.new_message() self.cruise_buttons = 0 self.left_blinker_cnt = 0 self.right_blinker_cnt = 0 self.left_blinker_prev = False self.right_blinker_prev = False ...
class CarStateBase(ABC):
def __init__(self, CP): self.CP = CP self.car_fingerprint = CP.carFingerprint self.out = car.CarState.new_message() self.cruise_buttons = 0 self.left_blinker_cnt = 0 self.right_blinker_cnt = 0 self.left_blinker_prev = False self.right_blinker_prev = False # Q = np.matrix([[10.0, ...
# if (cs_out.gasPressed and (not self.CS.out.gasPressed) and cs_out.vEgo > gas_resume_speed) or \ # (cs_out.brakePressed and (not self.CS.out.brakePressed or not cs_out.standstill)): # events.add(EventName.pedalPressed) # we engage when pcm is active (rising edge) if pcm_enable: if cs_ou...
256
256
1,071
7
248
powerscv1/openpilot
selfdrive/car/interfaces.py
Python
CarStateBase
CarStateBase
197
283
197
197
531f9835a9df0599aae631ad9c2ab93265b5bd10
bigcode/the-stack
train
a33205c48d3d542e6e8dc73c
train
class
class MSBuildBuildSystem(BuildSystemBase): def __init__(self): BuildSystemBase.__init__(self, "msbuild") self.msbuildTargets = ["Rebuild"] self.buildTypes = {"Release" : "Release", "RelWithDebInfo" : "Release", "Debug" : "Debug" } def configure(self, defines=""): return True ...
class MSBuildBuildSystem(BuildSystemBase):
def __init__(self): BuildSystemBase.__init__(self, "msbuild") self.msbuildTargets = ["Rebuild"] self.buildTypes = {"Release" : "Release", "RelWithDebInfo" : "Release", "Debug" : "Debug" } def configure(self, defines=""): return True def make(self): self.enterSourceD...
# documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 DISCLAIMED. I...
197
197
659
9
188
Inokinoki/craft
bin/BuildSystem/MSBuildBuildSystem.py
Python
MSBuildBuildSystem
MSBuildBuildSystem
30
95
30
30
12d9cfc21d1119baed75836a9fec992ed251949a
bigcode/the-stack
train
5a24e8fade71b69be579a204
train
class
class Uni(Expr): def __init__(self,t,op,expr): super().__init__(t) self._op = op self._expr = expr def op(self): return self._op def expr(self): return self._expr def accept(self,visitor): return visitor.visit(self) def _dump(self,dumper...
class Uni(Expr):
def __init__(self,t,op,expr): super().__init__(t) self._op = op self._expr = expr def op(self): return self._op def expr(self): return self._expr def accept(self,visitor): return visitor.visit(self) def _dump(self,dumper): dumper...
from .Expr import Expr class Uni(Expr):
11
64
108
5
5
U-Ar/Cpresto
cpc/ir/Uni.py
Python
Uni
Uni
3
19
3
3
2b27cd0ffe4f98173a7a37bb6c786a3aa7068cc1
bigcode/the-stack
train
59680a59124a1966728b6244
train
class
class ProjectManager: class __ProjectManager: def __str__(self): return repr(self) instance = None def __init__(self): if not ProjectManager.instance: ProjectManager.instance = ProjectManager.__ProjectManager() def __getattr__(self, name): return getatt...
class ProjectManager:
class __ProjectManager: def __str__(self): return repr(self) instance = None def __init__(self): if not ProjectManager.instance: ProjectManager.instance = ProjectManager.__ProjectManager() def __getattr__(self, name): return getattr(self.instance, name)...
from .entities.entity import Session, engine, Base from .entities.project import Project, ProjectSchema from .entities.pbutton import PButton, PButtonSchema from .entities.bookmark import Bookmark, BookmarkSchema from .entities.layout import Layout, LayoutSchema from .entities.layoutcolumn import LayoutColumn, LayoutCo...
190
256
2,832
4
186
kazamatzuri/yape-web
api/src/projectmanager.py
Python
ProjectManager
ProjectManager
28
469
28
28
09aa612751e777feb2bdf061da8632c9058fc822
bigcode/the-stack
train
2fd1e6edcf5e350f494dd050
train
class
class Project: def __init__(self, data, client): self.id = data["id"] self.title = data["title"] self.description = data["description"] self.instructions = data["instructions"] self.visible = data["visibility"] == "visible" self.public = data["public"] self.co...
class Project:
def __init__(self, data, client): self.id = data["id"] self.title = data["title"] self.description = data["description"] self.instructions = data["instructions"] self.visible = data["visibility"] == "visible" self.public = data["public"] self.comments_allowed ...
import requests import json from .IncompleteUser import IncompleteUser from .ScratchExceptions import UnauthorizedException from .ProjectComment import ProjectComment class Project:
34
256
2,253
3
30
potatojek/turbowarpclient
scratchclient/Project.py
Python
Project
Project
9
328
9
9
9dcf1699465a05594bd9dda9fa5f49f7fa60af3c
bigcode/the-stack
train
0311ee221989ec82c57fbc7c
train
function
def main7(id,ty): line=[] for line in open('p_name'+str(ty)+'.txt','r',encoding='utf-8'): line=eval(line) if line[0]==id: print('right') break if line[0]!=id: return 'no' print(line[0]) url='http://zupu.syshenshi.com/zuren_detail.aspx?id='+li...
def main7(id,ty):
line=[] for line in open('p_name'+str(ty)+'.txt','r',encoding='utf-8'): line=eval(line) if line[0]==id: print('right') break if line[0]!=id: return 'no' print(line[0]) url='http://zupu.syshenshi.com/zuren_detail.aspx?id='+line[0] print(ur...
import requests import csv import json import sys sys.path.append("..") import mytemp import re import time import xlsxwriter import pandas as pd def main7(id,ty):
46
102
340
7
38
zzh-python/all-project
zupu.syshenshi.com/writeToexcel_final.py
Python
main7
main7
13
49
13
13
7da3a185069fd342496ca609f5dc525f0a2b6fbf
bigcode/the-stack
train
c4b254ed737faa689fd83149
train
function
def main4(ty,workbook,worksheet_1,r): LEN=[1,10,1,10,12,12,12,12] #创建一个文件 colMax=0 rown=['自己','配偶','父亲','母亲','兄弟','姐妹','儿子','女儿'] rowname=[] for i in range(8): colMax=colMax+LEN[i] rowname=rowname+[rown[i] for j in range(LEN[i])] # print(colMax) for line in c...
def main4(ty,workbook,worksheet_1,r):
LEN=[1,10,1,10,12,12,12,12] #创建一个文件 colMax=0 rown=['自己','配偶','父亲','母亲','兄弟','姐妹','儿子','女儿'] rowname=[] for i in range(8): colMax=colMax+LEN[i] rowname=rowname+[rown[i] for j in range(LEN[i])] # print(colMax) for line in csv.reader(open('82.csv','r')): ...
row def main6(ty): f1=open('./zupu1/P_detail_final'+str(ty)+'.csv','w+',newline='',encoding='gb18030') csv_write1=csv.writer(f1) try: for line in open('./zupu1/P_detail'+str(ty)+'.txt','r',encoding='utf-8'): line=eval(line) if '否' in line[25]: ...
256
256
1,142
14
241
zzh-python/all-project
zupu.syshenshi.com/writeToexcel_final.py
Python
main4
main4
73
182
73
73
4e88278e89aab4434955c5597a1f222d02b3bccf
bigcode/the-stack
train
c79c02016d9d17fe89aca7cb
train
function
def main8(): #写入excel j=0 #写入excel的行数 r=0 page=1 print('page'+str(page)) num=4 page_max=20 zupufile='zupu_full' workbook = xlsxwriter.Workbook('excel_page'+str(page)+'_final.xlsx') worksheet_1 = workbook.add_worksheet() for line in open(zupufile+'.txt','r...
def main8(): #写入excel
j=0 #写入excel的行数 r=0 page=1 print('page'+str(page)) num=4 page_max=20 zupufile='zupu_full' workbook = xlsxwriter.Workbook('excel_page'+str(page)+'_final.xlsx') worksheet_1 = workbook.add_worksheet() for line in open(zupufile+'.txt','r',encoding='utf-8'): ...
i in range(32): if i==0: row[0][i]='http://zupu.syshenshi.com/zuren_detail.aspx?id='+row[0][i] worksheet_1.write(r,col*33+2+i,str(row[0][i]).strip()) r=r+1 return r def main8(): #写入excel
80
80
268
10
69
zzh-python/all-project
zupu.syshenshi.com/writeToexcel_final.py
Python
main8
main8
184
214
184
185
f0aabdb4d9ed3b4101bc06ac9f20af2685d30b2e
bigcode/the-stack
train
a2b95ffa30af859d34dcacfa
train
function
def main6(ty): f1=open('./zupu1/P_detail_final'+str(ty)+'.csv','w+',newline='',encoding='gb18030') csv_write1=csv.writer(f1) try: for line in open('./zupu1/P_detail'+str(ty)+'.txt','r',encoding='utf-8'): line=eval(line) if '否' in line[25]: i...
def main6(ty):
f1=open('./zupu1/P_detail_final'+str(ty)+'.csv','w+',newline='',encoding='gb18030') csv_write1=csv.writer(f1) try: for line in open('./zupu1/P_detail'+str(ty)+'.txt','r',encoding='utf-8'): line=eval(line) if '否' in line[25]: if len(line)==31:...
=tr.find_all('td',class_='left') for td in tdlist: row.append(td.get_text().replace(" ",'')) if len(row)==31: row=row[:26]+['','']+row[26:] print(row) return row def main6(ty):
67
67
226
6
60
zzh-python/all-project
zupu.syshenshi.com/writeToexcel_final.py
Python
main6
main6
51
70
51
51
2792cb57a03c45f23f955c60e61538aa77a47d36
bigcode/the-stack
train
414dc204b4138bea97e03822
train
class
@ddt class TestBernoulli(QiskitAquaTestCase): """Tests based on the Bernoulli A operator. This class tests * the estimation result * the constructed circuits """ def setUp(self): super().setUp() self._statevector = QuantumInstance(backend=BasicAer.get_backend('statevec...
@ddt class TestBernoulli(QiskitAquaTestCase):
"""Tests based on the Bernoulli A operator. This class tests * the estimation result * the constructed circuits """ def setUp(self): super().setUp() self._statevector = QuantumInstance(backend=BasicAer.get_backend('statevector_simulator'), ...
if matrix_power: return super().power(power, True) powered = QuantumCircuit(1) powered.ry(power * 2 * self.angle, 0) return powered class SineIntegral(QuantumCircuit): r"""Construct the A operator to approximate the integral \int_0^1 \sin^2(x) d x with a specifi...
256
256
1,816
17
239
stefan-woerner/aqua
test/aqua/test_amplitude_estimation.py
Python
TestBernoulli
TestBernoulli
76
266
76
77
20faa9aba49e4de7c24f0f782e60ee66d4f8a5b2
bigcode/the-stack
train
d0ab180db247067a457477ad
train
class
class BernoulliStateIn(QuantumCircuit): """A circuit preparing sqrt(1 - p)|0> + sqrt(p)|1>.""" def __init__(self, probability): super().__init__(1) angle = 2 * np.arcsin(np.sqrt(probability)) self.ry(angle, 0)
class BernoulliStateIn(QuantumCircuit):
"""A circuit preparing sqrt(1 - p)|0> + sqrt(p)|1>.""" def __init__(self, probability): super().__init__(1) angle = 2 * np.arcsin(np.sqrt(probability)) self.ry(angle, 0)
QFT, GroverOperator from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import (AmplitudeEstimation, MaximumLikelihoodAmplitudeEstimation, IterativeAmplitudeEstimation) from qiskit.quantum_info import Operator class BernoulliStateIn(QuantumCircuit):
64
64
70
10
53
stefan-woerner/aqua
test/aqua/test_amplitude_estimation.py
Python
BernoulliStateIn
BernoulliStateIn
28
34
28
28
97514dc588f2b85448203460f87308c9ba80daf7
bigcode/the-stack
train
2b81c5c6aaa0c94134245889
train
class
class SineIntegral(QuantumCircuit): r"""Construct the A operator to approximate the integral \int_0^1 \sin^2(x) d x with a specified number of qubits. """ def __init__(self, num_qubits): qr_state = QuantumRegister(num_qubits, 'state') qr_objective = QuantumRegister(1, 'obj') ...
class SineIntegral(QuantumCircuit):
r"""Construct the A operator to approximate the integral \int_0^1 \sin^2(x) d x with a specified number of qubits. """ def __init__(self, num_qubits): qr_state = QuantumRegister(num_qubits, 'state') qr_objective = QuantumRegister(1, 'obj') super().__init__(qr_state, qr...
, 0) def power(self, power, matrix_power=False): if matrix_power: return super().power(power, True) powered = QuantumCircuit(1) powered.ry(power * 2 * self.angle, 0) return powered class SineIntegral(QuantumCircuit):
64
64
199
8
55
stefan-woerner/aqua
test/aqua/test_amplitude_estimation.py
Python
SineIntegral
SineIntegral
54
73
54
54
0e2b6859c8fa5d3d510e191a0f35384f30497acd
bigcode/the-stack
train
5ba946e7494356e5f9ede8b5
train
class
class BernoulliGrover(QuantumCircuit): """The Grover operator corresponding to the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) self.angle = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self.angle, 0) def power(self, power, matrix_power=False): ...
class BernoulliGrover(QuantumCircuit):
"""The Grover operator corresponding to the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) self.angle = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self.angle, 0) def power(self, power, matrix_power=False): if matrix_power: ret...
(1 - p)|0> + sqrt(p)|1>.""" def __init__(self, probability): super().__init__(1) angle = 2 * np.arcsin(np.sqrt(probability)) self.ry(angle, 0) class BernoulliGrover(QuantumCircuit):
64
64
122
10
54
stefan-woerner/aqua
test/aqua/test_amplitude_estimation.py
Python
BernoulliGrover
BernoulliGrover
37
51
37
37
5fe832cba0f9fc0445d2724a08756e3c85ae4893
bigcode/the-stack
train
5b6baec6ac971509295dad11
train
class
@ddt class TestSineIntegral(QiskitAquaTestCase): """Tests based on the A operator to integrate sin^2(x). This class tests * the estimation result * the confidence intervals """ def setUp(self): super().setUp() self._statevector = QuantumInstance(backend=BasicAer.get_ba...
@ddt class TestSineIntegral(QiskitAquaTestCase):
"""Tests based on the A operator to integrate sin^2(x). This class tests * the estimation result * the confidence intervals """ def setUp(self): super().setUp() self._statevector = QuantumInstance(backend=BasicAer.get_backend('statevector_simulator'), ...
ae.grover_operator) self.assertIsNotNone(qae.objective_qubits) self.assertIsNotNone(qae._state_preparation) self.assertIsNone(qae._grover_operator) self.assertIsNone(qae._objective_qubits) qae.grover_operator = self.q_bernoulli self.assertIsNotNone(qae.state_preparation)...
256
256
1,321
17
239
stefan-woerner/aqua
test/aqua/test_amplitude_estimation.py
Python
TestSineIntegral
TestSineIntegral
327
441
327
328
c2a2bf110fdd8ed1b482d911b80155f7e3e044f3
bigcode/the-stack
train
6c98aa3deb8800723d005180
train
class
@ddt class TestProblemSetting(QiskitAquaTestCase): """Test the setting and getting of the A and Q operator and the objective qubit index.""" def setUp(self): super().setUp() self.a_bernoulli = BernoulliStateIn(0) self.q_bernoulli = BernoulliGrover(0) self.i_bernoulli = [0] ...
@ddt class TestProblemSetting(QiskitAquaTestCase):
"""Test the setting and getting of the A and Q operator and the objective qubit index.""" def setUp(self): super().setUp() self.a_bernoulli = BernoulliStateIn(0) self.q_bernoulli = BernoulliGrover(0) self.i_bernoulli = [0] num_qubits = 5 self.a_integral = SineIn...
_operator = BernoulliGrover(prob) circuit.ry(2 * 2 ** power * angle, q_objective[0]) else: oracle = QuantumCircuit(1) oracle.x(0) oracle.z(0) oracle.x(0) state_preparation = QuantumCi...
173
173
577
16
157
stefan-woerner/aqua
test/aqua/test_amplitude_estimation.py
Python
TestProblemSetting
TestProblemSetting
269
324
269
270
4da5eae3c8ead0819cf6f8b25d09d977d30ff194
bigcode/the-stack
train
3e6f112cd9fb55596830d4e9
train
class
class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE): IE_NAME = 'bbc.co.uk:playlist' _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s' _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)' _TES...
class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
IE_NAME = 'bbc.co.uk:playlist' _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s' _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)' _TESTS = [{ 'url': 'http://www.bbc.co.uk/pro...
episode, field): return episode.get(field) @staticmethod def _get_elements(data): return data['elements'] @staticmethod def _get_episode(element): return element def _call_api(self, pid, per_page, page=1, series_id=None): return self._download_json( 'h...
168
168
561
15
153
ouwou/yt-dlp
yt_dlp/extractor/bbc.py
Python
BBCCoUkPlaylistIE
BBCCoUkPlaylistIE
1,577
1,622
1,577
1,577
ee8e32189481438adddd5b0745b9442b854bf9f8
bigcode/the-stack
train
94fbfbf73e45e2ac8f5514b7
train
class
class BBCCoUkIPlayerPlaylistBaseIE(InfoExtractor): _VALID_URL_TMPL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/%%s/(?P<id>%s)' % BBCCoUkIE._ID_REGEX @staticmethod def _get_default(episode, key, default_key='default'): return try_get(episode, lambda x: x[key][default_key]) def _get_description(s...
class BBCCoUkIPlayerPlaylistBaseIE(InfoExtractor):
_VALID_URL_TMPL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/%%s/(?P<id>%s)' % BBCCoUkIE._ID_REGEX @staticmethod def _get_default(episode, key, default_key='default'): return try_get(episode, lambda x: x[key][default_key]) def _get_description(self, data): synopsis = data.get(self._DESCR...
?:(?!\2).)+)\2', webpage, 'next page url', default=None, group='url') if not next_page: break webpage = self._download_webpage( compat_urlparse.urljoin(url, next_page), playlist_id, 'Downloading page %d' % page_num, page_num) d...
158
158
529
14
144
ouwou/yt-dlp
yt_dlp/extractor/bbc.py
Python
BBCCoUkIPlayerPlaylistBaseIE
BBCCoUkIPlayerPlaylistBaseIE
1,374
1,421
1,374
1,374
3b5d0d7997f2cbd304df22aef5317644070ec3ed
bigcode/the-stack
train
fb563536afe72783e3d6b050
train
class
class BBCCoUkIPlayerGroupIE(BBCCoUkIPlayerPlaylistBaseIE): IE_NAME = 'bbc.co.uk:iplayer:group' _VALID_URL = BBCCoUkIPlayerPlaylistBaseIE._VALID_URL_TMPL % 'group' _TESTS = [{ # Available for over a year unlike 30 days for most other programmes 'url': 'http://www.bbc.co.uk/iplayer/group/p02tc...
class BBCCoUkIPlayerGroupIE(BBCCoUkIPlayerPlaylistBaseIE):
IE_NAME = 'bbc.co.uk:iplayer:group' _VALID_URL = BBCCoUkIPlayerPlaylistBaseIE._VALID_URL_TMPL % 'group' _TESTS = [{ # Available for over a year unlike 30 days for most other programmes 'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32', 'info_dict': { 'id': 'p02tcc32', ...
'perPage': per_page, } if series_id: variables['sliceId'] = series_id return self._download_json( 'https://graph.ibl.api.bbc.co.uk/', pid, headers={ 'Content-Type': 'application/json' }, data=json.dumps({ 'id': '5692d93d5aac8d7...
162
162
543
19
143
ouwou/yt-dlp
yt_dlp/extractor/bbc.py
Python
BBCCoUkIPlayerGroupIE
BBCCoUkIPlayerGroupIE
1,513
1,574
1,513
1,513
2fdcffe81b7a392d6b0c390fa613da2299397cbd
bigcode/the-stack
train
d2f2bf685d6bfbf208f5049a
train
class
class BBCCoUkArticleIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)' IE_NAME = 'bbc.co.uk:article' IE_DESC = 'BBC articles' _TEST = { 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ad...
class BBCCoUkArticleIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)' IE_NAME = 'bbc.co.uk:article' IE_DESC = 'BBC articles' _TEST = { 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer'...
.get('width')), 'height': int_or_none(image.get('height')), } for image in images] entries.append({ 'id': video_id, 'title': title, 'thumbnails': thumbnails, 'duration': duration, 'timestamp': timest...
102
102
343
11
91
ouwou/yt-dlp
yt_dlp/extractor/bbc.py
Python
BBCCoUkArticleIE
BBCCoUkArticleIE
1,312
1,339
1,312
1,312
64ef133d9e1e4c05cd33bfd93f94ed4c94e7fa9c
bigcode/the-stack
train
534abf167e5b74567b51db1c
train
class
class BBCCoUkIPlayerEpisodesIE(BBCCoUkIPlayerPlaylistBaseIE): IE_NAME = 'bbc.co.uk:iplayer:episodes' _VALID_URL = BBCCoUkIPlayerPlaylistBaseIE._VALID_URL_TMPL % 'episodes' _TESTS = [{ 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v', 'info_dict': { 'id': 'b05rcz9v', ...
class BBCCoUkIPlayerEpisodesIE(BBCCoUkIPlayerPlaylistBaseIE):
IE_NAME = 'bbc.co.uk:iplayer:episodes' _VALID_URL = BBCCoUkIPlayerPlaylistBaseIE._VALID_URL_TMPL % 'episodes' _TESTS = [{ 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v', 'info_dict': { 'id': 'b05rcz9v', 'title': 'The Disappearance', 'description':...
iplayer/episode/' + episode_id, 'thumbnail': thumbnail, 'description': self._get_description(episode), 'categories': [category] if category else None, 'series': self._get_episode_field(episode, 'title'), 'ie_key': BBCCoUkIE.ie_key(), ...
248
248
827
19
229
ouwou/yt-dlp
yt_dlp/extractor/bbc.py
Python
BBCCoUkIPlayerEpisodesIE
BBCCoUkIPlayerEpisodesIE
1,424
1,510
1,424
1,424
aa523208c0777c8a466f9bfd71c19f4c820d161e
bigcode/the-stack
train
d8ddfed84d3a3d3b3d46eaf8
train
class
class BBCIE(BBCCoUkIE): IE_NAME = 'bbc' IE_DESC = 'BBC' _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)' _MEDIA_SETS = [ 'mobile-tablet-main', 'pc', ] _TESTS = [{ # article with multiple videos embedded with data-playable containing vpid...
class BBCIE(BBCCoUkIE):
IE_NAME = 'bbc' IE_DESC = 'BBC' _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)' _MEDIA_SETS = [ 'mobile-tablet-main', 'pc', ] _TESTS = [{ # article with multiple videos embedded with data-playable containing vpids 'url': 'http:/...
._og_search_title(webpage, default=None) or self._html_search_regex( (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>', r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title') description = self._search_regex( (r'<p class="[^"]*medium-description[^"]*...
256
256
7,488
9
247
ouwou/yt-dlp
yt_dlp/extractor/bbc.py
Python
BBCIE
BBCIE
585
1,309
585
585
0e99154b2242bbae51dd9b3a7699b61c65a769a1
bigcode/the-stack
train
06d0942752d3c3235123c694
train
class
class BBCCoUkIE(InfoExtractor): IE_NAME = 'bbc.co.uk' IE_DESC = 'BBC iPlayer' _ID_REGEX = r'(?:[pbm][\da-z]{7}|w[\da-z]{7,14})' _VALID_URL = r'''(?x) https?:// (?:www\.)?bbc\.co\.uk/ (?: programmes/(?!article...
class BBCCoUkIE(InfoExtractor):
IE_NAME = 'bbc.co.uk' IE_DESC = 'BBC iPlayer' _ID_REGEX = r'(?:[pbm][\da-z]{7}|w[\da-z]{7,14})' _VALID_URL = r'''(?x) https?:// (?:www\.)?bbc\.co\.uk/ (?: programmes/(?!articles/)| ...
# coding: utf-8 from __future__ import unicode_literals import functools import itertools import json import re from .common import InfoExtractor from ..compat import ( compat_etree_Element, compat_HTTPError, compat_str, compat_urlparse, ) from ..utils import ( ExtractorError, OnDemandPagedLis...
163
256
5,139
10
153
ouwou/yt-dlp
yt_dlp/extractor/bbc.py
Python
BBCCoUkIE
BBCCoUkIE
38
582
38
38
7f0bcc9eb38965faf95faa7ff487c63e3721db51
bigcode/the-stack
train
256fd31b7240237da4e67005
train
class
class BBCCoUkPlaylistBaseIE(InfoExtractor): def _entries(self, webpage, url, playlist_id): single_page = 'page' in compat_urlparse.parse_qs( compat_urlparse.urlparse(url).query) for page_num in itertools.count(2): for video_id in re.findall( self._VIDEO_ID...
class BBCCoUkPlaylistBaseIE(InfoExtractor):
def _entries(self, webpage, url, playlist_id): single_page = 'page' in compat_urlparse.parse_qs( compat_urlparse.urlparse(url).query) for page_num in itertools.count(2): for video_id in re.findall( self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage): ...
title = self._og_search_title(webpage) description = self._og_search_description(webpage).strip() entries = [self.url_result(programme_url) for programme_url in re.findall( r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)] return self.playlist_result(entries, play...
92
92
307
12
80
ouwou/yt-dlp
yt_dlp/extractor/bbc.py
Python
BBCCoUkPlaylistBaseIE
BBCCoUkPlaylistBaseIE
1,342
1,371
1,342
1,342
094bf3cba034c8cf47a1580f3e9925054ad12c2a
bigcode/the-stack
train
e17af69e065bd91d44e6c0a7
train
function
def export_to_colmap_points3d_txt(colmap_points3d_filepath: str, colmap_image_ids: Dict[str, int], points3d: kapture.Points3d = None, observations: kapture.Observations = None, keypoin...
def export_to_colmap_points3d_txt(colmap_points3d_filepath: str, colmap_image_ids: Dict[str, int], points3d: kapture.Points3d = None, observations: kapture.Observations = None, keypoin...
""" Exports to colmap points3d text file. :param colmap_points3d_filepath: path to colmap points3d file to be writen. :param colmap_image_ids: correspondences between kapture image id (image path) and colmap image id :param points3d: kapture points3d to export :param observations: kapture obser...
filtering. :param colmap_matches_filepath: input path to colmap matches file to be writen. :param matches: input kapture.Matches """ assert isinstance(matches, kapture.Matches) with open(colmap_matches_filepath, 'w') as fid: # matches[(image_path1, image_path2)] = image_matches for...
169
169
564
66
103
v-mehta/kapture
kapture/converter/colmap/export_colmap_reconstruction.py
Python
export_to_colmap_points3d_txt
export_to_colmap_points3d_txt
124
165
124
128
b612c0fea197f0e30f51261c3f8277967ae005ac
bigcode/the-stack
train
df44cbdcb42f5cde23d8264e
train
function
def export_to_colmap_images_txt(colmap_images_filepath: str, images: kapture.RecordsCamera, trajectories: kapture.Trajectories, colmap_camera_ids: Dict[str, int], colmap_image_ids: Dict[str, i...
def export_to_colmap_images_txt(colmap_images_filepath: str, images: kapture.RecordsCamera, trajectories: kapture.Trajectories, colmap_camera_ids: Dict[str, int], colmap_image_ids: Dict[str, i...
""" Exports kapture to colmap reconstruction file "images.txt". :param colmap_images_filepath: path to colmap file "images.txt" to be writen. :param images: images list to export :param trajectories: poses to export :param colmap_camera_ids: correspondences between kapture camera id and colmap ...
open(colmap_cameras_filepath, 'w') as fid: fid.write(cameras_colmap_header) lines = (' '.join([str(colmap_camera_ids[cam_id]), CAMERA_MODEL_NAMES[col_cam_id]] + [str(int(width)), str(int(height))] + [str(int(v)) if v.is_integer() else str(v) for v in ...
201
201
670
78
123
v-mehta/kapture
kapture/converter/colmap/export_colmap_reconstruction.py
Python
export_to_colmap_images_txt
export_to_colmap_images_txt
54
107
54
59
43128090f86190a7b7f96ac13a73d0c711212be6
bigcode/the-stack
train
71fc53d7cd0289afcb82269d
train
function
def export_to_colmap_txt(colmap_reconstruction_dirpath: str, kapture_data: kapture.Kapture, kapture_dirpath: str, tar_handler: Optional[TarCollection], colmap_camera_ids: Dict[str, int], colmap_i...
def export_to_colmap_txt(colmap_reconstruction_dirpath: str, kapture_data: kapture.Kapture, kapture_dirpath: str, tar_handler: Optional[TarCollection], colmap_camera_ids: Dict[str, int], colmap_i...
""" Exports to colmap reconstruction text files. :param colmap_reconstruction_dirpath: path to directory where colmap reconstruction files will be stored. :param kapture_data: input kapture data :param kapture_dirpath: path to output directory, where colmap files will be stored :param tar_handl...
3d[3]), int(point3d[4]), int(point3d[5])) if observations is not None and i in observations: if len(observations[i]) == 0: continue elif len(observations[i]) == 1 and keypoints_type is None: keypoints_type = next(ite...
256
256
1,128
76
180
v-mehta/kapture
kapture/converter/colmap/export_colmap_reconstruction.py
Python
export_to_colmap_txt
export_to_colmap_txt
168
261
168
174
a5f43a3d36763d9ecd504b3e78e7ebe141a128fc
bigcode/the-stack
train
805f429a96ee589cb9758905
train
function
def export_to_colmap_cameras_txt(colmap_cameras_filepath: str, sensors: kapture.Sensors, colmap_camera_ids: Dict[str, int]) -> None: """ Exports to colmap reconstruction file "cameras.txt". :param colmap_cameras_filepath: path to colmap file...
def export_to_colmap_cameras_txt(colmap_cameras_filepath: str, sensors: kapture.Sensors, colmap_camera_ids: Dict[str, int]) -> None:
""" Exports to colmap reconstruction file "cameras.txt". :param colmap_cameras_filepath: path to colmap file "cameras.txt" to be writen. :param sensors: sensors to be exported :param colmap_camera_ids: gives the correspondences between kapture camera id and colmap camera id """ assert path....
only text format is supported). """ from kapture.io.tar import TarCollection import logging import os.path as path from typing import Dict, Optional, Tuple, List # kapture import kapture import kapture.io.features # local from .cameras import CAMERA_MODEL_NAMES, get_colmap_camera logger = logging.getLogger('colmap')...
114
114
383
38
76
v-mehta/kapture
kapture/converter/colmap/export_colmap_reconstruction.py
Python
export_to_colmap_cameras_txt
export_to_colmap_cameras_txt
21
51
21
23
24536d4227653fc9d2da8c91a9e2e80bf84d5de6
bigcode/the-stack
train
36652129cc1f752b0567605a
train
function
def export_to_colmap_matches_txt(colmap_matches_filepath: str, matches: kapture.Matches) -> None: """ Exports to colmap reconstruction file "matches.txt". This files can be used to redo the geometric filtering. :param colmap_matches_filepath: input path to colmap matches file to be writen. :param match...
def export_to_colmap_matches_txt(colmap_matches_filepath: str, matches: kapture.Matches) -> None:
""" Exports to colmap reconstruction file "matches.txt". This files can be used to redo the geometric filtering. :param colmap_matches_filepath: input path to colmap matches file to be writen. :param matches: input kapture.Matches """ assert isinstance(matches, kapture.Matches) with open(co...
_to_keypoints[sensing_filepath]] fid.write(' '.join('{} {} {}'.format(i, j, k) for i, j, k in p2d)) fid.write('\n') def export_to_colmap_matches_txt(colmap_matches_filepath: str, matches: kapture.Matches) -> None:
64
64
150
24
40
v-mehta/kapture
kapture/converter/colmap/export_colmap_reconstruction.py
Python
export_to_colmap_matches_txt
export_to_colmap_matches_txt
110
121
110
110
8d08a2479a11fdf3c5bf5458f9e122ee9809a25a
bigcode/the-stack
train
0acd6af6d09f622df0fcf950
train
function
def setup(bot): bot.add_cog(mido_music(bot)) if not hasattr(bot, "queue"): bot.queue = dict() if not hasattr(bot, "loop_queue"): bot.loop_queue = dict()
def setup(bot):
bot.add_cog(mido_music(bot)) if not hasattr(bot, "queue"): bot.queue = dict() if not hasattr(bot, "loop_queue"): bot.loop_queue = dict()
v = ctx.voice_client.source.volume except AttributeError: pass if self.bot.loop_queue[ctx.guild.id]: self.bot.queue[ctx.guild.id].append(self.bot.queue[ctx.guild.id][0]) self.bot.queue[ctx.guild.id].pop(0) def setup(bot):
64
64
46
4
60
midorichaan/DBot_3
cogs/mido_music.py
Python
setup
setup
304
310
304
304
c626eea1e120493d78dcacd39c82345cd55888c4
bigcode/the-stack
train
5e0dbf95d082f2d2a910e572
train
class
class mido_music(commands.Cog): def __init__(self, bot): self.bot = bot self.ytdl = youtube_dl.YoutubeDL(ytdl_format_options) self.youtube = build("youtube", "v3", developerKey=config.YOUTUBE_KEY) #get_data async def get_data(self, ctx, key, download=False): loop = self.bot...
class mido_music(commands.Cog):
def __init__(self, bot): self.bot = bot self.ytdl = youtube_dl.YoutubeDL(ytdl_format_options) self.youtube = build("youtube", "v3", developerKey=config.YOUTUBE_KEY) #get_data async def get_data(self, ctx, key, download=False): loop = self.bot.loop or asyncio.get_event_loop()...
import discord import functools from discord.ext import commands import asyncio import youtube_dl from apiclient.discovery import build import config youtube_dl.utils.bug_reports_message = lambda: '' ytdl_format_options = { 'proxy': f'{config.PROXY_URL}:{config.PROXY_PORT}', 'format': 'bestaudio/best', ...
245
256
2,985
8
237
midorichaan/DBot_3
cogs/mido_music.py
Python
mido_music
mido_music
36
302
36
37
2e8bd73300d6273b3d30016e3653c96e92205869
bigcode/the-stack
train
ecd8cf61912a1c869529d359
train
class
class UserUpdate(models.BaseUserUpdate): first_name: Optional[str]
class UserUpdate(models.BaseUserUpdate):
first_name: Optional[str]
") excalibur_password_hash = get_password_hash("excalibur") class User(models.BaseUser): first_name: Optional[str] last_name: Optional[str] picture: Optional[str] class UserCreate(models.BaseUserCreate): first_name: Optional[str] class UserUpdate(models.BaseUserUpdate):
64
64
15
8
56
chatalyan/fastapi-users
tests/conftest.py
Python
UserUpdate
UserUpdate
44
45
44
44
e701097d2bf3758ec3595060fba60222f1854dd1
bigcode/the-stack
train
103b180ea98962fe3d48625e
train
function
@pytest.fixture def oauth_client() -> OAuth2: CLIENT_ID = "CLIENT_ID" CLIENT_SECRET = "CLIENT_SECRET" AUTHORIZE_ENDPOINT = "https://www.camelot.bt/authorize" ACCESS_TOKEN_ENDPOINT = "https://www.camelot.bt/access-token" return OAuth2( CLIENT_ID, CLIENT_SECRET, AUTHORIZE_ENDP...
@pytest.fixture def oauth_client() -> OAuth2:
CLIENT_ID = "CLIENT_ID" CLIENT_SECRET = "CLIENT_SECRET" AUTHORIZE_ENDPOINT = "https://www.camelot.bt/authorize" ACCESS_TOKEN_ENDPOINT = "https://www.camelot.bt/access-token" return OAuth2( CLIENT_ID, CLIENT_SECRET, AUTHORIZE_ENDPOINT, ACCESS_TOKEN_ENDPOINT, n...
.AsyncClient, None]: async with LifespanManager(app): async with httpx.AsyncClient( app=app, base_url="http://app.io" ) as test_client: yield test_client return _get_test_client @pytest.fixture def oauth_client() -> OAuth2:
64
64
88
11
52
chatalyan/fastapi-users
tests/conftest.py
Python
oauth_client
oauth_client
502
515
502
503
3835cd1490af7a61ff98f91abe5ce157c2d0771f
bigcode/the-stack
train
94f2eebb4a6b4a62ab87b44e
train
function
@pytest.fixture def user_oauth(oauth_account1, oauth_account2) -> UserDBOAuth: return UserDBOAuth( email="king.arthur@camelot.bt", hashed_password=guinevere_password_hash, oauth_accounts=[oauth_account1, oauth_account2], )
@pytest.fixture def user_oauth(oauth_account1, oauth_account2) -> UserDBOAuth:
return UserDBOAuth( email="king.arthur@camelot.bt", hashed_password=guinevere_password_hash, oauth_accounts=[oauth_account1, oauth_account2], )
return request.param @pytest.fixture def user() -> UserDB: return UserDB( email="king.arthur@camelot.bt", hashed_password=guinevere_password_hash, ) @pytest.fixture def user_oauth(oauth_account1, oauth_account2) -> UserDBOAuth:
64
64
63
21
43
chatalyan/fastapi-users
tests/conftest.py
Python
user_oauth
user_oauth
142
148
142
143
5fb0df61e0ae55c3277e4791b5e4a15832c815ee
bigcode/the-stack
train
2723a90255031fe81955c708
train
function
@pytest.fixture(params=["SECRET", SecretStr("SECRET")]) def secret(request) -> SecretType: return request.param
@pytest.fixture(params=["SECRET", SecretStr("SECRET")]) def secret(request) -> SecretType:
return request.param
asyncio.Future() future.set_result(return_value) mock.return_value = future mock.side_effect = None setattr(object, method, mock) return mock return _async_method_mocker @pytest.fixture(params=["SECRET", SecretStr("SECRET")]) def secret(request) -> SecretType:
64
64
25
20
43
chatalyan/fastapi-users
tests/conftest.py
Python
secret
secret
129
131
129
130
69984569d13e7967bc35beb6b283a257d2a84e12
bigcode/the-stack
train
d281dc487494d0014a3b589c
train
class
class UserDB(User, models.BaseUserDB): pass
class UserDB(User, models.BaseUserDB):
pass
(models.BaseUser): first_name: Optional[str] last_name: Optional[str] picture: Optional[str] class UserCreate(models.BaseUserCreate): first_name: Optional[str] class UserUpdate(models.BaseUserUpdate): first_name: Optional[str] class UserDB(User, models.BaseUserDB):
64
64
13
10
54
chatalyan/fastapi-users
tests/conftest.py
Python
UserDB
UserDB
48
49
48
48
f33a937f8aabb5acc932d5c2b722670b66f78452
bigcode/the-stack
train
741593d9c9a3ffaf0453795a
train
function
@pytest.fixture def make_user_manager(mocker: MockerFixture): def _make_user_manager(user_manager_class: Type[BaseTestUserManager], mock_user_db): user_manager = user_manager_class(mock_user_db) mocker.spy(user_manager, "get_by_email") mocker.spy(user_manager, "request_verify") mocke...
@pytest.fixture def make_user_manager(mocker: MockerFixture):
def _make_user_manager(user_manager_class: Type[BaseTestUserManager], mock_user_db): user_manager = user_manager_class(mock_user_db) mocker.spy(user_manager, "get_by_email") mocker.spy(user_manager, "request_verify") mocker.spy(user_manager, "verify") mocker.spy(user_manager,...
async def update(self, user: UserDBOAuth) -> UserDBOAuth: return user_oauth async def delete(self, user: UserDBOAuth) -> None: pass return MockUserDatabase(UserDBOAuth) @pytest.fixture def make_user_manager(mocker: MockerFixture):
64
64
199
14
50
chatalyan/fastapi-users
tests/conftest.py
Python
make_user_manager
make_user_manager
397
415
397
398
7d11b46645b497a76689a67ee5c07511f4571cf8
bigcode/the-stack
train
f96d2568cf92f67407b7d8dc
train
function
@pytest.fixture def verified_user() -> UserDB: return UserDB( email="lake.lady@camelot.bt", hashed_password=excalibur_password_hash, is_active=True, is_verified=True, )
@pytest.fixture def verified_user() -> UserDB:
return UserDB( email="lake.lady@camelot.bt", hashed_password=excalibur_password_hash, is_active=True, is_verified=True, )
_oauth(oauth_account3) -> UserDBOAuth: return UserDBOAuth( email="percival@camelot.bt", hashed_password=angharad_password_hash, is_active=False, oauth_accounts=[oauth_account3], ) @pytest.fixture def verified_user() -> UserDB:
64
64
49
11
53
chatalyan/fastapi-users
tests/conftest.py
Python
verified_user
verified_user
170
177
170
171
cc2099dfb3d236c47d36a9251fe0c0e83fc95624
bigcode/the-stack
train
d137f6a56cebfb7eb1f12ec2
train
function
@pytest.fixture def oauth_account3() -> BaseOAuthAccount: return BaseOAuthAccount( oauth_name="service3", access_token="TOKEN", expires_at=1579000751, account_id="inactive_user_oauth1", account_email="percival@camelot.bt", )
@pytest.fixture def oauth_account3() -> BaseOAuthAccount:
return BaseOAuthAccount( oauth_name="service3", access_token="TOKEN", expires_at=1579000751, account_id="inactive_user_oauth1", account_email="percival@camelot.bt", )
return BaseOAuthAccount( oauth_name="service2", access_token="TOKEN", expires_at=1579000751, account_id="user_oauth2", account_email="king.arthur@camelot.bt", ) @pytest.fixture def oauth_account3() -> BaseOAuthAccount:
64
64
64
13
51
chatalyan/fastapi-users
tests/conftest.py
Python
oauth_account3
oauth_account3
252
260
252
253
51ae4040e5d31404bfa9de4c1727b62259c0660a
bigcode/the-stack
train
d21a5e2745064e96f8fd0567
train
class
class User(models.BaseUser): first_name: Optional[str] last_name: Optional[str] picture: Optional[str]
class User(models.BaseUser):
first_name: Optional[str] last_name: Optional[str] picture: Optional[str]
guinevere") angharad_password_hash = get_password_hash("angharad") viviane_password_hash = get_password_hash("viviane") lancelot_password_hash = get_password_hash("lancelot") excalibur_password_hash = get_password_hash("excalibur") class User(models.BaseUser):
64
64
26
6
58
chatalyan/fastapi-users
tests/conftest.py
Python
User
User
34
37
34
34
0dd97d0e0fa3d14bcba5bd2438731d25b9afbb76
bigcode/the-stack
train
07bd6c5f4adfe5228af0ca59
train
function
@pytest.fixture def get_user_manager(user_manager): def _get_user_manager(): return user_manager return _get_user_manager
@pytest.fixture def get_user_manager(user_manager):
def _get_user_manager(): return user_manager return _get_user_manager
_manager(make_user_manager, mock_user_db): return make_user_manager(UserManager, mock_user_db) @pytest.fixture def user_manager_oauth(make_user_manager, mock_user_db_oauth): return make_user_manager(UserManagerOAuth, mock_user_db_oauth) @pytest.fixture def get_user_manager(user_manager):
64
64
29
10
54
chatalyan/fastapi-users
tests/conftest.py
Python
get_user_manager
get_user_manager
428
433
428
429
17fca332a71e072f6b23a7d64b25eeb28a9e9137
bigcode/the-stack
train
85604b8c9c8280591532b199
train
function
@pytest.fixture def oauth_account1() -> BaseOAuthAccount: return BaseOAuthAccount( oauth_name="service1", access_token="TOKEN", expires_at=1579000751, account_id="user_oauth1", account_email="king.arthur@camelot.bt", )
@pytest.fixture def oauth_account1() -> BaseOAuthAccount:
return BaseOAuthAccount( oauth_name="service1", access_token="TOKEN", expires_at=1579000751, account_id="user_oauth1", account_email="king.arthur@camelot.bt", )
-> UserDBOAuth: return UserDBOAuth( email="the.real.merlin@camelot.bt", hashed_password=viviane_password_hash, is_superuser=True, is_verified=True, oauth_accounts=[], ) @pytest.fixture def oauth_account1() -> BaseOAuthAccount:
64
64
65
13
51
chatalyan/fastapi-users
tests/conftest.py
Python
oauth_account1
oauth_account1
230
238
230
231
f8a62c790a413f8885cd742aad656fed77d12253
bigcode/the-stack
train
f347d86d02e901c6d76c68d6
train
function
@pytest.fixture def get_user_manager_oauth(user_manager_oauth): def _get_user_manager_oauth(): return user_manager_oauth return _get_user_manager_oauth
@pytest.fixture def get_user_manager_oauth(user_manager_oauth):
def _get_user_manager_oauth(): return user_manager_oauth return _get_user_manager_oauth
mock_user_db_oauth): return make_user_manager(UserManagerOAuth, mock_user_db_oauth) @pytest.fixture def get_user_manager(user_manager): def _get_user_manager(): return user_manager return _get_user_manager @pytest.fixture def get_user_manager_oauth(user_manager_oauth):
64
64
39
14
49
chatalyan/fastapi-users
tests/conftest.py
Python
get_user_manager_oauth
get_user_manager_oauth
436
441
436
437
65688408121d3ec174a8daf677dafec1a8497d4a
bigcode/the-stack
train
b115032264713a50157dae5e
train
function
def get_mock_authentication(name: str): return AuthenticationBackend( name=name, transport=MockTransport(tokenUrl="/login"), get_strategy=lambda: MockStrategy(), )
def get_mock_authentication(name: str):
return AuthenticationBackend( name=name, transport=MockTransport(tokenUrl="/login"), get_strategy=lambda: MockStrategy(), )
: return None return None async def write_token(self, user: models.UD) -> str: return str(user.id) async def destroy_token(self, token: str, user: models.UD) -> None: return None def get_mock_authentication(name: str):
64
64
38
9
54
chatalyan/fastapi-users
tests/conftest.py
Python
get_mock_authentication
get_mock_authentication
477
482
477
477
59a8b5f7ef3ebefc06196268096bd6e090bc99e2
bigcode/the-stack
train
e32734e021e276eaae7d5b68
train
function
@pytest.fixture def inactive_user() -> UserDB: return UserDB( email="percival@camelot.bt", hashed_password=angharad_password_hash, is_active=False, )
@pytest.fixture def inactive_user() -> UserDB:
return UserDB( email="percival@camelot.bt", hashed_password=angharad_password_hash, is_active=False, )
1, oauth_account2) -> UserDBOAuth: return UserDBOAuth( email="king.arthur@camelot.bt", hashed_password=guinevere_password_hash, oauth_accounts=[oauth_account1, oauth_account2], ) @pytest.fixture def inactive_user() -> UserDB:
64
64
43
11
53
chatalyan/fastapi-users
tests/conftest.py
Python
inactive_user
inactive_user
151
157
151
152
74e03dbe21a484996c0dadd27e64d9ac947487eb
bigcode/the-stack
train