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
d504b23a4be488baad610c23
train
function
def install_packages(ctx, pkgs, config): """ Installs packages on each remote in ctx. :param ctx: the argparse.Namespace object :param pkgs: list of packages names to install :param config: the config dict """ install_pkgs = { "deb": deb._update_package_list_and_install, "rp...
def install_packages(ctx, pkgs, config):
""" Installs packages on each remote in ctx. :param ctx: the argparse.Namespace object :param pkgs: list of packages names to install :param config: the config dict """ install_pkgs = { "deb": deb._update_package_list_and_install, "rpm": rpm._update_package_list_and_install,...
log.info(msg) else: raise RuntimeError( "{pkg} version {ver} was not installed, found {installed}.".format( ver=version, installed=installed_ver, pkg=pkg_to_check ) ) def install_packages(ctx, pkgs, config):
64
64
172
10
54
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
install_packages
install_packages
66
87
66
66
bea76c0b2945a2d40dc4ba5589fdf8bb93986960
bigcode/the-stack
train
e799d2f1b4792bcf5e9621e4
train
function
def upgrade_remote_to_config(ctx, config): assert config is None or isinstance(config, dict), \ "install.upgrade only supports a dictionary for configuration" project = config.get('project', 'ceph') # use 'install' overrides here, in case the upgrade target is left # unspecified/implicit. ...
def upgrade_remote_to_config(ctx, config):
assert config is None or isinstance(config, dict), \ "install.upgrade only supports a dictionary for configuration" project = config.get('project', 'ceph') # use 'install' overrides here, in case the upgrade target is left # unspecified/implicit. install_overrides = ctx.config.get( ...
entry in dev_table: ceph_dev_parm = node[entry] if entry == 'release': ceph_rel_parm = node[entry] params = [] if ceph_dev_parm: params += ['--dev', ceph_dev_parm] if ceph_rel_parm: params += ['--release', ceph_rel_parm] params.append(remote.name) sub...
125
126
421
9
116
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
upgrade_remote_to_config
upgrade_remote_to_config
254
303
254
254
423793705625d8a5082cbc142b0fae8def888e94
bigcode/the-stack
train
8dcd697a0917d29567b0cfb1
train
function
@contextlib.contextmanager def ceph_deploy_upgrade(ctx, config): upgrade_common(ctx, config, upgrade_with_ceph_deploy) yield
@contextlib.contextmanager def ceph_deploy_upgrade(ctx, config):
upgrade_common(ctx, config, upgrade_with_ceph_deploy) yield
# look the same. # @contextlib.contextmanager def upgrade(ctx, config): upgrade_common(ctx, config, upgrade_old_style) yield upgrade.__doc__ = docstring_for_upgrade.format(cmd_parameter='upgrade') @contextlib.contextmanager def ceph_deploy_upgrade(ctx, config):
64
64
33
16
48
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
ceph_deploy_upgrade
ceph_deploy_upgrade
407
410
407
408
1f97c01517ca574bca6cdb6af5bb5387f24e5e6b
bigcode/the-stack
train
45b60a089e762bf47f2fcc32
train
function
def remove_sources(ctx, config): """ Removes repo source files from each remote in ctx. :param ctx: the argparse.Namespace object :param config: the config dict """ remove_sources_pkgs = { 'deb': deb._remove_sources_list, 'rpm': rpm._remove_sources_list, } with parallel(...
def remove_sources(ctx, config):
""" Removes repo source files from each remote in ctx. :param ctx: the argparse.Namespace object :param config: the config dict """ remove_sources_pkgs = { 'deb': deb._remove_sources_list, 'rpm': rpm._remove_sources_list, } with parallel() as p: project = config....
._remove, } with parallel() as p: for remote in ctx.cluster.remotes.keys(): system_type = teuthology.get_system_type(remote) p.spawn(remove_pkgs[ system_type], ctx, config, remote, pkgs[system_type]) def remove_sources(ctx, config):
64
64
143
7
57
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
remove_sources
remove_sources
109
126
109
109
b1f08eaa9f063990e2e216a20aa174c11482c1ee
bigcode/the-stack
train
14d29dace952b504272b113a
train
function
def get_package_list(ctx, config): debug = config.get('debuginfo', False) project = config.get('project', 'ceph') yaml_path = None # Look for <suite_path>/packages/packages.yaml if hasattr(ctx, 'config') and 'suite_path' in ctx.config: suite_packages_path = os.path.join( ctx.conf...
def get_package_list(ctx, config):
debug = config.get('debuginfo', False) project = config.get('project', 'ceph') yaml_path = None # Look for <suite_path>/packages/packages.yaml if hasattr(ctx, 'config') and 'suite_path' in ctx.config: suite_packages_path = os.path.join( ctx.config['suite_path'], 'pack...
, config): """ Removes repo source files from each remote in ctx. :param ctx: the argparse.Namespace object :param config: the config dict """ remove_sources_pkgs = { 'deb': deb._remove_sources_list, 'rpm': rpm._remove_sources_list, } with parallel() as p: projec...
147
147
491
8
139
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
get_package_list
get_package_list
129
175
129
129
48f495e7c696a319ade4baa27af64e4dad846881
bigcode/the-stack
train
eb234d85859fee7780a3dea7
train
function
def upgrade_old_style(ctx, node, remote, pkgs, system_type): """ Handle the upgrade using methods in use prior to ceph-deploy. """ if system_type == 'deb': deb._upgrade_packages(ctx, node, remote, pkgs) elif system_type == 'rpm': rpm._upgrade_packages(ctx, node, remote, pkgs)
def upgrade_old_style(ctx, node, remote, pkgs, system_type):
""" Handle the upgrade using methods in use prior to ceph-deploy. """ if system_type == 'deb': deb._upgrade_packages(ctx, node, remote, pkgs) elif system_type == 'rpm': rpm._upgrade_packages(ctx, node, remote, pkgs)
dict(deb=debs, rpm=rpms) install_packages(ctx, package_list, config) try: yield finally: remove_packages(ctx, config, package_list) remove_sources(ctx, config) def upgrade_old_style(ctx, node, remote, pkgs, system_type):
64
64
79
16
48
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
upgrade_old_style
upgrade_old_style
222
229
222
222
21c9759b59f079b2f9390c5c4956dda0b6ada808
bigcode/the-stack
train
319bc9a42479ac4cbab79d77
train
function
def verify_package_version(ctx, config, remote): """ Ensures that the version of package installed is what was asked for in the config. For most cases this is for ceph, but we also install samba for example. """ # Do not verify the version if the ceph-deploy task is being used to # inst...
def verify_package_version(ctx, config, remote):
""" Ensures that the version of package installed is what was asked for in the config. For most cases this is for ceph, but we also install samba for example. """ # Do not verify the version if the ceph-deploy task is being used to # install ceph. Verifying the ceph installed by ceph-de...
utils.version import LooseVersion from teuthology.task.install.util import ( _get_builder_project, get_flavor, ship_utilities, ) from teuthology.task.install import rpm, deb, redhat log = logging.getLogger(__name__) def get_upgrade_version(ctx, config, remote): builder = _get_builder_project(ctx, remote, con...
95
95
319
10
84
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
verify_package_version
verify_package_version
27
63
27
27
a5774cf0073e26a6ccc170c6767f18df81eca869
bigcode/the-stack
train
1fe277b294b589984bf37c54
train
function
@contextlib.contextmanager def upgrade(ctx, config): upgrade_common(ctx, config, upgrade_old_style) yield
@contextlib.contextmanager def upgrade(ctx, config):
upgrade_common(ctx, config, upgrade_old_style) yield
config: the config dict """ # # __doc__ strings for upgrade and ceph_deploy_upgrade are set from # the same string so that help(upgrade) and help(ceph_deploy_upgrade) # look the same. # @contextlib.contextmanager def upgrade(ctx, config):
63
64
26
12
51
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
upgrade
upgrade
399
402
399
400
190a72b4ce9bec6951407e0296912b0401ebed42
bigcode/the-stack
train
9f40a1d0ba52f1460a26e6b6
train
function
@contextlib.contextmanager def task(ctx, config): """ Install packages for a given project. tasks: - install: project: ceph branch: bar - install: project: samba branch: foo extra_packages: ['samba'] - install: extra_packages: deb: ['li...
@contextlib.contextmanager def task(ctx, config):
""" Install packages for a given project. tasks: - install: project: ceph branch: bar - install: project: samba branch: foo extra_packages: ['samba'] - install: extra_packages: deb: ['librados-dev', 'libradosstriper-dev'] rpm...
.{cmd_parameter}: all: (HACK: the overrides will *only* apply the sha1/branch/tag if those keys are not present in the config.) It is also possible to attempt to exclude packages from the upgrade set: tasks: - install.{cmd_parameter}: exclude_packages: ['ceph-test'...
256
256
1,398
12
244
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
task
task
416
612
416
417
4dea968852eb86893ebeea0ad70b337a3176d5fd
bigcode/the-stack
train
99eeb87e526f861f1299b093
train
function
def get_upgrade_version(ctx, config, remote): builder = _get_builder_project(ctx, remote, config) version = builder.version return version
def get_upgrade_version(ctx, config, remote):
builder = _get_builder_project(ctx, remote, config) version = builder.version return version
from distutils.version import LooseVersion from teuthology.task.install.util import ( _get_builder_project, get_flavor, ship_utilities, ) from teuthology.task.install import rpm, deb, redhat log = logging.getLogger(__name__) def get_upgrade_version(ctx, config, remote):
64
64
33
10
54
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
get_upgrade_version
get_upgrade_version
22
25
22
22
89d199b3b4066454e47286e92d1f5da701892dfc
bigcode/the-stack
train
9bdfbe25fad83d219327e990
train
function
def upgrade_with_ceph_deploy(ctx, node, remote, pkgs, sys_type): """ Upgrade using ceph-deploy """ dev_table = ['branch', 'tag', 'dev'] ceph_dev_parm = '' ceph_rel_parm = '' for entry in node.keys(): if entry in dev_table: ceph_dev_parm = node[entry] if entry == '...
def upgrade_with_ceph_deploy(ctx, node, remote, pkgs, sys_type):
""" Upgrade using ceph-deploy """ dev_table = ['branch', 'tag', 'dev'] ceph_dev_parm = '' ceph_rel_parm = '' for entry in node.keys(): if entry in dev_table: ceph_dev_parm = node[entry] if entry == 'release': ceph_rel_parm = node[entry] params = []...
""" if system_type == 'deb': deb._upgrade_packages(ctx, node, remote, pkgs) elif system_type == 'rpm': rpm._upgrade_packages(ctx, node, remote, pkgs) def upgrade_with_ceph_deploy(ctx, node, remote, pkgs, sys_type):
64
64
185
19
45
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
upgrade_with_ceph_deploy
upgrade_with_ceph_deploy
232
251
232
232
d44ddea230615874006563eb1e6eeefb7a4f2ef1
bigcode/the-stack
train
4595a074711d575d1b36686d
train
function
def _upgrade_is_downgrade(installed_version, upgrade_version): assert installed_version, "installed_version is empty" assert upgrade_version, "upgrade_version is empty" return LooseVersion(installed_version) > LooseVersion(upgrade_version)
def _upgrade_is_downgrade(installed_version, upgrade_version):
assert installed_version, "installed_version is empty" assert upgrade_version, "upgrade_version is empty" return LooseVersion(installed_version) > LooseVersion(upgrade_version)
None) teuthology.deep_merge(node, this_overrides) log.info('remote %s config %s', remote, node) node['project'] = project result[remote] = node return result def _upgrade_is_downgrade(installed_version, upgrade_version):
64
64
52
15
48
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
_upgrade_is_downgrade
_upgrade_is_downgrade
305
308
305
305
056e2087e3eb8c996564e06d16fbc0031b374e3f
bigcode/the-stack
train
a7a770227d4913b2dae05490
train
function
def upgrade_common(ctx, config, deploy_style): """ Common code for upgrading """ remotes = upgrade_remote_to_config(ctx, config) project = config.get('project', 'ceph') extra_pkgs = config.get('extra_packages', []) log.info('extra packages: {packages}'.format(packages=extra_pkgs)) for ...
def upgrade_common(ctx, config, deploy_style):
""" Common code for upgrading """ remotes = upgrade_remote_to_config(ctx, config) project = config.get('project', 'ceph') extra_pkgs = config.get('extra_packages', []) log.info('extra packages: {packages}'.format(packages=extra_pkgs)) for remote, node in remotes.items(): syste...
(node, this_overrides) log.info('remote %s config %s', remote, node) node['project'] = project result[remote] = node return result def _upgrade_is_downgrade(installed_version, upgrade_version): assert installed_version, "installed_version is empty" assert upgrade_version, "upgrade...
103
103
346
10
93
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
upgrade_common
upgrade_common
310
348
310
310
3423145a03c3306320d222b17e04426c0de11a88
bigcode/the-stack
train
77b8c84a4505cc3300ac6fcf
train
function
def remove_packages(ctx, config, pkgs): """ Removes packages from each remote in ctx. :param ctx: the argparse.Namespace object :param config: the config dict :param pkgs: list of packages names to remove """ remove_pkgs = { "deb": deb._remove, "rpm": rpm._remove, } ...
def remove_packages(ctx, config, pkgs):
""" Removes packages from each remote in ctx. :param ctx: the argparse.Namespace object :param config: the config dict :param pkgs: list of packages names to remove """ remove_pkgs = { "deb": deb._remove, "rpm": rpm._remove, } with parallel() as p: for remote...
p.spawn( install_pkgs[system_type], ctx, remote, pkgs[system_type], config) for remote in ctx.cluster.remotes.keys(): # verifies that the install worked as expected verify_package_version(ctx, config, remote) def remove_packages(ctx, config, pkgs):
64
64
131
10
54
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
remove_packages
remove_packages
90
106
90
90
ec7467a3c933d64b6b50aade156426b2c1a96970
bigcode/the-stack
train
de6431ff32af0c8ba3fb2974
train
function
@contextlib.contextmanager def install(ctx, config): """ The install task. Installs packages for a given project on all hosts in ctx. May work for projects besides ceph, but may not. Patches welcomed! :param ctx: the argparse.Namespace object :param config: the config dict """ package_list...
@contextlib.contextmanager def install(ctx, config):
""" The install task. Installs packages for a given project on all hosts in ctx. May work for projects besides ceph, but may not. Patches welcomed! :param ctx: the argparse.Namespace object :param config: the config dict """ package_list = get_package_list(ctx, config) debs = package_l...
_packages, dict): log.debug("Excluding packages: {}".format(excluded_packages)) debs = exclude(debs, excluded_packages.get('deb', [])) rpms = exclude(rpms, excluded_packages.get('rpm', [])) else: debs = exclude(debs, excluded_packages) rpms = exclude(rpms, excluded_packages) ...
123
123
413
12
110
sunilangadi2/teuthology
teuthology/task/install/__init__.py
Python
install
install
178
219
178
179
7f59cc95660b6e8bfa3423fda8277c54d3f9aa31
bigcode/the-stack
train
667ebbc547b45bd3801f644b
train
function
@register.filter @stringfilter def markdown2html(text): return md(text)
@register.filter @stringfilter def markdown2html(text):
return md(text)
from django import template from django.template.defaultfilters import stringfilter from mistune.markdown_mistune import markdown2html_mistune as md register = template.Library() @register.filter @stringfilter def markdown2html(text):
51
64
19
14
37
fenglb/mysite
homepages/templatetags/string_extras.py
Python
markdown2html
markdown2html
7
10
7
9
8bfc3e490849edab5f6198a5f2d469f79b3f282e
bigcode/the-stack
train
c1dc0cdeb1fc1ebdae32017a
train
class
class ArtworkActiveViewMixin: def get_artwork_active_form(self): return ArtworkActiveForm(prefix=self.get_prefix(), data=self.request.POST, files=self.request.FILES) def form_valid(self, form): result = super().form_valid(form) artwork_active_form = self.get_artwork_active_form() ...
class ArtworkActiveViewMixin:
def get_artwork_active_form(self): return ArtworkActiveForm(prefix=self.get_prefix(), data=self.request.POST, files=self.request.FILES) def form_valid(self, form): result = super().form_valid(form) artwork_active_form = self.get_artwork_active_form() # Set active image i...
sure the "permission_denied_message" string is returned to the user via the messages framework and also sets a reasonable default value for it. """ permission_denied_message = 'You do not have sufficient permissions to access this page' def handle_no_permission(self): messages.error(self.reque...
83
83
278
6
77
ghdpro/animesuki.com
animesuki/core/views.py
Python
ArtworkActiveViewMixin
ArtworkActiveViewMixin
27
57
27
28
083327f42060367e0fb5e6e3e619301fed039c36
bigcode/the-stack
train
c4524bfd429422c6f2ffb4ce
train
class
class ListViewQueryStringMixin: ALLOWED_ORDER = [] def build_querystring(self, page=None, order=None): q = dict() # Page if page is not None: q['page'] = page else: try: p = int(self.request.GET.get('page', 0)) if p > 0: ...
class ListViewQueryStringMixin:
ALLOWED_ORDER = [] def build_querystring(self, page=None, order=None): q = dict() # Page if page is not None: q['page'] = page else: try: p = int(self.request.GET.get('page', 0)) if p > 0: q['page'] = p ...
class CanonicalDetailViewMixin: def get(self, request, *args, **kwargs): self.object = self.get_object() # Redirect to canonical URL if request URL is not the canonical URL obj_url = self.object.get_absolute_url() if self.request.path != obj_url: return HttpResponsePe...
98
98
329
7
91
ghdpro/animesuki.com
animesuki/core/views.py
Python
ListViewQueryStringMixin
ListViewQueryStringMixin
72
112
72
72
efea88cccbb19fb44789249a77cc9a18d4ec128b
bigcode/the-stack
train
7d54de3dcb94de60cc2ee9bd
train
class
class PermissionMessageMixin(PermissionRequiredMixin): """" PermissionRequiredMixin modified to show error message to user. By default the PermissionRequiredMixin does not generate an error message, it just redirects to the login page. As that can be confusing, this simple mixin makes sure the "permiss...
class PermissionMessageMixin(PermissionRequiredMixin):
"""" PermissionRequiredMixin modified to show error message to user. By default the PermissionRequiredMixin does not generate an error message, it just redirects to the login page. As that can be confusing, this simple mixin makes sure the "permission_denied_message" string is returned to the user ...
uki Core views""" from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponsePermanentRedirect from django.utils.http import urlencode from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib import messages from .forms import ArtworkActiveForm class Permission...
64
64
135
9
54
ghdpro/animesuki.com
animesuki/core/views.py
Python
PermissionMessageMixin
PermissionMessageMixin
12
24
12
12
0a9540abcba79d95665fe1f4ac5c98fe37c27b47
bigcode/the-stack
train
b81741db285207f1fe6aaf2e
train
class
class CanonicalDetailViewMixin: def get(self, request, *args, **kwargs): self.object = self.get_object() # Redirect to canonical URL if request URL is not the canonical URL obj_url = self.object.get_absolute_url() if self.request.path != obj_url: return HttpResponsePerma...
class CanonicalDetailViewMixin:
def get(self, request, *args, **kwargs): self.object = self.get_object() # Redirect to canonical URL if request URL is not the canonical URL obj_url = self.object.get_absolute_url() if self.request.path != obj_url: return HttpResponsePermanentRedirect(obj_url) con...
.save() if self.object._cr.pk: messages.success(self.request, 'Changed active artwork for "{}" to "{}"' .format(self.object, self.object.artwork_active)) except (ObjectDoesNotExist, IndexError): pass return result class...
64
64
90
7
56
ghdpro/animesuki.com
animesuki/core/views.py
Python
CanonicalDetailViewMixin
CanonicalDetailViewMixin
60
69
60
61
8b42607d0413bfb229fe4f4ed5f68c670ba61112
bigcode/the-stack
train
027aad1d25501608ae116f96
train
function
def train_input_args(): parser = argparse.ArgumentParser( description='Image Classifier Parameters') parser.add_argument('--train_dir', help= 'Enter path to training data') parser.add_argument('--test_dir', help= 'Enter path to testing data') parser.add_argument('--valid_dir', help= 'E...
def train_input_args():
parser = argparse.ArgumentParser( description='Image Classifier Parameters') parser.add_argument('--train_dir', help= 'Enter path to training data') parser.add_argument('--test_dir', help= 'Enter path to testing data') parser.add_argument('--valid_dir', help= 'Enter path to validation data'...
import argparse def train_input_args():
9
73
245
6
2
marshall7m/udacity_plant_classifier
train_input_args.py
Python
train_input_args
train_input_args
3
22
3
4
aeb26f8ebb275b0cfd45820bebc4515633e8276b
bigcode/the-stack
train
7bfaf83803b6b353868c479a
train
class
class TestCheckout(): def test_checkout_no_offers(self): SKUs = 'DC' expected_price = 15 + 20 assert checkout_solution.checkout(SKUs) == expected_price def test_checkout_with_offers(self): SKUs = 'AAA' expected_price = 130 assert checkout_solution.checkout(SKUs) ...
class TestCheckout():
def test_checkout_no_offers(self): SKUs = 'DC' expected_price = 15 + 20 assert checkout_solution.checkout(SKUs) == expected_price def test_checkout_with_offers(self): SKUs = 'AAA' expected_price = 130 assert checkout_solution.checkout(SKUs) == expected_price ...
from solutions.CHK import checkout_solution class TestCheckout():
12
84
281
4
7
DPNT-Sourcecode/CHK-ujqy01
test/solution_tests/CHK/test_chk.py
Python
TestCheckout
TestCheckout
4
38
4
4
9467bcfa64f148a8f9fa5b5f4ea8559f5606a5b4
bigcode/the-stack
train
a9db4d0f70e7aa6750b51388
train
function
def recv_forward(): if _hcg.is_first_stage: input_tensor = None else: if not _send_recv_meta.has_recv_meta: _send_recv_meta.recv_meta(_hcg.recv_prev_group) _send_recv_meta.has_recv_meta = _use_cache input_tensor, _ = _p2p_helper( tensor_send_next=None...
def recv_forward():
if _hcg.is_first_stage: input_tensor = None else: if not _send_recv_meta.has_recv_meta: _send_recv_meta.recv_meta(_hcg.recv_prev_group) _send_recv_meta.has_recv_meta = _use_cache input_tensor, _ = _p2p_helper( tensor_send_next=None, tensor...
=_hcg.recv_next_group, use_calc_stream=True) allgather_partial( tensor_recv_next, nranks=mp_degree, rank_id=mp_rank, group=mp_group, use_calc_stream=True) return tensor_recv_prev, tensor_recv_next def recv_f...
64
64
99
4
59
RangeKing/Paddle
python/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py
Python
recv_forward
recv_forward
379
392
379
379
e7a16927e92fa92442cda2a4a88439d5530726c3
bigcode/the-stack
train
57182db6152335cb85b98aa8
train
function
def send_backward(input_tensor_grad): if not _hcg.is_first_stage: _p2p_helper( tensor_send_next=None, tensor_send_prev=input_tensor_grad, recv_prev=False, recv_next=False)
def send_backward(input_tensor_grad):
if not _hcg.is_first_stage: _p2p_helper( tensor_send_next=None, tensor_send_prev=input_tensor_grad, recv_prev=False, recv_next=False)
_meta.send_meta(output_tensor, _hcg.send_next_group) _send_recv_meta.has_send_meta = _use_cache _p2p_helper( tensor_send_next=output_tensor, tensor_send_prev=None, recv_prev=False, recv_next=False) def send_backward(input_tensor_grad):
64
64
48
7
57
RangeKing/Paddle
python/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py
Python
send_backward
send_backward
421
427
421
421
bb3c1c4942001cb8f35ba55bd6974e4964c99d5b
bigcode/the-stack
train
c8bbb904d76ebc4e48b1c698
train
function
def initialize_p2p_groups(hcg, use_cache=True): global _hcg, _use_cache _hcg = hcg _use_cache = use_cache send_next_group, send_prev_group, recv_next_group, recv_prev_group = _hcg.get_p2p_groups( ) debug_str = "P2pInfo: send_next_group: %s, send_prev_group: %s, " \ "recv_nex...
def initialize_p2p_groups(hcg, use_cache=True):
global _hcg, _use_cache _hcg = hcg _use_cache = use_cache send_next_group, send_prev_group, recv_next_group, recv_prev_group = _hcg.get_p2p_groups( ) debug_str = "P2pInfo: send_next_group: %s, send_prev_group: %s, " \ "recv_next_group: %s, recv_prev_group: %s" % (repr(send_n...
from paddle import _C_ops import paddle.fluid.core as core from paddle.fluid.framework import _in_legacy_dygraph, _non_static_mode, in_dygraph_mode _hcg = None _use_cache = False def initialize_p2p_groups(hcg, use_cache=True):
64
64
140
13
50
RangeKing/Paddle
python/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py
Python
initialize_p2p_groups
initialize_p2p_groups
27
37
27
27
bdef1811f9238fb86701e3ecbf0251863b51960d
bigcode/the-stack
train
71521d2f398e65695195a452
train
function
def _p2p_helper(tensor_send_next, tensor_send_prev, recv_prev, recv_next): global _hcg tensor_recv_prev = None tensor_recv_next = None # send / recv message recv_shape_msg = _send_recv_meta.recv_shape_message recv_dtype_msg = _send_recv_meta.recv_dtype_message recv_stop_gradient = _send_re...
def _p2p_helper(tensor_send_next, tensor_send_prev, recv_prev, recv_next):
global _hcg tensor_recv_prev = None tensor_recv_next = None # send / recv message recv_shape_msg = _send_recv_meta.recv_shape_message recv_dtype_msg = _send_recv_meta.recv_dtype_message recv_stop_gradient = _send_recv_meta.recv_stop_gradient send_shape_msg = _send_recv_meta.send_shape...
if group is None else group.id if _is_valid_send_recv_partial(tensor, nranks): _C_ops.partial_recv(tensor.detach(), 'use_calc_stream', use_calc_stream, 'ring_id', ring_id, 'peer', src, 'num', nranks, 'id', rank_id, 'dtype', tensor.dtype, 'out_shape',...
256
256
1,049
21
235
RangeKing/Paddle
python/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py
Python
_p2p_helper
_p2p_helper
224
376
224
224
9c3e32181f30b0145a69450f8d3412c7c9cd72b6
bigcode/the-stack
train
7b2553a28fb35ba2e9137250
train
function
def send_partial(tensor, dst=0, nranks=1, rank_id=0, group=None, use_calc_stream=True): if group is not None and not group.is_member(): return ring_id = 0 if group is None else group.id if _is_valid_send_recv_parti...
def send_partial(tensor, dst=0, nranks=1, rank_id=0, group=None, use_calc_stream=True):
if group is not None and not group.is_member(): return ring_id = 0 if group is None else group.id if _is_valid_send_recv_partial(tensor, nranks): return _C_ops.partial_send(tensor.detach(), 'use_calc_stream', use_calc_stream, 'ring_id', ring_id, 'peer', ...
enliang03) support mp+pp optimizer in future. # (partial_send/partial_recv/partial_allgather_) return False def send_partial(tensor, dst=0, nranks=1, rank_id=0, group=None, use_calc_stream=True):
64
64
155
33
30
RangeKing/Paddle
python/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py
Python
send_partial
send_partial
163
182
163
168
69a43585536ef5b42e10806e1549aa84e37c699f
bigcode/the-stack
train
3576e99057c77f086e6368db
train
class
class SendRecvMeta: """Mainly used to help p2p communication context information""" def __init__(self): self.send_shape_message = None self.send_dtype_message = None self.recv_shape_message = None self.recv_dtype_message = None self.recv_stop_gradient = None se...
class SendRecvMeta:
"""Mainly used to help p2p communication context information""" def __init__(self): self.send_shape_message = None self.send_dtype_message = None self.recv_shape_message = None self.recv_dtype_message = None self.recv_stop_gradient = None self.has_send_meta = F...
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import paddle from .utils import paddle_2_number, number_2_dtype from ...utils.log_util import logger import numpy as np from paddle import _C...
256
256
872
5
251
RangeKing/Paddle
python/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py
Python
SendRecvMeta
SendRecvMeta
40
145
40
40
119229abe49552279a1e4375444ea6b607911f6d
bigcode/the-stack
train
dd298a09a5263f32cb89f7ba
train
function
def send_backward_recv_forward(input_tensor_grad): if _hcg.is_first_stage: input_tensor = None else: input_tensor, _ = _p2p_helper( tensor_send_next=None, tensor_send_prev=input_tensor_grad, recv_prev=True, recv_next=False) return input_tensor
def send_backward_recv_forward(input_tensor_grad):
if _hcg.is_first_stage: input_tensor = None else: input_tensor, _ = _p2p_helper( tensor_send_next=None, tensor_send_prev=input_tensor_grad, recv_prev=True, recv_next=False) return input_tensor
_last_stage: output_tensor_grad = None else: _, output_tensor_grad = _p2p_helper( tensor_send_next=output_tensor, tensor_send_prev=None, recv_prev=False, recv_next=True) return output_tensor_grad def send_backward_recv_forward(input_tensor_grad):
64
64
68
9
54
RangeKing/Paddle
python/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py
Python
send_backward_recv_forward
send_backward_recv_forward
442
451
442
442
9a03fd33890d5c47d1c60eabf33a87e035876ea3
bigcode/the-stack
train
692ce8c33173e1e7e7b55789
train
function
def send_forward_recv_backward(output_tensor): if _hcg.is_last_stage: output_tensor_grad = None else: _, output_tensor_grad = _p2p_helper( tensor_send_next=output_tensor, tensor_send_prev=None, recv_prev=False, recv_next=True) return output_ten...
def send_forward_recv_backward(output_tensor):
if _hcg.is_last_stage: output_tensor_grad = None else: _, output_tensor_grad = _p2p_helper( tensor_send_next=output_tensor, tensor_send_prev=None, recv_prev=False, recv_next=True) return output_tensor_grad
_prev=False, recv_next=False) def send_backward(input_tensor_grad): if not _hcg.is_first_stage: _p2p_helper( tensor_send_next=None, tensor_send_prev=input_tensor_grad, recv_prev=False, recv_next=False) def send_forward_recv_backward(output_tensor...
64
64
69
8
56
RangeKing/Paddle
python/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py
Python
send_forward_recv_backward
send_forward_recv_backward
430
439
430
430
bc329c00e30457959e0f168e2eaa33e034772f05
bigcode/the-stack
train
a303187f6ea1477cb6d5717e
train
function
def _is_valid_send_recv_partial(tensor, mp_degree): if _in_legacy_dygraph(): tensor_numel = np.prod(tensor.shape) assert tensor_numel != 0, "can't send/recv zero element" return mp_degree > 1 and tensor_numel % mp_degree == 0 elif in_dygraph_mode(): # TODO(shenliang03) support m...
def _is_valid_send_recv_partial(tensor, mp_degree):
if _in_legacy_dygraph(): tensor_numel = np.prod(tensor.shape) assert tensor_numel != 0, "can't send/recv zero element" return mp_degree > 1 and tensor_numel % mp_degree == 0 elif in_dygraph_mode(): # TODO(shenliang03) support mp+pp optimizer in future. # (partial_send/pa...
.send_shape_message = tuple( [d.shape for d in tensor if not d.stop_gradient]) self.send_dtype_message = tuple( [paddle_2_number(d.dtype) for d in tensor]) _send_recv_meta = SendRecvMeta() def _is_valid_send_recv_partial(tensor, mp_degree):
64
64
112
13
51
RangeKing/Paddle
python/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py
Python
_is_valid_send_recv_partial
_is_valid_send_recv_partial
151
160
151
152
ea85a973f722684b576462d9f3a3b322913892ed
bigcode/the-stack
train
d9bb142bf970c8a674e477c1
train
function
def send_forward(output_tensor): if not _hcg.is_last_stage: if not _send_recv_meta.has_send_meta: _send_recv_meta.set_send_message(output_tensor) _send_recv_meta.send_meta(output_tensor, _hcg.send_next_group) _send_recv_meta.has_send_meta = _use_cache _p2p_helper...
def send_forward(output_tensor):
if not _hcg.is_last_stage: if not _send_recv_meta.has_send_meta: _send_recv_meta.set_send_message(output_tensor) _send_recv_meta.send_meta(output_tensor, _hcg.send_next_group) _send_recv_meta.has_send_meta = _use_cache _p2p_helper( tensor_send_next=ou...
if _hcg.is_last_stage: output_tensor_grad = None else: _, output_tensor_grad = _p2p_helper( tensor_send_next=None, tensor_send_prev=None, recv_prev=False, recv_next=True) return output_tensor_grad def send_forward(output_tensor):
64
64
99
6
57
RangeKing/Paddle
python/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py
Python
send_forward
send_forward
407
418
407
407
765d8455660bcebc4f7c6343d1395990261031d9
bigcode/the-stack
train
114bd0466087dccd273ba1de
train
function
def recv_partial(tensor, src=0, nranks=1, rank_id=0, group=None, use_calc_stream=True): if group is not None and not group.is_member(): return ring_id = 0 if group is None else group.id if _is_valid_send_recv_parti...
def recv_partial(tensor, src=0, nranks=1, rank_id=0, group=None, use_calc_stream=True):
if group is not None and not group.is_member(): return ring_id = 0 if group is None else group.id if _is_valid_send_recv_partial(tensor, nranks): _C_ops.partial_recv(tensor.detach(), 'use_calc_stream', use_calc_stream, 'ring_id', ring_id, 'peer', src, 'num', nran...
: return paddle.distributed.send( tensor.detach(), dst=dst, group=group, use_calc_stream=use_calc_stream) def recv_partial(tensor, src=0, nranks=1, rank_id=0, group=None, use_calc...
64
64
167
33
31
RangeKing/Paddle
python/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py
Python
recv_partial
recv_partial
185
205
185
190
34b83073b6cbeb5e9af684f3246273f4af2c87b5
bigcode/the-stack
train
f537da694da695c3c6c5edca
train
function
def recv_backward(): if _hcg.is_last_stage: output_tensor_grad = None else: _, output_tensor_grad = _p2p_helper( tensor_send_next=None, tensor_send_prev=None, recv_prev=False, recv_next=True) return output_tensor_grad
def recv_backward():
if _hcg.is_last_stage: output_tensor_grad = None else: _, output_tensor_grad = _p2p_helper( tensor_send_next=None, tensor_send_prev=None, recv_prev=False, recv_next=True) return output_tensor_grad
_meta(_hcg.recv_prev_group) _send_recv_meta.has_recv_meta = _use_cache input_tensor, _ = _p2p_helper( tensor_send_next=None, tensor_send_prev=None, recv_prev=True, recv_next=False) return input_tensor def recv_backward():
64
64
63
4
59
RangeKing/Paddle
python/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py
Python
recv_backward
recv_backward
395
404
395
395
4565bba8f720aee93dd4646dfe779e096324524c
bigcode/the-stack
train
25f2d94c832417ab704ad310
train
function
def allgather_partial(tensor, nranks=1, rank_id=0, group=None, use_calc_stream=True): if not _is_valid_send_recv_partial(tensor, nranks): return tensor if group is not None and not group.is_member(): return ...
def allgather_partial(tensor, nranks=1, rank_id=0, group=None, use_calc_stream=True):
if not _is_valid_send_recv_partial(tensor, nranks): return tensor if group is not None and not group.is_member(): return ring_id = 0 if group is None else group.id return _C_ops.partial_allgather_(tensor.detach(), 'use_calc_stream', use_calc_stream, ...
.shape) else: paddle.distributed.recv( tensor.detach(), src=src, group=group, use_calc_stream=use_calc_stream) def allgather_partial(tensor, nranks=1, rank_id=0, group=None, ...
64
64
122
30
34
RangeKing/Paddle
python/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py
Python
allgather_partial
allgather_partial
208
221
208
212
3301dbf9ebd438ab8dfcf1737dee2aa4ae455c12
bigcode/the-stack
train
9dc793642baf0ad2aa865529
train
class
class DeterministicActorCriticNet(nn.Module, BaseNet): def __init__(self, state_dim, action_dim, actor_opt_fn, critic_opt_fn, phi_body=None, actor_body=None, critic_body=None): super(Determ...
class DeterministicActorCriticNet(nn.Module, BaseNet):
def __init__(self, state_dim, action_dim, actor_opt_fn, critic_opt_fn, phi_body=None, actor_body=None, critic_body=None): super(DeterministicActorCriticNet, self).__init__() if phi_...
ensor(x)) q = self.fc_q(phi) beta = F.sigmoid(self.fc_beta(phi)) pi = self.fc_pi(phi) pi = pi.view(-1, self.num_options, self.action_dim) log_pi = F.log_softmax(pi, dim=-1) pi = F.softmax(pi, dim=-1) return {'q': q, 'beta': beta, 'l...
112
112
376
14
98
runxuanjiang/DeepRL
deep_rl/network/network_heads.py
Python
DeterministicActorCriticNet
DeterministicActorCriticNet
98
138
98
98
e59cfbdbdbfb559f842f64878a71421a56873cd9
bigcode/the-stack
train
c7160382edb36ed7cdc4d62b
train
class
class QuantileNet(nn.Module, BaseNet): def __init__(self, action_dim, num_quantiles, body): super(QuantileNet, self).__init__() self.fc_quantiles = layer_init(nn.Linear(body.feature_dim, action_dim * num_quantiles)) self.action_dim = action_dim self.num_quantiles = num_quantiles ...
class QuantileNet(nn.Module, BaseNet):
def __init__(self, action_dim, num_quantiles, body): super(QuantileNet, self).__init__() self.fc_quantiles = layer_init(nn.Linear(body.feature_dim, action_dim * num_quantiles)) self.action_dim = action_dim self.num_quantiles = num_quantiles self.body = body self.to(Co...
_prob = self.fc_categorical(phi).view((-1, self.action_dim, self.num_atoms)) prob = F.softmax(pre_prob, dim=-1) log_prob = F.log_softmax(pre_prob, dim=-1) return prob, log_prob class QuantileNet(nn.Module, BaseNet):
64
64
139
10
53
runxuanjiang/DeepRL
deep_rl/network/network_heads.py
Python
QuantileNet
QuantileNet
57
70
57
57
01c13c55f9d5e79bb739c0bb69ff422158183ad2
bigcode/the-stack
train
f4916eada4476699be06cdce
train
class
class DuelingNet(nn.Module, BaseNet): def __init__(self, action_dim, body): super(DuelingNet, self).__init__() self.fc_value = layer_init(nn.Linear(body.feature_dim, 1)) self.fc_advantage = layer_init(nn.Linear(body.feature_dim, action_dim)) self.body = body self.to(Config.DE...
class DuelingNet(nn.Module, BaseNet):
def __init__(self, action_dim, body): super(DuelingNet, self).__init__() self.fc_value = layer_init(nn.Linear(body.feature_dim, 1)) self.fc_advantage = layer_init(nn.Linear(body.feature_dim, action_dim)) self.body = body self.to(Config.DEVICE) def forward(self, x, to_num...
_head = layer_init(nn.Linear(body.feature_dim, output_dim)) self.body = body self.to(Config.DEVICE) def forward(self, x): phi = self.body(tensor(x)) y = self.fc_head(phi) return y class DuelingNet(nn.Module, BaseNet):
64
64
154
10
53
runxuanjiang/DeepRL
deep_rl/network/network_heads.py
Python
DuelingNet
DuelingNet
24
37
24
24
ec05b01d39acbff42aa12461266d655ad08e057f
bigcode/the-stack
train
f87e36449723bdbf452aacaa
train
class
class OptionCriticNet(nn.Module, BaseNet): def __init__(self, body, action_dim, num_options): super(OptionCriticNet, self).__init__() self.fc_q = layer_init(nn.Linear(body.feature_dim, num_options)) self.fc_pi = layer_init(nn.Linear(body.feature_dim, num_options * action_dim)) self.f...
class OptionCriticNet(nn.Module, BaseNet):
def __init__(self, body, action_dim, num_options): super(OptionCriticNet, self).__init__() self.fc_q = layer_init(nn.Linear(body.feature_dim, num_options)) self.fc_pi = layer_init(nn.Linear(body.feature_dim, num_options * action_dim)) self.fc_beta = layer_init(nn.Linear(body.feature_...
self.to(Config.DEVICE) def forward(self, x): phi = self.body(tensor(x)) quantiles = self.fc_quantiles(phi) quantiles = quantiles.view((-1, self.action_dim, self.num_quantiles)) return quantiles class OptionCriticNet(nn.Module, BaseNet):
68
68
229
11
56
runxuanjiang/DeepRL
deep_rl/network/network_heads.py
Python
OptionCriticNet
OptionCriticNet
73
95
73
73
208181c742be6165514cbe0a4e20304fb02b155e
bigcode/the-stack
train
5ac56d853d0c2376c93011a3
train
class
class TD3Net(nn.Module, BaseNet): def __init__(self, action_dim, actor_body_fn, critic_body_fn, actor_opt_fn, critic_opt_fn, ): super(TD3Net, self).__init__() self.actor_body = actor_body_fn() ...
class TD3Net(nn.Module, BaseNet):
def __init__(self, action_dim, actor_body_fn, critic_body_fn, actor_opt_fn, critic_opt_fn, ): super(TD3Net, self).__init__() self.actor_body = actor_body_fn() self.critic_body_1 = critic_bod...
critic_body(phi) logits = self.fc_action(phi_a) v = self.fc_critic(phi_v) dist = torch.distributions.Categorical(logits=logits) if action is None: action = dist.sample() log_prob = dist.log_prob(action).unsqueeze(-1) entropy = dist.entropy().unsqueeze(-1) ...
113
113
378
10
103
runxuanjiang/DeepRL
deep_rl/network/network_heads.py
Python
TD3Net
TD3Net
226
261
226
226
f8a65e7f8cfc463b0950ed19cda484f0735c6e54
bigcode/the-stack
train
d38af85dcba9afe5be66be96
train
class
class VanillaNet(nn.Module, BaseNet): def __init__(self, output_dim, body): super(VanillaNet, self).__init__() self.fc_head = layer_init(nn.Linear(body.feature_dim, output_dim)) self.body = body self.to(Config.DEVICE) def forward(self, x): phi = self.body(tensor(x)) ...
class VanillaNet(nn.Module, BaseNet):
def __init__(self, output_dim, body): super(VanillaNet, self).__init__() self.fc_head = layer_init(nn.Linear(body.feature_dim, output_dim)) self.body = body self.to(Config.DEVICE) def forward(self, x): phi = self.body(tensor(x)) y = self.fc_head(phi) retu...
2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) # # Permission given to modify the code as long as you keep this # # declaration at the top # ####################################################################### from .network_utils import * from .network_bodi...
64
64
89
9
55
runxuanjiang/DeepRL
deep_rl/network/network_heads.py
Python
VanillaNet
VanillaNet
11
21
11
11
16a5817fd4f9a3f3829ee4b5f970620b0d342316
bigcode/the-stack
train
bb302aff1665161f882378ad
train
class
class CategoricalActorCriticNet(nn.Module, BaseNet): def __init__(self, state_dim, action_dim, phi_body=None, actor_body=None, critic_body=None): super(CategoricalActorCriticNet, self).__init__() if phi_body is None...
class CategoricalActorCriticNet(nn.Module, BaseNet):
def __init__(self, state_dim, action_dim, phi_body=None, actor_body=None, critic_body=None): super(CategoricalActorCriticNet, self).__init__() if phi_body is None: phi_body = DummyBody(state_dim) if actor_bo...
= self.fc_critic(phi_v) dist = torch.distributions.Normal(mean, F.softplus(self.std)) if action is None: action = dist.sample() log_prob = dist.log_prob(action).sum(-1).unsqueeze(-1) entropy = dist.entropy().sum(-1).unsqueeze(-1) return {'a': action, ...
116
116
389
13
103
runxuanjiang/DeepRL
deep_rl/network/network_heads.py
Python
CategoricalActorCriticNet
CategoricalActorCriticNet
184
223
184
184
f5358c40f948840504aaf0a70a97bf0cac55b823
bigcode/the-stack
train
e15a731e1a26de617f6dfefd
train
class
class GaussianActorCriticNet(nn.Module, BaseNet): def __init__(self, state_dim, action_dim, phi_body=None, actor_body=None, critic_body=None): super(GaussianActorCriticNet, self).__init__() if phi_body is None: phi_...
class GaussianActorCriticNet(nn.Module, BaseNet):
def __init__(self, state_dim, action_dim, phi_body=None, actor_body=None, critic_body=None): super(GaussianActorCriticNet, self).__init__() if phi_body is None: phi_body = DummyBody(state_dim) if actor_body ...
_opt = critic_opt_fn(self.critic_params + self.phi_params) self.to(Config.DEVICE) def forward(self, obs): phi = self.feature(obs) action = self.actor(phi) return action def feature(self, obs): obs = tensor(obs) return self.phi_body(obs) def actor(self, phi)...
123
123
410
12
111
runxuanjiang/DeepRL
deep_rl/network/network_heads.py
Python
GaussianActorCriticNet
GaussianActorCriticNet
141
181
141
141
1bf1b629b16e0e3846f3b96d47a5f15c746cff74
bigcode/the-stack
train
e739810a544a86ba7422be08
train
class
class CategoricalNet(nn.Module, BaseNet): def __init__(self, action_dim, num_atoms, body): super(CategoricalNet, self).__init__() self.fc_categorical = layer_init(nn.Linear(body.feature_dim, action_dim * num_atoms)) self.action_dim = action_dim self.num_atoms = num_atoms self...
class CategoricalNet(nn.Module, BaseNet):
def __init__(self, action_dim, num_atoms, body): super(CategoricalNet, self).__init__() self.fc_categorical = layer_init(nn.Linear(body.feature_dim, action_dim * num_atoms)) self.action_dim = action_dim self.num_atoms = num_atoms self.body = body self.to(Config.DEVICE...
= self.fc_value(phi) advantange = self.fc_advantage(phi) q = value.expand_as(advantange) + (advantange - advantange.mean(1, keepdim=True).expand_as(advantange)) return q class CategoricalNet(nn.Module, BaseNet):
64
64
156
10
53
runxuanjiang/DeepRL
deep_rl/network/network_heads.py
Python
CategoricalNet
CategoricalNet
40
54
40
40
26444a651023f38b9173885dd9c3044e0a6428fa
bigcode/the-stack
train
07ca6f91fd04b6f415009582
train
class
class RESTAPIApplication: def __init__(self): self.logger = logging.getLogger("wallet-app") self.app_state = app_state # easier to mock def run_app(self): self.logger.debug("entering application main loop") try: while app_state.async_.loop.is_running(): ...
class RESTAPIApplication:
def __init__(self): self.logger = logging.getLogger("wallet-app") self.app_state = app_state # easier to mock def run_app(self): self.logger.debug("entering application main loop") try: while app_state.async_.loop.is_running(): time.sleep(0.1) # sol...
import concurrent.futures import json import logging import time from typing import Any, Callable, Iterable, Optional from aiorpcx import run_in_thread from bitcoinx import hash_to_hex_str from electrumsv.app_state import app_state from .errors import Errors from .constants import WalletEventNames from .handlers imp...
80
256
879
5
74
electrumsv/electrumsv
examples/applications/restapi/app.py
Python
RESTAPIApplication
RESTAPIApplication
17
95
17
18
b7fda962fced37ac0ca73cb4d09041318e185561
bigcode/the-stack
train
ea04340b2c23dace333c5db8
train
function
def assert_has_consistent_trace_distance_bound(val: Any) -> None: # pylint: disable=unused-variable __tracebackhide__ = True # pylint: enable=unused-variable u = protocols.unitary(val, default=None) val_from_trace = protocols.trace_distance_bound(val) assert 0.0 <= val_from_trace <= 1.0 if u...
def assert_has_consistent_trace_distance_bound(val: Any) -> None: # pylint: disable=unused-variable
__tracebackhide__ = True # pylint: enable=unused-variable u = protocols.unitary(val, default=None) val_from_trace = protocols.trace_distance_bound(val) assert 0.0 <= val_from_trace <= 1.0 if u is not None: class Unitary: def _unitary_(self): return u ...
assert val._eigen_shifts() == [ e[0] for e in val._eigen_components() ], "_eigen_shifts not consistent with _eigen_components" def assert_has_consistent_trace_distance_bound(val: Any) -> None: # pylint: disable=unused-variable
64
64
140
24
40
Nexuscompute/Cirq
cirq-core/cirq/testing/consistent_protocols.py
Python
assert_has_consistent_trace_distance_bound
assert_has_consistent_trace_distance_bound
119
134
119
120
18e0814899b77910fd1ce4a0f00d0ba261fde920
bigcode/the-stack
train
f93c4cb2a255d666dd712e86
train
function
def assert_commutes_magic_method_consistent_with_unitaries( *vals: Sequence[Any], atol: Union[int, float] = 1e-8 ) -> None: if any(isinstance(val, ops.Operation) for val in vals): raise TypeError('`_commutes_` need not be consistent with unitaries for `Operation`.') unitaries = [protocols.unitary(va...
def assert_commutes_magic_method_consistent_with_unitaries( *vals: Sequence[Any], atol: Union[int, float] = 1e-8 ) -> None:
if any(isinstance(val, ops.Operation) for val in vals): raise TypeError('`_commutes_` need not be consistent with unitaries for `Operation`.') unitaries = [protocols.unitary(val, None) for val in vals] pairs = itertools.permutations(zip(vals, unitaries), 2) for (left_val, left_unitary), (right_v...
if isinstance(val, ops.Gate) and protocols.has_mixture(val): assert_controlled_and_controlled_by_identical(val) def assert_commutes_magic_method_consistent_with_unitaries( *vals: Sequence[Any], atol: Union[int, float] = 1e-8 ) -> None:
64
64
197
37
27
Nexuscompute/Cirq
cirq-core/cirq/testing/consistent_protocols.py
Python
assert_commutes_magic_method_consistent_with_unitaries
assert_commutes_magic_method_consistent_with_unitaries
170
183
170
172
73455623a86cef0b58d30f8461aec6d389d99528
bigcode/the-stack
train
3b0fdfe8d516533d3d886b7c
train
function
def _assert_meets_standards_helper( val: Any, *, ignoring_global_phase: bool, setup_code: str, global_vals: Optional[Dict[str, Any]], local_vals: Optional[Dict[str, Any]], ignore_decompose_to_default_gateset: bool, ) -> None: __tracebackhide__ = True # pylint: disable=unused-variable ...
def _assert_meets_standards_helper( val: Any, *, ignoring_global_phase: bool, setup_code: str, global_vals: Optional[Dict[str, Any]], local_vals: Optional[Dict[str, Any]], ignore_decompose_to_default_gateset: bool, ) -> None:
__tracebackhide__ = True # pylint: disable=unused-variable assert_consistent_resolve_parameters(val) assert_specifies_has_unitary_if_unitary(val) assert_has_consistent_qid_shape(val) assert_has_consistent_apply_unitary(val) assert_all_implemented_act_on_effects_match_unitary(val) assert_qa...
= protocols.trace_distance_bound(Unitary()) assert val_from_trace >= val_from_unitary or np.isclose(val_from_trace, val_from_unitary) def _assert_meets_standards_helper( val: Any, *, ignoring_global_phase: bool, setup_code: str, global_vals: Optional[Dict[str, Any]], local_vals: Option...
99
99
333
68
31
Nexuscompute/Cirq
cirq-core/cirq/testing/consistent_protocols.py
Python
_assert_meets_standards_helper
_assert_meets_standards_helper
137
167
137
145
d9e4ae5367c1a8c0a21a82c115f60a44a0ff9d0e
bigcode/the-stack
train
dea3105592a8b1f3a8e553f6
train
function
def assert_eigen_shifts_is_consistent_with_eigen_components(val: ops.EigenGate) -> None: # pylint: disable=unused-variable __tracebackhide__ = True # pylint: enable=unused-variable if not protocols.is_parameterized(val): assert val._eigen_shifts() == [ e[0] for e in val._eigen_compon...
def assert_eigen_shifts_is_consistent_with_eigen_components(val: ops.EigenGate) -> None: # pylint: disable=unused-variable
__tracebackhide__ = True # pylint: enable=unused-variable if not protocols.is_parameterized(val): assert val._eigen_shifts() == [ e[0] for e in val._eigen_components() ], "_eigen_shifts not consistent with _eigen_components"
=global_vals, local_vals=local_vals, ignore_decompose_to_default_gateset=ignore_decompose_to_default_gateset, ) def assert_eigen_shifts_is_consistent_with_eigen_components(val: ops.EigenGate) -> None: # pylint: disable=unused-variable
64
64
99
32
32
Nexuscompute/Cirq
cirq-core/cirq/testing/consistent_protocols.py
Python
assert_eigen_shifts_is_consistent_with_eigen_components
assert_eigen_shifts_is_consistent_with_eigen_components
109
116
109
110
3250f31df81d96dd524abdb6eb8119f8a184c3ae
bigcode/the-stack
train
a92f80d8b0125940f1262f1e
train
function
def assert_implements_consistent_protocols( val: Any, *, exponents: Sequence[Any] = (0, 1, -1, 0.25, sympy.Symbol('s')), qubit_count: Optional[int] = None, ignoring_global_phase: bool = False, setup_code: str = 'import cirq\nimport numpy as np\nimport sympy', global_vals: Optional[Dict[str, ...
def assert_implements_consistent_protocols( val: Any, *, exponents: Sequence[Any] = (0, 1, -1, 0.25, sympy.Symbol('s')), qubit_count: Optional[int] = None, ignoring_global_phase: bool = False, setup_code: str = 'import cirq\nimport numpy as np\nimport sympy', global_vals: Optional[Dict[str, ...
"""Checks that a value is internally consistent and has a good __repr__.""" global_vals = global_vals or {} local_vals = local_vals or {} _assert_meets_standards_helper( val, ignoring_global_phase=ignoring_global_phase, setup_code=setup_code, global_vals=global_vals, ...
def assert_implements_consistent_protocols( val: Any, *, exponents: Sequence[Any] = (0, 1, -1, 0.25, sympy.Symbol('s')), qubit_count: Optional[int] = None, ignoring_global_phase: bool = False, setup_code: str = 'import cirq\nimport numpy as np\nimport sympy', global_vals: Optional[Dict[str, ...
130
96
321
130
0
Nexuscompute/Cirq
cirq-core/cirq/testing/consistent_protocols.py
Python
assert_implements_consistent_protocols
assert_implements_consistent_protocols
42
76
42
52
a89a18c47c6dd9b30aae5a942034f0d5a1a1d014
bigcode/the-stack
train
cb95a40aaa7ed6791072c643
train
function
def assert_eigengate_implements_consistent_protocols( eigen_gate_type: Type[ops.EigenGate], *, exponents: Sequence[value.TParamVal] = (0, 1, -1, 0.25, sympy.Symbol('s')), global_shifts: Sequence[float] = (0, -0.5, 0.1), qubit_count: Optional[int] = None, ignoring_global_phase: bool = False, ...
def assert_eigengate_implements_consistent_protocols( eigen_gate_type: Type[ops.EigenGate], *, exponents: Sequence[value.TParamVal] = (0, 1, -1, 0.25, sympy.Symbol('s')), global_shifts: Sequence[float] = (0, -0.5, 0.1), qubit_count: Optional[int] = None, ignoring_global_phase: bool = False, ...
"""Checks that an EigenGate subclass is internally consistent and has a good __repr__.""" # pylint: disable=unused-variable __tracebackhide__ = True # pylint: enable=unused-variable for exponent in exponents: for shift in global_shifts: _assert_meets_standards_helper( ...
def assert_eigengate_implements_consistent_protocols( eigen_gate_type: Type[ops.EigenGate], *, exponents: Sequence[value.TParamVal] = (0, 1, -1, 0.25, sympy.Symbol('s')), global_shifts: Sequence[float] = (0, -0.5, 0.1), qubit_count: Optional[int] = None, ignoring_global_phase: bool = False, ...
167
92
307
167
0
Nexuscompute/Cirq
cirq-core/cirq/testing/consistent_protocols.py
Python
assert_eigengate_implements_consistent_protocols
assert_eigengate_implements_consistent_protocols
79
106
79
90
99b12b7359318ca8c805180a183321e8fa6e7e56
bigcode/the-stack
train
244cfc45fdbb6c7b21f8b126
train
function
def kepdynamic(infile, outfile=None, datacol='SAP_FLUX', pmin=0.1, pmax=10., nfreq=2000, deltat=10., nslice=10, plot=False, plotscale='log', cmap='PuBu', noninteractive=False, overwrite=False, verbose=False, logfile='kepdynamic.log'): """ kepdynamic -- Construct a dynamic (time-dep...
def kepdynamic(infile, outfile=None, datacol='SAP_FLUX', pmin=0.1, pmax=10., nfreq=2000, deltat=10., nslice=10, plot=False, plotscale='log', cmap='PuBu', noninteractive=False, overwrite=False, verbose=False, logfile='kepdynamic.log'):
""" kepdynamic -- Construct a dynamic (time-dependent) power spectrum from time series data Parameters ---------- infile : str The name of a MAST standard format FITS file containing a Kepler light curve within the first data extension. outfile : string The name of t...
from .utils import PyKEArgumentHelpFormatter import re import numpy as np from astropy.io import fits as pyfits from astropy.stats import LombScargle from matplotlib import pyplot as plt from tqdm import tqdm from . import kepio, kepmsg, kepkey, kepstat __all__ = ['kepdynamic'] def kepdynamic(infile, outfile=None, da...
148
256
2,310
75
73
ecalifornica/pyke
pyke/kepdynamic.py
Python
kepdynamic
kepdynamic
14
240
14
16
6256a36e3214e4b13f85e25b767ef7831abde342
bigcode/the-stack
train
9409f58b1a6ff78965e0f8ac
train
function
def kepdynamic_main(): import argparse parser = argparse.ArgumentParser( description=('Construct a dynamic (time-dependent) power spectrum ' 'from Kepler time series data'), formatter_class=PyKEArgumentHelpFormatter) parser.add_argument('infile', help='Name ...
def kepdynamic_main():
import argparse parser = argparse.ArgumentParser( description=('Construct a dynamic (time-dependent) power spectrum ' 'from Kepler time series data'), formatter_class=PyKEArgumentHelpFormatter) parser.add_argument('infile', help='Name of input file', type=st...
,0.91,0.86]) dynam = dynam.transpose() plt.imshow(dynam, origin='lower', aspect='auto', cmap=cmap, vmin=zmin, vmax=zmax, extent=[barytime[0], barytime[-1], fmin, fmax], interpolation='bilinear') plt.xlabel(xlab, {'color' : 'k'}) plt.ylabel(r'Frequency (d$^{-1}$)', {'color' ...
153
153
512
5
148
ecalifornica/pyke
pyke/kepdynamic.py
Python
kepdynamic_main
kepdynamic_main
242
284
242
242
08dac533f3b2a640413d5c3796963add215ffb59
bigcode/the-stack
train
fb5ba9119f19621e4e48d20a
train
class
@dataclass(frozen=True) class GroupInfo: """ A group of peers assembled through decentralized matchmaking """ group_id: bytes # random unique bytestring that describes the current group, generated by group leader endpoints: Tuple[Endpoint, ...] # an ordered sequence of endpoints of each groupmate gath...
@dataclass(frozen=True) class GroupInfo:
""" A group of peers assembled through decentralized matchmaking """ group_id: bytes # random unique bytestring that describes the current group, generated by group leader endpoints: Tuple[Endpoint, ...] # an ordered sequence of endpoints of each groupmate gathered: Tuple[bytes, ...] # binary metadat...
from dataclasses import dataclass from typing import Tuple from hivemind.utils import Endpoint @dataclass(frozen=True) class GroupInfo:
30
64
125
10
19
Vsevolod-pl/hivemind
hivemind/client/averaging/group_info.py
Python
GroupInfo
GroupInfo
7
19
7
8
d675dac850cf3122d53398c63d5e089d2a0b65ad
bigcode/the-stack
train
f7fb67dc7a20307dd1f0f910
train
class
class Player: def __init__(self, name=None): self.name = name self.rowPoints = 0 self.combo = 0 self.field = Field() def updateRowPoints(self, rowPoints): self.rowPoints = rowPoints def updateCombo(self, combo): self.combo = combo
class Player:
def __init__(self, name=None): self.name = name self.rowPoints = 0 self.combo = 0 self.field = Field() def updateRowPoints(self, rowPoints): self.rowPoints = rowPoints def updateCombo(self, combo): self.combo = combo
# -*- coding: utf-8 -*- # Python3.4* from Bot.Game.Field import Field class Player:
26
64
72
3
22
bambrose24/block-battle-python3
Bot/Game/Player.py
Python
Player
Player
7
19
7
7
68cd30603c1d70426f8c8452b5245aaf8edf7c93
bigcode/the-stack
train
aa57aa8e7dd395f3aca1b7c9
train
class
class CertUpdateEventData(object): def __init__(self, event_data): raw_obj = event_data['raw_object'] metadata = raw_obj['metadata'] data = raw_obj['data'] managed_fields = metadata['managedFields'] self.action = event_data['type'] self.secret_name = metadata['name'] ...
class CertUpdateEventData(object):
def __init__(self, event_data): raw_obj = event_data['raw_object'] metadata = raw_obj['metadata'] data = raw_obj['data'] managed_fields = metadata['managedFields'] self.action = event_data['type'] self.secret_name = metadata['name'] self.last_operation = '' ...
Context(object): def __init__(self): self.dc_role = None self._token = None self._dc_tokens = {} self.kubernete_namespace = None def initialize(self): self.dc_role = utils.get_dc_role() def get_token(self): if not self._token or self._token.is_expired(): ...
179
179
597
7
171
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
CertUpdateEventData
CertUpdateEventData
75
135
75
75
3873f2c7c7721b41efd44632e31e6b1e2ceea11f
bigcode/the-stack
train
eb9bd8bc8870f29515f301c2
train
class
class RestApiCertRenew(PlatformCertRenew): def __init__(self, context): super(RestApiCertRenew, self).__init__(context, constants.RESTAPI_CERT_SECRET_NAME) def update_certificate(self, event_data): LOG.info('RestApiCertRenew: Secret changes detected. Initiating certificate update') toke...
class RestApiCertRenew(PlatformCertRenew):
def __init__(self, context): super(RestApiCertRenew, self).__init__(context, constants.RESTAPI_CERT_SECRET_NAME) def update_certificate(self, event_data): LOG.info('RestApiCertRenew: Secret changes detected. Initiating certificate update') token = self.context.get_token() system...
defaults to False """ pem_file_path = utils.update_pemfile(event_data.tls_crt, event_data.tls_key) token = self.context.get_token() utils.update_platform_cert(token, cert_type, pem_file_path, force) class RestApiCertRenew(PlatformCertRenew):
64
64
120
10
54
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
RestApiCertRenew
RestApiCertRenew
627
638
627
627
53a7d821b71ffa3ea450192b971f85042608bcd5
bigcode/the-stack
train
87bceb0394c7bb3ba75bb779
train
class
class RootCARenew(CertificateRenew): def __init__(self, context): super(RootCARenew, self).__init__(context) self.secrets_to_recreate = [] def notify_changed(self, event_data): if self.check_filter(event_data): self.do_action(event_data) else: return Fals...
class RootCARenew(CertificateRenew):
def __init__(self, context): super(RootCARenew, self).__init__(context) self.secrets_to_recreate = [] def notify_changed(self, event_data): if self.check_filter(event_data): self.do_action(event_data) else: return False def check_filter(self, event_d...
('%s is %s %s. Software version %s' % (sc_name, sc['management-state'], sc['availability-status'], sc['software-version'])) if sc['management-state'] == utils.MANAGEMENT_MANAGED: # don't do anything until...
235
235
786
9
225
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
RootCARenew
RootCARenew
505
588
505
505
c784c385728378435705d7f00f7f3cf29bb3f83a
bigcode/the-stack
train
d2752ed5e771934d327281a0
train
class
class AdminEndpointRenew(CertificateRenew): def __init__(self, context): super(AdminEndpointRenew, self).__init__(context) role = self.context.dc_role if role == constants.DISTRIBUTED_CLOUD_ROLE_SYSTEMCONTROLLER: self.secret_name = constants.DC_ADMIN_ENDPOINT_SECRET_NAME ...
class AdminEndpointRenew(CertificateRenew):
def __init__(self, context): super(AdminEndpointRenew, self).__init__(context) role = self.context.dc_role if role == constants.DISTRIBUTED_CLOUD_ROLE_SYSTEMCONTROLLER: self.secret_name = constants.DC_ADMIN_ENDPOINT_SECRET_NAME elif role == constants.DISTRIBUTED_CLOUD_ROL...
proper hardware and software configuration. reasonable_delay = 3600 # 1 hour delta = (event_data.last_operation_time - event_data.creation_time).total_seconds() if event_data.action == SECRET_ACTION_TYPE_MODIFIED and delta > reasonable_delay: self.recreate_secret(event_data) ...
80
80
267
8
72
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
AdminEndpointRenew
AdminEndpointRenew
395
423
395
395
838ce850dfb8f0e82c22d31aede2af6a9c4c5c7b
bigcode/the-stack
train
c4caacd3da02e7ada496590e
train
class
class CertWatcherListener(object): def __init__(self, context): self.context = context def notify_changed(self, event_data): if self.check_filter(event_data): self.do_action(event_data) else: return False def check_filter(self, event_data): return Fa...
class CertWatcherListener(object):
def __init__(self, context): self.context = context def notify_changed(self, event_data): if self.check_filter(event_data): self.do_action(event_data) else: return False def check_filter(self, event_data): return False def do_action(self, event_...
the task. A task will be replaced with a newer task with the same id when it is in a queue (for reattempting) """ return 'cert-update: %s' % self.event_data.secret_name def failed(self): self.listener.action_failed(self.event_data) class CertWatcherListener(object):
69
69
231
6
63
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
CertWatcherListener
CertWatcherListener
170
202
170
170
fdf122dc62c0d862f844524b3f6fc0dde8472942
bigcode/the-stack
train
14f0832ea9660e55b24dbcc3
train
class
class PlatformCertRenew(CertificateRenew): """Handles a renew event for a certificate that must be installed as a platform cert. """ def __init__(self, context, secret_name): super(PlatformCertRenew, self).__init__(context) self.secret_name = secret_name LOG.info('%s init with secre...
class PlatformCertRenew(CertificateRenew):
"""Handles a renew event for a certificate that must be installed as a platform cert. """ def __init__(self, context, secret_name): super(PlatformCertRenew, self).__init__(context) self.secret_name = secret_name LOG.info('%s init with secretname: %s' % (self.__class__.__name__, self...
_secret(secret, utils.CERT_NAMESPACE_SYS_CONTROLLER) except Exception as e: LOG.error('Deleting secret %s:%s. Error %s' % (utils.CERT_NAMESPACE_SYS_CONTROLLER, secret, e)) else: self.secrets_to_recreate.remove(secret) if len(self...
101
101
339
8
93
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
PlatformCertRenew
PlatformCertRenew
591
624
591
591
fa57a1973e3b0c0a6573d1d1cee1d78830f2ff77
bigcode/the-stack
train
b31cafb11298976d6a52e555
train
class
class CertificateRenew(CertWatcherListener): def __init__(self, context): super(CertificateRenew, self).__init__(context) self.monitor_start = datetime.now() def certificate_is_ready(self, event_data): if event_data.action in (SECRET_ACTION_TYPE_ADDED, SECRET_ACTION_TYPE_MODIFIED)\ ...
class CertificateRenew(CertWatcherListener):
def __init__(self, context): super(CertificateRenew, self).__init__(context) self.monitor_start = datetime.now() def certificate_is_ready(self, event_data): if event_data.action in (SECRET_ACTION_TYPE_ADDED, SECRET_ACTION_TYPE_MODIFIED)\ and event_data.ca_crt and event_d...
_PLATFORM_CERTS LOG.info('setting ns for restapi cert : %s & registering listener' % platcert_ns) self.namespace = platcert_ns self.context.kubernete_namespace = platcert_ns self.register_listener(RestApiCertRenew(self.context)) class RegistryCert_CertWatcher(CertWatcher): def __in...
170
170
567
8
162
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
CertificateRenew
CertificateRenew
343
392
343
343
5df2f4338c9d5afbb71c4779cd54aa1445edcb41
bigcode/the-stack
train
65579a98729f5388b95df9ab
train
class
class MonitorContext(object): def __init__(self): self.dc_role = None self._token = None self._dc_tokens = {} self.kubernete_namespace = None def initialize(self): self.dc_role = utils.get_dc_role() def get_token(self): if not self._token or self._token.is_e...
class MonitorContext(object):
def __init__(self): self.dc_role = None self._token = None self._dc_tokens = {} self.kubernete_namespace = None def initialize(self): self.dc_role = utils.get_dc_role() def get_token(self): if not self._token or self._token.is_expired(): self._to...
_kube KUBE_CONFIG_PATH = '/etc/kubernetes/admin.conf' LOG = log.getLogger(__name__) SECRET_ACTION_TYPE_ADDED = 'ADDED' SECRET_ACTION_TYPE_DELETED = 'DELETED' SECRET_ACTION_TYPE_MODIFIED = 'MODIFIED' CONF = cfg.CONF class MonitorContext(object):
64
64
174
5
58
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
MonitorContext
MonitorContext
49
72
49
49
106bece7fa656fa04ba73613c1fcd6d23e7bf5c7
bigcode/the-stack
train
f8076bd4449a019901910ebb
train
class
class RestApiCert_CertWatcher(CertWatcher): def __init__(self): super(RestApiCert_CertWatcher, self).__init__() def initialize(self): self.context.initialize() platcert_ns = constants.CERT_NAMESPACE_PLATFORM_CERTS LOG.info('setting ns for restapi cert : %s & registering listene...
class RestApiCert_CertWatcher(CertWatcher):
def __init__(self): super(RestApiCert_CertWatcher, self).__init__() def initialize(self): self.context.initialize() platcert_ns = constants.CERT_NAMESPACE_PLATFORM_CERTS LOG.info('setting ns for restapi cert : %s & registering listener' % platcert_ns) self.namespace = p...
.register_listener(AdminEndpointRenew(self.context)) if dc_role == constants.DISTRIBUTED_CLOUD_ROLE_SYSTEMCONTROLLER: self.register_listener(DCIntermediateCertRenew(self.context, audit_subcloud)) self.register_listener(RootCARenew(self.context)) class RestApiCert_CertWatcher(CertWatcher)...
64
64
107
11
53
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
RestApiCert_CertWatcher
RestApiCert_CertWatcher
315
326
315
315
4fe5f96aec81f6a2f1d030d7c5dcb770ff8ce702
bigcode/the-stack
train
885ab8fa7cc0f87cde1ff577
train
class
class DCIntermediateCertRenew(CertificateRenew): def __init__(self, context, audit_subcloud): super(DCIntermediateCertRenew, self).__init__(context) self.secret_pattern = re.compile('-adminep-ca-certificate$') self.audit_subcloud = audit_subcloud def check_filter(self, event_data): ...
class DCIntermediateCertRenew(CertificateRenew):
def __init__(self, context, audit_subcloud): super(DCIntermediateCertRenew, self).__init__(context) self.secret_pattern = re.compile('-adminep-ca-certificate$') self.audit_subcloud = audit_subcloud def check_filter(self, event_data): m = self.secret_pattern.search(event_data.sec...
.DC_ADMIN_ENDPOINT_SECRET_NAME elif role == constants.DISTRIBUTED_CLOUD_ROLE_SUBCLOUD: self.secret_name = constants.SC_ADMIN_ENDPOINT_SECRET_NAME else: self.secret_name = None def check_filter(self, event_data): if self.secret_name == event_data.secret_name: ...
217
217
724
9
208
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
DCIntermediateCertRenew
DCIntermediateCertRenew
426
502
426
426
98ce71a8ff6ebc02b4640ede0b0901997cbe8df5
bigcode/the-stack
train
af2a006eb664630149e18e50
train
class
class RegistryCertRenew(PlatformCertRenew): def __init__(self, context): super(RegistryCertRenew, self).__init__(context, constants.REGISTRY_CERT_SECRET_NAME) def update_certificate(self, event_data): LOG.info('RegistryCertRenew: Secret changes detected. Initiating certificate update') ...
class RegistryCertRenew(PlatformCertRenew):
def __init__(self, context): super(RegistryCertRenew, self).__init__(context, constants.REGISTRY_CERT_SECRET_NAME) def update_certificate(self, event_data): LOG.info('RegistryCertRenew: Secret changes detected. Initiating certificate update') self.update_platform_certificate(event_data...
update') token = self.context.get_token() system_uuid = utils.get_isystems_uuid(token) ret = utils.enable_https(token, system_uuid) if ret is True: self.update_platform_certificate(event_data, constants.CERT_MODE_SSL, force=True) class RegistryCertRenew(PlatformCertRenew):
64
64
85
9
55
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
RegistryCertRenew
RegistryCertRenew
641
648
641
641
9b4a452276e03ee40e21555f534bed23545742be
bigcode/the-stack
train
be71340ae244921624534598
train
class
class CertWatcher(object): def __init__(self): self.listeners = [] self.namespace = None self.context = MonitorContext() self.last_resource_version = None def register_listener(self, listener): return self.listeners.append(listener) def start_watch(self, on_success,...
class CertWatcher(object):
def __init__(self): self.listeners = [] self.namespace = None self.context = MonitorContext() self.last_resource_version = None def register_listener(self, listener): return self.listeners.append(listener) def start_watch(self, on_success, on_error): config....
(self, event_data): if self.check_filter(event_data): self.do_action(event_data) else: return False def check_filter(self, event_data): return False def do_action(self, event_data): """ event with event_data will be refired up to max reattempt ...
211
211
706
5
206
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
CertWatcher
CertWatcher
205
289
205
205
fb5e6baca47c9d6a91cc148668a28ba05ae08a60
bigcode/the-stack
train
a3b25276ba3a7efaf39214a4
train
class
class CertUpdateEvent(object): def __init__(self, listener, event_data): self.listener = listener self.event_data = event_data self.number_of_reattempt = 0 def run(self): try: self.listener.notify_changed(self.event_data) except Exception as e: LO...
class CertUpdateEvent(object):
def __init__(self, listener, event_data): self.listener = listener self.event_data = event_data self.number_of_reattempt = 0 def run(self): try: self.listener.notify_changed(self.event_data) except Exception as e: LOG.error('Reattempt failed [#%s]...
(self.tls_crt), self.hash(self.tls_key), self.creation_time, self.last_operation, self.last_operation_time) @staticmethod def hash(data): m = hashlib.md5() m.update(encodeutils.safe_encode(data)) return m.hexdigest() class CertUpdateEvent(object):
66
66
222
6
60
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
CertUpdateEvent
CertUpdateEvent
138
167
138
138
4059ff5e131d24f2826b936ed4e45c68ecf6ea89
bigcode/the-stack
train
b9d5d50c8685d7cdc81a2607
train
class
class RegistryCert_CertWatcher(CertWatcher): def __init__(self): super(RegistryCert_CertWatcher, self).__init__() def initialize(self): self.context.initialize() platcert_ns = constants.CERT_NAMESPACE_PLATFORM_CERTS LOG.info('setting ns for registry cert : %s & registering list...
class RegistryCert_CertWatcher(CertWatcher):
def __init__(self): super(RegistryCert_CertWatcher, self).__init__() def initialize(self): self.context.initialize() platcert_ns = constants.CERT_NAMESPACE_PLATFORM_CERTS LOG.info('setting ns for registry cert : %s & registering listener' % platcert_ns) self.namespace =...
LOG.info('setting ns for restapi cert : %s & registering listener' % platcert_ns) self.namespace = platcert_ns self.context.kubernete_namespace = platcert_ns self.register_listener(RestApiCertRenew(self.context)) class RegistryCert_CertWatcher(CertWatcher):
64
64
105
10
54
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
RegistryCert_CertWatcher
RegistryCert_CertWatcher
329
340
329
329
2d38f8888fc6062a53826688ba6a8f22a3f6f878
bigcode/the-stack
train
f3e710dc563b96d208784a78
train
class
class DC_CertWatcher(CertWatcher): def __init__(self): super(DC_CertWatcher, self).__init__() def initialize(self, audit_subcloud): self.context.initialize() dc_role = self.context.dc_role LOG.info('DC role: %s' % dc_role) if dc_role == constants.DISTRIBUTED_CLOUD_ROLE_...
class DC_CertWatcher(CertWatcher):
def __init__(self): super(DC_CertWatcher, self).__init__() def initialize(self, audit_subcloud): self.context.initialize() dc_role = self.context.dc_role LOG.info('DC role: %s' % dc_role) if dc_role == constants.DISTRIBUTED_CLOUD_ROLE_SUBCLOUD: ns = utils.CE...
except Exception as e: LOG.error("Monitoring action in namespace=%s failed: %s, %s" % (self.namespace, event_data, e)) if not isinstance(e, URLError): LOG.exception(e) on_error(update_event) class DC_CertWatcher(CertWat...
64
64
199
9
55
albailey/config
sysinv/sysinv/sysinv/sysinv/cert_mon/watcher.py
Python
DC_CertWatcher
DC_CertWatcher
292
312
292
292
0d57350f22bd975b44914c228ee89a100f3414a0
bigcode/the-stack
train
a82f0e5432ea7f3c6e48f659
train
function
def read_file(filename): with open(os_path.join(this_directory, filename), encoding='utf-8') as f: long_description = f.read() return long_description
def read_file(filename):
with open(os_path.join(this_directory, filename), encoding='utf-8') as f: long_description = f.read() return long_description
from os import path as os_path from setuptools import setup import Pyrics.Pyrics as Pyrics this_directory = os_path.abspath(os_path.dirname(__file__)) # reand content def read_file(filename):
45
64
37
5
39
xiedekun/Pyrics
setup.py
Python
read_file
read_file
9
12
9
9
b65b5cb5a332457c9006347aa8477f8ce305bbe8
bigcode/the-stack
train
fd07a2df9571271c0409702a
train
function
def read_requirements(filename): return [line.strip() for line in read_file(filename).splitlines() if not line.startswith('#')]
def read_requirements(filename):
return [line.strip() for line in read_file(filename).splitlines() if not line.startswith('#')]
_directory = os_path.abspath(os_path.dirname(__file__)) # reand content def read_file(filename): with open(os_path.join(this_directory, filename), encoding='utf-8') as f: long_description = f.read() return long_description # acquire dependencies def read_requirements(filename):
64
64
29
6
57
xiedekun/Pyrics
setup.py
Python
read_requirements
read_requirements
15
17
15
15
2176f1cca3f5113348d561354c9e9d1397b11df1
bigcode/the-stack
train
f5d6b14fb7627041debf4475
train
function
def run_crf_model(crf, evaluationfile): test_sents = extract_sents_from_conll(evaluationfile) X_test = [sent2features(s) for s in test_sents] y_pred = crf.predict(X_test) return y_pred, X_test
def run_crf_model(crf, evaluationfile):
test_sents = extract_sents_from_conll(evaluationfile) X_test = [sent2features(s) for s in test_sents] y_pred = crf.predict(X_test) return y_pred, X_test
X_train = [sent2features(s) for s in train_sents] y_train = [sent2labels(s) for s in train_sents] crf = train_crf_model(X_train, y_train) return crf def run_crf_model(crf, evaluationfile):
64
64
62
11
52
maxzw/ma-ml4nlp-labs
code/assignment3/CRF.py
Python
run_crf_model
run_crf_model
94
100
94
95
8ff2d0ea28dc8d3b59c06e1e00b44fc4be70441f
bigcode/the-stack
train
cbf15f789a449d54f909da24
train
function
def main(args=None): if args==None: args = sys.argv trainingfile = args[1] evaluationfile = args[2] outputfile = args[3] train_and_run_crf_model(trainingfile, evaluationfile, outputfile)
def main(args=None):
if args==None: args = sys.argv trainingfile = args[1] evaluationfile = args[2] outputfile = args[3] train_and_run_crf_model(trainingfile, evaluationfile, outputfile)
def train_and_run_crf_model(trainingfile, evaluationfile, outputfile): crf = create_crf_model(trainingfile) pred_labels, eval_data = run_crf_model(crf, evaluationfile) write_out_evaluation(eval_data, pred_labels, outputfile) def main(args=None):
64
64
59
6
58
maxzw/ma-ml4nlp-labs
code/assignment3/CRF.py
Python
main
main
119
128
119
120
212769414cf76c0460f374bd4601f151823c0576
bigcode/the-stack
train
5821985d7db7bbf775e4baa6
train
function
def train_and_run_crf_model(trainingfile, evaluationfile, outputfile): crf = create_crf_model(trainingfile) pred_labels, eval_data = run_crf_model(crf, evaluationfile) write_out_evaluation(eval_data, pred_labels, outputfile)
def train_and_run_crf_model(trainingfile, evaluationfile, outputfile):
crf = create_crf_model(trainingfile) pred_labels, eval_data = run_crf_model(crf, evaluationfile) write_out_evaluation(eval_data, pred_labels, outputfile)
for evalsents, predsents in zip(eval_data, pred_labels): for data, pred in zip(evalsents, predsents): outfile.write(data.get('token') + "\t" + pred + "\n") def train_and_run_crf_model(trainingfile, evaluationfile, outputfile):
64
64
58
16
48
maxzw/ma-ml4nlp-labs
code/assignment3/CRF.py
Python
train_and_run_crf_model
train_and_run_crf_model
112
116
112
113
0dc9dbac2019bb7dd2e2203f0aba1c9fc3680566
bigcode/the-stack
train
7ab9405b044d512ce71ffedb
train
function
def remove_BIO(tag): if tag == 'NN|SYM': return 'NN' return re.sub(r"[A-Z]-", "", tag)
def remove_BIO(tag):
if tag == 'NN|SYM': return 'NN' return re.sub(r"[A-Z]-", "", tag)
# set file directory as working directory os.chdir(os.path.dirname(sys.argv[0])) ## based on https://github.com/cltl/ba-text-mining/blob/master/lab_sessions/lab4/Lab4a.4-NERC-CRF-Dutch.ipynb def remove_BIO(tag):
64
64
33
6
57
maxzw/ma-ml4nlp-labs
code/assignment3/CRF.py
Python
remove_BIO
remove_BIO
16
19
16
16
2b715158f8f04b8759b3c7299fd6be32ed2cda08
bigcode/the-stack
train
c867db5c79a4c582767e9669
train
function
def create_crf_model(trainingfile): train_sents = extract_sents_from_conll(trainingfile) X_train = [sent2features(s) for s in train_sents] y_train = [sent2labels(s) for s in train_sents] crf = train_crf_model(X_train, y_train) return crf
def create_crf_model(trainingfile):
train_sents = extract_sents_from_conll(trainingfile) X_train = [sent2features(s) for s in train_sents] y_train = [sent2labels(s) for s in train_sents] crf = train_crf_model(X_train, y_train) return crf
RF( algorithm='lbfgs', c1=0.1, c2=0.1, max_iterations=100, all_possible_transitions=True ) crf.fit(X_train, y_train) return crf def create_crf_model(trainingfile):
64
64
76
8
55
maxzw/ma-ml4nlp-labs
code/assignment3/CRF.py
Python
create_crf_model
create_crf_model
83
91
83
84
7178acb20c1fa38c2ffa51a86ccc1904e59dc543
bigcode/the-stack
train
02b10a490021c0010773f62f
train
function
def extract_sents_from_conll(inputfile): csvinput = open(inputfile,'r') csvreader = csv.reader(csvinput,delimiter='\t') sents = [] current_sent = [] for row in csvreader: if len(row) > 3: current_sent.append(tuple(row)) #note that this is a simplification that wo...
def extract_sents_from_conll(inputfile):
csvinput = open(inputfile,'r') csvreader = csv.reader(csvinput,delimiter='\t') sents = [] current_sent = [] for row in csvreader: if len(row) > 3: current_sent.append(tuple(row)) #note that this is a simplification that works well for this particular data, in other si...
sure to add them here as well. return [remove_BIO(label) for token, postag, chunklabel, label in sent] def sent2tokens(sent): return [token for token, postag, chunklabel, label in sent] def extract_sents_from_conll(inputfile):
63
64
127
11
52
maxzw/ma-ml4nlp-labs
code/assignment3/CRF.py
Python
extract_sents_from_conll
extract_sents_from_conll
53
66
53
54
3949cfbc708a7d7ffbb4e10fd779ec42aad31a50
bigcode/the-stack
train
9b9dd6c50acafc145ba1602c
train
function
def train_crf_model(X_train, y_train): crf = sklearn_crfsuite.CRF( algorithm='lbfgs', c1=0.1, c2=0.1, max_iterations=100, all_possible_transitions=True ) crf.fit(X_train, y_train) return crf
def train_crf_model(X_train, y_train):
crf = sklearn_crfsuite.CRF( algorithm='lbfgs', c1=0.1, c2=0.1, max_iterations=100, all_possible_transitions=True ) crf.fit(X_train, y_train) return crf
simplification that works well for this particular data, in other situations, you may need to do more advanced preprocessing to identify sentence boundaries if row[0] == ".": sents.append(current_sent) current_sent = [] return sents def train_crf_model(X_train, y_train):...
64
64
76
11
52
maxzw/ma-ml4nlp-labs
code/assignment3/CRF.py
Python
train_crf_model
train_crf_model
69
80
69
70
81b71283ad285e2d4fae7647514be7e0340ba2ad
bigcode/the-stack
train
0a38ef5616beb568e0746779
train
function
def write_out_evaluation(eval_data, pred_labels, outputfile): outfile = open(outputfile, 'w') for evalsents, predsents in zip(eval_data, pred_labels): for data, pred in zip(evalsents, predsents): outfile.write(data.get('token') + "\t" + pred + "\n")
def write_out_evaluation(eval_data, pred_labels, outputfile):
outfile = open(outputfile, 'w') for evalsents, predsents in zip(eval_data, pred_labels): for data, pred in zip(evalsents, predsents): outfile.write(data.get('token') + "\t" + pred + "\n")
test_sents = extract_sents_from_conll(evaluationfile) X_test = [sent2features(s) for s in test_sents] y_pred = crf.predict(X_test) return y_pred, X_test def write_out_evaluation(eval_data, pred_labels, outputfile):
64
64
73
14
49
maxzw/ma-ml4nlp-labs
code/assignment3/CRF.py
Python
write_out_evaluation
write_out_evaluation
103
109
103
104
cfd90d4d0721c2643f1f56cea07adf4a6477d603
bigcode/the-stack
train
532e9397128813a712b791cc
train
function
def sent2labels(sent): #if you added features to your input file, make sure to add them here as well. return [remove_BIO(label) for token, postag, chunklabel, label in sent]
def sent2labels(sent): #if you added features to your input file, make sure to add them here as well.
return [remove_BIO(label) for token, postag, chunklabel, label in sent]
1: features['EOS'] = True return features def sent2features(sent): return [token2features(sent, i) for i in range(len(sent))] def sent2labels(sent): #if you added features to your input file, make sure to add them here as well.
63
64
47
26
38
maxzw/ma-ml4nlp-labs
code/assignment3/CRF.py
Python
sent2labels
sent2labels
44
46
44
45
79730fc43625bc51d5d567dbbddf5ee52523b315
bigcode/the-stack
train
93cd5226969291eaad0554d9
train
function
def token2features(sentence, i): token = sentence[i][0] postag = sentence[i][1] features = { 'bias': 1.0, 'token': token.lower(), 'postag': postag } if i == 0: features['BOS'] = True elif i == len(sentence) -1: features['EOS'] = True ret...
def token2features(sentence, i):
token = sentence[i][0] postag = sentence[i][1] features = { 'bias': 1.0, 'token': token.lower(), 'postag': postag } if i == 0: features['BOS'] = True elif i == len(sentence) -1: features['EOS'] = True return features
/lab_sessions/lab4/Lab4a.4-NERC-CRF-Dutch.ipynb def remove_BIO(tag): if tag == 'NN|SYM': return 'NN' return re.sub(r"[A-Z]-", "", tag) def token2features(sentence, i):
64
64
94
8
56
maxzw/ma-ml4nlp-labs
code/assignment3/CRF.py
Python
token2features
token2features
22
37
22
23
3bcf048ecf4c1d263340e335c3063a9e9b2c04c4
bigcode/the-stack
train
6905b2bb0c3c4c991221a999
train
function
def sent2tokens(sent): return [token for token, postag, chunklabel, label in sent]
def sent2tokens(sent):
return [token for token, postag, chunklabel, label in sent]
, i) for i in range(len(sent))] def sent2labels(sent): #if you added features to your input file, make sure to add them here as well. return [remove_BIO(label) for token, postag, chunklabel, label in sent] def sent2tokens(sent):
64
64
23
6
58
maxzw/ma-ml4nlp-labs
code/assignment3/CRF.py
Python
sent2tokens
sent2tokens
49
50
49
49
2ca5cc8ff8fe49536195953a48ec4ac53aae1e29
bigcode/the-stack
train
1306e102903bf7038c8f9243
train
function
def sent2features(sent): return [token2features(sent, i) for i in range(len(sent))]
def sent2features(sent):
return [token2features(sent, i) for i in range(len(sent))]
.0, 'token': token.lower(), 'postag': postag } if i == 0: features['BOS'] = True elif i == len(sentence) -1: features['EOS'] = True return features def sent2features(sent):
64
64
23
6
57
maxzw/ma-ml4nlp-labs
code/assignment3/CRF.py
Python
sent2features
sent2features
40
41
40
40
ee61e118eb1e3e3c799e220c178a180acf23c2a0
bigcode/the-stack
train
8defadfa92efb87cbfa82eda
train
function
@pytest.mark.asyncio async def test_motion_slide(all_data_provider): element: Dict[str, Any] = {"id": 1} data = await projector.motion_slide(all_data_provider, element, 1) assert data == { "identifier": "4", "title": "12345", "text": "motion text", "amendments": [ ...
@pytest.mark.asyncio async def test_motion_slide(all_data_provider):
element: Dict[str, Any] = {"id": 1} data = await projector.motion_slide(all_data_provider, element, 1) assert data == { "identifier": "4", "title": "12345", "text": "motion text", "amendments": [ { "id": 2, "title": "Amendment for...
_id": 1, "rejected": False, "internal": False, "type": 0, "other_description": "", "line_from": 1, "line_to": 2, "text": "public new motion text", "creation_time": "2019-02-09T09:54:06.256378+01:00", }, } ret...
109
109
365
14
95
topelrapha/OpenSlides
server/tests/unit/motions/test_projector.py
Python
test_motion_slide
test_motion_slide
261
307
261
262
3f857d455e2bd75c49b83b11f6e1921b72545f46
bigcode/the-stack
train
fe390e6a931a6c13af48bdd7
train
function
@pytest.mark.asyncio async def test_statute_amendment_slide(all_data_provider): element: Dict[str, Any] = {"id": 3} data = await projector.motion_slide(all_data_provider, element, 1) assert data == { "identifier": None, "title": "Statute amendment for §1 Preamble", "text": "<p>Some...
@pytest.mark.asyncio async def test_statute_amendment_slide(all_data_provider):
element: Dict[str, Any] = {"id": 3} data = await projector.motion_slide(all_data_provider, element, 1) assert data == { "identifier": None, "title": "Statute amendment for §1 Preamble", "text": "<p>Some other preamble text</p>", "amendments": [], "amendment_paragrap...
"", "submitters": ["Administrator"], "line_length": 85, "line_numbering_mode": "outside", "preamble": "The assembly may decide:", "recommendation_referencing_motions": None, } @pytest.mark.asyncio async def test_statute_amendment_slide(all_data_provider):
69
69
231
18
51
topelrapha/OpenSlides
server/tests/unit/motions/test_projector.py
Python
test_statute_amendment_slide
test_statute_amendment_slide
337
361
337
338
d2594fd53ab20152ed5a858e2256ce249b0fcb8c
bigcode/the-stack
train
a378614ac48c7e1c08a3dfc8
train
function
@pytest.mark.asyncio async def test_amendment_slide(all_data_provider): element: Dict[str, Any] = {"id": 2} data = await projector.motion_slide(all_data_provider, element, 1) assert data == { "identifier": "Ä1", "title": "Amendment for 12345", "text": "", "amendments": [], ...
@pytest.mark.asyncio async def test_amendment_slide(all_data_provider):
element: Dict[str, Any] = {"id": 2} data = await projector.motion_slide(all_data_provider, element, 1) assert data == { "identifier": "Ä1", "title": "Amendment for 12345", "text": "", "amendments": [], "amendment_paragraphs": ["New motion text"], "change_rec...
"submitters": ["Administrator"], "line_length": 85, "line_numbering_mode": "outside", "preamble": "The assembly may decide:", "recommendation_referencing_motions": None, } @pytest.mark.asyncio async def test_amendment_slide(all_data_provider):
66
66
220
16
50
topelrapha/OpenSlides
server/tests/unit/motions/test_projector.py
Python
test_amendment_slide
test_amendment_slide
310
334
310
311
40e3147451e5a8ef4fca34cc94c938b572f6e138
bigcode/the-stack
train
963fdd6c852c745038af3df8
train
function
@pytest.fixture def all_data_provider(): data = {} data["motions/motion"] = { 1: { "id": 1, "identifier": "4", "title": "12345", "text": "motion text", "amendment_paragraphs": None, "modified_final_version": "", "reason"...
@pytest.fixture def all_data_provider():
data = {} data["motions/motion"] = { 1: { "id": 1, "identifier": "4", "title": "12345", "text": "motion text", "amendment_paragraphs": None, "modified_final_version": "", "reason": "", "parent_id": None, ...
from typing import Any, Dict import pytest from openslides.motions import projector from ...integration.helpers import get_all_data_provider @pytest.fixture def all_data_provider():
37
256
2,145
8
28
topelrapha/OpenSlides
server/tests/unit/motions/test_projector.py
Python
all_data_provider
all_data_provider
10
258
10
11
73b11a9f896f5254d1e8cb2970074b6ffff2a41a
bigcode/the-stack
train
bd09fabcf37c21e79c2478e8
train
class
class topological_index( object ): def __init__( self, mol, bond = [] ): self.natm = mol.natm self.anum = mol.anum if( len( bond ) > 0 ): self.bond = bond[:] else: self.bond = qm3.utils.connectivity( mol ) self.conn = [ [] for i in range( self.natm ) ]...
class topological_index( object ):
def __init__( self, mol, bond = [] ): self.natm = mol.natm self.anum = mol.anum if( len( bond ) > 0 ): self.bond = bond[:] else: self.bond = qm3.utils.connectivity( mol ) self.conn = [ [] for i in range( self.natm ) ] for i,j in self.bond: ...
.labl.append( mol.labl[i] ) out.resi.append( mol.resi[i] ) out.resn.append( mol.resn[i] ) out.segn.append( mol.segn[i] ) out.coor += mol.coor[3*i:3*i+3] out.anum.append( mol.anum[i] ) out.chrg.append( mol.chrg[i] ) if( len( mol.type ) >...
255
256
1,624
7
248
SinHouse/qm3
qm3/utils/qsar.py
Python
topological_index
topological_index
52
177
52
52
3ce96903e7c1c6a5c28e625c3804430d023a4a6e
bigcode/the-stack
train
713005a00506b594bb99141a
train
function
def remove_non_polar_H( mol, bnd = [] ): if( bnd == [] ): bnd = qm3.utils.connectivity( mol ) con = [ [] for i in range( mol.natm ) ] for i,j in bnd: con[i].append( j ) con[j].append( i ) out = qm3.mol.molecule() rem = [] chg = [] for i in range( mol.natm ): i...
def remove_non_polar_H( mol, bnd = [] ):
if( bnd == [] ): bnd = qm3.utils.connectivity( mol ) con = [ [] for i in range( mol.natm ) ] for i,j in bnd: con[i].append( j ) con[j].append( i ) out = qm3.mol.molecule() rem = [] chg = [] for i in range( mol.natm ): if( mol.anum[i] != 1 or mol.anum[con[i][0]...
# -*- coding: iso-8859-1 -*- from __future__ import print_function, division import sys if( sys.version_info[0] == 2 ): range = xrange import math import qm3.elements import qm3.maths.matrix import qm3.utils def remove_non_polar_H( mol, bnd = [] ):
75
113
377
14
60
SinHouse/qm3
qm3/utils/qsar.py
Python
remove_non_polar_H
remove_non_polar_H
14
48
14
14
fc699ec7331ff8b67d01f0599f66a0c2795e0ecb
bigcode/the-stack
train
3dd25ce664257d7b028941dd
train
function
def bump(package, version): version = v.parse(version) try: pypi = requests.get('https://pypi.org/pypi/inaccel-' + package + '/json').json() releases = [v.parse(release) for release in pypi['releases']] releases = filter(lambda release: release.release[:-1] == version.release, releases) ...
def bump(package, version):
version = v.parse(version) try: pypi = requests.get('https://pypi.org/pypi/inaccel-' + package + '/json').json() releases = [v.parse(release) for release in pypi['releases']] releases = filter(lambda release: release.release[:-1] == version.release, releases) inaccel = tuple([max...
"""Setup inaccel package.""" import requests from packaging import version as v from setuptools import find_namespace_packages, setup def bump(package, version):
32
64
131
6
25
inaccel/keras
setup.py
Python
bump
bump
8
17
8
8
601e83180f7d833d65cc1a11286a69e873949375
bigcode/the-stack
train
a70ca07b085be2c7c3ccc28e
train
class
class Migration(migrations.Migration): dependencies = [ ('jobs', '0006_auto_20150710_2211'), ] operations = [ migrations.RemoveField( model_name='event', name='email', ), migrations.AddField( model_name='event', name='picture'...
class Migration(migrations.Migration):
dependencies = [ ('jobs', '0006_auto_20150710_2211'), ] operations = [ migrations.RemoveField( model_name='event', name='email', ), migrations.AddField( model_name='event', name='picture', field=models.ImageField(up...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
31
72
240
7
23
TonkWorks/django_skeleton
src/jobs/migrations/0007_auto_20150710_2220.py
Python
Migration
Migration
7
43
7
8
d6da5ad96c677c47d900604a763a45a1fee844d0
bigcode/the-stack
train
c4efcfa10f6103798b999d10
train
class
class FlaskPlugin(BasePlugin): def import_module(self, callback): """ Handle "magic" Flask extension imports: ``flask.ext.foo`` is really ``flask_foo`` or ``flaskext.foo``. """ def wrapper(evaluator, import_names, module_context, *args, **kwargs): if len(import_na...
class FlaskPlugin(BasePlugin):
def import_module(self, callback): """ Handle "magic" Flask extension imports: ``flask.ext.foo`` is really ``flask_foo`` or ``flaskext.foo``. """ def wrapper(evaluator, import_names, module_context, *args, **kwargs): if len(import_names) == 3 and import_names[:2] ...
from jedi.plugins.base import BasePlugin class FlaskPlugin(BasePlugin):
15
66
222
6
8
mak213k/Servidor_automatizado_python
ServidorPython/python32_web/Lib/site-packages/jedi/plugins/flask.py
Python
FlaskPlugin
FlaskPlugin
4
25
4
4
94cd8128d34342007bce1e2c29d5392940697574
bigcode/the-stack
train
8dc074c82eb2cba474410b17
train
class
class TaskResult: def __init__(self, task_id: int, compact_model: Module, compact_model_masks: Dict[str, Dict[str, Tensor]], pruner_generated_masks: Dict[str, Dict[str, Tensor]], score: Optional[float]) -> None: """ Parameters ---------- task_id The uniqu...
class TaskResult:
def __init__(self, task_id: int, compact_model: Module, compact_model_masks: Dict[str, Dict[str, Tensor]], pruner_generated_masks: Dict[str, Dict[str, Tensor]], score: Optional[float]) -> None: """ Parameters ---------- task_id The unique id of task. ...
[ref] -= 1 if self._reference_counter[ref] <= 0: os.remove(ref) if self._reference_counter[ref] < 0: _logger.warning('Referance counter error, the number of %s is %d', ref, self._reference_counter[ref...
98
98
328
4
94
LikeJulia/nni
nni/algorithms/compression/v2/pytorch/base/scheduler.py
Python
TaskResult
TaskResult
113
139
113
113
ac3ccaed9e563fec69b3dfbcc19575d44da102ee
bigcode/the-stack
train
513fa59e81821570304d4f5f
train
class
class BasePruningScheduler: def generate_task(self) -> Optional[Task]: """ Returns ------- Optional[Task] Return the next pruning task. """ raise NotImplementedError() def record_task_result(self, task_result: TaskResult): """ Paramete...
class BasePruningScheduler:
def generate_task(self) -> Optional[Task]: """ Returns ------- Optional[Task] Return the next pruning task. """ raise NotImplementedError() def record_task_result(self, task_result: TaskResult): """ Parameters ---------- ...
TODO: If the compact model has been speeduped, the auto infer masks maybe also need. score The score of the pruning effect. i.e., the accuracy or latency after pruning. """ self.task_id = task_id self.compact_model = compact_model self.compact_model_masks = compact_m...
95
95
317
6
88
LikeJulia/nni
nni/algorithms/compression/v2/pytorch/base/scheduler.py
Python
BasePruningScheduler
BasePruningScheduler
142
198
142
142
214eaeff5a8df9453c8aa5657c7af5d791040e9d
bigcode/the-stack
train
145f9daa610892e1dcabd16f
train
class
class Task: # NOTE: If we want to support multi-thread, this part need to refactor, maybe use file and lock to sync. _reference_counter = {} def __init__(self, task_id: int, model_path: str, masks_path: str, config_list_path: str, speedup: Optional[bool] = True, finetune: Optional[bool] = ...
class Task: # NOTE: If we want to support multi-thread, this part need to refactor, maybe use file and lock to sync.
_reference_counter = {} def __init__(self, task_id: int, model_path: str, masks_path: str, config_list_path: str, speedup: Optional[bool] = True, finetune: Optional[bool] = True, evaluate: Optional[bool] = True): """ Parameters ---------- task_id The...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import gc import logging import os from pathlib import Path from typing import List, Dict, Tuple, Optional import json_tricks import torch from torch import Tensor from torch.nn import Module _logger = logging.getLogger(__name__) class Task: ...
97
240
800
30
67
LikeJulia/nni
nni/algorithms/compression/v2/pytorch/base/scheduler.py
Python
Task
Task
18
110
18
19
9d96cbffc7681469126a14bc53ba870efeb873b6
bigcode/the-stack
train
3939c0f01aaf4931ff897daa
train
class
class ResourceCollectionPackageDescriptionResource(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute ...
class ResourceCollectionPackageDescriptionResource(object):
"""NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name ...
# coding: utf-8 """ Octopus Server API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 2019.6.7+Branch.tags-2019.6.7.Sha.aa18dc6809953218c66f57eff7d26481d9b23d6a Generated by: https://github.com/swagger-api...
155
256
2,344
8
146
cvent/octopus-deploy-api-client
octopus_deploy_swagger_client/models/resource_collection_package_description_resource.py
Python
ResourceCollectionPackageDescriptionResource
ResourceCollectionPackageDescriptionResource
22
351
22
22
2038b19b5624b7514bfa4f91e1aeccd17d9c9759
bigcode/the-stack
train
abe3dbc22d20e592a14f75d2
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, ...
class Migration(migrations.Migration):
initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
# Generated by Django 2.1.7 on 2019-03-21 21:59 from django.db import migrations, models class Migration(migrations.Migration):
38
94
314
7
30
CodingMBA/recipe-app-api
app/core/migrations/0001_initial.py
Python
Migration
Migration
6
33
6
7
889e72eff2df7e61ebc154c7e408bb4a3170504c
bigcode/the-stack
train
6d197ca5515364c62f1f947b
train
function
def crearTabla(cursor): cursor.execute('''CREATE TABLE IF NOT EXISTS alumno( alumno_id INTEGER PRIMARY KEY AUTOINCREMENT, alumno_nombre VARCHAR(20) NOT NULL, alumno_apellidopat varchar(20) NOT NULL, alumno_apellidomat varchar(20) NOT NULL, alumno_grupo var...
def crearTabla(cursor):
cursor.execute('''CREATE TABLE IF NOT EXISTS alumno( alumno_id INTEGER PRIMARY KEY AUTOINCREMENT, alumno_nombre VARCHAR(20) NOT NULL, alumno_apellidopat varchar(20) NOT NULL, alumno_apellidomat varchar(20) NOT NULL, alumno_grupo varchar(10) ...
import sqlite3 def crearTabla(cursor):
9
64
83
5
3
josrangel/SQLiteEjemploPython
archivoSqlite.py
Python
crearTabla
crearTabla
3
11
3
3
ad53fa55624f2ed1444c889a0a1cf0556567a12a
bigcode/the-stack
train
bdcf7a6bf1da1d0464051471
train
function
def borraAlumno(cursor,idAlumno): borrarAlumno="DELETE FROM alumno WHERE alumno_id="+idAlumno+";" cursor.execute(borrarAlumno) bd.commit() print("se elimino el alumno") enlistaAlumnos(cursor)
def borraAlumno(cursor,idAlumno):
borrarAlumno="DELETE FROM alumno WHERE alumno_id="+idAlumno+";" cursor.execute(borrarAlumno) bd.commit() print("se elimino el alumno") enlistaAlumnos(cursor)
ellidomat, alumno_grupo) VALUES('"+nombre+"','"+apellidoPaterno+"','"+apellidoMaterno+"','"+grupo+"');" cursor.execute(insertaAlumno) bd.commit() print("se inserto el alumno") enlistaAlumnos(cursor) def borraAlumno(cursor,idAlumno):
64
64
50
8
56
josrangel/SQLiteEjemploPython
archivoSqlite.py
Python
borraAlumno
borraAlumno
20
25
20
20
48c3b37b21e9e82ed5fc45df0fce20f16edf50cd
bigcode/the-stack
train