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
5502acc3ced49c361d35a7b2
train
class
class TransformerBuild(Build): params:dict model:Model eval_model:Model train_model:Model epoch:Optional[int] filewriter:SummaryWriter tbcallback:TensorBoard subtokenizer:Subtokenizer
class TransformerBuild(Build):
params:dict model:Model eval_model:Model train_model:Model epoch:Optional[int] filewriter:SummaryWriter tbcallback:TensorBoard subtokenizer:Subtokenizer
.data import eval_ds, predict_ds from stagedml.types import ( WmtSubtok, TransWmt, Dict, Optional,Any,List,Tuple,Union ) from stagedml.stages.fetchwmt import create_subtokenizer from official.utils.flags._performance import DTYPE_MAP class TransformerBuild(Build):
64
64
56
5
58
stagedml/stagedml
src/stagedml/stages/transformer_wmt.py
Python
TransformerBuild
TransformerBuild
32
40
32
32
58f870c6c9db239d982cadda0985de2626b7097f
bigcode/the-stack
train
e29b9c3769ddd0d267fa9edb
train
function
def build(b:TransformerBuild, instance_idx:int)->None: c = build_cattrs(b) o = build_outpaths(b)[instance_idx] me = mklens(b,o) clear_session() compute_missing_params(b, instance_idx) set_session_config(enable_xla=c.enable_xla) b.train_model = create_train_model(c.params) b.train_model.compile(create_...
def build(b:TransformerBuild, instance_idx:int)->None:
c = build_cattrs(b) o = build_outpaths(b)[instance_idx] me = mklens(b,o) clear_session() compute_missing_params(b, instance_idx) set_session_config(enable_xla=c.enable_xla) b.train_model = create_train_model(c.params) b.train_model.compile(create_optimizer(c.params)) # b.train_model.summary() b.e...
.vocab_refpath.syspath) assert vocab_contents is not None c.params["vocab_size"] = len(vocab_contents.split('\n')) # print(f'Setting vocab_size to {c.params["vocab_size"]}') def build(b:TransformerBuild, instance_idx:int)->None:
63
64
176
13
50
stagedml/stagedml
src/stagedml/stages/transformer_wmt.py
Python
build
build
58
76
58
58
889353c44a882bd7bfc8ed7d7eeb36e01fc47a75
bigcode/the-stack
train
1198b5d20a06b9e8b03cada7
train
function
def transformer_wmt(m:Manager, wmt:WmtSubtok, num_instances:int=1)->TransWmt: train_steps = 300000 def _realize(b:TransformerBuild)->None: build_setoutpaths(b,num_instances) for instance_idx in range(num_instances): # print(f'Building Transformer instance {instance_idx+1} of {num_instances}') b...
def transformer_wmt(m:Manager, wmt:WmtSubtok, num_instances:int=1)->TransWmt:
train_steps = 300000 def _realize(b:TransformerBuild)->None: build_setoutpaths(b,num_instances) for instance_idx in range(num_instances): # print(f'Building Transformer instance {instance_idx+1} of {num_instances}') build(b,instance_idx) train(b,instance_idx) def _config(): name = ...
b.epoch < nepoches: history = b.train_model.fit( train_ds(c.params), initial_epoch=b.epoch, epochs=b.epoch+1, steps_per_epoch=c.steps_between_evals, callbacks=callbacks, verbose=True) ckpt = me.checkpoint_refpath.syspath print(f"Saving '{ckpt}'") b.train_model.save_...
136
136
456
26
109
stagedml/stagedml
src/stagedml/stages/transformer_wmt.py
Python
transformer_wmt
transformer_wmt
180
226
180
180
1def1654b730f0c103f0326bd611aca12fee9c64
bigcode/the-stack
train
2e5dde9fc9199409ba6f776c
train
function
def evaluate(b:TransformerBuild, instance_idx:int)->None: assert b.train_model is not None c = build_cattrs(b) me = mklens(b,o=build_outpaths(b)[instance_idx]) input_txt:Path=me.eval_input_refpath.syspath target_src_txt:Path=me.eval_target_refpath.syspath # print('Evaluating') epoch=b.epoch if b.epoch is ...
def evaluate(b:TransformerBuild, instance_idx:int)->None:
assert b.train_model is not None c = build_cattrs(b) me = mklens(b,o=build_outpaths(b)[instance_idx]) input_txt:Path=me.eval_input_refpath.syspath target_src_txt:Path=me.eval_target_refpath.syspath # print('Evaluating') epoch=b.epoch if b.epoch is not None else 0 ds = eval_ds(b.subtokenizer, ...
klens(b,o=build_outpaths(b)[instance_idx]) ckpt0 = me.checkpoint_init.val assert ckpt0 is not None b.train_model.load_weights(ckpt0) b.epoch = None def evaluate(b:TransformerBuild, instance_idx:int)->None:
64
64
198
13
50
stagedml/stagedml
src/stagedml/stages/transformer_wmt.py
Python
evaluate
evaluate
87
104
87
87
41e0c06d5c9034a43f2edf19c425a3fe1754bca4
bigcode/the-stack
train
f1099449138f0feaaa4c8a30
train
function
def predict(b:TransformerBuild, instance_idx:int)->None: assert b.eval_model is not None c = build_cattrs(b) o = build_outpaths(b)[instance_idx] me = mklens(b,o=o) input_txt:Path=me.eval_input_refpath.syspath target_src_txt:Path=me.eval_target_refpath.syspath target_txt=join(o,'targets.txt') epoch=b.epo...
def predict(b:TransformerBuild, instance_idx:int)->None:
assert b.eval_model is not None c = build_cattrs(b) o = build_outpaths(b)[instance_idx] me = mklens(b,o=o) input_txt:Path=me.eval_input_refpath.syspath target_src_txt:Path=me.eval_target_refpath.syspath target_txt=join(o,'targets.txt') epoch=b.epoch if b.epoch is not None else 0 output_txt:Path=Path(j...
spath # print('Evaluating') epoch=b.epoch if b.epoch is not None else 0 ds = eval_ds(b.subtokenizer, input_txt, target_src_txt, batch_size=me.eval_batch_size.val, params=me.params.val, take=me.eval_steps.val) h=b.train_model.evaluate(ds,...
137
137
459
13
124
stagedml/stagedml
src/stagedml/stages/transformer_wmt.py
Python
predict
predict
107
145
107
107
6d4bd9d22ba819a78a4e6f5a3ee475d80cf7e94d
bigcode/the-stack
train
ac9e837a227c0f3bf680f4ad
train
function
def compute_missing_params(b, instance_idx:int): c = build_cattrs(b) o = build_outpaths(b)[instance_idx] me = mklens(b,o) c.params["model_dir"] = o c.params["dtype"] = DTYPE_MAP[c.dtype] c.params["data_dir"] = me.data_dir.syspath vocab_contents = tryread(me.vocab_refpath.syspath) assert vocab_contents i...
def compute_missing_params(b, instance_idx:int):
c = build_cattrs(b) o = build_outpaths(b)[instance_idx] me = mklens(b,o) c.params["model_dir"] = o c.params["dtype"] = DTYPE_MAP[c.dtype] c.params["data_dir"] = me.data_dir.syspath vocab_contents = tryread(me.vocab_refpath.syspath) assert vocab_contents is not None c.params["vocab_size"] = len(vocab_c...
filewriter:SummaryWriter tbcallback:TensorBoard subtokenizer:Subtokenizer # def cont(b:TransformerBuild)->None: # copy_tree(rref2path(build_cattrs(b).continue_from),build_outpath(b)) def compute_missing_params(b, instance_idx:int):
64
64
114
10
54
stagedml/stagedml
src/stagedml/stages/transformer_wmt.py
Python
compute_missing_params
compute_missing_params
45
54
45
45
93b557e7c28daddbfad67dbad6bebb67d0ffb97f
bigcode/the-stack
train
16025ea6ec9d8a3263a93775
train
function
def loadcp(b:TransformerBuild, instance_idx): me = mklens(b,o=build_outpaths(b)[instance_idx]) ckpt0 = me.checkpoint_init.val assert ckpt0 is not None b.train_model.load_weights(ckpt0) b.epoch = None
def loadcp(b:TransformerBuild, instance_idx):
me = mklens(b,o=build_outpaths(b)[instance_idx]) ckpt0 = me.checkpoint_init.val assert ckpt0 is not None b.train_model.load_weights(ckpt0) b.epoch = None
= create_file_writer(join(o,'eval')) b.tbcallback = TensorBoard(log_dir=o, profile_batch=0, write_graph=False) b.subtokenizer = create_subtokenizer(WmtSubtok(me.wmt.dref), build_context(b)) def loadcp(b:TransformerBuild, instance_idx):
64
64
66
11
53
stagedml/stagedml
src/stagedml/stages/transformer_wmt.py
Python
loadcp
loadcp
79
84
79
79
c30a4bf55d80ea797b39ff80da90366eaee03b45
bigcode/the-stack
train
08c256fb52d35932295789cf
train
function
def train(b:TransformerBuild, instance_idx:int=0): assert b.train_model is not None c = build_cattrs(b) o = build_outpaths(b)[instance_idx] me = mklens(b,o) callbacks = [ b.tbcallback, LearningRateScheduler( LearningRateFn(c.params["learning_rate"], c.params["hidden_size...
def train(b:TransformerBuild, instance_idx:int=0):
assert b.train_model is not None c = build_cattrs(b) o = build_outpaths(b)[instance_idx] me = mklens(b,o) callbacks = [ b.tbcallback, LearningRateScheduler( LearningRateFn(c.params["learning_rate"], c.params["hidden_size"], c.params["learning_rate_...
step=epoch) tf.summary.scalar('bleu_uncased',bleu_uncased,step=epoch) with open(me.bleu_refpath.syspath,'w') as f: f.write(f"{(bleu_cased + bleu_uncased)/2.0}\n") def train(b:TransformerBuild, instance_idx:int=0):
74
74
249
13
61
stagedml/stagedml
src/stagedml/stages/transformer_wmt.py
Python
train
train
148
177
148
148
32ce7a807f5ae11f191f291fe102582285678cdf
bigcode/the-stack
train
67445fa991aee1fa6045467c
train
class
class ID3NoHeaderError(error, ValueError): pass
class ID3NoHeaderError(error, ValueError):
pass
Christoph Reiter # # This program is free software; you can redistribute it and/or modify # it under the terms of version 2 of the GNU General Public License as # published by the Free Software Foundation. class error(Exception): pass class ID3NoHeaderError(error, ValueError):
64
64
14
11
52
Jianwei-Wang/python2.7_lib
dist-packages/mutagen/_id3util.py
Python
ID3NoHeaderError
ID3NoHeaderError
13
14
13
13
ced21196c4f63f1ff59a2976068c6a0e72b80327
bigcode/the-stack
train
5a5a69a2561725ac278b5512
train
class
class ID3BadCompressedData(error, ValueError): pass
class ID3BadCompressedData(error, ValueError):
pass
2 of the GNU General Public License as # published by the Free Software Foundation. class error(Exception): pass class ID3NoHeaderError(error, ValueError): pass class ID3BadUnsynchData(error, ValueError): pass class ID3BadCompressedData(error, ValueError):
64
64
14
11
52
Jianwei-Wang/python2.7_lib
dist-packages/mutagen/_id3util.py
Python
ID3BadCompressedData
ID3BadCompressedData
21
22
21
21
17c4c589e07cf02e869fc8b9d72f00773664c74c
bigcode/the-stack
train
86e95c896b1ec673a23277df
train
class
class BitPaddedInt(int, _BitPaddedMixin): def __new__(cls, value, bits=7, bigendian=True): mask = (1 << (bits)) - 1 numeric_value = 0 shift = 0 if isinstance(value, (int, long)): while value: numeric_value += (value & mask) << shift valu...
class BitPaddedInt(int, _BitPaddedMixin):
def __new__(cls, value, bits=7, bigendian=True): mask = (1 << (bits)) - 1 numeric_value = 0 shift = 0 if isinstance(value, (int, long)): while value: numeric_value += (value & mask) << shift value >>= 8 shift += bits ...
value & mask: return False value >>= 8 elif isinstance(value, str): for byte in value: if ord(byte) & mask: return False else: raise TypeError return True class BitPaddedInt(int, _BitPaddedMixin):
64
64
208
13
50
Jianwei-Wang/python2.7_lib
dist-packages/mutagen/_id3util.py
Python
BitPaddedInt
BitPaddedInt
143
172
143
144
a539c5782da96562caf7a089c73d38c17cc15de9
bigcode/the-stack
train
cd656615320d70b33c66005f
train
class
class ID3EncryptionUnsupportedError(error, NotImplementedError): pass
class ID3EncryptionUnsupportedError(error, NotImplementedError):
pass
ynchData(error, ValueError): pass class ID3BadCompressedData(error, ValueError): pass class ID3TagError(error, ValueError): pass class ID3UnsupportedVersionError(error, NotImplementedError): pass class ID3EncryptionUnsupportedError(error, NotImplementedError):
64
64
15
12
51
Jianwei-Wang/python2.7_lib
dist-packages/mutagen/_id3util.py
Python
ID3EncryptionUnsupportedError
ID3EncryptionUnsupportedError
33
34
33
33
f7d9e5f84b8f97a0101a856b95c3abe24e194356
bigcode/the-stack
train
9896e27b0b7fddbcce3108ba
train
class
class ID3TagError(error, ValueError): pass
class ID3TagError(error, ValueError):
pass
Free Software Foundation. class error(Exception): pass class ID3NoHeaderError(error, ValueError): pass class ID3BadUnsynchData(error, ValueError): pass class ID3BadCompressedData(error, ValueError): pass class ID3TagError(error, ValueError):
64
64
13
10
53
Jianwei-Wang/python2.7_lib
dist-packages/mutagen/_id3util.py
Python
ID3TagError
ID3TagError
25
26
25
25
9cab8b9cd13e0e4567923a9dda0b6a9c31279913
bigcode/the-stack
train
a1d09558dc80c7b506353782
train
class
class ID3JunkFrameError(error, ValueError): pass
class ID3JunkFrameError(error, ValueError):
pass
Data(error, ValueError): pass class ID3TagError(error, ValueError): pass class ID3UnsupportedVersionError(error, NotImplementedError): pass class ID3EncryptionUnsupportedError(error, NotImplementedError): pass class ID3JunkFrameError(error, ValueError):
64
64
15
12
51
Jianwei-Wang/python2.7_lib
dist-packages/mutagen/_id3util.py
Python
ID3JunkFrameError
ID3JunkFrameError
37
38
37
37
1db1a6303b5757354238e33634198c47ff8e1a32
bigcode/the-stack
train
8a8e789b698795a5758687ed
train
class
class error(Exception): pass
class error(Exception):
pass
) 2005 Michael Urman # 2013 Christoph Reiter # # This program is free software; you can redistribute it and/or modify # it under the terms of version 2 of the GNU General Public License as # published by the Free Software Foundation. class error(Exception):
64
64
7
4
60
Jianwei-Wang/python2.7_lib
dist-packages/mutagen/_id3util.py
Python
error
error
9
10
9
9
1d7ff5edbc7d9e7d9e9055f6cab0637fb51786c0
bigcode/the-stack
train
4640a8ca6c09ee759b781ca2
train
class
class unsynch(object): @staticmethod def decode(value): output = [] safe = True append = output.append for val in value: if safe: append(val) safe = val != '\xFF' else: if val >= '\xE0': r...
class unsynch(object): @staticmethod
def decode(value): output = [] safe = True append = output.append for val in value: if safe: append(val) safe = val != '\xFF' else: if val >= '\xE0': raise ValueError('invalid sync-safe string...
class ID3UnsupportedVersionError(error, NotImplementedError): pass class ID3EncryptionUnsupportedError(error, NotImplementedError): pass class ID3JunkFrameError(error, ValueError): pass class ID3Warning(error, UserWarning): pass class unsynch(object): @staticmethod
67
67
226
9
57
Jianwei-Wang/python2.7_lib
dist-packages/mutagen/_id3util.py
Python
unsynch
unsynch
45
84
45
46
74e62a8b7dcd02d1e9b8622cd571cea92adfe86b
bigcode/the-stack
train
1e44e6787e9e77ddd45b5283
train
class
class ID3Warning(error, UserWarning): pass
class ID3Warning(error, UserWarning):
pass
TagError(error, ValueError): pass class ID3UnsupportedVersionError(error, NotImplementedError): pass class ID3EncryptionUnsupportedError(error, NotImplementedError): pass class ID3JunkFrameError(error, ValueError): pass class ID3Warning(error, UserWarning):
64
64
12
9
54
Jianwei-Wang/python2.7_lib
dist-packages/mutagen/_id3util.py
Python
ID3Warning
ID3Warning
41
42
41
41
682c76ddc229c288fdf8c1fbbd2504e1ae744509
bigcode/the-stack
train
314bf9fb6583638d4baa94d2
train
class
class _BitPaddedMixin(object): def as_str(self, width=4, minwidth=4): return self.to_str(self, self.bits, self.bigendian, width, minwidth) @staticmethod def to_str(value, bits=7, bigendian=True, width=4, minwidth=4): mask = (1 << bits) - 1 if width != -1: index = 0 ...
class _BitPaddedMixin(object):
def as_str(self, width=4, minwidth=4): return self.to_str(self, self.bits, self.bigendian, width, minwidth) @staticmethod def to_str(value, bits=7, bigendian=True, width=4, minwidth=4): mask = (1 << bits) - 1 if width != -1: index = 0 bytes_ = bytearray(widt...
= True append = output.append for val in value: if safe: append(val) if val == '\xFF': safe = False elif val == '\x00' or val >= '\xE0': append('\x00') append(val) safe = val != '...
108
108
360
8
100
Jianwei-Wang/python2.7_lib
dist-packages/mutagen/_id3util.py
Python
_BitPaddedMixin
_BitPaddedMixin
87
140
87
88
f664b89b20d4675b7497cd45316880208b1ffa2b
bigcode/the-stack
train
3c91c0e059d19e7dfcfef7b8
train
class
class ID3BadUnsynchData(error, ValueError): pass
class ID3BadUnsynchData(error, ValueError):
pass
redistribute it and/or modify # it under the terms of version 2 of the GNU General Public License as # published by the Free Software Foundation. class error(Exception): pass class ID3NoHeaderError(error, ValueError): pass class ID3BadUnsynchData(error, ValueError):
64
64
15
12
51
Jianwei-Wang/python2.7_lib
dist-packages/mutagen/_id3util.py
Python
ID3BadUnsynchData
ID3BadUnsynchData
17
18
17
17
de1247f47549b956d3e8c9440b703e9287d060a1
bigcode/the-stack
train
3f44727fedc25dcc8a4ceb4d
train
class
class BitPaddedLong(long, _BitPaddedMixin): pass
class BitPaddedLong(long, _BitPaddedMixin):
pass
= long.__new__(BitPaddedLong, numeric_value) else: self = int.__new__(BitPaddedInt, numeric_value) self.bits = bits self.bigendian = bigendian return self class BitPaddedLong(long, _BitPaddedMixin):
64
64
16
13
50
Jianwei-Wang/python2.7_lib
dist-packages/mutagen/_id3util.py
Python
BitPaddedLong
BitPaddedLong
175
176
175
175
5f3057f32b01410b614211afbc5642ed670b3c4f
bigcode/the-stack
train
47986c6e17f2f64e908f79f4
train
class
class ID3UnsupportedVersionError(error, NotImplementedError): pass
class ID3UnsupportedVersionError(error, NotImplementedError):
pass
HeaderError(error, ValueError): pass class ID3BadUnsynchData(error, ValueError): pass class ID3BadCompressedData(error, ValueError): pass class ID3TagError(error, ValueError): pass class ID3UnsupportedVersionError(error, NotImplementedError):
64
64
15
12
51
Jianwei-Wang/python2.7_lib
dist-packages/mutagen/_id3util.py
Python
ID3UnsupportedVersionError
ID3UnsupportedVersionError
29
30
29
29
016cdb4b352abc5503b34345d188868c7e04646e
bigcode/the-stack
train
bf57e5c8733c4ab0988cb152
train
function
def entry_point(): """Zero-argument entry point for use with setuptools/distribute.""" raise SystemExit(main(sys.argv))
def entry_point():
"""Zero-argument entry point for use with setuptools/distribute.""" raise SystemExit(main(sys.argv))
#!/usr/bin/env /usr/bin/python3 import sys from luxon.core.handlers.cmd import Cmd import tradius.cmd def main(argv): tradius = Cmd('tradius', path='/tmp') tradius() def entry_point():
52
64
26
4
48
Vuader/tradius
tradius/main.py
Python
entry_point
entry_point
11
13
11
11
1af93eb768bfe8148f0c26db43bba44ac2b60554
bigcode/the-stack
train
e57af44a2bf71f6754c8a2f8
train
function
def main(argv): tradius = Cmd('tradius', path='/tmp') tradius()
def main(argv):
tradius = Cmd('tradius', path='/tmp') tradius()
#!/usr/bin/env /usr/bin/python3 import sys from luxon.core.handlers.cmd import Cmd import tradius.cmd def main(argv):
31
64
21
4
26
Vuader/tradius
tradius/main.py
Python
main
main
7
9
7
7
879caf34653a102b2b2209697d47b394859299af
bigcode/the-stack
train
03cbaac7db70b8e54ad7aff9
train
class
class Player(object): def __init__(self): self.name = None self.results = dict() self.rolls = [] self.scores = dict() # # set pins scores for a frame. # def set_result(self, frame, result): self.results[frame] = result def calculate_score(...
class Player(object):
def __init__(self): self.name = None self.results = dict() self.rolls = [] self.scores = dict() # # set pins scores for a frame. # def set_result(self, frame, result): self.results[frame] = result def calculate_score(self): running...
class Player(object):
4
83
278
4
0
ask5/bowling
player.py
Python
Player
Player
2
35
2
2
83a17262372d4b6d298b3ab8eff7a4ac799b4bd4
bigcode/the-stack
train
e20a17b2d05c43881ad777ad
train
function
def search(code: str): log = [] # DNA SEQUENCE log.append('-'.join(splitThree(code))) # tRNA SEQUENCE swapped = '' for i in code: swapped += swap(i, False) log.append('-'.join(splitThree(swapped))) # RNA SEQUENCE swapped = '' for i in code: swapped += swap(i, True) log.append('-'.join(splitThree(swa...
def search(code: str):
log = [] # DNA SEQUENCE log.append('-'.join(splitThree(code))) # tRNA SEQUENCE swapped = '' for i in code: swapped += swap(i, False) log.append('-'.join(splitThree(swapped))) # RNA SEQUENCE swapped = '' for i in code: swapped += swap(i, True) log.append('-'.join(splitThree(swapped))) # HIDDEN MESS...
t': return 'u' return value # Split string into array of strings for every 3 letters def splitThree(str: str): n = 3 arr = [str[i:i+n] for i in range(0, len(str), n)] return arr def search(code: str):
64
64
215
6
57
TenType/dna-decoder
main.py
Python
search
search
17
59
17
17
b8a470a90a7a9ae10d05ecf11a7823b83c797922
bigcode/the-stack
train
3996e37cc72150bc60344395
train
function
def splitThree(str: str): n = 3 arr = [str[i:i+n] for i in range(0, len(str), n)] return arr
def splitThree(str: str):
n = 3 arr = [str[i:i+n] for i in range(0, len(str), n)] return arr
inputs import inputs # Swap pairs def swap(letter: str, rna: bool): value = bases[letter] if rna is True and value == 't': return 'u' return value # Split string into array of strings for every 3 letters def splitThree(str: str):
64
64
35
7
56
TenType/dna-decoder
main.py
Python
splitThree
splitThree
12
15
12
12
ecadc39185cfcf7762941c2c9fc07ec54c95e037
bigcode/the-stack
train
5610d8134f508c9e56a35062
train
function
def swap(letter: str, rna: bool): value = bases[letter] if rna is True and value == 't': return 'u' return value
def swap(letter: str, rna: bool):
value = bases[letter] if rna is True and value == 't': return 'u' return value
from data import bases, decoderKey, acids from inputs import inputs # Swap pairs def swap(letter: str, rna: bool):
30
64
36
11
18
TenType/dna-decoder
main.py
Python
swap
swap
5
9
5
5
5330255b969ec2bb646dbf7d7251f88ef6e1f2fd
bigcode/the-stack
train
f5717b900934be6f981567a3
train
class
class Order(models.Model): order_date = models.DateField(null=False) shipped_date = models.DateField(null=True) delivered_date = models.DateField(null=True) coupon_code = models.CharField(max_length=50, null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=False) produ...
class Order(models.Model):
order_date = models.DateField(null=False) shipped_date = models.DateField(null=True) delivered_date = models.DateField(null=True) coupon_code = models.CharField(max_length=50, null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=False) products = models.ManyToManyFiel...
models.CharField(max_length=50, null=False) email = models.CharField(max_length=50, null=False, unique=True) class Product(models.Model): name = models.CharField(max_length=50, null=False, unique=True) price = models.IntegerField(null=False) class Order(models.Model):
64
64
81
5
59
Ujjawal-Rajput/yes
2021/07/28/How to Use Select Related and Prefetch Related in Django/django_related/related_example/example/models.py
Python
Order
Order
15
21
15
15
baa3cd0f55bb37294dd9c49afad69010f5e80870
bigcode/the-stack
train
1809ddf39d53cfbe43a8aa63
train
class
class Product(models.Model): name = models.CharField(max_length=50, null=False, unique=True) price = models.IntegerField(null=False)
class Product(models.Model):
name = models.CharField(max_length=50, null=False, unique=True) price = models.IntegerField(null=False)
address = models.CharField(max_length=500, null=False) city = models.CharField(max_length=50, null=False) postcode = models.CharField(max_length=50, null=False) email = models.CharField(max_length=50, null=False, unique=True) class Product(models.Model):
64
64
31
5
59
Ujjawal-Rajput/yes
2021/07/28/How to Use Select Related and Prefetch Related in Django/django_related/related_example/example/models.py
Python
Product
Product
11
13
11
11
60f749443936703aac3b50a1cd72c0115587ccf3
bigcode/the-stack
train
ec88dbaf9952e7aebf71d8f4
train
class
class LineItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, null=False) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=False) quantity = models.IntegerField(null=False)
class LineItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE, null=False) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=False) quantity = models.IntegerField(null=False)
=True) delivered_date = models.DateField(null=True) coupon_code = models.CharField(max_length=50, null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=False) products = models.ManyToManyField(Product, through='LineItem') class LineItem(models.Model):
64
64
47
6
58
Ujjawal-Rajput/yes
2021/07/28/How to Use Select Related and Prefetch Related in Django/django_related/related_example/example/models.py
Python
LineItem
LineItem
23
26
23
23
b09babe3a69dbe8063708954afa246527a5005b2
bigcode/the-stack
train
34dbdd896a2d45a733001f15
train
class
class Customer(models.Model): first_name = models.CharField(max_length=50, null=False) last_name = models.CharField(max_length=50, null=False) address = models.CharField(max_length=500, null=False) city = models.CharField(max_length=50, null=False) postcode = models.CharField(max_length=50, null=Fal...
class Customer(models.Model):
first_name = models.CharField(max_length=50, null=False) last_name = models.CharField(max_length=50, null=False) address = models.CharField(max_length=500, null=False) city = models.CharField(max_length=50, null=False) postcode = models.CharField(max_length=50, null=False) email = models.CharFie...
from django.db import models class Customer(models.Model):
11
64
94
5
5
Ujjawal-Rajput/yes
2021/07/28/How to Use Select Related and Prefetch Related in Django/django_related/related_example/example/models.py
Python
Customer
Customer
3
9
3
3
d28d7e2234fb4aed6fcb2e7634dbf80d0954eef3
bigcode/the-stack
train
b8257170e2f75afe1db7ead7
train
class
class PassaroVermelho(Passaro): _caracter_ativo = 'V' _caracter_destruido = 'v' velocidade_escalar = 20
class PassaroVermelho(Passaro):
_caracter_ativo = 'V' _caracter_destruido = 'v' velocidade_escalar = 20
return self.foi_lancado() and self.status == ATIVO class PassaroAmarelo(Passaro): _caracter_ativo = 'A' _caracter_destruido = 'a' velocidade_escalar = 30 class PassaroVermelho(Passaro):
64
64
39
10
53
Arthurregismais/pythonbirds
atores.py
Python
PassaroVermelho
PassaroVermelho
175
178
175
175
2f47f399c95ae5055dd10551a02a01de562de3ac
bigcode/the-stack
train
a403651ac0de12be14ab0aab
train
class
class Ator(): """ Classe que representa um ator. Ele representa um ponto cartesiano na tela. """ _caracter_ativo = 'A' _caracter_destruido = ' ' def __init__(self, x=0, y=0): """ Método de inicialização da classe. Deve inicializar os parâmetros x, y, caracter e status :...
class Ator():
""" Classe que representa um ator. Ele representa um ponto cartesiano na tela. """ _caracter_ativo = 'A' _caracter_destruido = ' ' def __init__(self, x=0, y=0): """ Método de inicialização da classe. Deve inicializar os parâmetros x, y, caracter e status :param x: Posiç...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math DESTRUIDO = 'Destruido' ATIVO = 'Ativo' GRAVIDADE = 10 # m/s^2 class Ator():
53
132
443
4
48
Arthurregismais/pythonbirds
atores.py
Python
Ator
Ator
12
60
12
12
95457413a3834091bb842b2bd6c80cdee550178d
bigcode/the-stack
train
8eb1d19d783195b90a8250e8
train
class
class Obstaculo(Ator): _caracter_ativo = 'O' _caracter_destruido = ' '
class Obstaculo(Ator):
_caracter_ativo = 'O' _caracter_destruido = ' '
_x = abs(self.x - outro_ator.x) delta_y = abs(self.y - outro_ator.y) if delta_x <= intervalo and delta_y <= intervalo: self.status = DESTRUIDO outro_ator.status = DESTRUIDO class Obstaculo(Ator):
64
64
28
8
55
Arthurregismais/pythonbirds
atores.py
Python
Obstaculo
Obstaculo
64
66
64
64
4ab6ebf7afbe3c1065e7ea310dfdda7c95682693
bigcode/the-stack
train
bd0a4af0597bbb7f6f24c087
train
class
class Passaro(Ator): velocidade_escalar = 10 def __init__(self, x=0, y=0): """ Método de inicialização de pássaro. Deve chamar a inicialização de ator. Além disso, deve armazenar a posição inicial e incializar o tempo de lançamento e angulo de lançamento :param x: ...
class Passaro(Ator):
velocidade_escalar = 10 def __init__(self, x=0, y=0): """ Método de inicialização de pássaro. Deve chamar a inicialização de ator. Além disso, deve armazenar a posição inicial e incializar o tempo de lançamento e angulo de lançamento :param x: :param y: ...
igual ao parâmetro intervalo, em volta do ponto onde se encontra o ator. Se os atores estiverem dentro desse mesmo quadrado, seus status devem ser alterados para destruido, seus caracteres para destruido também. :param outro_ator: Ator a ser considerado na colisão :param intervalo: Int...
230
230
767
7
222
Arthurregismais/pythonbirds
atores.py
Python
Passaro
Passaro
79
166
79
79
c20a93c02c9d2a0256237a7b6329dc4cdd866a26
bigcode/the-stack
train
c7b05a4bf41fc0a3410bbf69
train
class
class Porco(Ator): _caracter_ativo = '@' _caracter_destruido = '+'
class Porco(Ator):
_caracter_ativo = '@' _caracter_destruido = '+'
<= intervalo and delta_y <= intervalo: self.status = DESTRUIDO outro_ator.status = DESTRUIDO class Obstaculo(Ator): _caracter_ativo = 'O' _caracter_destruido = ' ' class Porco(Ator):
63
64
26
7
56
Arthurregismais/pythonbirds
atores.py
Python
Porco
Porco
70
72
70
70
31598e5a246e4bb9cd7c2971be49c25792558cac
bigcode/the-stack
train
ff5fd2385f172212e5b6fa8d
train
class
class PassaroAmarelo(Passaro): _caracter_ativo = 'A' _caracter_destruido = 'a' velocidade_escalar = 30
class PassaroAmarelo(Passaro):
_caracter_ativo = 'A' _caracter_destruido = 'a' velocidade_escalar = 30
x_atual += self.velocidade_escalar * delta_t * math.cos(angulo_radianos) self.x = x_atual def _esta_voando(self): return self.foi_lancado() and self.status == ATIVO class PassaroAmarelo(Passaro):
64
64
39
10
53
Arthurregismais/pythonbirds
atores.py
Python
PassaroAmarelo
PassaroAmarelo
169
172
169
169
feab6c1a7cc47872daf214d3141787871e0a3db0
bigcode/the-stack
train
281ad7ddd70c6b8e20094c90
train
class
class DuploLancamentoExcecao(Exception): pass
class DuploLancamentoExcecao(Exception):
pass
Obstaculo(Ator): _caracter_ativo = 'O' _caracter_destruido = ' ' class Porco(Ator): _caracter_ativo = '@' _caracter_destruido = '+' class DuploLancamentoExcecao(Exception):
64
64
13
10
53
Arthurregismais/pythonbirds
atores.py
Python
DuploLancamentoExcecao
DuploLancamentoExcecao
75
76
75
75
7e4a1496f7347bf8b7e97b659c0bc76665283bd9
bigcode/the-stack
train
84d87e7438a2137715810be7
train
function
@event('plugin.register') def register_plugin(): plugin.register(TorrentFiles, 'torrent_files', builtin=True, api_ver=2)
@event('plugin.register') def register_plugin():
plugin.register(TorrentFiles, 'torrent_files', builtin=True, api_ver=2)
.join(item['path'], item['name']) for item in entry['torrent'].get_filelist() ] if files: log.debug('%s files: %s' % (entry['title'], files)) entry['content_files'] = files @event('plugin.register') def register_plugin():
64
64
29
10
53
guillaumelamirand/Flexget
flexget/components/bittorrent/torrent_files.py
Python
register_plugin
register_plugin
26
28
26
27
f8c38c4a0dccf3c03f6357028c2319a357278f07
bigcode/the-stack
train
dbbd98fdf14828a9e65da4aa
train
class
class TorrentFiles: """Provides content files information when dealing with torrents.""" @plugin.priority(200) def on_task_modify(self, task, config): for entry in task.entries: if 'torrent' in entry: files = [ posixpath.join(item['path'], item['name'...
class TorrentFiles:
"""Provides content files information when dealing with torrents.""" @plugin.priority(200) def on_task_modify(self, task, config): for entry in task.entries: if 'torrent' in entry: files = [ posixpath.join(item['path'], item['name']) ...
import logging import posixpath from flexget import plugin from flexget.event import event log = logging.getLogger('torrent_files') class TorrentFiles:
34
64
110
4
30
guillaumelamirand/Flexget
flexget/components/bittorrent/torrent_files.py
Python
TorrentFiles
TorrentFiles
10
23
10
10
9034c55b9c2e975dc9189d8d1e0ed93d9ad82b5e
bigcode/the-stack
train
2c8e1e3f7e7fe393bf988067
train
function
def f(x): return np.sin(2*x*math.pi)
def f(x):
return np.sin(2*x*math.pi)
import numpy as np import matplotlib.pyplot as plt import math from sklearn.linear_model import Ridge, RidgeCV from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import make_pipeline from sklearn.metrics import mean_squared_error def f(x):
50
64
15
4
45
him1411/machine-learning-assignments
assignment1/task4-3.py
Python
f
f
10
11
10
10
412157ff9378e7c6f1ac267abff9ea6198033891
bigcode/the-stack
train
28eed04a84371e8698d68cb9
train
class
class SynonymMapsOperations: """SynonymMapsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :typ...
class SynonymMapsOperations:
"""SynonymMapsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.search.docum...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
246
256
3,201
6
240
praveenkuttappan/azure-sdk-for-python
sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_synonym_maps_operations.py
Python
SynonymMapsOperations
SynonymMapsOperations
25
363
25
25
f577b11aebc6c3d2aa02e2a5cd53baaeff2afbd4
bigcode/the-stack
train
575ef27cefe311678b62ce8a
train
function
def provide_trigger_dict(): """Provide a dictionnary mapping str names to byte values.""" trigger_dict = OrderedDict() # At the beginning and end of the experiment ... take these triggers to # crop the meaningful EEG data. Make sure to include some time BEFORE and # AFTER the triggers so that filte...
def provide_trigger_dict():
"""Provide a dictionnary mapping str names to byte values.""" trigger_dict = OrderedDict() # At the beginning and end of the experiment ... take these triggers to # crop the meaningful EEG data. Make sure to include some time BEFORE and # AFTER the triggers so that filtering does not introduce arti...
"""Definitions for the TTL triggers to be sent. main file: sp.py For more information, see also the "event_value" key within the define_variable_meanings.make_events_json_dict. """ from collections import OrderedDict def provide_trigger_dict():
52
180
601
5
46
sappelhoff/sp_psychopy
sp_experiment/define_ttl_triggers.py
Python
provide_trigger_dict
provide_trigger_dict
12
70
12
12
21a434d747d1c9fc47fb7242a8f56ae107670930
bigcode/the-stack
train
f028aa66a50559714c75cb79
train
function
def optimize(fn=None, *, data=None): if fn is None: return partial(optimize, data=data) return Optimizer(fn, data)
def optimize(fn=None, *, data=None):
if fn is None: return partial(optimize, data=data) return Optimizer(fn, data)
joblib.load(self.model_path) else: self.model_ = self.optimize() predicted_probas = self.model_.predict_proba(X) if as_proba: return predicted_probas[0, 1] return predicted_probas.argmax() def optimize(fn=None, *, data=None):
64
64
32
9
55
cosmicBboy/software20
software20/optimizers.py
Python
optimize
optimize
109
112
109
109
5182e4b97868a65e6b0c30d9de78a497bc4449c9
bigcode/the-stack
train
4868e7ba1edec36a609fe6ff
train
class
class Optimizer: def __init__(self, opt_fn, data=None, batch_size=3, test_size=0.2): self._opt_fn = opt_fn self._data = data self._batch_size = batch_size self._test_size = test_size self.model_ = None self.model_dir = Path(os.path.dirname(self.module.__file__)) / "m...
class Optimizer:
def __init__(self, opt_fn, data=None, batch_size=3, test_size=0.2): self._opt_fn = opt_fn self._data = data self._batch_size = batch_size self._test_size = test_size self.model_ = None self.model_dir = Path(os.path.dirname(self.module.__file__)) / "models" sel...
"""Optimizer decorators.""" import importlib import os from functools import partial from pathlib import Path from typing import Any import pandas as pd import numpy as np import joblib from sklearn.metrics import SCORERS from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import...
98
196
654
4
93
cosmicBboy/software20
software20/optimizers.py
Python
Optimizer
Optimizer
20
106
20
21
fe0b98e6ea79022a83eaa9db5d34d4801c9306de
bigcode/the-stack
train
7bcd9af5bbe9d67bb5e3c3aa
train
class
class TestDialign(unittest.TestCase): def setUp(self): aln_seqs = { "HTL2": "ldtapC-LFSDGS------PQKAAYVL-------WDQTILQQDITPLPSHethSAQKGELLALICGLRAak------------", "MMLV": "pdadhtw-YTDGSSLLQEGQRKAGAAVtteteviWa----KALDAG---T---SAQRAELIALTQALKm--------------", "HEPB": "rpgl-...
class TestDialign(unittest.TestCase):
def setUp(self): aln_seqs = { "HTL2": "ldtapC-LFSDGS------PQKAAYVL-------WDQTILQQDITPLPSHethSAQKGELLALICGLRAak------------", "MMLV": "pdadhtw-YTDGSSLLQEGQRKAGAAVtteteviWa----KALDAG---T---SAQRAELIALTQALKm--------------", "HEPB": "rpgl-CQVFADAT------PTGWGLVM-------GHQRMRGTF...
43 ---SAQRAEL IALTQALKm- ---------- --- HEPB 37 t------AEL LAA-CFARSr sganiigtdn svv ECOL 43 ---TNNRMEL MAAIv----- ---------- --- 0003333455 5533333300 0000000000 000 Sequence tree: ============== Tree constructed using UPGMAbased on D...
163
163
546
8
155
rahulghangas/cogent3
tests/test_parse/test_dialign.py
Python
TestDialign
TestDialign
90
128
90
90
6ac9d43d4d68a266f38cecf2e999b8c139a7f7a9
bigcode/the-stack
train
27b8411835bc52338d019754
train
class
class Api: """ Api class Class to deal with the foreman API v2 """ maxHistory = 16 def __init__(self, password, login='admin', ip='127.0.0.1', printErrors=False, ca_cert=None): """ Function __init__ Init the API with the connection params @param passwor...
class Api:
""" Api class Class to deal with the foreman API v2 """ maxHistory = 16 def __init__(self, password, login='admin', ip='127.0.0.1', printErrors=False, ca_cert=None): """ Function __init__ Init the API with the connection params @param password: authenti...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
202
256
1,780
3
198
ckxng/foreman
foreman/api.py
Python
Api
Api
25
250
25
25
0f623f11f786563b3f6a320513ed0ab18a92cbd1
bigcode/the-stack
train
1d5797b0d99086e9d104df42
train
function
def rename_and_move(folder_name, file_name): print(file_name) return folder_name.replace("ui/", "ui_generated/"), "ui_" + file_name
def rename_and_move(folder_name, file_name):
print(file_name) return folder_name.replace("ui/", "ui_generated/"), "ui_" + file_name
from PyQt5 import uic def rename_and_move(folder_name, file_name):
18
64
35
10
7
LLNL/RASE
build-ui.py
Python
rename_and_move
rename_and_move
4
6
4
4
67592970687694bff14914bef6a4263616539313
bigcode/the-stack
train
d2c58881ebc8a4a2d1beabfe
train
function
def download_energy(out_dir): energy_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/00242/ENB2012_data.xlsx" with tempfile.TemporaryDirectory() as tmp_dir: energy_file = os.path.join(tmp_dir, 'energy.xlsx') r = requests.get(energy_url, allow_redirects=True) with open(en...
def download_energy(out_dir):
energy_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/00242/ENB2012_data.xlsx" with tempfile.TemporaryDirectory() as tmp_dir: energy_file = os.path.join(tmp_dir, 'energy.xlsx') r = requests.get(energy_url, allow_redirects=True) with open(energy_file, 'wb') as fh: ...
(506, 1) boston_hdf_file = os.path.join(out_dir, 'boston.hdf5') with h5py.File(boston_hdf_file, 'w') as hf: hf.create_dataset("X", data=X, dtype=np.float64, compression='gzip') hf.create_dataset("Y", data=Y, dtype=np.float64, compression='gzip') def download_energy(out_dir):
89
89
298
6
83
mohamad-amin/falkon
notebooks/uci_datasets_download.py
Python
download_energy
download_energy
51
70
51
51
e4705553444c947ddd77fefedb77490ad90fc9f9
bigcode/the-stack
train
063103d5c28825fce6de9fe0
train
function
def download_boston(out_dir): boston_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data" with tempfile.TemporaryDirectory() as tmp_dir: boston_file = os.path.join(tmp_dir, 'boston.tsv') r = requests.get(boston_url, allow_redirects=True) with open(boston...
def download_boston(out_dir):
boston_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data" with tempfile.TemporaryDirectory() as tmp_dir: boston_file = os.path.join(tmp_dir, 'boston.tsv') r = requests.get(boston_url, allow_redirects=True) with open(boston_file, 'wb') as fh: ...
os.path.join(out_dir, 'protein.hdf5') with h5py.File(protein_hdf_file, 'w') as hf: hf.create_dataset("X", data=X, dtype=np.float64, compression='gzip') hf.create_dataset("Y", data=Y, dtype=np.float64, compression='gzip') def download_boston(out_dir):
76
76
256
7
69
mohamad-amin/falkon
notebooks/uci_datasets_download.py
Python
download_boston
download_boston
31
48
31
31
191a1ffaf5b2854a3f99b8877af967dbd6c76647
bigcode/the-stack
train
cd368feed5b4645b6efa35c9
train
function
def download_kin40k(out_dir): """ Data is impossible to find from reputable sources. Delve repository does not have 40k points (only 8192). Github repository with full data: https://github.com/trungngv/fgp """ url_test_y = "https://github.com/trungngv/fgp/raw/master/data/kin40k/kin40k_test_labels.as...
def download_kin40k(out_dir):
""" Data is impossible to find from reputable sources. Delve repository does not have 40k points (only 8192). Github repository with full data: https://github.com/trungngv/fgp """ url_test_y = "https://github.com/trungngv/fgp/raw/master/data/kin40k/kin40k_test_labels.asc" url_train_y = "https://...
_float=False) df = df.drop(["Unnamed: 10", "Unnamed: 11"], axis=1) df = df.dropna(axis=0, how='all') df.head() df = df.astype(float) Y = df["Y1"].values.reshape(-1, 1) # heating load X = df.drop(["Y1", "Y2"], axis=1).values assert X.shape == (768, 8) asse...
195
195
650
9
186
mohamad-amin/falkon
notebooks/uci_datasets_download.py
Python
download_kin40k
download_kin40k
73
109
73
73
5a43473eaff9de9043ae161cfe1950c2ed30c370
bigcode/the-stack
train
b8d4edff1eb6ec40c5593ac8
train
function
def download_protein(out_dir): protein_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/00265/CASP.csv" with tempfile.TemporaryDirectory() as tmp_dir: protein_file = os.path.join(tmp_dir, 'protein.csv') r = requests.get(protein_url, allow_redirects=True) with open(protein...
def download_protein(out_dir):
protein_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/00265/CASP.csv" with tempfile.TemporaryDirectory() as tmp_dir: protein_file = os.path.join(tmp_dir, 'protein.csv') r = requests.get(protein_url, allow_redirects=True) with open(protein_file, 'wb') as fh: ...
import argparse import os import tempfile import h5py import numpy as np import pandas as pd import requests def download_protein(out_dir):
34
83
278
7
26
mohamad-amin/falkon
notebooks/uci_datasets_download.py
Python
download_protein
download_protein
11
28
11
11
accc4f113b554fb13ded4da9df06df8a84f7f71d
bigcode/the-stack
train
7d9309d6cc921e8e96b64a3d
train
class
class Transaction(BaseTransaction): def __init__(self, connection: sqlite3.Connection, bus: EventBus) -> None: self._bus = bus self._connection = connection self._cursor = self._connection.cursor() self._cursor.execute("begin") self._season = SeasonRepository(self._connecti...
class Transaction(BaseTransaction):
def __init__(self, connection: sqlite3.Connection, bus: EventBus) -> None: self._bus = bus self._connection = connection self._cursor = self._connection.cursor() self._cursor.execute("begin") self._season = SeasonRepository(self._connection, self._cursor, self._bus) ...
import sqlite3 from fbsrankings.common import EventBus from fbsrankings.infrastructure import Transaction as BaseTransaction from fbsrankings.infrastructure.sqlite.write.affiliation import AffiliationRepository from fbsrankings.infrastructure.sqlite.write.game import GameRepository from fbsrankings.infrastructure.sqli...
130
131
437
5
124
mikee385/fbsrankings
src/fbsrankings/infrastructure/sqlite/write/transaction.py
Python
Transaction
Transaction
14
79
14
14
3965e8c435aea395de4632c6d68a4e68a58eeeb9
bigcode/the-stack
train
4e0545c63b39d479c5d4bcdd
train
function
@app.route('/logout') def logout(): logout_user() return redirect(url_for('index'))
@app.route('/logout') def logout():
logout_user() return redirect(url_for('index'))
next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index') return redirect(next_page) return render_template('login.html', title='Sign In', form=form) @app.route('/logout') def logout():
64
64
20
8
56
evaristofm/microblog
app/routes.py
Python
logout
logout
70
73
70
71
24af72d1eb73694ee7f6bdff88b5741fa957d6ce
bigcode/the-stack
train
f2dfab0a82f27b6dff178dd1
train
function
@app.route('/register', methods=['GET', 'POST']) def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password...
@app.route('/register', methods=['GET', 'POST']) def register():
if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() ...
= url_for('index') return redirect(next_page) return render_template('login.html', title='Sign In', form=form) @app.route('/logout') def logout(): logout_user() return redirect(url_for('index')) @app.route('/register', methods=['GET', 'POST']) def register():
63
64
111
15
48
evaristofm/microblog
app/routes.py
Python
register
register
76
88
76
77
7d21e62818ec0f49beba17dbe22a5904149395fd
bigcode/the-stack
train
e71af928878ca93b5a97f1b8
train
function
@app.route('/unfollow/<username>', methods=['POST']) @login_required def unfollow(username): form = EmptyForm() if form.validate_on_submit(): user = User.query.filter_by(username=username).first() if user is None: flash('User {} not found.'.format(username)) return redire...
@app.route('/unfollow/<username>', methods=['POST']) @login_required def unfollow(username):
form = EmptyForm() if form.validate_on_submit(): user = User.query.filter_by(username=username).first() if user is None: flash('User {} not found.'.format(username)) return redirect(url_for('index')) if user == current_user: flash('You cannot unfollow ...
_user.follow(user) db.session.commit() flash('You are following {}!'.format(username)) return redirect(url_for('user', username=username)) else: return redirect(url_for('index')) @app.route('/unfollow/<username>', methods=['POST']) @login_required def unfollow(username):
63
64
143
20
43
evaristofm/microblog
app/routes.py
Python
unfollow
unfollow
150
167
150
152
e4fd70c33ee1cbdc11a9b0148d75ecc795ab709c
bigcode/the-stack
train
c4c3a63c40f2df5396ef34d7
train
function
@app.route('/user/<username>') @login_required def user(username): user = User.query.filter_by(username=username).first_or_404() page = request.args.get('page', 1, type=int) posts = user.posts.order_by(Post.timestamp.desc()).paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for...
@app.route('/user/<username>') @login_required def user(username):
user = User.query.filter_by(username=username).first_or_404() page = request.args.get('page', 1, type=int) posts = user.posts.order_by(Post.timestamp.desc()).paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('user', username=user.username, page=posts.next_num) \ if ...
(form.password.data) db.session.add(user) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form) @app.route('/user/<username>') @login_required def user(userna...
64
64
164
14
50
evaristofm/microblog
app/routes.py
Python
user
user
91
104
91
93
1a8b3d5cb1c32a662915bce2ce746ec24d0acb38
bigcode/the-stack
train
1fefbf2c179413674200eb55
train
function
@app.route('/', methods=['GET', 'POST']) @app.route('/index', methods=['GET', 'POST']) @login_required def index(): form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post is n...
@app.route('/', methods=['GET', 'POST']) @app.route('/index', methods=['GET', 'POST']) @login_required def index():
form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post is now live!') return redirect(url_for('index')) page = request.args.get('page', 1, type=int) posts = cu...
, Post from app.forms import LoginForm, RegistrationForm, EditProfileForm, PostForm, EmptyForm from werkzeug.urls import url_parse from datetime import datetime @app.route('/', methods=['GET', 'POST']) @app.route('/index', methods=['GET', 'POST']) @login_required def index():
64
64
203
28
35
evaristofm/microblog
app/routes.py
Python
index
index
13
33
13
16
b7934b0f21ef813e5c9d54e5a86ea47d0d05b172
bigcode/the-stack
train
6030ff09d9efa7ba5437254e
train
function
@app.route('/edit_profile', methods=['GET', 'POST']) @login_required def edit_profile(): form = EditProfileForm(current_user.username) if form.validate_on_submit(): current_user.username = form.username.data current_user.about_me = form.about_me.data db.session.commit() flash('Yo...
@app.route('/edit_profile', methods=['GET', 'POST']) @login_required def edit_profile():
form = EditProfileForm(current_user.username) if form.validate_on_submit(): current_user.username = form.username.data current_user.about_me = form.about_me.data db.session.commit() flash('You changes have been saved.') return redirect(url_for('edit_profile')) elif re...
next_url=next_url, prev_url=prev_url, form=form) @app.before_request def before_request(): if current_user.is_authenticated: current_user.last_seen = datetime.utcnow() db.session.commit() @app.route('/edit_profile', methods=['GET', 'POST']) @login_required def edit_profile():
64
64
125
20
44
evaristofm/microblog
app/routes.py
Python
edit_profile
edit_profile
113
127
113
115
98c9c7cc8a028ab1155b16f6af5aafcf774fe49b
bigcode/the-stack
train
b00905f6c6ea278d71e036dd
train
function
@app.before_request def before_request(): if current_user.is_authenticated: current_user.last_seen = datetime.utcnow() db.session.commit()
@app.before_request def before_request():
if current_user.is_authenticated: current_user.last_seen = datetime.utcnow() db.session.commit()
=user.username, page=posts.prev_num) \ if posts.has_prev else None form = EmptyForm() return render_template('user.html', user=user, posts=posts.items, next_url=next_url, prev_url=prev_url, form=form) @app.before_request def before_request():
64
64
29
8
56
evaristofm/microblog
app/routes.py
Python
before_request
before_request
106
110
106
107
5cb6daede5004badd7f6e1f0759e9c44c399ecd0
bigcode/the-stack
train
e07655a26b3f699e3e33ef14
train
function
@app.route('/explore') @login_required def explore(): page = request.args.get('page', 1, type=int) posts = Post.query.order_by(Post.timestamp.desc()).paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('explore', page=posts.next_num) \ if posts.has_next else None prev...
@app.route('/explore') @login_required def explore():
page = request.args.get('page', 1, type=int) posts = Post.query.order_by(Post.timestamp.desc()).paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('explore', page=posts.next_num) \ if posts.has_next else None prev_url = url_for('explore', page=posts.prev_num) \ ...
('index', page=posts.prev_num) \ if posts.has_prev else None return render_template('index.html', title='Home', form=form, posts=posts.items, next_url=next_url, prev_url=prev_url) @app.route('/explore') @login_required def explore():
64
64
133
12
52
evaristofm/microblog
app/routes.py
Python
explore
explore
37
48
37
39
65053378e1fabe0466e73027f4a78a57d5f9e9c4
bigcode/the-stack
train
005b9d2ae6529b3ce642f8cc
train
function
@app.route('/follow/<username>', methods=['POST']) @login_required def follow(username): form = EmptyForm() if form.validate_on_submit(): user = User.query.filter_by(username=username).first() if user is None: flash('User {} not found.'.format(username)) return redirect(u...
@app.route('/follow/<username>', methods=['POST']) @login_required def follow(username):
form = EmptyForm() if form.validate_on_submit(): user = User.query.filter_by(username=username).first() if user is None: flash('User {} not found.'.format(username)) return redirect(url_for('index')) if user == current_user: flash('You cannot follow yo...
')) elif request.method == 'GET': form.username.data = current_user.username form.about_me.data = current_user.about_me return render_template('edit_profile.html', title='Edit Profile', form=form) @app.route('/follow/<username>', methods=['POST']) @login_required def follow(username):
64
64
139
18
46
evaristofm/microblog
app/routes.py
Python
follow
follow
130
147
130
132
a0cebc5cf9023bd06f8089f97c08b7cb42f8e8a4
bigcode/the-stack
train
a199e93b30d8eccd62a8004f
train
function
@app.route('/login', methods=['GET', 'POST']) def login(): if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(...
@app.route('/login', methods=['GET', 'POST']) def login():
if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or...
('explore', page=posts.prev_num) \ if posts.has_prev else None return render_template("index.html", title='Explore', posts=posts.items, next_url=next_url, prev_url=prev_url) @app.route('/login', methods=['GET', 'POST']) def login():
64
64
155
15
49
evaristofm/microblog
app/routes.py
Python
login
login
52
67
52
53
e037400cebdf220624521ca34a7a2b146a8c3ab4
bigcode/the-stack
train
f44a8c3aa1cc639c3d6d21ab
train
class
class TestAuthorisation(TestCase): """ Test that events can only be created and edited by users who should be allowed to do so """ def setUp(self): """ Creates users but doesn't log any of them in. The individual tests should do that """ self.client = Client() #Cr...
class TestAuthorisation(TestCase):
""" Test that events can only be created and edited by users who should be allowed to do so """ def setUp(self): """ Creates users but doesn't log any of them in. The individual tests should do that """ self.client = Client() #Create the 'Contributors' group ...
'event-location': u'', 'event-start': VALID_DATE_STRING, 'event-topics': [], 'event-group-description': u'', 'event-department_organiser': u'', 'event-group-event_group_select': u'', 'event-speakers': [], 'event-group-group_...
256
256
2,017
7
249
alan-turing-institute/talks.ox
talks/contributors/tests.py
Python
TestAuthorisation
TestAuthorisation
543
757
543
543
37cc184aad24528d041a122b39c91f4cf66832a7
bigcode/the-stack
train
41a94f7ced3c7a10d6c22230
train
class
class TestEventGroupForm(TestCase): def test_empty(self): form = forms.EventGroupForm({}) self.assertEquals(form.is_valid(), False, "empty form should not validate") errors = form.errors.as_data() self.assertIn('title', errors) self.assertEquals(len(errors), 1) def test...
class TestEventGroupForm(TestCase):
def test_empty(self): form = forms.EventGroupForm({}) self.assertEquals(form.is_valid(), False, "empty form should not validate") errors = form.errors.as_data() self.assertIn('title', errors) self.assertEquals(len(errors), 1) def test_all_fields_blanked(self): da...
errors: %s", errors) self.assertNotIn("Either provide the Title or mark it as TBA", form.errors.get('__all__', [])) self.assertNotIn('title', form.errors) self.assertNotIn('title_not_announced', form.errors) class TestEventGroupForm(TestCase):
66
66
221
8
58
alan-turing-institute/talks.ox
talks/contributors/tests.py
Python
TestEventGroupForm
TestEventGroupForm
158
186
158
159
c7b53eb3883b7aaa81f9a868533c5b12b38cde01
bigcode/the-stack
train
1ac8a81cfdfc856d2bc225d3
train
class
class TestEventForm(TestCase): def test_empty(self): form = forms.EventForm({}) self.assertEquals(form.is_valid(), False, "empty form should not validate") errors = form.errors.as_data() logging.info("form errors: %s", errors) self.assertEquals(len(errors), 5) self.a...
class TestEventForm(TestCase):
def test_empty(self): form = forms.EventForm({}) self.assertEquals(form.is_valid(), False, "empty form should not validate") errors = form.errors.as_data() logging.info("form errors: %s", errors) self.assertEquals(len(errors), 5) self.assertIn('booking_type', errors) ...
from __future__ import absolute_import import logging import mock from django.test import TestCase from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User, Group, Permission from django.test.client import Client from talks.events import models, factories from talks.contr...
140
256
1,182
7
133
alan-turing-institute/talks.ox
talks/contributors/tests.py
Python
TestEventForm
TestEventForm
19
155
19
20
d75d086737caed3dada5cc8d819d4c4c5a82ff9e
bigcode/the-stack
train
e189ad62081f40e9c54c0bbd
train
class
class TestCreateEventView(AuthTestCase): def test_get_happy_no_group_id(self): response = self.client.get('/talks/new') logging.info("Form errors: %s", response.context['event_form'].errors) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'contributors...
class TestCreateEventView(AuthTestCase):
def test_get_happy_no_group_id(self): response = self.client.get('/talks/new') logging.info("Form errors: %s", response.context['event_form'].errors) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'contributors/event_form.html') self.assertCont...
self.assertTemplateUsed(response, "contributors/event_group_form.html") def test_create_event_group_post_happy(self): data = { 'title': 'lkfjlfkds', 'description': 'dflksfoingf', 'group_type': '', } response = self.client.post("/talks/series/new"...
256
256
2,230
9
247
alan-turing-institute/talks.ox
talks/contributors/tests.py
Python
TestCreateEventView
TestCreateEventView
320
540
320
321
4d735cd59ab3bbffd9a07b02112de3b2343ea0ca
bigcode/the-stack
train
f0b4df79eaf3c0903d2ff6c6
train
class
class AuthTestCase(TestCase): """Subclass AuthTestCase if you need to create/edit Event or EventGroup (requiring auth) """ def setUp(self): self.client = Client() #Create the 'Contributors' group self.group = Group(name=GROUP_EDIT_EVENTS) self.group.save() #Add ...
class AuthTestCase(TestCase):
"""Subclass AuthTestCase if you need to create/edit Event or EventGroup (requiring auth) """ def setUp(self): self.client = Client() #Create the 'Contributors' group self.group = Group(name=GROUP_EDIT_EVENTS) self.group.save() #Add edit permissions for Event, Ev...
): data = { 'description': u'something', 'title': u'some title', 'group_type': u'SE', } form = forms.EventGroupForm(data) self.assertEquals(form.is_valid(), True, "form should validate") class AuthTestCase(TestCase):
64
64
178
7
57
alan-turing-institute/talks.ox
talks/contributors/tests.py
Python
AuthTestCase
AuthTestCase
189
211
189
189
cb6d4c4e84c11bdbda0d9807ff871414dae121fb
bigcode/the-stack
train
cc43da1f61108c1b4c70b688
train
class
class TestEventGroupViews(AuthTestCase): def test_show_event_group_404(self): response = self.client.get("/talks/series/1") self.assertEquals(response.status_code, 404) def test_list_event_groups_empty(self): response = self.client.get("/talks/series/") self.assertEquals(respon...
class TestEventGroupViews(AuthTestCase):
def test_show_event_group_404(self): response = self.client.get("/talks/series/1") self.assertEquals(response.status_code, 404) def test_list_event_groups_empty(self): response = self.client.get("/talks/series/") self.assertEquals(response.status_code, 200) def test_list_ev...
(errors), 1) def test_all_fields_valid(self): data = { 'description': u'something', 'title': u'some title', 'group_type': u'SE', } form = forms.EventGroupForm(data) self.assertEquals(form.is_valid(), True, "form should validate") class AuthTestC...
256
256
955
9
247
alan-turing-institute/talks.ox
talks/contributors/tests.py
Python
TestEventGroupViews
TestEventGroupViews
214
317
214
215
fea5c512a822210d3b0daae72cb02d66266613b1
bigcode/the-stack
train
c327d483b1c0cda893a5c5a3
train
class
class TestEditEventView(AuthTestCase): def test_edit_event_404(self): response = self.client.get("/talks/id/1/edit") self.assertEquals(response.status_code, 404) self.assertTemplateNotUsed(response, "contributors/event_form.html") def test_edit_event_200(self): event = factorie...
class TestEditEventView(AuthTestCase):
def test_edit_event_404(self): response = self.client.get("/talks/id/1/edit") self.assertEquals(response.status_code, 404) self.assertTemplateNotUsed(response, "contributors/event_form.html") def test_edit_event_200(self): event = factories.EventFactory.create() event.ed...
( title='series title', ) group.editor_set.add(self.contrib_user1) group.save() #create event and set user1 as an editor event = factories.EventFactory.create(title='event title') event.editor_set.add(self.contrib_user2) event.group = group eve...
256
256
923
9
247
alan-turing-institute/talks.ox
talks/contributors/tests.py
Python
TestEditEventView
TestEditEventView
760
854
760
761
a4444f770608b976034d209b9e21df7660203f87
bigcode/the-stack
train
6057f7779c4cadd18d6a3514
train
class
class PeerExpressRouteCircuitConnectionsOperations(object): """PeerExpressRouteCircuitConnectionsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to mode...
class PeerExpressRouteCircuitConnectionsOperations(object):
"""PeerExpressRouteCircuitConnectionsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~a...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
237
256
1,771
9
228
xolve/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2021_05_01/operations/_peer_express_route_circuit_connections_operations.py
Python
PeerExpressRouteCircuitConnectionsOperations
PeerExpressRouteCircuitConnectionsOperations
26
194
26
26
40bf1afd17dc77b717396f7fe68d92c326e27cc6
bigcode/the-stack
train
824adad2bf6343667755b880
train
class
class NLR2(nn.Module): def __init__(self,netin,netout,nethidden1,nethidden2): super().__init__() self.netmodel= torch.nn.Sequential(torch.nn.Linear(netin, nethidden1),torch.nn.Sigmoid(),torch.nn.Linear(nethidden1, nethidden2),torch.nn.Linear(nethidden2, netout)) def myforward (self,inv): outv=self.netmo...
class NLR2(nn.Module):
def __init__(self,netin,netout,nethidden1,nethidden2): super().__init__() self.netmodel= torch.nn.Sequential(torch.nn.Linear(netin, nethidden1),torch.nn.Sigmoid(),torch.nn.Linear(nethidden1, nethidden2),torch.nn.Linear(nethidden2, netout)) def myforward (self,inv): outv=self.netmodel(inv) return out...
+= 1 r /= len(nn_result) #out += [('recall_top' + str(k) + '_correct_composition', r)] out.append(str(k) + ' ---> '+ str(r*100)) print(out) return out class NLR2(nn.Module):
64
64
104
7
56
mohamedaboalimaa/tirg
BK/mainM.py
Python
NLR2
NLR2
729
735
729
729
2cc50a1c663496dcc86e033922d7313dc8528672
bigcode/the-stack
train
3ef086970b9728792b70bcc2
train
function
def test_and_save(opt, model, testset): """Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_target_captions = [] all_captions=[] if test_queries: # compute test query features imgs = [] mod...
def test_and_save(opt, model, testset):
"""Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_target_captions = [] all_captions=[] if test_queries: # compute test query features imgs = [] mods = [] for t in tqdm(test_queries): ...
_eucld) test_train=0 set_size_divider=1 normal_beta=1 create_load=0 filename='REGTS33NE.BTA' # 5 E print(' 5 E', file=sourceFile) out =test_retrieval.test_on_saved(test_train,normal_beta,create_load,filename,normal_normalize, set_size_divider, dot_eucld) print_results(sourceFile,out,test_train,normal...
256
256
1,486
11
245
mohamedaboalimaa/tirg
BK/mainM.py
Python
test_and_save
test_and_save
367
511
367
367
8be4711b22ad87cd9eacd220ae4602acf4c9c06b
bigcode/the-stack
train
5f5daabaecb36747b06cd5c5
train
function
def ab_Ogetvaluesfilesaved(): trainset = datasets.Fashion200k( path=Path1, split='train', transform=torchvision.transforms.Compose([ torchvision.transforms.Resize(224), torchvision.transforms.CenterCrop(224), torchvision.transforms.ToTensor(), t...
def ab_Ogetvaluesfilesaved():
trainset = datasets.Fashion200k( path=Path1, split='train', transform=torchvision.transforms.Compose([ torchvision.transforms.Resize(224), torchvision.transforms.CenterCrop(224), torchvision.transforms.ToTensor(), torchvision.transforms.Normalize...
/= len(nn_result) out += [('recall_top' + str(k) + '_correct_adj', r)] r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i].split()[1] in [c.split()[1] for c in nns[:k]]: r += 1 r /= len(nn_result) out += [('recall_top' + str(k) + '_correct_noun', r)] ...
116
116
389
8
107
mohamedaboalimaa/tirg
BK/mainM.py
Python
ab_Ogetvaluesfilesaved
ab_Ogetvaluesfilesaved
1,056
1,096
1,056
1,057
ae447fcea568f5193555f214af502ffb8fdc80ac
bigcode/the-stack
train
3909dcb3a34ab73135cc0548
train
function
def ab_Otest(opt, model, testset): """Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_target_captions = [] if test_queries: # compute test query features imgs = [] mods = [] for t in tqd...
def ab_Otest(opt, model, testset):
"""Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_target_captions = [] if test_queries: # compute test query features imgs = [] mods = [] for t in tqdm(test_queries): imgs += [tes...
(), torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ])) trig= img_text_composition_models.TIRG([t.encode().decode('utf-8') for t in trainset.get_all_texts()],512) trig.load_state_dict(torch.load(Path1+r'\fashion200k.ti...
256
256
1,151
11
245
mohamedaboalimaa/tirg
BK/mainM.py
Python
ab_Otest
ab_Otest
1,098
1,211
1,098
1,098
9c49762c7b7514f51e7ee0e59e2942accdc40881
bigcode/the-stack
train
c24c04d85c7205ccd76d7f39
train
function
def train_network_on_saved(test_train,create_load,normal_normalize,filename,sz,dot_eucld): if test_train==0: with open(Path1+r"/"+'test_test_queries.pkl', 'rb') as fp: test_queries=pickle.load( fp) with open(Path1+r"/"+'test_all_queriesG.pkl', 'rb') as fp: all_queries=pickle.load( fp) with open(Path...
def train_network_on_saved(test_train,create_load,normal_normalize,filename,sz,dot_eucld):
if test_train==0: with open(Path1+r"/"+'test_test_queries.pkl', 'rb') as fp: test_queries=pickle.load( fp) with open(Path1+r"/"+'test_all_queriesG.pkl', 'rb') as fp: all_queries=pickle.load( fp) with open(Path1+r"/"+'test_all_imgsG.pkl', 'rb') as fp: all_imgs=pickle.load( fp) with open(Path1+...
nn_result = [[all_captions[nn] for nn in nns] for nns in nn_result] for k in [1, 5, 10, 50, 100]: r = 0.0 for i, nns in enumerate(nn_result): for c in range(k): if (all_target_captions[i] == nns[c]): r += 1 r /= len(nn_result) out2.append(str(k) + ' ---> '+ str(r*100)) fo...
256
256
858
24
231
mohamedaboalimaa/tirg
BK/mainM.py
Python
train_network_on_saved
train_network_on_saved
649
727
649
649
74fccee5baba26b1af6192857a8837a018c033e0
bigcode/the-stack
train
0aba91fb4ce181030345172c
train
function
def neural_model(all_queries,all_imgs,model_option,test_queries): if model_option==0: hidden1=800 hidden2=700 batch_size=100 itr=10000 if not test_queries: build_and_train_netMSE(hidden1,hidden2,itr, 0.02, all_queries,all_imgs,batch_size) model=NLR2(all_queries.shape[1],all_imgs.shape[1]...
def neural_model(all_queries,all_imgs,model_option,test_queries):
if model_option==0: hidden1=800 hidden2=700 batch_size=100 itr=10000 if not test_queries: build_and_train_netMSE(hidden1,hidden2,itr, 0.02, all_queries,all_imgs,batch_size) model=NLR2(all_queries.shape[1],all_imgs.shape[1],800,700) model.load_state_dict(torch.load(Path1+r"/"+r'\NLPM...
1): new_all_queries=regression(all_queries,all_imgs,0,test_queries) if (option==2): new_all_queries=neural_model(all_queries,all_imgs,0,test_queries) return new_all_queries def neural_model(all_queries,all_imgs,model_option,test_queries):
64
64
214
14
49
mohamedaboalimaa/tirg
BK/mainM.py
Python
neural_model
neural_model
1,415
1,438
1,415
1,415
df3c8cb7df84188f0346c244fdbcecc382db5973
bigcode/the-stack
train
d8af14796bc466587ce2c22b
train
function
def mymodels(all_queries,all_imgs,all_target_captions,option,test_queries): if (option==0): return all_queries if (option==1): new_all_queries=regression(all_queries,all_imgs,0,test_queries) if (option==2): new_all_queries=neural_model(all_queries,all_imgs,0,test_queries) return new_all_queri...
def mymodels(all_queries,all_imgs,all_target_captions,option,test_queries):
if (option==0): return all_queries if (option==1): new_all_queries=regression(all_queries,all_imgs,0,test_queries) if (option==2): new_all_queries=neural_model(all_queries,all_imgs,0,test_queries) return new_all_queries
+= [('recall_top' + str(k) + '_correct_composition', r)] out3.append(str(k) + ' ---> '+ str(r*100)) return out, out2, out3 def mymodels(all_queries,all_imgs,all_target_captions,option,test_queries):
64
64
86
19
44
mohamedaboalimaa/tirg
BK/mainM.py
Python
mymodels
mymodels
1,404
1,413
1,404
1,404
99ed1a8af97ac57ce27cd0a89400da41491074b0
bigcode/the-stack
train
52b5dfc39d590b1aca209343
train
function
def print_results(sourceFile,out,test_train,normal_beta,create_load,filename,normal_normalize, set_size_divider, dot_eucld): print(' Experiment setup : ', file = sourceFile) if (test_train==1): print('Dataset:Training Data set', file = sourceFile) else: print('Dataset:Testing Data set', file = sourceFile)...
def print_results(sourceFile,out,test_train,normal_beta,create_load,filename,normal_normalize, set_size_divider, dot_eucld):
print(' Experiment setup : ', file = sourceFile) if (test_train==1): print('Dataset:Training Data set', file = sourceFile) else: print('Dataset:Testing Data set', file = sourceFile) if (normal_beta==0): print(' Trig', file = sourceFile) else: print(' Trig followed by Regression network', file...
tmp1=tmp1/len(l) for j in range(len(l)): new_all_imgs[l[j],:]=tmp1 with open(Path1+r"/"+'new_all_imgs2006172k.pkl', 'wb') as fp: pickle.dump(new_all_imgs, fp) def print_results(sourceFile,out,test_train,normal_beta,create_load,filename,normal_normalize, set_size_divider, dot_eucld):
93
94
314
31
62
mohamedaboalimaa/tirg
BK/mainM.py
Python
print_results
print_results
146
174
146
146
d0966fd03ee00944a44aa37b04ff166a9cdf6f75
bigcode/the-stack
train
54c0088c4b47fe5970123326
train
function
def adapt_dataset(size_limit): with open(Path1+r"/"+'test_queries1806172k.pkl', 'rb') as fp: test_queries=pickle.load( fp) with open(Path1+r"/"+'all_queries1806172k.pkl', 'rb') as fp: all_queries=pickle.load( fp) with open(Path1+r"/"+'all_imgs1806172k.pkl', 'rb') as fp: all_imgs=pickle.load( fp) #...
def adapt_dataset(size_limit):
with open(Path1+r"/"+'test_queries1806172k.pkl', 'rb') as fp: test_queries=pickle.load( fp) with open(Path1+r"/"+'all_queries1806172k.pkl', 'rb') as fp: all_queries=pickle.load( fp) with open(Path1+r"/"+'all_imgs1806172k.pkl', 'rb') as fp: all_imgs=pickle.load( fp) #with open(Path1+r"/"+'all_capti...
with open(Path1+r"/"+'all_imgs1806172k.pkl', 'wb') as fp: pickle.dump(all_imgs, fp) with open(Path1+r"/"+'all_captions1806172k.pkl', 'wb') as fp: pickle.dump(all_captions, fp) with open(Path1+r"/"+'all_target_captions1806172k.pkl', 'wb') as fp: pickle.dump(all_target_captions, fp) def adapt_dataset(si...
109
110
367
6
103
mohamedaboalimaa/tirg
BK/mainM.py
Python
adapt_dataset
adapt_dataset
111
144
111
111
1c3c25ebdedb8aa320e1815e3b1653f92189d030
bigcode/the-stack
train
3f0c41e3efc8bc87f3319121
train
function
def results_temp(): stime=time.strftime("%Y%m%d-%H%M%S") sourceFile = open(Path1+r"/"+'results'+stime+'.txt', 'w') test_train=1 normal_beta=0 set_size_divider=100 normal_normalize=0 create_load=0 filename='beta1806.pkl' dot_eucld=0 # 1 print(' 1 ', file=sourceFile) print ('1') #out =test_on_sa...
def results_temp():
stime=time.strftime("%Y%m%d-%H%M%S") sourceFile = open(Path1+r"/"+'results'+stime+'.txt', 'w') test_train=1 normal_beta=0 set_size_divider=100 normal_normalize=0 create_load=0 filename='beta1806.pkl' dot_eucld=0 # 1 print(' 1 ', file=sourceFile) print ('1') #out =test_on_saved(test_train,norma...
ucld==0): nn_result.append(np.argsort(-sims[0, :])[:105]) else: nn_result.append(np.argsort(sims[0, :])[:105]) all_imgs=[] all_queries=[] # compute recalls out = [] nn_result = [[all_captions[nn] for nn in nns] for nns in nn_result] for k in [1, 5, 10, 50, 100]: r = 0.0 for i, nn...
196
197
658
4
192
mohamedaboalimaa/tirg
BK/mainM.py
Python
results_temp
results_temp
920
984
920
920
9532c0577f3cd3bfdcf8059850942df94e001325
bigcode/the-stack
train
9f9fb2a22525a2a62bd726eb
train
function
def test_on_saved(test_train,normal_beta,create_load,filename,normal_normalize,sz,dot_eucld): # test_queries: if test_train==0: with open(Path1+r"/"+'test_test_queries.pkl', 'rb') as fp: test_queries=pickle.load( fp) with open(Path1+r"/"+'test_all_queriesG.pkl', 'rb') as fp: all_queries=pickle.load( ...
def test_on_saved(test_train,normal_beta,create_load,filename,normal_normalize,sz,dot_eucld): # test_queries:
if test_train==0: with open(Path1+r"/"+'test_test_queries.pkl', 'rb') as fp: test_queries=pickle.load( fp) with open(Path1+r"/"+'test_all_queriesG.pkl', 'rb') as fp: all_queries=pickle.load( fp) with open(Path1+r"/"+'test_all_imgsG.pkl', 'rb') as fp: all_imgs=pickle.load( fp) with open(Path1+...
ns[:k]: r += 1 r /= len(nn_result) #out += [('recall_top' + str(k) + '_correct_composition', r)] out.append(str(k) + ' ---> '+ str(r*100)) if opt.dataset == 'mitstates': r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i].split()[0] in [c.split()[0] for c i...
256
256
1,456
31
224
mohamedaboalimaa/tirg
BK/mainM.py
Python
test_on_saved
test_on_saved
513
647
513
514
97462d4d851edeecb4819082fd83f0d32f2d1b09
bigcode/the-stack
train
e1ff7a4e37ce29d6a52def9f
train
function
def build_and_train_netMSE(hidden1,hidden2,max_iterations, min_error, all_queries,all_imgs,batch_size): all_queries=Variable(torch.Tensor(all_queries)) all_imgs=variable(torch.tensor(all_imgs)) model=NLR2(all_queries.shape[1],all_imgs.shape[1],hidden1,hidden2) #model=model.cuda() torch.manual_seed(3) loss_f...
def build_and_train_netMSE(hidden1,hidden2,max_iterations, min_error, all_queries,all_imgs,batch_size):
all_queries=Variable(torch.Tensor(all_queries)) all_imgs=variable(torch.tensor(all_imgs)) model=NLR2(all_queries.shape[1],all_imgs.shape[1],hidden1,hidden2) #model=model.cuda() torch.manual_seed(3) loss_fn = torch.nn.MSELoss() torch.manual_seed(3) #criterion = nn.CosineSimilarity() criterion=nn.MSELo...
__(self,netin,netout,nethidden1,nethidden2): super().__init__() self.netmodel= torch.nn.Sequential(torch.nn.Linear(netin, nethidden1),torch.nn.Sigmoid(),torch.nn.Linear(nethidden1, nethidden2),torch.nn.Linear(nethidden2, netout)) def myforward (self,inv): outv=self.netmodel(inv) return outv def build_...
120
120
402
27
92
mohamedaboalimaa/tirg
BK/mainM.py
Python
build_and_train_netMSE
build_and_train_netMSE
737
777
737
737
ff3c2aeec2cd71330c5e986f78c2a8f96f699de6
bigcode/the-stack
train
89496cb0d1ffdad8e8e45231
train
function
def regression(all_queries,all_imgs,option, test_queries): if (option==0 ): if (test_queries): with open(Path1+r"/"+'beta0.pkl', 'rb') as fp: beta=pickle.load( fp) new_all_queries=np.zeros(all_queries.shape) for i in range(new_all_queries.shape[0]): new_all_queries[i,:]=np.ma...
def regression(all_queries,all_imgs,option, test_queries):
if (option==0 ): if (test_queries): with open(Path1+r"/"+'beta0.pkl', 'rb') as fp: beta=pickle.load( fp) new_all_queries=np.zeros(all_queries.shape) for i in range(new_all_queries.shape[0]): new_all_queries[i,:]=np.matmul(all_queries[i,:],beta) else: new_all_queries=al...
forward(all_queries) new_all_queries = torch.tensor(new_all_queries,requires_grad=False) #all_queries.detach().numpy() new_all_queries=np.array(new_all_queries) return new_all_queries else: return all_queries def regression(all_queries,all_imgs,option, test_queries):
66
67
225
14
51
mohamedaboalimaa/tirg
BK/mainM.py
Python
regression
regression
1,441
1,463
1,441
1,442
d4ef2561c51a51f880d0f3af30e1243fb737b252
bigcode/the-stack
train
b30a70c4edd9bb8578230570
train
function
def ab_Mgetvaluesfilesaved(option): trainset = datasets.Fashion200k( path=Path1, split='train', transform=torchvision.transforms.Compose([ torchvision.transforms.Resize(224), torchvision.transforms.CenterCrop(224), torchvision.transforms.ToTensor(), ...
def ab_Mgetvaluesfilesaved(option):
trainset = datasets.Fashion200k( path=Path1, split='train', transform=torchvision.transforms.Compose([ torchvision.transforms.Resize(224), torchvision.transforms.CenterCrop(224), torchvision.transforms.ToTensor(), torchvision.transforms.Normalize...
ns[:k]]: r += 1 r /= len(nn_result) out += [('recall_top' + str(k) + '_correct_adj', r)] r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i].split()[1] in [c.split()[1] for c in nns[:k]]: r += 1 r /= len(nn_result) out += [('recall_top' ...
129
129
433
9
119
mohamedaboalimaa/tirg
BK/mainM.py
Python
ab_Mgetvaluesfilesaved
ab_Mgetvaluesfilesaved
1,213
1,254
1,213
1,214
65c2cf23d5da755915822963442bcda057dccfd8
bigcode/the-stack
train
ec64c0f51412002314ea1684
train
function
def abt_MtestLoaded(opt, model, testset,option): """Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_target_captions = [] if test_queries: # compute test query features all_imgs = datasets...
def abt_MtestLoaded(opt, model, testset,option):
"""Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_target_captions = [] if test_queries: # compute test query features all_imgs = datasets.Features33K().Get_all_images() all_captions ...
r += 1 r /= len(new_nn_result) #out += [('recall_top' + str(k) + '_correct_composition', r)] out2.append(str(k) + ' ---> '+ str(r*100)) r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i] in nns[:k]: r += 1 r /= len(nn_result) #out += [('recall_top' +...
160
160
536
15
144
mohamedaboalimaa/tirg
BK/mainM.py
Python
abt_MtestLoaded
abt_MtestLoaded
1,350
1,402
1,350
1,350
cbcbf04043239025b584c4cc6790404aa6bec3ac
bigcode/the-stack
train
7ea3bd734dc2416cc2f94e6a
train
function
def results(): sourceFile = open(Path1+r"/"+'results'+time.strftime("%Y%m%d-%H%M%S")+'.txt', 'w') test_train=0 normal_beta=0 set_size_divider=1 normal_normalize=0 create_load=0 filename='na' dot_eucld=0 # 1 print(' 1', file=sourceFile) out =test_retrieval.test_on_saved(test_train,normal_beta,creat...
def results():
sourceFile = open(Path1+r"/"+'results'+time.strftime("%Y%m%d-%H%M%S")+'.txt', 'w') test_train=0 normal_beta=0 set_size_divider=1 normal_normalize=0 create_load=0 filename='na' dot_eucld=0 # 1 print(' 1', file=sourceFile) out =test_retrieval.test_on_saved(test_train,normal_beta,create_load,filename...
= sourceFile) else: print('Dataset:Testing Data set', file = sourceFile) if (normal_beta==0): print(' Trig', file = sourceFile) else: print(' Trig followed by Regression network', file = sourceFile) if (normal_beta==1): if (create_load==0): print(' Regression Network Created, save to fil...
256
256
2,191
3
253
mohamedaboalimaa/tirg
BK/mainM.py
Python
results
results
176
365
176
176
6d76d0ee90d6a3dde9cbd13cd2acdce289bc4de0
bigcode/the-stack
train
b0ab4bdddb1260e34757ead8
train
function
def ab_OtestLoaded(opt, model, testset): """Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() test_train=1 all_imgs = [] all_captions = [] all_queries = [] all_target_captions = [] if (test_train)==0: # compute test query features all_imgs ...
def ab_OtestLoaded(opt, model, testset):
"""Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() test_train=1 all_imgs = [] all_captions = [] all_queries = [] all_target_captions = [] if (test_train)==0: # compute test query features all_imgs = datasets.Features33K().Get_all_images()...
d) print_results(sourceFile,out,test_train,normal_beta,create_load,filename,normal_normalize, set_size_divider, dot_eucld) sourceFile.close() sourceFile = open(Path1+r"/"+'results'+stime+'.txt', 'a') test_train=1 normal_beta=1 set_size_divider=100 normal_normalize=0 create_load=0 filename='beta1806euc...
210
210
700
12
198
mohamedaboalimaa/tirg
BK/mainM.py
Python
ab_OtestLoaded
ab_OtestLoaded
986
1,054
986
986
dd010e7758077db7aee908b76b80c94c9dd40e4b
bigcode/the-stack
train
3cc83e81886232e01458bd01
train
function
def Reform_Training_Dataset(): train = datasets.Fashion200k( path=Path1, split='train', transform=torchvision.transforms.Compose([ torchvision.transforms.Resize(224), torchvision.transforms.CenterCrop(224), torchvision.transforms.ToTensor(), ...
def Reform_Training_Dataset():
train = datasets.Fashion200k( path=Path1, split='train', transform=torchvision.transforms.Compose([ torchvision.transforms.Resize(224), torchvision.transforms.CenterCrop(224), torchvision.transforms.ToTensor(), torchvision.transforms.Normalize([0...
import torch.nn as nn import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') import numpy as np from torch import optim import torch.nn.functional as F import math as m import time import os #from google.colab import drive import random from PIL import Image from torch.autograd import Variable, variable f...
196
196
655
8
188
mohamedaboalimaa/tirg
BK/mainM.py
Python
Reform_Training_Dataset
Reform_Training_Dataset
43
109
43
45
0839a2613cb7dbb4d550b63ec7b70ff7255430e6
bigcode/the-stack
train
256aad516a17a3f2953bb3e0
train
function
def test_on_saved_NN_CMP(test_train,normal_beta_NN,create_load,filename,normal_normalize,sz,dot_eucld,hiddensize,model_fn): # test_queries: if test_train==0: with open(Path1+r"/"+'test_test_queries.pkl', 'rb') as fp: test_queries=pickle.load( fp) with open(Path1+r"/"+'test_all_queriesG.pkl', 'rb') as fp:...
def test_on_saved_NN_CMP(test_train,normal_beta_NN,create_load,filename,normal_normalize,sz,dot_eucld,hiddensize,model_fn): # test_queries:
if test_train==0: with open(Path1+r"/"+'test_test_queries.pkl', 'rb') as fp: test_queries=pickle.load( fp) with open(Path1+r"/"+'test_all_queriesG.pkl', 'rb') as fp: all_queries=pickle.load( fp) with open(Path1+r"/"+'test_all_imgsG.pkl', 'rb') as fp: all_imgs=pickle.load( fp) with open(Path1+...
_size:(l+1)*batch_size-1,:] target_batch=all_imgs[l*batch_size:(l+1)*batch_size-1,:] netoutbatch=model.myforward(item_batch) loss = loss_fn(target_batch,netoutbatch) losses.append(loss) optimizer.zero_grad() loss.backward() optimizer.step() total_loss+=loss if (l%10...
255
256
1,421
44
211
mohamedaboalimaa/tirg
BK/mainM.py
Python
test_on_saved_NN_CMP
test_on_saved_NN_CMP
779
918
779
780
a8a9232c007d8c8f1992154bf730e95b66e523ea
bigcode/the-stack
train
3d2fa5e506735ae2067aa873
train
function
def ab_MtestLoaded(opt, model, testset,option): """Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_target_captions = [] if test_queries: # compute test query features all_imgs = datasets....
def ab_MtestLoaded(opt, model, testset,option):
"""Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_target_captions = [] if test_queries: # compute test query features all_imgs = datasets.Features33K().Get_all_images() all_captions ...
_models.TIRG([t.encode().decode('utf-8') for t in trainset.get_all_texts()],512) trig.load_state_dict(torch.load(Path1+r'\fashion200k.tirg.iter160k.pth' , map_location=torch.device('cpu') )['model_state_dict']) opt = argparse.ArgumentParser() opt.add_argument('--batch_size', type=int, default=2) opt.add_arg...
256
256
1,010
14
242
mohamedaboalimaa/tirg
BK/mainM.py
Python
ab_MtestLoaded
ab_MtestLoaded
1,256
1,348
1,256
1,256
9de86cccc74bddd1bc02166bbd4252956090e20e
bigcode/the-stack
train
c18852cf6d7a12638aa2dd6f
train
class
class ShapeBase(ResourceBase): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types...
class ShapeBase(ResourceBase):
""" Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'self_uri': 'Resourc...
of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnishe...
256
256
3,333
7
248
rizwanniazigroupdocs/aspose-slides-cloud-python
asposeslidescloud/models/shape_base.py
Python
ShapeBase
ShapeBase
35
496
35
37
022d2865ac1b19ec58096755c687088f66c8aa74
bigcode/the-stack
train
dbc590113ea6baed7665e752
train
class
class InitializersTest(absltest.TestCase): def test_random_normal(self): initializer = initializers.RandomNormalInitializer() input_shape = (29, 5, 7, 20) init_value = initializer(input_shape, random.get_prng(0)) self.assertEqual(tuple(init_value.shape), input_shape) def test_lecun_uniform(self): ...
class InitializersTest(absltest.TestCase):
def test_random_normal(self): initializer = initializers.RandomNormalInitializer() input_shape = (29, 5, 7, 20) init_value = initializer(input_shape, random.get_prng(0)) self.assertEqual(tuple(init_value.shape), input_shape) def test_lecun_uniform(self): initializer = initializers.LeCunUniformI...
coding=utf-8 # Copyright 2020 The Trax Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
207
207
692
10
196
jackalhan/trax
trax/layers/initializers_test.py
Python
InitializersTest
InitializersTest
27
91
27
28
22dfdd69e7f55c1eb364ff96dbc46b8079b66aaf
bigcode/the-stack
train
b9d4672256f648c1b4b2e12c
train
function
@keras_export('keras.datasets.cifar100.load_data') def load_data(label_mode='fine'): """Loads the CIFAR100 dataset. This is a dataset of 50,000 32x32 color training images and 10,000 test images, labeled over 100 fine-grained classes that are grouped into 20 coarse-grained classes. See more info at the [CIFA...
@keras_export('keras.datasets.cifar100.load_data') def load_data(label_mode='fine'):
"""Loads the CIFAR100 dataset. This is a dataset of 50,000 32x32 color training images and 10,000 test images, labeled over 100 fine-grained classes that are grouped into 20 coarse-grained classes. See more info at the [CIFAR homepage](https://www.cs.toronto.edu/~kriz/cifar.html). Args: label_mode: on...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
208
226
755
20
187
Halo9Pan/dive-keras
keras/datasets/cifar100.py
Python
load_data
load_data
27
93
27
28
3a8fda5019a231df23a71bee1f924d169e4be046
bigcode/the-stack
train
106161de3342062b17837bed
train
class
class FmColorEdit(QtGui.QLineEdit): def __init__(self, parent): super(FmColorEdit, self).__init__(parent) self.setReadOnly(True) def mousePressEvent(self, event): self.color = QtGui.QColorDialog.getColor(Qt.blue) palette = self.palette() palette.setColor(QPalette.Base, ...
class FmColorEdit(QtGui.QLineEdit):
def __init__(self, parent): super(FmColorEdit, self).__init__(parent) self.setReadOnly(True) def mousePressEvent(self, event): self.color = QtGui.QColorDialog.getColor(Qt.blue) palette = self.palette() palette.setColor(QPalette.Base, self.color) self.setPalette(p...
from PyQt4.QtGui import QPalette, QColor __author__ = 'pawel' from PyQt4 import QtGui from PyQt4.QtCore import Qt class FmColorEdit(QtGui.QLineEdit):
48
64
137
11
36
ComputerArchitectureGroupPWr/Floorplan-Maker
src/fmWidgets/FmColorEdit.py
Python
FmColorEdit
FmColorEdit
9
28
9
10
f089c3e312f92c83ab4056f45ecf3ba2a793436d
bigcode/the-stack
train
7b01df86b1bf24d9d3deb949
train
class
class SaharaOutputDataSourcesTestCase(test.ScenarioTestCase): def setUp(self): super(SaharaOutputDataSourcesTestCase, self).setUp() fake_dict = objects.Credential("http://fake.example.org:5000/v2.0/", "user", "passwd") self.tenants_num = 2 self...
class SaharaOutputDataSourcesTestCase(test.ScenarioTestCase):
def setUp(self): super(SaharaOutputDataSourcesTestCase, self).setUp() fake_dict = objects.Credential("http://fake.example.org:5000/v2.0/", "user", "passwd") self.tenants_num = 2 self.users_per_tenant = 2 self.users = self.tenants_num * s...
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software #...
183
256
951
13
170
varuntiwari27/rally
tests/unit/plugins/openstack/context/sahara/test_sahara_output_data_sources.py
Python
SaharaOutputDataSourcesTestCase
SaharaOutputDataSourcesTestCase
24
145
24
25
99c5947d8a477b00f8867624afa9355ff84aba64
bigcode/the-stack
train
624e06e6c026cdf63fd3eb8d
train
function
@User.on_message(filters.private & filters.incoming & ~filters.bot & ~filters.service & ~filters.me & ~filters.edited) async def nopm(client, message): if REPLY_MESSAGE is not None: try: inline = await client.get_inline_bot_results(USERNAME, "UFSBotz") await client.send_inline_bot_re...
@User.on_message(filters.private & filters.incoming & ~filters.bot & ~filters.service & ~filters.me & ~filters.edited) async def nopm(client, message):
if REPLY_MESSAGE is not None: try: inline = await client.get_inline_bot_results(USERNAME, "UFSBotz") await client.send_inline_bot_result( message.chat.id, query_id=inline.query_id, result_id=inline.results[0].id, hide_vi...
= Config.REPLY_MESSAGE User = ufs( Config.SESSION_STRING, Config.API_ID, Config.API_HASH ) @User.on_message(filters.private & filters.incoming & ~filters.bot & ~filters.service & ~filters.me & ~filters.edited) async def nopm(client, message):
64
64
214
36
28
jinspalakkattu/UFSStreamingBot
bot/ufsbotz/nopm.py
Python
nopm
nopm
40
63
40
41
093a7675168a236ad26c52ab2770680ab243d343
bigcode/the-stack
train
9b2c64a3e1d89b358bc59e6b
train
function
def Main1Page(wd, url): wd.get(url) TypeXpath = 'XPath 값' wd.find_element_by_xpath(TypeXpath).click() time.sleep(2) wd.find_element_by_name('searchWord').send_keys('입력값') time.sleep(2) SearchXpath = 'XPath 값' wd.find_element_by_xpath(SearchXpath).click() time.sleep(5) #driver.save_screenshot(f'.\\Capture2\...
def Main1Page(wd, url):
wd.get(url) TypeXpath = 'XPath 값' wd.find_element_by_xpath(TypeXpath).click() time.sleep(2) wd.find_element_by_name('searchWord').send_keys('입력값') time.sleep(2) SearchXpath = 'XPath 값' wd.find_element_by_xpath(SearchXpath).click() time.sleep(5) #driver.save_screenshot(f'.\\Capture2\\Capture{i+1}.png') c...
userid').send_keys('ID') wd.find_element_by_name('password').send_keys('비밀번호') time.sleep(1) LoginXpath='//*[@id="big_login"]/fieldset/form/a' wd.find_element_by_xpath(LoginXpath).click() time.sleep(3) def Main1Page(wd, url):
66
66
221
9
57
liberte97/FileCpature
LoginA.py
Python
Main1Page
Main1Page
19
42
19
19
bdf911392b725a148895ebc22e517e3ebaeb60d2
bigcode/the-stack
train
ddb2631db8c6da7fc663efc1
train
function
def Login(wd, url): wd.get(url) LoginXpath = '//*[@id="arGnb"]/div/div/div[3]/div/a[1]' wd.find_element_by_xpath(LoginXpath).click() time.sleep(2) wd.find_element_by_name('userid').send_keys('ID') wd.find_element_by_name('password').send_keys('비밀번호') time.sleep(1) LoginXpath='//*[@id="big_login"]/fieldset/form/...
def Login(wd, url):
wd.get(url) LoginXpath = '//*[@id="arGnb"]/div/div/div[3]/div/a[1]' wd.find_element_by_xpath(LoginXpath).click() time.sleep(2) wd.find_element_by_name('userid').send_keys('ID') wd.find_element_by_name('password').send_keys('비밀번호') time.sleep(1) LoginXpath='//*[@id="big_login"]/fieldset/form/a' wd.find_element_...
from selenium import webdriver import time, os, errno, shutil import pandas as pd import webbrowser, subprocess, pyautogui from PIL import ImageGrab def Login(wd, url):
43
64
115
7
35
liberte97/FileCpature
LoginA.py
Python
Login
Login
7
17
7
7
eb76556ada2901fe378fd2edee701c225a7cd20e
bigcode/the-stack
train
570e41d6f8944ad280979b7d
train
function
def WebCrawMain(url, title_site): wd = webdriver.Chrome('chromedriver.exe') wd.implicitly_wait(3) wd.set_window_position(50,50) wd.set_window_size(1200, 1350) Login(wd, url) Main1Page(wd, url) for i in range(2): wd.get(title_site[i+1]) time.sleep(3) im = ImageGrab.grab(bbox=(60, 50, 1140, 1040)) #driver...
def WebCrawMain(url, title_site):
wd = webdriver.Chrome('chromedriver.exe') wd.implicitly_wait(3) wd.set_window_position(50,50) wd.set_window_size(1200, 1350) Login(wd, url) Main1Page(wd, url) for i in range(2): wd.get(title_site[i+1]) time.sleep(3) im = ImageGrab.grab(bbox=(60, 50, 1140, 1040)) #driver.save_screenshot(f'.\\Capture2\\Ca...
time.sleep(2) if (i+1)%20 == 0: count = count + 1 NextXpath = f'XPath 값' wd.find_element_by_xpath(NextXpath).click() time.sleep(4) def WebCrawMain(url, title_site):
64
64
191
10
54
liberte97/FileCpature
LoginA.py
Python
WebCrawMain
WebCrawMain
44
62
44
44
8af1b7fc6d68aa493b619e50c4755238e93c7580
bigcode/the-stack
train