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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
95e6b99ceaacb2cf463acd97 | train | class | class DevJwt(JwtAuthBase):
"""Authentication to be used in development only.
Creates a self-signed jwt without going to a remote identity provider. This is helpful when the dev server is configured to accept self-signed jwt"""
def __init__(self, email : str="user@example.com",
emai... | class DevJwt(JwtAuthBase):
| """Authentication to be used in development only.
Creates a self-signed jwt without going to a remote identity provider. This is helpful when the dev server is configured to accept self-signed jwt"""
def __init__(self, email : str="user@example.com",
email_claim : str="https://claim... | token_response = self.authenticate_with_refresh_token(self._refresh_token)
return token_response["access_token"]
@property
def refresh_token(self):
if self._refresh_token is None:
self.authenticate_without_refresh_token()
return self._refresh_token
cla... | 64 | 64 | 170 | 8 | 55 | DouglasConnect/edelweiss-data-python | edelweiss_data/server.py | Python | DevJwt | DevJwt | 179 | 195 | 179 | 179 | 389be23f1dc66397a25717468ba40703f5c0ed01 | bigcode/the-stack | train |
a651858be2a23813357fcf1a | train | class | class OidcJwt(JwtAuthBase):
"""Authenticates requests by adding a jwt to each request.
The user must sign in to the identity provider by copying a url into their web browser.
This is an implementation of the oidc device authorization flow
https://auth0.com/docs/flows/guides/device-auth/ca... | class OidcJwt(JwtAuthBase):
| """Authenticates requests by adding a jwt to each request.
The user must sign in to the identity provider by copying a url into their web browser.
This is an implementation of the oidc device authorization flow
https://auth0.com/docs/flows/guides/device-auth/call-api-device-auth
""... | None
@abc.abstractmethod
def generate_jwt(self):
"""child classes should implement this method"""
raise NotImplementedError
@property
def jwt(self):
if not self.is_valid():
# jwt either does not exist or it has expired, so get a new one
self.... | 255 | 256 | 1,023 | 10 | 245 | DouglasConnect/edelweiss-data-python | edelweiss_data/server.py | Python | OidcJwt | OidcJwt | 57 | 176 | 57 | 57 | a8be686c870caa80c14e1c3216afe948ac9261ec | bigcode/the-stack | train |
660e9205534fefc84b762771 | train | function | def get_internal_tenant_context():
"""Build and return the Venus internal tenant context object
This request context will only work for internal Venus operations. It will
not be able to make requests to remote services. To do so it will need to
use the keystone client to get an auth_token.
""... | def get_internal_tenant_context():
| """Build and return the Venus internal tenant context object
This request context will only work for internal Venus operations. It will
not be able to make requests to remote services. To do so it will need to
use the keystone client to get an auth_token.
"""
project_id = CONF.venus_inter... | @user_id.setter
def user_id(self, value):
self.user = value
def get_admin_context(read_deleted="no"):
return RequestContext(user_id=None,
project_id=None,
is_admin=True,
read_deleted=read_deleted,
... | 64 | 64 | 151 | 7 | 57 | 1049965823/venus | venus/context.py | Python | get_internal_tenant_context | get_internal_tenant_context | 188 | 205 | 188 | 188 | 9f47e433cdb21f102c58d276250a22f95020bfc3 | bigcode/the-stack | train |
1f0db4bd0cb48d435383e412 | train | class | class RequestContext(context.RequestContext):
"""Security context and request information.
Represents the user taking a given action within the system.
"""
def __init__(self, user_id, project_id, is_admin=None, read_deleted="no",
roles=None, project_name=None, remote_address=... | class RequestContext(context.RequestContext):
| """Security context and request information.
Represents the user taking a given action within the system.
"""
def __init__(self, user_id, project_id, is_admin=None, read_deleted="no",
roles=None, project_name=None, remote_address=None,
timestamp=None, request... | of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the s... | 255 | 256 | 1,011 | 7 | 248 | 1049965823/venus | venus/context.py | Python | RequestContext | RequestContext | 45 | 177 | 45 | 45 | 65f50524de593f6e7c45af544fc3e5eda0ab2a92 | bigcode/the-stack | train |
496c24735b0faacfa1246a27 | train | function | def get_admin_context(read_deleted="no"):
return RequestContext(user_id=None,
project_id=None,
is_admin=True,
read_deleted=read_deleted,
overwrite=False)
| def get_admin_context(read_deleted="no"):
| return RequestContext(user_id=None,
project_id=None,
is_admin=True,
read_deleted=read_deleted,
overwrite=False)
| @project_id.setter
def project_id(self, value):
self.tenant = value
@property
def user_id(self):
return self.user
@user_id.setter
def user_id(self, value):
self.user = value
def get_admin_context(read_deleted="no"):
| 64 | 64 | 38 | 9 | 54 | 1049965823/venus | venus/context.py | Python | get_admin_context | get_admin_context | 180 | 185 | 180 | 180 | 0fb7b15919a370d787b8edb2465d4f83728588fd | bigcode/the-stack | train |
11ba1fe3fe2d38e83f22862a | train | function | def dict_to_namespace(dic: Dict) -> Namespace:
if isinstance(dic, dict):
for k, v in dic.items():
dic[k] = dict_to_namespace(v)
return Namespace(**dic)
elif isinstance(dic, list):
return [dict_to_namespace(i) for i in dic]
return dic
| def dict_to_namespace(dic: Dict) -> Namespace:
| if isinstance(dic, dict):
for k, v in dic.items():
dic[k] = dict_to_namespace(v)
return Namespace(**dic)
elif isinstance(dic, list):
return [dict_to_namespace(i) for i in dic]
return dic
| from typing import Dict, Any, Union
from argparse import Namespace
import yaml
def dict_to_namespace(dic: Dict) -> Namespace:
| 28 | 64 | 67 | 11 | 16 | izhx/nmnlp | common/config.py | Python | dict_to_namespace | dict_to_namespace | 7 | 14 | 7 | 7 | d8a8a70c5e054da46144c6943912a26e30c429ad | bigcode/the-stack | train |
c9a72801f9bc3a986f2f7b92 | train | function | def namespace_to_dict(obj: Namespace) -> Dict:
if isinstance(obj, Namespace):
obj = vars(obj)
if isinstance(obj, dict):
obj = {k: namespace_to_dict(v) for k, v in obj.items()}
elif isinstance(obj, list):
obj = [namespace_to_dict(i) for i in obj]
return obj
| def namespace_to_dict(obj: Namespace) -> Dict:
| if isinstance(obj, Namespace):
obj = vars(obj)
if isinstance(obj, dict):
obj = {k: namespace_to_dict(v) for k, v in obj.items()}
elif isinstance(obj, list):
obj = [namespace_to_dict(i) for i in obj]
return obj
| (dic, dict):
for k, v in dic.items():
dic[k] = dict_to_namespace(v)
return Namespace(**dic)
elif isinstance(dic, list):
return [dict_to_namespace(i) for i in dic]
return dic
def namespace_to_dict(obj: Namespace) -> Dict:
| 64 | 64 | 75 | 11 | 52 | izhx/nmnlp | common/config.py | Python | namespace_to_dict | namespace_to_dict | 17 | 25 | 17 | 17 | 4b853b16f18240fc15f8584f3dd8281906ee9fa9 | bigcode/the-stack | train |
b594d606164e5e18c3740a61 | train | function | def load_yaml(path: str) -> Dict[str, Any]:
if path.endswith(('yml', 'yaml')):
with open(path) as file:
config = yaml.load(file, Loader=yaml.SafeLoader)
config['path'] = path
return config
else:
raise ValueError(
f"The config file at {path} has a w... | def load_yaml(path: str) -> Dict[str, Any]:
| if path.endswith(('yml', 'yaml')):
with open(path) as file:
config = yaml.load(file, Loader=yaml.SafeLoader)
config['path'] = path
return config
else:
raise ValueError(
f"The config file at {path} has a wrong type!")
| if isinstance(obj, dict):
obj = {k: namespace_to_dict(v) for k, v in obj.items()}
elif isinstance(obj, list):
obj = [namespace_to_dict(i) for i in obj]
return obj
def load_yaml(path: str) -> Dict[str, Any]:
| 64 | 64 | 79 | 13 | 50 | izhx/nmnlp | common/config.py | Python | load_yaml | load_yaml | 28 | 36 | 28 | 28 | 7058129e1ef5b1d24ec3f948cdc71a3fe1f7f741 | bigcode/the-stack | train |
f5fe93e94dce5695024c6675 | train | function | def save_yaml(obj: Union[Dict, Namespace], path: str = None) -> None:
if isinstance(obj, Namespace):
obj = namespace_to_dict(obj)
if path is None:
try:
path = obj.pop('path')
except KeyError:
raise KeyError("存储的配置文件损坏!")
with open(path, mode='w+') as file:
... | def save_yaml(obj: Union[Dict, Namespace], path: str = None) -> None:
| if isinstance(obj, Namespace):
obj = namespace_to_dict(obj)
if path is None:
try:
path = obj.pop('path')
except KeyError:
raise KeyError("存储的配置文件损坏!")
with open(path, mode='w+') as file:
yaml.dump(obj, file)
obj['path'] = path
| .load(file, Loader=yaml.SafeLoader)
config['path'] = path
return config
else:
raise ValueError(
f"The config file at {path} has a wrong type!")
def save_yaml(obj: Union[Dict, Namespace], path: str = None) -> None:
| 63 | 64 | 97 | 20 | 43 | izhx/nmnlp | common/config.py | Python | save_yaml | save_yaml | 39 | 49 | 39 | 39 | d377ddfa998f7168c4412c58cf70617cd4564556 | bigcode/the-stack | train |
1f96214df8b3f2ecbab7e644 | train | function | def Rgg010(
directed: bool = False,
verbose: int = 2,
cache_path: str = "graphs/networkrepository",
**additional_graph_kwargs: Dict
) -> EnsmallenGraph:
"""Return new instance of the rgg010 graph.
The graph is automatically retrieved from the NetworkRepository repository.
Parameters
... | def Rgg010(
directed: bool = False,
verbose: int = 2,
cache_path: str = "graphs/networkrepository",
**additional_graph_kwargs: Dict
) -> EnsmallenGraph:
| """Return new instance of the rgg010 graph.
The graph is automatically retrieved from the NetworkRepository repository.
Parameters
-------------------
directed: bool = False,
Wether to load the graph as directed or undirected.
By default false.
verbose: int = 2,
Wet... | train_graph, validation_graph = graph.connected_holdout(
# You can use an 80/20 split the holdout, for example.
train_size=0.8,
# The random state is used to reproduce the holdout.
random_state=42,
# Wether to show a loading bar.
verbose=True
)
# Remember that, ... | 224 | 224 | 748 | 46 | 177 | caufieldjh/ensmallen_graph | bindings/python/ensmallen_graph/datasets/networkrepository/rgg010.py | Python | Rgg010 | Rgg010 | 78 | 178 | 78 | 83 | 94cee8c7862c7a408ca766794b479191e8bc2f08 | bigcode/the-stack | train |
cda5aac58b0060830e106f94 | train | class | class RequestStageType(models.Model):
_name = 'request.stage.type'
_inherit = [
'generic.mixin.name_with_code',
'generic.mixin.uniq_name_code',
]
_description = 'Request Stage Type'
# Defined in generic.mixin.name_with_code
name = fields.Char()
code = fields.Char()
acti... | class RequestStageType(models.Model):
| _name = 'request.stage.type'
_inherit = [
'generic.mixin.name_with_code',
'generic.mixin.uniq_name_code',
]
_description = 'Request Stage Type'
# Defined in generic.mixin.name_with_code
name = fields.Char()
code = fields.Char()
active = fields.Boolean(index=True, defaul... | from odoo import models, fields, api
from .request_stage import DEFAULT_BG_COLOR, DEFAULT_LABEL_COLOR
class RequestStageType(models.Model):
| 30 | 78 | 262 | 7 | 22 | marionumza/vocal_v12 | addons/generic_request/models/request_stage_type.py | Python | RequestStageType | RequestStageType | 5 | 42 | 5 | 5 | 8208daf5da662ef2c4005accd6e6aa0d4df6fbe2 | bigcode/the-stack | train |
8868a414ac7485e939e3c225 | train | function | def token_batch_size_fn(new, count, sofar):
"""Compute batch size based on number of tokens (+padding)"""
global max_sgn_in_batch, max_gls_in_batch, max_txt_in_batch
if count == 1:
max_sgn_in_batch = 0
max_gls_in_batch = 0
max_txt_in_batch = 0
max_sgn_in_batch = max(max_sgn_in_ba... | def token_batch_size_fn(new, count, sofar):
| """Compute batch size based on number of tokens (+padding)"""
global max_sgn_in_batch, max_gls_in_batch, max_txt_in_batch
if count == 1:
max_sgn_in_batch = 0
max_gls_in_batch = 0
max_txt_in_batch = 0
max_sgn_in_batch = max(max_sgn_in_batch, len(new.sgn))
max_gls_in_batch = ma... | more elegant solution for this it at some point.
# pylint: disable=global-at-module-level
global max_sgn_in_batch, max_gls_in_batch, max_txt_in_batch
# pylint: disable=unused-argument,global-variable-undefined
def token_batch_size_fn(new, count, sofar):
| 64 | 64 | 190 | 12 | 51 | SamuelDiai/slt | signjoey/data.py | Python | token_batch_size_fn | token_batch_size_fn | 228 | 241 | 228 | 228 | 56b33ba819d83cf47d5f238a72b74493bf197d10 | bigcode/the-stack | train |
b268fd50f14211c6d4e137ec | train | function | def make_data_iter(
dataset: Dataset,
batch_size: int,
batch_type: str = "sentence",
train: bool = False,
shuffle: bool = False,
) -> Iterator:
"""
Returns a torchtext iterator for a torchtext dataset.
:param dataset: torchtext dataset containing sgn and optionally txt
:param batch_... | def make_data_iter(
dataset: Dataset,
batch_size: int,
batch_type: str = "sentence",
train: bool = False,
shuffle: bool = False,
) -> Iterator:
| """
Returns a torchtext iterator for a torchtext dataset.
:param dataset: torchtext dataset containing sgn and optionally txt
:param batch_size: size of the batches the iterator prepares
:param batch_type: measure batch size by sentence count or by token count
:param train: whether it's trainin... | 2)
sgn_elements = count * max_sgn_in_batch
gls_elements = count * max_gls_in_batch
txt_elements = count * max_txt_in_batch
return max(sgn_elements, gls_elements, txt_elements)
def make_data_iter(
dataset: Dataset,
batch_size: int,
batch_type: str = "sentence",
train: bool = False,
sh... | 96 | 96 | 323 | 43 | 53 | SamuelDiai/slt | signjoey/data.py | Python | make_data_iter | make_data_iter | 244 | 290 | 244 | 250 | 846ca8a69db87bf2e79af8f8b712acfebc7fe892 | bigcode/the-stack | train |
23c5bf7175d9b94e0ef8b738 | train | function | def load_data(data_cfg: dict) -> (Dataset, Dataset, Dataset, Vocabulary, Vocabulary):
"""
Load train, dev and optionally test data as specified in configuration.
Vocabularies are created from the training set with a limit of `voc_limit`
tokens and a minimum token frequency of `voc_min_freq`
(specifi... | def load_data(data_cfg: dict) -> (Dataset, Dataset, Dataset, Vocabulary, Vocabulary):
| """
Load train, dev and optionally test data as specified in configuration.
Vocabularies are created from the training set with a limit of `voc_limit`
tokens and a minimum token frequency of `voc_min_freq`
(specified in the configuration dictionary).
The training data is filtered to include sen... | # coding: utf-8
"""
Data module
"""
import os
import sys
import random
import torch
from torchtext import data
from torchtext.data import Dataset, Iterator
import socket
from signjoey.dataset import SignTranslationDataset
from signjoey.vocabulary import (
build_vocab,
Vocabulary,
UNK_TOKEN,
EOS_TOKEN,
... | 105 | 256 | 1,673 | 20 | 85 | SamuelDiai/slt | signjoey/data.py | Python | load_data | load_data | 24 | 218 | 24 | 24 | a564a0d87dc522d7c13437cb8db684095e3b151a | bigcode/the-stack | train |
9b77c523289460d40d0ca9f3 | train | class | class CreateProject(workflows.Workflow):
slug = "create_project"
name = _("Create Project")
finalize_button_name = _("Create Project")
success_message = _('Created new project "%s".')
failure_message = _('Unable to create project "%s".')
success_url = "horizon:identity:projects:index"
defaul... | class CreateProject(workflows.Workflow):
| slug = "create_project"
name = _("Create Project")
finalize_button_name = _("Create Project")
success_message = _('Created new project "%s".')
failure_message = _('Unable to create project "%s".')
success_url = "horizon:identity:projects:index"
default_steps = (CreateProjectInfo,
... | _roles = api.keystone.get_project_groups_roles(
request, project_id)
except Exception:
exceptions.handle(request,
err_msg,
redirect=reverse(INDEX_URL))
for group_id in groups_roles:
... | 256 | 256 | 904 | 7 | 248 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | CreateProject | CreateProject | 459 | 574 | 459 | 459 | 6ee643f2fc95a18b70158bd091591ec361c33f1b | bigcode/the-stack | train |
8e33ba9f8f53ddace07f3b24 | train | class | class UpdateProjectGroups(workflows.UpdateMembersStep):
action_class = UpdateProjectGroupsAction
available_list_title = _("All Groups")
members_list_title = _("Project Groups")
no_available_text = _("No groups found.")
no_members_text = _("No groups.")
def contribute(self, data, context):
... | class UpdateProjectGroups(workflows.UpdateMembersStep):
| action_class = UpdateProjectGroupsAction
available_list_title = _("All Groups")
members_list_title = _("Project Groups")
no_available_text = _("No groups found.")
no_members_text = _("No groups.")
def contribute(self, data, context):
if data:
try:
roles = api... | _id]
for role_id in roles_ids:
field_name = self.get_member_field_name(role_id)
self.fields[field_name].initial.append(group_id)
class Meta(object):
name = _("Project Groups")
slug = PROJECT_GROUP_MEMBER_SLUG
class UpdateProjectGroups(workflow... | 64 | 64 | 143 | 10 | 53 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | UpdateProjectGroups | UpdateProjectGroups | 437 | 456 | 437 | 437 | 9494e048e5f27a7dbe402674f4a8efdfa9f2ddc2 | bigcode/the-stack | train |
d9911c9844e86e637d4d605d | train | class | class UpdateProjectMembers(workflows.UpdateMembersStep):
action_class = UpdateProjectMembersAction
available_list_title = _("All Users")
members_list_title = _("Project Members")
no_available_text = _("No users found.")
no_members_text = _("No users.")
def contribute(self, data, context):
... | class UpdateProjectMembers(workflows.UpdateMembersStep):
| action_class = UpdateProjectMembersAction
available_list_title = _("All Users")
members_list_title = _("Project Members")
no_available_text = _("No users found.")
no_members_text = _("No users.")
def contribute(self, data, context):
if data:
try:
roles = api.... | _id]
for role_id in roles_ids:
field_name = self.get_member_field_name(role_id)
self.fields[field_name].initial.append(user_id)
class Meta(object):
name = _("Project Members")
slug = PROJECT_USER_MEMBER_SLUG
class UpdateProjectMembers(workflow... | 64 | 64 | 143 | 10 | 53 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | UpdateProjectMembers | UpdateProjectMembers | 339 | 358 | 339 | 339 | 482991eb2eab648211a6016036ff8305596874fd | bigcode/the-stack | train |
d279a83ef6908e3b55134166 | train | class | class NetworkQuotaAction(CommonQuotaAction):
network = forms.IntegerField(min_value=-1, label=_("Networks"))
subnet = forms.IntegerField(min_value=-1, label=_("Subnets"))
port = forms.IntegerField(min_value=-1, label=_("Ports"))
router = forms.IntegerField(min_value=-1, label=_("Routers"))
floatingi... | class NetworkQuotaAction(CommonQuotaAction):
| network = forms.IntegerField(min_value=-1, label=_("Networks"))
subnet = forms.IntegerField(min_value=-1, label=_("Subnets"))
port = forms.IntegerField(min_value=-1, label=_("Ports"))
router = forms.IntegerField(min_value=-1, label=_("Routers"))
floatingip = forms.IntegerField(min_value=-1, label=_(... | tenant_quota_update(request, project_id, **data)
class Meta(object):
name = _("Volume")
slug = 'update_volume_quotas'
help_text = _("Set maximum quotas for the project.")
permissions = ('openstack.roles.admin', 'openstack.services.compute')
class NetworkQuotaAction(CommonQuotaAction... | 68 | 68 | 228 | 8 | 60 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | NetworkQuotaAction | NetworkQuotaAction | 146 | 166 | 146 | 146 | 93f08bdcce7bb7fcf83550ec1516c697fd99a06a | bigcode/the-stack | train |
42588aea3213fb2fc5630ba5 | train | class | class UpdateProjectMembersAction(workflows.MembershipAction):
def __init__(self, request, *args, **kwargs):
super().__init__(request, *args, **kwargs)
err_msg = _('Unable to retrieve user list. Please try again later.')
# Use the domain_id from the project
domain_id = self.initial.ge... | class UpdateProjectMembersAction(workflows.MembershipAction):
| def __init__(self, request, *args, **kwargs):
super().__init__(request, *args, **kwargs)
err_msg = _('Unable to retrieve user list. Please try again later.')
# Use the domain_id from the project
domain_id = self.initial.get("domain_id", None)
project_id = ''
if 'proj... | _TABLE_EXTRA_INFO
for key, value in EXTRA_INFO.items():
form = forms.CharField(label=value, required=False,)
self.fields[key] = form
class Meta(object):
name = _("Project Information")
help_text = _("Create a project to organize users.")
class CreateProjectInfo(wor... | 162 | 162 | 543 | 11 | 151 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | UpdateProjectMembersAction | UpdateProjectMembersAction | 265 | 336 | 265 | 265 | a4c1e0a19b94a1b2101703aad82e417b2c11e4fb | bigcode/the-stack | train |
0c0b2524c641c2d7745ce1bd | train | class | class UpdateQuota(workflows.Workflow):
slug = "update_quotas"
name = _("Edit Quotas")
finalize_button_name = _("Save")
success_message = _('Modified quotas of project')
failure_message = _('Unable to modify quotas of project')
success_url = "horizon:identity:projects:index"
default_steps = (... | class UpdateQuota(workflows.Workflow):
| slug = "update_quotas"
name = _("Edit Quotas")
finalize_button_name = _("Save")
success_message = _('Modified quotas of project')
failure_message = _('Unable to modify quotas of project')
success_url = "horizon:identity:projects:index"
default_steps = (UpdateComputeQuota,
... | = ("project_id", "disabled_quotas")
contributes = quotas.NEUTRON_QUOTA_FIELDS
def allowed(self, request):
return (api.base.is_service_enabled(request, 'network') and
api.neutron.is_quotas_extension_supported(request))
class UpdateQuota(workflows.Workflow):
| 64 | 64 | 86 | 7 | 57 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | UpdateQuota | UpdateQuota | 200 | 209 | 200 | 200 | f9a12b88313044e3b79f95792698512baf23faef | bigcode/the-stack | train |
4c11e5585891f1b15772d293 | train | class | class UpdateProject(workflows.Workflow):
slug = "update_project"
name = _("Edit Project")
finalize_button_name = _("Save")
success_message = _('Modified project "%s".')
failure_message = _('Unable to modify project "%s".')
success_url = "horizon:identity:projects:index"
default_steps = (Upda... | class UpdateProject(workflows.Workflow):
| slug = "update_project"
name = _("Edit Project")
finalize_button_name = _("Save")
success_message = _('Modified project "%s".')
failure_message = _('Unable to modify project "%s".')
success_url = "horizon:identity:projects:index"
default_steps = (UpdateProjectInfo,
Updat... | iev): in case the current project is being edited, its
# 'enabled' field is disabled to prevent changing the field value
# which is always `True` for the current project (because the user
# logged in it). Since Django treats disabled checkbox as providing
# `False` value even if its init... | 256 | 256 | 2,297 | 7 | 249 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | UpdateProject | UpdateProject | 624 | 907 | 624 | 624 | f88f6dead883188363876915aec0ebc934d11bcb | bigcode/the-stack | train |
de9c985f086bc4230edfaa07 | train | class | class CreateProjectInfoAction(workflows.Action):
# Hide the domain_id and domain_name by default
domain_id = forms.CharField(label=_("Domain ID"),
required=False,
widget=forms.HiddenInput())
domain_name = forms.CharField(label=_("Domain Name"),... | class CreateProjectInfoAction(workflows.Action):
# Hide the domain_id and domain_name by default
| domain_id = forms.CharField(label=_("Domain ID"),
required=False,
widget=forms.HiddenInput())
domain_name = forms.CharField(label=_("Domain Name"),
required=False,
widget=forms.Hid... | otas")
finalize_button_name = _("Save")
success_message = _('Modified quotas of project')
failure_message = _('Unable to modify quotas of project')
success_url = "horizon:identity:projects:index"
default_steps = (UpdateComputeQuota,
UpdateVolumeQuota,
Update... | 85 | 85 | 286 | 21 | 64 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | CreateProjectInfoAction | CreateProjectInfoAction | 212 | 246 | 212 | 213 | a55127d8e4db7c99184cf352cf4f189403d0774c | bigcode/the-stack | train |
e799e06738a818d9433bc0d9 | train | class | class CreateProjectInfo(workflows.Step):
action_class = CreateProjectInfoAction
template_name = COMMON_HORIZONTAL_TEMPLATE
contributes = ("domain_id",
"domain_name",
"project_id",
"name",
"description",
"enabled")... | class CreateProjectInfo(workflows.Step):
| action_class = CreateProjectInfoAction
template_name = COMMON_HORIZONTAL_TEMPLATE
contributes = ("domain_id",
"domain_name",
"project_id",
"name",
"description",
"enabled")
def __init__(self, workflow):
... |
for key, value in EXTRA_INFO.items():
form = forms.CharField(label=value, required=False,)
self.fields[key] = form
class Meta(object):
name = _("Project Information")
help_text = _("Create a project to organize users.")
class CreateProjectInfo(workflows.Step):
| 63 | 64 | 92 | 8 | 55 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | CreateProjectInfo | CreateProjectInfo | 249 | 262 | 249 | 249 | bdd1a5f93cb09dc116098095dd660407b6b6aa85 | bigcode/the-stack | train |
83d14d94ff4bedf142534e05 | train | class | class UpdateNetworkQuota(workflows.Step):
action_class = NetworkQuotaAction
template_name = COMMON_HORIZONTAL_TEMPLATE
depends_on = ("project_id", "disabled_quotas")
contributes = quotas.NEUTRON_QUOTA_FIELDS
def allowed(self, request):
return (api.base.is_service_enabled(request, 'network')... | class UpdateNetworkQuota(workflows.Step):
| action_class = NetworkQuotaAction
template_name = COMMON_HORIZONTAL_TEMPLATE
depends_on = ("project_id", "disabled_quotas")
contributes = quotas.NEUTRON_QUOTA_FIELDS
def allowed(self, request):
return (api.base.is_service_enabled(request, 'network') and
api.neutron.is_quotas... | action_class = VolumeQuotaAction
template_name = COMMON_HORIZONTAL_TEMPLATE
depends_on = ("project_id", "disabled_quotas")
contributes = quotas.CINDER_QUOTA_FIELDS
def allowed(self, request):
return cinder.is_volume_service_enabled(request)
class UpdateNetworkQuota(workflows.Step):
| 64 | 64 | 84 | 8 | 56 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | UpdateNetworkQuota | UpdateNetworkQuota | 189 | 197 | 189 | 189 | 79f6210e63e2947a464bef87e49d657299e10ec0 | bigcode/the-stack | train |
f9c411e46a8ec9a6387cc212 | train | class | class ComputeQuotaAction(CommonQuotaAction):
instances = forms.IntegerField(min_value=-1, label=_("Instances"))
cores = forms.IntegerField(min_value=-1, label=_("VCPUs"))
ram = forms.IntegerField(min_value=-1, label=_("RAM (MB)"))
metadata_items = forms.IntegerField(min_value=-1,
... | class ComputeQuotaAction(CommonQuotaAction):
| instances = forms.IntegerField(min_value=-1, label=_("Instances"))
cores = forms.IntegerField(min_value=-1, label=_("VCPUs"))
ram = forms.IntegerField(min_value=-1, label=_("RAM (MB)"))
metadata_items = forms.IntegerField(min_value=-1,
label=_("Metadata Items"))
... | _id']
disabled_quotas = context['disabled_quotas']
data = {key: context[key] for key in
self._quota_fields - disabled_quotas}
if data:
self._tenant_quota_update(request, project_id, data)
@abc.abstractmethod
def _tenant_quota_update(self, request, project_id,... | 90 | 90 | 303 | 8 | 81 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | ComputeQuotaAction | ComputeQuotaAction | 97 | 125 | 97 | 97 | da892c8cdc535995c76f473c55350c50411e0cc0 | bigcode/the-stack | train |
fa5a30cf9efb28dab04a9962 | train | class | class UpdateComputeQuota(workflows.Step):
action_class = ComputeQuotaAction
template_name = COMMON_HORIZONTAL_TEMPLATE
depends_on = ("project_id", "disabled_quotas")
contributes = quotas.NOVA_QUOTA_FIELDS
def allowed(self, request):
return api.base.is_service_enabled(request, 'compute')
| class UpdateComputeQuota(workflows.Step):
| action_class = ComputeQuotaAction
template_name = COMMON_HORIZONTAL_TEMPLATE
depends_on = ("project_id", "disabled_quotas")
contributes = quotas.NOVA_QUOTA_FIELDS
def allowed(self, request):
return api.base.is_service_enabled(request, 'compute')
| (request, project_id, **data)
class Meta(object):
name = _("Network")
slug = 'update_network_quotas'
help_text = _("Set maximum quotas for the project.")
permissions = ('openstack.roles.admin', 'openstack.services.compute')
class UpdateComputeQuota(workflows.Step):
| 64 | 64 | 67 | 8 | 56 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | UpdateComputeQuota | UpdateComputeQuota | 169 | 176 | 169 | 169 | 6eb813c1afc9e825ea5f49f9ff619ade3275acdb | bigcode/the-stack | train |
e4b77b11a8007815008e0dd0 | train | class | class UpdateVolumeQuota(workflows.Step):
action_class = VolumeQuotaAction
template_name = COMMON_HORIZONTAL_TEMPLATE
depends_on = ("project_id", "disabled_quotas")
contributes = quotas.CINDER_QUOTA_FIELDS
def allowed(self, request):
return cinder.is_volume_service_enabled(request)
| class UpdateVolumeQuota(workflows.Step):
| action_class = VolumeQuotaAction
template_name = COMMON_HORIZONTAL_TEMPLATE
depends_on = ("project_id", "disabled_quotas")
contributes = quotas.CINDER_QUOTA_FIELDS
def allowed(self, request):
return cinder.is_volume_service_enabled(request)
| = ComputeQuotaAction
template_name = COMMON_HORIZONTAL_TEMPLATE
depends_on = ("project_id", "disabled_quotas")
contributes = quotas.NOVA_QUOTA_FIELDS
def allowed(self, request):
return api.base.is_service_enabled(request, 'compute')
class UpdateVolumeQuota(workflows.Step):
| 64 | 64 | 65 | 8 | 56 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | UpdateVolumeQuota | UpdateVolumeQuota | 179 | 186 | 179 | 179 | 9f7f84a4a84818e3c384f8beea4a51959203c6ce | bigcode/the-stack | train |
98f4ea7c5d568282b96bd156 | train | class | class CommonQuotaAction(workflows.Action):
_quota_fields = None
def __init__(self, request, *args, **kwargs):
super().__init__(request, *args, **kwargs)
disabled_quotas = self.initial['disabled_quotas']
for field in disabled_quotas:
if field in self.fields:
... | class CommonQuotaAction(workflows.Action):
| _quota_fields = None
def __init__(self, request, *args, **kwargs):
super().__init__(request, *args, **kwargs)
disabled_quotas = self.initial['disabled_quotas']
for field in disabled_quotas:
if field in self.fields:
self.fields[field].required = False
... | import cinder
from openstack_dashboard.api import keystone
from openstack_dashboard.api import nova
from openstack_dashboard.usage import quotas
from openstack_dashboard.utils import identity
LOG = logging.getLogger(__name__)
INDEX_URL = "horizon:identity:projects:index"
ADD_USER_URL = "horizon:identity:projects:cr... | 114 | 114 | 381 | 8 | 106 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | CommonQuotaAction | CommonQuotaAction | 51 | 94 | 51 | 52 | 73ae7b805147115877cb3a598fad50808de7f263 | bigcode/the-stack | train |
ae99628c962fc4ca1b27b44f | train | class | class UpdateProjectInfo(workflows.Step):
action_class = UpdateProjectInfoAction
template_name = COMMON_HORIZONTAL_TEMPLATE
depends_on = ("project_id",)
contributes = ("domain_id",
"domain_name",
"name",
"description",
"enabled")... | class UpdateProjectInfo(workflows.Step):
| action_class = UpdateProjectInfoAction
template_name = COMMON_HORIZONTAL_TEMPLATE
depends_on = ("project_id",)
contributes = ("domain_id",
"domain_name",
"name",
"description",
"enabled")
def __init__(self, workflow):
... | .fields['enabled'].widget.attrs.get('disabled', False):
cleaned_data['enabled'] = True
return cleaned_data
class Meta(object):
name = _("Project Information")
slug = 'update_info'
help_text = _("Edit the project details.")
class UpdateProjectInfo(workflows.Step):
| 63 | 64 | 96 | 8 | 55 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | UpdateProjectInfo | UpdateProjectInfo | 608 | 621 | 608 | 608 | d01345a7620281e329f9d1455f9d56871c570590 | bigcode/the-stack | train |
20c509a723c1644440170f9c | train | class | class UpdateProjectGroupsAction(workflows.MembershipAction):
def __init__(self, request, *args, **kwargs):
super().__init__(request, *args, **kwargs)
err_msg = _('Unable to retrieve group list. Please try again later.')
# Use the domain_id from the project
domain_id = self.initial.ge... | class UpdateProjectGroupsAction(workflows.MembershipAction):
| def __init__(self, request, *args, **kwargs):
super().__init__(request, *args, **kwargs)
err_msg = _('Unable to retrieve group list. Please try again later.')
# Use the domain_id from the project
domain_id = self.initial.get("domain_id", None)
project_id = ''
if 'proj... | ):
name = _("Project Members")
slug = PROJECT_USER_MEMBER_SLUG
class UpdateProjectMembers(workflows.UpdateMembersStep):
action_class = UpdateProjectMembersAction
available_list_title = _("All Users")
members_list_title = _("Project Members")
no_available_text = _("No users found.")
... | 171 | 171 | 571 | 11 | 159 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | UpdateProjectGroupsAction | UpdateProjectGroupsAction | 361 | 434 | 361 | 361 | ba4d51807f12841225020bb8161c7c57ddfbee20 | bigcode/the-stack | train |
a01ba5239661a6d5d9864b7e | train | class | class VolumeQuotaAction(CommonQuotaAction):
volumes = forms.IntegerField(min_value=-1, label=_("Volumes"))
snapshots = forms.IntegerField(min_value=-1, label=_("Volume Snapshots"))
gigabytes = forms.IntegerField(
min_value=-1, label=_("Total Size of Volumes and Snapshots (GiB)"))
_quota_fields ... | class VolumeQuotaAction(CommonQuotaAction):
| volumes = forms.IntegerField(min_value=-1, label=_("Volumes"))
snapshots = forms.IntegerField(min_value=-1, label=_("Volume Snapshots"))
gigabytes = forms.IntegerField(
min_value=-1, label=_("Total Size of Volumes and Snapshots (GiB)"))
_quota_fields = quotas.CINDER_QUOTA_FIELDS
def _tenan... | (request, project_id, **data)
class Meta(object):
name = _("Compute")
slug = 'update_compute_quotas'
help_text = _("Set maximum quotas for the project.")
permissions = ('openstack.roles.admin', 'openstack.services.compute')
class VolumeQuotaAction(CommonQuotaAction):
| 64 | 64 | 164 | 8 | 56 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | VolumeQuotaAction | VolumeQuotaAction | 128 | 143 | 128 | 128 | a8159d88616f1789aa52f07252cc36216dc200a3 | bigcode/the-stack | train |
cd677a1aaf348c22df1ef0f0 | train | class | class UpdateProjectInfoAction(CreateProjectInfoAction):
enabled = forms.BooleanField(required=False, label=_("Enabled"))
domain_name = forms.CharField(label=_("Domain Name"),
required=False,
widget=forms.HiddenInput())
def __init__(self, r... | class UpdateProjectInfoAction(CreateProjectInfoAction):
| enabled = forms.BooleanField(required=False, label=_("Enabled"))
domain_name = forms.CharField(label=_("Domain Name"),
required=False,
widget=forms.HiddenInput())
def __init__(self, request, initial, *args, **kwargs):
super().__ini... | 'and update project quotas.')
% groups_to_add)
def handle(self, request, data):
project = self._create_project(request, data)
if not project:
return False
project_id = project.id
self._update_project_members(request, data, project_id)
... | 88 | 88 | 296 | 10 | 77 | lianggengdino/kolla-build | openstack_dashboard/dashboards/identity/projects/workflows.py | Python | UpdateProjectInfoAction | UpdateProjectInfoAction | 577 | 605 | 577 | 577 | 740c49e92d396082cc81235a3e87e3bdfcabff42 | bigcode/the-stack | train |
1b7ca3224f570e8200222ea1 | train | function | async def request(pkg):
res = await session.get(URL, params={"name": pkg})
return res.json()
| async def request(pkg):
| res = await session.get(URL, params={"name": pkg})
return res.json()
| # MIT licensed
# Copyright (c) 2013-2020 lilydjwg <lilydjwg@gmail.com>, et al.
from nvchecker.api import session, GetVersionError
URL = 'https://www.archlinux.org/packages/search/json/'
async def request(pkg):
| 58 | 64 | 24 | 5 | 53 | trathborne/nvchecker | nvchecker_source/archpkg.py | Python | request | request | 8 | 10 | 8 | 8 | d9d6e710227ca7affbbe8cdc7514432ee8ddd578 | bigcode/the-stack | train |
f0b8075836bc4633d23b22ca | train | function | async def get_version(name, conf, *, cache, **kwargs):
pkg = conf.get('archpkg') or name
strip_release = conf.get('strip_release', False)
provided = conf.get('provided')
data = await cache.get(pkg, request)
if not data['results']:
raise GetVersionError('Arch package not found')
r = [r for r in data['... | async def get_version(name, conf, *, cache, **kwargs):
| pkg = conf.get('archpkg') or name
strip_release = conf.get('strip_release', False)
provided = conf.get('provided')
data = await cache.get(pkg, request)
if not data['results']:
raise GetVersionError('Arch package not found')
r = [r for r in data['results'] if r['repo'] != 'testing'][0]
if provided:... | .
from nvchecker.api import session, GetVersionError
URL = 'https://www.archlinux.org/packages/search/json/'
async def request(pkg):
res = await session.get(URL, params={"name": pkg})
return res.json()
async def get_version(name, conf, *, cache, **kwargs):
| 64 | 64 | 187 | 14 | 50 | trathborne/nvchecker | nvchecker_source/archpkg.py | Python | get_version | get_version | 12 | 34 | 12 | 12 | 60788e07b0efa60543a89c24a5bbbd8c85f14cdf | bigcode/the-stack | train |
b5c09d2e1106df41a2f218d1 | train | function | def parse_line(line):
"""
Reads single line from cAdvisor logfile
:param line: single line as str
:returns: OrderedDict of line read
"""
tmp_res = OrderedDict()
# split line into array of "key=value" metrics
metrics = line.split()
for metric in metrics:
key, value = metric.... | def parse_line(line):
| """
Reads single line from cAdvisor logfile
:param line: single line as str
:returns: OrderedDict of line read
"""
tmp_res = OrderedDict()
# split line into array of "key=value" metrics
metrics = line.split()
for metric in metrics:
key, value = metric.split('=')
tmp... | val = float(results[cnt][field])/results[cnt]['count']
results[cnt][field] = '{0:.2f}'.format(val)
results[cnt].pop('count')
#sort results
results[cnt] = OrderedDict(sorted(results[cnt].items()))
return results
def parse_line(line):
| 64 | 64 | 92 | 5 | 58 | shreyagupta30/vineperf | tools/collectors/cadvisor/cadvisor.py | Python | parse_line | parse_line | 203 | 218 | 203 | 203 | 2e382b973b5811814a81e17f8bcb98e05830c474 | bigcode/the-stack | train |
4601344d6623c7addde863a3 | train | function | def calculate_average(results):
"""
Calculates average for container stats
"""
for cnt in results:
for field in results[cnt]:
if field != 'count':
val = float(results[cnt][field])/results[cnt]['count']
results[cnt][field] = '{0:.2f}'.format(val)
... | def calculate_average(results):
| """
Calculates average for container stats
"""
for cnt in results:
for field in results[cnt]:
if field != 'count':
val = float(results[cnt][field])/results[cnt]['count']
results[cnt][field] = '{0:.2f}'.format(val)
results[cnt].pop('count')
... | continue
continue
result[cnt][field] = float(result[cnt][field]) + val
result[cnt]['count'] += 1
previous[cnt] = tmp_res
# calculate average results for containers
result = calculate_average(result)
re... | 64 | 64 | 96 | 5 | 58 | shreyagupta30/vineperf | tools/collectors/cadvisor/cadvisor.py | Python | calculate_average | calculate_average | 186 | 200 | 186 | 186 | f7ca1fe1a329cb276e3524b7937e1aef1d98692f | bigcode/the-stack | train |
61a870e63034fd0f95914c0e | train | class | class Cadvisor(collector.ICollector):
"""A collector of container metrics based on cAdvisor
It starts cadvisor and collects metrics.
"""
def __init__(self, results_dir, test_name):
"""
Initialize collection of statistics
"""
self._logger = logging.getLogger(__name__)
... | class Cadvisor(collector.ICollector):
| """A collector of container metrics based on cAdvisor
It starts cadvisor and collects metrics.
"""
def __init__(self, results_dir, test_name):
"""
Initialize collection of statistics
"""
self._logger = logging.getLogger(__name__)
self.resultsdir = results_dir
... | # Copyright 2020 University Of Delhi.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | 200 | 210 | 702 | 8 | 192 | shreyagupta30/vineperf | tools/collectors/cadvisor/cadvisor.py | Python | Cadvisor | Cadvisor | 32 | 125 | 32 | 32 | a6ae50d9565a98a93199ae058af21469c30db1bf | bigcode/the-stack | train |
b7505afabae63263354d1ae3 | train | function | def cadvisor_log_result(filename, containers):
"""
Processes cAdvisor logfile and returns average results
:param filename: Name of cadvisor logfile
:param containers: List of container names
:returns: Result as average stats of Containers
"""
result = OrderedDict()
previous = OrderedDi... | def cadvisor_log_result(filename, containers):
| """
Processes cAdvisor logfile and returns average results
:param filename: Name of cadvisor logfile
:param containers: List of container names
:returns: Result as average stats of Containers
"""
result = OrderedDict()
previous = OrderedDict()
logfile = open(filename, 'r')
with... | ['memory_usage', 'memory_working_set']:
value = round(float(value) / 1024 / 1024, 4)
postfix = 'MB'
if key in ['rx_bytes', 'tx_bytes']:
value = round(float(value) / 1024 / 1024, 4)
postfix = 'mBps'
logging... | 108 | 108 | 363 | 9 | 99 | shreyagupta30/vineperf | tools/collectors/cadvisor/cadvisor.py | Python | cadvisor_log_result | cadvisor_log_result | 128 | 183 | 128 | 128 | 0f07fa0a20bdbaa8be5eed28a15ba01282e4f163 | bigcode/the-stack | train |
db5eae51b1b0b23073bd2370 | train | function | @pytest.fixture
def chia_pet_peak_quality_metric(testapp, award, encode_lab, analysis_step_run_chia_peak_calling, chia_peaks):
item = {
"step_run": analysis_step_run_chia_peak_calling['@id'],
"award": award["uuid"],
"lab": encode_lab["uuid"],
"assay_term_name": 'ChIA-PET',
"q... | @pytest.fixture
def chia_pet_peak_quality_metric(testapp, award, encode_lab, analysis_step_run_chia_peak_calling, chia_peaks):
| item = {
"step_run": analysis_step_run_chia_peak_calling['@id'],
"award": award["uuid"],
"lab": encode_lab["uuid"],
"assay_term_name": 'ChIA-PET',
"quality_metric_of": [chia_peaks['@id']],
"binding_peaks": 7831
}
return testapp.post_json('/chia_pet_peak_enric... | import pytest
@pytest.fixture
def chia_pet_peak_quality_metric(testapp, award, encode_lab, analysis_step_run_chia_peak_calling, chia_peaks):
| 33 | 64 | 131 | 30 | 2 | procha2/encoded | src/encoded/tests/fixtures/schemas/chia_pet_peak_enrichment_quality_metric.py | Python | chia_pet_peak_quality_metric | chia_pet_peak_quality_metric | 4 | 15 | 4 | 5 | ec7f07dd5fe7f8b98e4f1ac465701f63b7876b52 | bigcode/the-stack | train |
4b0348f62a759d2519f3c923 | train | class | class DTLSettings(LazySettings):
def _setup(self, name=None):
"""
Load the settings module pointed to by the environment variable. This
is used the first time we need any settings at all, if the user has not
previously configured the settings manually.
"""
try:
... | class DTLSettings(LazySettings):
| def _setup(self, name=None):
"""
Load the settings module pointed to by the environment variable. This
is used the first time we need any settings at all, if the user has not
previously configured the settings manually.
"""
try:
settings_module = os.enviro... | import os
from django.conf import LazySettings, Settings
from django.core.exceptions import ImproperlyConfigured
ENVIRONMENT_VARIABLE = "DTL_SETTINGS_MODULE"
class DTLSettings(LazySettings):
| 41 | 64 | 132 | 9 | 32 | rocktavious/DevToolsLib | DTL/conf/__init__.py | Python | DTLSettings | DTLSettings | 7 | 23 | 7 | 8 | f2568e691a12de86be4be9b270d06b00b5659a9e | bigcode/the-stack | train |
a741e9b02dfc35e284b1799a | train | function | def most_relevant_ch(traces):
"""
Calculates the most relevant channel for an Unit.
Estimates the channel where the max-min difference of the average traces is greatest.
traces : ndarray
ndarray of shape (nSpikes, nChannels, nSamples)
"""
n_channels = traces.shape[1]
avg = np.mean(t... | def most_relevant_ch(traces):
| """
Calculates the most relevant channel for an Unit.
Estimates the channel where the max-min difference of the average traces is greatest.
traces : ndarray
ndarray of shape (nSpikes, nChannels, nSamples)
"""
n_channels = traces.shape[1]
avg = np.mean(traces, axis=0)
max_min = ... | tolist()))
nSpikes = np.diff([0] + list(units_table['spike_times_index'].data[:])).tolist()
ind = np.where(np.array(units_table.id[:]) == unit_id)[0][0]
return nSpikes[ind]
def most_relevant_ch(traces):
| 64 | 64 | 131 | 8 | 56 | yarikoptic/spikeextractors | spikeextractors/extractors/nwbextractors/nwbextractors.py | Python | most_relevant_ch | most_relevant_ch | 102 | 118 | 102 | 102 | 4c4dafc02c160af8f15c4e4dfd8b3372b1fa3acf | bigcode/the-stack | train |
7555c5b099afd47b05b132f4 | train | function | def find_all_unit_property_names(properties_dict: dict, features_dict: dict):
"""
Finds all existing units properties and units spikes features in the sorting
dictionaries.
"""
properties_set = set()
for k, v in properties_dict.items():
properties_set.update(list(v.keys()))
features... | def find_all_unit_property_names(properties_dict: dict, features_dict: dict):
| """
Finds all existing units properties and units spikes features in the sorting
dictionaries.
"""
properties_set = set()
for k, v in properties_dict.items():
properties_set.update(list(v.keys()))
features_set = set()
for k, v in features_dict.items():
features_set.updat... | _name):
all_row_ids = list(dynamic_table.id[:])
if row_ids is None:
row_ids = all_row_ids
return [dynamic_table[property_name][all_row_ids.index(x)] for x in row_ids]
def find_all_unit_property_names(properties_dict: dict, features_dict: dict):
| 64 | 64 | 93 | 16 | 48 | yarikoptic/spikeextractors | spikeextractors/extractors/nwbextractors/nwbextractors.py | Python | find_all_unit_property_names | find_all_unit_property_names | 75 | 88 | 75 | 75 | 94962c8662d3de8652aff031417502cb5ef7b185 | bigcode/the-stack | train |
030498611bb00855fb147b5d | train | function | def get_nspikes(units_table, unit_id):
"""Returns the number of spikes for chosen unit."""
check_nwb_install()
if unit_id not in units_table.id[:]:
raise ValueError(str(unit_id) + " is an invalid unit_id. "
"Valid ids: " + str(units_table.id[:].tolist()))
nSpikes = np.di... | def get_nspikes(units_table, unit_id):
| """Returns the number of spikes for chosen unit."""
check_nwb_install()
if unit_id not in units_table.id[:]:
raise ValueError(str(unit_id) + " is an invalid unit_id. "
"Valid ids: " + str(units_table.id[:].tolist()))
nSpikes = np.diff([0] + list(units_table['spike_times_... | set()
for k, v in properties_dict.items():
properties_set.update(list(v.keys()))
features_set = set()
for k, v in features_dict.items():
features_set.update(list(v.keys()))
return properties_set, features_set
def get_nspikes(units_table, unit_id):
| 64 | 64 | 127 | 12 | 51 | yarikoptic/spikeextractors | spikeextractors/extractors/nwbextractors/nwbextractors.py | Python | get_nspikes | get_nspikes | 91 | 99 | 91 | 91 | b1f3b52c324189262f50224f1467ed32d39b5f24 | bigcode/the-stack | train |
3acb9adbdaf8f3ed25ca0faa | train | function | def get_dynamic_table_property(dynamic_table, *, row_ids=None, property_name):
all_row_ids = list(dynamic_table.id[:])
if row_ids is None:
row_ids = all_row_ids
return [dynamic_table[property_name][all_row_ids.index(x)] for x in row_ids]
| def get_dynamic_table_property(dynamic_table, *, row_ids=None, property_name):
| all_row_ids = list(dynamic_table.id[:])
if row_ids is None:
row_ids = all_row_ids
return [dynamic_table[property_name][all_row_ids.index(x)] for x in row_ids]
| if property_name in dynamic_table:
# TODO
raise NotImplementedError
else:
dynamic_table.add_column(
name=property_name,
description=description,
data=values,
index=index
)
def get_dynamic_table_prope... | 64 | 64 | 62 | 16 | 48 | yarikoptic/spikeextractors | spikeextractors/extractors/nwbextractors/nwbextractors.py | Python | get_dynamic_table_property | get_dynamic_table_property | 68 | 72 | 68 | 68 | 93d1ef6ed8c2ff98b76c6800c50cd1cd59d44b9c | bigcode/the-stack | train |
b99dea128959b4bab9bbfe10 | train | function | def check_nwb_install():
assert HAVE_NWB, "To use the Nwb extractors, install pynwb: \n\n pip install pynwb\n\n"
| def check_nwb_install():
| assert HAVE_NWB, "To use the Nwb extractors, install pynwb: \n\n pip install pynwb\n\n"
| BFile
from pynwb.ecephys import ElectricalSeries
from pynwb.ecephys import ElectrodeGroup
from hdmf.data_utils import DataChunkIterator
HAVE_NWB = True
except ModuleNotFoundError:
HAVE_NWB = False
def check_nwb_install():
| 64 | 64 | 35 | 6 | 57 | yarikoptic/spikeextractors | spikeextractors/extractors/nwbextractors/nwbextractors.py | Python | check_nwb_install | check_nwb_install | 24 | 25 | 24 | 24 | c246613590f7a59d27294de5e6862e559c49d375 | bigcode/the-stack | train |
4ad76874a7225b93af6600b2 | train | function | def set_dynamic_table_property(dynamic_table, row_ids, property_name, values, index=False,
default_value=np.nan, description='no description'):
check_nwb_install()
if not isinstance(row_ids, list) or not all(isinstance(x, int) for x in row_ids):
raise TypeError("'ids' must... | def set_dynamic_table_property(dynamic_table, row_ids, property_name, values, index=False,
default_value=np.nan, description='no description'):
| check_nwb_install()
if not isinstance(row_ids, list) or not all(isinstance(x, int) for x in row_ids):
raise TypeError("'ids' must be a list of integers")
ids = list(dynamic_table.id[:])
if any([i not in ids for i in row_ids]):
raise ValueError("'ids' contains values outside the range of ... | import ElectrodeGroup
from hdmf.data_utils import DataChunkIterator
HAVE_NWB = True
except ModuleNotFoundError:
HAVE_NWB = False
def check_nwb_install():
assert HAVE_NWB, "To use the Nwb extractors, install pynwb: \n\n pip install pynwb\n\n"
def set_dynamic_table_property(dynamic_table, row_ids, pro... | 102 | 102 | 343 | 30 | 72 | yarikoptic/spikeextractors | spikeextractors/extractors/nwbextractors/nwbextractors.py | Python | set_dynamic_table_property | set_dynamic_table_property | 28 | 65 | 28 | 29 | 95d48c129a2c68bc50246923fbfddfcd970cd838 | bigcode/the-stack | train |
0792f3ae851cce0c7637677d | train | class | class NwbSortingExtractor(se.SortingExtractor):
extractor_name = 'NwbSortingExtractor'
installed = HAVE_NWB # check at class level if installed or not
is_writable = True
mode = 'file'
installation_mesg = "To use the Nwb extractors, install pynwb: \n\n pip install pynwb\n\n"
def __init__(self, ... | class NwbSortingExtractor(se.SortingExtractor):
| extractor_name = 'NwbSortingExtractor'
installed = HAVE_NWB # check at class level if installed or not
is_writable = True
mode = 'file'
installation_mesg = "To use the Nwb extractors, install pynwb: \n\n pip install pynwb\n\n"
def __init__(self, file_path, electrical_series=None, sampling_freq... | 'identifier': str(uuid.uuid4()),
'session_start_time': datetime.now()}
nwbfile = NWBFile(**metadata['NWBFile'])
# Add devices
nwbfile = se.NwbRecordingExtractor.add_devices(
recording=recording,
nwbfile=... | 256 | 256 | 1,745 | 10 | 246 | yarikoptic/spikeextractors | spikeextractors/extractors/nwbextractors/nwbextractors.py | Python | NwbSortingExtractor | NwbSortingExtractor | 576 | 773 | 576 | 576 | 7bb3ebc8c1c91cc7a00fb6a24dbbd06029a1cf0c | bigcode/the-stack | train |
f2ab7e0b29ad6bb02d209809 | train | function | def update_dict(d, u):
for k, v in u.items():
if isinstance(v, abc.Mapping):
d[k] = update_dict(d.get(k, {}), v)
else:
d[k] = v
return d
| def update_dict(d, u):
| for k, v in u.items():
if isinstance(v, abc.Mapping):
d[k] = update_dict(d.get(k, {}), v)
else:
d[k] = v
return d
| , axis=0)
max_min = np.zeros(n_channels)
for ch in range(n_channels):
max_min[ch] = avg[ch, :].max() - avg[ch, :].min()
relevant_ch = np.argmax(max_min)
return relevant_ch
def update_dict(d, u):
| 64 | 64 | 53 | 7 | 56 | yarikoptic/spikeextractors | spikeextractors/extractors/nwbextractors/nwbextractors.py | Python | update_dict | update_dict | 121 | 127 | 121 | 121 | 95c7184e6e55ecc04fe9c223a83f19d72cca8649 | bigcode/the-stack | train |
67b2f3a2081cbf4a7c1828ec | train | class | class NwbRecordingExtractor(se.RecordingExtractor):
extractor_name = 'NwbRecording'
has_default_locations = True
installed = HAVE_NWB # check at class level if installed or not
is_writable = True
mode = 'file'
installation_mesg = "To use the Nwb extractors, install pynwb: \n\n pip install pynwb... | class NwbRecordingExtractor(se.RecordingExtractor):
| extractor_name = 'NwbRecording'
has_default_locations = True
installed = HAVE_NWB # check at class level if installed or not
is_writable = True
mode = 'file'
installation_mesg = "To use the Nwb extractors, install pynwb: \n\n pip install pynwb\n\n"
def __init__(self, file_path, electrical_... | (units_table.id[:].tolist()))
nSpikes = np.diff([0] + list(units_table['spike_times_index'].data[:])).tolist()
ind = np.where(np.array(units_table.id[:]) == unit_id)[0][0]
return nSpikes[ind]
def most_relevant_ch(traces):
"""
Calculates the most relevant channel for an Unit.
Estimates the chan... | 256 | 256 | 4,063 | 10 | 245 | yarikoptic/spikeextractors | spikeextractors/extractors/nwbextractors/nwbextractors.py | Python | NwbRecordingExtractor | NwbRecordingExtractor | 130 | 573 | 130 | 130 | a87ea5ab0122b9297ee3f1487c94f55c67896cdf | bigcode/the-stack | train |
337af40f6d068f4a7098a03d | train | function | def test_prod():
assert prod(()) == 1
assert prod((2,)) == 2
assert prod((2, 3)) == 6
n = np.iinfo(np.int64).max
assert prod((n, 2)) == n * 2
| def test_prod():
| assert prod(()) == 1
assert prod((2,)) == 2
assert prod((2, 3)) == 6
n = np.iinfo(np.int64).max
assert prod((n, 2)) == n * 2
| import numpy as np
from rechunker.compat import prod
def test_prod():
| 16 | 64 | 64 | 4 | 11 | andrewbrettin/rechunker | tests/test_compat.py | Python | test_prod | test_prod | 5 | 10 | 5 | 5 | 1d652c8feca3e69e6f234008bb157fff19b08cd0 | bigcode/the-stack | train |
30a851a6a46c1948bf1dd6a1 | train | function | def confusion_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""
Compute a confusion matrix between two sets of integer vectors
Parameters
----------
a: ndarray of shape (n_samples,)
First vector of integers
b: ndarray of shape (n_samples,)
Second vector of integers
R... | def confusion_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
| """
Compute a confusion matrix between two sets of integer vectors
Parameters
----------
a: ndarray of shape (n_samples,)
First vector of integers
b: ndarray of shape (n_samples,)
Second vector of integers
Returns
-------
confusion_matrix: ndarray of shape (a_uniqu... | *train_proportion)))
y_train = y[X_train.index]
X_test = X.drop(X_train.index)
y_test = y[X_test.index]
return X_train, y_train, X_test, y_test
def confusion_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
| 64 | 64 | 138 | 17 | 46 | giladh7/IML.HUJI | IMLearn/utils/utils.py | Python | confusion_matrix | confusion_matrix | 47 | 65 | 47 | 47 | 65a030fe5ba3fd16d540ce68b61a372d11ddefdc | bigcode/the-stack | train |
eaca95ea2d738fbd748bf900 | train | function | def split_train_test(X: pd.DataFrame, y: pd.Series, train_proportion: float = .75) \
-> Tuple[pd.DataFrame, pd.Series, pd.DataFrame, pd.Series]:
"""
Randomly split given sample to a training- and testing sample
Parameters
----------
X : DataFrame of shape (n_samples, n_features)
Dat... | def split_train_test(X: pd.DataFrame, y: pd.Series, train_proportion: float = .75) \
-> Tuple[pd.DataFrame, pd.Series, pd.DataFrame, pd.Series]:
| """
Randomly split given sample to a training- and testing sample
Parameters
----------
X : DataFrame of shape (n_samples, n_features)
Data frame of samples and feature values.
y : Series of shape (n_samples, )
Responses corresponding samples in data frame.
train_proportio... | from typing import Tuple
import numpy as np
import pandas as pd
def split_train_test(X: pd.DataFrame, y: pd.Series, train_proportion: float = .75) \
-> Tuple[pd.DataFrame, pd.Series, pd.DataFrame, pd.Series]:
| 58 | 104 | 347 | 43 | 14 | giladh7/IML.HUJI | IMLearn/utils/utils.py | Python | split_train_test | split_train_test | 6 | 44 | 6 | 7 | 5af6bdcd4735e811ca06aff350bec5ca691e4211 | bigcode/the-stack | train |
e44a9346c8353bd5576263d4 | train | function | def main():
fire.Fire(TweetPhish())
| def main():
| fire.Fire(TweetPhish())
| import fire
from tweetphish import TweetPhish
def main():
| 15 | 64 | 11 | 3 | 11 | MSAdministrator/tweet-phish | tweetphish/__main__.py | Python | main | main | 5 | 6 | 5 | 5 | edf2aedee4fcff7eeb3e09562f0d683ff1cc48a1 | bigcode/the-stack | train |
8294067774c693d5c612c6fe | train | class | class TestV1ClusterRoleBinding(unittest.TestCase):
""" V1ClusterRoleBinding unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1ClusterRoleBinding(self):
"""
Test V1ClusterRoleBinding
"""
# FIXME: construct object with mandatory... | class TestV1ClusterRoleBinding(unittest.TestCase):
| """ V1ClusterRoleBinding unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1ClusterRoleBinding(self):
"""
Test V1ClusterRoleBinding
"""
# FIXME: construct object with mandatory attributes with example values
#model = ku... |
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v1_cluster_role_binding import V1ClusterRoleBinding
class TestV1ClusterRoleBinding(unittest.TestCase):
| 64 | 64 | 99 | 11 | 52 | TomasTomecek/kubernetes-python | kubernetes/test/test_v1_cluster_role_binding.py | Python | TestV1ClusterRoleBinding | TestV1ClusterRoleBinding | 25 | 40 | 25 | 25 | f22677b5be3a9162cc9eb2b01e814a9d3ac701eb | bigcode/the-stack | train |
cc77535bf603aa61fda64980 | train | class | class Folder(RootFolder):
pass
| class Folder(RootFolder):
| pass
| from jenni.tests.unittestutils import RootFolder
class Folder(RootFolder):
| 17 | 64 | 9 | 6 | 10 | synamedia-jenni/Jenni | jenni/tests/params/__init__.py | Python | Folder | Folder | 4 | 5 | 4 | 4 | 090a85e729341c5dc8d359c1f9249ce9bb1cb4c8 | bigcode/the-stack | train |
b370e4b094be72acba877fe9 | train | function | def parse_kafka_version(api_version):
version = StrictVersion(api_version).version
if not (0, 9) <= version < (3, 0):
raise ValueError(api_version)
return version
| def parse_kafka_version(api_version):
| version = StrictVersion(api_version).version
if not (0, 9) <= version < (3, 0):
raise ValueError(api_version)
return version
| PY_35"]
try:
from asyncio import ensure_future
except ImportError:
exec("from asyncio import async as ensure_future")
def create_future(loop):
try:
return loop.create_future()
except AttributeError:
return asyncio.Future(loop=loop)
def parse_kafka_version(api_version):
| 64 | 64 | 47 | 8 | 56 | spencerpomme/Public-Transit-Status-with-Apache-Kafka | consumers/venv/lib/python3.7/site-packages/aiokafka/util.py | Python | parse_kafka_version | parse_kafka_version | 24 | 28 | 24 | 24 | 7d5913f6454488f0138bd2723c1ae200667d007d | bigcode/the-stack | train |
cdb017906c2cb4c1c87be369 | train | function | def create_future(loop):
try:
return loop.create_future()
except AttributeError:
return asyncio.Future(loop=loop)
| def create_future(loop):
| try:
return loop.create_future()
except AttributeError:
return asyncio.Future(loop=loop)
| .version import StrictVersion
from .structs import TopicPartition, OffsetAndMetadata
__all__ = ["ensure_future", "create_future", "PY_35"]
try:
from asyncio import ensure_future
except ImportError:
exec("from asyncio import async as ensure_future")
def create_future(loop):
| 64 | 64 | 27 | 5 | 59 | spencerpomme/Public-Transit-Status-with-Apache-Kafka | consumers/venv/lib/python3.7/site-packages/aiokafka/util.py | Python | create_future | create_future | 17 | 21 | 17 | 17 | 723c899ef1c08a2c95bbeed526721daddc91c6ad | bigcode/the-stack | train |
c431d49de907a5857cdd3439 | train | function | def commit_structure_validate(offsets):
# validate `offsets` structure
if not offsets or not isinstance(offsets, dict):
raise ValueError(offsets)
formatted_offsets = {}
for tp, offset_and_metadata in offsets.items():
if not isinstance(tp, TopicPartition):
raise ValueError("K... | def commit_structure_validate(offsets):
# validate `offsets` structure
| if not offsets or not isinstance(offsets, dict):
raise ValueError(offsets)
formatted_offsets = {}
for tp, offset_and_metadata in offsets.items():
if not isinstance(tp, TopicPartition):
raise ValueError("Key should be TopicPartition instance")
if isinstance(offset_and_me... | )
def parse_kafka_version(api_version):
version = StrictVersion(api_version).version
if not (0, 9) <= version < (3, 0):
raise ValueError(api_version)
return version
def commit_structure_validate(offsets):
# validate `offsets` structure
| 64 | 64 | 155 | 16 | 47 | spencerpomme/Public-Transit-Status-with-Apache-Kafka | consumers/venv/lib/python3.7/site-packages/aiokafka/util.py | Python | commit_structure_validate | commit_structure_validate | 31 | 53 | 31 | 32 | a016e12de072355402b9412a48f5f29d30c36b05 | bigcode/the-stack | train |
bf1b0e7f3c2fcf9fb449379b | train | class | class LogSenseCommand(CDBBuffer):
operation_code = be_uint_field(where=bytes_ref[0], set_before_pack=0x4d)
sp = be_uint_field(where=bytes_ref[1].bits[0])
page_code = be_uint_field(where=bytes_ref[2].bits[0:6])
pc = be_uint_field(where=bytes_ref[2].bits[6:8])
subpage_code = be_uint_field(where=bytes_... | class LogSenseCommand(CDBBuffer):
| operation_code = be_uint_field(where=bytes_ref[0], set_before_pack=0x4d)
sp = be_uint_field(where=bytes_ref[1].bits[0])
page_code = be_uint_field(where=bytes_ref[2].bits[0:6])
pc = be_uint_field(where=bytes_ref[2].bits[6:8])
subpage_code = be_uint_field(where=bytes_ref[3])
parameter_pointer = be... | from infi.asi.cdb import CDBBuffer
from infi.asi import SCSIReadCommand
from infi.asi.cdb.control import ControlBuffer, DEFAULT_CONTROL_BUFFER
from infi.instruct.buffer import *
from infi.instruct.buffer.macros import *
class LogSenseCommand(CDBBuffer):
| 65 | 85 | 284 | 8 | 57 | jasonjorge/infi.asi | src/infi/asi/cdb/log_sense.py | Python | LogSenseCommand | LogSenseCommand | 8 | 30 | 8 | 8 | 65f1262a264f0332fd040c1f62db6d61729da466 | bigcode/the-stack | train |
ba0fcb993e26a5b9db3c928f | train | function | def _f( function ):
return _p.createFunction( function,_p.PLATFORM.WGL,'WGL_EXT_colorspace',error_checker=_errors._error_checker)
| def _f( function ):
| return _p.createFunction( function,_p.PLATFORM.WGL,'WGL_EXT_colorspace',error_checker=_errors._error_checker)
| GL import _types as _cs
# End users want this...
from OpenGL.raw.WGL._types import *
from OpenGL.raw.WGL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'WGL_EXT_colorspace'
def _f( function ):
| 64 | 64 | 36 | 7 | 57 | JE-Chen/je_old_repo | OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/raw/WGL/EXT/colorspace.py | Python | _f | _f | 12 | 13 | 12 | 12 | 6f89add4907d87b542acae677770abe6f6b7ab79 | bigcode/the-stack | train |
bb5310678bcb0b44632532f7 | train | class | class Provider(BankProvider):
bban_format = '################'
country_code = 'AT'
| class Provider(BankProvider):
| bban_format = '################'
country_code = 'AT'
| from .. import Provider as BankProvider
class Provider(BankProvider):
| 14 | 64 | 21 | 6 | 7 | m2jobe/c_x | src/djangoreactredux/djrenv/lib/python3.5/site-packages/faker/providers/bank/de_AT/__init__.py | Python | Provider | Provider | 3 | 5 | 3 | 3 | 7bd30681e129b73cd82aa8ebba4fe3bf8f3f6349 | bigcode/the-stack | train |
9a0621e9ef466d3aa3a074ff | train | class | class OneBotAdapterException(AdapterException):
def __init__(self):
super().__init__("onebot")
| class OneBotAdapterException(AdapterException):
| def __init__(self):
super().__init__("onebot")
| import AdapterException
from nonebot.exception import ActionFailed as BaseActionFailed
from nonebot.exception import NetworkError as BaseNetworkError
from nonebot.exception import NoLogException as BaseNoLogException
from nonebot.exception import ApiNotAvailable as BaseApiNotAvailable
class OneBotAdapterException(Adap... | 64 | 64 | 23 | 8 | 55 | nonebot/adapter-onebot | nonebot/adapters/onebot/exception.py | Python | OneBotAdapterException | OneBotAdapterException | 17 | 19 | 17 | 17 | db51bf4d8bc0fa80f0fad985d48a567ce5c13614 | bigcode/the-stack | train |
b01ff150f9a8a8932f075664 | train | class | class ApiNotAvailable(BaseApiNotAvailable, OneBotAdapterException):
pass
| class ApiNotAvailable(BaseApiNotAvailable, OneBotAdapterException):
| pass
| __()
self.msg: Optional[str] = msg
"""错误原因"""
def __repr__(self):
return f"<NetWorkError message={self.msg}>"
def __str__(self):
return self.__repr__()
class ApiNotAvailable(BaseApiNotAvailable, OneBotAdapterException):
| 63 | 64 | 17 | 14 | 50 | nonebot/adapter-onebot | nonebot/adapters/onebot/exception.py | Python | ApiNotAvailable | ApiNotAvailable | 63 | 64 | 63 | 63 | b1562eedce17aed8510382600d5454a2babd2d54 | bigcode/the-stack | train |
88e441976bfa80d83aecf50e | train | class | class NoLogException(BaseNoLogException, OneBotAdapterException):
pass
| class NoLogException(BaseNoLogException, OneBotAdapterException):
| pass
| nonebot.exception import NoLogException as BaseNoLogException
from nonebot.exception import ApiNotAvailable as BaseApiNotAvailable
class OneBotAdapterException(AdapterException):
def __init__(self):
super().__init__("onebot")
class NoLogException(BaseNoLogException, OneBotAdapterException):
| 64 | 64 | 17 | 14 | 50 | nonebot/adapter-onebot | nonebot/adapters/onebot/exception.py | Python | NoLogException | NoLogException | 22 | 23 | 22 | 22 | 594f67d7a3d575d7105dc3db2c811aceca6aee98 | bigcode/the-stack | train |
431ea8881c2e726ccf0296af | train | class | class ActionFailed(BaseActionFailed, OneBotAdapterException):
"""API 请求返回错误信息。
参数:
retcode (int): 错误码
kwargs: 其他协议端提供信息
"""
def __init__(self, **kwargs):
super().__init__()
self.info = kwargs
"""所有错误信息"""
def __repr__(self):
return (
"<A... | class ActionFailed(BaseActionFailed, OneBotAdapterException):
| """API 请求返回错误信息。
参数:
retcode (int): 错误码
kwargs: 其他协议端提供信息
"""
def __init__(self, **kwargs):
super().__init__()
self.info = kwargs
"""所有错误信息"""
def __repr__(self):
return (
"<ActionFailed " + ", ".join(f"{k}={v}" for k, v in self.info.ite... | bot.exception import ApiNotAvailable as BaseApiNotAvailable
class OneBotAdapterException(AdapterException):
def __init__(self):
super().__init__("onebot")
class NoLogException(BaseNoLogException, OneBotAdapterException):
pass
class ActionFailed(BaseActionFailed, OneBotAdapterException):
| 64 | 64 | 126 | 12 | 51 | nonebot/adapter-onebot | nonebot/adapters/onebot/exception.py | Python | ActionFailed | ActionFailed | 26 | 45 | 26 | 26 | 3e4fa8564f51ff8fef612a77352f89868ca344d8 | bigcode/the-stack | train |
6167effc612783b0c4afae2b | train | class | class NetworkError(BaseNetworkError, OneBotAdapterException):
"""网络错误。"""
def __init__(self, msg: Optional[str] = None):
super().__init__()
self.msg: Optional[str] = msg
"""错误原因"""
def __repr__(self):
return f"<NetWorkError message={self.msg}>"
def __str__(self):
... | class NetworkError(BaseNetworkError, OneBotAdapterException):
| """网络错误。"""
def __init__(self, msg: Optional[str] = None):
super().__init__()
self.msg: Optional[str] = msg
"""错误原因"""
def __repr__(self):
return f"<NetWorkError message={self.msg}>"
def __str__(self):
return self.__repr__()
| __repr__(self):
return (
"<ActionFailed " + ", ".join(f"{k}={v}" for k, v in self.info.items()) + ">"
)
def __str__(self):
return self.__repr__()
class NetworkError(BaseNetworkError, OneBotAdapterException):
| 63 | 64 | 86 | 12 | 52 | nonebot/adapter-onebot | nonebot/adapters/onebot/exception.py | Python | NetworkError | NetworkError | 48 | 60 | 48 | 48 | 2e4b2a4f3afb4d5a088f8638089d4c84dee290c0 | bigcode/the-stack | train |
8bd45aeb918ef2aebde6d381 | train | class | class Solution(object):
def distanceK(self, root, target, K):
def dfs(node, par = None):
if node:
node.par = par
dfs(node.left, node)
dfs(node.right, node)
dfs(root)
queue = collections.deque([(target, 0)])
seen = {target}... | class Solution(object):
| def distanceK(self, root, target, K):
def dfs(node, par = None):
if node:
node.par = par
dfs(node.left, node)
dfs(node.right, node)
dfs(root)
queue = collections.deque([(target, 0)])
seen = {target}
while queue:
... | [y for x in bfs for y in conn[x] if y not in visited]
visited |= set(bfs)
return bfs
# V1'''''''
# https://www.jiuzhang.com/solution/all-nodes-distance-k-in-binary-tree/#tag-highlight-lang-python
class Solution(object):
| 64 | 64 | 149 | 4 | 59 | yennanliu/Python_basics | leetcode_python/Tree/all-nodes-distance-k-in-binary-tree.py | Python | Solution | Solution | 332 | 352 | 332 | 332 | 6ab6d9bcda126685e60614ed7378f34432aaf622 | bigcode/the-stack | train |
e001cebf8c25cf3b66e6148b | train | class | class Solution(object):
def distanceK(self, root, target, K):
ans = []
# Return distance from node to target if exists, else -1
# Vertex distance: the # of vertices on the path from node to target
def dfs(node):
if not node:
return -1
elif nod... | class Solution(object):
| def distanceK(self, root, target, K):
ans = []
# Return distance from node to target if exists, else -1
# Vertex distance: the # of vertices on the path from node to target
def dfs(node):
if not node:
return -1
elif node is target:
... | nei and nei not in seen:
seen.add(nei)
queue.append((nei, d+1))
return []
# V1''''''''''
# https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/solution/
# IDEA : Percolate Distance
# Time Complexity: O(N)
# Space Complexity: O(N)
class Solution(object):
| 77 | 77 | 259 | 4 | 73 | yennanliu/Python_basics | leetcode_python/Tree/all-nodes-distance-k-in-binary-tree.py | Python | Solution | Solution | 391 | 427 | 391 | 391 | e0dc621705349e84c394918a8914dbbe8f62a40a | bigcode/the-stack | train |
f5bb3ff57f8033030233bae6 | train | class | class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:
def dfs(node, dist):
if not node:
return
cur_dist = dist
if node.val in path:
cur_dist = path[node.val]
if... | class Solution:
| def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:
def dfs(node, dist):
if not node:
return
cur_dist = dist
if node.val in path:
cur_dist = path[node.val]
if cur_dist == K:
... | .popleft()
for j in conn[node]:
if j not in visited:
que.append(j)
visited.add(j)
return list(que)
### Test case : dev
# V1''''
# https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/1044354/easy-python
c... | 72 | 72 | 240 | 3 | 68 | yennanliu/Python_basics | leetcode_python/Tree/all-nodes-distance-k-in-binary-tree.py | Python | Solution | Solution | 254 | 295 | 254 | 254 | 3c0f9bcb47bb3f889b4d18bd49f06253cb7fc0bb | bigcode/the-stack | train |
a0fc048b8cfc41023511c90a | train | class | class Solution(object):
def distanceK(self, root, target, K):
def dfs(node, par = None):
if node:
node.par = par
dfs(node.left, node)
dfs(node.right, node)
dfs(root)
queue = collections.deque([(target, 0)])
seen = {target}... | class Solution(object):
| def distanceK(self, root, target, K):
def dfs(node, par = None):
if node:
node.par = par
dfs(node.left, node)
dfs(node.right, node)
dfs(root)
queue = collections.deque([(target, 0)])
seen = {target}
while queue:
... | (node)
vis.add(node)
q.append((node,j+1))
return ans if len(q) < K else [target.val]
# V1'
# IDEA : Annotate Parent
# https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/solution/
class Solution(object):
| 64 | 64 | 149 | 4 | 60 | yennanliu/Python_basics | leetcode_python/Tree/all-nodes-distance-k-in-binary-tree.py | Python | Solution | Solution | 147 | 168 | 147 | 147 | eefcc3fb9d4a26e1d4d9ffab7d2db840f6b6a95e | bigcode/the-stack | train |
1461b2052dcef362fb5b760d | train | class | class Solution(object):
def distanceK(self, root, target, K):
def dfs(node, par = None):
if node:
node.par = par
dfs(node.left, node)
dfs(node.right, node)
dfs(root)
queue = collections.deque([(target, 0)])
seen = {target}... | class Solution(object):
| def distanceK(self, root, target, K):
def dfs(node, par = None):
if node:
node.par = par
dfs(node.left, node)
dfs(node.right, node)
dfs(root)
queue = collections.deque([(target, 0)])
seen = {target}
while queue:
... | then perform a breadth first search from the target node to find the answer.
# 1. We first do a depth first search where we annotate every node with information about it's parent.
# 2. After, we do a breadth first search to find all nodes a distance K from the target.
class Solution(object):
| 64 | 64 | 149 | 4 | 60 | yennanliu/Python_basics | leetcode_python/Tree/all-nodes-distance-k-in-binary-tree.py | Python | Solution | Solution | 363 | 384 | 363 | 363 | eefcc3fb9d4a26e1d4d9ffab7d2db840f6b6a95e | bigcode/the-stack | train |
6c723466bed427087b873298 | train | class | class Solution:
def build(self,parent,child):
if parent and child:
self.graph[parent.val].append(child.val)
self.graph[child.val].append(parent.val)
if child.left:
self.build(child,child.left)
if child.right:
self.build(child,child.right)
... | class Solution:
| def build(self,parent,child):
if parent and child:
self.graph[parent.val].append(child.val)
self.graph[child.val].append(parent.val)
if child.left:
self.build(child,child.left)
if child.right:
self.build(child,child.right)
def ... | 6: [5], 2: [5, 7, 4], 7: [2], 4: [2], 1: [3, 0, 8], 0: [1], 8: [1]})
from collections import defaultdict
class Solution:
| 64 | 64 | 200 | 4 | 59 | yennanliu/Python_basics | leetcode_python/Tree/all-nodes-distance-k-in-binary-tree.py | Python | Solution | Solution | 42 | 69 | 42 | 43 | 4402311891fe45587b4987b779373ecbc8433703 | bigcode/the-stack | train |
8504e467c8a7ecd61a878748 | train | class | class Solution:
def __init__(self):
self.graph=defaultdict(list)
def build(self,parent,child):
if parent and child:
self.graph[parent.val].append(child.val)
self.graph[child.val].append(parent.val)
if child.left:
self.build(child,child.left)
... | class Solution:
| def __init__(self):
self.graph=defaultdict(list)
def build(self,parent,child):
if parent and child:
self.graph[parent.val].append(child.val)
self.graph[child.val].append(parent.val)
if child.left:
self.build(child,child.left)
if child.righ... | :
q.append(j)
visited.add(j)
return list(q)
# V1
# IDEA : DFS + BFS
# https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/604718/Python-BFS-solution
from collections import defaultdict,deque
class Solution:
| 64 | 64 | 189 | 3 | 60 | yennanliu/Python_basics | leetcode_python/Tree/all-nodes-distance-k-in-binary-tree.py | Python | Solution | Solution | 115 | 142 | 115 | 115 | 4d4912195fdf11c07e13b4c79f0561a702faa462 | bigcode/the-stack | train |
4e681532d0b3f5c48755832c | train | class | class Solution(object):
def distanceK(self, root, target, K):
"""
:type root: TreeNode
:type target: TreeNode
:type K: int
:rtype: List[int]
"""
def dfs(parent, child, neighbors):
if not child:
return
if parent:
... | class Solution(object):
| def distanceK(self, root, target, K):
"""
:type root: TreeNode
:type target: TreeNode
:type K: int
:rtype: List[int]
"""
def dfs(parent, child, neighbors):
if not child:
return
if parent:
neighbors[parent... | :
ans.append(node.val)
else:
subtree_add(node.left, dist + 1)
subtree_add(node.right, dist + 1)
dfs(root)
return ans
# V2
# Time: O(n)
# Space: O(n)
import collections
class Solution(object):
| 64 | 64 | 179 | 4 | 59 | yennanliu/Python_basics | leetcode_python/Tree/all-nodes-distance-k-in-binary-tree.py | Python | Solution | Solution | 433 | 459 | 433 | 433 | 4bd17ac00c59515f741b7da965266ce3497c58c8 | bigcode/the-stack | train |
0af60a41399696377b580a2d | train | class | class Solution(object):
def distanceK(self, root, target, K):
"""
:type root: TreeNode
:type target: TreeNode
:type K: int
:rtype: List[int]
"""
# DFS
conn = collections.defaultdict(list)
def connect(parent, child):
if parent and ch... | class Solution(object):
| def distanceK(self, root, target, K):
"""
:type root: TreeNode
:type target: TreeNode
:type K: int
:rtype: List[int]
"""
# DFS
conn = collections.defaultdict(list)
def connect(parent, child):
if parent and child:
con... | n.net/fuxuemingzhu/article/details/82709619
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
| 64 | 64 | 205 | 4 | 59 | yennanliu/Python_basics | leetcode_python/Tree/all-nodes-distance-k-in-binary-tree.py | Python | Solution | Solution | 219 | 248 | 219 | 219 | 43bb8cf19778731b8d406238a467bd1d8d49562f | bigcode/the-stack | train |
16c72eb20bc42135343b3326 | train | class | class Solution(object):
def distanceK(self, root, target, K):
# DFS
def connect(parent, child):
# build graph
if parent and child:
conn[parent.val].append(child.val)
conn[child.val].append(parent.val)
if child.left:
... | class Solution(object):
| def distanceK(self, root, target, K):
# DFS
def connect(parent, child):
# build graph
if parent and child:
conn[parent.val].append(child.val)
conn[child.val].append(parent.val)
if child.left:
connect(child, child.lef... | node in self.graph[i]:
if node not in vis:
if j==K:
ans.append(node)
vis.add(node)
q.append((node,j+1))
return ans if len(q) < K else [target.val]
# V0'
# IDEA : DFS + BFS
class Solution(object):
| 67 | 67 | 226 | 4 | 62 | yennanliu/Python_basics | leetcode_python/Tree/all-nodes-distance-k-in-binary-tree.py | Python | Solution | Solution | 73 | 109 | 73 | 73 | 37e9e436de695cb035ab1655883f91a25805743c | bigcode/the-stack | train |
ed1f739fdb46a8474cce15f6 | train | class | class Solution(object):
def distanceK(self, root, target, K):
"""
:type root: TreeNode
:type target: TreeNode
:type K: int
:rtype: List[int]
"""
# DFS
conn = collections.defaultdict(list)
def connect(parent, child):
if parent and ch... | class Solution(object):
| def distanceK(self, root, target, K):
"""
:type root: TreeNode
:type target: TreeNode
:type K: int
:rtype: List[int]
"""
# DFS
conn = collections.defaultdict(list)
def connect(parent, child):
if parent and child:
con... | n.net/fuxuemingzhu/article/details/82709619
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
| 64 | 64 | 180 | 4 | 59 | yennanliu/Python_basics | leetcode_python/Tree/all-nodes-distance-k-in-binary-tree.py | Python | Solution | Solution | 305 | 328 | 305 | 305 | 0f15945f129e4dadb37ef44e9f94ec198a69c4a6 | bigcode/the-stack | train |
20d9f81824989adbac7e3c98 | train | class | class Solution(object):
def distanceK(self, root, target, K):
ans = []
# Return distance from node to target if exists, else -1
# Vertex distance: the # of vertices on the path from node to target
def dfs(node):
if not node:
return -1
elif nod... | class Solution(object):
| def distanceK(self, root, target, K):
ans = []
# Return distance from node to target if exists, else -1
# Vertex distance: the # of vertices on the path from node to target
def dfs(node):
if not node:
return -1
elif node is target:
... | ()
for nei in (node.left, node.right, node.par):
if nei and nei not in seen:
seen.add(nei)
queue.append((nei, d+1))
return []
# V1''
# IDEA : Percolate Distance
# https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/solution/
cla... | 77 | 77 | 259 | 4 | 73 | yennanliu/Python_basics | leetcode_python/Tree/all-nodes-distance-k-in-binary-tree.py | Python | Solution | Solution | 173 | 209 | 173 | 173 | e0dc621705349e84c394918a8914dbbe8f62a40a | bigcode/the-stack | train |
7f294b20d6c1fca6d07c55d5 | train | function | def save_ply(
filename,
vertices,
faces=[],
normals=None,
charges=None,
vertex_cb=None,
hbond=None,
hphob=None,
iface=None,
normalize_charges=False,
):
""" Save vertices, mesh in ply format.
vertices: coordinates of vertices
faces: mesh
"""
mesh = pyme... | def save_ply(
filename,
vertices,
faces=[],
normals=None,
charges=None,
vertex_cb=None,
hbond=None,
hphob=None,
iface=None,
normalize_charges=False,
):
| """ Save vertices, mesh in ply format.
vertices: coordinates of vertices
faces: mesh
"""
mesh = pymesh.form_mesh(vertices, faces)
if normals is not None:
n1 = normals[:, 0]
n2 = normals[:, 1]
n3 = normals[:, 2]
mesh.add_attribute("vertex_nx")
mesh.... | pymesh
import numpy
"""
read_ply.py: Save a ply file to disk using pymesh and load the attributes used by MaSIF.
Pablo Gainza - LPDI STI EPFL 2019
Released under an Apache License 2.0
"""
def save_ply(
filename,
vertices,
faces=[],
normals=None,
charges=None,
vertex_cb=None,
hbond=None,
... | 107 | 107 | 357 | 50 | 57 | NBDsoftware/masif | source/input_output/save_ply.py | Python | save_ply | save_ply | 10 | 57 | 10 | 21 | b5ca570d393fdeb8122ca494ec0a56d16ed764d7 | bigcode/the-stack | train |
c198bc75c9ede3313e2c7c24 | train | function | def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column(
'categories',
sa.Column('sort_order', sa.Integer(), nullable=True, default=0))
op.add_column(
'service',
sa.Column('sort_order', sa.Integer(), nullable=True, default=0))
| def upgrade():
### commands auto generated by Alembic - please adjust! ###
| op.add_column(
'categories',
sa.Column('sort_order', sa.Integer(), nullable=True, default=0))
op.add_column(
'service',
sa.Column('sort_order', sa.Integer(), nullable=True, default=0))
| .
revision = '368b199625d8'
down_revision = '9b6d9727e3ac'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
| 64 | 64 | 69 | 17 | 46 | Hack4Eugene/15th-night-by-dumpsterfire | _15thnight/migrations/versions/368b199625d8_service_category_sort.py | Python | upgrade | upgrade | 19 | 27 | 19 | 20 | 9c4110d9e1478a86a98da94dc1ff348114648b5a | bigcode/the-stack | train |
739d79c4600665da46331e49 | train | function | def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('service', 'sort_order')
op.drop_column('categories', 'sort_order')
| def downgrade():
### commands auto generated by Alembic - please adjust! ###
| op.drop_column('service', 'sort_order')
op.drop_column('categories', 'sort_order')
| _order', sa.Integer(), nullable=True, default=0))
op.add_column(
'service',
sa.Column('sort_order', sa.Integer(), nullable=True, default=0))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
| 63 | 64 | 39 | 17 | 46 | Hack4Eugene/15th-night-by-dumpsterfire | _15thnight/migrations/versions/368b199625d8_service_category_sort.py | Python | downgrade | downgrade | 31 | 34 | 31 | 32 | 384bd8e92918041b4d79e09f8676fe37a2f0b457 | bigcode/the-stack | train |
9a57349183afb61375d252bd | train | class | class USBVendorSpecificVendor(USBVendor):
name = 'VendorSpecificVendor'
def setup_local_handlers(self):
self.local_handlers = {
x: self.handle_generic for x in range(256)
}
def handle_generic(self, req):
self.usb_function_supported()
self.always('Generic Vendor ... | class USBVendorSpecificVendor(USBVendor):
| name = 'VendorSpecificVendor'
def setup_local_handlers(self):
self.local_handlers = {
x: self.handle_generic for x in range(256)
}
def handle_generic(self, req):
self.usb_function_supported()
self.always('Generic Vendor handler - req: %s' % req)
| DeviceRequest, Request
from facedancer.USBEndpoint import USBEndpoint
from facedancer.USBVendor import USBVendor
from facedancer.USBConfiguration import USBConfiguration
from facedancer.USBInterface import USBInterface
from facedancer.USB import *
import struct
class USBVendorSpecificVendor(USBVendor):
| 64 | 64 | 77 | 9 | 54 | gy741/Facedancer | facedancer/devices/vendor_specific.py | Python | USBVendorSpecificVendor | USBVendorSpecificVendor | 15 | 25 | 15 | 15 | b4f420c46234d5b4ae4e0592db4a9df481d4eb24 | bigcode/the-stack | train |
f5c00840ab239b7991793063 | train | class | class USBVendorSpecificDevice(USBDevice):
name = 'Vendor specific device'
def __init__(self, phy, vid, pid, rev=1, **kwargs):
self.phy = phy
super(USBVendorSpecificDevice, self).__init__(
phy=phy,
device_class=USBClass.VendorSpecific,
device_subclass=1,
... | class USBVendorSpecificDevice(USBDevice):
| name = 'Vendor specific device'
def __init__(self, phy, vid, pid, rev=1, **kwargs):
self.phy = phy
super(USBVendorSpecificDevice, self).__init__(
phy=phy,
device_class=USBClass.VendorSpecific,
device_subclass=1,
protocol_rel_num=1,
max... | = 4
bNumEndpoints = len(self.virtual_endpoints)
d = struct.pack(
'<BBBBBBBBB',
bLength, # length of descriptor in bytes
bDescriptorType, # descriptor type 4 == interface
self.number,
self.alternate,
bNumEndpoints,
se... | 256 | 256 | 1,187 | 9 | 247 | gy741/Facedancer | facedancer/devices/vendor_specific.py | Python | USBVendorSpecificDevice | USBVendorSpecificDevice | 120 | 223 | 120 | 120 | 907546a3c3b056d61d388d7adc4f860724e9529a | bigcode/the-stack | train |
3d5e5b808e22c9d37182173a | train | class | class USBVendorSpecificInterface(USBInterface):
name = 'VendorSpecificInterface'
def __init__(self, phy, num=0, interface_alternate=0, endpoints=[]):
# TODO: un-hardcode string index
super(USBVendorSpecificInterface, self).__init__(
phy=phy,
interface_number=num,
... | class USBVendorSpecificInterface(USBInterface):
| name = 'VendorSpecificInterface'
def __init__(self, phy, num=0, interface_alternate=0, endpoints=[]):
# TODO: un-hardcode string index
super(USBVendorSpecificInterface, self).__init__(
phy=phy,
interface_number=num,
interface_alternate=interface_alternate,
... | Vendor):
name = 'VendorSpecificVendor'
def setup_local_handlers(self):
self.local_handlers = {
x: self.handle_generic for x in range(256)
}
def handle_generic(self, req):
self.usb_function_supported()
self.always('Generic Vendor handler - req: %s' % req)
class... | 156 | 156 | 521 | 9 | 147 | gy741/Facedancer | facedancer/devices/vendor_specific.py | Python | USBVendorSpecificInterface | USBVendorSpecificInterface | 41 | 117 | 41 | 41 | 7239a6d09d130e192d0ce1b8010e9af066c40304 | bigcode/the-stack | train |
5fff755d18d888316a5be9ab | train | class | class USBVendorSpecificClass(USBClass):
name = 'VendorSpecificClass'
def setup_local_handlers(self):
self.local_handlers = {
x: self.handle_generic for x in range(256)
}
def handle_generic(self, req):
self.usb_function_supported()
self.always('Generic Class hand... | class USBVendorSpecificClass(USBClass):
| name = 'VendorSpecificClass'
def setup_local_handlers(self):
self.local_handlers = {
x: self.handle_generic for x in range(256)
}
def handle_generic(self, req):
self.usb_function_supported()
self.always('Generic Class handler - req: %s' % req)
| (self):
self.local_handlers = {
x: self.handle_generic for x in range(256)
}
def handle_generic(self, req):
self.usb_function_supported()
self.always('Generic Vendor handler - req: %s' % req)
class USBVendorSpecificClass(USBClass):
| 64 | 64 | 77 | 9 | 55 | gy741/Facedancer | facedancer/devices/vendor_specific.py | Python | USBVendorSpecificClass | USBVendorSpecificClass | 28 | 38 | 28 | 28 | 98539eca7d2d6b52915c1cf33f7bafeac031f6ac | bigcode/the-stack | train |
7727a33ee5816368725a319f | train | function | @task(incrementable=["verbose"])
def config(ctx, loc="local"):
"""
Open coverage report inside of browser
Usage: inv view.config
"""
env = get_compose_env(ctx, loc=loc)
# Only display result
ctx.config["run"]["echo"] = True
# Override run commands env variables one key at a time
fo... | @task(incrementable=["verbose"])
def config(ctx, loc="local"):
| """
Open coverage report inside of browser
Usage: inv view.config
"""
env = get_compose_env(ctx, loc=loc)
# Only display result
ctx.config["run"]["echo"] = True
# Override run commands env variables one key at a time
for k, v in env.items():
ctx.config["run"]["env"][k] = v
... | clean, execute_sql
from .utils import (
COLOR_WARNING,
COLOR_DANGER,
COLOR_SUCCESS,
COLOR_CAUTION,
COLOR_STABLE,
)
logger = logging.getLogger(__name__)
logger.setLevel("DEBUG")
@task(incrementable=["verbose"])
def config(ctx, loc="local"):
| 64 | 64 | 124 | 16 | 48 | universityofprofessorex/machine-learning-with-python | tasks/view.py | Python | config | config | 23 | 40 | 23 | 24 | 5189022fa913ca0a2188abe587b7f1013e46d063 | bigcode/the-stack | train |
0476fc4e657b0f9a77cbe97c | train | class | class JSONResponse(JsonResponse):
'''A Django JsonResponse class that consumes data to be serialized to JSON using CustomJsonEncoder.
'''
def __init__(self, data, encoder=CustomJsonEncoder, safe=True, json_dumps_params=None, **kwargs):
'''
Args:
data: Data to be dumped into JSON... | class JSONResponse(JsonResponse):
| '''A Django JsonResponse class that consumes data to be serialized to JSON using CustomJsonEncoder.
'''
def __init__(self, data, encoder=CustomJsonEncoder, safe=True, json_dumps_params=None, **kwargs):
'''
Args:
data: Data to be dumped into JSON. By default only dict objects
... | , obj):
'''JSON Encoding handler method
'''
if isinstance(obj, ObjectId):
return str(obj)
if isinstance(obj, datetime):
return int(float(obj.strftime('%s')) * 1000)
return super(CustomJsonEncoder, self).default(obj)
class JSONResponse(JsonResponse):
| 64 | 64 | 172 | 6 | 58 | rupeshcode/youtube_scraper | commons/utils/response.py | Python | JSONResponse | JSONResponse | 27 | 42 | 27 | 27 | b6d765eadc9cbd5e0b44bb97d817ce8314c93308 | bigcode/the-stack | train |
5e5dcae8a95386a982a101a3 | train | class | class CustomJsonEncoder(DjangoJSONEncoder):
'''A custom JSON encoder handling JSON native encoding for following python types
- datetime
- bson object id
'''
def default(self, obj):
'''JSON Encoding handler method
'''
if isinstance(obj, ObjectId):
return... | class CustomJsonEncoder(DjangoJSONEncoder):
| '''A custom JSON encoder handling JSON native encoding for following python types
- datetime
- bson object id
'''
def default(self, obj):
'''JSON Encoding handler method
'''
if isinstance(obj, ObjectId):
return str(obj)
if isinstance(obj, dateti... | from datetime import datetime
from bson.objectid import ObjectId
from django.core.serializers.json import DjangoJSONEncoder
from django.http.response import JsonResponse
class CustomJsonEncoder(DjangoJSONEncoder):
| 41 | 64 | 98 | 9 | 31 | rupeshcode/youtube_scraper | commons/utils/response.py | Python | CustomJsonEncoder | CustomJsonEncoder | 8 | 24 | 8 | 8 | 578bc946f50875701eb2695e628f23b83732556a | bigcode/the-stack | train |
e58d5e8eb35623fc83430390 | train | class | class OK(JSONResponse):
'''A Custom JSONResponse class that append response with 200 http status code.
'''
def __init__(self, data, encoder=CustomJsonEncoder, safe=True, json_dumps_params=None, **kwargs):
'''
Args:
data: Data to be dumped into JSON. By default only dict objects
... | class OK(JSONResponse):
| '''A Custom JSONResponse class that append response with 200 http status code.
'''
def __init__(self, data, encoder=CustomJsonEncoder, safe=True, json_dumps_params=None, **kwargs):
'''
Args:
data: Data to be dumped into JSON. By default only dict objects
are al... | json_dumps_params: A dictionary of kwargs passed to json.dumps().
kwargs: key word args for Django's JsonResponse class (params of HttpResponseBase class)
'''
super(JSONResponse, self).__init__(data, encoder, safe, json_dumps_params, **kwargs)
class OK(JSONResponse):
| 64 | 64 | 185 | 5 | 59 | rupeshcode/youtube_scraper | commons/utils/response.py | Python | OK | OK | 45 | 63 | 45 | 45 | 9bb8b30deddf40c58fccdb5b2366664632ab897c | bigcode/the-stack | train |
d590ce47394ec015d110ea86 | train | class | class TestArgumentParserInit(unittest.TestCase):
def setUp(self):
self.ap = ArgumentParser(USAGE)
def assert_long_opts(self, expected, ap=None):
expected += ['no' + e for e in expected if not e.endswith('=')]
long_opts = (ap or self.ap)._long_opts
assert_equal(sorted(long_opts)... | class TestArgumentParserInit(unittest.TestCase):
| def setUp(self):
self.ap = ArgumentParser(USAGE)
def assert_long_opts(self, expected, ap=None):
expected += ['no' + e for e in expected if not e.endswith('=')]
long_opts = (ap or self.ap)._long_opts
assert_equal(sorted(long_opts), sorted(expected))
def assert_short_opts(sel... | value and next nothing after option name
-v --variable name:value *
-N --name name
-t -T --toggle Something
-h -? --help
--version Explanation
-z No long option so not an option line.
--z No long option here either
this line doesn't start with a '-' so not an --optionline
-\\-option escape... | 198 | 198 | 661 | 9 | 189 | anilameec/robotframework | utest/utils/test_argumentparser.py | Python | TestArgumentParserInit | TestArgumentParserInit | 54 | 121 | 54 | 55 | 7f98ea2970bfed8098b009c47b6daa10658e140c | bigcode/the-stack | train |
a0d42db76967952e56a77d34 | train | class | class TestDefaultsFromEnvironmentVariables(unittest.TestCase):
def setUp(self):
os.environ['ROBOT_TEST_OPTIONS'] = '-t --value default -m1 --multi=2'
self.ap = ArgumentParser('''Options:
-t --toggle
-v --value value
-m --multi multi *
''', env_options='ROBOT_TEST_OPTIONS')
def tearDown(self... | class TestDefaultsFromEnvironmentVariables(unittest.TestCase):
| def setUp(self):
os.environ['ROBOT_TEST_OPTIONS'] = '-t --value default -m1 --multi=2'
self.ap = ArgumentParser('''Options:
-t --toggle
-v --value value
-m --multi multi *
''', env_options='ROBOT_TEST_OPTIONS')
def tearDown(self):
os.environ.pop('ROBOT_TEST_OPTIONS')
def test_fl... | value value
-m --multi multi *
''')
opts, args = ap.parse_args(())
assert_equal(opts, {'toggle': None,
'value': None,
'multi': []})
assert_equal(args, [])
opts, args = ap.parse_args(('-t', '-v', 'xxx', '-m', '1', '-m2', 'arg'))
... | 125 | 126 | 421 | 10 | 115 | anilameec/robotframework | utest/utils/test_argumentparser.py | Python | TestDefaultsFromEnvironmentVariables | TestDefaultsFromEnvironmentVariables | 279 | 324 | 279 | 280 | b1e3f3e0c6d004eec68585c608827f7efb6cac00 | bigcode/the-stack | train |
82b037547306f47d30e86053 | train | class | class TestPrintHelpAndVersion(unittest.TestCase):
def setUp(self):
self.ap = ArgumentParser(USAGE, version='1.0 alpha')
self.ap2 = ArgumentParser(USAGE2)
def test_print_help(self):
assert_raises_with_msg(Information, USAGE2,
self.ap2.parse_args, ['--help'... | class TestPrintHelpAndVersion(unittest.TestCase):
| def setUp(self):
self.ap = ArgumentParser(USAGE, version='1.0 alpha')
self.ap2 = ArgumentParser(USAGE2)
def test_print_help(self):
assert_raises_with_msg(Information, USAGE2,
self.ap2.parse_args, ['--help'])
def test_name_is_got_from_first_line_of_the... | validate(options, args):
return options, [a.upper() for a in args]
ap = ArgumentParser(USAGE2, validator=validate)
opts, args = ap.parse_args(['-v', 'value', 'inp1', 'inp2'])
assert_equal(opts['variable'], 'value')
assert_equal(args, ['INP1', 'INP2'])
class TestPrintHelpAndV... | 90 | 91 | 305 | 10 | 80 | anilameec/robotframework | utest/utils/test_argumentparser.py | Python | TestPrintHelpAndVersion | TestPrintHelpAndVersion | 381 | 411 | 381 | 382 | 202d0a75a511b50e07a0eb17f9a2afc693892222 | bigcode/the-stack | train |
d2a665ab512c06feb826964c | train | class | class TestArgumentValidation(unittest.TestCase):
def test_check_args_with_correct_args(self):
for arg_limits in [None, (1, 1), 1, (1,)]:
ap = ArgumentParser(USAGE, arg_limits=arg_limits)
assert_equal(ap.parse_args(['hello'])[1], ['hello'])
def test_default_validation(self):
... | class TestArgumentValidation(unittest.TestCase):
| def test_check_args_with_correct_args(self):
for arg_limits in [None, (1, 1), 1, (1,)]:
ap = ArgumentParser(USAGE, arg_limits=arg_limits)
assert_equal(ap.parse_args(['hello'])[1], ['hello'])
def test_default_validation(self):
ap = ArgumentParser(USAGE)
for args i... | m3', '--multi', '4'])
assert_equal(opts['multi'], ['1', '2', '3', '4'])
def test_arguments(self):
os.environ['ROBOT_TEST_OPTIONS'] = '-o opt arg1 arg2'
ap = ArgumentParser('Usage:\n -o --opt value',
env_options='ROBOT_TEST_OPTIONS')
opts, args = ap.parse_... | 174 | 175 | 585 | 8 | 166 | anilameec/robotframework | utest/utils/test_argumentparser.py | Python | TestArgumentValidation | TestArgumentValidation | 327 | 378 | 327 | 328 | d7ce8ed65282181dddbdb7737a5d2af3eab8038a | bigcode/the-stack | train |
386625cbae137fb2ea02273b | train | class | class TestArgumentParserParseArgs(unittest.TestCase):
def setUp(self):
self.ap = ArgumentParser(USAGE)
def test_missing_argument_file_throws_data_error(self):
inargs = '--argumentfile missing_argument_file_that_really_is_not_there.txt'.split()
self.assertRaises(DataError, self.ap.parse... | class TestArgumentParserParseArgs(unittest.TestCase):
| def setUp(self):
self.ap = ArgumentParser(USAGE)
def test_missing_argument_file_throws_data_error(self):
inargs = '--argumentfile missing_argument_file_that_really_is_not_there.txt'.split()
self.assertRaises(DataError, self.ap.parse_args, inargs)
def test_single_options(self):
... | ):
ap = ArgumentParser(' -f --foo\n -B --BAR\n')
self.assert_short_opts('fB', ap)
self.assert_long_opts(['foo', 'bar'], ap)
def test_same_option_multiple_times(self):
for usage in [' --foo\n --foo\n',
' --foo\n -f --Foo\n',
' -x --foo xxx\... | 256 | 256 | 1,654 | 10 | 246 | anilameec/robotframework | utest/utils/test_argumentparser.py | Python | TestArgumentParserParseArgs | TestArgumentParserParseArgs | 124 | 276 | 124 | 125 | 790fec7c8e357d6b2ade10fd29cd48a6895e3e9c | bigcode/the-stack | train |
9b9fdceddd33df518a9315cb | train | function | def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
| def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
| geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
| env, "-1")
arg1 = msat_make_times(menv, arg1, n_m1)
return msat_make_plus(menv, arg0, arg1)
def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
| 64 | 64 | 56 | 26 | 38 | EnricoMagnago/F3 | benchmarks/ltl_maxplus/f3/maxplus_40_87.py | Python | msat_make_lt | msat_make_lt | 44 | 46 | 44 | 44 | f682ff02b643620fb47f1bac9d203fab49c9977a | bigcode/the-stack | train |
d4d94b9ba64abfad9e636eac | train | function | def check_ltl(menv: msat_env, enc: LTLEncoder) -> (Iterable, msat_term,
msat_term, msat_term):
assert menv
assert isinstance(menv, msat_env)
assert enc
assert isinstance(enc, LTLEncoder)
real_type = msat_get_rational_type(menv)
names = ["x_0", ... | def check_ltl(menv: msat_env, enc: LTLEncoder) -> (Iterable, msat_term,
msat_term, msat_term):
| assert menv
assert isinstance(menv, msat_env)
assert enc
assert isinstance(enc, LTLEncoder)
real_type = msat_get_rational_type(menv)
names = ["x_0", "x_1", "x_2", "x_3", "x_4", "x_5", "x_6", "x_7", "x_8", "x_9", "x_10", "x_11", "x_12", "x_13", "x_14", "x_15", "x_16", "x_17", "x_18", "x_19", "x_... | _make_plus(menv, arg0, arg1)
def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
return msat_make_leq(menv, arg1, arg0)
def msat_make_gt(menv: msat... | 256 | 256 | 47,729 | 33 | 223 | EnricoMagnago/F3 | benchmarks/ltl_maxplus/f3/maxplus_40_87.py | Python | check_ltl | check_ltl | 63 | 2,712 | 63 | 64 | b35acde5db313330d8d5dd02f8651af5c5521d73 | bigcode/the-stack | train |
9670f82776a882cdd38cdc86 | train | function | def msat_make_minus(menv: msat_env, arg0: msat_term, arg1: msat_term):
n_m1 = msat_make_number(menv, "-1")
arg1 = msat_make_times(menv, arg1, n_m1)
return msat_make_plus(menv, arg0, arg1)
| def msat_make_minus(menv: msat_env, arg0: msat_term, arg1: msat_term):
| n_m1 = msat_make_number(menv, "-1")
arg1 = msat_make_times(menv, arg1, n_m1)
return msat_make_plus(menv, arg0, arg1)
| env, args[0], args[1])
for arg in args[2:]:
res = _msat_make_or(menv, res, arg)
return res
def msat_make_minus(menv: msat_env, arg0: msat_term, arg1: msat_term):
| 64 | 64 | 74 | 26 | 37 | EnricoMagnago/F3 | benchmarks/ltl_maxplus/f3/maxplus_40_87.py | Python | msat_make_minus | msat_make_minus | 38 | 41 | 38 | 38 | f8d30a5c43833c88fe170e1ff20910d15fe5def6 | bigcode/the-stack | train |
7453f424d37bb316bac6fb28 | train | function | def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
return msat_make_leq(menv, arg1, arg0)
| def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
| return msat_make_leq(menv, arg1, arg0)
| arg1: msat_term):
geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
| 64 | 64 | 43 | 27 | 37 | EnricoMagnago/F3 | benchmarks/ltl_maxplus/f3/maxplus_40_87.py | Python | msat_make_geq | msat_make_geq | 49 | 50 | 49 | 49 | b508b807d803a8843eb678982d7c937a8b671e86 | bigcode/the-stack | train |
c0a2567ede4ba116e6b42ede | train | function | def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
n_arg0 = msat_make_not(menv, arg0)
return msat_make_or(menv, n_arg0, arg1)
| def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
| n_arg0 = msat_make_not(menv, arg0)
return msat_make_or(menv, n_arg0, arg1)
| , arg1: msat_term):
leq = msat_make_leq(menv, arg0, arg1)
return msat_make_not(menv, leq)
def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
| 64 | 64 | 57 | 26 | 38 | EnricoMagnago/F3 | benchmarks/ltl_maxplus/f3/maxplus_40_87.py | Python | msat_make_impl | msat_make_impl | 58 | 60 | 58 | 58 | 6517b33753958b928ace2c9a49a92b8749eb6875 | bigcode/the-stack | train |
8af0567b9f9dd2606a5e448e | train | function | def msat_make_and(menv: msat_env, *args):
if len(args) == 0:
return msat_make_true(menv)
if len(args) == 1:
return args[0]
res = _msat_make_and(menv, args[0], args[1])
for arg in args[2:]:
res = _msat_make_and(menv, res, arg)
return res
| def msat_make_and(menv: msat_env, *args):
| if len(args) == 0:
return msat_make_true(menv)
if len(args) == 1:
return args[0]
res = _msat_make_and(menv, args[0], args[1])
for arg in args[2:]:
res = _msat_make_and(menv, res, arg)
return res
| import msat_make_leq, msat_make_equal
from mathsat import msat_make_number, msat_make_plus, msat_make_times
from ltl.ltl import TermMap, LTLEncoder
from utils import name_next
def msat_make_and(menv: msat_env, *args):
| 64 | 64 | 95 | 15 | 48 | EnricoMagnago/F3 | benchmarks/ltl_maxplus/f3/maxplus_40_87.py | Python | msat_make_and | msat_make_and | 16 | 24 | 16 | 16 | f8f7a52d4982ec0803a7ef0bd7f6ebf8eec9ee81 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.