uid
string
split
string
category
string
content
string
signature
string
suffix
string
prefix
string
prefix_token_count
int64
prefix_token_budget
int64
element_token_count
int64
signature_token_count
int64
prefix_context_token_count
int64
repo
string
path
string
language
string
name
string
qualname
string
start_line
int64
end_line
int64
signature_start_line
int64
signature_end_line
int64
source_hash
string
source_dataset
string
source_split
string
07c39a3b8eb47ee379152c68
train
function
def myexpand(func, target): expanded = expand_func(func) if target is not None: return expanded == target if expanded == func: # it didn't expand return False # check to see that the expanded and original evaluate to the same value subs = {} for a in func.free_symbols: ...
def myexpand(func, target):
expanded = expand_func(func) if target is not None: return expanded == target if expanded == func: # it didn't expand return False # check to see that the expanded and original evaluate to the same value subs = {} for a in func.free_symbols: subs[a] = randcplx() ret...
randcplx() assert td(zeta(b, x), x) assert td(polylog(b, z), z) assert td(lerchphi(c, b, x), x) assert td(lerchphi(x, b, c), x) def myexpand(func, target):
64
64
115
7
57
ovolve/sympy
sympy/functions/special/tests/test_zeta_functions.py
Python
myexpand
myexpand
108
120
108
108
64a715565ab0cb989c936119373b12c76cc11911
bigcode/the-stack
train
2637f71767c2e4e39c575056
train
function
def test_rewriting(): assert dirichlet_eta(x).rewrite(zeta) == (1 - 2**(1 - x))*zeta(x) assert zeta(x).rewrite(dirichlet_eta) == dirichlet_eta(x)/(1 - 2**(1 - x)) assert tn(dirichlet_eta(x), dirichlet_eta(x).rewrite(zeta), x) assert tn(zeta(x), zeta(x).rewrite(dirichlet_eta), x) assert zeta(x, a).r...
def test_rewriting():
assert dirichlet_eta(x).rewrite(zeta) == (1 - 2**(1 - x))*zeta(x) assert zeta(x).rewrite(dirichlet_eta) == dirichlet_eta(x)/(1 - 2**(1 - x)) assert tn(dirichlet_eta(x), dirichlet_eta(x).rewrite(zeta), x) assert tn(zeta(x), zeta(x).rewrite(dirichlet_eta), x) assert zeta(x, a).rewrite(lerchphi) == le...
Rational(1, 4) assert dirichlet_eta(1) == log(2) assert dirichlet_eta(2) == pi**2/12 assert dirichlet_eta(4) == pi**4*Rational(7, 720) def test_rewriting():
64
64
202
5
59
ovolve/sympy
sympy/functions/special/tests/test_zeta_functions.py
Python
test_rewriting
test_rewriting
78
88
78
78
d31f89d7f934c1402bed74fa6b5301038af360de
bigcode/the-stack
train
8929cd9bd338424d85f8dc1e
train
function
def test_stieltjes_evalf(): assert abs(stieltjes(0).evalf() - 0.577215664) < 1E-9 assert abs(stieltjes(0, 0.5).evalf() - 1.963510026) < 1E-9 assert abs(stieltjes(1, 2).evalf() + 0.072815845 ) < 1E-9
def test_stieltjes_evalf():
assert abs(stieltjes(0).evalf() - 0.577215664) < 1E-9 assert abs(stieltjes(0, 0.5).evalf() - 1.963510026) < 1E-9 assert abs(stieltjes(1, 2).evalf() + 0.072815845 ) < 1E-9
1) == S.ComplexInfinity assert stieltjes(1.5) == S.ComplexInfinity assert stieltjes(z, 0) == S.ComplexInfinity assert stieltjes(z, -1) == S.ComplexInfinity def test_stieltjes_evalf():
64
64
97
8
55
ovolve/sympy
sympy/functions/special/tests/test_zeta_functions.py
Python
test_stieltjes_evalf
test_stieltjes_evalf
177
180
177
177
d744333f9d2fa1c8805e3712ff101987bc120e82
bigcode/the-stack
train
f36ea23ca16a4d662f55084a
train
function
def test_derivatives(): from sympy import Derivative assert zeta(x, a).diff(x) == Derivative(zeta(x, a), x) assert zeta(x, a).diff(a) == -x*zeta(x + 1, a) assert lerchphi( z, s, a).diff(z) == (lerchphi(z, s - 1, a) - a*lerchphi(z, s, a))/z assert lerchphi(z, s, a).diff(a) == -s*lerchphi(z, s...
def test_derivatives():
from sympy import Derivative assert zeta(x, a).diff(x) == Derivative(zeta(x, a), x) assert zeta(x, a).diff(a) == -x*zeta(x + 1, a) assert lerchphi( z, s, a).diff(z) == (lerchphi(z, s - 1, a) - a*lerchphi(z, s, a))/z assert lerchphi(z, s, a).diff(a) == -s*lerchphi(z, s + 1, a) assert poly...
== lerchphi(z, s, 1)*z assert lerchphi(1, x, a).rewrite(zeta) == zeta(x, a) assert z*lerchphi(z, s, 1).rewrite(polylog) == polylog(s, z) def test_derivatives():
66
66
223
5
61
ovolve/sympy
sympy/functions/special/tests/test_zeta_functions.py
Python
test_derivatives
test_derivatives
91
105
91
91
5c12d21d99b6dd2bbe91e1c6f0ccf8dc8e7f126f
bigcode/the-stack
train
a86735b3e44cbb436f3a9adf
train
function
def test_stieltjes(): assert isinstance(stieltjes(x), stieltjes) assert isinstance(stieltjes(x, a), stieltjes) # Zero'th constant EulerGamma assert stieltjes(0) == S.EulerGamma assert stieltjes(0, 1) == S.EulerGamma # Not defined assert stieltjes(nan) == nan assert stieltjes(0, nan) ==...
def test_stieltjes():
assert isinstance(stieltjes(x), stieltjes) assert isinstance(stieltjes(x, a), stieltjes) # Zero'th constant EulerGamma assert stieltjes(0) == S.EulerGamma assert stieltjes(0, 1) == S.EulerGamma # Not defined assert stieltjes(nan) == nan assert stieltjes(0, nan) == nan assert stielt...
2)) assert myexpand(lerchphi(I, s, a), None) assert myexpand(lerchphi(-I, s, a), None) assert myexpand(lerchphi(exp(2*I*pi/5), s, a), None) def test_stieltjes():
64
64
163
6
58
ovolve/sympy
sympy/functions/special/tests/test_zeta_functions.py
Python
test_stieltjes
test_stieltjes
160
174
160
160
992fd3fcb125b0437147f844c2189907f695ba92
bigcode/the-stack
train
33f51cd91355994c654456a7
train
function
def test_dirichlet_eta_eval(): assert dirichlet_eta(0) == Rational(1, 2) assert dirichlet_eta(-1) == Rational(1, 4) assert dirichlet_eta(1) == log(2) assert dirichlet_eta(2) == pi**2/12 assert dirichlet_eta(4) == pi**4*Rational(7, 720)
def test_dirichlet_eta_eval():
assert dirichlet_eta(0) == Rational(1, 2) assert dirichlet_eta(-1) == Rational(1, 4) assert dirichlet_eta(1) == log(2) assert dirichlet_eta(2) == pi**2/12 assert dirichlet_eta(4) == pi**4*Rational(7, 720)
e-19) def test_zeta_series(): assert zeta(x, a).series(a, 0, 2) == \ zeta(x, 0) - x*a*zeta(x + 1, 0) + O(a**2) def test_dirichlet_eta_eval():
64
64
94
8
56
ovolve/sympy
sympy/functions/special/tests/test_zeta_functions.py
Python
test_dirichlet_eta_eval
test_dirichlet_eta_eval
69
75
69
70
205322d6cdfd0be4ae693338233c1e84793f8356
bigcode/the-stack
train
31ec67895c59287a986c9e92
train
function
def test_issue_10475(): a = Symbol('a', real=True) b = Symbol('b', positive=True) s = Symbol('s', zero=False) assert zeta(2 + I).is_finite assert zeta(1).is_finite is False assert zeta(x).is_finite is None assert zeta(x + I).is_finite is None assert zeta(a).is_finite is None assert ...
def test_issue_10475():
a = Symbol('a', real=True) b = Symbol('b', positive=True) s = Symbol('s', zero=False) assert zeta(2 + I).is_finite assert zeta(1).is_finite is False assert zeta(x).is_finite is None assert zeta(x + I).is_finite is None assert zeta(a).is_finite is None assert zeta(b).is_finite is Non...
jes(0, 0.5).evalf() - 1.963510026) < 1E-9 assert abs(stieltjes(1, 2).evalf() + 0.072815845 ) < 1E-9 def test_issue_10475():
64
64
191
7
56
ovolve/sympy
sympy/functions/special/tests/test_zeta_functions.py
Python
test_issue_10475
test_issue_10475
183
198
183
183
a3859b32c644b4471a3790517d8e9554aa89aa67
bigcode/the-stack
train
c468b577ea6c98f4060b0f69
train
function
def test_zeta_series(): assert zeta(x, a).series(a, 0, 2) == \ zeta(x, 0) - x*a*zeta(x + 1, 0) + O(a**2)
def test_zeta_series():
assert zeta(x, a).series(a, 0, 2) == \ zeta(x, 0) - x*a*zeta(x + 1, 0) + O(a**2)
2) assert zeta(0, -2) == Rational(3, 2) assert zeta( 3).evalf(20).epsilon_eq(Float("1.2020569031595942854", 20), 1e-19) def test_zeta_series():
64
64
52
6
58
ovolve/sympy
sympy/functions/special/tests/test_zeta_functions.py
Python
test_zeta_series
test_zeta_series
64
66
64
64
26e72bdaa4e058cf713711f7a53042046c45f7fb
bigcode/the-stack
train
3a5189adfd0a6de38f7e4562
train
function
def test_zeta_eval(): assert zeta(nan) == nan assert zeta(x, nan) == nan assert zeta(0) == Rational(-1, 2) assert zeta(0, x) == Rational(1, 2) - x assert zeta(1) == zoo assert zeta(1, 2) == zoo assert zeta(1, -7) == zoo assert zeta(1, x) == zoo assert zeta(2, 1) == pi**2/6 a...
def test_zeta_eval():
assert zeta(nan) == nan assert zeta(x, nan) == nan assert zeta(0) == Rational(-1, 2) assert zeta(0, x) == Rational(1, 2) - x assert zeta(1) == zoo assert zeta(1, 2) == zoo assert zeta(1, -7) == zoo assert zeta(1, x) == zoo assert zeta(2, 1) == pi**2/6 assert zeta(2) == pi**2/...
from sympy import (Symbol, zeta, nan, Rational, Float, pi, dirichlet_eta, log, zoo, expand_func, polylog, lerchphi, S, exp, sqrt, I, exp_polar, polar_lift, O, stieltjes) from sympy.utilities.randtest import (test_derivative_numerically as td, random_complex_nu...
125
181
606
6
119
ovolve/sympy
sympy/functions/special/tests/test_zeta_functions.py
Python
test_zeta_eval
test_zeta_eval
13
61
13
14
6001b00b09476d977f91f7ee8eda373e1d5f9bd2
bigcode/the-stack
train
a7344c534cafeb3069da146e
train
class
class AwesomeModel(models.Model): name = models.CharField(max_length=100, unique=True)
class AwesomeModel(models.Model):
name = models.CharField(max_length=100, unique=True)
from django.db import models class AwesomeModel(models.Model):
12
64
20
6
5
jrobichaud/django-awesome-presentations
testing_migrations/models.py
Python
AwesomeModel
AwesomeModel
4
5
4
4
1c0618de1d3d370afe68064b64c2787737d1d658
bigcode/the-stack
train
876bd23d9db5ad5b7fc7cd7f
train
class
class KittenName(models.Model): kitten = models.ForeignKey(Kitten, on_delete=models.CASCADE) name = models.CharField(max_length=100)
class KittenName(models.Model):
kitten = models.ForeignKey(Kitten, on_delete=models.CASCADE) name = models.CharField(max_length=100)
models.CharField(max_length=100, unique=True) class Kitten(models.Model): """ Kitten used to have a `name = models.CharField(max_length=100)` and was replaced by a KittenName model in order support multiple names """ class KittenName(models.Model):
63
64
33
7
56
jrobichaud/django-awesome-presentations
testing_migrations/models.py
Python
KittenName
KittenName
15
17
15
15
4ccb049d402202a999a9f4eb0af799c80b4a434a
bigcode/the-stack
train
9e34246cf1df5a768429ab0e
train
class
class Kitten(models.Model): """ Kitten used to have a `name = models.CharField(max_length=100)` and was replaced by a KittenName model in order support multiple names """
class Kitten(models.Model):
""" Kitten used to have a `name = models.CharField(max_length=100)` and was replaced by a KittenName model in order support multiple names """
from django.db import models class AwesomeModel(models.Model): name = models.CharField(max_length=100, unique=True) class Kitten(models.Model):
32
64
45
6
26
jrobichaud/django-awesome-presentations
testing_migrations/models.py
Python
Kitten
Kitten
8
12
8
8
c3ade34bc29c6b732059400c5d120e058853f420
bigcode/the-stack
train
4d895bfc562ef56b9eb93924
train
function
def objectives(point): print('objective is not needed when options["RCI_mode"]=True')
def objectives(point):
print('objective is not needed when options["RCI_mode"]=True')
+ "/../../../GPTune/")) from gptune import * # import all from autotune.problem import * from autotune.space import * from autotune.search import * from callopentuner import OpenTuner from callhpbandster import HpBandSter import math ################################################################################...
64
64
20
5
58
kadircs/GPTune
examples/MFEM_RCI/mfem_maxwell3d_RCI.py
Python
objectives
objectives
56
57
56
56
6fd54d602e27ebbd0b4eafbfc4b9d3215e4f3ad9
bigcode/the-stack
train
ccfa6c019626cb1e99a19cb9
train
function
def parse_args(): parser = argparse.ArgumentParser() # Problem related arguments parser.add_argument('-obj', type=str, default='time', help='Tuning objective (time or memory)') # Machine related arguments parser.add_argument('-nprocmin_pernode', type=int, default=1,help='Minimum number of MPIs per machine node ...
def parse_args():
parser = argparse.ArgumentParser() # Problem related arguments parser.add_argument('-obj', type=str, default='time', help='Tuning objective (time or memory)') # Machine related arguments parser.add_argument('-nprocmin_pernode', type=int, default=1,help='Minimum number of MPIs per machine node for the application...
tid]) print(" Os ", data.O[tid].tolist()) print(' Popt ', data.P[tid][np.argmin(data.O[tid])], 'Oopt ', min(data.O[tid])[0], 'nth ', np.argmin(data.O[tid])) def parse_args():
63
64
149
4
59
kadircs/GPTune
examples/MFEM_RCI/mfem_maxwell3d_RCI.py
Python
parse_args
parse_args
151
165
151
152
304d16536f654369ae6d2c776417fdd30b0dd156
bigcode/the-stack
train
38f13ca7d5110eb3e1f63d1d
train
function
def main(): # Parse command line arguments args = parse_args() # Extract arguments nprocmin_pernode = args.nprocmin_pernode optimization = args.optimization nrun = args.nrun obj = args.obj target=obj (machine, processor, nodes, cores) = GetMachineConfiguration() print ("machine: " + machine + " process...
def main(): # Parse command line arguments
args = parse_args() # Extract arguments nprocmin_pernode = args.nprocmin_pernode optimization = args.optimization nrun = args.nrun obj = args.obj target=obj (machine, processor, nodes, cores) = GetMachineConfiguration() print ("machine: " + machine + " processor: " + processor + " num_nodes: " + str(nodes)...
, prepare # derivative works, and perform publicly and display publicly, and to permit # other to do so. # ################################################################################ """ Example of invocation of this script: python mfem_maxwell3d_RCI.py -nprocmin_pernode 1 -nrun 800 -obj time where: -nprocmin_pe...
255
256
987
11
244
kadircs/GPTune
examples/MFEM_RCI/mfem_maxwell3d_RCI.py
Python
main
main
60
148
60
64
623e53c01619ea4ae48eb9b9f1d4584e0bceddd6
bigcode/the-stack
train
56e424fc76a0dd821764bdbd
train
class
class StorageArrayPortStatsInfo(NetAppObject): """ Contains statistics about an array port. """ _node = None @property def node(self): """ Node name of array's target port. """ return self._node @node.setter def node(self, val): if val != None...
class StorageArrayPortStatsInfo(NetAppObject):
""" Contains statistics about an array port. """ _node = None @property def node(self): """ Node name of array's target port. """ return self._node @node.setter def node(self, val): if val != None: self.validate('node', val) ...
from netapp.netapp_object import NetAppObject class StorageArrayPortStatsInfo(NetAppObject):
21
256
2,473
10
10
radekg/netapp-ontap-lib-get
generated-libraries/python/netapp/storage_array/storage_array_port_stats_info.py
Python
StorageArrayPortStatsInfo
StorageArrayPortStatsInfo
3
321
3
3
f4d24ca66388bc51e63bbdf7024048d2c8319688
bigcode/the-stack
train
3d161d0be3be6ad2cf938d36
train
function
def safer_getattr(object, name, default=None, getattr=getattr): '''Getattr implementation which prevents using format on string objects. format() is considered harmful: http://lucumr.pocoo.org/2016/12/29/careful-with-str-format/ ''' if name == 'format' and isinstance(object, str): raise No...
def safer_getattr(object, name, default=None, getattr=getattr):
'''Getattr implementation which prevents using format on string objects. format() is considered harmful: http://lucumr.pocoo.org/2016/12/29/careful-with-str-format/ ''' if name == 'format' and isinstance(object, str): raise NotImplementedError( 'Using format() on a %s is not sa...
, 'any': any, 'all': all, } builtins = safe_builtins.copy() builtins.update(utility_builtins) builtins.update(limited_builtins) builtins.update(extra_builtins) def safer_getattr(object, name, default=None, getattr=getattr):
64
64
153
15
49
osoblanco/aim
aim/storage/query.py
Python
safer_getattr
safer_getattr
37
53
37
37
978445cab30dee273c7d9bd346e4ce8b4f546883
bigcode/the-stack
train
e2a1fd64af6fc00b746236fb
train
class
class RestrictedPythonQuery(Query): allowed_params = {'run', 'metric', 'images', 'distributions','dictionaries'} def __init__( self, query: str ): stripped_query = strip_query(query) expr = query_add_default_expr(stripped_query) super().__init__(expr=expr) se...
class RestrictedPythonQuery(Query):
allowed_params = {'run', 'metric', 'images', 'distributions','dictionaries'} def __init__( self, query: str ): stripped_query = strip_query(query) expr = query_add_default_expr(stripped_query) super().__init__(expr=expr) self._checker = compile_checker(expr) ...
ived == False' # add the default expression to the query if needed if not query: return default_expression else: if 'run.archived' not in query: return f'{default_expression} and {query}' else: return query class RestrictedPythonQuery(Query):
64
64
197
6
57
osoblanco/aim
aim/storage/query.py
Python
RestrictedPythonQuery
RestrictedPythonQuery
147
178
147
147
0669c2662cef89eb06694a1229ca64b3b63df1db
bigcode/the-stack
train
fe2544169cdc6110510d8bde
train
function
def syntax_error_check(expr): if not expr: return expr = strip_query(expr) try: compile_restricted(expr, filename='<inline code>', mode='eval') except SyntaxError: compile(expr, filename='<inline code>', mode='eval')
def syntax_error_check(expr):
if not expr: return expr = strip_query(expr) try: compile_restricted(expr, filename='<inline code>', mode='eval') except SyntaxError: compile(expr, filename='<inline code>', mode='eval')
**params ): return self.check(**params) @lru_cache(maxsize=100) def compile_checker(expr): source_code = expr byte_code = compile_restricted(source_code, filename='<inline code>', mode='eval') return byte_code def syntax_er...
64
64
59
6
57
osoblanco/aim
aim/storage/query.py
Python
syntax_error_check
syntax_error_check
102
111
102
102
e5eb3a0f89b5d4e83678f8a71785316433dfea48
bigcode/the-stack
train
aa70bf31b85617a9799678c6
train
function
@lru_cache(maxsize=100) def query_add_default_expr(query: str) -> str: default_expression = 'run.archived == False' # add the default expression to the query if needed if not query: return default_expression else: if 'run.archived' not in query: return f'{default_expression} ...
@lru_cache(maxsize=100) def query_add_default_expr(query: str) -> str:
default_expression = 'run.archived == False' # add the default expression to the query if needed if not query: return default_expression else: if 'run.archived' not in query: return f'{default_expression} and {query}' else: return query
flags=re.IGNORECASE)[1] except IndexError: stripped_query = '' if stripped_query: stripped_query = f'({stripped_query.strip()})' return stripped_query @lru_cache(maxsize=100) def query_add_default_expr(query: str) -> str:
64
64
86
21
42
osoblanco/aim
aim/storage/query.py
Python
query_add_default_expr
query_add_default_expr
134
144
134
135
fc8da393ca02a21569783a99fbbf7c135e299be6
bigcode/the-stack
train
3b45dbaea436d43d9c4500d7
train
function
@lru_cache(maxsize=100) def strip_query(query: str) -> str: import re stripped_query = query.strip() # cut the hardcoded part (SELECT something IF) if query.lower().startswith('select'): try: stripped_query = re.split('if', query, ...
@lru_cache(maxsize=100) def strip_query(query: str) -> str:
import re stripped_query = query.strip() # cut the hardcoded part (SELECT something IF) if query.lower().startswith('select'): try: stripped_query = re.split('if', query, maxsplit=1, ...
expr = strip_query(expr) try: compile_restricted(expr, filename='<inline code>', mode='eval') except SyntaxError: compile(expr, filename='<inline code>', mode='eval') @lru_cache(maxsize=100) def strip_query(query: str) -> str:
64
64
115
19
45
osoblanco/aim
aim/storage/query.py
Python
strip_query
strip_query
114
131
114
115
58ce20ca155c8ef9387a8b2327c32617f9754b39
bigcode/the-stack
train
7dd03894406418de06fb8e22
train
class
class Query: def __init__( self, expr: str ): self.expr = expr @abstractmethod def check( self, **params ) -> bool: ... def __call__( self, **params ): return self.check(**params)
class Query:
def __init__( self, expr: str ): self.expr = expr @abstractmethod def check( self, **params ) -> bool: ... def __call__( self, **params ): return self.check(**params)
, "_getiter_": iter, "_getitem_": default_guarded_getitem, "_iter_unpack_sequence_": guarded_iter_unpack_sequence, "_unpack_sequence_": guarded_unpack_sequence } logger = logging.getLogger(__name__) # CODE_FORMAT = """{expr})""" class Query:
64
64
68
3
61
osoblanco/aim
aim/storage/query.py
Python
Query
Query
72
90
72
72
87afe295d38b2fdcaacd3a9dd7edfac0e8f82157
bigcode/the-stack
train
def5d79c33cbb3d86e5a5db5
train
function
@lru_cache(maxsize=100) def compile_checker(expr): source_code = expr byte_code = compile_restricted(source_code, filename='<inline code>', mode='eval') return byte_code
@lru_cache(maxsize=100) def compile_checker(expr):
source_code = expr byte_code = compile_restricted(source_code, filename='<inline code>', mode='eval') return byte_code
self.expr = expr @abstractmethod def check( self, **params ) -> bool: ... def __call__( self, **params ): return self.check(**params) @lru_cache(maxsize=100) def compile_checker(expr):
64
64
46
14
50
osoblanco/aim
aim/storage/query.py
Python
compile_checker
compile_checker
93
99
93
94
27fdcf99b5bb6f4dbebffab7049d045286c8318f
bigcode/the-stack
train
cf1204a7c454730191470963
train
class
class DAGNN(torch.nn.Module): def __init__(self, args): super(DAGNN, self).__init__() for k, v in vars(args).items(): setattr(self, k, v) self.lin1 = Linear(args.num_feats, self.dim_hidden) self.lin2 = Linear(self.dim_hidden, args.num_classes) if args.dataset == '...
class DAGNN(torch.nn.Module):
def __init__(self, args): super(DAGNN, self).__init__() for k, v in vars(args).items(): setattr(self, k, v) self.lin1 = Linear(args.num_feats, self.dim_hidden) self.lin2 = Linear(self.dim_hidden, args.num_classes) if args.dataset == 'ogbn-arxiv': self....
(retain_score, pps).squeeze() return out def message(self, x_j, norm): return norm.view(-1, 1) * x_j def __repr__(self): return '{}(K={})'.format(self.__class__.__name__, self.K) def reset_parameters(self): self.proj.reset_parameters() class DAGNN(torch.nn.Module):
83
83
278
7
76
ngohienduong/Deep_GCN_Benchmarking
models/DAGNN.py
Python
DAGNN
DAGNN
76
106
76
76
8239115c173e0f26802b4626ee3c916436cd43fc
bigcode/the-stack
train
c1da7f3f9d183d36ef9588ae
train
function
def gcn_norm(edge_index, edge_weight=None, num_nodes=None, improved=False, add_self_loops=True, dtype=None): fill_value = 2. if improved else 1. num_nodes = int(edge_index.max()) + 1 if num_nodes is None else num_nodes if edge_weight is None: edge_weight = torch.ones((edge_index.size(1)...
def gcn_norm(edge_index, edge_weight=None, num_nodes=None, improved=False, add_self_loops=True, dtype=None):
fill_value = 2. if improved else 1. num_nodes = int(edge_index.max()) + 1 if num_nodes is None else num_nodes if edge_weight is None: edge_weight = torch.ones((edge_index.size(1),), dtype=dtype, device=edge_index.device) if add_self_loops: edge_index, tm...
torch.nn.functional as F from torch.nn import Linear from torch_geometric.nn.conv import MessagePassing from torch_geometric.utils import add_remaining_self_loops from torch_scatter import scatter_add def gcn_norm(edge_index, edge_weight=None, num_nodes=None, improved=False, add_self_loops=True, dtype=Non...
70
70
234
28
41
ngohienduong/Deep_GCN_Benchmarking
models/DAGNN.py
Python
gcn_norm
gcn_norm
9
27
9
10
65409a2b2232d591f027f528a57127d4757d9a3a
bigcode/the-stack
train
f7638bb281d0803f0481579d
train
class
class Prop(MessagePassing): def __init__(self, num_classes, K, bias=True, cached=True, **kwargs): super(Prop, self).__init__(aggr='add', **kwargs) self.K = K self.proj = Linear(num_classes, 1) self.cached = cached self.edge_index = None self.norm = None def forw...
class Prop(MessagePassing):
def __init__(self, num_classes, K, bias=True, cached=True, **kwargs): super(Prop, self).__init__(aggr='add', **kwargs) self.K = K self.proj = Linear(num_classes, 1) self.cached = cached self.edge_index = None self.norm = None def forward(self, x, edge_index, edg...
_value, num_nodes) assert tmp_edge_weight is not None edge_weight = tmp_edge_weight row, col = edge_index[0], edge_index[1] deg = scatter_add(edge_weight, col, dim=0, dim_size=num_nodes) deg_inv_sqrt = deg.pow_(-0.5) deg_inv_sqrt.masked_fill_(deg_inv_sqrt == float('inf'), 0) return ...
117
117
392
5
112
ngohienduong/Deep_GCN_Benchmarking
models/DAGNN.py
Python
Prop
Prop
30
73
30
30
f1501ebb36a910839bfe9c1c2e250b636f824aa3
bigcode/the-stack
train
7635d69318097f0769ad6328
train
function
def get_real_test_list(root_folder = TEST_ROOT, data_folder=Data_Folder, name='Agriculture', bands=['RGB']): dict_list = {} basname = [img_basename(f) for f in os.listdir(os.path.join(root_folder, 'nir'))] dict_list['all'] = basname test_dict = { IDS: dict_list, IMG: [os.path.join(data_...
def get_real_test_list(root_folder = TEST_ROOT, data_folder=Data_Folder, name='Agriculture', bands=['RGB']):
dict_list = {} basname = [img_basename(f) for f in os.listdir(os.path.join(root_folder, 'nir'))] dict_list['all'] = basname test_dict = { IDS: dict_list, IMG: [os.path.join(data_folder[name]['ROOT'], 'test', data_folder[name][band]) for band in bands], # GT: os.path.join(data_fo...
print('train set -------', len(train_dict[GT])) print('val set ---------', len(val_dict[GT])) return train_dict, val_dict, test_dict def get_real_test_list(root_folder = TEST_ROOT, data_folder=Data_Folder, name='Agriculture', bands=['RGB']):
64
64
157
27
36
PKSingh0017/MSCG-Net
data/AgricultureVision/pre_process.py
Python
get_real_test_list
get_real_test_list
178
189
178
178
a91caec1008066368c3e6b90bd4b5c296a30cff8
bigcode/the-stack
train
4bf44423496312004b91439a
train
function
def get_training_list(root_folder = TRAIN_ROOT, count_label=True): dict_list = {} basname = [img_basename(f) for f in os.listdir(os.path.join(root_folder, 'images/nir'))] if count_label: for key in labels_folder.keys(): no_zero_files=[] for fname in basname: g...
def get_training_list(root_folder = TRAIN_ROOT, count_label=True):
dict_list = {} basname = [img_basename(f) for f in os.listdir(os.path.join(root_folder, 'images/nir'))] if count_label: for key in labels_folder.keys(): no_zero_files=[] for fname in basname: gt = np.array(cv2.imread(os.path.join(root_folder, 'labels', key, fn...
.path.join(root_folder, key, gt), -1) / 255, dtype=int) gtz[mask == 0] = 255 cv2.imwrite(os.path.join(root_folder, out_path, gt), gtz) def get_training_list(root_folder = TRAIN_ROOT, count_label=True):
64
64
136
14
50
PKSingh0017/MSCG-Net
data/AgricultureVision/pre_process.py
Python
get_training_list
get_training_list
114
127
114
114
5601b012e6659d1d90acea386851bd019fbf047d
bigcode/the-stack
train
caf20ef029e3d4e5027d57b5
train
function
def prepare_gt(root_folder = TRAIN_ROOT, out_path='gt'): if not os.path.exists(os.path.join(root_folder, out_path)): print('----------creating groundtruth data for training./.val---------------') check_mkdir(os.path.join(root_folder, out_path)) basname = [img_basename(f) for f in os.listdir(...
def prepare_gt(root_folder = TRAIN_ROOT, out_path='gt'):
if not os.path.exists(os.path.join(root_folder, out_path)): print('----------creating groundtruth data for training./.val---------------') check_mkdir(os.path.join(root_folder, out_path)) basname = [img_basename(f) for f in os.listdir(os.path.join(root_folder,'images/rgb'))] gt = bas...
def check_mkdir(dir_name): if not os.path.exists(dir_name): os.mkdir(dir_name) def img_basename(filename): return os.path.basename(os.path.splitext(filename)[0]) def is_image(filename): return any(filename.endswith(ext) for ext in ['.png','.jpg']) def prepare_gt(root_folder = TRAIN_ROOT, out_pat...
75
76
256
14
61
PKSingh0017/MSCG-Net
data/AgricultureVision/pre_process.py
Python
prepare_gt
prepare_gt
94
111
94
94
f46407b705f4ac82f8ab61dd3e90119418605e09
bigcode/the-stack
train
a7d5c8f9dafd7c14c2989fef
train
function
def split_train_val_test_sets(data_folder=Data_Folder, name='Agriculture', bands=['NIR','RGB'], KF=3, k=1, seeds=69278): train_id, t_list = get_training_list(root_folder=TRAIN_ROOT, count_label=False) val_id, v_list = get_training_list(root_folder=VAL_ROOT, count_label=False) if KF >=2: kf = KFold...
def split_train_val_test_sets(data_folder=Data_Folder, name='Agriculture', bands=['NIR','RGB'], KF=3, k=1, seeds=69278):
train_id, t_list = get_training_list(root_folder=TRAIN_ROOT, count_label=False) val_id, v_list = get_training_list(root_folder=VAL_ROOT, count_label=False) if KF >=2: kf = KFold(n_splits=KF, shuffle=True, random_state=seeds) val_ids = np.array(v_list) idx = list(kf.split(np.array(va...
img_basename(f) for f in os.listdir(os.path.join(root_folder, 'images/nir'))] if count_label: for key in labels_folder.keys(): no_zero_files=[] for fname in basname: gt = np.array(cv2.imread(os.path.join(root_folder, 'labels', key, fname+'.png'), -1)) ...
164
164
547
38
126
PKSingh0017/MSCG-Net
data/AgricultureVision/pre_process.py
Python
split_train_val_test_sets
split_train_val_test_sets
131
175
131
132
de16e19c17f1be049d89010e7162511d553d5cb7
bigcode/the-stack
train
53d025e8259f248414c5b603
train
function
def check_mkdir(dir_name): if not os.path.exists(dir_name): os.mkdir(dir_name)
def check_mkdir(dir_name):
if not os.path.exists(dir_name): os.mkdir(dir_name)
'images/nir/{}.jpg', 'SHAPE': (512, 512), 'GT': 'gt/{}.png', }, } IMG = 'images' # RGB or IRRG, rgb/nir GT = 'gt' IDS = 'IDs' def check_mkdir(dir_name):
64
64
22
7
57
PKSingh0017/MSCG-Net
data/AgricultureVision/pre_process.py
Python
check_mkdir
check_mkdir
81
83
81
81
6caceb8d0e53b8308b29d7ef836b63c196bb95d4
bigcode/the-stack
train
6c040354e555ef319f7a2c2a
train
function
def is_image(filename): return any(filename.endswith(ext) for ext in ['.png','.jpg'])
def is_image(filename):
return any(filename.endswith(ext) for ext in ['.png','.jpg'])
RGB or IRRG, rgb/nir GT = 'gt' IDS = 'IDs' def check_mkdir(dir_name): if not os.path.exists(dir_name): os.mkdir(dir_name) def img_basename(filename): return os.path.basename(os.path.splitext(filename)[0]) def is_image(filename):
64
64
21
5
59
PKSingh0017/MSCG-Net
data/AgricultureVision/pre_process.py
Python
is_image
is_image
90
91
90
90
4c08b761cf4f845bb2cfb9cc40ad829d80119165
bigcode/the-stack
train
a9b47856a17b4c4ab97bf886
train
function
def img_basename(filename): return os.path.basename(os.path.splitext(filename)[0])
def img_basename(filename):
return os.path.basename(os.path.splitext(filename)[0])
GT': 'gt/{}.png', }, } IMG = 'images' # RGB or IRRG, rgb/nir GT = 'gt' IDS = 'IDs' def check_mkdir(dir_name): if not os.path.exists(dir_name): os.mkdir(dir_name) def img_basename(filename):
64
64
18
6
58
PKSingh0017/MSCG-Net
data/AgricultureVision/pre_process.py
Python
img_basename
img_basename
86
87
86
86
c9c984e6799262219abe69127e0b801325c61a1f
bigcode/the-stack
train
62fe8d4d9f19b1876c53006f
train
class
class Function_Bessel_I(BuiltinFunction): r""" The Bessel I function, or the Modified Bessel Function of the First Kind. DEFINITION: .. MATH:: I_\nu(x) = i^{-\nu} J_\nu(ix) EXAMPLES:: sage: bessel_I(1, x) bessel_I(1, x) sage: bessel_I(1.0, 1.0) 0.56515910...
class Function_Bessel_I(BuiltinFunction):
r""" The Bessel I function, or the Modified Bessel Function of the First Kind. DEFINITION: .. MATH:: I_\nu(x) = i^{-\nu} J_\nu(ix) EXAMPLES:: sage: bessel_I(1, x) bessel_I(1, x) sage: bessel_I(1.0, 1.0) 0.565159103992485 sage: n = var('n') ...
function. EXAMPLES:: sage: f(x) = bessel_Y(10, x) sage: derivative(f, x) x |--> -1/2*bessel_Y(11, x) + 1/2*bessel_Y(9, x) sage: nu = var('nu') sage: bessel_Y(nu, x).diff(nu) Traceback (most recent call last): ... ...
256
256
1,510
9
247
fredstro/sage
src/sage/functions/bessel.py
Python
Function_Bessel_I
Function_Bessel_I
565
730
565
565
ac35461e7402133d0cb254f3be90e4262a572701
bigcode/the-stack
train
14ad6838d0a58c583b18ce58
train
class
class Function_Bessel_K(BuiltinFunction): r""" The Bessel K function, or the modified Bessel function of the second kind. DEFINITION: .. MATH:: K_\nu(x) = \frac{\pi}{2} \frac{I_{-\nu}(x)-I_\nu(x)}{\sin(\nu \pi)} EXAMPLES:: sage: bessel_K(1, x) bessel_K(1, x) sage...
class Function_Bessel_K(BuiltinFunction):
r""" The Bessel K function, or the modified Bessel function of the second kind. DEFINITION: .. MATH:: K_\nu(x) = \frac{\pi}{2} \frac{I_{-\nu}(x)-I_\nu(x)}{\sin(\nu \pi)} EXAMPLES:: sage: bessel_K(1, x) bessel_K(1, x) sage: bessel_K(1.0, 1.0) 0.60190723019...
x`. EXAMPLES:: sage: f(z) = bessel_I(10, x) sage: derivative(f, x) z |--> 1/2*bessel_I(11, x) + 1/2*bessel_I(9, x) sage: nu = var('nu') sage: bessel_I(nu, x).diff(nu) Traceback (most recent call last): ... NotImple...
256
256
1,645
9
247
fredstro/sage
src/sage/functions/bessel.py
Python
Function_Bessel_K
Function_Bessel_K
735
907
735
735
e42c7d64459a578f0160e9eec37366cd535e63b3
bigcode/the-stack
train
c47efd136c31e1013fc3b01c
train
function
def Bessel(*args, **kwds): """ A function factory that produces symbolic I, J, K, and Y Bessel functions. There are several ways to call this function: - ``Bessel(order, type)`` - ``Bessel(order)`` -- type defaults to 'J' - ``Bessel(order, typ=T)`` - ``Bessel(typ=T)`` -- ord...
def Bessel(*args, **kwds):
""" A function factory that produces symbolic I, J, K, and Y Bessel functions. There are several ways to call this function: - ``Bessel(order, type)`` - ``Bessel(order)`` -- type defaults to 'J' - ``Bessel(order, typ=T)`` - ``Bessel(typ=T)`` -- order is unspecified, this is ...
11, x) - 1/2*bessel_K(9, x) sage: nu = var('nu') sage: bessel_K(nu, x).diff(nu) Traceback (most recent call last): ... NotImplementedError: derivative with respect to order """ if diff_param == 1: return -(bessel_K(n - 1, x) + besse...
256
256
1,895
10
246
fredstro/sage
src/sage/functions/bessel.py
Python
Bessel
Bessel
916
1,080
916
916
0576656a59e27b07cb9f33e8501f28676a9bef63
bigcode/the-stack
train
2452058ec28d2c85e5fabf60
train
class
class Function_Bessel_J(BuiltinFunction): r""" The Bessel J Function, denoted by bessel_J(`\nu`, x) or `J_\nu(x)`. As a Taylor series about `x=0` it is equal to: .. MATH:: J_\nu(x) = \sum_{k=0}^\infty \frac{(-1)^k}{k! \Gamma(k+\nu+1)} \left(\frac{x}{2}\right)^{2k+\nu} The paramete...
class Function_Bessel_J(BuiltinFunction):
r""" The Bessel J Function, denoted by bessel_J(`\nu`, x) or `J_\nu(x)`. As a Taylor series about `x=0` it is equal to: .. MATH:: J_\nu(x) = \sum_{k=0}^\infty \frac{(-1)^k}{k! \Gamma(k+\nu+1)} \left(\frac{x}{2}\right)^{2k+\nu} The parameter `\nu` is called the order and may be any...
of the GNU General Public License (GPL) # # This code is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # The full text of the ...
256
256
1,637
9
246
fredstro/sage
src/sage/functions/bessel.py
Python
Function_Bessel_J
Function_Bessel_J
207
381
207
207
df256494bf271cce7b76f38efe05d7d746807afc
bigcode/the-stack
train
044a495c3ea5fea44ee4ba66
train
class
class Function_Struve_L(BuiltinFunction): r""" The modified Struve functions. .. MATH:: \mathrm{L}_\alpha(x) = -i\cdot e^{-\frac{i\alpha\pi}{2}}\cdot\mathrm{H}_\alpha(ix) EXAMPLES:: sage: struve_L(2,x) struve_L(2, x) sage: struve_L(1/2,pi).n() 4.76805417696286...
class Function_Struve_L(BuiltinFunction):
r""" The modified Struve functions. .. MATH:: \mathrm{L}_\alpha(x) = -i\cdot e^{-\frac{i\alpha\pi}{2}}\cdot\mathrm{H}_\alpha(ix) EXAMPLES:: sage: struve_L(2,x) struve_L(2, x) sage: struve_L(1/2,pi).n() 4.76805417696286 sage: diff(struve_L(1,x),x) ...
def _derivative_(self, a, z, diff_param=None): """ EXAMPLES:: sage: diff(struve_H(3/2,x),x) -1/2*sqrt(2)*sqrt(1/(pi*x))*(cos(x) - 1) + 1/16*sqrt(2)*x^(3/2)/sqrt(pi) - 1/2*struve_H(5/2, x) """ if diff_param == 0: raise ValueError("cannot differentiate...
256
256
1,015
9
247
fredstro/sage
src/sage/functions/bessel.py
Python
Function_Struve_L
Function_Struve_L
1,201
1,309
1,201
1,201
bf0e3e2cf89377d8b05b71c07f4d6ec72e96d276
bigcode/the-stack
train
1076a0b40a966124657c41bc
train
class
class Function_Bessel_Y(BuiltinFunction): r""" The Bessel Y functions, also known as the Bessel functions of the second kind, Weber functions, or Neumann functions. `Y_\nu(z)` is a holomorphic function of `z` on the complex plane, cut along the negative real axis. It is singular at `z = 0`. When `z...
class Function_Bessel_Y(BuiltinFunction):
r""" The Bessel Y functions, also known as the Bessel functions of the second kind, Weber functions, or Neumann functions. `Y_\nu(z)` is a holomorphic function of `z` on the complex plane, cut along the negative real axis. It is singular at `z = 0`. When `z` is fixed, `Y_\nu(z)` is an entire fu...
function. EXAMPLES:: sage: f(z) = bessel_J(10, z) sage: derivative(f, z) z |--> -1/2*bessel_J(11, z) + 1/2*bessel_J(9, z) sage: nu = var('nu') sage: bessel_J(nu, z).diff(nu) Traceback (most recent call last): ... ...
256
256
1,695
9
247
fredstro/sage
src/sage/functions/bessel.py
Python
Function_Bessel_Y
Function_Bessel_Y
386
560
386
386
8aed9797f4faf9aff0d9f842a5061cb7343825e7
bigcode/the-stack
train
b5ada489573bc8fdd6a4abb9
train
class
class Function_Struve_H(BuiltinFunction): r""" The Struve functions, solutions to the non-homogeneous Bessel differential equation: .. MATH:: x^2\frac{d^2y}{dx^2}+x\frac{dy}{dx}+(x^2-\alpha^2)y=\frac{4\bigl(\frac{x}{2}\bigr)^{\alpha+1}}{\sqrt\pi\Gamma(\alpha+\tfrac12)}, .. MATH:: \ma...
class Function_Struve_H(BuiltinFunction):
r""" The Struve functions, solutions to the non-homogeneous Bessel differential equation: .. MATH:: x^2\frac{d^2y}{dx^2}+x\frac{dy}{dx}+(x^2-\alpha^2)y=\frac{4\bigl(\frac{x}{2}\bigr)^{\alpha+1}}{\sqrt\pi\Gamma(\alpha+\tfrac12)}, .. MATH:: \mathrm{H}_\alpha(x) = y(x) EXAMPLES:: ...
_order = args[0] _type = args[1] _nargs = 1 else: raise ValueError("Too many arguments (%s given)" % str(len(args))) # check for type inconsistency if _type is not None and 'typ' in kwds and _type != kwds['typ']: raise ValueError("inconsistent types given") # re...
256
256
1,084
9
246
fredstro/sage
src/sage/functions/bessel.py
Python
Function_Struve_H
Function_Struve_H
1,083
1,197
1,083
1,083
8dd7529252bcc2ec05dbcecc4846eb94b804f1e5
bigcode/the-stack
train
b97af1120a6e6b44859190ef
train
class
class BookmarkletTest(T.TestCase, AsyncTestCase): def get_handlers(self): return [ (CreateRequestBookmarkletHandler.url, CreateRequestBookmarkletHandler), (CheckSitesBookmarkletHandler.url, CheckSitesBookmarkletHandler), ] @contextlib.contextmanager def page(self, h...
class BookmarkletTest(T.TestCase, AsyncTestCase):
def get_handlers(self): return [ (CreateRequestBookmarkletHandler.url, CreateRequestBookmarkletHandler), (CheckSitesBookmarkletHandler.url, CheckSitesBookmarkletHandler), ] @contextlib.contextmanager def page(self, handler): with mock.patch.object(handler, "g...
import contextlib import mock import testify as T from pushmanager.handlers import CheckSitesBookmarkletHandler from pushmanager.handlers import CreateRequestBookmarkletHandler from pushmanager.testing.testservlet import AsyncTestCase class BookmarkletTest(T.TestCase, AsyncTestCase):
58
77
259
12
45
Mango-J/pushmanager
pushmanager/tests/test_bookmarklet.py
Python
BookmarkletTest
BookmarkletTest
10
39
10
11
6bc5ae6fdb03d7402319aef1018474e4a12d1e3a
bigcode/the-stack
train
16d1870311561b1092bb1e2d
train
class
class RouteFilter(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, peerings: Opt...
class RouteFilter(pulumi.CustomResource):
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, peerings: Optional[pulumi.Input[Sequence[pulumi.Input[p...
# 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 from ... import _utilities, _tables from...
110
256
2,022
9
101
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/network/v20170901/route_filter.py
Python
RouteFilter
RouteFilter
17
168
17
17
ad00a0befc5d071d382513b6d21d664d70909f45
bigcode/the-stack
train
3687425c2633591eb0a80aa1
train
class
class JobPost(Document): posted = DateTimeField() scraperTaskId = StringField(required=True, max_length=200) city = StringField(required=True, max_length=200) state = StringField(required=True, max_length=2) technologies = ListField() jobkey = StringField(required=True, max_length=200) taskN...
class JobPost(Document):
posted = DateTimeField() scraperTaskId = StringField(required=True, max_length=200) city = StringField(required=True, max_length=200) state = StringField(required=True, max_length=2) technologies = ListField() jobkey = StringField(required=True, max_length=200) taskName = StringField(require...
import datetime import os from mongoengine import * # Connect to db connect(os.environ["DATABASE_NAME"], host='mongo', port=int(os.environ["DB_PORT"]) ) class JobPost(Document):
41
64
139
5
36
JackMGrundy/tech-skills-scraper-and-visualizer
scraper/models/jobPost.py
Python
JobPost
JobPost
8
19
8
8
ae682d6ddb03934913883ec5f53ee641aeb5e3ca
bigcode/the-stack
train
520a2a72f178fb5a24f57f11
train
function
def createJobPost(scraperTaskId, posted, city, state, technologies, jobkey, taskName, username, title, company, experience): return ( JobPost( scraperTaskId = scraperTaskId, posted = posted, city = city, state = state, technologies = technologies, ...
def createJobPost(scraperTaskId, posted, city, state, technologies, jobkey, taskName, username, title, company, experience):
return ( JobPost( scraperTaskId = scraperTaskId, posted = posted, city = city, state = state, technologies = technologies, jobkey = jobkey, taskName = taskName, username = username, title = title, ...
=False, max_length=200) company = StringField(required=False, max_length=200) experience = StringField(required=False, max_length=200) def createJobPost(scraperTaskId, posted, city, state, technologies, jobkey, taskName, username, title, company, experience):
64
64
105
31
33
JackMGrundy/tech-skills-scraper-and-visualizer
scraper/models/jobPost.py
Python
createJobPost
createJobPost
22
37
22
22
4a99acb8221d19b4cd374685e4469ac8b5fd8687
bigcode/the-stack
train
6493e8ce77739ad2f1d6c283
train
function
def set_battery_charging(on): with open('/sys/class/power_supply/battery/charging_enabled', 'w') as f: f.write(f"{1 if on else 0}\n")
def set_battery_charging(on):
with open('/sys/class/power_supply/battery/charging_enabled', 'w') as f: f.write(f"{1 if on else 0}\n")
", lambda x: bool(int(x)), False) def get_battery_charging(): # This does correspond with actually charging return _read_param("/sys/class/power_supply/battery/charge_type", lambda x: x.strip() != "N/A", True) def set_battery_charging(on):
64
64
43
8
56
martpoko/openpilot
selfdrive/thermald/power_monitoring.py
Python
set_battery_charging
set_battery_charging
51
53
51
51
6583446ce7fc091d901cb648f39708af715d04a7
bigcode/the-stack
train
df7d501657ce87f3314ee828
train
class
class PowerMonitoring: def __init__(self): self.params = Params() self.last_measurement_time = None # Used for integration delta self.last_save_time = 0 # Used for saving current value in a param self.power_used_uWh = 0 # Integrated power usage in uWh ...
class PowerMonitoring:
def __init__(self): self.params = Params() self.last_measurement_time = None # Used for integration delta self.last_save_time = 0 # Used for saving current value in a param self.power_used_uWh = 0 # Integrated power usage in uWh since going into offroa...
attery_current(): return _read_param("/sys/class/power_supply/battery/current_now", int) def get_battery_voltage(): return _read_param("/sys/class/power_supply/battery/voltage_now", int) def get_usb_present(): return _read_param("/sys/class/power_supply/usb/present", lambda x: bool(int(x)), False) def get_b...
256
256
1,877
4
251
martpoko/openpilot
selfdrive/thermald/power_monitoring.py
Python
PowerMonitoring
PowerMonitoring
70
237
70
70
5c1b01dc23053b09dd562172883b1c77c0b24edc
bigcode/the-stack
train
4593457f6cf2cba5fc8c1a93
train
function
def get_battery_capacity(): return _read_param("/sys/class/power_supply/battery/capacity", int)
def get_battery_capacity():
return _read_param("/sys/class/power_supply/battery/capacity", int)
e6 CAR_CHARGING_RATE_W = 45 VBATT_PAUSE_CHARGING = 11.5 # Minimum voltage cutoff point for C2 MAX_TIME_OFFROAD_S = 6*3600 # Maxmimu Sleep Time for C2 # Parameters def get_battery_capacity():
64
64
25
6
57
martpoko/openpilot
selfdrive/thermald/power_monitoring.py
Python
get_battery_capacity
get_battery_capacity
24
25
24
24
1fd755f533d3fa273518a52e2adfafc1e44a1cc6
bigcode/the-stack
train
7e7e00092f59c4250b88d6e5
train
function
def get_battery_status(): # This does not correspond with actual charging or not. # If a USB cable is plugged in, it responds with 'Charging', even when charging is disabled return _read_param("/sys/class/power_supply/battery/status", lambda x: x.strip(), '')
def get_battery_status(): # This does not correspond with actual charging or not. # If a USB cable is plugged in, it responds with 'Charging', even when charging is disabled
return _read_param("/sys/class/power_supply/battery/status", lambda x: x.strip(), '')
get_battery_capacity(): return _read_param("/sys/class/power_supply/battery/capacity", int) def get_battery_status(): # This does not correspond with actual charging or not. # If a USB cable is plugged in, it responds with 'Charging', even when charging is disabled
64
64
62
40
24
martpoko/openpilot
selfdrive/thermald/power_monitoring.py
Python
get_battery_status
get_battery_status
28
31
28
30
0cfb30c297534bf1c8bf449f71c2a6bb6d0ee372
bigcode/the-stack
train
de9ffa9f2f6dcfe91e8466da
train
function
def get_battery_voltage(): return _read_param("/sys/class/power_supply/battery/voltage_now", int)
def get_battery_voltage():
return _read_param("/sys/class/power_supply/battery/voltage_now", int)
responds with 'Charging', even when charging is disabled return _read_param("/sys/class/power_supply/battery/status", lambda x: x.strip(), '') def get_battery_current(): return _read_param("/sys/class/power_supply/battery/current_now", int) def get_battery_voltage():
64
64
26
6
58
martpoko/openpilot
selfdrive/thermald/power_monitoring.py
Python
get_battery_voltage
get_battery_voltage
38
39
38
38
3c714859b2546f5d8bc8d0d5dcb6381813cd7b49
bigcode/the-stack
train
b8997e63ad3fa7d482207694
train
function
def get_usb_present(): return _read_param("/sys/class/power_supply/usb/present", lambda x: bool(int(x)), False)
def get_usb_present():
return _read_param("/sys/class/power_supply/usb/present", lambda x: bool(int(x)), False)
", lambda x: x.strip(), '') def get_battery_current(): return _read_param("/sys/class/power_supply/battery/current_now", int) def get_battery_voltage(): return _read_param("/sys/class/power_supply/battery/voltage_now", int) def get_usb_present():
64
64
30
5
59
martpoko/openpilot
selfdrive/thermald/power_monitoring.py
Python
get_usb_present
get_usb_present
42
43
42
42
2c7e947e28828ef9be95e0f8f0bee60df9dc69ab
bigcode/the-stack
train
bcf37e31594d208425644ebf
train
function
def get_battery_charging(): # This does correspond with actually charging return _read_param("/sys/class/power_supply/battery/charge_type", lambda x: x.strip() != "N/A", True)
def get_battery_charging(): # This does correspond with actually charging
return _read_param("/sys/class/power_supply/battery/charge_type", lambda x: x.strip() != "N/A", True)
_read_param("/sys/class/power_supply/battery/voltage_now", int) def get_usb_present(): return _read_param("/sys/class/power_supply/usb/present", lambda x: bool(int(x)), False) def get_battery_charging(): # This does correspond with actually charging
64
64
46
16
48
martpoko/openpilot
selfdrive/thermald/power_monitoring.py
Python
get_battery_charging
get_battery_charging
46
48
46
47
9f18ddc190aba654255e3c7de106ae43d6ec6cfc
bigcode/the-stack
train
97872b091a4a45d5e528b441
train
function
def panda_current_to_actual_current(panda_current): # From white/grey panda schematic return (3.3 - (panda_current * 3.3 / 4096)) / 8.25
def panda_current_to_actual_current(panda_current): # From white/grey panda schematic
return (3.3 - (panda_current * 3.3 / 4096)) / 8.25
0}\n") # Helpers def _read_param(path, parser, default=0): try: with open(path) as f: return parser(f.read()) except Exception: return default def panda_current_to_actual_current(panda_current): # From white/grey panda schematic
64
64
46
19
44
martpoko/openpilot
selfdrive/thermald/power_monitoring.py
Python
panda_current_to_actual_current
panda_current_to_actual_current
65
67
65
66
26ae350bbfcb8b2f2a1b9468dd625c40d9165ab6
bigcode/the-stack
train
173d236a2a8dfc17ef73b3fc
train
function
def get_battery_current(): return _read_param("/sys/class/power_supply/battery/current_now", int)
def get_battery_current():
return _read_param("/sys/class/power_supply/battery/current_now", int)
(): # This does not correspond with actual charging or not. # If a USB cable is plugged in, it responds with 'Charging', even when charging is disabled return _read_param("/sys/class/power_supply/battery/status", lambda x: x.strip(), '') def get_battery_current():
63
64
24
6
57
martpoko/openpilot
selfdrive/thermald/power_monitoring.py
Python
get_battery_current
get_battery_current
34
35
34
34
0c7f5e8f97e6fcc1af3f6fb49db11509e37129a0
bigcode/the-stack
train
1db237dc96322d33a815af7a
train
function
def _read_param(path, parser, default=0): try: with open(path) as f: return parser(f.read()) except Exception: return default
def _read_param(path, parser, default=0):
try: with open(path) as f: return parser(f.read()) except Exception: return default
"N/A", True) def set_battery_charging(on): with open('/sys/class/power_supply/battery/charging_enabled', 'w') as f: f.write(f"{1 if on else 0}\n") # Helpers def _read_param(path, parser, default=0):
64
64
37
12
51
martpoko/openpilot
selfdrive/thermald/power_monitoring.py
Python
_read_param
_read_param
57
62
57
57
1622fbc9531117f4c61108a3e112d68014a19969
bigcode/the-stack
train
978dc886255d1b98419e0f62
train
function
def get_tests_SHA512(): test_vectors = load_tests(("Cryptodome", "SelfTest", "Hash", "test_vectors", "SHA2"), "SHA512ShortMsg.rsp", "KAT SHA-512", { "len" : lambda x: int(x) } ) test_data = test_data_512_other[:] ...
def get_tests_SHA512():
test_vectors = load_tests(("Cryptodome", "SelfTest", "Hash", "test_vectors", "SHA2"), "SHA512ShortMsg.rsp", "KAT SHA-512", { "len" : lambda x: int(x) } ) test_data = test_data_512_other[:] for tv in test_vectors...
f07451f67a28e37d09cde769424c96aea6f8971389db9e1993d6c565c3c71b855723c', 'Franz jagt im komplett verwahrlosten Taxi quer durch Bayern'), ] def get_tests_SHA512():
64
64
181
6
58
Zhangxi-Lam/alfred-google-keep
lib/lib/Cryptodome/SelfTest/Hash/test_SHA512.py
Python
get_tests_SHA512
get_tests_SHA512
53
74
53
54
70d74c5075103f29671c543bd6158d203d62d824
bigcode/the-stack
train
6acdae3724275ee395106491
train
function
def get_tests_SHA512_256(): test_vectors = load_tests(("Cryptodome", "SelfTest", "Hash", "test_vectors", "SHA2"), "SHA512_256ShortMsg.rsp", "KAT SHA-512/256", { "len" : lambda x: int(x) } ) test_data = [] for t...
def get_tests_SHA512_256():
test_vectors = load_tests(("Cryptodome", "SelfTest", "Hash", "test_vectors", "SHA2"), "SHA512_256ShortMsg.rsp", "KAT SHA-512/256", { "len" : lambda x: int(x) } ) test_data = [] for tv in test_vectors: tr...
(SHA512, "SHA512/224", test_data, digest_size=28, oid="2.16.840.1.101.3.4.2.5", extra_params={ "truncate" : "224" }) return tests def get_tests_SHA512_256():
64
64
195
8
55
Zhangxi-Lam/alfred-google-keep
lib/lib/Cryptodome/SelfTest/Hash/test_SHA512.py
Python
get_tests_SHA512_256
get_tests_SHA512_256
102
124
102
103
4156fcba5246d82aad1dfb54774faf49b90b4019
bigcode/the-stack
train
50e08281c67e97c07ff19b08
train
function
def get_tests_SHA512_224(): test_vectors = load_tests(("Cryptodome", "SelfTest", "Hash", "test_vectors", "SHA2"), "SHA512_224ShortMsg.rsp", "KAT SHA-512/224", { "len" : lambda x: int(x) } ) test_data = [] for t...
def get_tests_SHA512_224():
test_vectors = load_tests(("Cryptodome", "SelfTest", "Hash", "test_vectors", "SHA2"), "SHA512_224ShortMsg.rsp", "KAT SHA-512/224", { "len" : lambda x: int(x) } ) test_data = [] for tv in test_vectors: tr...
.md), tv.msg, tv.desc)) tests = make_hash_tests(SHA512, "SHA512", test_data, digest_size=64, oid="2.16.840.1.101.3.4.2.3") return tests def get_tests_SHA512_224():
64
64
195
8
55
Zhangxi-Lam/alfred-google-keep
lib/lib/Cryptodome/SelfTest/Hash/test_SHA512.py
Python
get_tests_SHA512_224
get_tests_SHA512_224
77
99
77
78
d5ce4918f99bbd298d66a25bbc89e2d93bac90f0
bigcode/the-stack
train
4a8daa913d275dd7269f5b47
train
function
def get_tests(config={}): tests = [] tests += get_tests_SHA512() tests += get_tests_SHA512_224() tests += get_tests_SHA512_256() return tests
def get_tests(config={}):
tests = [] tests += get_tests_SHA512() tests += get_tests_SHA512_224() tests += get_tests_SHA512_256() return tests
_tests(SHA512, "SHA512/256", test_data, digest_size=32, oid="2.16.840.1.101.3.4.2.6", extra_params={ "truncate" : "256" }) return tests def get_tests(config={}):
64
64
43
7
56
Zhangxi-Lam/alfred-google-keep
lib/lib/Cryptodome/SelfTest/Hash/test_SHA512.py
Python
get_tests
get_tests
127
133
127
128
8f9da96f915c12aa0fd26d33bc6286596039ae62
bigcode/the-stack
train
8d85ff0b47081bcc055a0687
train
class
class Solution: def maxSideLength(self, A, thres): def getA(i, j): return A[i][j] if i >= 0 <= j else 0 ans = 0 for i in range(len(A)): for j in range(len(A[0])): A[i][j] += getA(i - 1, j) + getA(i, j - 1) - getA(i - 1, j - 1) if A[i]...
class Solution:
def maxSideLength(self, A, thres): def getA(i, j): return A[i][j] if i >= 0 <= j else 0 ans = 0 for i in range(len(A)): for j in range(len(A[0])): A[i][j] += getA(i - 1, j) + getA(i, j - 1) - getA(i - 1, j - 1) if A[i][j] <= thres and...
class Solution:
3
64
130
3
0
kuanhungchen/leetcode-practice
Python/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.py
Python
Solution
Solution
1
12
1
1
c6a775c1a6d6df3348d7376cb101a6c9ad1db4ec
bigcode/the-stack
train
e893a8ef013f36e0d0d41107
train
class
class Main(): def __init__(self): assert len(sys.argv) == 4 self.size = map(int, sys.argv[1].split("x")) orig = map(int, sys.argv[2].split("x")) self.orig = orig[1], orig[0] self.path = sys.argv[3] self.scalel = True self.scalep = False ...
class Main():
def __init__(self): assert len(sys.argv) == 4 self.size = map(int, sys.argv[1].split("x")) orig = map(int, sys.argv[2].split("x")) self.orig = orig[1], orig[0] self.path = sys.argv[3] self.scalel = True self.scalep = False self.cap = ...
import pygame import cStringIO import sys from time import time from capclient import CapClient from touchclient import TouchClient from rotationclient import RotationClient from adbclient import AdbClient MENU_TAP = 2 MENU_TIMEOUT = 10 MENU_BORDER = 10 MENU_WIDTH = 15 NAV_WIDTH = 7 DOUBLECLICK_TIME = 0.2 class Mai...
88
256
2,221
3
84
fhorinek/adbmirror
adbmirror/gui.py
Python
Main
Main
20
296
20
20
b406559807ea6892c2b10c6f6d0731130561c5bd
bigcode/the-stack
train
9044ae6bb99df9b3d0d5523b
train
function
def configure_subparser(subparser): pass
def configure_subparser(subparser):
pass
def configure_subparser(subparser):
7
64
10
7
0
wfercosta/poc_aws_glue_spark
apps/data/data-metrics/src/jobs/report_montly_endpoint/__init__.py
Python
configure_subparser
configure_subparser
2
3
2
2
565fb24ca2c0f96c285b38d5af766114e435022d
bigcode/the-stack
train
35eb28f2fd6c48f7f98eed3e
train
function
def execute(spark, args): pass
def execute(spark, args):
pass
def configure_subparser(subparser): pass def execute(spark, args):
18
64
9
7
10
wfercosta/poc_aws_glue_spark
apps/data/data-metrics/src/jobs/report_montly_endpoint/__init__.py
Python
execute
execute
6
7
6
6
299f0f82e0f14805a947ec2b59bb3ec9ac8fd9af
bigcode/the-stack
train
1db10d48a3e605790ff858c2
train
class
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA) class Update(base.UpdateCommand): """Update a HTTPS health check. *{command}* is used to update an existing HTTPS health check. Only arguments passed in will be updated on the health check. Other attributes will remain unaffected. """ HEALT...
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA) class Update(base.UpdateCommand):
"""Update a HTTPS health check. *{command}* is used to update an existing HTTPS health check. Only arguments passed in will be updated on the health check. Other attributes will remain unaffected. """ HEALTH_CHECK_ARG = None @classmethod def Args(cls, parser): cls.HEALTH_CHECK_ARG = flags.HealthC...
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
236
256
1,048
22
213
bopopescu/searchparty
google-cloud-sdk/lib/surface/compute/health_checks/update/https.py
Python
Update
Update
24
156
24
25
d90ef792b2f40787d5867a112cbcf769c9ef107c
bigcode/the-stack
train
d6d206490271bb94850260df
train
class
@base.ReleaseTracks(base.ReleaseTrack.ALPHA) class UpdateAlpha(Update): """Update a HTTPS health check. *{command}* is used to update an existing HTTPS health check. Only arguments passed in will be updated on the health check. Other attributes will remain unaffected. """ @staticmethod def Args(parser):...
@base.ReleaseTracks(base.ReleaseTrack.ALPHA) class UpdateAlpha(Update):
"""Update a HTTPS health check. *{command}* is used to update an existing HTTPS health check. Only arguments passed in will be updated on the health check. Other attributes will remain unaffected. """ @staticmethod def Args(parser): Update.Args(parser) health_checks_utils.AddHttpRelatedResponseA...
# print the resource and return. if objects[0] == new_object: log.status.Print( 'No change requested; skipping update for [{0}].'.format( objects[0].name)) return objects return client.MakeRequests( [self.GetSetRequest(client, health_check_ref, new_object)]) @bas...
87
88
296
16
71
bopopescu/searchparty
google-cloud-sdk/lib/surface/compute/health_checks/update/https.py
Python
UpdateAlpha
UpdateAlpha
159
200
159
160
ddc1d14d4f00c7bc98cbd4e1d19098c70e361e01
bigcode/the-stack
train
3aa57fc65806f2067d2e3ae9
train
function
def GetDayOfWeek(datetimes, dataframe=None): """ Convert DateTime Objects to Day of Week Inputting a DataFrame will append the new data column Example: # Return a pd.Series with datetime index series = GetDayOfWeek(datetimes) # Return yo...
def GetDayOfWeek(datetimes, dataframe=None):
""" Convert DateTime Objects to Day of Week Inputting a DataFrame will append the new data column Example: # Return a pd.Series with datetime index series = GetDayOfWeek(datetimes) # Return your dataframe # with the new data column appended ...
# To access Tulip indicators w/default values # Only one of these may be necessary from .pantulipy import * from .pantulipy import _DEFAULTLESS_INDICATORS import pandas_ta as ta import pandas as pd def GetDayOfWeek(datetimes, dataframe=None):
63
69
233
12
50
voidful/CryptoTA
cryptota/main.py
Python
GetDayOfWeek
GetDayOfWeek
12
45
12
13
eccbab574e2119ccf4417c12a575149d2459fe1e
bigcode/the-stack
train
7c71efe5a75cc1a0a62ba569
train
class
class TA_Features: """ Get 144 Unique Indicator Values based on a DataFrame, with columns: 'open' 'high' 'low' 'close' 'volume'. Using Tulip indicators and Pandas_TA Indicators. """ unique_pandas_ta_indicators = { 'accbands': ta.accbands, 'amat': ta.amat, 'aobv': ta.aobv, ...
class TA_Features:
""" Get 144 Unique Indicator Values based on a DataFrame, with columns: 'open' 'high' 'low' 'close' 'volume'. Using Tulip indicators and Pandas_TA Indicators. """ unique_pandas_ta_indicators = { 'accbands': ta.accbands, 'amat': ta.amat, 'aobv': ta.aobv, 'cg': ta.cg, ...
DEFAULTLESS_INDICATORS import pandas_ta as ta import pandas as pd def GetDayOfWeek(datetimes, dataframe=None): """ Convert DateTime Objects to Day of Week Inputting a DataFrame will append the new data column Example: # Return a pd.Series with datetime index...
256
256
2,508
5
250
voidful/CryptoTA
cryptota/main.py
Python
TA_Features
TA_Features
48
196
48
48
8fa4261a2601b93bdad2988c81597bbca911e8a9
bigcode/the-stack
train
b57df678cb6d1a615522bbba
train
function
def load_feature_dict(features_to_use): """ loads feature dicts of all relevant categorical features """ # assume the necessary file exists assert os.path.isfile("feature_dicts.json") print("loading feature dicts...") all_categorical_features = ['user', 'countries', 'client', 'session', 'fo...
def load_feature_dict(features_to_use):
""" loads feature dicts of all relevant categorical features """ # assume the necessary file exists assert os.path.isfile("feature_dicts.json") print("loading feature dicts...") all_categorical_features = ['user', 'countries', 'client', 'session', 'format', 'token', 'part_of_speech', ...
"values") with open('feature_dicts.json', 'w') as fp: fp.write( '[' + ',\n'.join(json.dumps(i) for i in n_attr_dicts) + ']\n') print("saving finished ") def load_feature_dict(features_to_use):
63
64
156
8
55
Kostis-S-Z/DL_4_SLAM
starter_code/count_features.py
Python
load_feature_dict
load_feature_dict
284
304
284
284
078854a5313da230d710c934c70aab506780d794
bigcode/the-stack
train
8cde6ccc8eb765d0e890917a
train
function
def load_data(filename, train_data_use, start_from_line=0, end_line=0): """ This method loads and returns the data in filename. If the data is labelled training data, it returns labels too. Parameters: filename: the location of the training or test data you want to load. train_data_use: how...
def load_data(filename, train_data_use, start_from_line=0, end_line=0):
""" This method loads and returns the data in filename. If the data is labelled training data, it returns labels too. Parameters: filename: the location of the training or test data you want to load. train_data_use: how many of the training data to use start_from_line: specific numb...
_chunks - 1): if VERBOSE > 0: print("Loading chunk", chunk + 1, "out of", num_chunks) # Start loading data from the last point training_data, training_labels, end_line, instance_count, num_exercises = load_data(train_path, ...
256
256
1,490
20
235
Kostis-S-Z/DL_4_SLAM
starter_code/count_features.py
Python
load_data
load_data
92
262
92
92
181969694e30140e418bdfdebbbb92415e9e05e0
bigcode/the-stack
train
c23346b5c13fca210d85facf
train
function
def load_in_chunks(): num_chunks = int(1 / TRAINING_PERC) start_line = 0 total_instances = 0 total_exercises = 0 for chunk in range(num_chunks - 1): if VERBOSE > 0: print("Loading chunk", chunk + 1, "out of", num_chunks) # Start loading data from the last point ...
def load_in_chunks():
num_chunks = int(1 / TRAINING_PERC) start_line = 0 total_instances = 0 total_exercises = 0 for chunk in range(num_chunks - 1): if VERBOSE > 0: print("Loading chunk", chunk + 1, "out of", num_chunks) # Start loading data from the last point training_data, traini...
{}, {}, {}, {}, {}, {}, {}] all_features = ['user', 'countries', 'client', 'session', 'format', 'token', 'part_of_speech', 'dependency_label'] # all_features = ['client', 'session', 'format', 'part_of_speech'] def main(): print("create new feature dictionaries") load_in_chunks() save_feature_dict() def...
84
84
282
5
79
Kostis-S-Z/DL_4_SLAM
starter_code/count_features.py
Python
load_in_chunks
load_in_chunks
56
89
56
56
eda5e0428e29ba16ef804e3798567c42f1a26fba
bigcode/the-stack
train
0050d77dc9587831f018f257
train
function
def main(): print("create new feature dictionaries") load_in_chunks() save_feature_dict()
def main():
print("create new feature dictionaries") load_in_chunks() save_feature_dict()
= [{}, {}, {}, {}, {}, {}, {}, {}] all_features = ['user', 'countries', 'client', 'session', 'format', 'token', 'part_of_speech', 'dependency_label'] # all_features = ['client', 'session', 'format', 'part_of_speech'] def main():
64
64
21
3
61
Kostis-S-Z/DL_4_SLAM
starter_code/count_features.py
Python
main
main
48
53
48
48
7e037ce8377347986724d03c01c2eac10fb1ae97
bigcode/the-stack
train
2d30427527a526dad1117fcd
train
function
def save_feature_dict(): """ saves feature dicts in file "feature_dicts.p" """ print("Saving feature dict...") print("values for:") for i in range(len(n_attr_dicts)): print(all_features[i], "has", len(n_attr_dicts[i]), "values") with open('feature_dicts.json', 'w') as fp: f...
def save_feature_dict():
""" saves feature dicts in file "feature_dicts.p" """ print("Saving feature dict...") print("values for:") for i in range(len(n_attr_dicts)): print(all_features[i], "has", len(n_attr_dicts[i]), "values") with open('feature_dicts.json', 'w') as fp: fp.write( '[' ...
1: print('Done loading ' + str(len(data)) + ' instances across ' + str(num_exercises) + ' exercises.\n') if training: return data, labels, num_lines, instance_count, num_exercises else: return data def save_feature_dict():
64
64
117
5
58
Kostis-S-Z/DL_4_SLAM
starter_code/count_features.py
Python
save_feature_dict
save_feature_dict
265
281
265
265
a0c5f43702ee6d07337ec451674ade865746251e
bigcode/the-stack
train
96f0a2746718b7082352590f
train
function
def getRuntimeTraceOfLoadedFiles(logger, command, required=False): """Returns the files loaded when executing a binary.""" # This will make a crazy amount of work, # pylint: disable=I0021,too-many-branches,too-many-locals,too-many-statements path = command[0] if not os.path.exists(path): ...
def getRuntimeTraceOfLoadedFiles(logger, command, required=False):
"""Returns the files loaded when executing a binary.""" # This will make a crazy amount of work, # pylint: disable=I0021,too-many-branches,too-many-locals,too-many-statements path = command[0] if not os.path.exists(path): logger.sysexit("Error, cannot find %r (%r)." % (path, os.path.abspa...
License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Licens...
256
256
956
14
241
charterchap/Nuitka
nuitka/freezer/RuntimeTracing.py
Python
getRuntimeTraceOfLoadedFiles
getRuntimeTraceOfLoadedFiles
41
170
41
41
185d0e912d15e878d2aeef160abb4bae3c187f4e
bigcode/the-stack
train
0a23c06e638e35b5f18006c7
train
class
class GitlabConnector(HelpDeskConnector): """ Github implementation of our base connector. """ project = None def __init__(self, gitlab_url, personal_token, project, *args, **kwargs): """ Initiates a Gitlab api instance, authenticates it and sets it as our authenticated cli...
class GitlabConnector(HelpDeskConnector):
""" Github implementation of our base connector. """ project = None def __init__(self, gitlab_url, personal_token, project, *args, **kwargs): """ Initiates a Gitlab api instance, authenticates it and sets it as our authenticated client. If project is specified, it populates...
import logging import gitlab from .base import AuthenticationError, HelpDeskConnector, OperationError logger = logging.getLogger("helpdesk") class GitlabConnector(HelpDeskConnector):
39
256
2,187
9
30
andrlik/looking-for-group
looking_for_group/helpdesk/backends/gitlab.py
Python
GitlabConnector
GitlabConnector
10
275
10
10
9bdb08c3ac7e8eb22af7fb051b0faaa66a7d733e
bigcode/the-stack
train
620e7d8c4f5ffef3647e3ee5
train
class
class Command(BaseCommand): args = '' help = 'Send reminder mails to patients are going to have an appointment tomorrow' def handle(self, *args, **options): translation.activate(settings.LANGUAGE_CODE) for app in Appointment.objects.filter(notify=True, date=d...
class Command(BaseCommand):
args = '' help = 'Send reminder mails to patients are going to have an appointment tomorrow' def handle(self, *args, **options): translation.activate(settings.LANGUAGE_CODE) for app in Appointment.objects.filter(notify=True, date=date.today()+timedelta(hours=...
fernando ruiz from django.core.management.base import BaseCommand, CommandError from cal.models import Appointment from datetime import date, timedelta from django.template.loader import render_to_string from django.conf import settings from django.core.mail import send_mail from django.utils import translation class...
64
64
112
5
58
frhumanes/consulting
web/src/cal/management/commands/warn_appointments.py
Python
Command
Command
15
25
15
15
f6d70e000cc8c491973313b6ab0e9745507da1c5
bigcode/the-stack
train
2e38e970a3f1afe070246dbb
train
class
class Wikipedia2VecDataset(Dataset): def __init__(self, path_wikipedia2vec: str, transform=None): warnings.warn("experimental dataset.") assert os.path.exists(path_wikipedia2vec), f"file not found: {path_wikipedia2vec}" self.model = Wikipedia2Vec.load(path_wikipedia2vec) self.trans...
class Wikipedia2VecDataset(Dataset):
def __init__(self, path_wikipedia2vec: str, transform=None): warnings.warn("experimental dataset.") assert os.path.exists(path_wikipedia2vec), f"file not found: {path_wikipedia2vec}" self.model = Wikipedia2Vec.load(path_wikipedia2vec) self.transform = transform self._idx_to_...
embedding = self.embedding[idx,:] sample = {"entity":word, "embedding":embedding} if self.transform is not None: sample = self.transform(sample) return sample @property def n_dim(self): return self.embedding.shape[1] class Wikipedia2VecDataset(Dataset):
66
66
221
8
58
s-mizuki-nlp/hierarchical_code_learning
dataset/other_embeddings.py
Python
Wikipedia2VecDataset
Wikipedia2VecDataset
51
82
51
52
9c5f15b3b79f1c6a52227001c393b68aa45c901b
bigcode/the-stack
train
3eeded37d2f9c6a5348b1f4b
train
class
class ToyEmbeddingsDataset(Dataset): def __init__(self, sample_size: int, embedding_dim: int, transform=None, seed: int = 0): np.random.seed(seed) self.embedding = np.random.normal(size=sample_size * embedding_dim).astype(np.float32).reshape((sample_size, embedding_dim)) self._idx_to_word ...
class ToyEmbeddingsDataset(Dataset):
def __init__(self, sample_size: int, embedding_dim: int, transform=None, seed: int = 0): np.random.seed(seed) self.embedding = np.random.normal(size=sample_size * embedding_dim).astype(np.float32).reshape((sample_size, embedding_dim)) self._idx_to_word = {idx:f"{idx}" for idx in range(sampl...
from __future__ import division from __future__ import print_function import os, sys, io import argparse import warnings import numpy as np import torch from torch.utils.data import Dataset from wikipedia2vec.wikipedia2vec import Wikipedia2Vec class ToyEmbeddingsDataset(Dataset):
64
64
208
8
55
s-mizuki-nlp/hierarchical_code_learning
dataset/other_embeddings.py
Python
ToyEmbeddingsDataset
ToyEmbeddingsDataset
18
48
18
19
04c9b274ba36aa418bfa988212092349d74d49d1
bigcode/the-stack
train
c39c056e2604255d1f84fcec
train
class
class TestDecryption(TestCase): """Test decryption methods""" NUMBER_OF_GUARDIANS = 3 QUORUM = 2 CEREMONY_DETAILS = CeremonyDetails(NUMBER_OF_GUARDIANS, QUORUM) def setUp(self): # Key Ceremony self.key_ceremony_mediator = KeyCeremonyMediator( "key_ceremony_mediator_med...
class TestDecryption(TestCase):
"""Test decryption methods""" NUMBER_OF_GUARDIANS = 3 QUORUM = 2 CEREMONY_DETAILS = CeremonyDetails(NUMBER_OF_GUARDIANS, QUORUM) def setUp(self): # Key Ceremony self.key_ceremony_mediator = KeyCeremonyMediator( "key_ceremony_mediator_mediator", self.CEREMONY_DETAILS ...
CompensatedDecryptionShare, create_ciphertext_decryption_selection, ) from electionguard.election_polynomial import compute_lagrange_coefficient from electionguard.elgamal import ElGamalKeyPair from electionguard.group import ( ZERO_MOD_Q, mult_p, pow_p, ) from electionguard.election_builder import Ele...
256
256
3,868
7
249
soham4abc/electionguard-python
tests/unit/test_decryption.py
Python
TestDecryption
TestDecryption
53
577
53
53
46db0150a5d2707c886865cecbeea68001f16e32
bigcode/the-stack
train
0e7c7a8c558606736fc3a4ac
train
class
class ContinuousLocalOptimization(FitnessFunction): """Fitness evaluation metric for individuals. A class for the fitness evaluation metric of genetic individuals that may or may not need local optimization before evaluation. Parameters ---------- fitness_function : `FitnessFunction` A...
class ContinuousLocalOptimization(FitnessFunction):
"""Fitness evaluation metric for individuals. A class for the fitness evaluation metric of genetic individuals that may or may not need local optimization before evaluation. Parameters ---------- fitness_function : `FitnessFunction` A FitnessFunction that evaluates the fitness of a `ch...
lm' # 'broyden1', # 'broyden2', # 'anderson', # 'linearmixing', # 'diagbroyden', # 'excitingmixing', # 'krylov', # 'df-sane' } MINIMIZE_SET = { 'Nelder-Mead', 'Powell', 'CG', 'BFGS', # 'Newton-CG', 'L-BFGS-B', 'TNC', # 'COBYLA', 'SLSQP' # 'trust-c...
256
256
1,301
8
248
nolanstr/bingo_multi_stage
bingo/local_optimizers/continuous_local_opt.py
Python
ContinuousLocalOptimization
ContinuousLocalOptimization
63
225
63
63
fa4b4ca6bff25988d2b56f89a27f84bc898044f4
bigcode/the-stack
train
ed8a94092496b5cc6b692dcd
train
class
class ChromosomeInterface(metaclass=ABCMeta): """For chromosomes with continuous local optimization An interface to be used on chromosomes that will be using continuous local optimization. """ @abstractmethod def needs_local_optimization(self): """Does the individual need local optimiza...
class ChromosomeInterface(metaclass=ABCMeta):
"""For chromosomes with continuous local optimization An interface to be used on chromosomes that will be using continuous local optimization. """ @abstractmethod def needs_local_optimization(self): """Does the individual need local optimization Returns ------- ...
= optimize.minimize(sub_routine, params, args=(individual, ), method=self._algorithm, tol=1e-6) return optimize_result.x def _evaluate_fitness(self, i...
66
66
222
11
55
nolanstr/bingo_multi_stage
bingo/local_optimizers/continuous_local_opt.py
Python
ChromosomeInterface
ChromosomeInterface
228
275
228
228
5e7ca65b04dbce102ecec1ac78a35ede5ce47851
bigcode/the-stack
train
802792d40a63a8e5faaeef48
train
class
class ExtractedAudio(VideoConverter): """Script para extração de audio de video utilizando o FFMpeg""" def format_output(self, format_audio: str) -> str: if format_audio == 'mp3': self.output_format = format_audio self.codec_audio = '-acodec libmp3lame' self.bitrate_...
class ExtractedAudio(VideoConverter):
"""Script para extração de audio de video utilizando o FFMpeg""" def format_output(self, format_audio: str) -> str: if format_audio == 'mp3': self.output_format = format_audio self.codec_audio = '-acodec libmp3lame' self.bitrate_audio = '-b:a 320k' return...
import os from fnmatch import fnmatch from .setting_video import VideoConverter from utils.check_file_exist import file_exist class ExtractedAudio(VideoConverter):
34
158
527
7
26
debxp/media_of_transcoder
settings/setting_audio.py
Python
ExtractedAudio
ExtractedAudio
8
67
8
8
0da95315ac471e8ffa149591c2a3480f5de00508
bigcode/the-stack
train
113faec3e654db5be924cce4
train
class
class AudioConverter(ExtractedAudio): ...
class AudioConverter(ExtractedAudio):
...
i "{full_path}" -vn {self.bitrate_audio} ' f'{self.codec_audio} {self.time} "{exit_file}" -y' ) if file_exist(exit_file): os.system(command) else: continue return True class AudioConverter(ExtractedAudio)...
64
64
10
8
55
debxp/media_of_transcoder
settings/setting_audio.py
Python
AudioConverter
AudioConverter
70
71
70
70
94f53ba9522e12a13aea8bce33f28b8e16b30d37
bigcode/the-stack
train
2c4fbd6c37bf12cb7b71d088
train
class
class Parser: def __init__(self): self.config = None def _verify_event(self, event): # Make sure the event values are valid events = ['any', 'created', 'modified', 'deleted', 'moved'] if event not in events: raise InvalidEventValue(f'\n\nYou cannot use "{event}" as an event value.\n\nThe available option...
class Parser:
def __init__(self): self.config = None def _verify_event(self, event): # Make sure the event values are valid events = ['any', 'created', 'modified', 'deleted', 'moved'] if event not in events: raise InvalidEventValue(f'\n\nYou cannot use "{event}" as an event value.\n\nThe available options are: {events...
''' Handles parsing of the .supervisorconf file. ''' import os class InvalidEventValue(Exception): pass class InvalidPathValue(Exception): pass class Parser:
34
72
241
3
30
Infinium8/Supervisor
ssupervisor/lib/parser.py
Python
Parser
Parser
13
42
13
13
27b7ba04dbcab2c9114b94f8220526dd7cb997d8
bigcode/the-stack
train
7ea8fd23cd7a26797bdb701d
train
class
class InvalidEventValue(Exception): pass
class InvalidEventValue(Exception):
pass
''' Handles parsing of the .supervisorconf file. ''' import os class InvalidEventValue(Exception):
21
64
8
6
14
Infinium8/Supervisor
ssupervisor/lib/parser.py
Python
InvalidEventValue
InvalidEventValue
7
8
7
7
2d790fc4177c492d0a1bebaacb1ebd55b6bee405
bigcode/the-stack
train
3e040cfd5ad871015cfe3836
train
class
class InvalidPathValue(Exception): pass
class InvalidPathValue(Exception):
pass
''' Handles parsing of the .supervisorconf file. ''' import os class InvalidEventValue(Exception): pass class InvalidPathValue(Exception):
29
64
8
6
22
Infinium8/Supervisor
ssupervisor/lib/parser.py
Python
InvalidPathValue
InvalidPathValue
10
11
10
10
91c0f1205d0de63bd2b87d788c5b82e399528b18
bigcode/the-stack
train
a5ae9cf74e86a1e681effaee
train
function
def format_send(bot, update): msg = update.message chat_id = msg.chat_id bot.send_message(chat_id = chat_id, text = "*Format*\n_/convert 50 USD to INR_", parse_mode = "Markdown", reply_to_message_id = msg.message_id)
def format_send(bot, update):
msg = update.message chat_id = msg.chat_id bot.send_message(chat_id = chat_id, text = "*Format*\n_/convert 50 USD to INR_", parse_mode = "Markdown", reply_to_message_id = msg.message_id)
.send_message(chat_id = chat_id, text = f"*{needed_amount} {to_convert_to}*", parse_mode = "markdown", reply_to_message_id = msg.message_id) except: format_send(bot, update) else: format_send(bot, update) def format_send(bot, update):
64
64
59
7
57
CrEaTiiOn187/tg-management-bot
currency.py
Python
format_send
format_send
30
33
30
30
a442b6fc36a0d00c81344342b5a50af551d0044e
bigcode/the-stack
train
c2122c31c83a5bdb6b2e35d9
train
function
def currency(bot, update): msg = update.message chat_id = msg.chat_id text = msg.text.split() if len(text)==5: amount = text[1] to_be_converted = text[2].upper() to_convert_to = text[4].upper() api_key = f"{to_be_converted}_{to_convert_to}" url = f"https://free.currencyconverterapi.com/api/...
def currency(bot, update):
msg = update.message chat_id = msg.chat_id text = msg.text.split() if len(text)==5: amount = text[1] to_be_converted = text[2].upper() to_convert_to = text[4].upper() api_key = f"{to_be_converted}_{to_convert_to}" url = f"https://free.currencyconverterapi.com/api/v6/convert?q={api_key}&compa...
import requests def currency(bot, update):
9
64
208
6
2
CrEaTiiOn187/tg-management-bot
currency.py
Python
currency
currency
3
28
3
3
b713c5a3386c572c7114e21b5030e9575d7f61c0
bigcode/the-stack
train
9d8016365a3be6a733c58528
train
class
class CCWallet: wallet_state_manager: Any log: logging.Logger wallet_info: WalletInfo cc_coin_record: WalletCoinRecord cc_info: CCInfo standard_wallet: Wallet base_puzzle_program: Optional[bytes] base_inner_puzzle_hash: Optional[bytes32] cost_of_single_tx: Optional[int] @staticm...
class CCWallet:
wallet_state_manager: Any log: logging.Logger wallet_info: WalletInfo cc_coin_record: WalletCoinRecord cc_info: CCInfo standard_wallet: Wallet base_puzzle_program: Optional[bytes] base_inner_puzzle_hash: Optional[bytes32] cost_of_single_tx: Optional[int] @staticmethod async ...
32, uint64, uint128 from kale.util.json_util import dict_to_json_str from kale.wallet.block_record import HeaderBlockRecord from kale.wallet.cc_wallet.cc_info import CCInfo from kale.wallet.cc_wallet.cc_utils import ( CC_MOD, SpendableCC, cc_puzzle_for_inner_puzzle, cc_puzzle_hash_for_inner_puzzle_hash,...
256
256
5,988
4
251
grayfallstown/kale-blockchain
kale/wallet/cc_wallet/cc_wallet.py
Python
CCWallet
CCWallet
54
747
54
54
a0a22769a2e3d986bb486514f213d1747bbcf51d
bigcode/the-stack
train
a48878875ca142e1fc1c2632
train
class
class TestColumnsToVectorStreamOp(unittest.TestCase): def test_columnstovectorstreamop(self): df = pd.DataFrame([ ['1', '{"f0":"1.0","f1":"2.0"}', '$3$0:1.0 1:2.0', 'f0:1.0,f1:2.0', '1.0,2.0', 1.0, 2.0], ['2', '{"f0":"4.0","f1":"8.0"}', '$3$0:4.0 1:8.0', 'f0:4.0,f1:8.0', '4.0,8.0', ...
class TestColumnsToVectorStreamOp(unittest.TestCase):
def test_columnstovectorstreamop(self): df = pd.DataFrame([ ['1', '{"f0":"1.0","f1":"2.0"}', '$3$0:1.0 1:2.0', 'f0:1.0,f1:2.0', '1.0,2.0', 1.0, 2.0], ['2', '{"f0":"4.0","f1":"8.0"}', '$3$0:4.0 1:8.0', 'f0:4.0,f1:8.0', '4.0,8.0', 4.0, 8.0]]) data = StreamOperator.fro...
import unittest from pyalink.alink import * import numpy as np import pandas as pd class TestColumnsToVectorStreamOp(unittest.TestCase):
31
81
272
11
19
wenwei8268/Alink
python/src/main/python/pyalink/alink/tests/examples/from_docs/test_columnstovectorstreamop.py
Python
TestColumnsToVectorStreamOp
TestColumnsToVectorStreamOp
5
24
5
5
0e684c38ff9e7bf52b2dd31c12f8aed3c680118c
bigcode/the-stack
train
1007b708213018570d98eac6
train
function
def get_mean_intensity(miller_array): sum = 0.0 for d in miller_array.data(): sum += d return (sum / len(miller_array.data()))
def get_mean_intensity(miller_array):
sum = 0.0 for d in miller_array.data(): sum += d return (sum / len(miller_array.data()))
_J = 2.0*sigma_I*post_F*post_sig_F F = post_F*math.sqrt(sigma_I) sigma_F = post_sig_F*math.sqrt(sigma_I) return J, sigma_J, F, sigma_F def get_mean_intensity(miller_array):
64
64
42
9
54
dperl-sol/cctbx_project
cctbx/french_wilson.py
Python
get_mean_intensity
get_mean_intensity
172
176
172
172
5669e69d6843d952f91b821552c28a54de040945
bigcode/the-stack
train
c16df6d46ea7e7b98ebf23be
train
function
def show_rejected_summary(rejected, log=None): if log == None: log = sys.stdout print("** Total # rejected intensities: %d **" % len(rejected), file=log) if len(rejected) > 0: print("** Summary or rejected intensities **", file=log) print("--------------------------------------------------------------...
def show_rejected_summary(rejected, log=None):
if log == None: log = sys.stdout print("** Total # rejected intensities: %d **" % len(rejected), file=log) if len(rejected) > 0: print("** Summary or rejected intensities **", file=log) print("-----------------------------------------------------------------", file=log) print("Miller Index : Int...
miller_array.customized_copy(indices=new_indices, data=new_F, sigmas=new_sigma_F) f_obs.set_observation_type_xray_amplitude() show_rejected_summary(rejected=rejected, log=log) return f_obs def show_rejected_summary(rejected, log=None):...
64
64
165
11
52
dperl-sol/cctbx_project
cctbx/french_wilson.py
Python
show_rejected_summary
show_rejected_summary
470
481
470
470
8b4602807bc2a3eda8b5fb7ff358c77f5242fa7c
bigcode/the-stack
train
4ae37fe5ef662851740231fe
train
function
def calculate_mean_intensities(miller_array, log=None): if log == None: log = sys.stdout print("** Calculating bin mean intensity values for each intensity **", file=log) bin_mean_intensities = miller_array.mean(use_binning=True).data bin_centers = get_bin_centers(miller_array=miller_array) d_mean_intensi...
def calculate_mean_intensities(miller_array, log=None):
if log == None: log = sys.stdout print("** Calculating bin mean intensity values for each intensity **", file=log) bin_mean_intensities = miller_array.mean(use_binning=True).data bin_centers = get_bin_centers(miller_array=miller_array) d_mean_intensities = dict() for i_bin in miller_array.binner().range...
selection(i_bin) bin = miller_array.select(sel) if bin.size() > 0: if bin.size() < min_bin_size: max_bins = max_bins - 1 if max_bins == 0: raise ValueError("Too few reflections for accurate binning.") print("bin too small, trying %d bins" % max_bins, file=lo...
256
256
1,221
13
243
dperl-sol/cctbx_project
cctbx/french_wilson.py
Python
calculate_mean_intensities
calculate_mean_intensities
214
307
214
214
2fe40af95c8fcf5d76feceb9dd8cb16f864bc07f
bigcode/the-stack
train
9999ec8405dc1023e7f965cc
train
function
def get_bin_centers(miller_array): from cctbx.array_family import flex centers = flex.double() for i_bin in miller_array.binner().range_all(): sel = miller_array.binner().selection(i_bin) bin = miller_array.select(sel) bin_center = (bin.d_max_min()[0]+bin.d_max_min()[1])/2 centers.append(bin_cente...
def get_bin_centers(miller_array):
from cctbx.array_family import flex centers = flex.double() for i_bin in miller_array.binner().range_all(): sel = miller_array.binner().selection(i_bin) bin = miller_array.select(sel) bin_center = (bin.d_max_min()[0]+bin.d_max_min()[1])/2 centers.append(bin_center) return centers
ning.") print("bin too small, trying %d bins" % max_bins, file=log) bin_success = False break #f_w_binning(miller_array, max_bins=new_max_bins, log=log) return True def get_bin_centers(miller_array):
64
64
92
9
54
dperl-sol/cctbx_project
cctbx/french_wilson.py
Python
get_bin_centers
get_bin_centers
201
209
201
201
a1b5dc26cde9b9422c7579e4dd40617e538060d1
bigcode/the-stack
train
c7ebc8a18fda3bcc6d2b174d
train
function
def french_wilson_scale( miller_array, params=None, sigma_iobs_rejection_criterion=None, merge=False, min_bin_size=40, max_bins=60, log=None): from cctbx.array_family import flex if not miller_array.is_xray_intensity_array(): raise Sorry("Input array appears to be ampli...
def french_wilson_scale( miller_array, params=None, sigma_iobs_rejection_criterion=None, merge=False, min_bin_size=40, max_bins=60, log=None):
from cctbx.array_family import flex if not miller_array.is_xray_intensity_array(): raise Sorry("Input array appears to be amplitudes. "+ "This method is only appropriate for input intensities.") if miller_array.unit_cell() is None: raise Sorry("No unit cell information found. Please supply unit cell...
pt_2=m_2, delta=delta) assert (d_1 > d > d_2) if ( not ( (m_1 > mean_i > m_2) or (m_2 > mean_i > m_1) ) and not (m_1 == mean_i == m_2 == 0.0) and (math.fabs(m_1-m_2) > 1.0e-10) ): ...
256
256
1,580
47
208
dperl-sol/cctbx_project
cctbx/french_wilson.py
Python
french_wilson_scale
french_wilson_scale
309
468
309
316
d17dfc5fbe8af71b9cc1cc45324f7019ffb2b19f
bigcode/the-stack
train
a629875f40c1f69a4947b216
train
function
def fw_acentric( I, sigma_I, mean_intensity, sigma_iobs_rejection_criterion): assert (mean_intensity != 0) and (sigma_I != 0) h = (I/sigma_I) - (sigma_I/mean_intensity) h_min = sigma_iobs_rejection_criterion i_sig_min = h_min+0.3 if (I/sigma_I) < i_sig_min or h < h_min: return -1.0...
def fw_acentric( I, sigma_I, mean_intensity, sigma_iobs_rejection_criterion):
assert (mean_intensity != 0) and (sigma_I != 0) h = (I/sigma_I) - (sigma_I/mean_intensity) h_min = sigma_iobs_rejection_criterion i_sig_min = h_min+0.3 if (I/sigma_I) < i_sig_min or h < h_min: return -1.0, -1.0, -1.0, -1.0 else: if h < 3.0: point = 10.0*(h+4.0) pt_1 = int(point) pt...
0.278,0.272 ] master_phil = libtbx.phil.parse(""" max_bins = 60 .type = int .short_caption = Max. resolution bins .help = '''Maximum number of resolution bins''' min_bin_size = 40 .type = int .short_caption = Minimum bin size .help = '''Minimum number of reflections per bin''' """) def fw_...
118
118
396
27
91
dperl-sol/cctbx_project
cctbx/french_wilson.py
Python
fw_acentric
fw_acentric
92
126
92
96
c2494095457ec484587d072abe21b3aacfb83621
bigcode/the-stack
train
b5c3e9206f59320a4725ab10
train
function
def interpolate(pt_1, pt_2, delta): return ( ((1.0-delta)*pt_1) + (delta*pt_2) )
def interpolate(pt_1, pt_2, delta):
return ( ((1.0-delta)*pt_1) + (delta*pt_2) )
sel = miller_array.binner().selection(i_bin) bin = miller_array.select(sel) bin_center = (bin.d_max_min()[0]+bin.d_max_min()[1])/2 centers.append(bin_center) return centers def interpolate(pt_1, pt_2, delta):
64
64
35
12
51
dperl-sol/cctbx_project
cctbx/french_wilson.py
Python
interpolate
interpolate
211
212
211
211
9d57862afd433fbe35bc4b71de06ec739e385376
bigcode/the-stack
train
87382b2a0915c5383c15fb50
train
function
def f_w_binning(miller_array, max_bins=60, min_bin_size=40, log=None): if log == None: log = sys.stdout bin_success = False while not bin_success: miller_array.setup_binner(n_bins=max_bins) bin_success = True for i_bin in miller_array.binner().range_all(): sel = miller_array.binner().selecti...
def f_w_binning(miller_array, max_bins=60, min_bin_size=40, log=None):
if log == None: log = sys.stdout bin_success = False while not bin_success: miller_array.setup_binner(n_bins=max_bins) bin_success = True for i_bin in miller_array.binner().range_all(): sel = miller_array.binner().selection(i_bin) bin = miller_array.select(sel) if bin.size() > 0:...
/ len(miller_array.data())) # default number of bins is 60, but require that each bin has at least 40 reflections # if not try again with less bins until condition is satisfied def f_w_binning(miller_array, max_bins=60, min_bin_size=40, log=None):
64
64
204
23
40
dperl-sol/cctbx_project
cctbx/french_wilson.py
Python
f_w_binning
f_w_binning
180
199
180
180
d51ab17a91cb0909d27b2eec62e165f13916aea3
bigcode/the-stack
train
75fddf90d3919613b47a7ff3
train
function
def fw_centric( I, sigma_I, mean_intensity, sigma_iobs_rejection_criterion): assert (mean_intensity != 0) and (sigma_I != 0) h = (I/sigma_I) - ( sigma_I/(2.0*mean_intensity) ) h_min = sigma_iobs_rejection_criterion i_sig_min = h_min+0.3 if (I/sigma_I) < i_sig_min or h < h_min: retu...
def fw_centric( I, sigma_I, mean_intensity, sigma_iobs_rejection_criterion):
assert (mean_intensity != 0) and (sigma_I != 0) h = (I/sigma_I) - ( sigma_I/(2.0*mean_intensity) ) h_min = sigma_iobs_rejection_criterion i_sig_min = h_min+0.3 if (I/sigma_I) < i_sig_min or h < h_min: return -1.0, -1.0, -1.0, -1.0 else: if h < 4.0: point = 10.0*(h+4.0) pt_1 = int(point) ...
pt_1], pt_2=ac_zj_sd[pt_2], delta=delta) * sigma_I F = interpolate(pt_1=ac_zf[pt_1], pt_2=ac_zf[pt_2], delta=delta) * math.sqrt(sigma_I) sigma_F = interpolate(pt_1=ac_zf_sd[pt_1], ...
188
188
628
26
161
dperl-sol/cctbx_project
cctbx/french_wilson.py
Python
fw_centric
fw_centric
128
170
128
132
e702aaa7bcc7e4fdb3bdefe3e7acc79b1b19872c
bigcode/the-stack
train
dd67a7e926591b34dfd21e54
train
class
class OptionParser(optparse.OptionParser): """Creates the option parse and add --verbose support.""" def __init__(self, *args, **kwargs): optparse.OptionParser.__init__(self, *args, version=__version__, **kwargs) self.add_option( '--verbose', action='count', default=0, help='Use 2 times for ...
class OptionParser(optparse.OptionParser):
"""Creates the option parse and add --verbose support.""" def __init__(self, *args, **kwargs): optparse.OptionParser.__init__(self, *args, version=__version__, **kwargs) self.add_option( '--verbose', action='count', default=0, help='Use 2 times for more debugging info') self.add_option('...
= parser.parse_args(args) assert opt.change, "-c not defined" result = gerrit_util.AbandonChange( urlparse.urlparse(opt.host).netloc, opt.change, opt.message) logging.info(result) write_result(result, opt) class OptionParser(optparse.OptionParser):
66
66
221
8
58
yefengfang/depot_tools
gerrit_client.py
Python
OptionParser
OptionParser
170
188
170
170
44c1f41b351e24b3fb246917e3f1f9c3f3b7b81a
bigcode/the-stack
train
8adcb663606545a651c204ea
train
function
@subcommand.usage('') def CMDabandon(parser, args): parser.add_option('-c', '--change', type=int, help='change number') parser.add_option('-m', '--message', default='', help='reason for abandoning') (opt, args) = parser.parse_args(args) assert opt.change, "-c not defined" result = gerrit_util.AbandonChange( ...
@subcommand.usage('') def CMDabandon(parser, args):
parser.add_option('-c', '--change', type=int, help='change number') parser.add_option('-m', '--message', default='', help='reason for abandoning') (opt, args) = parser.parse_args(args) assert opt.change, "-c not defined" result = gerrit_util.AbandonChange( urlparse.urlparse(opt.host).netloc, opt....
limit=opt.limit, # Default: None o_params=opt.o_params, # Default: None ) logging.info('Change query returned %d changes.', len(result)) write_result(result, opt) @subcommand.usage('') def CMDabandon(parser, args):
64
64
114
14
50
yefengfang/depot_tools
gerrit_client.py
Python
CMDabandon
CMDabandon
156
167
156
157
cf53e768507c08a81b4f1e5df6bf95886343f65e
bigcode/the-stack
train
0777918a3c583741b6840b2d
train
function
@subcommand.usage('[args ...]') def CMDmovechanges(parser, args): parser.add_option('-p', '--param', dest='params', action='append', help='repeatable query parameter, format: -p key=value') parser.add_option('--destination_branch', dest='destination_branch', help='where to mo...
@subcommand.usage('[args ...]') def CMDmovechanges(parser, args):
parser.add_option('-p', '--param', dest='params', action='append', help='repeatable query parameter, format: -p key=value') parser.add_option('--destination_branch', dest='destination_branch', help='where to move changes to') (opt, args) = parser.parse_args(args) assert ...
import setup_color __version__ = '0.1' def write_result(result, opt): if opt.json_file: with open(opt.json_file, 'w') as json_file: json_file.write(json.dumps(result)) @subcommand.usage('[args ...]') def CMDmovechanges(parser, args):
66
66
221
17
49
yefengfang/depot_tools
gerrit_client.py
Python
CMDmovechanges
CMDmovechanges
40
65
40
41
6fb0279b0a6caf620b6a2d6afb27b63f9dd78a8d
bigcode/the-stack
train