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
578cbad4c52ed883f1efb2e2
train
function
def no_grad(): return using_config('enable_backprop', False)
def no_grad():
return using_config('enable_backprop', False)
.grad, num_grad) self.assertTrue(flg) @contextlib.contextmanager def using_config(name, value): old_value = getattr(Config, name) setattr(Config, name, value) try: yield finally: setattr(Config, name, old_value) def no_grad():
64
64
15
4
60
ck-ksst/deep-learning-from-scratch-3
steps/step18.py
Python
no_grad
no_grad
151
152
151
151
ae2afaae8a92c34edd8bcb6c7f543f6936995390
bigcode/the-stack
train
8020f694acaa2acecb6fec25
train
class
class Config: enable_backprop = True
class Config:
enable_backprop = True
.inputs = inputs self.outputs = [weakref.ref(output) for output in outputs] return outputs if len(outputs) > 1 else outputs[0] def forward(self, x): raise NotImplementedError() def backward(self, gy): raise NotImplementedError() class Config:
64
64
10
3
61
ck-ksst/deep-learning-from-scratch-3
steps/step18.py
Python
Config
Config
94
95
94
94
1064c7d2db5c56b318c82469d3ee301894d3692c
bigcode/the-stack
train
228a77eb21f068859121446e
train
class
class Square(Function): def forward(self, x): y = x ** 2 return y def backward(self, gy): x = self.inputs[0].data gx = 2 * x * gy return gx
class Square(Function):
def forward(self, x): y = x ** 2 return y def backward(self, gy): x = self.inputs[0].data gx = 2 * x * gy return gx
.ref(output) for output in outputs] return outputs if len(outputs) > 1 else outputs[0] def forward(self, x): raise NotImplementedError() def backward(self, gy): raise NotImplementedError() class Config: enable_backprop = True class Square(Function):
64
64
54
4
59
ck-ksst/deep-learning-from-scratch-3
steps/step18.py
Python
Square
Square
98
106
98
98
da00eee0f4ae194ae18121e7497ff6835620f99a
bigcode/the-stack
train
9ed457daf60d065d9864e4f7
train
class
class SquareTest(unittest.TestCase): def test_forward(self): x = Variable(np.array(2.0)) y = square(x) expected = np.array(4.0) self.assertEqual(y.data, expected) def test_backward(self): x = Variable(np.array(3.0)) y = square(x) y.backward() expe...
class SquareTest(unittest.TestCase):
def test_forward(self): x = Variable(np.array(2.0)) y = square(x) expected = np.array(4.0) self.assertEqual(y.data, expected) def test_backward(self): x = Variable(np.array(3.0)) y = square(x) y.backward() expected = np.array(6.0) self.ass...
e-4): x0 = Variable(x.data - eps) x1 = Variable(x.data + eps) y0 = f(x0) y1 = f(x1) return (y1.data - y0.data) / (2 * eps) class SquareTest(unittest.TestCase):
64
64
152
7
57
ck-ksst/deep-learning-from-scratch-3
steps/step18.py
Python
SquareTest
SquareTest
120
140
120
120
c36f0dc91e5a071457fabe3b6337d5c3653e240a
bigcode/the-stack
train
a07e48fbc81a1065c5ccd388
train
class
class GetAttribute(Function): """Get an attribute value of an entity defined in the service template Node template attributes values are set in runtime and therefore its the responsibility of the Tosca engine to implement the evaluation of get_attribute functions. Arguments: * Node template n...
class GetAttribute(Function):
"""Get an attribute value of an entity defined in the service template Node template attributes values are set in runtime and therefore its the responsibility of the Tosca engine to implement the evaluation of get_attribute functions. Arguments: * Node template name | HOST. * Attribute na...
therefore its the responsibility of the orchestrator/translator to take care of such functions invocation. :return: Function invocation result. """ return {self.name: self.args} @abc.abstractmethod def validate(self): """Validates function arguments.""" pass ...
245
245
818
5
240
spzala/tosca-parser
parser/elements/templates/functions.py
Python
GetAttribute
GetAttribute
92
193
92
92
a9a77f0cf7bb6c51fb7083cec45cfd214acd4f00
bigcode/the-stack
train
29b7488c5798d71a9dc7d2a0
train
function
def get_function(tosca_tpl, node_template, raw_function): """Gets a Function instance representing the provided template function. If the format provided raw_function format is not relevant for template functions or if the function name doesn't exist in function mapping the method returns the provided ...
def get_function(tosca_tpl, node_template, raw_function):
"""Gets a Function instance representing the provided template function. If the format provided raw_function format is not relevant for template functions or if the function name doesn't exist in function mapping the method returns the provided raw_function. :param tosca_tpl: The tosca template. ...
ca intrinsic function, otherwise False. """ if isinstance(function, dict) and len(function) == 1: func_name = list(function.keys())[0] return func_name in function_mappings return isinstance(function, Function) def get_function(tosca_tpl, node_template, raw_function):
64
64
210
14
50
spzala/tosca-parser
parser/elements/templates/functions.py
Python
get_function
get_function
357
378
357
357
db581aa407a04eaf31dbd937b5cb38e2e26ae9c8
bigcode/the-stack
train
22ab7b1ccc26b0ba369e7348
train
class
@six.add_metaclass(abc.ABCMeta) class Function(object): """An abstract type for representing a Tosca template function.""" def __init__(self, tosca_tpl, context, name, args): self.tosca_tpl = tosca_tpl self.context = context self.name = name self.args = args self.validat...
@six.add_metaclass(abc.ABCMeta) class Function(object):
"""An abstract type for representing a Tosca template function.""" def __init__(self, tosca_tpl, context, name, args): self.tosca_tpl = tosca_tpl self.context = context self.name = name self.args = args self.validate() @abc.abstractmethod def result(self): ...
textutils import _ GET_PROPERTY = 'get_property' GET_ATTRIBUTE = 'get_attribute' GET_INPUT = 'get_input' SELF = 'SELF' HOST = 'HOST' HOSTED_ON = 'tosca.relationships.HostedOn' @six.add_metaclass(abc.ABCMeta) class Function(object):
64
64
180
15
49
spzala/tosca-parser
parser/elements/templates/functions.py
Python
Function
Function
32
58
32
33
24cfc3d3c3df87c64b1000915b29b08514a261fe
bigcode/the-stack
train
f04f5dcde532782c91caa3ff
train
function
def is_function(function): """Returns True if the provided function is a Tosca intrinsic function. Examples: * "{ get_property: { SELF, port } }" * "{ get_input: db_name }" * Function instance :param function: Function as string or a Function instance. :return: True if function is a Tosca...
def is_function(function):
"""Returns True if the provided function is a Tosca intrinsic function. Examples: * "{ get_property: { SELF, port } }" * "{ get_input: db_name }" * Function instance :param function: Function as string or a Function instance. :return: True if function is a Tosca intrinsic function, otherw...
@property def req_or_cap(self): if len(self.args) > 2: return self.args[1] return None function_mappings = { GET_PROPERTY: GetProperty, GET_INPUT: GetInput, GET_ATTRIBUTE: GetAttribute } def is_function(function):
64
64
124
5
59
spzala/tosca-parser
parser/elements/templates/functions.py
Python
is_function
is_function
339
354
339
339
07a5af01c0edee8dbe1f82e8e0553cc8c16c59d9
bigcode/the-stack
train
6af58941a0a2db1bf6fa45af
train
class
class GetInput(Function): """Get a property value declared within the input of the service template. Arguments: * Input name. Example: * get_input: port """ def validate(self): if len(self.args) != 1: raise ValueError(_( 'Expected one argument for get...
class GetInput(Function):
"""Get a property value declared within the input of the service template. Arguments: * Input name. Example: * get_input: port """ def validate(self): if len(self.args) != 1: raise ValueError(_( 'Expected one argument for get_input function but receiv...
its the responsibility of the orchestrator/translator to take care of such functions invocation. :return: Function invocation result. """ return {self.name: self.args} @abc.abstractmethod def validate(self): """Validates function arguments.""" pass class GetInp...
64
64
180
5
58
spzala/tosca-parser
parser/elements/templates/functions.py
Python
GetInput
GetInput
61
89
61
61
2ad23557a863410080ff5aee4222f7ff8073bf2f
bigcode/the-stack
train
cb94316ef751ba4a0952ecb9
train
class
class GetProperty(Function): """Get a property value of an entity defined in the same service template. Arguments: * Node template name. * Requirement or capability name (optional). * Property name. If requirement or capability name is specified, the behavior is as follows: The req or cap...
class GetProperty(Function):
"""Get a property value of an entity defined in the same service template. Arguments: * Node template name. * Requirement or capability name (optional). * Property name. If requirement or capability name is specified, the behavior is as follows: The req or cap name is first looked up in t...
= self._find_node_template(node_template_name) from parser.elements.types.entitytype import EntityType hosted_on_rel = EntityType.TOSCA_DEF[HOSTED_ON] for r in node_template.requirements: for requirement, target_name in r.items(): target_node = self._find_node_templa...
256
256
1,039
5
251
spzala/tosca-parser
parser/elements/templates/functions.py
Python
GetProperty
GetProperty
196
329
196
196
3887413ecacb5230cd59fd2dd811f0262187eee3
bigcode/the-stack
train
4a854679351b98ee8f7dad77
train
function
def run_nonadd_calculation(args): """ Main routine to run the Nonadditivity calculations. run_control needs to have the following attributes: - infile (required) - outfile (optional) - props (can be empty) - units (as many as props or empty) - shorts (as many as props or empty) - max...
def run_nonadd_calculation(args):
""" Main routine to run the Nonadditivity calculations. run_control needs to have the following attributes: - infile (required) - outfile (optional) - props (can be empty) - units (as many as props or empty) - shorts (as many as props or empty) - max_heavy (required) - update (Bo...
enumerate(props): try: dat[cid, prp] = "{:.3g}".format(a["pAct"][idx]) except: continue with open(image_dat_path, "wb") as output_file: pickle.dump(dat, output_file) def run_nonadd_calculation(args):
64
64
192
8
56
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
run_nonadd_calculation
run_nonadd_calculation
1,153
1,180
1,153
1,153
9be81513fc20a93be13900c0f7c926677b2ced3d
bigcode/the-stack
train
2302c639f4769a3e97d0ce44
train
function
def get_circles(neighs): """ Assemble circle information """ print("Assembling circles") still_in = {key: True for key in neighs.keys()} neighbors = {key: [i[0] for i in dat] for key, dat in neighs.items()} trans = {} for key, dat in neighs.items(): for partner, T1 in dat: ...
def get_circles(neighs):
""" Assemble circle information """ print("Assembling circles") still_in = {key: True for key in neighs.keys()} neighbors = {key: [i[0] for i in dat] for key, dat in neighs.items()} trans = {} for key, dat in neighs.items(): for partner, T1 in dat: trans[key, partne...
[i[0] for i in neighs[id_lhs]].index(id_rhs) old_transf_len = len(neighs[id_lhs][id_rhs_idx][1]) if len(transf) < old_transf_len: neighs[id_lhs][id_rhs_idx] = (id_rhs, transf) else: neighs[id_lhs] = [(id_rhs, transf)] return neighs def get_ci...
99
99
331
9
89
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
get_circles
get_circles
150
193
150
150
8bcb65a92e6695d5b56e5e44f761ee8b57276f07
bigcode/the-stack
train
aff88055548077394c6925cc
train
function
def draw_image(ids, smiles, tsmarts, pActs, Acts, qualifiers, nonadd, target, mcss_tot, image_file): """ Draw Nonadditivity Circle to Image file """ cpds = [Chem.MolFromSmiles(i) for i in smiles] ######### # Compute Coordinates of local MCSS, aligned with global MCSS mcss_loc = Chem.MolFrom...
def draw_image(ids, smiles, tsmarts, pActs, Acts, qualifiers, nonadd, target, mcss_tot, image_file):
""" Draw Nonadditivity Circle to Image file """ cpds = [Chem.MolFromSmiles(i) for i in smiles] ######### # Compute Coordinates of local MCSS, aligned with global MCSS mcss_loc = Chem.MolFromSmarts( rdFMCS.FindMCS(cpds, completeRingsOnly=True, timeout=10).smartsString ) if m...
(nonadd_mixed), str(nonadd_cnt_mixed), "{:.2g}".format(nonadd_sd_mixed), ] else: outline = outline + ["", "", ""] g.write("\t".join(outline) + "\n") else: ...
256
256
1,994
30
226
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
draw_image
draw_image
551
754
551
551
0f6ffc1c51e05a446c1e93127cc082f56242970b
bigcode/the-stack
train
c442152a8c96db0137341d6e
train
function
def build_ligand_dictionary_from_infile( infile: str, error_path: str, props, units, *, delimiter=None, series_column=None, ): """ Read input file and assemble dictionaries """ if delimiter == "comma": delimiter = "," if delimiter == "tab" or delimiter is None: ...
def build_ligand_dictionary_from_infile( infile: str, error_path: str, props, units, *, delimiter=None, series_column=None, ):
""" Read input file and assemble dictionaries """ if delimiter == "comma": delimiter = "," if delimiter == "tab" or delimiter is None: delimiter = "\t" elif delimiter == "space": delimiter = " " elif delimiter == "semicolon": delimiter = ";" with open(inf...
+ " " + smifile ) else: print("Generating MMP Fragments") sp_call = ( "python -m mmpdblib fragment" + " --num-jobs 20 -i smi --delimiter tab " + " --max-rotatable-bonds 20 --output " + fragfile + " " ...
256
256
2,491
39
216
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
build_ligand_dictionary_from_infile
build_ligand_dictionary_from_infile
825
1,093
825
833
c518d891dcefb75fcf9ed29ffbf5cd4db489da9e
bigcode/the-stack
train
34019e8c2e355bb9a8cd7dc0
train
function
def read_raw_mmps(path): """ Read raw precalculated MMPs """ with open(path, "r") as f: mmps = f.readlines() return mmps
def read_raw_mmps(path):
""" Read raw precalculated MMPs """ with open(path, "r") as f: mmps = f.readlines() return mmps
_call = "python -m mmpdblib index" sp_call = sp_call + " --out csv --symmetric --output " + mmp_path + " " + fragfile subprocess.call(sp_call, shell=True) # Fragment_matching & Indexing def read_raw_mmps(path):
64
64
44
7
56
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
read_raw_mmps
read_raw_mmps
816
822
816
816
d926d73792f633196e28fb4811a124d7ddf065d2
bigcode/the-stack
train
3f2eb45b189d9540ad1a2158
train
function
def write_propdata_dict(meas, props, *, image_dat_path): """ Store property values for future image update """ dat = {} for cid, a in meas.items(): for idx, prp in enumerate(props): try: dat[cid, prp] = "{:.3g}".format(a["pAct"][idx]) except: ...
def write_propdata_dict(meas, props, *, image_dat_path):
""" Store property values for future image update """ dat = {} for cid, a in meas.items(): for idx, prp in enumerate(props): try: dat[cid, prp] = "{:.3g}".format(a["pAct"][idx]) except: continue with open(image_dat_path, "wb") as o...
+ " out of " + str(len(del_file)) + " previous images." ) for idx, delete in enumerate(del_file): if delete: os.remove(os.path.join(image_dir, image_files[idx])) def write_propdata_dict(meas, props, *, image_dat_path):
63
64
104
15
48
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
write_propdata_dict
write_propdata_dict
1,137
1,150
1,137
1,137
5d04f7727f76156a9fe61c6887a0f01562abfb5f
bigcode/the-stack
train
8f25f252465fb8295820f846
train
function
def is_number(s): try: float(s) return True except ValueError: return False
def is_number(s):
try: float(s) return True except ValueError: return False
Chem.MolFromSmiles(tsmarts[1][tsmarts[1].index(">") + 2 :]) new_im.paste(Draw.MolToImage(b, size=(50, 50)), (520, 300)) new_im.save(image_file) def is_number(s):
64
64
25
5
59
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
is_number
is_number
757
762
757
757
7fb2138879eebb4d11262f792c55f2d5538d2923
bigcode/the-stack
train
20360f5fab71e2e977f6c000
train
function
def numpy_std(values): return np.std(values)
def numpy_std(values):
return np.std(values)
= {"M": 1.0, "mM": 1e-3, "uM": 1e-6, "nM": 1e-9, "pM": 1e-12, "noconv": 1.0} def numpy_std(values):
64
64
11
5
59
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
numpy_std
numpy_std
52
53
52
52
2bf8d300b2c00a5082ea5581f703bdf5ebca3a67
bigcode/the-stack
train
62cae863fa1d555dc0245b10
train
function
def calc_raw_MMPs(*, update, fragfile, mmp_path, smifile): """ Generate MMP Indexing and Matching using mmpdb """ # TODO switch system calls to just importing the python code and using it directly if update: print("Updating MMP Fragments") sp_call = ( "python -m mmpdblib ...
def calc_raw_MMPs(*, update, fragfile, mmp_path, smifile):
""" Generate MMP Indexing and Matching using mmpdb """ # TODO switch system calls to just importing the python code and using it directly if update: print("Updating MMP Fragments") sp_call = ( "python -m mmpdblib fragment " + " --num-jobs 20 --delimiter tab --...
Chem.MolFromSmiles(meas[entry]["smiles"]) if mol.GetNumHeavyAtoms() > max_heavy: continue f.write(meas[entry]["smiles"] + "\t" + entry + "\n") except: print("Skipping compound", entry) continue def calc_raw_MMPs(*, update, ...
86
86
287
21
64
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
calc_raw_MMPs
calc_raw_MMPs
781
813
781
781
a82c90d52c2cd27c8a5cfc14f949fa10a61beeae
bigcode/the-stack
train
c220f49418e494080ed63264
train
function
def Sn_MedMed_std(values): """ Estimate the standard deviation based on the median of median pairwise differences as defined by Rousseeuw and Croux [1]: Sn = 1.1926 * med_i( med_j(abs(xi - xj))) [1] Rousseeuw, Peter J.; Croux, Christophe (December 1993), "Alternatives to the Median Absolute De...
def Sn_MedMed_std(values):
""" Estimate the standard deviation based on the median of median pairwise differences as defined by Rousseeuw and Croux [1]: Sn = 1.1926 * med_i( med_j(abs(xi - xj))) [1] Rousseeuw, Peter J.; Croux, Christophe (December 1993), "Alternatives to the Median Absolute Deviation", Journal of th...
a fast and simple robust SD estimator. However, it may have problems for small datasets where the average is not well estimated. """ median = np.median(values) ad = np.abs(values - median) mad = np.median(ad) return 1.4826 * mad def Sn_MedMed_std(values):
72
72
243
8
63
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
Sn_MedMed_std
Sn_MedMed_std
71
93
71
71
f615fa60f24f9610c4aa6329f5b3652a01bc8232
bigcode/the-stack
train
0b2044c6b8625b42dd50b3c9
train
function
def clean_image_folder(meas, props, *, image_dir, image_dat_path): """ Delete Cycle images where the properties have changed """ print("Deleting Cycle images where property values changed since last run.") image_files = os.listdir(image_dir) try: with open(image_dat_path, "rb") as oldp...
def clean_image_folder(meas, props, *, image_dir, image_dat_path):
""" Delete Cycle images where the properties have changed """ print("Deleting Cycle images where property values changed since last run.") image_files = os.listdir(image_dir) try: with open(image_dat_path, "rb") as oldprops_file: oldprops = pickle.load(oldprops_file) ...
]][1:])) else: print("Did not recognize number " + str(line[act_col[i]])) print(" in line: " + " ".join(line)) print("Please fix.") raise RuntimeError if len(units) == 0: units = ["noconv" fo...
96
96
322
17
78
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
clean_image_folder
clean_image_folder
1,096
1,134
1,096
1,096
e3b9f431baa3042b1761288d1a89ed3d78c7e029
bigcode/the-stack
train
c04d39bd078158c3d34f5f60
train
function
def build_neighbor_dictionary(mmps, no_chiral=False): """ Generate neighbor dictionary from calculated MMPs """ print("Analyzing neighborhoods") neighs = {} for line in mmps: smiles_lhs, smiles_rhs, id_lhs, id_rhs, transf, const = line.split("\t") if no_chiral and "@" in transf:...
def build_neighbor_dictionary(mmps, no_chiral=False):
""" Generate neighbor dictionary from calculated MMPs """ print("Analyzing neighborhoods") neighs = {} for line in mmps: smiles_lhs, smiles_rhs, id_lhs, id_rhs, transf, const = line.split("\t") if no_chiral and "@" in transf: continue var_lhs, var_rhs = trans...
1993), "Alternatives to the Median Absolute Deviation", Journal of the American Statistical Association, American Statistical Association, 88 (424): 1273–1283, doi:10.2307/2291267, JSTOR 2291267 """ pairwise_medians = np.empty(len(values)) for idx, i_value in enumerate(values): # Do I ...
175
175
585
12
162
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
build_neighbor_dictionary
build_neighbor_dictionary
96
147
96
96
8e4ce429c57fd79319d6de59cbec05f4f38080df
bigcode/the-stack
train
b3fc30a748ada46ef347fad9
train
function
def run_nonadd_calculation_helper( *, infile: Union[str, Path], directory: Optional[str] = None, units: Optional[List[str]] = None, props: Optional[List[str]] = None, update: bool = False, max_heavy: int = 70, no_chiral: bool = False, shorts: Optional[List[str]] = None, write_ima...
def run_nonadd_calculation_helper( *, infile: Union[str, Path], directory: Optional[str] = None, units: Optional[List[str]] = None, props: Optional[List[str]] = None, update: bool = False, max_heavy: int = 70, no_chiral: bool = False, shorts: Optional[List[str]] = None, write_ima...
if directory is None: directory = os.path.dirname(infile) error_path = os.path.join(directory, "problem_smiles.smi") fragment_path = os.path.join(directory, "fragments.jsonl") smi_path = os.path.join(directory, "ligands.smi") mmp_path = os.path.join(directory, "mmp_raw.tsv") image_dat_pa...
) """ return run_nonadd_calculation_helper( infile=args.infile, units=args.units, props=args.props, update=args.update, max_heavy=args.max_heavy, no_chiral=args.no_chiral, directory=args.directory, shorts=args.shorts, write_images=args.writ...
214
214
714
121
93
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
run_nonadd_calculation_helper
run_nonadd_calculation_helper
1,183
1,267
1,183
1,197
fb59e24bc99bbf09a2894248c74d0b54d23c7ed5
bigcode/the-stack
train
346466ab8d3ec9da2a6d509f
train
function
def mad_std(values): """ Estimate the standard deviation based on the median absolute deviation (MAD) In Gaussian distributions, SD = 1.4826 * MAD This is a fast and simple robust SD estimator. However, it may have problems for small datasets where the average is not well estimated. """ med...
def mad_std(values):
""" Estimate the standard deviation based on the median absolute deviation (MAD) In Gaussian distributions, SD = 1.4826 * MAD This is a fast and simple robust SD estimator. However, it may have problems for small datasets where the average is not well estimated. """ median = np.median(value...
M": 1e-3, "uM": 1e-6, "nM": 1e-9, "pM": 1e-12, "noconv": 1.0} def numpy_std(values): return np.std(values) def mad_std(values):
64
64
103
5
59
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
mad_std
mad_std
56
68
56
56
f5f8685eb4100c3040b0001029620af2ec1bbc44
bigcode/the-stack
train
8e3987ac58d9e36e548913e9
train
function
def write_circles_to_output( circles, meas, neighs, props, units, images=False, include_censored=False, update=False, series_column=None, *, images_dir, outfile: str, nonadd_percompound_file: str, circle_to_cpd_file: str, ): """ Get Diffs and write to outp...
def write_circles_to_output( circles, meas, neighs, props, units, images=False, include_censored=False, update=False, series_column=None, *, images_dir, outfile: str, nonadd_percompound_file: str, circle_to_cpd_file: str, ):
""" Get Diffs and write to output """ print("Writing Output.") ######### # Assemble header header = ( "Compound1\tCompound2\tCompound3\tCompound4\t" + "SMILES1\tSMILES2\tSMILES3\tSMILES4\tSeries\t" + "Transformation1\tTransformation2\tProperty\t" ) for i in...
ighs.keys()): still_in_2 = still_in.copy() for C2 in neighbors[C1]: if not still_in[C2]: continue for C3, C4 in trans_pairs[trans[C1, C2]]: if not still_in_2[C3]: continue if not still_in_2[C4]: ...
256
256
3,135
73
182
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
write_circles_to_output
write_circles_to_output
196
548
196
211
f2aebd2eb7242634cf1e3804a745e208b5478537
bigcode/the-stack
train
9db41ba7bc173db0e41558ad
train
function
def write_smiles_id_file(meas, max_heavy, *, smifile): """ Format dataset for MMP analysis and write to temp file """ with open(smifile, "w") as f: for entry in meas.keys(): try: mol = Chem.MolFromSmiles(meas[entry]["smiles"]) if mol.GetNumHeavyAtoms()...
def write_smiles_id_file(meas, max_heavy, *, smifile):
""" Format dataset for MMP analysis and write to temp file """ with open(smifile, "w") as f: for entry in meas.keys(): try: mol = Chem.MolFromSmiles(meas[entry]["smiles"]) if mol.GetNumHeavyAtoms() > max_heavy: continue ...
, size=(50, 50)), (520, 300)) new_im.save(image_file) def is_number(s): try: float(s) return True except ValueError: return False def write_smiles_id_file(meas, max_heavy, *, smifile):
64
64
126
18
45
KramerChristian/NonadditivityAnalysis
src/nonadditivity/api.py
Python
write_smiles_id_file
write_smiles_id_file
765
778
765
765
5ee8e7547b643c0613f663887cf6a6ac3f1d794d
bigcode/the-stack
train
6bc0204c003706b6ab57a30d
train
function
def get_examples(): examples_repo = "MODFLOW-USGS/modflow6-examples" version = pymake.repo_latest_version( github_repo=examples_repo, verify=VERIFY ) print("current examples version: {}".format(version)) url = "https://github.com/{}".format( examples_repo ) + "/releases/download/...
def get_examples():
examples_repo = "MODFLOW-USGS/modflow6-examples" version = pymake.repo_latest_version( github_repo=examples_repo, verify=VERIFY ) print("current examples version: {}".format(version)) url = "https://github.com/{}".format( examples_repo ) + "/releases/download/{}/modflow6-examples...
time_sec = 0.0 t = elt_str.split() for idx in range(0, len(t), 2): t0 = float(t[idx]) time_sec += t0 * time_factor(t[idx + 1].lower()) return time_sec def get_examples():
64
64
188
4
59
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
get_examples
get_examples
194
211
194
194
2aa627dc14f6c023d17be64e59f7d90057cac2c6
bigcode/the-stack
train
587bdb77e098b30028ff4426
train
function
def elapsed_string_to_real(elt_str): time_sec = 0.0 t = elt_str.split() for idx in range(0, len(t), 2): t0 = float(t[idx]) time_sec += t0 * time_factor(t[idx + 1].lower()) return time_sec
def elapsed_string_to_real(elt_str):
time_sec = 0.0 t = elt_str.split() for idx in range(0, len(t), 2): t0 = float(t[idx]) time_sec += t0 * time_factor(t[idx + 1].lower()) return time_sec
): if "hours" in time_unit: factor = 60.0 * 60.0 elif "minutes" in time_unit: factor = 60.0 else: factor = 1.0 return factor def elapsed_string_to_real(elt_str):
64
64
69
9
54
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
elapsed_string_to_real
elapsed_string_to_real
185
191
185
185
e92fdc0561396d05775f0777553a4d2f29c3624e
bigcode/the-stack
train
bb1023be8e4c95cff2468c61
train
function
def get_elapsed_time(buff, tag="Elapsed run time:"): elt_str = "" for line in buff: if tag in line: i0 = line.index(":") elt_str = line[i0 + 1 :].strip() return elt_str
def get_elapsed_time(buff, tag="Elapsed run time:"):
elt_str = "" for line in buff: if tag in line: i0 = line.index(":") elt_str = line[i0 + 1 :].strip() return elt_str
pth, "w") as f: for line in lines: if replace[0] in line.lower(): line = line.lower().replace( replace[0], replace[1] ) f.write(line) re...
64
64
57
13
50
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
get_elapsed_time
get_elapsed_time
166
172
166
166
3131d5fce4e6cb510220d9d2bebdda2cb233d940
bigcode/the-stack
train
2e4a7a52bd19e0ced631ddb2
train
function
def run_model(app, app0, example, fmd, silent=True, pool=False): id0 = example.index(examples_dir) + len(examples_dir) + 1 test = example[id0:] print("Running simulation: {}".format(test)) line = "| {} |".format(test) # copy directory for previous application prev_dir = os.path.join(example, "p...
def run_model(app, app0, example, fmd, silent=True, pool=False):
id0 = example.index(examples_dir) + len(examples_dir) + 1 test = example[id0:] print("Running simulation: {}".format(test)) line = "| {} |".format(test) # copy directory for previous application prev_dir = os.path.join(example, "previous") if os.path.isdir(prev_dir): shutil.rmtree(p...
, examples_dir) if not _is_dryrun(): pymake.download_and_unzip(url, pth=pth, verbose=True, verify=VERIFY) example_files = [] for root, dirs, files in os.walk(pth): fpth = os.path.join(root, "mfsim.nam") if os.path.exists(fpth): example_files.append(os.path.abspath(root)) ...
146
146
489
19
127
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
run_model
run_model
224
294
224
224
3268a3753152cd7f77d72d92239822dae577483e
bigcode/the-stack
train
2859c481ca7df832fdf85fa6
train
function
def build_current_version(): if not _is_dryrun(): build_mf6(appdir=working_dir) return os.path.abspath(os.path.join(working_dir, "mf6{}".format(app_ext)))
def build_current_version():
if not _is_dryrun(): build_mf6(appdir=working_dir) return os.path.abspath(os.path.join(working_dir, "mf6{}".format(app_ext)))
appdir = os.path.join(pth, "bin") if not _is_dryrun(): build_mf6(srcdir=srcdir, appdir=appdir) return os.path.abspath(os.path.join(appdir, "mf6{}".format(app_ext))) def build_current_version():
63
64
45
5
58
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
build_current_version
build_current_version
83
86
83
83
7f13996f7f61c4010033a0037ac8c9bc6b2b835e
bigcode/the-stack
train
c1cc318f5bd5faf4b6f296ef
train
function
def build_previous_version(pth): _del_version() srcdir = os.path.join(pth, "src") appdir = os.path.join(pth, "bin") if not _is_dryrun(): build_mf6(srcdir=srcdir, appdir=appdir) return os.path.abspath(os.path.join(appdir, "mf6{}".format(app_ext)))
def build_previous_version(pth):
_del_version() srcdir = os.path.join(pth, "src") appdir = os.path.join(pth, "bin") if not _is_dryrun(): build_mf6(srcdir=srcdir, appdir=appdir) return os.path.abspath(os.path.join(appdir, "mf6{}".format(app_ext)))
/{0}/mf{0}.zip".format(version) if not _is_dryrun(): pymake.download_and_unzip( url, pth=working_dir, verbose=True, verify=VERIFY ) return version, "mf{}".format(version) def build_previous_version(pth):
64
64
83
7
57
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
build_previous_version
build_previous_version
73
80
73
73
709aec2d3b11fed3137ff9e0b13331da3d55bf45
bigcode/the-stack
train
2b635c178de386b9e38c56ef
train
function
def time_factor(time_unit): if "hours" in time_unit: factor = 60.0 * 60.0 elif "minutes" in time_unit: factor = 60.0 else: factor = 1.0 return factor
def time_factor(time_unit):
if "hours" in time_unit: factor = 60.0 * 60.0 elif "minutes" in time_unit: factor = 60.0 else: factor = 1.0 return factor
def get_elapsed_time(buff, tag="Elapsed run time:"): elt_str = "" for line in buff: if tag in line: i0 = line.index(":") elt_str = line[i0 + 1 :].strip() return elt_str def time_factor(time_unit):
64
64
60
6
57
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
time_factor
time_factor
175
182
175
175
19e917f2617ab8ecd002b97abfbdcaae6f988f17
bigcode/the-stack
train
c98ba0ef995975cf777046f0
train
function
def get_mf6_version(app, verbose=False): text = "mf6:" if app.endswith(".exe"): text = "mf6.exe:" version = get_mf6_cmdargs(app, [app, "-v"], text=text, verbose=verbose) if version is not None: version = version.split()[0] if verbose: print("version: {}".format(versio...
def get_mf6_version(app, verbose=False):
text = "mf6:" if app.endswith(".exe"): text = "mf6.exe:" version = get_mf6_cmdargs(app, [app, "-v"], text=text, verbose=verbose) if version is not None: version = version.split()[0] if verbose: print("version: {}".format(version)) return version
.rstrip("\r\n") if verbose: print("{}".format(c)) if text in c: idx0 = c.index(text) + len(text) + 1 return_text = c[idx0:].strip() return return_text def get_mf6_version(app, verbose=False):
64
64
89
11
52
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
get_mf6_version
get_mf6_version
109
118
109
109
34006a8466426a7743c7a2591b507ae9c1ea0127
bigcode/the-stack
train
40ae6f31298cf202451f2a0d
train
function
def _del_version(): i0 = None for idx, arg in enumerate(sys.argv): if arg == "--version": i0 = idx break if i0 is not None: del sys.argv[i0 : i0 + 2]
def _del_version():
i0 = None for idx, arg in enumerate(sys.argv): if arg == "--version": i0 = idx break if i0 is not None: del sys.argv[i0 : i0 + 2]
, arg in enumerate(sys.argv): if arg == "--version": version = sys.argv[idx + 1] break if version is None: version = pymake.repo_latest_version( github_repo=github_repo, verify=VERIFY ) return version def _del_version():
64
64
58
5
58
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
_del_version
_del_version
37
44
37
37
833add3cf50556f9c6964815134117e139f4763c
bigcode/the-stack
train
559c5e83b23e214a63ed30cc
train
function
def get_mf6_cmdargs(app, argv, text="mf6:", verbose=False): return_text = None proc = subprocess.Popen( argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(app), ) result, error = proc.communicate() if result is not None: c = result.decod...
def get_mf6_cmdargs(app, argv, text="mf6:", verbose=False):
return_text = None proc = subprocess.Popen( argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(app), ) result, error = proc.communicate() if result is not None: c = result.decode("utf-8") c = c.rstrip("\r\n") if verbose: ...
build_current_version(): if not _is_dryrun(): build_mf6(appdir=working_dir) return os.path.abspath(os.path.join(working_dir, "mf6{}".format(app_ext))) def get_mf6_cmdargs(app, argv, text="mf6:", verbose=False):
63
64
136
19
44
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
get_mf6_cmdargs
get_mf6_cmdargs
89
106
89
89
329652f71bd4aa5274cb410d61cc15fcf7607bec
bigcode/the-stack
train
b041b4fd1d7d017cf7847a54
train
function
def _get_download_dir(): return "mf{}".format(_get_version())
def _get_download_dir():
return "mf{}".format(_get_version())
del sys.argv[i0 : i0 + 2] def _is_dryrun(): dryrun = False for idx, arg in enumerate(sys.argv): if arg == "--dryrun": dryrun = True break return dryrun def _get_download_dir():
64
64
16
6
57
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
_get_download_dir
_get_download_dir
56
57
56
56
3c30eba14f8b6f9d5839eb9699a3ab5ef4726763
bigcode/the-stack
train
a0d8de89d1889eb4f860033b
train
function
def run_function(app, example): return flopy.run_model( app, None, model_ws=example, silent=True, report=True, )
def run_function(app, example):
return flopy.run_model( app, None, model_ws=example, silent=True, report=True, )
example_files = [] for root, dirs, files in os.walk(pth): fpth = os.path.join(root, "mfsim.nam") if os.path.exists(fpth): example_files.append(os.path.abspath(root)) return sorted(example_files) def run_function(app, example):
64
64
36
7
57
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
run_function
run_function
214
221
214
214
e75d7846ea58625b60ee1590517b71d0a1b7e494
bigcode/the-stack
train
6393c8c6539a883137e32994
train
function
def cleanup(): b = None if not _is_dryrun(): b = True return
def cleanup():
b = None if not _is_dryrun(): b = True return
{:.2%} |".format(pd) else: line += " -- |" fmd.write("{}\n".format(line)) fmd.flush() # clean up previous directory if os.path.isdir(prev_dir): shutil.rmtree(prev_dir) return success def cleanup():
64
64
25
3
60
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
cleanup
cleanup
297
301
297
297
2bdd6720b1de306e36f6db8cefd5674827630901
bigcode/the-stack
train
5caec5264b016265e42d53b6
train
function
def get_mf6_compiler(app, verbose=False): text = "mf6:" if app.endswith(".exe"): text = "mf6.exe:" compiler = get_mf6_cmdargs(app, [app, "-c"], text=text, verbose=verbose) if verbose and compiler is not None: print("compiler: {}".format(compiler)) return compiler
def get_mf6_compiler(app, verbose=False):
text = "mf6:" if app.endswith(".exe"): text = "mf6.exe:" compiler = get_mf6_cmdargs(app, [app, "-c"], text=text, verbose=verbose) if verbose and compiler is not None: print("compiler: {}".format(compiler)) return compiler
_mf6_cmdargs(app, [app, "-v"], text=text, verbose=verbose) if version is not None: version = version.split()[0] if verbose: print("version: {}".format(version)) return version def get_mf6_compiler(app, verbose=False):
64
64
81
12
51
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
get_mf6_compiler
get_mf6_compiler
121
128
121
121
a71774fd0e6528b190204707be26ea00d350f20e
bigcode/the-stack
train
d7c8226ced8df1b2c775b23c
train
function
def _get_previous_version(): version = _get_version() url = "https://github.com/{}".format( github_repo ) + "/releases/download/{0}/mf{0}.zip".format(version) if not _is_dryrun(): pymake.download_and_unzip( url, pth=working_dir, verbose=True, verify=VERIFY ) retu...
def _get_previous_version():
version = _get_version() url = "https://github.com/{}".format( github_repo ) + "/releases/download/{0}/mf{0}.zip".format(version) if not _is_dryrun(): pymake.download_and_unzip( url, pth=working_dir, verbose=True, verify=VERIFY ) return version, "mf{}".format(ver...
_dryrun(): dryrun = False for idx, arg in enumerate(sys.argv): if arg == "--dryrun": dryrun = True break return dryrun def _get_download_dir(): return "mf{}".format(_get_version()) def _get_previous_version():
64
64
93
6
58
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
_get_previous_version
_get_previous_version
60
70
60
60
43c5666eb51e6df3f10c5b4599e0d558d49d3a93
bigcode/the-stack
train
81ad2479c909e89f2d7c966c
train
function
def revert_files(app, example): replace_dict = { ".ims": { (6, 1, 1): ("dvclose", "hclose"), } } extensions = list(replace_dict.keys()) # get current version version = get_mf6_version(app) if version is not None: version = tuple([int(v) for v in version.split...
def revert_files(app, example):
replace_dict = { ".ims": { (6, 1, 1): ("dvclose", "hclose"), } } extensions = list(replace_dict.keys()) # get current version version = get_mf6_version(app) if version is not None: version = tuple([int(v) for v in version.split(".")]) # get a list of fil...
:" if app.endswith(".exe"): text = "mf6.exe:" compiler = get_mf6_cmdargs(app, [app, "-c"], text=text, verbose=verbose) if verbose and compiler is not None: print("compiler: {}".format(compiler)) return compiler def revert_files(app, example):
70
70
234
7
62
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
revert_files
revert_files
131
163
131
131
2ec3866225fb0c6b9f8def24abbd8585278b9291
bigcode/the-stack
train
b049a4d905473bae6924e53b
train
function
def _get_version(): version = None for idx, arg in enumerate(sys.argv): if arg == "--version": version = sys.argv[idx + 1] break if version is None: version = pymake.repo_latest_version( github_repo=github_repo, verify=VERIFY ) return version
def _get_version():
version = None for idx, arg in enumerate(sys.argv): if arg == "--version": version = sys.argv[idx + 1] break if version is None: version = pymake.repo_latest_version( github_repo=github_repo, verify=VERIFY ) return version
", "autotest")) from build_exes import build_mf6 github_repo = "MODFLOW-USGS/modflow6" working_dir = "./temp/" examples_dir = "examples" app_ext = "" if sys.platform == "win32": app_ext = ".exe" def _get_version():
64
64
72
5
59
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
_get_version
_get_version
24
34
24
24
d6448cefece1b68ad7e5acd359bd9e8044b0f5fd
bigcode/the-stack
train
017dc4a1807b8a9611a5e3d2
train
function
def _is_dryrun(): dryrun = False for idx, arg in enumerate(sys.argv): if arg == "--dryrun": dryrun = True break return dryrun
def _is_dryrun():
dryrun = False for idx, arg in enumerate(sys.argv): if arg == "--dryrun": dryrun = True break return dryrun
_del_version(): i0 = None for idx, arg in enumerate(sys.argv): if arg == "--version": i0 = idx break if i0 is not None: del sys.argv[i0 : i0 + 2] def _is_dryrun():
64
64
45
7
57
jmccreight/modflow6
distribution/evaluate_run_times.py
Python
_is_dryrun
_is_dryrun
47
53
47
47
94469f88f25f307a8ed763865db91772f82f459b
bigcode/the-stack
train
07932af782786fe1e80b29ea
train
function
def repositoryForked(): config = getConfig() repo_map = config['repomap'] session = giteaSession() gh = ghApi() for repo in gh.get_user().get_repos(): if repo.fork: real_repo = repo.full_name.split('/')[1] gitea_dest_user = repo.owner.login repo_owner=rep...
def repositoryForked():
config = getConfig() repo_map = config['repomap'] session = giteaSession() gh = ghApi() for repo in gh.get_user().get_repos(): if repo.fork: real_repo = repo.full_name.split('/')[1] gitea_dest_user = repo.owner.login repo_owner=repo.owner.login ...
#!/usr/bin/env python # https://github.com/PyGithub/PyGithub from helper import log,getConfig,giteaCreateUserOrOrg,giteaSetRepoTopics,giteaSession,giteaCreateRepo,ghApi,giteaCreateOrg,giteaGetUser,config from github import GithubException from localCacheHelper import giteaExistsRepos,saveLocalCache def repositoryForked...
88
121
404
5
82
chmac/github-gitea-mirror
src/repositoryForked.py
Python
repositoryForked
repositoryForked
7
56
7
7
d8c64def8cf88dcc1f78063bc7b2d0989d34d22c
bigcode/the-stack
train
dc88b09ff3a592a0fe07dd84
train
function
def sample_HOD(): ''' sample HOD value based on priors set by Parejko+(2013) ''' hod_min = np.array([13.2, 0.4, 13.1, 14., 0.7]) dhod = np.array([0.15, 0.1, 0.4, 0.3, 0.4]) _hod = hod_min + 0.5 * dhod + 0.1 * dhod * np.random.normal(size=(5)) return {'logMmin': _hod[0], 'sigma_logM': _hod[1], '...
def sample_HOD():
''' sample HOD value based on priors set by Parejko+(2013) ''' hod_min = np.array([13.2, 0.4, 13.1, 14., 0.7]) dhod = np.array([0.15, 0.1, 0.4, 0.3, 0.4]) _hod = hod_min + 0.5 * dhod + 0.1 * dhod * np.random.normal(size=(5)) return {'logMmin': _hod[0], 'sigma_logM': _hod[1], 'logM0': _hod[2], 'l...
halos as Halos from simbig import galaxies as Galaxies from simbig import forwardmodel as FM np.random.seed(1) i0 = int(sys.argv[1]) i1 = int(sys.argv[2]) zred = float(sys.argv[3]) def sample_HOD():
64
64
167
6
58
muntazirabidi/boss-sbi
bin/make_hod_fid.py
Python
sample_HOD
sample_HOD
22
28
22
22
ea8e53d78b990a60f597f3263105485bf79aae50
bigcode/the-stack
train
f56455b395a9635311607508
train
class
class _PartialAppInfoOptional(TypedDict, total=False): rpc_origins: List[str] cover_image: str hook: bool terms_of_service_url: str privacy_policy_url: str max_participants: int flags: int
class _PartialAppInfoOptional(TypedDict, total=False):
rpc_origins: List[str] cover_image: str hook: bool terms_of_service_url: str privacy_policy_url: str max_participants: int flags: int
hook: bool max_participants: int class AppInfo(BaseAppInfo, _AppInfoOptional): rpc_origins: List[str] owner: User bot_public: bool bot_require_code_grant: bool class _PartialAppInfoOptional(TypedDict, total=False):
64
64
59
13
50
Alcamoru/discord.py
discord/types/appinfo.py
Python
_PartialAppInfoOptional
_PartialAppInfoOptional
61
68
61
61
abd6dfcf0f084204645c9964a4a6b524028fcd67
bigcode/the-stack
train
b6e5732e1018de729adc8ba9
train
class
class AppInfo(BaseAppInfo, _AppInfoOptional): rpc_origins: List[str] owner: User bot_public: bool bot_require_code_grant: bool
class AppInfo(BaseAppInfo, _AppInfoOptional):
rpc_origins: List[str] owner: User bot_public: bool bot_require_code_grant: bool
team: Team guild_id: Snowflake primary_sku_id: Snowflake slug: str terms_of_service_url: str privacy_policy_url: str hook: bool max_participants: int class AppInfo(BaseAppInfo, _AppInfoOptional):
64
64
40
12
51
Alcamoru/discord.py
discord/types/appinfo.py
Python
AppInfo
AppInfo
54
58
54
54
b1cd2fb58827749ed3a63e32acd7c8603a11a6c7
bigcode/the-stack
train
a5a6a2410d3ba71928ce2672
train
class
class PartialAppInfo(_PartialAppInfoOptional, BaseAppInfo): pass
class PartialAppInfo(_PartialAppInfoOptional, BaseAppInfo):
pass
, total=False): rpc_origins: List[str] cover_image: str hook: bool terms_of_service_url: str privacy_policy_url: str max_participants: int flags: int class PartialAppInfo(_PartialAppInfoOptional, BaseAppInfo):
64
64
17
14
49
Alcamoru/discord.py
discord/types/appinfo.py
Python
PartialAppInfo
PartialAppInfo
71
72
71
71
e1c692a8ee1b13efa89ddbc608ef01718296cef1
bigcode/the-stack
train
8924f75edd4a94d925c3cac5
train
class
class BaseAppInfo(TypedDict): id: Snowflake name: str verify_key: str icon: Optional[str] summary: str description: str
class BaseAppInfo(TypedDict):
id: Snowflake name: str verify_key: str icon: Optional[str] summary: str description: str
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import annotations from typing import TypedDict, List, Optional from .snowflake import Snowflake from .team import Team from .user import User class BaseAppInfo(TypedDict):
64
64
41
8
55
Alcamoru/discord.py
discord/types/appinfo.py
Python
BaseAppInfo
BaseAppInfo
34
40
34
34
56d28189b66d02ae94ef08f7a24fdbb45d68f237
bigcode/the-stack
train
fec952bee02af74f7f3a297f
train
class
class _AppInfoOptional(TypedDict, total=False): team: Team guild_id: Snowflake primary_sku_id: Snowflake slug: str terms_of_service_url: str privacy_policy_url: str hook: bool max_participants: int
class _AppInfoOptional(TypedDict, total=False):
team: Team guild_id: Snowflake primary_sku_id: Snowflake slug: str terms_of_service_url: str privacy_policy_url: str hook: bool max_participants: int
.team import Team from .user import User class BaseAppInfo(TypedDict): id: Snowflake name: str verify_key: str icon: Optional[str] summary: str description: str class _AppInfoOptional(TypedDict, total=False):
64
64
65
12
51
Alcamoru/discord.py
discord/types/appinfo.py
Python
_AppInfoOptional
_AppInfoOptional
43
51
43
43
f0302cb0ff1d8150f620ed4244ad0cf28ae99706
bigcode/the-stack
train
abb0bcbf711cab05d2d2bd8e
train
class
class TestSchismVerticalMesh(unittest.TestCase): def setUp(self): self.dir_cur = os.path.dirname(__file__) def check_vmesh_lsc2_1(self, vmesh): self.assertEqual(vmesh.ivcor, 1) self.assertEqual(vmesh.n_vert_levels(), 48) self.assertEqual(len(vmesh.sigma), 6) self.assert...
class TestSchismVerticalMesh(unittest.TestCase):
def setUp(self): self.dir_cur = os.path.dirname(__file__) def check_vmesh_lsc2_1(self, vmesh): self.assertEqual(vmesh.ivcor, 1) self.assertEqual(vmesh.n_vert_levels(), 48) self.assertEqual(len(vmesh.sigma), 6) self.assertEqual(vmesh.kbps[0], 42) self.assertEqual(...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ unit tests of schism_vertical_mesh """ from schimpy.schism_vertical_mesh import SchismLocalVerticalMesh, read_vmesh, write_vmesh from schimpy.schism_mesh import read_mesh import numpy as np import unittest import os class TestSchismVerticalMesh(unittest.TestCase):
79
198
662
10
68
CADWRDeltaModeling/schimpy
tests/test_schism_vertical_mesh.py
Python
TestSchismVerticalMesh
TestSchismVerticalMesh
12
69
12
13
1eed10957a1c809e4b64223ed37d0853820d4045
bigcode/the-stack
train
798cfbb31bc801e6d8df2eac
train
class
@define(auto_attribs=False, slots=False) class CachedHTTPResponse(HTTPResponse): """A serializable dataclass that emulates :py:class:`~urllib3.response.HTTPResponse`. Supports streaming requests and generator usage. The only action this doesn't support is explicitly calling :py:meth:`.read` with ``deco...
@define(auto_attribs=False, slots=False) class CachedHTTPResponse(HTTPResponse):
"""A serializable dataclass that emulates :py:class:`~urllib3.response.HTTPResponse`. Supports streaming requests and generator usage. The only action this doesn't support is explicitly calling :py:meth:`.read` with ``decode_content=False``. """ decode_content: bool = field(default=None) h...
from io import BytesIO from logging import getLogger from typing import Mapping from attr import define, field, fields_dict from requests import Response from urllib3.response import HTTPHeaderDict, HTTPResponse, is_fp_closed logger = getLogger(__name__) @define(auto_attribs=False, slots=False) class CachedHTTPRespon...
74
227
757
19
55
meggiman/requests-cache
requests_cache/models/raw_response.py
Python
CachedHTTPResponse
CachedHTTPResponse
12
94
12
13
54e9dca7de85dfc427fac710aae010750c4f4c63
bigcode/the-stack
train
05dff13e112f8279444ff290
train
function
def main(): from .cli import cli cli()
def main():
from .cli import cli cli()
#!/usr/bin/env python # -*- coding: utf-8 -*- def main():
17
64
13
3
14
Sebastian-Hojas/itunesdiff
itunesdiff/__main__.py
Python
main
main
4
6
4
4
6ddfafe64e0dc19a1005deecd2d9b848dbce6b00
bigcode/the-stack
train
7e74ecaf50da06d68b1336fd
train
function
def set_default_security_headers(website, response, request=None): # Allow CORS for assets # The subdomains need this to access the assets on the main domain. if request is not None and request.path.raw.startswith('/assets/'): response.headers[b'Access-Control-Allow-Origin'] = b'*' # X-Frame-Op...
def set_default_security_headers(website, response, request=None): # Allow CORS for assets # The subdomains need this to access the assets on the main domain.
if request is not None and request.path.raw.startswith('/assets/'): response.headers[b'Access-Control-Allow-Origin'] = b'*' # X-Frame-Options is a security measure to prevent clickjacking # See http://en.wikipedia.org/wiki/Clickjacking response.headers[b'X-Frame-Options'] = b'SAMEORIGIN' #...
def set_default_security_headers(website, response, request=None): # Allow CORS for assets # The subdomains need this to access the assets on the main domain.
37
99
331
37
0
liberapay/liberapay.com
liberapay/security/__init__.py
Python
set_default_security_headers
set_default_security_headers
2
25
2
4
3eb44f503fc226265b656d14d2ae912a1b90038a
bigcode/the-stack
train
28acd4c5ef46d720fc6897ae
train
class
class TestOnnx(TestCase): def test_trainer_trace_onnx(self): model = ResNet18(10, pretrained=False, include_top=False, freeze=True) loss = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.01) trainer = Trainer(max_epochs=1) pl_model = Trainer.compi...
class TestOnnx(TestCase):
def test_trainer_trace_onnx(self): model = ResNet18(10, pretrained=False, include_top=False, freeze=True) loss = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.01) trainer = Trainer(max_epochs=1) pl_model = Trainer.compile(model, loss, optimizer)...
num_classes, pretrained=True, include_top=False, freeze=True): super().__init__() backbone = vision.resnet18(pretrained=pretrained, include_top=include_top, freeze=freeze) output_size = backbone.get_output_size() head = nn.Linear(output_size, num_classes) self.model = nn.Sequent...
216
216
723
7
209
Forest216/BigDL
python/nano/test/onnx/pytorch/test_onnx.py
Python
TestOnnx
TestOnnx
66
134
66
66
591f129e438a783fe9dd8210cd295f0223fb7712
bigcode/the-stack
train
57481d47b0a02f831abc8638
train
class
class MultiInputModel(nn.Module): def __init__(self): super().__init__() self.layer_1 = nn.Linear(28 * 28, 128) self.layer_2 = nn.Linear(28 * 28, 128) self.layer_3 = nn.Linear(256, 2) def forward(self, x1, x2): x1 = self.layer_1(x1) x2 = self.layer_2(x2) ...
class MultiInputModel(nn.Module):
def __init__(self): super().__init__() self.layer_1 = nn.Linear(28 * 28, 128) self.layer_2 = nn.Linear(28 * 28, 128) self.layer_3 = nn.Linear(256, 2) def forward(self, x1, x2): x1 = self.layer_1(x1) x2 = self.layer_2(x2) x = torch.cat([x1, x2], axis=1) ...
pretrained, include_top=include_top, freeze=freeze) output_size = backbone.get_output_size() head = nn.Linear(output_size, num_classes) self.model = nn.Sequential(backbone, head) def forward(self, x): return self.model(x) class MultiInputModel(nn.Module):
64
64
124
7
57
Forest216/BigDL
python/nano/test/onnx/pytorch/test_onnx.py
Python
MultiInputModel
MultiInputModel
50
63
50
50
68c3ebed32486023b639e14fbdc0a736825eb9d3
bigcode/the-stack
train
54801e337bbf8610f7095fba
train
class
class ResNet18(nn.Module): def __init__(self, num_classes, pretrained=True, include_top=False, freeze=True): super().__init__() backbone = vision.resnet18(pretrained=pretrained, include_top=include_top, freeze=freeze) output_size = backbone.get_output_size() head = nn.Linear(output_s...
class ResNet18(nn.Module):
def __init__(self, num_classes, pretrained=True, include_top=False, freeze=True): super().__init__() backbone = vision.resnet18(pretrained=pretrained, include_top=include_top, freeze=freeze) output_size = backbone.get_output_size() head = nn.Linear(output_size, num_classes) s...
import torchmetrics import numpy as np from bigdl.nano.pytorch import Trainer from bigdl.nano.pytorch.vision.models import vision batch_size = 256 num_workers = 0 data_dir = os.path.join(os.path.dirname(__file__), "data") class ResNet18(nn.Module):
64
64
99
7
57
Forest216/BigDL
python/nano/test/onnx/pytorch/test_onnx.py
Python
ResNet18
ResNet18
38
47
38
38
9fd3ab794c043fc537436c3ed4df68ad520ce46b
bigcode/the-stack
train
9189f9e94d838a13c667291c
train
function
def get(title, artist, album=''): providers = [ ProviderAzLyrics(), ProviderDarkLyrics(), ProviderGenius(), ProviderMetrolyrics(), ProviderMusicmatch(), ] random.shuffle(providers) for provider in providers: lyrics = provider.get_lyrics(title, artist, alb...
def get(title, artist, album=''):
providers = [ ProviderAzLyrics(), ProviderDarkLyrics(), ProviderGenius(), ProviderMetrolyrics(), ProviderMusicmatch(), ] random.shuffle(providers) for provider in providers: lyrics = provider.get_lyrics(title, artist, album) if lyrics: ...
from .provider_azlyrics import ProviderAzLyrics from .provider_darklyrics import ProviderDarkLyrics from .provider_genius import ProviderGenius from .provider_metrolyrics import ProviderMetrolyrics from .provider_musixmatch import ProviderMusicmatch def get(title, artist, album=''):
64
64
122
9
54
vedard/MusicPlayer
mokaplayer/core/fetchers/lyrics/__init__.py
Python
get
get
11
29
11
11
f719198ce7a380bdfc34403c45542fb3f4f38ea4
bigcode/the-stack
train
9dbd89eb1e625da0a461762d
train
function
def _read_netcdf_grid_shape(root): """Get the shape of a raster grid. Parameters ---------- root : netcdf_file A NetCDF object. Returns ------- (rows, columns) Shape of the grid. """ shape = [] for axis_name in _AXIS_DIMENSION_NAMES: try: sha...
def _read_netcdf_grid_shape(root):
"""Get the shape of a raster grid. Parameters ---------- root : netcdf_file A NetCDF object. Returns ------- (rows, columns) Shape of the grid. """ shape = [] for axis_name in _AXIS_DIMENSION_NAMES: try: shape.append(_length_of_axis_dimension...
Name of the axis in the NetCDF file. Returns ------- int Size of the dimension. """ try: return len(root.dimensions[axis_name]) except TypeError: return root.dimensions[axis_name] def _read_netcdf_grid_shape(root):
64
64
102
10
54
elbeejay/landlab
landlab/io/netcdf/read.py
Python
_read_netcdf_grid_shape
_read_netcdf_grid_shape
49
68
49
49
6670e483d55a70711c563d6125ed97ae9ae4ca79
bigcode/the-stack
train
91230eb3d574846af9161776
train
function
def _read_netcdf_structured_data(root): """Get data values for a structured grid. Parameters ---------- root : netcdf_file A NetCDF file. Returns ------- dict Data values, reshaped to match that of the grid. Keys are the variable names as read from the NetCDF file. ...
def _read_netcdf_structured_data(root):
"""Get data values for a structured grid. Parameters ---------- root : netcdf_file A NetCDF file. Returns ------- dict Data values, reshaped to match that of the grid. Keys are the variable names as read from the NetCDF file. """ fields = dict() grid_map...
the grid. """ shape = _read_netcdf_grid_shape(root) coordinates = _read_netcdf_coordinate_values(root) if len(coordinates) != 2: assert ValueError("Rasters must have only two spatial coordinate dimensions") else: coordinates = np.meshgrid(coordinates[0], coordinates[1], indexing="i...
103
103
344
11
91
elbeejay/landlab
landlab/io/netcdf/read.py
Python
_read_netcdf_structured_data
_read_netcdf_structured_data
166
208
166
166
67dceb50e56849dc0e6ee8f0665e56986c4ec8af
bigcode/the-stack
train
5a03d2fc15ca80d0790964ac
train
function
def _read_netcdf_coordinate_units(root): """Get units for coodinate values. Parameters ---------- root : netcdf_file A NetCDF file. Returns ------- tuple of str Units for each coordinate. """ units = [] for coordinate_name in _AXIS_COORDINATE_NAMES: try:...
def _read_netcdf_coordinate_units(root):
"""Get units for coodinate values. Parameters ---------- root : netcdf_file A NetCDF file. Returns ------- tuple of str Units for each coordinate. """ units = [] for coordinate_name in _AXIS_COORDINATE_NAMES: try: units.append(root.variables[...
Node coordinates for each dimension. """ values = [] for coordinate_name in _AXIS_COORDINATE_NAMES: try: values.append(root.variables[coordinate_name][:].copy()) except KeyError: pass return tuple(values) def _read_netcdf_coordinate_units(root):
64
64
101
10
54
elbeejay/landlab
landlab/io/netcdf/read.py
Python
_read_netcdf_coordinate_units
_read_netcdf_coordinate_units
93
112
93
93
98acd4655da26242220a455e96629663ed69a7f3
bigcode/the-stack
train
be4a4d5614f77e0ff16023a7
train
function
def _read_netcdf_coordinate_values(root): """Get arrays of coordinates for grid points. Parameters ---------- root : netcdf_file A NetCDF file. Returns ------- tuple of ndarray Node coordinates for each dimension. """ values = [] for coordinate_name in _AXIS_COO...
def _read_netcdf_coordinate_values(root):
"""Get arrays of coordinates for grid points. Parameters ---------- root : netcdf_file A NetCDF file. Returns ------- tuple of ndarray Node coordinates for each dimension. """ values = [] for coordinate_name in _AXIS_COORDINATE_NAMES: try: va...
) Shape of the grid. """ shape = [] for axis_name in _AXIS_DIMENSION_NAMES: try: shape.append(_length_of_axis_dimension(root, axis_name)) except KeyError: pass return tuple(shape) def _read_netcdf_coordinate_values(root):
64
64
102
10
54
elbeejay/landlab
landlab/io/netcdf/read.py
Python
_read_netcdf_coordinate_values
_read_netcdf_coordinate_values
71
90
71
71
7cfc60a5433c40c47937d5210079d94fa7c479c3
bigcode/the-stack
train
cc195cf06a93999177fd703b
train
function
def _get_raster_spacing(coords): """Get the row and column spacing of a raster grid. Parameters ---------- root : netcdf_file A NetCDF object. Returns ------- (dy, dx) Spacing of grid rows and columns. """ spacing = np.empty(len(coords), dtype=np.float64) for (...
def _get_raster_spacing(coords):
"""Get the row and column spacing of a raster grid. Parameters ---------- root : netcdf_file A NetCDF object. Returns ------- (dy, dx) Spacing of grid rows and columns. """ spacing = np.empty(len(coords), dtype=np.float64) for (axis, coord) in enumerate(coords)...
[att] = getattr(grid_mapping_variable, att) except AttributeError: # if scipy is doing the reading for att in var._attributes: grid_mapping_dict[att] = getattr(grid_mapping_variable, att) return fields, grid_mapping_dict def _get_raster_spacing(coords):
64
64
155
8
55
elbeejay/landlab
landlab/io/netcdf/read.py
Python
_get_raster_spacing
_get_raster_spacing
211
235
211
211
1719400e4f26e82b4b4ed75858337d67d3af9973
bigcode/the-stack
train
7fe747a4b059890b34bef32f
train
function
def _length_of_axis_dimension(root, axis_name): """Get the size of an axis by axis name. Parameters ---------- root : netcdf_file A NetCDF object. axis_name : str Name of the axis in the NetCDF file. Returns ------- int Size of the dimension. """ try: ...
def _length_of_axis_dimension(root, axis_name):
"""Get the size of an axis by axis name. Parameters ---------- root : netcdf_file A NetCDF object. axis_name : str Name of the axis in the NetCDF file. Returns ------- int Size of the dimension. """ try: return len(root.dimensions[axis_name]) ...
cdf._constants import ( _AXIS_COORDINATE_NAMES, _AXIS_DIMENSION_NAMES, _COORDINATE_NAMES, ) from landlab.io.netcdf.errors import NotRasterGridError from landlab.utils import add_halo def _length_of_axis_dimension(root, axis_name):
64
64
101
11
52
elbeejay/landlab
landlab/io/netcdf/read.py
Python
_length_of_axis_dimension
_length_of_axis_dimension
28
46
28
28
769d3725dbb0f6bfd381b3373999e281afeaa642
bigcode/the-stack
train
83b4eba187ce28a6d36a7897
train
function
def _read_netcdf_raster_structured_grid(root): """Get node coordinates for a structured grid written as a raster. Parameters ---------- root : netcdf_file A NetCDF file. Returns ------- tuple of ndarray Node coordinates for each dimension reshaped to match the shape ...
def _read_netcdf_raster_structured_grid(root):
"""Get node coordinates for a structured grid written as a raster. Parameters ---------- root : netcdf_file A NetCDF file. Returns ------- tuple of ndarray Node coordinates for each dimension reshaped to match the shape of the grid. """ shape = _read_netcdf_...
match the shape of the grid. """ shape = _read_netcdf_grid_shape(root) coordinates = _read_netcdf_coordinate_values(root) for coordinate in coordinates: coordinate.shape = shape return coordinates def _read_netcdf_raster_structured_grid(root):
64
64
162
13
50
elbeejay/landlab
landlab/io/netcdf/read.py
Python
_read_netcdf_raster_structured_grid
_read_netcdf_raster_structured_grid
138
163
138
138
bccf7582980d74bdb2c3081f49efc6833db423d7
bigcode/the-stack
train
1a4e891ed39b44d8006bb43b
train
function
def _read_netcdf_structured_grid(root): """Get node coordinates for a structured grid. Parameters ---------- root : netcdf_file A NetCDF file. Returns ------- tuple of ndarray Node coordinates for each dimension reshaped to match the shape of the grid. """ s...
def _read_netcdf_structured_grid(root):
"""Get node coordinates for a structured grid. Parameters ---------- root : netcdf_file A NetCDF file. Returns ------- tuple of ndarray Node coordinates for each dimension reshaped to match the shape of the grid. """ shape = _read_netcdf_grid_shape(root) ...
Units for each coordinate. """ units = [] for coordinate_name in _AXIS_COORDINATE_NAMES: try: units.append(root.variables[coordinate_name].units) except KeyError: pass return tuple(units) def _read_netcdf_structured_grid(root):
64
64
109
11
53
elbeejay/landlab
landlab/io/netcdf/read.py
Python
_read_netcdf_structured_grid
_read_netcdf_structured_grid
115
135
115
115
9bebdf8fe4f92ce24683e074aa8cab5dda8829ec
bigcode/the-stack
train
4a5d9b26d29747ca6eca1925
train
function
def read_netcdf( nc_file, grid=None, name=None, just_grid=False, halo=0, nodata_value=-9999.0, ): """Create a :class:`~.RasterModelGrid` from a netcdf file. Create a new :class:`~.RasterModelGrid` from the netcdf file, *nc_file*. If the netcdf file also contains data, add that data to the grid's fields...
def read_netcdf( nc_file, grid=None, name=None, just_grid=False, halo=0, nodata_value=-9999.0, ):
"""Create a :class:`~.RasterModelGrid` from a netcdf file. Create a new :class:`~.RasterModelGrid` from the netcdf file, *nc_file*. If the netcdf file also contains data, add that data to the grid's fields. To create a new grid without any associated data from the netcdf file, set the *just_grid* k...
in grid_mapping_variable.ncattrs(): grid_mapping_dict[att] = getattr(grid_mapping_variable, att) except AttributeError: # if scipy is doing the reading for att in var._attributes: grid_mapping_dict[att] = getattr(grid_mapping_variable, att) return fields, grid_m...
256
256
1,703
34
222
elbeejay/landlab
landlab/io/netcdf/read.py
Python
read_netcdf
read_netcdf
238
407
238
240
8a287dcadc2152ef87cb819548969dae2f21770c
bigcode/the-stack
train
c2c1d1343c93aa41a708f0b5
train
function
def allConstruct_recursive(target: str, word_bank: List[str]) -> List[List[str]]: if target == '': return [[]] all_target_combs = list() for word in word_bank: if target.startswith(word): suffix = target.removeprefix(word) suffix_combs = allConstruct_recursive(suffi...
def allConstruct_recursive(target: str, word_bank: List[str]) -> List[List[str]]:
if target == '': return [[]] all_target_combs = list() for word in word_bank: if target.startswith(word): suffix = target.removeprefix(word) suffix_combs = allConstruct_recursive(suffix, word_bank) for comb in suffix_combs: comb = [word,...
_bank' Each subarray consists of the combination of strings from 'wordbank' that constructs the 'target' Reuse of words from wordbank is allowed. """ from typing import List # ------------------------- Recursive Implementation------------------- def allConstruct_recursive(target: str, word_bank: List[str]) -> List[Li...
63
64
106
19
44
belikesayantan/DSA
Python/Dynamic_Programming/allConstruct.py
Python
allConstruct_recursive
allConstruct_recursive
14
29
14
14
e7de4fe17da0ebfbe5dad42bd2cf9f859853a681
bigcode/the-stack
train
f7c06d5cb19718a5f72d47ef
train
function
def allConstruct_memoize(target: str, word_bank: List[str]) -> List[List[str]]: global comb_memo if target in comb_memo: return comb_memo[target] if target == '': return [[]] all_target_combs = list() for word in word_bank: if target.startswith(word): suffix =...
def allConstruct_memoize(target: str, word_bank: List[str]) -> List[List[str]]:
global comb_memo if target in comb_memo: return comb_memo[target] if target == '': return [[]] all_target_combs = list() for word in word_bank: if target.startswith(word): suffix = target.removeprefix(word) suffix_combs = allConstruct_memoize(suffi...
suffix_combs: comb = [word, *comb] all_target_combs.append(comb) return all_target_combs # ------------------------- Memoization Implementation------------------- comb_memo = dict() def allConstruct_memoize(target: str, word_bank: List[str]) -> List[List[str]]:
64
64
143
21
43
belikesayantan/DSA
Python/Dynamic_Programming/allConstruct.py
Python
allConstruct_memoize
allConstruct_memoize
37
57
37
37
793f7718be957c16ce68bd2844f4cc3c7b000b92
bigcode/the-stack
train
870dcd8a91024c364c880ced
train
class
class OptionNotFound(Exception): pass
class OptionNotFound(Exception):
pass
class InvalidConfigPath(Exception): pass class OptionNotFound(Exception):
15
64
9
6
8
kylie-a/bumpversion
bumpv/client/config/exceptions.py
Python
OptionNotFound
OptionNotFound
5
6
5
5
11c4f9e11b02a9fbb0b137f1a24b279c69e52504
bigcode/the-stack
train
0f2987f511c4e4c688ba9a14
train
class
class InvalidConfigPath(Exception): pass
class InvalidConfigPath(Exception):
pass
class InvalidConfigPath(Exception):
6
64
9
6
0
kylie-a/bumpversion
bumpv/client/config/exceptions.py
Python
InvalidConfigPath
InvalidConfigPath
1
2
1
1
973092750faa16c7bc39b74f631b1cfcb630197a
bigcode/the-stack
train
11ce27a2281c6dc40fe71776
train
class
class Solution: def minWindow(self, s: str, t: str) -> str: return self.filtered_sliding_window_soln(s, t) def filtered_sliding_window_soln(self, s: str, t: str) -> str: """ Sliding window but with a filtered s Runtime: O(2 * |filtered_s| + |s| + |t|) """ if s =...
class Solution:
def minWindow(self, s: str, t: str) -> str: return self.filtered_sliding_window_soln(s, t) def filtered_sliding_window_soln(self, s: str, t: str) -> str: """ Sliding window but with a filtered s Runtime: O(2 * |filtered_s| + |s| + |t|) """ if s == "" or t == "":...
# # @lc app=leetcode id=76 lang=python3 # # [76] Minimum Window Substring # # https://leetcode.com/problems/minimum-window-substring/description/ # # algorithms # Hard (32.77%) # Likes: 3218 # Dislikes: 238 # Total Accepted: 310.5K # Total Submissions: 946.8K # Testcase Example: '"ADOBECODEBANC"\n"ABC"' # # Give...
240
241
804
3
236
Dxyk/LeetCode
Python/76.minimum-window-substring.py
Python
Solution
Solution
40
151
40
40
6a71c23ae1da7cb9488d1a3a86bfd3af56670c6b
bigcode/the-stack
train
22778eccf958a1e79ca274f9
train
class
class DataRecorder(CtaArbitrageTemplate): """ 纯粹用来记录历史数据的工具(基于CTA策略), 建议运行在实际交易程序外的一个vn.trader实例中, 本工具会记录Tick和1分钟K线数据。 """ className = 'DataRecorder' author = u'用Python的交易员' # 策略的基本参数 name = EMPTY_UNICODE # 策略实例名称 vtSymbol = EMPTY_STRING # 交易的合约vt系统代码 # 策略的变量 bar = No...
class DataRecorder(CtaArbitrageTemplate):
""" 纯粹用来记录历史数据的工具(基于CTA策略), 建议运行在实际交易程序外的一个vn.trader实例中, 本工具会记录Tick和1分钟K线数据。 """ className = 'DataRecorder' author = u'用Python的交易员' # 策略的基本参数 name = EMPTY_UNICODE # 策略实例名称 vtSymbol = EMPTY_STRING # 交易的合约vt系统代码 # 策略的变量 bar = None # K线数据对象 barMinute = EMPTY_STRING ...
bar数据""" self.ctaEngine.insertData(self.barDbName, vtsymbol, bar) # ---------------------------------------------------------------------- def loadTick(self, days, vtsymbol): """读取tick数据""" return self.ctaEngine.loadTick(self.tickDbName, vtsymbol, days) # --------------------------...
235
235
784
10
224
JesseXu117/vn.trader_Arbitrage
ctaStrategy/ctaArbitrageTemplate.py
Python
DataRecorder
DataRecorder
294
395
294
294
b515b0635672ec53bc0241f4f18567d0365fe5af
bigcode/the-stack
train
cd21e451ccf032062f95085b
train
class
class CtaArbitrageTemplate(object): """CTA策略模板""" # 策略类的名称和作者 className = 'CtaArbitrageTemplate' author = EMPTY_UNICODE # MongoDB数据库的名称,K线数据库默认为1分钟 tickDbName = TICK_DB_NAME barDbName = MINUTE_DB_NAME # 策略的基本参数 name = EMPTY_UNICODE # 策略实例名称 vtSymbol = EMPTY_STRING # 交易的合约vt系...
class CtaArbitrageTemplate(object):
"""CTA策略模板""" # 策略类的名称和作者 className = 'CtaArbitrageTemplate' author = EMPTY_UNICODE # MongoDB数据库的名称,K线数据库默认为1分钟 tickDbName = TICK_DB_NAME barDbName = MINUTE_DB_NAME # 策略的基本参数 name = EMPTY_UNICODE # 策略实例名称 vtSymbol = EMPTY_STRING # 交易的合约vt系统代码 tradeparam = {} product...
# encoding: UTF-8 ''' 本文件包含了CTA引擎中的策略开发用模板,开发策略时需要继承CtaTemplate类。 ''' from ctaStrategy.ctaBase import * from vtConstant import * EMPTY_STRING = '' EMPTY_UNICODE = u'' ######################################################################## class CtaArbitrageTemplate(object):
70
256
2,293
9
60
JesseXu117/vn.trader_Arbitrage
ctaStrategy/ctaArbitrageTemplate.py
Python
CtaArbitrageTemplate
CtaArbitrageTemplate
12
290
12
12
3cafc7176818a2061c9a6d56226f92771f378875
bigcode/the-stack
train
892efe77e3fbe1ffcc66ce49
train
class
class Migration(migrations.Migration): dependencies = [ ('core', '0016_auto_20200818_0932'), ] operations = [ migrations.CreateModel( name='Room', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID...
class Migration(migrations.Migration):
dependencies = [ ('core', '0016_auto_20200818_0932'), ] operations = [ migrations.CreateModel( name='Room', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.Cha...
# Generated by Django 3.1 on 2020-08-19 21:05 from django.db import migrations, models class Migration(migrations.Migration):
36
64
176
7
28
Latiftanga/twysis-api
api/core/migrations/0017_room.py
Python
Migration
Migration
6
26
6
7
c380dee778bd342623ad8da4397100f933cfaa13
bigcode/the-stack
train
12a2eacb8aabadf40fc9597f
train
function
def check_filters(cui, filters): r''' Checks is a CUI in the filters Args: cui filters Return: bool: True if in filters else False ''' if cui in filters.get('cuis', {}) or not filters.get('cuis', {}): if cui not in filters.get('cuis_exclude', {}): ...
def check_filters(cui, filters):
r''' Checks is a CUI in the filters Args: cui filters Return: bool: True if in filters else False ''' if cui in filters.get('cuis', {}) or not filters.get('cuis', {}): if cui not in filters.get('cuis_exclude', {}): return True else: ...
def check_filters(cui, filters):
8
64
99
8
0
louni-g/MedCAT
medcat/utils/filters.py
Python
check_filters
check_filters
1
18
1
1
e01cd145242be3c4dfc40d7c87b5dc72b0824649
bigcode/the-stack
train
b87e3aa72a0815025624c511
train
function
def process_old_project_filters(cuis, type_ids, cdb): cui_filter = set() if cuis is not None and cuis: cui_filter.update([x.strip() for x in cuis.split(",")]) if type_ids is not None and type_ids: type_ids = [x.strip().upper() for x in type_ids.split(",")] # Convert type_ids to cuis...
def process_old_project_filters(cuis, type_ids, cdb):
cui_filter = set() if cuis is not None and cuis: cui_filter.update([x.strip() for x in cuis.split(",")]) if type_ids is not None and type_ids: type_ids = [x.strip().upper() for x in type_ids.split(",")] # Convert type_ids to cuis if 'type_id2cuis' in cdb.addl_info: ...
filters.get('cuis', {}) or not filters.get('cuis', {}): if cui not in filters.get('cuis_exclude', {}): return True else: return False else: return False def process_old_project_filters(cuis, type_ids, cdb):
64
64
178
14
49
louni-g/MedCAT
medcat/utils/filters.py
Python
process_old_project_filters
process_old_project_filters
20
37
20
20
30af9389ec5ede6f23c2013be4fdc43f07c561b7
bigcode/the-stack
train
832e94eb3454daf4e7077ad2
train
class
class SetSpeakerHandler(webapp2.RequestHandler): def post(self): """Set speaker infomation in memcache""" # obtain names of this speaker speaker = ndb.Key(urlsafe=self.request.get('speakerWSK')).get() fullName = speaker.speakerFirst + " " + speaker.speakerLast # obtain name...
class SetSpeakerHandler(webapp2.RequestHandler):
def post(self): """Set speaker infomation in memcache""" # obtain names of this speaker speaker = ndb.Key(urlsafe=self.request.get('speakerWSK')).get() fullName = speaker.speakerFirst + " " + speaker.speakerLast # obtain names of sessions having this speaker in the conferen...
_KEY = "GET_FEATURED_SPEAKER" INFORMATION_TPL = ('Your speaker %s is also leading these other sessions: %s') class SetAnnouncementHandler(webapp2.RequestHandler): def get(self): """Set Announcement in Memcache.""" ConferenceApi._cacheAnnouncement() self.response.set_status(204) class SetSp...
78
78
261
10
68
erooma/project4
main.py
Python
SetSpeakerHandler
SetSpeakerHandler
38
66
38
38
59f1e7551e09f9ae6a5942e704f7ea4eddf985f3
bigcode/the-stack
train
1da82b3b051aa47a348196c2
train
class
class SetAnnouncementHandler(webapp2.RequestHandler): def get(self): """Set Announcement in Memcache.""" ConferenceApi._cacheAnnouncement() self.response.set_status(204)
class SetAnnouncementHandler(webapp2.RequestHandler):
def get(self): """Set Announcement in Memcache.""" ConferenceApi._cacheAnnouncement() self.response.set_status(204)
from google.appengine.api import taskqueue from models import Session from conference import ConferenceApi SPEAKER_INFORMATION_KEY = "GET_FEATURED_SPEAKER" INFORMATION_TPL = ('Your speaker %s is also leading these other sessions: %s') class SetAnnouncementHandler(webapp2.RequestHandler):
64
64
38
10
54
erooma/project4
main.py
Python
SetAnnouncementHandler
SetAnnouncementHandler
31
35
31
31
c8e3ca0012b4da489114d5a7e97a70a2c30b5e6b
bigcode/the-stack
train
6de179ac10ef233a27cc5d6f
train
class
class SendConfirmationEmailHandler(webapp2.RequestHandler): def post(self): """Send email confirming Conference creation.""" mail.send_mail( 'noreply@%s.appspotmail.com' % ( app_identity.get_application_id()), # from self.request.get('email'), ...
class SendConfirmationEmailHandler(webapp2.RequestHandler):
def post(self): """Send email confirming Conference creation.""" mail.send_mail( 'noreply@%s.appspotmail.com' % ( app_identity.get_application_id()), # from self.request.get('email'), # to 'You created a new Conference!', ...
_INFORMATION_KEY, speakerInformation) else: # If there are no other speaker hosted sessions, # delete the memcache information entry speakerInformation = "" memcache.delete(SPEAKER_INFORMATION_KEY) self.response.set_status(204) class SendC...
63
64
113
11
52
erooma/project4
main.py
Python
SendConfirmationEmailHandler
SendConfirmationEmailHandler
70
81
70
70
5dfe3c3237a244c7bd542b81f3d694da809115d1
bigcode/the-stack
train
631310d48b13303d75c6f070
train
class
@pulumi.input_type class DeviceArgs: def __init__(__self__, *, resource_group_name: pulumi.Input[str], data_box_edge_device_status: Optional[pulumi.Input[Union[str, 'DataBoxEdgeDeviceStatus']]] = None, device_name: Optional[pulumi.Input[str]] = None, ...
@pulumi.input_type class DeviceArgs:
def __init__(__self__, *, resource_group_name: pulumi.Input[str], data_box_edge_device_status: Optional[pulumi.Input[Union[str, 'DataBoxEdgeDeviceStatus']]] = None, device_name: Optional[pulumi.Input[str]] = None, etag: Optional[pulumi.Input[str]] ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from...
113
256
1,341
10
103
polivbr/pulumi-azure-native
sdk/python/pulumi_azure_native/databoxedge/device.py
Python
DeviceArgs
DeviceArgs
16
148
16
17
370a7d325035972397720eaceefe641347f7022d
bigcode/the-stack
train
4d4a7ec3ed0775634ae10c97
train
class
class Device(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, data_box_edge_device_status: Optional[pulumi.Input[Union[str, 'DataBoxEdgeDeviceStatus']]] = None, device_n...
class Device(pulumi.CustomResource): @overload
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, data_box_edge_device_status: Optional[pulumi.Input[Union[str, 'DataBoxEdgeDeviceStatus']]] = None, device_name: Optional[pulumi.Input[str]] = None, ...
specified on update, the request will succeed. """ return pulumi.get(self, "location") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "location", value) @property @pulumi.getter def sku(self) -> Optional[pulumi.Input['SkuArgs']]: ...
256
256
3,633
13
243
polivbr/pulumi-azure-native
sdk/python/pulumi_azure_native/databoxedge/device.py
Python
Device
Device
151
503
151
152
3e9c22769e0bffcd3e2b91d3351992ce336f922b
bigcode/the-stack
train
49e41b4b5448f2c3bfffa2c7
train
class
class TestEvent(DynamicEnum): Invalid = 0 SkillValueChange = 1 ObjectAdd = 2 InteractionComplete = 3 SituationEnded = 4 ItemCrafted = 5 InteractionAtEvent = 6 SimoleonsEarned = 7 UpdateAllEvent = 8 TraitAddEvent = 9 MotiveLevelChange = 10 TestTotalTime = 11 SimTravel ...
class TestEvent(DynamicEnum):
Invalid = 0 SkillValueChange = 1 ObjectAdd = 2 InteractionComplete = 3 SituationEnded = 4 ItemCrafted = 5 InteractionAtEvent = 6 SimoleonsEarned = 7 UpdateAllEvent = 8 TraitAddEvent = 9 MotiveLevelChange = 10 TestTotalTime = 11 SimTravel = 12 AddRelationshipBit = ...
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\event_testing\test_events.py # Compiled at: 2020-08-21 01:35:08 # Size of source mod 2**32: 9633 byt...
206
256
915
7
199
velocist/TS4CheatsInfo
Scripts/simulation/event_testing/test_events.py
Python
TestEvent
TestEvent
14
124
14
14
bb69c82867f11a0f98caaaba06ceefb108f56fcd
bigcode/the-stack
train
b3000534d3c36369a1b47680
train
function
@decorator def cached_test(fn): @functools.wraps(fn) def wrapper(test, **kwargs): if caches.skip_cache: return fn(test, **kwargs) cache = wrapper.cache if caches.global_cache_version != wrapper.cache_version: cache.clear() wrapper.cach...
@decorator def cached_test(fn): @functools.wraps(fn)
def wrapper(test, **kwargs): if caches.skip_cache: return fn(test, **kwargs) cache = wrapper.cache if caches.global_cache_version != wrapper.cache_version: cache.clear() wrapper.cache_version = caches.global_cache_version else: ...
Late = 107 UtilityStatusChanged = 108 RoutingFormationStarted = 109 CONTENT_SET_GEN_PROCESS_HOUSEHOLD_EVENT_CACHE_GROUP = 'CONTENT_SET_GEN_PROCESS_HOUSEHOLD_EVENT_CACHE_GROUP' @decorator def cached_test(fn): @functools.wraps(fn)
64
64
144
18
46
velocist/TS4CheatsInfo
Scripts/simulation/event_testing/test_events.py
Python
cached_test
cached_test
129
153
129
132
f91571d6169f623c097dd4343de9769c6c58879f
bigcode/the-stack
train
5e4320c18eb2e0c113e81aa6
train
function
@pmp("nx", (30, 250)) @pmp("ny", (128,)) @pmp("fov", (5.0,)) @pmp("nrow", (3333, 10000)) @pmp("nchan", (1, 8)) @pmp("nband", (1, 2)) @pmp("precision", ('single', 'double')) @pmp("nthreads", (1, 4)) @pmp("nchunks", (1, 3)) def test_dask_residual(nx, ny, fov, nrow, nchan, nband, precision, nthreads...
@pmp("nx", (30, 250)) @pmp("ny", (128,)) @pmp("fov", (5.0,)) @pmp("nrow", (3333, 10000)) @pmp("nchan", (1, 8)) @pmp("nband", (1, 2)) @pmp("precision", ('single', 'double')) @pmp("nthreads", (1, 4)) @pmp("nchunks", (1, 3)) def test_dask_residual(nx, ny, fov, nrow, nchan, nband, precision, nthreads...
da = pytest.importorskip("dask.array") from africanus.gridding.wgridder import residual as residual_np from africanus.gridding.wgridder.dask import residual np.random.seed(420) if precision == 'single': real_type = np.float32 complex_type = np.complex64 decimal = 4 # sometim...
(freq_bin_counts, chunks=1) vis_da = model(uvw_da, freq_da, image_da, freq_bin_idx_da, freq_bin_counts_da, cell, weights=wgt_da, nthreads=nthreads).compute() # relative error should agree to within epsilon vmax = np.maximum(np.abs(vis).max(), np.abs(vis_da).max()) ...
240
240
802
143
97
JoshVStaden/codex-africanus
africanus/gridding/wgridder/tests/test_wgridder.py
Python
test_dask_residual
test_dask_residual
406
469
406
416
538f57918c550a64c7d0af658750ae6ce8fb2d91
bigcode/the-stack
train
4f46a52f2301d8fe99c4effd
train
function
def explicit_gridder(uvw, freq, ms, wgt, nxdirty, nydirty, xpixsize, ypixsize, apply_w): x, y = np.meshgrid(*[-ss/2 + np.arange(ss) for ss in [nxdirty, nydirty]], indexing='ij') x *= xpixsize y *= ypixsize res = np.zeros((nxdirty, nydirty)) eps = x**2+y**2...
def explicit_gridder(uvw, freq, ms, wgt, nxdirty, nydirty, xpixsize, ypixsize, apply_w):
x, y = np.meshgrid(*[-ss/2 + np.arange(ss) for ss in [nxdirty, nydirty]], indexing='ij') x *= xpixsize y *= ypixsize res = np.zeros((nxdirty, nydirty)) eps = x**2+y**2 if apply_w: nm1 = -eps/(np.sqrt(1.-eps)+1.) n = nm1+1 else: nm1 = 0. ...
pmp = pytest.mark.parametrize def _l2error(a, b): return np.sqrt(np.sum(np.abs(a-b)**2)/np.maximum(np.sum(np.abs(a)**2), np.sum(np.abs(b)**2))) def explicit_gridder(uvw, freq, ms, wgt, nxdirty, nydirty, xpixsize, ypixsize, apply_w):
81
82
275
33
48
JoshVStaden/codex-africanus
africanus/gridding/wgridder/tests/test_wgridder.py
Python
explicit_gridder
explicit_gridder
16
39
16
17
a4da6f9cf8b2920fa2fc7504e93a56950a18a7d1
bigcode/the-stack
train
e926e17e15b6f3c1029b7db5
train
function
@pmp("nx", (20, )) @pmp("ny", (32, 70)) @pmp("fov", (1.5, 3.5)) @pmp("nrow", (222, 777,)) @pmp("nchan", (1, 5)) @pmp("nband", (1, 3)) @pmp("precision", ('single', 'double')) @pmp("nthreads", (3,)) def test_residual(nx, ny, fov, nrow, nchan, nband, precision, nthreads): # Compare the result of im2r...
@pmp("nx", (20, )) @pmp("ny", (32, 70)) @pmp("fov", (1.5, 3.5)) @pmp("nrow", (222, 777,)) @pmp("nchan", (1, 5)) @pmp("nband", (1, 3)) @pmp("precision", ('single', 'double')) @pmp("nthreads", (3,)) def test_residual(nx, ny, fov, nrow, nchan, nband, precision, nthreads): # Compare the result of im2r...
from africanus.gridding.wgridder import dirty, model, residual np.random.seed(420) if precision == 'single': real_type = np.float32 complex_type = np.complex64 decimal = 4 else: real_type = np.float64 complex_type = np.complex128 decimal = 12 cell = fo...
close to machine precision assert_allclose(np.vdot(vis, modelvis).real, np.vdot(image, model_im), rtol=tol) @pmp("nx", (20, )) @pmp("ny", (32, 70)) @pmp("fov", (1.5, 3.5)) @pmp("nrow", (222, 777,)) @pmp("nchan", (1, 5)) @pmp("nband", (1, 3)) @pmp("precision", ('single', 'double')) @pmp("nthread...
204
204
682
171
33
JoshVStaden/codex-africanus
africanus/gridding/wgridder/tests/test_wgridder.py
Python
test_residual
test_residual
151
206
151
163
e65d985be91a0493128109d3aa8cbd05c97d4ef1
bigcode/the-stack
train
4286dcd40baa963b1f421253
train
function
@pmp("nx", (30, 250)) @pmp("ny", (128,)) @pmp("fov", (5.0,)) @pmp("nrow", (3333, 10000)) @pmp("nchan", (1, 8)) @pmp("nband", (1, 2)) @pmp("precision", ('single', 'double')) @pmp("nthreads", (1, 4)) @pmp("nchunks", (1, 3)) def test_dask_model(nx, ny, fov, nrow, nchan, nband, precision, nthreads, nchu...
@pmp("nx", (30, 250)) @pmp("ny", (128,)) @pmp("fov", (5.0,)) @pmp("nrow", (3333, 10000)) @pmp("nchan", (1, 8)) @pmp("nband", (1, 2)) @pmp("precision", ('single', 'double')) @pmp("nthreads", (1, 4)) @pmp("nchunks", (1, 3)) def test_dask_model(nx, ny, fov, nrow, nchan, nband, precision, nthreads, nchu...
da = pytest.importorskip("dask.array") from africanus.gridding.wgridder import model as model_np from africanus.gridding.wgridder.dask import model np.random.seed(420) if precision == 'single': real_type = np.float32 complex_type = np.complex64 decimal = 4 # sometimes fails ...
= dirty(uvw_da, freq_da, vis_da, freq_bin_idx_da, freq_bin_counts_da, nx, ny, cell, weights=wgt_da, nthreads=nthreads).compute() # relative error should agree to within epsilon dmax = np.maximum(np.abs(image).max(), np.abs(image_da).max()) assert_array_almost_equa...
233
233
777
142
91
JoshVStaden/codex-africanus
africanus/gridding/wgridder/tests/test_wgridder.py
Python
test_dask_model
test_dask_model
339
403
339
349
975f72e0f2fd9991d85620e52d0c2de3dcd787a0
bigcode/the-stack
train
877c08384d428a0f6fb349a8
train
function
@pmp("nx", (16,)) @pmp("ny", (18, 64)) @pmp("fov", (5.0,)) @pmp("nrow", (1000,)) @pmp("nchan", (1, 7)) @pmp("nband", (1, 3)) @pmp("precision", ('single', 'double')) @pmp("epsilon", (1e-3, 1e-4)) @pmp("nthreads", (1, 6)) def test_gridder(nx, ny, fov, nrow, nchan, nband, precision, epsilon, nthreads): ...
@pmp("nx", (16,)) @pmp("ny", (18, 64)) @pmp("fov", (5.0,)) @pmp("nrow", (1000,)) @pmp("nchan", (1, 7)) @pmp("nband", (1, 3)) @pmp("precision", ('single', 'double')) @pmp("epsilon", (1e-3, 1e-4)) @pmp("nthreads", (1, 6)) def test_gridder(nx, ny, fov, nrow, nchan, nband, precision, epsilon, nthreads): ...
if nband > nchan: return from africanus.gridding.wgridder import dirty if precision == 'single': real_type = "f4" complex_type = "c8" else: real_type = "f8" complex_type = "c16" np.random.seed(420) cell = fov*np.pi/180/nx f0 = 1e9 freq = (f0 + np....
]*wgt[row, chan] * np.exp(2j*np.pi*phase)).real return res/n @pmp("nx", (16,)) @pmp("ny", (18, 64)) @pmp("fov", (5.0,)) @pmp("nrow", (1000,)) @pmp("nchan", (1, 7)) @pmp("nband", (1, 3)) @pmp("precision", ('single', 'double')) @pmp("epsilon", (1e-3, 1e-4)) @pmp("nthreads", (1, 6)) def test_gr...
180
180
600
154
25
JoshVStaden/codex-africanus
africanus/gridding/wgridder/tests/test_wgridder.py
Python
test_gridder
test_gridder
42
91
42
53
8e6650659ad16c9d96cf2a926647932c7e51499e
bigcode/the-stack
train
db06da3d4ec253907aa2bbc8
train
function
@pmp("nx", (64,)) @pmp("ny", (128,)) @pmp("fov", (5.0,)) @pmp("nrow", (3333, 10000)) @pmp("nchan", (4,)) @pmp("nband", (2,)) @pmp("precision", ('single', 'double')) @pmp("nthreads", (1,)) @pmp("nchunks", (1, 3)) def test_dask_hessian(nx, ny, fov, nrow, nchan, nband, precision, nthreads, nchunks): ...
@pmp("nx", (64,)) @pmp("ny", (128,)) @pmp("fov", (5.0,)) @pmp("nrow", (3333, 10000)) @pmp("nchan", (4,)) @pmp("nband", (2,)) @pmp("precision", ('single', 'double')) @pmp("nthreads", (1,)) @pmp("nchunks", (1, 3)) def test_dask_hessian(nx, ny, fov, nrow, nchan, nband, precision, nthreads, nchunks):
da = pytest.importorskip("dask.array") from africanus.gridding.wgridder import hessian as hessian_np from africanus.gridding.wgridder.dask import hessian np.random.seed(420) if precision == 'single': real_type = np.float32 decimal = 4 # sometimes fails at 5 else: real_ty...
freq_bin_idx_da, freq_bin_counts_da, cell, weights=wgt_da, nthreads=nthreads).compute() # should agree to within epsilon rmax = np.maximum(np.abs(residim_np).max(), np.abs(residim_da).max()) assert_array_almost_equal( residim_np/rmax, residim_da/r...
213
213
713
131
82
JoshVStaden/codex-africanus
africanus/gridding/wgridder/tests/test_wgridder.py
Python
test_dask_hessian
test_dask_hessian
472
530
472
482
59ff96ef73c7b52966dbcade679e6e9190ddcdbf
bigcode/the-stack
train
504831075ac63f160ee84ad0
train
function
def _l2error(a, b): return np.sqrt(np.sum(np.abs(a-b)**2)/np.maximum(np.sum(np.abs(a)**2), np.sum(np.abs(b)**2)))
def _l2error(a, b):
return np.sqrt(np.sum(np.abs(a-b)**2)/np.maximum(np.sum(np.abs(a)**2), np.sum(np.abs(b)**2)))
# -*- coding: utf-8 -*- import numpy as np from numpy.testing import assert_allclose, assert_array_almost_equal import pytest from africanus.constants import c as lightspeed pmp = pytest.mark.parametrize def _l2error(a, b):
56
64
41
9
46
JoshVStaden/codex-africanus
africanus/gridding/wgridder/tests/test_wgridder.py
Python
_l2error
_l2error
11
13
11
11
d98836b8f9089518c50b84fed77ce544202c16fc
bigcode/the-stack
train
825d6c7e2245c1a96dd5ba6e
train
function
@pmp("nx", (128, )) @pmp("ny", (256,)) @pmp("fov", (0.5,)) @pmp("nrow", (10000000,)) @pmp("nchan", (2,)) @pmp("nband", (2,)) @pmp("precision", ('single',)) @pmp("nthreads", (4,)) def test_hessian(nx, ny, fov, nrow, nchan, nband, precision, nthreads): # Compare the result of dirty computed with Hess...
@pmp("nx", (128, )) @pmp("ny", (256,)) @pmp("fov", (0.5,)) @pmp("nrow", (10000000,)) @pmp("nchan", (2,)) @pmp("nband", (2,)) @pmp("precision", ('single',)) @pmp("nthreads", (4,)) def test_hessian(nx, ny, fov, nrow, nchan, nband, precision, nthreads): # Compare the result of dirty computed with Hess...
from africanus.gridding.wgridder import dirty, hessian np.random.seed(420) if precision == 'single': real_type = np.float32 complex_type = np.complex64 atol = 1e-5 else: real_type = np.float64 complex_type = np.complex128 atol = 1e-5 uvw = 1000*np.ran...
thing just in a different # order so should be close to machine precision rmax = np.maximum(np.abs(residim1).max(), np.abs(residim2).max()) assert_array_almost_equal( residim1/rmax, residim2/rmax, decimal=decimal) @pmp("nx", (128, )) @pmp("ny", (256,)) @pmp("fov", (0.5,)) @pmp("nrow", (10000000,)) ...
203
203
678
138
65
JoshVStaden/codex-africanus
africanus/gridding/wgridder/tests/test_wgridder.py
Python
test_hessian
test_hessian
209
272
209
221
c4e89a17c2599a859adb9c0f7aa81a08f90a2761
bigcode/the-stack
train
d54ebbfe57bcc1def24c122e
train
function
@pmp("nx", (30,)) @pmp("ny", (50, 128)) @pmp("fov", (0.5, 2.5)) @pmp("nrow", (333, 5000,)) @pmp("nchan", (1, 4)) @pmp("nband", (1, 2)) @pmp("precision", ('single', 'double')) @pmp("nthreads", (6,)) def test_adjointness(nx, ny, fov, nrow, nchan, nband, precision, nthreads): # instead of explicit...
@pmp("nx", (30,)) @pmp("ny", (50, 128)) @pmp("fov", (0.5, 2.5)) @pmp("nrow", (333, 5000,)) @pmp("nchan", (1, 4)) @pmp("nband", (1, 2)) @pmp("precision", ('single', 'double')) @pmp("nthreads", (6,)) def test_adjointness(nx, ny, fov, nrow, nchan, nband, precision, nthreads): # instead of explicit...
if nband > nchan: return from africanus.gridding.wgridder import dirty, model if precision == 'single': real_type = np.float32 complex_type = np.complex64 tol = 1e-4 else: real_type = np.float64 complex_type = np.complex128 tol = 1e-12 np.rando...
@pmp("nx", (30,)) @pmp("ny", (50, 128)) @pmp("fov", (0.5, 2.5)) @pmp("nrow", (333, 5000,)) @pmp("nchan", (1, 4)) @pmp("nband", (1, 2)) @pmp("precision", ('single', 'double')) @pmp("nthreads", (6,)) def test_adjointness(nx, ny, fov, nrow, nchan, nband, precision, nthreads): # instead of explicit...
208
196
655
208
0
JoshVStaden/codex-africanus
africanus/gridding/wgridder/tests/test_wgridder.py
Python
test_adjointness
test_adjointness
94
148
94
110
46d99f1f6b687f34aa2a0b6d6fbeedc4ec3d373e
bigcode/the-stack
train
794254b6a2042dfabf849144
train
function
@pmp("nx", (30, 250)) @pmp("ny", (128,)) @pmp("fov", (5.0,)) @pmp("nrow", (3333, 10000)) @pmp("nchan", (1, 8)) @pmp("nband", (1, 2)) @pmp("precision", ('single', 'double')) @pmp("nthreads", (1, 4)) @pmp("nchunks", (1, 3)) def test_dask_dirty(nx, ny, fov, nrow, nchan, nband, precision, nthreads, nchu...
@pmp("nx", (30, 250)) @pmp("ny", (128,)) @pmp("fov", (5.0,)) @pmp("nrow", (3333, 10000)) @pmp("nchan", (1, 8)) @pmp("nband", (1, 2)) @pmp("precision", ('single', 'double')) @pmp("nthreads", (1, 4)) @pmp("nchunks", (1, 3)) def test_dask_dirty(nx, ny, fov, nrow, nchan, nband, precision, nthreads, nchu...
da = pytest.importorskip("dask.array") from africanus.gridding.wgridder import dirty as dirty_np from africanus.gridding.wgridder.dask import dirty np.random.seed(420) if precision == 'single': real_type = np.float32 complex_type = np.complex64 decimal = 4 # sometimes fails ...
(uvw, freq, model_im, freq_bin_idx, freq_bin_counts, cell, nthreads=nthreads, do_wstacking=False, double_accum=True) # rtol not reliable since there will be values close to zero in the # dirty images assert_allclose(dirty_im1/nrow, dirty_im2/nrow, atol=atol, ...
230
230
768
142
88
JoshVStaden/codex-africanus
africanus/gridding/wgridder/tests/test_wgridder.py
Python
test_dask_dirty
test_dask_dirty
275
336
275
285
ecab2934fb93d997f137b6a1d8a6dbe1057bfa61
bigcode/the-stack
train
14d46873d438708e31cf4b3f
train
function
def register_string_typecasters(connection): # raw_unicode_escape used for SQL ASCII will escape the # characters. Here we unescape them using unicode_escape # and send ahead. When insert update is done, the characters # are escaped again and sent to the DB. if connection.encoding in ('SQL_ASCII', '...
def register_string_typecasters(connection): # raw_unicode_escape used for SQL ASCII will escape the # characters. Here we unescape them using unicode_escape # and send ahead. When insert update is done, the characters # are escaped again and sent to the DB.
if connection.encoding in ('SQL_ASCII', 'SQLASCII', 'MULE_INTERNAL', 'MULEINTERNAL'): if sys.version_info >= (3,): def non_ascii_escape(value, cursor): if value is None: return None return bytes( ...
type caster to convert various pg array types into # array of string type psycopg2.extensions.register_type(pg_array_types_to_array_of_string_type) def register_string_typecasters(connection): # raw_unicode_escape used for SQL ASCII will escape the # characters. Here we unescape them using unicode_esca...
93
93
313
59
34
sahilsdei/django_ecommerce
local/lib/python3.6/site-packages/pgadmin4/pgadmin/utils/driver/psycopg2/typecast.py
Python
register_string_typecasters
register_string_typecasters
166
197
166
170
365ee4b57567264d65af9870ae86581be75858f5
bigcode/the-stack
train
6e6480eff3235c6239bb279f
train
function
def register_array_to_string_typecasters(connection): psycopg2.extensions.register_type( psycopg2.extensions.new_type( PSYCOPG_SUPPORTED_BUILTIN_ARRAY_DATATYPES + PSYCOPG_SUPPORTED_JSON_ARRAY_TYPES + PSYCOPG_SUPPORTED_IPADDRESS_ARRAY_TYPES + PSYCOPG_SUPPORTED_...
def register_array_to_string_typecasters(connection):
psycopg2.extensions.register_type( psycopg2.extensions.new_type( PSYCOPG_SUPPORTED_BUILTIN_ARRAY_DATATYPES + PSYCOPG_SUPPORTED_JSON_ARRAY_TYPES + PSYCOPG_SUPPORTED_IPADDRESS_ARRAY_TYPES + PSYCOPG_SUPPORTED_RANGE_ARRAY_TYPES + TO_ARRAY_OF_STRING_DAT...
a[] type 1001, ), 'BYTEA_ARRAY_PLACEHOLDER', # Only show placeholder if data actually exists. lambda value, cursor: 'binary data[]' if value is not None else None), connection ) def register_array_to_string_typecasters(connection):
64
64
96
9
55
sahilsdei/django_ecommerce
local/lib/python3.6/site-packages/pgadmin4/pgadmin/utils/driver/psycopg2/typecast.py
Python
register_array_to_string_typecasters
register_array_to_string_typecasters
228
239
228
228
7ab29b9d343e4f4c6b9e98d247f43f17768939db
bigcode/the-stack
train
0fd9921c789560317302e054
train
function
def register_global_typecasters(): if sys.version_info < (3,): psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY) unicode_type_for_record = psycopg2.extensions.new_type( (2249,), "RECORD", ps...
def register_global_typecasters():
if sys.version_info < (3,): psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY) unicode_type_for_record = psycopg2.extensions.new_type( (2249,), "RECORD", psycopg2.extensions.UNICODE ) ...
/lib/_range.py PSYCOPG_SUPPORTED_RANGE_TYPES = (3904, 3926, 3906, 3912, 3908, 3910) # int4range[], int8range[], numrange[], daterange[] tsrange[], tstzrange[] # OID reference psycopg2/lib/_range.py PSYCOPG_SUPPORTED_RANGE_ARRAY_TYPES = (3905, 3927, 3907, 3913, 3909, 3911) def register_global_typecasters():
111
111
373
6
105
sahilsdei/django_ecommerce
local/lib/python3.6/site-packages/pgadmin4/pgadmin/utils/driver/psycopg2/typecast.py
Python
register_global_typecasters
register_global_typecasters
121
163
121
121
d0d18c95b8117e00fd535aa44641afb41cc8b0ab
bigcode/the-stack
train
8590939aef8474d650aacf33
train
function
def register_binary_typecasters(connection): psycopg2.extensions.register_type( psycopg2.extensions.new_type( ( # To cast bytea type 17, ), 'BYTEA_PLACEHOLDER', # Only show placeholder if data actually exists. lambda...
def register_binary_typecasters(connection):
psycopg2.extensions.register_type( psycopg2.extensions.new_type( ( # To cast bytea type 17, ), 'BYTEA_PLACEHOLDER', # Only show placeholder if data actually exists. lambda value, cursor: 'binary data' if ...
1003, 1009, 1014, 1015, 0 ), 'UNICODEARRAY', unicode_type) psycopg2.extensions.register_type(unicode_type, connection) psycopg2.extensions.register_type(unicode_array_type, connection) def register_binary_typecasters(connection):
64
64
163
7
57
sahilsdei/django_ecommerce
local/lib/python3.6/site-packages/pgadmin4/pgadmin/utils/driver/psycopg2/typecast.py
Python
register_binary_typecasters
register_binary_typecasters
200
225
200
200
0a7c8f431d6328a860aab654a284a0230190c7fa
bigcode/the-stack
train
99b3a4e3d7c019c75f8f800b
train
function
@git_support def get_new_command(command): return replace_argument(command.script, '-d', '-D')
@git_support def get_new_command(command):
return replace_argument(command.script, '-d', '-D')
frick.utils import replace_argument from thefrick.specific.git import git_support @git_support def match(command): return ('branch -d' in command.script and 'If you are sure you want to delete it' in command.output) @git_support def get_new_command(command):
64
64
23
10
54
earboxer/thefrick
thefrick/rules/git_branch_delete.py
Python
get_new_command
get_new_command
11
13
11
12
31e5a1cf119fe1a858d09b98997e757279859496
bigcode/the-stack
train