uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
d0599bef5134160e9d09fe68
train
function
def TopoPatternOptimizer(p1, p2, ign=True): return TopoOptimizer(PatternSub(p1, p2), ignore_newtrees=ign)
def TopoPatternOptimizer(p1, p2, ign=True):
return TopoOptimizer(PatternSub(p1, p2), ignore_newtrees=ign)
y') z = MyVariable('z') return x, y, z def PatternOptimizer(p1, p2, ign=False): return OpKeyOptimizer(PatternSub(p1, p2), ignore_newtrees=ign) def TopoPatternOptimizer(p1, p2, ign=True):
64
64
34
14
50
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
TopoPatternOptimizer
TopoPatternOptimizer
96
97
96
96
1d8a3bbcd7a7f1ab5e50f56518b81b39977702f4
bigcode/the-stack
train
e429a9b37f842cc0479cf2f0
train
class
class TestOpSubOptimizer: def test_straightforward(self): x, y, z = inputs() e = op1(op1(op1(op1(op1(x))))) g = FunctionGraph([x, y, z], [e]) OpSubOptimizer(op1, op2).optimize(g) assert str(g) == "[Op2(Op2(Op2(Op2(Op2(x)))))]" def test_straightforward_2(self): x...
class TestOpSubOptimizer:
def test_straightforward(self): x, y, z = inputs() e = op1(op1(op1(op1(op1(x))))) g = FunctionGraph([x, y, z], [e]) OpSubOptimizer(op1, op2).optimize(g) assert str(g) == "[Op2(Op2(Op2(Op2(Op2(x)))))]" def test_straightforward_2(self): x, y, z = inputs() e...
', 'y')), # (op3, 'x', 'y')).optimize(g) # assert str(g) == "[Op3(x, y)]" def OpSubOptimizer(op1, op2): return OpKeyOptimizer(OpSub(op1, op2)) class TestOpSubOptimizer:
64
64
177
6
58
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
TestOpSubOptimizer
TestOpSubOptimizer
281
295
281
282
f311db045d59dc6437c7460342f021bdd455964d
bigcode/the-stack
train
0381d46081657ab0b95c1048
train
function
def OpSubOptimizer(op1, op2): return OpKeyOptimizer(OpSub(op1, op2))
def OpSubOptimizer(op1, op2):
return OpKeyOptimizer(OpSub(op1, op2))
op4, (op1, 'x', 'y'), (op1, 'x', 'y')), # (op3, 'x', 'y')).optimize(g) # assert str(g) == "[Op3(x, y)]" def OpSubOptimizer(op1, op2):
64
64
23
10
54
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
OpSubOptimizer
OpSubOptimizer
277
278
277
277
dc39de1eb9f7171edb77d09b79beea91c3557902
bigcode/the-stack
train
ec6b77f475c17b704931d8f1
train
class
class TestEquilibrium(object): def test_1(self): x, y, z = map(MyVariable, 'xyz') e = op3(op4(x, y)) g = FunctionGraph([x, y, z], [e]) # print g opt = EquilibriumOptimizer( [PatternSub((op1, 'x', 'y'), (op2, 'x', 'y')), PatternSub((op4, 'x', 'y'), (o...
class TestEquilibrium(object):
def test_1(self): x, y, z = map(MyVariable, 'xyz') e = op3(op4(x, y)) g = FunctionGraph([x, y, z], [e]) # print g opt = EquilibriumOptimizer( [PatternSub((op1, 'x', 'y'), (op2, 'x', 'y')), PatternSub((op4, 'x', 'y'), (op1, 'x', 'y')), Pat...
| |Elemwise{gt,no_inplace} [id K] '' 0 | |x2 [id I] | |x3 [id G] |dot [id B] '' 6 ''' print(strg) assert strg == strref, (strg, strref) def test_merge_noinput(self): # Check that identical Apply nodes without inputs will be merged x = NoInputOp(param=0)() ...
191
191
637
6
184
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
TestEquilibrium
TestEquilibrium
517
571
517
518
f5f3d5f63d258515c170dcb68eedae47f3448d17
bigcode/the-stack
train
095a72352fa498f993459821
train
class
class MyType(Type): def filter(self, data): return data def __eq__(self, other): return isinstance(other, MyType) def __hash__(self): return hash(MyType)
class MyType(Type):
def filter(self, data): return data def __eq__(self, other): return isinstance(other, MyType) def __hash__(self): return hash(MyType)
pre_constant_merge, pre_greedy_local_optimizer) from theano.gof.fg import FunctionGraph from theano import tensor as T def as_variable(x): if not isinstance(x, Variable): raise TypeError("not a Variable", x) return x class MyType(Type):
64
64
46
5
58
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
MyType
MyType
21
30
21
22
b1bc6ef338c3ae204370f0f224a1c9741019cdda
bigcode/the-stack
train
28cddb5808621e3654747dfc
train
class
class NoInputOp(Op): __props__ = ('param',) def __init__(self, param): self.param = param def make_node(self): return Apply(self, [], [MyType()()]) def perform(self, node, inputs, output_storage): output_storage[0][0] = self.param
class NoInputOp(Op):
__props__ = ('param',) def __init__(self, param): self.param = param def make_node(self): return Apply(self, [], [MyType()()]) def perform(self, node, inputs, output_storage): output_storage[0][0] = self.param
(y), op4(z)) g = FunctionGraph([x, y, z], [e]) OpSubOptimizer(op3, op4).optimize(g) assert str(g) == "[Op1(Op2(x), Op4(y), Op4(z))]" class NoInputOp(Op):
63
64
72
6
57
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
NoInputOp
NoInputOp
298
308
298
298
168dd7b4bbf887b78e398b0b848f87f161a2a3ff
bigcode/the-stack
train
9643d28809e0d9dce98e299e
train
class
class TestMergeOptimizer: def test_straightforward(self): x, y, z = inputs() e = op1(op2(x, y), op2(x, y), op2(x, z)) g = FunctionGraph([x, y, z], [e]) MergeOptimizer().optimize(g) assert str(g) == "[Op1(*1 -> Op2(x, y), *1, Op2(x, z))]" def test_constant_merging(self):...
class TestMergeOptimizer:
def test_straightforward(self): x, y, z = inputs() e = op1(op2(x, y), op2(x, y), op2(x, z)) g = FunctionGraph([x, y, z], [e]) MergeOptimizer().optimize(g) assert str(g) == "[Op1(*1 -> Op2(x, y), *1, Op2(x, z))]" def test_constant_merging(self): x = MyVariable('x'...
)) class TestOpSubOptimizer: def test_straightforward(self): x, y, z = inputs() e = op1(op1(op1(op1(op1(x))))) g = FunctionGraph([x, y, z], [e]) OpSubOptimizer(op1, op2).optimize(g) assert str(g) == "[Op2(Op2(Op2(Op2(Op2(x)))))]" def test_straightforward_2(self): ...
256
256
2,580
5
250
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
TestMergeOptimizer
TestMergeOptimizer
311
514
311
312
6c2adf468b26abfcd936f23f529212a1cdf86b67
bigcode/the-stack
train
151cd97ea285d2c7267874be
train
function
def test_pre_constant_merge_slice(): ms = theano.tensor.type_other.MakeSlice()(1) pre_constant_merge([ms]) const_slice = theano.tensor.type_other.SliceConstant( type=theano.tensor.type_other.slicetype, data=slice(1, None, 2)) adv = theano.tensor.subtensor.AdvancedSubtensor()(theano.tenso...
def test_pre_constant_merge_slice():
ms = theano.tensor.type_other.MakeSlice()(1) pre_constant_merge([ms]) const_slice = theano.tensor.type_other.SliceConstant( type=theano.tensor.type_other.slicetype, data=slice(1, None, 2)) adv = theano.tensor.subtensor.AdvancedSubtensor()(theano.tensor.matrix(), ...
=1. / len(g.apply_nodes)) # each opt can only be applied once opt.optimize(g) finally: _logger.setLevel(oldlevel) # print 'after', g assert str(g) == '[Op1(x, y)]' def test_pre_constant_merge_slice():
64
64
153
7
57
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
test_pre_constant_merge_slice
test_pre_constant_merge_slice
574
588
574
574
f5f1de4680aa79d60259be356bd1c37f8622bac0
bigcode/the-stack
train
e56eae7799723274ee001cc4
train
function
def inputs(): x = MyVariable('x') y = MyVariable('y') z = MyVariable('z') return x, y, z
def inputs():
x = MyVariable('x') y = MyVariable('y') z = MyVariable('z') return x, y, z
') op5 = MyOp('Op5') op6 = MyOp('Op6') op_d = MyOp('OpD', {0: [0]}) op_y = MyOp('OpY', x=1) op_z = MyOp('OpZ', x=1) def inputs():
64
64
35
3
61
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
inputs
inputs
85
89
85
85
a2d46c4699a38b781638ba3935f52d3a21cc9d49
bigcode/the-stack
train
c7c88e0be57511fa680c62e9
train
class
class RiskReconParser(object): def get_scan_types(self): return ["Risk Recon API Importer"] def get_label_for_scan_types(self, scan_type): return "Risk Recon API Importer" def get_description_for_scan_types(self, scan_type): return "Risk Recon ApI will be accessed to gather findin...
class RiskReconParser(object):
def get_scan_types(self): return ["Risk Recon API Importer"] def get_label_for_scan_types(self, scan_type): return "Risk Recon API Importer" def get_description_for_scan_types(self, scan_type): return "Risk Recon ApI will be accessed to gather finding information. Report format her...
import json from dojo.models import Finding from dojo.tools.risk_recon.api import RiskReconAPI class RiskReconParser(object):
28
196
656
6
21
steven-hadfield/django-DefectDojo
dojo/tools/risk_recon/parser.py
Python
RiskReconParser
RiskReconParser
7
82
7
8
ab04a237b6813c620986acb0160fb1d094cd0baa
bigcode/the-stack
train
bbec48fb3411ef3c98213e65
train
class
class Constant: __excludes__ = [] class ConstantError(Exception): pass def __setattr__(self, name, value): exclude = name in Constant.__excludes__ if self.__dict__.get(name, None) and not exclude: raise Constant.ConstantError("Property %s is not mutable" % name) ...
class Constant:
__excludes__ = [] class ConstantError(Exception): pass def __setattr__(self, name, value): exclude = name in Constant.__excludes__ if self.__dict__.get(name, None) and not exclude: raise Constant.ConstantError("Property %s is not mutable" % name) self.__dict_...
class Constant:
3
64
82
3
0
mile-core/mile-csa-python
milecsa/config.py
Python
Constant
Constant
2
16
2
3
ae802007b0d308d1d15c1ee410c4d2feace94f0e
bigcode/the-stack
train
013c3f64668336934b210d6d
train
class
class Config(Constant): def __init__(self): Constant.__excludes__.append('sslVerification') Constant.__excludes__.append('connectionTimeout') Constant.__excludes__.append('url') Constant.__excludes__.append('useBalancing') Constant.__excludes__.append('rpcDebug') s...
class Config(Constant):
def __init__(self): Constant.__excludes__.append('sslVerification') Constant.__excludes__.append('connectionTimeout') Constant.__excludes__.append('url') Constant.__excludes__.append('useBalancing') Constant.__excludes__.append('rpcDebug') self.version = "1" ...
class Constant: __excludes__ = [] class ConstantError(Exception): pass def __setattr__(self, name, value): exclude = name in Constant.__excludes__ if self.__dict__.get(name, None) and not exclude: raise Constant.ConstantError("Property %s is not mutable" % name) ...
87
119
397
4
82
mile-core/mile-csa-python
milecsa/config.py
Python
Config
Config
19
70
19
20
7caa3500fc1d19c793d2648edf38954246885402
bigcode/the-stack
train
c1a3697ec1a976c3ef539090
train
class
class GetUserProjectDetailAPITest(APITest): def url(self): return "/apigw/get_user_project_detail/{project_id}/" @patch( PROJECT_GET, MagicMock( return_value=MockProject( project_id=TEST_PROJECT_ID, name=TEST_PROJECT_NAME, bk_b...
class GetUserProjectDetailAPITest(APITest):
def url(self): return "/apigw/get_user_project_detail/{project_id}/" @patch( PROJECT_GET, MagicMock( return_value=MockProject( project_id=TEST_PROJECT_ID, name=TEST_PROJECT_NAME, bk_biz_id=TEST_BIZ_CC_ID, from_c...
language governing permissions and limitations under the License. """ import ujson as json from pipeline.utils.collections import FancyDict from gcloud.tests.mock import * # noqa from gcloud.tests.mock_settings import * # noqa from gcloud import err_code from .utils import APITest TEST_PROJECT_ID = "1" TEST_PR...
163
163
545
10
153
springborland/bk-sops
gcloud/tests/apigw/views/test_get_user_project_detail.py
Python
GetUserProjectDetailAPITest
GetUserProjectDetailAPITest
35
107
35
35
0ef641bedae4457363f409cdf4acfe7766c8531b
bigcode/the-stack
train
5b64fdcf7ad394aaedf3cd6d
train
class
class Trial(BaseTrial): """A trial is a process of evaluating an objective function. This object is passed to an objective function and provides interfaces to get parameter suggestion, manage the trial's state, and set/get user-defined attributes of the trial. Note that the direct use of this construc...
class Trial(BaseTrial):
"""A trial is a process of evaluating an objective function. This object is passed to an objective function and provides interfaces to get parameter suggestion, manage the trial's state, and set/get user-defined attributes of the trial. Note that the direct use of this constructor is not recommended. ...
import copy import datetime from typing import Any from typing import Dict from typing import Optional from typing import Sequence from typing import Union import warnings import optuna from optuna import distributions from optuna import logging from optuna import pruners from optuna._deprecated import deprecated from...
195
256
5,579
5
190
Turakar/optuna
optuna/trial/_trial.py
Python
Trial
Trial
30
749
30
30
0865917fb540431384dcdf67492c0d489c377a8c
bigcode/the-stack
train
65ac57da95839df74771e1f8
train
class
class ListPartnerAdjustRecordsRequest: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sens...
class ListPartnerAdjustRecordsRequest:
""" Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { ...
# coding: utf-8 import pprint import re import six class ListPartnerAdjustRecordsRequest:
23
256
2,255
7
15
wuchen-huawei/huaweicloud-sdk-python-v3
huaweicloud-sdk-bss/huaweicloudsdkbss/v2/model/list_partner_adjust_records_request.py
Python
ListPartnerAdjustRecordsRequest
ListPartnerAdjustRecordsRequest
12
299
12
14
4a3262a76b20aeee6568ce3f60681f60fc5a9db4
bigcode/the-stack
train
47a62cf00747f2c74657a7d5
train
function
def print_usage_error(err): """Print an error about incorrect usage.""" print("USAGE ERROR: %s" % err.message) if err.suggestion is not None: print("Suggestion: %s" % err.suggestion)
def print_usage_error(err):
"""Print an error about incorrect usage.""" print("USAGE ERROR: %s" % err.message) if err.suggestion is not None: print("Suggestion: %s" % err.suggestion)
: %s" % err.variable_name) if value is not None: print("Current Value: %s" % os.environ.get(err.variable_name)) print("Use: %s" % err.reason) print("Suggestion: %s" % err.suggestion) def print_usage_error(err):
64
64
51
6
58
iotile/multipackage
multipackage/scripts/multipackage.py
Python
print_usage_error
print_usage_error
253
259
253
253
1af41203569334c22f3a66cadef5f7d0b077d523
bigcode/the-stack
train
3ea25f1bf25de6972e05f49d
train
function
def main(argv=None): """Main entry point for multipackage console script.""" if argv is None: argv = sys.argv[1:] parser = build_parser() args = parser.parse_args(argv) setup_logging(args) retval = 0 try: if args.action == 'doctor': retval = doctor_repo(args....
def main(argv=None):
"""Main entry point for multipackage console script.""" if argv is None: argv = sys.argv[1:] parser = build_parser() args = parser.parse_args(argv) setup_logging(args) retval = 0 try: if args.action == 'doctor': retval = doctor_repo(args.repo) elif ar...
%s" % err.suggestion) def print_usage_error(err): """Print an error about incorrect usage.""" print("USAGE ERROR: %s" % err.message) if err.suggestion is not None: print("Suggestion: %s" % err.suggestion) def main(argv=None):
64
64
193
5
59
iotile/multipackage
multipackage/scripts/multipackage.py
Python
main
main
262
296
262
262
17d91619e9335c94d74351e3ab39e59e803a7ef9
bigcode/the-stack
train
67fae6a51a68590852b64284
train
function
def build_parser(): """Build the argument parser.""" parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging level (goes error, warn, info, debug)") subparser ...
def build_parser():
"""Build the argument parser.""" parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging level (goes error, warn, info, debug)") subparser = parser.add_subpars...
not been set up with multipackage.\n") print("Set it up with:\n\n\tmultipackage init {}\n".format(repo_path)) return 1 repo.manifest.verify_all(report=True) variables = { "repo": repo, "repo_path": repo_path } info = render_template(repo.template.INFO_TEMPLATE, variab...
103
103
346
4
98
iotile/multipackage
multipackage/scripts/multipackage.py
Python
build_parser
build_parser
182
205
182
182
2100a8bacbe042685331a778fbb4a78d5d3a1a4d
bigcode/the-stack
train
068d8908b728aeb65967ebed
train
function
def setup_logging(args): """Setup log level and output.""" should_log = args.verbose > 0 verbosity = args.verbose root = logging.getLogger() if should_log: formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s', '%y-%m-%d %H:%M:%S') handler = ...
def setup_logging(args):
"""Setup log level and output.""" should_log = args.verbose > 0 verbosity = args.verbose root = logging.getLogger() if should_log: formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s', '%y-%m-%d %H:%M:%S') handler = logging.StreamHandler() ...
update_parser = subparser.add_parser('update', description="Update all managed files to their latest versions", help="update all managed files to their latest versions") update_parser.add_argument('repo', nargs='?', help="Optional path to repository, defaults to cwd") ...
64
64
166
5
58
iotile/multipackage
multipackage/scripts/multipackage.py
Python
setup_logging
setup_logging
208
231
208
208
95e83d9dd6b15b976167a65c603585750974a7a2
bigcode/the-stack
train
ed94e2339630090ede94fb41
train
function
def doctor_repo(repo_path): """Verify that all required environment settings are correct.""" repo = create_repo(repo_path) if repo_path is None: repo_path = "" try: GITRepository(repo_path) except UsageError: print("STATUS: Repository is not a valid git repo.\n") p...
def doctor_repo(repo_path):
"""Verify that all required environment settings are correct.""" repo = create_repo(repo_path) if repo_path is None: repo_path = "" try: GITRepository(repo_path) except UsageError: print("STATUS: Repository is not a valid git repo.\n") print("Make sure your path is...
.""" required = False for decl in declarations: if decl.required: required = True break if value is not None: return "PRESENT" if required and value is None: return "MISSING" return "NOT PRESENT" def doctor_repo(repo_path):
64
64
199
6
58
iotile/multipackage
multipackage/scripts/multipackage.py
Python
doctor_repo
doctor_repo
68
100
68
68
85a65f7a90f475bc5ec15a5ee5dd3eec9fdcbdff
bigcode/the-stack
train
e301f3f84e08d4173071e7ff
train
function
def create_repo(repo_path): """Helper method to create a Repository object.""" if repo_path is None: repo_path = os.getcwd() return Repository(repo_path)
def create_repo(repo_path):
"""Helper method to create a Repository object.""" if repo_path is None: repo_path = os.getcwd() return Repository(repo_path)
"repo": repo, "repo_path": repo_path } filters = { "variable_status": _variable_status } info = render_template(repo.template.DOCTOR_TEMPLATE, variables, filters=filters) sys.stdout.write(info) return 0 def create_repo(repo_path):
64
64
36
6
57
iotile/multipackage
multipackage/scripts/multipackage.py
Python
create_repo
create_repo
103
109
103
103
f5fad1c1b770a19bcc18be0b6692007e9fd4980d
bigcode/the-stack
train
5b7fc11f7c0ed9dfea8198b6
train
function
def _variable_status(value, declarations): """Check that an environment variable exists.""" required = False for decl in declarations: if decl.required: required = True break if value is not None: return "PRESENT" if required and value is None: retu...
def _variable_status(value, declarations):
"""Check that an environment variable exists.""" required = False for decl in declarations: if decl.required: required = True break if value is not None: return "PRESENT" if required and value is None: return "MISSING" return "NOT PRESENT"
must already have a working set of multipackage release scripts installed via a previous call to multipackage init. This will also verify that all of the multipackage build/release scripts in the given repository are correctly installed and check for common errors. """ def _variable_status(value, decl...
64
64
74
8
56
iotile/multipackage
multipackage/scripts/multipackage.py
Python
_variable_status
_variable_status
50
65
50
50
93cadcf6c2eacde0fa5b36c4812a9cf061e1718a
bigcode/the-stack
train
4208d7cdb300afd7ffcf77c4
train
function
def print_environment_error(err): """Print an error about a missing or incorrect ENV variable.""" value = os.environ.get(err.variable_name) if value is None: print("ERROR: A required environment variable is not set correctly") else: print("ERROR: A required environment variable is miss...
def print_environment_error(err):
"""Print an error about a missing or incorrect ENV variable.""" value = os.environ.get(err.variable_name) if value is None: print("ERROR: A required environment variable is not set correctly") else: print("ERROR: A required environment variable is missing") print("Variable Name: %...
.WARNING, logging.INFO, logging.DEBUG] if verbosity >= len(loglevels): verbosity = len(loglevels) - 1 level = loglevels[verbosity] root.setLevel(level) root.addHandler(handler) else: root.addHandler(logging.NullHandler()) def print_environment_error(err):
64
64
127
6
58
iotile/multipackage
multipackage/scripts/multipackage.py
Python
print_environment_error
print_environment_error
234
250
234
234
57a593f8861868e0b08ee610e5489197d6202865
bigcode/the-stack
train
8f37f2936076e68846b3c3e7
train
function
def update_repo(repo_path): """Update the installed files in a repository.""" repo = create_repo(repo_path) if repo.initialized is False: print("\nSTATUS: Repository has not been set up with multipackage.\n") print("Set it up with:\n\n\tmultipackage init {}\n".format(repo_path)) re...
def update_repo(repo_path):
"""Update the installed files in a repository.""" repo = create_repo(repo_path) if repo.initialized is False: print("\nSTATUS: Repository has not been set up with multipackage.\n") print("Set it up with:\n\n\tmultipackage init {}\n".format(repo_path)) return 1 if not repo.clea...
.""" if repo_path is None: repo_path = os.getcwd() return Repository(repo_path) def init_repo(repo_path, clean): """Initialize or reinitialize a repository.""" repo = create_repo(repo_path) repo.initialize(clean=clean) return 0 def update_repo(repo_path):
64
64
123
6
57
iotile/multipackage
multipackage/scripts/multipackage.py
Python
update_repo
update_repo
120
136
120
120
64431195b6d76ac27026377f305c1cbba81e8873
bigcode/the-stack
train
89eb41baf1b8f9e315ff5861
train
function
def info_repo(repo_path): """Get info on the given repository. Args: repo_path (str): The path to the repository. Returns: int: An error code indicating any issues. """ repo = create_repo(repo_path) if repo_path is None: repo_path = "" try: GITRepository(...
def info_repo(repo_path):
"""Get info on the given repository. Args: repo_path (str): The path to the repository. Returns: int: An error code indicating any issues. """ repo = create_repo(repo_path) if repo_path is None: repo_path = "" try: GITRepository(repo_path) except Usag...
multipackage init {}\n".format(repo_path)) return 1 if not repo.clean: print("ERROR: Repository has errors, please correct them first\n") print(" multipackage info {}".format(repo_path)) return 2 repo.update() return 0 def info_repo(repo_path):
68
68
227
6
61
iotile/multipackage
multipackage/scripts/multipackage.py
Python
info_repo
info_repo
139
179
139
139
b0fcd1aa839be1b8c256dca1556ba70a391a488b
bigcode/the-stack
train
965695c360403a5887b42e75
train
function
def init_repo(repo_path, clean): """Initialize or reinitialize a repository.""" repo = create_repo(repo_path) repo.initialize(clean=clean) return 0
def init_repo(repo_path, clean):
"""Initialize or reinitialize a repository.""" repo = create_repo(repo_path) repo.initialize(clean=clean) return 0
CTOR_TEMPLATE, variables, filters=filters) sys.stdout.write(info) return 0 def create_repo(repo_path): """Helper method to create a Repository object.""" if repo_path is None: repo_path = os.getcwd() return Repository(repo_path) def init_repo(repo_path, clean):
64
64
37
8
56
iotile/multipackage
multipackage/scripts/multipackage.py
Python
init_repo
init_repo
112
118
112
112
0866a8425455ab0bdc663a9c3a748e31609d53a1
bigcode/the-stack
train
47f7e3de721833176d895a03
train
function
def test(): import doctest doctest.testmod(verbose=1)
def test():
import doctest doctest.testmod(verbose=1)
>>> exp2(17)-1 131071 >>> exp2 = lambda y: pow(2, y) >>> exp2(12) 4096 >>> exp2(17)-1 131071 """ __test__ = { "test_correctness": test_correctness, } def test():
64
64
17
3
61
leetschau/Functional-Python-Programming-Second-Edition
Chapter10/ch10_ex3.py
Python
test
test
37
39
37
37
bd22aafef1291cde98e568e9094957bed57a9db0
bigcode/the-stack
train
e2bb50e2cb7ad3013da40580
train
function
def performance(): import timeit f1 = timeit.timeit("""exp2(12)""", setup=""" from functools import partial exp2 = partial(pow, 2)""") print("partial", f1) f2 = timeit.timeit("""exp2(12)""", """exp2 = lambda y: pow(2, y)""") print("lambda", f2)
def performance():
import timeit f1 = timeit.timeit("""exp2(12)""", setup=""" from functools import partial exp2 = partial(pow, 2)""") print("partial", f1) f2 = timeit.timeit("""exp2(12)""", """exp2 = lambda y: pow(2, y)""") print("lambda", f2)
#!/usr/bin/env python3 """Functional Python Programming Chapter 10, Example Set 3 """ # pylint: disable=wrong-import-position from functools import partial def performance():
39
64
90
3
35
leetschau/Functional-Python-Programming-Second-Edition
Chapter10/ch10_ex3.py
Python
performance
performance
10
18
10
10
ba8e3f8b225095df46936b5c5454ab29c5dd4db3
bigcode/the-stack
train
27094e1ced994c56d0489fd6
train
function
def zero_one_unnormalization(X_normalized, lower, upper): return lower + (upper - lower) * X_normalized
def zero_one_unnormalization(X_normalized, lower, upper):
return lower + (upper - lower) * X_normalized
=0) if upper is None: upper = np.max(X, axis=0) X_normalized = np.true_divide((X - lower), (upper - lower)) return X_normalized, lower, upper def zero_one_unnormalization(X_normalized, lower, upper):
64
64
29
15
48
PKU-DAIR/open-box
openbox/utils/transform.py
Python
zero_one_unnormalization
zero_one_unnormalization
18
19
18
18
08eb88020e866e663e526cf1d612c42209eb931b
bigcode/the-stack
train
e2b5e80638caf9359c716796
train
function
def zero_one_normalization(X, lower=None, upper=None): if lower is None: lower = np.min(X, axis=0) if upper is None: upper = np.max(X, axis=0) X_normalized = np.true_divide((X - lower), (upper - lower)) return X_normalized, lower, upper
def zero_one_normalization(X, lower=None, upper=None):
if lower is None: lower = np.min(X, axis=0) if upper is None: upper = np.max(X, axis=0) X_normalized = np.true_divide((X - lower), (upper - lower)) return X_normalized, lower, upper
# License: MIT import numpy as np from scipy import stats def zero_one_normalization(X, lower=None, upper=None):
28
64
76
13
14
PKU-DAIR/open-box
openbox/utils/transform.py
Python
zero_one_normalization
zero_one_normalization
7
15
7
7
7b0b5f19acd5c0fce7b52c8db98df57c10326ea4
bigcode/the-stack
train
60db199b64d690768c113f4d
train
function
def zero_mean_unit_var_normalization(X, mean=None, std=None): if mean is None: mean = np.mean(X, axis=0) if std is None: std = np.std(X, axis=0) + 1e-4 X_normalized = (X - mean) / std return X_normalized, mean, std
def zero_mean_unit_var_normalization(X, mean=None, std=None):
if mean is None: mean = np.mean(X, axis=0) if std is None: std = np.std(X, axis=0) + 1e-4 X_normalized = (X - mean) / std return X_normalized, mean, std
((X - lower), (upper - lower)) return X_normalized, lower, upper def zero_one_unnormalization(X_normalized, lower, upper): return lower + (upper - lower) * X_normalized def zero_mean_unit_var_normalization(X, mean=None, std=None):
64
64
79
15
48
PKU-DAIR/open-box
openbox/utils/transform.py
Python
zero_mean_unit_var_normalization
zero_mean_unit_var_normalization
22
30
22
22
671f6decbe92dca361f529315622fbcb8161ae2e
bigcode/the-stack
train
2569106e04414ba6c4989eee
train
function
def zero_mean_unit_var_unnormalization(X_normalized, mean, std): return X_normalized * std + mean
def zero_mean_unit_var_unnormalization(X_normalized, mean, std):
return X_normalized * std + mean
if std is None: std = np.std(X, axis=0) + 1e-4 X_normalized = (X - mean) / std return X_normalized, mean, std def zero_mean_unit_var_unnormalization(X_normalized, mean, std):
64
64
27
17
46
PKU-DAIR/open-box
openbox/utils/transform.py
Python
zero_mean_unit_var_unnormalization
zero_mean_unit_var_unnormalization
33
34
33
33
8d0640723c34993122bc4868164e6865258f6244
bigcode/the-stack
train
1bd7abb0eb22ca903d311511
train
function
def bilog_transform(X: np.ndarray): """Magnify the difference between X and 0""" X = X.copy() idx = (X >= 0) X[idx] = np.log(1 + X[idx]) X[~idx] = -np.log(1 - X[~idx]) return X
def bilog_transform(X: np.ndarray):
"""Magnify the difference between X and 0""" X = X.copy() idx = (X >= 0) X[idx] = np.log(1 + X[idx]) X[~idx] = -np.log(1 - X[~idx]) return X
1e-4 X_normalized = (X - mean) / std return X_normalized, mean, std def zero_mean_unit_var_unnormalization(X_normalized, mean, std): return X_normalized * std + mean def bilog_transform(X: np.ndarray):
64
64
71
9
54
PKU-DAIR/open-box
openbox/utils/transform.py
Python
bilog_transform
bilog_transform
37
43
37
37
6884b5afb8ce79711bf15acc04c47a2a2b9380fb
bigcode/the-stack
train
e32cf3a4a2ae3900edc63d14
train
function
def gaussian_transform(X: np.ndarray): """ Transform data into Gaussian by applying psi = Phi^{-1} o F where F is the truncated ECDF. References: [1] Andrew Gordon Wilson and Zoubin Ghahramani. Copula processes. In Proceedings of the 23rd International Conference on Neural Information Processin...
def gaussian_transform(X: np.ndarray):
""" Transform data into Gaussian by applying psi = Phi^{-1} o F where F is the truncated ECDF. References: [1] Andrew Gordon Wilson and Zoubin Ghahramani. Copula processes. In Proceedings of the 23rd International Conference on Neural Information Processing Systems - Volume 2, NIPS’10, ...
ormalization(X_normalized, mean, std): return X_normalized * std + mean def bilog_transform(X: np.ndarray): """Magnify the difference between X and 0""" X = X.copy() idx = (X >= 0) X[idx] = np.log(1 + X[idx]) X[~idx] = -np.log(1 - X[~idx]) return X def gaussian_transform(X: np.ndarray):
99
99
333
8
90
PKU-DAIR/open-box
openbox/utils/transform.py
Python
gaussian_transform
gaussian_transform
46
76
46
46
713d82ba0fd5bd77f65c7fec218951fb28b2092a
bigcode/the-stack
train
51f2349fd332df3c09b4a7f1
train
function
def get_transform_function(transform: str): if transform in _func_dict.keys(): return _func_dict[transform] else: raise ValueError('Invalid transform: %s' % (transform, ))
def get_transform_function(transform: str):
if transform in _func_dict.keys(): return _func_dict[transform] else: raise ValueError('Invalid transform: %s' % (transform, ))
ile, a_min=delta, a_max=1 - delta) return stats.norm.ppf(truncated_quantile(X)) _func_dict = { 'bilog': bilog_transform, 'gaussian': gaussian_transform, None: lambda x: x, } def get_transform_function(transform: str):
64
64
44
8
56
PKU-DAIR/open-box
openbox/utils/transform.py
Python
get_transform_function
get_transform_function
86
90
86
86
4793791453925a381e3b46cf7d29d3f913474472
bigcode/the-stack
train
de096b4157aa18a115f03631
train
function
@tier1 @skipif_ocs_version("<4.6") @skipif_ocp_version("<4.6") @marks.polarion_id("OCS-2376") @marks.bugzilla("1873162") @skipif_managed_service def test_hpa_noobaa_endpoint_metric(): """ Test to verify HPA noobaa-endpoint cpu metrics is available. Since 4.10, it uses horizontal-pod-autoscaler-v2 API. "...
@tier1 @skipif_ocs_version("<4.6") @skipif_ocp_version("<4.6") @marks.polarion_id("OCS-2376") @marks.bugzilla("1873162") @skipif_managed_service def test_hpa_noobaa_endpoint_metric():
""" Test to verify HPA noobaa-endpoint cpu metrics is available. Since 4.10, it uses horizontal-pod-autoscaler-v2 API. """ ocp_version = get_semantic_version(get_ocp_version(), only_major_minor=True) ocp_obj = ocp.OCP( kind=constants.HPA, resource_name="noobaa-endpoint", ...
if_ocp_version from ocs_ci.ocs import constants, defaults, ocp from ocs_ci.ocs.version import get_ocp_version from ocs_ci.utility.version import get_semantic_version, VERSION_4_10 logger = logging.getLogger(__name__) @tier1 @skipif_ocs_version("<4.6") @skipif_ocp_version("<4.6") @marks.polarion_id("OCS-2376") @marks.b...
124
124
414
66
58
srivickynesh/ocs-ci
tests/manage/monitoring/prometheusmetrics/test_mcg_hpa.py
Python
test_hpa_noobaa_endpoint_metric
test_hpa_noobaa_endpoint_metric
14
55
14
20
984f31324515416a63632ec8e2073164e246276c
bigcode/the-stack
train
80e8a8ddd8928810e7fe26a9
train
class
class TestMerger(object): def __init__(self, name, input_pattern, input_separator, input_terminator, output_separator, output_terminator): self.name = name self.input_pattern = input_pattern self.input_separator = input_separator self.input_terminator = input_terminator ...
class TestMerger(object):
def __init__(self, name, input_pattern, input_separator, input_terminator, output_separator, output_terminator): self.name = name self.input_pattern = input_pattern self.input_separator = input_separator self.input_terminator = input_terminator self.output_separator =...
FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # import fnmatch import os.path from rime.basic import consts from rime.basic import test import rime.basic.targe...
110
110
367
6
103
ProgrammingDaisukiClub/Orientation2015Problems
rime/plugins/merged_test.py
Python
TestMerger
TestMerger
35
74
35
35
447edc40cab6d398b54815e8cce3d9a5bf918c02
bigcode/the-stack
train
f68a074ff1c75b774292b6b6
train
class
class MergedTestCase(test.TestCase): def __init__(self, testset, merger): super(MergedTestCase, self).__init__( testset, os.path.join(testset.out_dir, '%s%s' % (merger.name, consts.IN_EXT))) self.merger = merger @property def timeout(self): return None
class MergedTestCase(test.TestCase):
def __init__(self, testset, merger): super(MergedTestCase, self).__init__( testset, os.path.join(testset.out_dir, '%s%s' % (merger.name, consts.IN_EXT))) self.merger = merger @property def timeout(self): return None
dst, separator, terminator): with open(dst, 'w') as f: for i, src in enumerate(srcs): if i > 0: f.write(separator) f.write(files.ReadFile(src)) f.write(terminator) class MergedTestCase(test.TestCase):
64
64
81
9
55
ProgrammingDaisukiClub/Orientation2015Problems
rime/plugins/merged_test.py
Python
MergedTestCase
MergedTestCase
77
86
77
77
0a4803bee9537ade6e175db6b8c8e3c41b30c1af
bigcode/the-stack
train
22a10428ad022c8937bc72c2
train
class
class Testset(targets.registry.Testset): def __init__(self, *args, **kwargs): super(Testset, self).__init__(*args, **kwargs) self.mergers = [] def PreLoad(self, ui): super(Testset, self).PreLoad(ui) def merged_test(name=None, input_pattern=('*' + consts.IN_EXT), input_separator=...
class Testset(targets.registry.Testset):
def __init__(self, *args, **kwargs): super(Testset, self).__init__(*args, **kwargs) self.mergers = [] def PreLoad(self, ui): super(Testset, self).PreLoad(ui) def merged_test(name=None, input_pattern=('*' + consts.IN_EXT), input_separator='', input_terminator='', ...
.input_separator, self.input_terminator) ui.console.PrintAction( 'MERGE', merged_testcase.testset, 'Generating %s' % os.path.basename(merged_testcase.difffile), progress=True) self._Concatenate(difffiles, merged_testcase.difffile, self.output_separat...
239
239
799
9
229
ProgrammingDaisukiClub/Orientation2015Problems
rime/plugins/merged_test.py
Python
Testset
Testset
89
175
89
89
ab6d2aec1af1ec761a918ec1218327fd2f8ae97d
bigcode/the-stack
train
482963980bbbd2a7d5b283a7
train
class
class CallEvent(ct.Structure): _fields_ = [ ("depth", ct.c_ulonglong), ("pid", ct.c_ulonglong), ("clazz", ct.c_char * 80), ("method", ct.c_char * 80) ]
class CallEvent(ct.Structure):
_fields_ = [ ("depth", ct.c_ulonglong), ("pid", ct.c_ulonglong), ("clazz", ct.c_char * 80), ("method", ct.c_char * 80) ]
method calls in %s process %d... Ctrl-C to quit." % (language, args.pid)) print("%-3s %-6s %-6s %-8s %s" % ("CPU", "PID", "TID", "TIME(us)", "METHOD")) class CallEvent(ct.Structure):
64
64
55
7
57
yzhao1012/bcc
tools/lib/uflow.py
Python
CallEvent
CallEvent
190
196
190
190
c3d9d4b5859e106b347edf6d573c51fe2e356dba
bigcode/the-stack
train
a3df25c4861db56f27550c05
train
function
def enable_probe(probe_name, func_name, read_class, read_method, is_return): global program, trace_template, usdt depth = "*depth + 1" if not is_return else "*depth | (1ULL << 63)" update = "++(*depth);" if not is_return else "if (*depth) --(*depth);" filter_class = "if (!prefix_class(data.clazz)) { ret...
def enable_probe(probe_name, func_name, read_class, read_method, is_return):
global program, trace_template, usdt depth = "*depth + 1" if not is_return else "*depth | (1ULL << 63)" update = "++(*depth);" if not is_return else "if (*depth) --(*depth);" filter_class = "if (!prefix_class(data.clazz)) { return 0; }" \ if args.clazz else "" filter_method = "if ...
, &zero); if (!depth) { depth = &zero; } data.depth = DEPTH; UPDATE calls.perf_submit(ctx, &data, sizeof(data)); return 0; } """ def enable_probe(probe_name, func_name, read_class, read_method, is_return):
67
67
226
19
48
yzhao1012/bcc
tools/lib/uflow.py
Python
enable_probe
enable_probe
103
118
103
103
767e2232909bd3be08819614f9240ed08cde3b5d
bigcode/the-stack
train
193d3e4b2f69db91f9007d9e
train
function
def print_event(cpu, data, size): event = ct.cast(data, ct.POINTER(CallEvent)).contents depth = event.depth & (~(1 << 63)) direction = "<- " if event.depth & (1 << 63) else "-> " print("%-3d %-6d %-6d %-8.3f %-40s" % (cpu, event.pid >> 32, event.pid & 0xFFFFFFFF, time.time() - start_ts, ...
def print_event(cpu, data, size):
event = ct.cast(data, ct.POINTER(CallEvent)).contents depth = event.depth & (~(1 << 63)) direction = "<- " if event.depth & (1 << 63) else "-> " print("%-3d %-6d %-6d %-8.3f %-40s" % (cpu, event.pid >> 32, event.pid & 0xFFFFFFFF, time.time() - start_ts, (" " * (depth - 1)) + direction +...
): _fields_ = [ ("depth", ct.c_ulonglong), ("pid", ct.c_ulonglong), ("clazz", ct.c_char * 80), ("method", ct.c_char * 80) ] start_ts = time.time() def print_event(cpu, data, size):
64
64
148
9
55
yzhao1012/bcc
tools/lib/uflow.py
Python
print_event
print_event
200
208
200
200
50d7410ad05f8c48ebf0b56bec497e95c3d85d24
bigcode/the-stack
train
453da72c4949dd0fae353716
train
class
class Caption(Component): """A Caption component. Keyword arguments: - children (a list of or a singular dash component, string or number; optional): The children of this component - id (string; optional): The ID of this component, used to identify dash components in callbacks. The ID needs to be unique across al...
class Caption(Component):
"""A Caption component. Keyword arguments: - children (a list of or a singular dash component, string or number; optional): The children of this component - id (string; optional): The ID of this component, used to identify dash components in callbacks. The ID needs to be unique across all of the components in an ...
# AUTO GENERATED FILE - DO NOT EDIT from dash.development.base_component import Component, _explicitize_args class Caption(Component):
27
256
1,045
4
22
alzo425/dash-sample-apps
apps/dash-web-trader/env/Lib/site-packages/dash_html_components/Caption.py
Python
Caption
Caption
6
61
6
6
7b994e8a9ceb8371f4f7da331ef699bc056e9809
bigcode/the-stack
train
1386f70ea92bbdb0731a218a
train
class
class py_external(object): def __init__(self): super(py_external, self).__init__() self.pyTemperature = None def getDataFromWunderground(self): #f = urlopen(STATION_URL) # DEBUG ONLY #json_file=open("pws_IMEYREUI2.json") #json_data = json.load(json_file) ...
class py_external(object):
def __init__(self): super(py_external, self).__init__() self.pyTemperature = None def getDataFromWunderground(self): #f = urlopen(STATION_URL) # DEBUG ONLY #json_file=open("pws_IMEYREUI2.json") #json_data = json.load(json_file) #json_file.close() ...
#!/usr/bin/env python # Get External Temperature from OpenWeatherMap # External informations are : # - temperature # - humidity # - pressure # - precipitation volume (each 3h) import urllib.request import json import pyowm from datetime import datetime from urllib.request import urlopen import json from pyserial impo...
168
170
567
5
163
mattcongy/piprobe
pyexternal.py
Python
py_external
py_external
25
96
25
25
8e63749718f7afa9c2eee84fbc990f11ad939a4f
bigcode/the-stack
train
e54ed1d7e255a6ae70971d06
train
class
class HDF5StubImageFile(ImageFile.StubImageFile): format = "HDF5" format_description = "HDF5" def _open(self): offset = self.fp.tell() if not _accept(self.fp.read(8)): raise SyntaxError("Not an HDF file") self.fp.seek(offset) # make something up self...
class HDF5StubImageFile(ImageFile.StubImageFile):
format = "HDF5" format_description = "HDF5" def _open(self): offset = self.fp.tell() if not _accept(self.fp.read(8)): raise SyntaxError("Not an HDF file") self.fp.seek(offset) # make something up self.mode = "F" self.size = 1, 1 loade...
handler: Handler object. """ global _handler _handler = handler # -------------------------------------------------------------------- # Image adapter def _accept(prefix): return prefix[:8] == b"\x89HDF\r\n\x1a\n" class HDF5StubImageFile(ImageFile.StubImageFile):
64
64
122
14
50
Seifar/ChitAnalysis
venv/lib/python3.6/site-packages/PIL/Hdf5StubImagePlugin.py
Python
HDF5StubImageFile
HDF5StubImageFile
34
57
34
35
7e42f7f4a9ebb09b93fea7faa30b7382ddf79ff6
bigcode/the-stack
train
240b2804af8c41a5748861e2
train
function
def _save(im, fp, filename): if _handler is None or not hasattr("_handler", "save"): raise IOError("HDF5 save handler not installed") _handler.save(im, fp, filename)
def _save(im, fp, filename):
if _handler is None or not hasattr("_handler", "save"): raise IOError("HDF5 save handler not installed") _handler.save(im, fp, filename)
self.fp.seek(offset) # make something up self.mode = "F" self.size = 1, 1 loader = self._load() if loader: loader.open(self) def _load(self): return _handler def _save(im, fp, filename):
64
64
46
9
54
Seifar/ChitAnalysis
venv/lib/python3.6/site-packages/PIL/Hdf5StubImagePlugin.py
Python
_save
_save
60
63
60
60
175bd7868411552f7933f14da9b4ee803858301b
bigcode/the-stack
train
782e8a51afa62ce10f3275ae
train
function
def register_handler(handler): """ Install application-specific HDF5 image handler. :param handler: Handler object. """ global _handler _handler = handler
def register_handler(handler):
""" Install application-specific HDF5 image handler. :param handler: Handler object. """ global _handler _handler = handler
Imaging Library # $Id$ # # HDF5 stub adapter # # Copyright (c) 2000-2003 by Fredrik Lundh # # See the README file for information on usage and redistribution. # from . import Image, ImageFile _handler = None def register_handler(handler):
64
64
38
5
58
Seifar/ChitAnalysis
venv/lib/python3.6/site-packages/PIL/Hdf5StubImagePlugin.py
Python
register_handler
register_handler
17
24
17
17
036184a8d3cabd5de5171d04cc1cc55ad05852c1
bigcode/the-stack
train
50d02414a151c590729ff863
train
function
def _accept(prefix): return prefix[:8] == b"\x89HDF\r\n\x1a\n"
def _accept(prefix):
return prefix[:8] == b"\x89HDF\r\n\x1a\n"
. # from . import Image, ImageFile _handler = None def register_handler(handler): """ Install application-specific HDF5 image handler. :param handler: Handler object. """ global _handler _handler = handler # -------------------------------------------------------------------- # Image adap...
64
64
25
5
58
Seifar/ChitAnalysis
venv/lib/python3.6/site-packages/PIL/Hdf5StubImagePlugin.py
Python
_accept
_accept
30
31
30
30
5564b12aa2790030f9ed2dbbb390394ffb668e6c
bigcode/the-stack
train
716d03bd2ccf10a1b11880bc
train
class
class ArubaCentralBase: def __init__(self, central_info, token_store=None, logger=None, ssl_verify=True): self.central_info = parseInputArgs(central_info) self.token_store = token_store self.logger = None self.ssl_verify = ssl_verify # Set logger if l...
class ArubaCentralBase:
def __init__(self, central_info, token_store=None, logger=None, ssl_verify=True): self.central_info = parseInputArgs(central_info) self.token_store = token_store self.logger = None self.ssl_verify = ssl_verify # Set logger if logger: self....
Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED...
256
256
3,401
5
250
k1z2/central-examples-only
rest-api-python-scripts/central_lib/arubacentral_base.py
Python
ArubaCentralBase
ArubaCentralBase
36
460
36
36
54c071ff483b3027a177d28ced8ecab146c11950
bigcode/the-stack
train
6d09e772a45333dd53151a4b
train
class
class BearerAuth(requests.auth.AuthBase): def __init__(self, token): self.token = token def __call__(self, r): r.headers["authorization"] = "Bearer " + self.token return r
class BearerAuth(requests.auth.AuthBase):
def __init__(self, token): self.token = token def __call__(self, r): r.headers["authorization"] = "Bearer " + self.token return r
os import requests from central_lib.arubacentral_utilities import tokenLocalStoreUtil from central_lib.arubacentral_utilities import C_DEFAULT_ARGS, get_url from central_lib.arubacentral_utilities import console_logger, parseInputArgs class BearerAuth(requests.auth.AuthBase):
64
64
52
10
53
k1z2/central-examples-only
rest-api-python-scripts/central_lib/arubacentral_base.py
Python
BearerAuth
BearerAuth
29
34
29
29
ccc775c79a08e20cbabee019f4342ed99a2ef0b9
bigcode/the-stack
train
8b619c5ac713e5e1d3d29fa9
train
function
@pytest.fixture def points(): return np.array([[2.0, 3.0], [2.0, 1.0], [1.0, 1.0]])
@pytest.fixture def points():
return np.array([[2.0, 3.0], [2.0, 1.0], [1.0, 1.0]])
.potential import laplace, helmholtz, maxwell scalar_spaces = [("DP", 0), ("DP", 1), ("P", 1)] div_spaces = [("RWG", 0)] curl_spaces = [("SNC", 0)] @pytest.fixture def points():
63
64
40
6
57
pescap/bempp-cl
test/unit/operators/test_potential_operators.py
Python
points
points
14
16
14
15
11012e02b4bedb9dc03062aa2f923f07529c42a5
bigcode/the-stack
train
8dc08a847128bec2605c8f9d
train
function
@pytest.mark.parametrize("operator", [laplace.single_layer, laplace.double_layer]) @pytest.mark.parametrize("space_type", scalar_spaces) def test_laplace_operators(points, operator, space_type): """Test dense assembler for the Laplace operators.""" grid = bempp.api.shapes.regular_sphere(0) space = function_...
@pytest.mark.parametrize("operator", [laplace.single_layer, laplace.double_layer]) @pytest.mark.parametrize("space_type", scalar_spaces) def test_laplace_operators(points, operator, space_type):
"""Test dense assembler for the Laplace operators.""" grid = bempp.api.shapes.regular_sphere(0) space = function_space(grid, *space_type) fun = bempp.api.GridFunction( space, coefficients=np.random.rand(space.global_dof_count) ) operator(space, points).evaluate(fun)
0], [2.0, 1.0], [1.0, 1.0]]) @pytest.mark.parametrize("operator", [laplace.single_layer, laplace.double_layer]) @pytest.mark.parametrize("space_type", scalar_spaces) def test_laplace_operators(points, operator, space_type):
63
64
111
41
22
pescap/bempp-cl
test/unit/operators/test_potential_operators.py
Python
test_laplace_operators
test_laplace_operators
19
29
19
21
565bd17efebc511541f38e15a75ea330d987d515
bigcode/the-stack
train
13bdfdf39d7e14fe02ce8f76
train
function
@pytest.mark.parametrize("operator", [helmholtz.single_layer, helmholtz.double_layer]) @pytest.mark.parametrize("space_type", scalar_spaces) @pytest.mark.parametrize("wavenumber", [2.5, 2.5 + 1j]) def test_helmholtz_operators(points, operator, wavenumber, space_type): """Test dense assembler for the Helmholtz opera...
@pytest.mark.parametrize("operator", [helmholtz.single_layer, helmholtz.double_layer]) @pytest.mark.parametrize("space_type", scalar_spaces) @pytest.mark.parametrize("wavenumber", [2.5, 2.5 + 1j]) def test_helmholtz_operators(points, operator, wavenumber, space_type):
"""Test dense assembler for the Helmholtz operators.""" grid = bempp.api.shapes.regular_sphere(0) space = function_space(grid, *space_type) fun = bempp.api.GridFunction( space, coefficients=np.random.rand(space.global_dof_count) ) operator(space, points, wavenumber).evaluate(fun)
@pytest.mark.parametrize("operator", [helmholtz.single_layer, helmholtz.double_layer]) @pytest.mark.parametrize("space_type", scalar_spaces) @pytest.mark.parametrize("wavenumber", [2.5, 2.5 + 1j]) def test_helmholtz_operators(points, operator, wavenumber, space_type):
70
64
145
70
0
pescap/bempp-cl
test/unit/operators/test_potential_operators.py
Python
test_helmholtz_operators
test_helmholtz_operators
32
43
32
35
db8ed803f75241d355b3a4ce4dc53fedc2d9d4b0
bigcode/the-stack
train
4ac67217c3bea81e7376e4f9
train
function
@pytest.mark.parametrize("operator", [maxwell.electric_field, maxwell.magnetic_field]) @pytest.mark.parametrize("space_type", div_spaces) @pytest.mark.parametrize("wavenumber", [2.5, 2.5 + 1j]) def test_maxwell_operators(points, operator, wavenumber, space_type): """Test dense assembler for the Helmholtz operators....
@pytest.mark.parametrize("operator", [maxwell.electric_field, maxwell.magnetic_field]) @pytest.mark.parametrize("space_type", div_spaces) @pytest.mark.parametrize("wavenumber", [2.5, 2.5 + 1j]) def test_maxwell_operators(points, operator, wavenumber, space_type):
"""Test dense assembler for the Helmholtz operators.""" grid = bempp.api.shapes.regular_sphere(0) space = function_space(grid, *space_type) fun = bempp.api.GridFunction( space, coefficients=np.random.rand(space.global_dof_count) ) operator(space, points, wavenumber).evaluate(fun)
@pytest.mark.parametrize("operator", [maxwell.electric_field, maxwell.magnetic_field]) @pytest.mark.parametrize("space_type", div_spaces) @pytest.mark.parametrize("wavenumber", [2.5, 2.5 + 1j]) def test_maxwell_operators(points, operator, wavenumber, space_type):
68
64
143
68
0
pescap/bempp-cl
test/unit/operators/test_potential_operators.py
Python
test_maxwell_operators
test_maxwell_operators
46
57
46
49
ae35ab048d1feb70bf31498d2cbcec7bac2c8fc0
bigcode/the-stack
train
26a8530b72694761597e6331
train
function
def build( step, pkg, depmap, signkey, chost = False, dirty = False, keep_temp = False, check_fail = False ): if chost: depn = "host-" + pkg.pkgname else: depn = pkg.pkgname if pkg.pkgname in depmap or depn in depmap: pkg.error(f"build-time dependency cycle encountered for {...
def build( step, pkg, depmap, signkey, chost = False, dirty = False, keep_temp = False, check_fail = False ):
if chost: depn = "host-" + pkg.pkgname else: depn = pkg.pkgname if pkg.pkgname in depmap or depn in depmap: pkg.error(f"build-time dependency cycle encountered for {pkg.pkgname} (dependency of {pkg.origin.pkgname})") depmap[depn] = True pkg.install_done = False pkg.cur...
from cbuild.step import fetch, extract, patch, configure from cbuild.step import build as buildm, check, install, prepkg, pkg as pkgsm from cbuild.core import chroot, logger, dependencies from cbuild.core import template, pkg as pkgm, paths, errors from cbuild.apk import cli as apk import os import pathlib def build( ...
113
256
1,062
35
77
matu3ba/cports
src/cbuild/core/build.py
Python
build
build
10
163
10
13
e29491775ad4e2f6ecf24c6529a2e6d3da82a065
bigcode/the-stack
train
df535b667190d31abb449385
train
class
class ZwaveColorLight(ZwaveDimmer): """Representation of a Z-Wave color changing light.""" def __init__(self, value, refresh, delay): """Initialize the light.""" from openzwave.network import ZWaveNetwork from pydispatch import dispatcher self._value_color = None self._...
class ZwaveColorLight(ZwaveDimmer):
"""Representation of a Z-Wave color changing light.""" def __init__(self, value, refresh, delay): """Initialize the light.""" from openzwave.network import ZWaveNetwork from pydispatch import dispatcher self._value_color = None self._value_color_channels = None ...
@property def is_on(self): """Return true if device is on.""" return self._state == STATE_ON @property def supported_features(self): """Flag supported features.""" return SUPPORT_ZWAVE def turn_on(self, **kwargs): """Turn the device on.""" if ATTR_BR...
256
256
1,312
10
246
mbs-technologie/home-assistant
homeassistant/components/light/zwave.py
Python
ZwaveColorLight
ZwaveColorLight
190
351
190
190
4db138ca3a1b48e60fe006f16819b9a16bc2d0e6
bigcode/the-stack
train
9287105a3e1f1fb7cdf804af
train
class
class ZwaveDimmer(zwave.ZWaveDeviceEntity, Light): """Representation of a Z-Wave dimmer.""" def __init__(self, value, refresh, delay): """Initialize the light.""" from openzwave.network import ZWaveNetwork from pydispatch import dispatcher zwave.ZWaveDeviceEntity.__init__(self,...
class ZwaveDimmer(zwave.ZWaveDeviceEntity, Light):
"""Representation of a Z-Wave dimmer.""" def __init__(self, value, refresh, delay): """Initialize the light.""" from openzwave.network import ZWaveNetwork from pydispatch import dispatcher zwave.ZWaveDeviceEntity.__init__(self, value, DOMAIN) self._brightness = None ...
= node_config.get(zwave.CONF_REFRESH_DELAY) _LOGGER.debug('customize=%s name=%s node_config=%s CONF_REFRESH_VALUE=%s' ' CONF_REFRESH_DELAY=%s', customize, name, node_config, refresh, delay) if value.command_class != zwave.const.COMMAND_CLASS_SWITCH_MULTILEVEL: return...
222
222
742
15
206
mbs-technologie/home-assistant
homeassistant/components/light/zwave.py
Python
ZwaveDimmer
ZwaveDimmer
85
180
85
85
241299527820e722d5b9c83b6df5625ba66d6149
bigcode/the-stack
train
9d139e6904927511d8471368
train
function
def brightness_state(value): """Return the brightness and state.""" if value.data > 0: return (value.data / 99) * 255, STATE_ON else: return 255, STATE_OFF
def brightness_state(value):
"""Return the brightness and state.""" if value.data > 0: return (value.data / 99) * 255, STATE_ON else: return 255, STATE_OFF
: return value.set_change_verified(False) if node.has_command_class(zwave.const.COMMAND_CLASS_SWITCH_COLOR): add_devices([ZwaveColorLight(value, refresh, delay)]) else: add_devices([ZwaveDimmer(value, refresh, delay)]) def brightness_state(value):
63
64
48
5
58
mbs-technologie/home-assistant
homeassistant/components/light/zwave.py
Python
brightness_state
brightness_state
77
82
77
77
12616642b9606799b938e5c6eae848f5c265e6bf
bigcode/the-stack
train
45cf476775ad08d47c31c052
train
function
def ct_to_rgb(temp): """Convert color temperature (mireds) to RGB.""" colorlist = list( color_temperature_to_rgb(color_temperature_mired_to_kelvin(temp))) return [int(val) for val in colorlist]
def ct_to_rgb(temp):
"""Convert color temperature (mireds) to RGB.""" colorlist = list( color_temperature_to_rgb(color_temperature_mired_to_kelvin(temp))) return [int(val) for val in colorlist]
(self._value.value_id, brightness): self._state = STATE_ON def turn_off(self, **kwargs): """Turn the device off.""" if self._value.node.set_dimmer(self._value.value_id, 0): self._state = STATE_OFF def ct_to_rgb(temp):
64
64
51
6
57
mbs-technologie/home-assistant
homeassistant/components/light/zwave.py
Python
ct_to_rgb
ct_to_rgb
183
187
183
183
ae7df1471d3c7b4c97c420f6d03aad80d561b843
bigcode/the-stack
train
5a85927a9ae094b8cbb12da2
train
function
def setup_platform(hass, config, add_devices, discovery_info=None): """Find and add Z-Wave lights.""" if discovery_info is None or zwave.NETWORK is None: return node = zwave.NETWORK.nodes[discovery_info[zwave.const.ATTR_NODE_ID]] value = node.values[discovery_info[zwave.const.ATTR_VALUE_ID]] ...
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Find and add Z-Wave lights.""" if discovery_info is None or zwave.NETWORK is None: return node = zwave.NETWORK.nodes[discovery_info[zwave.const.ATTR_NODE_ID]] value = node.values[discovery_info[zwave.const.ATTR_VALUE_ID]] customize = hass.data['zwave_customize'] name = '{}.{}'.format(...
ARM_HASS = (HASS_COLOR_MAX - HASS_COLOR_MIN) / 3 * 2 + HASS_COLOR_MIN TEMP_COLD_HASS = (HASS_COLOR_MAX - HASS_COLOR_MIN) / 3 + HASS_COLOR_MIN SUPPORT_ZWAVE = SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_RGB_COLOR def setup_platform(hass, config, add_devices, discovery_info=None):
87
87
291
15
71
mbs-technologie/home-assistant
homeassistant/components/light/zwave.py
Python
setup_platform
setup_platform
48
74
48
48
7020549c9ceea16dc8f58132dd2c3123e814b79f
bigcode/the-stack
train
9df6478e4846975cc1fe5c82
train
class
class SNMPCollector(diamond.collector.Collector): def __init__(self, config, handlers): """ Create a new instance of the SNMPCollector class """ # Initialize base Class diamond.collector.Collector.__init__(self, config, handlers) # Initialize SNMP Command Generator ...
class SNMPCollector(diamond.collector.Collector):
def __init__(self, config, handlers): """ Create a new instance of the SNMPCollector class """ # Initialize base Class diamond.collector.Collector.__init__(self, config, handlers) # Initialize SNMP Command Generator if pysnmp is not None: self.snm...
# coding=utf-8 """ SNMPCollector is a special collector for collecting data from using SNMP #### Dependencies * pysnmp """ import socket try: import pysnmp.entity.rfc3413.oneliner.cmdgen as cmdgen import pysnmp.debug pysnmp # workaround for pyflakes issue #13 except ImportError: pysnmp = None i...
103
256
905
11
91
dreamhost/Diamond
src/collectors/snmp/snmp.py
Python
SNMPCollector
SNMPCollector
24
153
24
25
d16384ab82b67afed943d5948899bd3f58657bb5
bigcode/the-stack
train
1b5ccd7c3aaa3b21e1670576
train
function
async def initialize_refresh_token_file(): if os.path.isfile(REFRESH_TOKEN_FILENAME): return refresh_token = input("Initial refresh token value: ") async with aiofiles.open(REFRESH_TOKEN_FILENAME, "w") as fp: await fp.write(refresh_token)
async def initialize_refresh_token_file():
if os.path.isfile(REFRESH_TOKEN_FILENAME): return refresh_token = input("Initial refresh token value: ") async with aiofiles.open(REFRESH_TOKEN_FILENAME, "w") as fp: await fp.write(refresh_token)
=<REDDIT_CLIENT_SECRET> python3 use_file_token_manager.py """ import asyncio import os import sys import aiofiles import asyncpraw from asyncpraw.util.token_manager import FileTokenManager REFRESH_TOKEN_FILENAME = "refresh_token.txt" async def initialize_refresh_token_file():
64
64
58
7
57
Lordshinjo/asyncpraw
docs/examples/use_file_token_manager.py
Python
initialize_refresh_token_file
initialize_refresh_token_file
31
37
31
31
cb2a61da4e3d9f7dd5075c2eddd372bcbea0b75d
bigcode/the-stack
train
e12b3c1938af45a50819abb9
train
function
async def main(): if "praw_client_id" not in os.environ: sys.stderr.write("Environment variable ``praw_client_id`` must be defined\n") return 1 if "praw_client_secret" not in os.environ: sys.stderr.write( "Environment variable ``praw_client_secret`` must be defined\n" ...
async def main():
if "praw_client_id" not in os.environ: sys.stderr.write("Environment variable ``praw_client_id`` must be defined\n") return 1 if "praw_client_secret" not in os.environ: sys.stderr.write( "Environment variable ``praw_client_secret`` must be defined\n" ) return ...
refresh_token.txt" async def initialize_refresh_token_file(): if os.path.isfile(REFRESH_TOKEN_FILENAME): return refresh_token = input("Initial refresh token value: ") async with aiofiles.open(REFRESH_TOKEN_FILENAME, "w") as fp: await fp.write(refresh_token) async def main():
66
66
221
4
62
Lordshinjo/asyncpraw
docs/examples/use_file_token_manager.py
Python
main
main
40
66
40
40
e44451e23c70ba69df6bc75834ef7da129de27d3
bigcode/the-stack
train
c845aaa1b38c0f8be5f30c4c
train
class
class MeshRegNet(nn.Module): def __init__( self, fc_dropout=0, resnet_version=18, criterion2d="l2", mano_neurons=[512, 512], mano_comps=15, mano_use_shape=False, mano_lambda_pose_reg=0, mano_use_pca=True, mano_center_idx=9, mano...
class MeshRegNet(nn.Module):
def __init__( self, fc_dropout=0, resnet_version=18, criterion2d="l2", mano_neurons=[512, 512], mano_comps=15, mano_use_shape=False, mano_lambda_pose_reg=0, mano_use_pca=True, mano_center_idx=9, mano_root="assets/mano", ...
regressor.shape[1]) tip_reg[0, 745] = 1 tip_reg[1, 317] = 1 tip_reg[2, 444] = 1 tip_reg[3, 556] = 1 tip_reg[4, 673] = 1 reordered_reg = torch.cat([regressor, tip_reg])[ [0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, ...
256
256
3,676
7
248
wangyida/hand-object
meshreg/models/meshregnet.py
Python
MeshRegNet
MeshRegNet
54
384
54
54
685b993f8d4661f801f8cd666ab2e367137c50e6
bigcode/the-stack
train
f8cd7309820361b3e088ded2
train
function
def normalize_pixel_out(data, inp_res=256): centered = data - inp_res scaled = centered / inp_res / 2 return scaled.float()
def normalize_pixel_out(data, inp_res=256):
centered = data - inp_res scaled = centered / inp_res / 2 return scaled.float()
anch import AbsoluteBranch from meshreg.models.manobranch import ManoBranch, ManoLoss from meshreg.models.objbranch import ObjBranch from meshreg.models import project from meshreg.datasets.queries import TransQueries, BaseQueries, one_query_in def normalize_pixel_out(data, inp_res=256):
64
64
35
11
52
wangyida/hand-object
meshreg/models/meshregnet.py
Python
normalize_pixel_out
normalize_pixel_out
17
20
17
17
912121170c8ae9597afb3d8a7e184b32a7dc3416
bigcode/the-stack
train
00da5af3471ed49f9c6445ce
train
class
class ManoAdaptor(torch.nn.Module): def __init__(self, mano_layer, load_path=None): super().__init__() self.adaptor = torch.nn.Linear(778, 21, bias=False) if load_path is not None: with open(load_path, "rb") as p_f: exp_data = pickle.load(p_f) weig...
class ManoAdaptor(torch.nn.Module):
def __init__(self, mano_layer, load_path=None): super().__init__() self.adaptor = torch.nn.Linear(778, 21, bias=False) if load_path is not None: with open(load_path, "rb") as p_f: exp_data = pickle.load(p_f) weights = exp_data["adaptor"] ...
_freeze from meshreg.models import resnet from meshreg.models.absolutebranch import AbsoluteBranch from meshreg.models.manobranch import ManoBranch, ManoLoss from meshreg.models.objbranch import ObjBranch from meshreg.models import project from meshreg.datasets.queries import TransQueries, BaseQueries, one_query_in ...
114
114
380
7
107
wangyida/hand-object
meshreg/models/meshregnet.py
Python
ManoAdaptor
ManoAdaptor
23
51
23
23
741e046edaa8368c6047d15c12eb3a547acdc251
bigcode/the-stack
train
264b3e0a119f01e88bb7b41e
train
function
def main(args): df = pandas.read_csv(args.data) # df = df[df.target.isin(list(set(df.target))[:5])] df = df.set_index("SMILES") output = pandas.DataFrame(index=list(set(df.target)), columns=["Cochrans p-val", "Kappa(Chemdist)", ...
def main(args):
df = pandas.read_csv(args.data) # df = df[df.target.isin(list(set(df.target))[:5])] df = df.set_index("SMILES") output = pandas.DataFrame(index=list(set(df.target)), columns=["Cochrans p-val", "Kappa(Chemdist)", ...
(y_test, y_ecfp0, y_ecfp4, y_cdist) ps.append(p) aucs_ecfp0.append(auc_ecfp0) aucs_ecfp4.append(auc_ecfp4) aucs_cd.append(auc_cd) return numpy.mean(ps), numpy.mean(aucs_cd), numpy.mean(aucs_ecfp4), numpy.mean(aucs_ecfp0) def main(args):
92
92
307
4
88
DCoupry/ChemDist_paper
Code/benchmark_p.py
Python
main
main
78
103
78
78
a780acb6805be18e65c24269524902100ab259b8
bigcode/the-stack
train
78065229f488111bcd7bddbe
train
function
def get_score(data): ps = [] aucs_ecfp0 = [] aucs_ecfp4 = [] aucs_cd = [] X_ecfp4 = numpy.stack(data.index.map(lambda s: GetMorganFingerprintAsBitVect(MolFromSmiles(s), 2, nBits=1024))) X_ecfp0 = numpy.stack(data.index.map(lambda s: GetMorganFingerprintAsBitVect(MolFromSmiles(s), 0, nBits=1024))...
def get_score(data):
ps = [] aucs_ecfp0 = [] aucs_ecfp4 = [] aucs_cd = [] X_ecfp4 = numpy.stack(data.index.map(lambda s: GetMorganFingerprintAsBitVect(MolFromSmiles(s), 2, nBits=1024))) X_ecfp0 = numpy.stack(data.index.map(lambda s: GetMorganFingerprintAsBitVect(MolFromSmiles(s), 0, nBits=1024))) X_cdist = numpy...
from tqdm.auto import tqdm from chemdist import DistanceNetworkLigthning from dgllife.utils import smiles_to_bigraph, CanonicalAtomFeaturizer, CanonicalBondFeaturizer from mlxtend.evaluate import mcnemar, mcnemar_table, cochrans_q MODEL = DistanceNetworkLigthning.load_from_checkpoint("model_ablation.pt")._net NF = Can...
180
180
600
5
175
DCoupry/ChemDist_paper
Code/benchmark_p.py
Python
get_score
get_score
43
75
43
43
c8a48713e05a5d95ab9071d664a5d1b380d27320
bigcode/the-stack
train
02110137ad057751595c7eb5
train
function
def chemdist_func(s): g = smiles_to_bigraph(smiles=s, node_featurizer=NF, edge_featurizer=BF) nfeats = g.ndata.pop('h') efeats = g.edata.pop('e') return MODEL(g, nfeats, efeats).cpu().detach().numpy().ravel()
def chemdist_func(s):
g = smiles_to_bigraph(smiles=s, node_featurizer=NF, edge_featurizer=BF) nfeats = g.ndata.pop('h') efeats = g.edata.pop('e') return MODEL(g, nfeats, efeats).cpu().detach().numpy().ravel()
from mlxtend.evaluate import mcnemar, mcnemar_table, cochrans_q MODEL = DistanceNetworkLigthning.load_from_checkpoint("model_ablation.pt")._net NF = CanonicalAtomFeaturizer() BF = CanonicalBondFeaturizer() def chemdist_func(s):
64
64
76
7
57
DCoupry/ChemDist_paper
Code/benchmark_p.py
Python
chemdist_func
chemdist_func
36
40
36
36
64f1b041cc412a8443349cd208bb0f47ecb24362
bigcode/the-stack
train
0d25ccb1dbec729ce35c9a91
train
function
def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+"
def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+"
= run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces):
64
64
43
7
56
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
plus_or_dot
plus_or_dot
308
312
308
308
e66ee6ec1a8d4f40272fa193cbd32446fc176795
bigcode/the-stack
train
8c024c68d6973f35cff9e1c1
train
function
def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exce...
def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0....
rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces):
64
64
104
9
54
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
render_pep440_pre
render_pep440_pre
340
353
340
340
c6c4ff64dd83fe1cefa9d0205d5bfcf382058796
bigcode/the-stack
train
106453bcea4339d1dc94ac51
train
class
class VersioneerConfig: """Container for Versioneer configuration parameters."""
class VersioneerConfig:
"""Container for Versioneer configuration parameters."""
(). git_refnames = "$Format:%d$" git_full = "$Format:%H$" git_date = "$Format:%ci$" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig:
64
64
14
5
58
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
VersioneerConfig
VersioneerConfig
33
34
33
33
f68b42475e4e512eb76a6e114aeca1e46ffc7801
bigcode/the-stack
train
19ccfd748b7513e15b32c038
train
function
def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an ap...
def versions_from_parentdir(parentdir_prefix, root, verbose):
"""Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] ...
!= 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose):
64
64
204
13
50
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
versions_from_parentdir
versions_from_parentdir
107
129
107
107
43e05a663fbea3783a2c67b82fd35bad9a9ef28f
bigcode/the-stack
train
20f6c49d9c2886a633e19cee
train
function
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on w...
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):
"""Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, ...
the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, ...
87
87
293
22
64
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
run_command
run_command
70
104
70
71
0bba8431e29e33877c8cce5511404052c7219fc2
bigcode/the-stack
train
d51848ce12e0a73022a05de5
train
class
class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario."""
class NotThisMethod(Exception):
"""Exception raised if a method is not valid for the current scenario."""
() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.versionfile_source = "kubo_group_study/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception):
64
64
21
6
57
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
NotThisMethod
NotThisMethod
51
52
51
51
e079db8a1cef60e672393bd70abd3dc5c2787e10
bigcode/the-stack
train
e03ef803a6e31e815e9550fd
train
function
def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which #...
def get_versions():
"""Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only us...
= render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": p...
108
109
366
4
104
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
get_versions
get_versions
477
520
477
477
b78ae74a11925f2c0fbd22dfabbdc7d52b417187
bigcode/the-stack
train
a8123e4d52f3fd2d8a4f6cae
train
function
@register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a r...
@register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs):
"""Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} ...
os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfi...
77
77
259
20
57
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
git_get_keywords
git_get_keywords
132
158
132
133
04b5a6d19ca3d22d0e7e9a65df90187d2ebfde59
bigcode/the-stack
train
498a58e3fac7e0294f109742
train
function
def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] ...
def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["di...
pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces):
64
64
133
9
54
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
render_git_describe_long
render_git_describe_long
425
442
425
425
5e4bff692adb192739763d5a533f5bcc0732f3f4
bigcode/the-stack
train
07d3138c2cc76576b73dbfca
train
function
@register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%...
@register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands...
we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: ...
214
214
714
24
189
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
git_versions_from_keywords
git_versions_from_keywords
161
213
161
162
258bec4042f67b04a452ff5b0dab5edb6266331e
bigcode/the-stack
train
f248d923f6e8f8a16b11c8f2
train
function
@register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been ...
@register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
"""Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if ...
)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag...
256
256
875
34
222
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
git_pieces_from_vcs
git_pieces_from_vcs
216
305
216
217
7e492a17adf1befe9c93b7056873cc07a673d681
bigcode/the-stack
train
0fc74394dd10b90f54ca8c9c
train
function
def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keyword...
def get_keywords():
"""Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refname...
the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords():
64
64
131
4
59
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
get_keywords
get_keywords
20
30
20
20
469718b2e0436724ddd20fba9e7cbdc15bc48baa
bigcode/the-stack
train
d550207ba081b3baaa3d2785
train
function
def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[...
def render_pep440_post(pieces):
"""TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["cl...
"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces):
64
64
216
9
54
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
render_pep440_post
render_pep440_post
356
380
356
356
9e2eecbd5bfd1b01f575f39434f71060139bf1cb
bigcode/the-stack
train
b0bde1b6f7f43faf8f24e302
train
function
def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} ...
def render(pieces, style):
"""Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "d...
' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, s...
78
78
260
7
70
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
render
render
445
474
445
445
930892a99868150d540c69d8477df76e6496af2a
bigcode/the-stack
train
7353a040ebd430d5a20357be
train
function
def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered +=...
def render_git_describe(pieces):
"""TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"],...
pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces):
64
64
129
8
55
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
render_git_describe
render_git_describe
405
422
405
405
223b07609e73d4d8f3a7e7f56bac470548fcc640
bigcode/the-stack
train
8901aad529146f6b7a3ce69d
train
function
def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return ...
def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate
_study/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator
63
64
87
14
49
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
register_vcs_handler
register_vcs_handler
59
67
59
59
ed9726848b45d214b93361a4ec9112702345e96c
bigcode/the-stack
train
a9cd0578e3dc90bc965aa493
train
function
def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHE...
def render_pep440(pieces):
"""Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pi...
).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces):
63
64
213
8
55
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
render_pep440
render_pep440
315
337
315
315
68d7ccd160ed451a6dc4fdbd8fe09be136102e6e
bigcode/the-stack
train
e06bbc770c2118c1dc2881cf
train
function
def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.versio...
def get_config():
"""Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.versionfile_source = "ku...
_full = "$Format:%H$" git_date = "$Format:%ci$" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config():
63
64
104
4
59
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
get_config
get_config
37
48
37
37
4289d1db026ed167e596f9d2a1d4379a9d520eab
bigcode/the-stack
train
b45c7a7ab2e742617f815ccc
train
function
def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pie...
def render_pep440_old(pieces):
"""TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if ...
pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces):
64
64
145
9
54
HanboHong/kubo_group_study
kubo_group_study/_version.py
Python
render_pep440_old
render_pep440_old
383
402
383
383
a62a9f8f75c0be14c98316b48d886e021a1c5f2b
bigcode/the-stack
train
3f4249ef87b8e9d5cac89555
train
class
class PostgresFileWriter(PostgresWriter): """Class used to ouput the PostgreSQL compatable DDL and/or data to the specified output :py:obj:`file` from a MySQL server. :Parameters: - `output_file`: the output :py:obj:`file` to send the DDL and/or data - `verbose`: whether or not to log progr...
class PostgresFileWriter(PostgresWriter):
"""Class used to ouput the PostgreSQL compatable DDL and/or data to the specified output :py:obj:`file` from a MySQL server. :Parameters: - `output_file`: the output :py:obj:`file` to send the DDL and/or data - `verbose`: whether or not to log progress to :py:obj:`stdout` """ verbo...
from __future__ import absolute_import import time from .postgres_writer import PostgresWriter from . import print_row_progress, status_logger class PostgresFileWriter(PostgresWriter):
39
256
1,341
9
29
senique/py-mysql2pgsql
mysql2pgsql/lib/postgres_file_writer.py
Python
PostgresFileWriter
PostgresFileWriter
11
173
11
11
6e88fa23b5ecfb025164482bcfa8beabcaa9fdf6
bigcode/the-stack
train
104fd70441220aab735fe51d
train
class
class PathAttributeNextHop(BGPPathAttribute): def __init__(self, payload): BGPPathAttribute.__init__(self, payload) self.type = BGPStatics.UPDATE_ATTRIBUTE_NEXT_HOP # Path attribute specific variable self.next_hop = None self.__parse() def __parse(self): try: ...
class PathAttributeNextHop(BGPPathAttribute):
def __init__(self, payload): BGPPathAttribute.__init__(self, payload) self.type = BGPStatics.UPDATE_ATTRIBUTE_NEXT_HOP # Path attribute specific variable self.next_hop = None self.__parse() def __parse(self): try: self.parsed = True self...
from pbgpp.BGP.Statics import BGPStatics from pbgpp.BGP.Translation import BGPTranslation from pbgpp.BGP.Update.PathAttribute import BGPPathAttribute from pbgpp.BGP.Update.Route import BGPRoute class PathAttributeNextHop(BGPPathAttribute):
65
65
217
10
54
antoine-blin/pbgp-parser
pbgpp/BGP/Update/PathAttributes/NextHop.py
Python
PathAttributeNextHop
PathAttributeNextHop
28
61
28
28
0d02f26b4083c41b137940c44653ff264bf6d186
bigcode/the-stack
train
7f435fb8926634ae3b88d073
train
class
class KubernetesSysConfigPolicyList(ModelComposed): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is...
class KubernetesSysConfigPolicyList(ModelComposed):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a c...
# noqa: E501 The version of the OpenAPI document: 1.0.9-4950 Contact: intersight@cisco.com Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from intersight.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, Model...
256
256
1,727
10
245
CiscoDevNet/intersight-python
intersight/model/kubernetes_sys_config_policy_list.py
Python
KubernetesSysConfigPolicyList
KubernetesSysConfigPolicyList
39
238
39
39
cef1e35019b58e902ce170835bb9680a767773b5
bigcode/the-stack
train
d25ae5bdc723c1be38f760a3
train
function
def lazy_import(): from intersight.model.kubernetes_sys_config_policy import KubernetesSysConfigPolicy from intersight.model.kubernetes_sys_config_policy_list_all_of import KubernetesSysConfigPolicyListAllOf from intersight.model.mo_base_response import MoBaseResponse globals()['KubernetesSysConfigPolic...
def lazy_import():
from intersight.model.kubernetes_sys_config_policy import KubernetesSysConfigPolicy from intersight.model.kubernetes_sys_config_policy_list_all_of import KubernetesSysConfigPolicyListAllOf from intersight.model.mo_base_response import MoBaseResponse globals()['KubernetesSysConfigPolicy'] = KubernetesSys...
ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, ) def lazy_import():
64
64
106
4
60
CiscoDevNet/intersight-python
intersight/model/kubernetes_sys_config_policy_list.py
Python
lazy_import
lazy_import
30
36
30
30
86f7736962751f1b9138369717fe80d8d90152c4
bigcode/the-stack
train
d5be6e55b71fec0158125a78
train
class
class Image(): def list_images(self,user): image_list = self.list_all_image(user) global total_image_list total_image_list = [] return image_list def list_all_image(self,user,parameter=None): global total_image_list if parameter is None: image_list = ...
class Image():
def list_images(self,user): image_list = self.list_all_image(user) global total_image_list total_image_list = [] return image_list def list_all_image(self,user,parameter=None): global total_image_list if parameter is None: image_list = glance_api.list...
# coding=utf-8 __author__ = 'aaron' import appName.api.glance as glance_api global total_image_list total_image_list = [] class Image():
37
150
500
3
34
luqitao/WebPOS
userPortal/appName/view/image_view.py
Python
Image
Image
9
78
9
9
aad633cd0119edefc6ceb1a6624aba7a7ddcf0b1
bigcode/the-stack
train
6fe1c159e0eddf775f25f077
train
class
class Session(object): def __init__(self, _id=-1, server_ip='', server_port=-1, pid=-1, active=False, account_id=-1, key_id=-1, local_port=-1, server_session_token='', restart_command='', http_forward=False, http_forward_address='', open_port_for_ip_link='', app_management_port=-1,...
class Session(object):
def __init__(self, _id=-1, server_ip='', server_port=-1, pid=-1, active=False, account_id=-1, key_id=-1, local_port=-1, server_session_token='', restart_command='', http_forward=False, http_forward_address='', open_port_for_ip_link='', app_management_port=-1, forwa...
import pickle class Session(object):
7
256
938
4
2
Deshdeepak1/openport
openport/common/session.py
Python
Session
Session
4
114
4
4
747ef3bbd441a35ed56a1d7057f6d85d35dd6e4f
bigcode/the-stack
train
39934677c67988557c0f3db2
train
class
class SSLMiddleware(wsgi.Middleware): """A middleware that replaces the request wsgi.url_scheme environment variable with the value of HTTP header configured in secure_proxy_ssl_header if exists in the incoming request. This is useful if the server is behind a SSL termination proxy. """ @classm...
class SSLMiddleware(wsgi.Middleware):
"""A middleware that replaces the request wsgi.url_scheme environment variable with the value of HTTP header configured in secure_proxy_ssl_header if exists in the incoming request. This is useful if the server is behind a SSL termination proxy. """ @classmethod def factory(cls, global_conf...
Proto', help="The HTTP Header that will be used to determine which " "the original request protocol scheme was, even if it was " "removed by an SSL terminator proxy.") ] cfg.CONF.register_opts(ssl_middleware_opts) LOG = logging.getLogger(__name__) class SSLMiddlewa...
68
68
227
8
60
gokrokvertskhov/murano
murano/api/middleware/ssl.py
Python
SSLMiddleware
SSLMiddleware
29
52
29
29
fec0f5897281844b0c4611bcea4f8347fb099450
bigcode/the-stack
train
a6e2c235d48dc41fce2bd424
train
function
@register_b.route('/register', methods=['POST', 'GET']) def register(): if auth.loggedin(): return redirect('/') if request.method == 'POST': q_username = request.form['username'] q_password = request.form['password'] user = auth.User.query.filter_by(username=q_username).f...
@register_b.route('/register', methods=['POST', 'GET']) def register():
if auth.loggedin(): return redirect('/') if request.method == 'POST': q_username = request.form['username'] q_password = request.form['password'] user = auth.User.query.filter_by(username=q_username).first() if user is None: if len(q_password) < 8: ...
from flask import Blueprint, render_template, redirect, request, session import jwt import routes.auth as auth register_b = Blueprint('register', __name__) @register_b.route('/register', methods=['POST', 'GET']) def register():
50
64
183
17
33
Hazeral/LoginSystem
routes/register.py
Python
register
register
8
27
8
9
10c5804bdd79f325650e4a4e299f2bbcb9628c5b
bigcode/the-stack
train
89cab792a4cb76a2ef1ef4a6
train
function
def _derive_axis_ratio(path_ts): if not (MAJOR_AXIS_PATH in path_ts and MINOR_AXIS_PATH in path_ts): return major = path_ts[MAJOR_AXIS_PATH] minor = path_ts[MINOR_AXIS_PATH] ratio = [ [ major_val / minor_val for major_val, minor_val in zip(major_list, minor_list) ...
def _derive_axis_ratio(path_ts):
if not (MAJOR_AXIS_PATH in path_ts and MINOR_AXIS_PATH in path_ts): return major = path_ts[MAJOR_AXIS_PATH] minor = path_ts[MINOR_AXIS_PATH] ratio = [ [ major_val / minor_val for major_val, minor_val in zip(major_list, minor_list) ] for major_list,...
[ c / a for c, a in zip(circumference_list, area_list) ] for circumference_list, area_list in zip(circumference, area) ] path_ts[CIRCUMFERENCE_AREA_RATIO_PATH] = ratio def _derive_axis_ratio(path_ts):
64
64
112
8
55
vivarium-collective/vivarium-cell
vivarium_cell/plots/colonies.py
Python
_derive_axis_ratio
_derive_axis_ratio
59
71
59
59
92cbdfe66dc1e6ceed8753619b9bb1990fc232ca
bigcode/the-stack
train
459db2120c2c28e7577d93fb
train
function
def plot_colony_metrics( path_ts, title_size=16, tick_label_size=12, max_cols=5 ): '''Plot colony metrics over time. Metric mean is plotted with SEM error bands. Arguments: path_ts (dict): Path timeseries of the data to plot. Each item in the dictionary should have as its key the p...
def plot_colony_metrics( path_ts, title_size=16, tick_label_size=12, max_cols=5 ):
'''Plot colony metrics over time. Metric mean is plotted with SEM error bands. Arguments: path_ts (dict): Path timeseries of the data to plot. Each item in the dictionary should have as its key the path and as its value a list of values for each timepoint. Each value should...
_ts[CIRCUMFERENCE_PATH] area = path_ts[AREA_PATH] ratio = [ [ c / a for c, a in zip(circumference_list, area_list) ] for circumference_list, area_list in zip(circumference, area) ] path_ts[CIRCUMFERENCE_AREA_RATIO_PATH] = ratio def _derive_axis_ratio(path...
256
256
856
27
229
vivarium-collective/vivarium-cell
vivarium_cell/plots/colonies.py
Python
plot_colony_metrics
plot_colony_metrics
81
177
81
83
a2e19f6e76ceee2bca92853b93d672611003ae4d
bigcode/the-stack
train
c733f11ef3f3830909f25640
train
function
def plot_metric_across_experiments( path_ts_dict, path, title=None, xlabel='time (s)', ylabel=None, title_size=16, tick_label_size=12, ): '''Overlay plots of a single metric from different experiments. Parameters: path_ts_dict (dict): Map from the string to use as the label for the ...
def plot_metric_across_experiments( path_ts_dict, path, title=None, xlabel='time (s)', ylabel=None, title_size=16, tick_label_size=12, ):
'''Overlay plots of a single metric from different experiments. Parameters: path_ts_dict (dict): Map from the string to use as the label for the experiment in the legend to that experiment's path timeseries. path (tuple): Path to plot. Should be a key in each value of ...
len(array) > 1 else 0) plot_times.append(times[i_time]) x = np.array(plot_times) y = np.array(means) yerr = np.array(sems) yerr[np.isnan(yerr)] = 0 ax.plot(x, y) ax.fill_between(x, y - yerr, y + yerr, al...
129
129
432
41
87
vivarium-collective/vivarium-cell
vivarium_cell/plots/colonies.py
Python
plot_metric_across_experiments
plot_metric_across_experiments
180
231
180
183
fc4a0fbe35aa65905f801a7ea3691247f64cc739
bigcode/the-stack
train
3e6fa62682c38a6060acbd24
train
function
def _derive_circumference_area_ratio(path_ts): if not (CIRCUMFERENCE_PATH in path_ts and AREA_PATH in path_ts): return circumference = path_ts[CIRCUMFERENCE_PATH] area = path_ts[AREA_PATH] ratio = [ [ c / a for c, a in zip(circumference_list, area_list) ] ...
def _derive_circumference_area_ratio(path_ts):
if not (CIRCUMFERENCE_PATH in path_ts and AREA_PATH in path_ts): return circumference = path_ts[CIRCUMFERENCE_PATH] area = path_ts[AREA_PATH] ratio = [ [ c / a for c, a in zip(circumference_list, area_list) ] for circumference_list, area_list in zi...
IES_PATH = 'Number of Colonies' #: Key to which the ratio of major axis to minor axis is written in the #: path timeseries AXIS_RATIO_PATH = '(Major Axis) / (Minor Axis)' # METRIC DERIVERS def _derive_circumference_area_ratio(path_ts):
64
64
115
12
51
vivarium-collective/vivarium-cell
vivarium_cell/plots/colonies.py
Python
_derive_circumference_area_ratio
_derive_circumference_area_ratio
45
57
45
45
d8d140303ea5c8b4f02a3cd411370f97319b6751
bigcode/the-stack
train