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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4f2095a97cc93382ca539025 | train | class | class HasZooModel(etal.HasPublishedModel):
"""Mixin class for Config classes of :class:`fiftyone.core.models.Model`
instances whose models are stored in the FiftyOne Model Zoo.
This class provides the following functionality:
- The model to load can be specified either by:
(a) providing a `... | class HasZooModel(etal.HasPublishedModel):
| """Mixin class for Config classes of :class:`fiftyone.core.models.Model`
instances whose models are stored in the FiftyOne Model Zoo.
This class provides the following functionality:
- The model to load can be specified either by:
(a) providing a `model_name`, which specifies the zoo model ... | """Deletes the zoo model from local disk, if necessary.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appended to
refer to a specific version of the model. If no version is
specified, the latest version of the model is used
"""
model, model_path = _get... | 97 | 97 | 324 | 10 | 87 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | HasZooModel | HasZooModel | 259 | 296 | 259 | 259 | 2d71f4ba1ec01d0deb798ca774812f38cd849533 | bigcode/the-stack | train |
38fd90a38bc7800e3cb53561 | train | function | def delete_zoo_model(name):
"""Deletes the zoo model from local disk, if necessary.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appended to
refer to a specific version of the model. If no version is
specified, the latest version of the model is used
"""
... | def delete_zoo_model(name):
| """Deletes the zoo model from local disk, if necessary.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appended to
refer to a specific version of the model. If no version is
specified, the latest version of the model is used
"""
model, model_path = _get... | _model(name):
"""Returns the :class:`ZooModel` instance for the model with the given
name.
Args:
name: the name of the zoo model
Returns:
a :class:`ZooModel`
"""
return _get_model(name)
def delete_zoo_model(name):
| 64 | 64 | 94 | 7 | 57 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | delete_zoo_model | delete_zoo_model | 247 | 256 | 247 | 247 | 7bf32e285ced4a9f2de64911b646be1d8711db13 | bigcode/the-stack | train |
7f042f641458c719528b4ce6 | train | function | def load_zoo_model(
name,
download_if_necessary=True,
install_requirements=False,
error_level=None,
**kwargs,
):
"""Loads the model of the given name from the FiftyOne Model Zoo.
By default, the model will be downloaded if necessary if it does not
exist in ``fiftyone.config.model_zoo_di... | def load_zoo_model(
name,
download_if_necessary=True,
install_requirements=False,
error_level=None,
**kwargs,
):
| """Loads the model of the given name from the FiftyOne Model Zoo.
By default, the model will be downloaded if necessary if it does not
exist in ``fiftyone.config.model_zoo_dir``.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appended to
refer to a specific versio... | log warning if a requirement is not satisifed
- 2: ignore unsatisifed requirements
By default, ``fo.config.requirement_error_level`` is used
log_success (True): whether to generate a log message when a
requirement is satisifed
"""
if error_level is None:
e... | 138 | 138 | 463 | 32 | 106 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | load_zoo_model | load_zoo_model | 152 | 207 | 152 | 158 | bb8d4d4d4236430a1c28264bbe09229438bb4b37 | bigcode/the-stack | train |
2abda964fd597f0a786aedf3 | train | function | def download_zoo_model(name, overwrite=False):
"""Downloads the model of the given name from the FiftyOne Dataset Zoo.
If the model is already downloaded, it is not re-downloaded unless
``overwrite == True`` is specified.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appende... | def download_zoo_model(name, overwrite=False):
| """Downloads the model of the given name from the FiftyOne Dataset Zoo.
If the model is already downloaded, it is not re-downloaded unless
``overwrite == True`` is specified.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appended to
refer to a specific version of... | version of the model. If no version is
specified, the latest version of the model is used
Returns:
True/False
"""
model = _get_model(name)
models_dir = fo.config.model_zoo_dir
return model.is_in_dir(models_dir)
def download_zoo_model(name, overwrite=False):
| 70 | 70 | 234 | 10 | 60 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | download_zoo_model | download_zoo_model | 73 | 99 | 73 | 73 | fabbd255565fd98dcba6fdf9db1466134f03c7eb | bigcode/the-stack | train |
a7fa62d2eba23cfff46e18da | train | class | class ZooModel(etam.Model):
"""Class describing a model in the FiftyOne Model Zoo.
Args:
base_name: the base name of the model (no version info)
base_filename: the base filename of the model (no version info)
manager: the :class:`fiftyone.core.models.ModelManager` instance that
... | class ZooModel(etam.Model):
| """Class describing a model in the FiftyOne Model Zoo.
Args:
base_name: the base name of the model (no version info)
base_filename: the base filename of the model (no version info)
manager: the :class:`fiftyone.core.models.ModelManager` instance that
describes the remote sto... | if not self.model_name and not self.model_path:
raise ConfigError(
"Either `model_name` or `model_path` must be provided"
)
if self.model_path is None:
self.model_path = download_zoo_model(self.model_name)
@classmethod
def _get_model(cls, model_name... | 85 | 85 | 285 | 7 | 78 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | ZooModel | ZooModel | 299 | 324 | 299 | 299 | ca504c287ca4a7c78b1731bd21372a4edf8b1e52 | bigcode/the-stack | train |
b618712b0929f30a1a522db6 | train | function | def install_zoo_model_requirements(name, error_level=None):
"""Installs any package requirements for the zoo model with the given name.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appended to
refer to a specific version of the model. If no version is
specifi... | def install_zoo_model_requirements(name, error_level=None):
| """Installs any package requirements for the zoo model with the given name.
Args:
name: the name of the zoo model, which can have ``@<ver>`` appended to
refer to a specific version of the model. If no version is
specified, the latest version of the model is used. Call
... | (name)
if not overwrite and is_zoo_model_downloaded(name):
logger.info("Model '%s' is already downloaded", name)
else:
model.manager.download_model(model_path, force=overwrite)
return model, model_path
def install_zoo_model_requirements(name, error_level=None):
| 64 | 64 | 206 | 13 | 50 | FLIR/fiftyone | fiftyone/zoo/models/__init__.py | Python | install_zoo_model_requirements | install_zoo_model_requirements | 102 | 122 | 102 | 102 | 30c6caca6310841efa03c0ee8a52ba9051cc9973 | bigcode/the-stack | train |
bcdb08ba08866b1a51672503 | train | class | class AEReward:
def __init__(self, ob_space, sess=None):
logger.info("Using AEReward")
self.sess = sess or tf.get_default_session()
self.X = observation_placeholder(ob_space)
initializer = tf.variance_scaling_initializer()
num_inp = ob_space.shape[0]
num_hid1 = num_in... | class AEReward:
| def __init__(self, ob_space, sess=None):
logger.info("Using AEReward")
self.sess = sess or tf.get_default_session()
self.X = observation_placeholder(ob_space)
initializer = tf.variance_scaling_initializer()
num_inp = ob_space.shape[0]
num_hid1 = num_inp // 2
#... | import tensorflow as tf
import numpy as np
from baselines import logger
from baselines.common.tf_util import adjust_shape
from baselines.common.input import observation_placeholder
from baselines.a2c.utils import fc
class AEReward:
| 49 | 203 | 678 | 4 | 44 | veniversum/baselines | baselines/common/exploration.py | Python | AEReward | AEReward | 8 | 59 | 8 | 8 | 948d5d6016a581551d55cf62d156a7032e878086 | bigcode/the-stack | train |
f8915638b788e05001654f97 | train | class | class RNDReward:
def __init__(self, ob_space, sess=None):
logger.info("Using RNDReward")
self.sess = sess or tf.get_default_session()
# RND.
num_inp = ob_space.shape[0]
num_hid1 = 64 #num_inp // 2
num_hid_pred = 32
rep_size = 10
proportion_of_exp_used_... | class RNDReward:
| def __init__(self, ob_space, sess=None):
logger.info("Using RNDReward")
self.sess = sess or tf.get_default_session()
# RND.
num_inp = ob_space.shape[0]
num_hid1 = 64 #num_inp // 2
num_hid_pred = 32
rep_size = 10
proportion_of_exp_used_for_predictor_upd... | self.bonus = tf.reduce_mean(tf.square(output_layer - self.X), 1) # novelty reward as AE loss per observation
optimizer = tf.train.AdamOptimizer(0.01)
self.train = optimizer.minimize(self.loss)
tf.global_variables_initializer().run(session=sess)
def update(self, batch):
sess = self... | 212 | 212 | 708 | 5 | 207 | veniversum/baselines | baselines/common/exploration.py | Python | RNDReward | RNDReward | 61 | 111 | 61 | 61 | 0b2791f8947b17d8be3dab8e7bd364d5675623a4 | bigcode/the-stack | train |
92e20ac4aafa7a3c2d9bd058 | train | function | def test_andrea():
ext = GenderExtractor()
assert ext.extract_gender("Andrea")=='female'
assert ext.extract_gender("Andrea", "Italy")=='mostly male'
| def test_andrea():
| ext = GenderExtractor()
assert ext.extract_gender("Andrea")=='female'
assert ext.extract_gender("Andrea", "Italy")=='mostly male'
| from gender_extractor import GenderExtractor
def test_andrea():
| 13 | 64 | 37 | 5 | 7 | wwydmanski/gender-extractor | tests/basic_test.py | Python | test_andrea | test_andrea | 4 | 7 | 4 | 4 | f0a5b46aab58244a9e7dd9b18598d29a7ee43cbe | bigcode/the-stack | train |
ff665088cf558e9010945b54 | train | function | def exception_handler(exception_type, value, tb_obj):
""" Global exception handler useful in GUIs.
tb_obj: exception.__traceback__ """
tb = '\n'.join(traceback.format_tb(tb_obj))
text = 'Traceback (most recent call last):\n' + tb + '\n' + exception_type.__name__ + ': ' + str(value)
print(text)
l... | def exception_handler(exception_type, value, tb_obj):
| """ Global exception handler useful in GUIs.
tb_obj: exception.__traceback__ """
tb = '\n'.join(traceback.format_tb(tb_obj))
text = 'Traceback (most recent call last):\n' + tb + '\n' + exception_type.__name__ + ': ' + str(value)
print(text)
logger.error(_("Uncaught exception: ") + text)
QtWi... | from PyQt5 import QtWidgets, QtCore
import os
import sys
import logging
import traceback
from .ui_dialog_information import Ui_Dialog_information
path = os.path.abspath(os.path.dirname(__file__))
logger = logging.getLogger(__name__)
def exception_handler(exception_type, value, tb_obj):
| 64 | 64 | 112 | 11 | 53 | fmagin/QualCoder | qualcoder/GUI/information.py | Python | exception_handler | exception_handler | 40 | 47 | 40 | 40 | b6aec4299225fb1a96d73910500ec2ce8d4d9009 | bigcode/the-stack | train |
dfd7af38b6fc2e0efe1f9f3a | train | class | class DialogInformation(QtWidgets.QDialog):
"""
Dialog to display about information from html and text files for PyQDA development,
version and license.
The html is coded below because it avoids potential data file import errors with pyinstaller.
Called from:
qualcoder.MainWindow.about
... | class DialogInformation(QtWidgets.QDialog):
| """
Dialog to display about information from html and text files for PyQDA development,
version and license.
The html is coded below because it avoids potential data file import errors with pyinstaller.
Called from:
qualcoder.MainWindow.about
view_graph_original.ViewGraphOriginal.l... | GUIs.
tb_obj: exception.__traceback__ """
tb = '\n'.join(traceback.format_tb(tb_obj))
text = 'Traceback (most recent call last):\n' + tb + '\n' + exception_type.__name__ + ': ' + str(value)
print(text)
logger.error(_("Uncaught exception: ") + text)
QtWidgets.QMessageBox.critical(None, _('Uncaug... | 102 | 102 | 340 | 8 | 94 | fmagin/QualCoder | qualcoder/GUI/information.py | Python | DialogInformation | DialogInformation | 50 | 92 | 50 | 50 | dc443be7c1cf68d2a08fcc7de5d16bbfb6b3ff6b | bigcode/the-stack | train |
a575fa78d87a22f7c4447756 | train | class | class HoneyPotCommand:
"""
This is the super class for all commands in cowrie/commands
"""
safeoutfile: str = ""
def __init__(self, protocol, *args):
self.protocol = protocol
self.args = list(args)
self.environ = self.protocol.cmdstack[0].environ
self.fs = self.prot... | class HoneyPotCommand:
| """
This is the super class for all commands in cowrie/commands
"""
safeoutfile: str = ""
def __init__(self, protocol, *args):
self.protocol = protocol
self.args = list(args)
self.environ = self.protocol.cmdstack[0].environ
self.fs = self.protocol.fs
self.da... | # Copyright (c) 2009-2014 Upi Tamminen <desaster@gmail.com>
# See the COPYRIGHT file for more information
"""
This module contains code to run a command
"""
import os
import re
import shlex
import stat
import time
from typing import Callable
from twisted.internet import error
from twisted.python import failure, log... | 98 | 256 | 1,343 | 5 | 92 | eeload/cowrie | src/cowrie/shell/command.py | Python | HoneyPotCommand | HoneyPotCommand | 23 | 197 | 23 | 23 | 871835f402c950d0982dde7450d518c406884580 | bigcode/the-stack | train |
d7e983c070ab1817805efd87 | train | class | class SecurityGroupTabTests(test.TestCase):
def setUp(self):
super(SecurityGroupTabTests, self).setUp()
@test.create_stubs({api.network: ('floating_ip_supported',
'tenant_floating_ip_list',
'security_group_list',
... | class SecurityGroupTabTests(test.TestCase):
| def setUp(self):
super(SecurityGroupTabTests, self).setUp()
@test.create_stubs({api.network: ('floating_ip_supported',
'tenant_floating_ip_list',
'security_group_list',
'floating_ip_pools_l... | ['private'][0]['addr'] = "10.0.0.5"
servers.append(server3)
targets = [api.nova.FloatingIpTarget(s) for s in servers]
api.network.tenant_floating_ip_list(
IsA(http.HttpRequest)) \
.AndReturn(self.floating_ips.list())
api.network.floating_ip_target_list(
... | 256 | 256 | 1,092 | 9 | 246 | ankur-gupta91/block_storage | openstack_dashboard/dashboards/project/access_and_security/tests.py | Python | SecurityGroupTabTests | SecurityGroupTabTests | 166 | 297 | 166 | 166 | 17082e869a398936b7e781a91ef29108aa4b7e35 | bigcode/the-stack | train |
7894a3d15ae9285d681c2728 | train | class | class AccessAndSecurityTests(test.TestCase):
def setUp(self):
super(AccessAndSecurityTests, self).setUp()
@test.create_stubs({api.network: ('floating_ip_supported',
'tenant_floating_ip_list',
'floating_ip_pools_list',
... | class AccessAndSecurityTests(test.TestCase):
| def setUp(self):
super(AccessAndSecurityTests, self).setUp()
@test.create_stubs({api.network: ('floating_ip_supported',
'tenant_floating_ip_list',
'floating_ip_pools_list',
'security_group_... | .
#
# Copyright 2012 Nebula, Inc.
#
# 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 a... | 256 | 256 | 1,152 | 9 | 247 | ankur-gupta91/block_storage | openstack_dashboard/dashboards/project/access_and_security/tests.py | Python | AccessAndSecurityTests | AccessAndSecurityTests | 36 | 157 | 36 | 36 | fc42d0f04e7af1438ef1a31663c2178e3c7e1f0b | bigcode/the-stack | train |
edcb353167e970dfb7ef37ad | train | class | class AccessAndSecurityNeutronProxyTests(AccessAndSecurityTests):
def setUp(self):
super(AccessAndSecurityNeutronProxyTests, self).setUp()
self.floating_ips = self.floating_ips_uuid
| class AccessAndSecurityNeutronProxyTests(AccessAndSecurityTests):
| def setUp(self):
super(AccessAndSecurityNeutronProxyTests, self).setUp()
self.floating_ips = self.floating_ips_uuid
| ">server_1 (1)</option>')
self.assertContains(res, '<option value="101">server_1 (101)</option>')
self.assertContains(res, '<option value="2">server_2 (2)</option>')
class AccessAndSecurityNeutronProxyTests(AccessAndSecurityTests):
| 63 | 64 | 48 | 14 | 50 | ankur-gupta91/block_storage | openstack_dashboard/dashboards/project/access_and_security/tests.py | Python | AccessAndSecurityNeutronProxyTests | AccessAndSecurityNeutronProxyTests | 160 | 163 | 160 | 160 | b90f946dbd9efb78abe8d0450e13a473aa173838 | bigcode/the-stack | train |
89742966d02f112094631ce4 | train | class | class ColorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="colorsrc", parent_name="sunburst.hoverlabel.font", **kwargs
):
super(ColorsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_... | class ColorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
| def __init__(
self, plotly_name="colorsrc", parent_name="sunburst.hoverlabel.font", **kwargs
):
super(ColorsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
**kwargs,
... | import _plotly_utils.basevalidators
class ColorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
| 22 | 64 | 89 | 14 | 7 | mastermind88/plotly.py | packages/python/plotly/plotly/validators/sunburst/hoverlabel/font/_colorsrc.py | Python | ColorsrcValidator | ColorsrcValidator | 4 | 13 | 4 | 4 | 14bb4675e0dfa2a17a00d0d3a4f0c29b8b1e7d26 | bigcode/the-stack | train |
1691724bccb24d37f009bb9a | train | function | def make_directory(path):
try:
os.mkdir(path)
except OSError:
# Already exists
pass
| def make_directory(path):
| try:
os.mkdir(path)
except OSError:
# Already exists
pass
| # `[.LoadBalancerArn]` presents other issues, so this extracts out the inner, inner value.
# Similar issue for elb:describe-tags
filename = parameter[0][0]
else:
filename = parameter
return urllib.parse.quote_plus(filename)
def make_directory(path):
| 64 | 64 | 26 | 5 | 59 | tgrushka/cloudmapper | commands/collect.py | Python | make_directory | make_directory | 52 | 57 | 52 | 52 | b271dae93cf3e13ec9812b9210f704d8afa49a69 | bigcode/the-stack | train |
2c70d2bc22a7577deaf19dbc | train | function | def run(arguments):
parser = argparse.ArgumentParser()
parser.add_argument(
"--config", help="Config file name", default="config.json", type=str
)
parser.add_argument(
"--account",
help="Account to collect from",
required=False,
type=str,
dest="account_nam... | def run(arguments):
| parser = argparse.ArgumentParser()
parser.add_argument(
"--config", help="Config file name", default="config.json", type=str
)
parser.add_argument(
"--account",
help="Account to collect from",
required=False,
type=str,
dest="account_name",
)
parser... | len(failures)))
if len(failures) > 0:
print("Failures:")
for call_summary in failures:
print(
" {}.{}({}): {}".format(
call_summary["service"],
call_summary["action"],
call_summary["parameters"],
... | 88 | 88 | 296 | 4 | 84 | tgrushka/cloudmapper | commands/collect.py | Python | run | run | 488 | 536 | 488 | 488 | dbb587b60f6059d3b3acf634b4dd9a2d980cad3c | bigcode/the-stack | train |
392a2ee78e76c33ea3d96f69 | train | function | def snakecase(s):
return s.replace("-", "_")
| def snakecase(s):
| return s.replace("-", "_")
| ConnectionError, NoCredentialsError
from shared.common import get_account, custom_serializer
from botocore.config import Config
__description__ = "Run AWS API calls to collect data from the account"
MAX_RETRIES = 3
MAX_TASKS_PER_DESCRIBE = 100
def snakecase(s):
| 64 | 64 | 12 | 5 | 58 | tgrushka/cloudmapper | commands/collect.py | Python | snakecase | snakecase | 23 | 24 | 23 | 23 | ee17893d15ec5ed6b57b2caaa4d494d0ca9b7995 | bigcode/the-stack | train |
0904e2514586f2b4b6ee91db | train | function | def collect(arguments):
logging.getLogger("botocore").setLevel(logging.WARN)
account_dir = "./{}".format(arguments.account_name)
summary = []
if arguments.clean and os.path.exists("account-data/{}".format(account_dir)):
rmtree("account-data/{}".format(account_dir))
make_directory("account... | def collect(arguments):
| logging.getLogger("botocore").setLevel(logging.WARN)
account_dir = "./{}".format(arguments.account_name)
summary = []
if arguments.clean and os.path.exists("account-data/{}".format(account_dir)):
rmtree("account-data/{}".format(account_dir))
make_directory("account-data")
make_directo... | _policy"
):
print(" - Denied, which should mean this KMS has restricted access")
elif (
"AccessDeniedException" in str(e)
and call_summary["service"] == "kms"
and call_summary["action"] == "get_key_rotation_status"
):
print(" - Denied... | 256 | 256 | 2,030 | 4 | 252 | tgrushka/cloudmapper | commands/collect.py | Python | collect | collect | 200 | 485 | 200 | 200 | eb0cf4ae50ba3eba11f665fa2073b31d884e3b5e | bigcode/the-stack | train |
0f1cfa5ee8aa23a912042be0 | train | function | def get_identifier_from_parameter(parameter):
if isinstance(parameter, list):
identifier = parameter[0]
else:
identifier = parameter
return identifier
| def get_identifier_from_parameter(parameter):
| if isinstance(parameter, list):
identifier = parameter[0]
else:
identifier = parameter
return identifier
| custom_serializer
from botocore.config import Config
__description__ = "Run AWS API calls to collect data from the account"
MAX_RETRIES = 3
MAX_TASKS_PER_DESCRIBE = 100
def snakecase(s):
return s.replace("-", "_")
def get_identifier_from_parameter(parameter):
| 64 | 64 | 33 | 7 | 57 | tgrushka/cloudmapper | commands/collect.py | Python | get_identifier_from_parameter | get_identifier_from_parameter | 27 | 33 | 27 | 27 | 2da95b3896e97732bf0172136946fcfe03c309c0 | bigcode/the-stack | train |
30f0edf927c025c776052cca | train | function | def call_function(outputfile, handler, method_to_call, parameters, check, summary):
"""
Calls the AWS API function and downloads the data
check: Value to check and repeat the call if it fails
summary: Keeps tracks of failures
"""
# TODO: Decorate this with rate limiters from
# https://githu... | def call_function(outputfile, handler, method_to_call, parameters, check, summary):
| """
Calls the AWS API function and downloads the data
check: Value to check and repeat the call if it fails
summary: Keeps tracks of failures
"""
# TODO: Decorate this with rate limiters from
# https://github.com/Netflix-Skunkworks/cloudaux/blob/master/cloudaux/aws/decorators.py
data =... | Run AWS API calls to collect data from the account"
MAX_RETRIES = 3
MAX_TASKS_PER_DESCRIBE = 100
def snakecase(s):
return s.replace("-", "_")
def get_identifier_from_parameter(parameter):
if isinstance(parameter, list):
identifier = parameter[0]
else:
identifier = parameter
return ... | 256 | 256 | 1,146 | 18 | 237 | tgrushka/cloudmapper | commands/collect.py | Python | call_function | call_function | 60 | 197 | 60 | 60 | ec5ce3e164194270343a835d005c0f461c5097d4 | bigcode/the-stack | train |
27f478f0b154a40b9d778faf | train | function | def get_filename_from_parameter(parameter):
if isinstance(parameter, list):
if len(parameter) > 1:
filename = parameter[1]
elif isinstance(parameter[0], list):
# For elbv2:describe-tags we need ResourceArns as a list like `[Arn]`
# the yaml file specifies `[[.Load... | def get_filename_from_parameter(parameter):
| if isinstance(parameter, list):
if len(parameter) > 1:
filename = parameter[1]
elif isinstance(parameter[0], list):
# For elbv2:describe-tags we need ResourceArns as a list like `[Arn]`
# the yaml file specifies `[[.LoadBalancerArn]]` because just doing
... |
MAX_TASKS_PER_DESCRIBE = 100
def snakecase(s):
return s.replace("-", "_")
def get_identifier_from_parameter(parameter):
if isinstance(parameter, list):
identifier = parameter[0]
else:
identifier = parameter
return identifier
def get_filename_from_parameter(parameter):
| 64 | 64 | 138 | 7 | 56 | tgrushka/cloudmapper | commands/collect.py | Python | get_filename_from_parameter | get_filename_from_parameter | 36 | 49 | 36 | 36 | a206dd58e10b88e70550c161cceef1d95907ce3f | bigcode/the-stack | train |
00ce10db7d3f75f92cfa6ece | train | function | def error(
msg: str,
*,
time: datetime = None,
deep: Optional[str] = None,
extra: Optional[dict] = None,
) -> datetime:
"""\
Log message with specific level and return current time.
Parameters
==========
msg
Message to display.
time
A time in the past. If this... | def error(
msg: str,
*,
time: datetime = None,
deep: Optional[str] = None,
extra: Optional[dict] = None,
) -> datetime:
| """\
Log message with specific level and return current time.
Parameters
==========
msg
Message to display.
time
A time in the past. If this is passed, the time difference from then
to now is appended to `msg` as ` (HH:MM:SS)`.
If `msg` contains `{time_passed}`, t... | _signature(fn):
return partial(update_wrapper, wrapped=fn, assigned=['__doc__', '__annotations__'])
def error(
msg: str,
*,
time: datetime = None,
deep: Optional[str] = None,
extra: Optional[dict] = None,
) -> datetime:
| 63 | 64 | 205 | 40 | 23 | mruffalo/epiScanpy | episcanpy/logging.py | Python | error | error | 180 | 205 | 180 | 186 | cb8b985cd5f165e2841c390d0838e4425c2508d8 | bigcode/the-stack | train |
e58e5dd7db30925fb518241a | train | function | def _copy_docs_and_signature(fn):
return partial(update_wrapper, wrapped=fn, assigned=['__doc__', '__annotations__'])
| def _copy_docs_and_signature(fn):
| return partial(update_wrapper, wrapped=fn, assigned=['__doc__', '__annotations__'])
| from . import __version__
from ._settings import settings
print(
f'Running Scanpy {__version__}, '
f'on {datetime.now():%Y-%m-%d %H:%M}.',
file=settings.logfile,
)
def _copy_docs_and_signature(fn):
| 64 | 64 | 28 | 8 | 56 | mruffalo/epiScanpy | episcanpy/logging.py | Python | _copy_docs_and_signature | _copy_docs_and_signature | 176 | 177 | 176 | 176 | 5d18a940ecc6d68b690780de2f380265213d3d2e | bigcode/the-stack | train |
57c088de2c3990e4b0486b40 | train | function | @_copy_docs_and_signature(error)
def info(msg, *, time=None, deep=None, extra=None) -> datetime:
from ._settings import settings
return settings._root_logger.info(msg, time=time, deep=deep, extra=extra)
| @_copy_docs_and_signature(error)
def info(msg, *, time=None, deep=None, extra=None) -> datetime:
| from ._settings import settings
return settings._root_logger.info(msg, time=time, deep=deep, extra=extra)
| =None, deep=None, extra=None) -> datetime:
from ._settings import settings
return settings._root_logger.warning(msg, time=time, deep=deep, extra=extra)
@_copy_docs_and_signature(error)
def info(msg, *, time=None, deep=None, extra=None) -> datetime:
| 64 | 64 | 53 | 25 | 39 | mruffalo/epiScanpy | episcanpy/logging.py | Python | info | info | 214 | 217 | 214 | 215 | f2acbe93ca420a0ff9d6e10493b9fd9aec71f0b7 | bigcode/the-stack | train |
7d17bfc707127e09a7736876 | train | class | class _LogFormatter(logging.Formatter):
def __init__(self, fmt='{levelname}: {message}', datefmt='%Y-%m-%d %H:%M', style='{'):
super().__init__(fmt, datefmt, style)
def format(self, record: logging.LogRecord):
format_orig = self._style._fmt
if record.levelno == INFO:
self._s... | class _LogFormatter(logging.Formatter):
| def __init__(self, fmt='{levelname}: {message}', datefmt='%Y-%m-%d %H:%M', style='{'):
super().__init__(fmt, datefmt, style)
def format(self, record: logging.LogRecord):
format_orig = self._style._fmt
if record.levelno == INFO:
self._style._fmt = '{message}'
elif rec... | :
raise RuntimeError('Scanpy’s root logger somehow got more than one handler')
root.addHandler(h)
def _set_log_level(settings, level: int):
root = settings._root_logger
root.setLevel(level)
h, = root.handlers # may only be 1
h.setLevel(level)
class _LogFormatter(logging.Formatter):
| 77 | 77 | 258 | 8 | 69 | mruffalo/epiScanpy | episcanpy/logging.py | Python | _LogFormatter | _LogFormatter | 91 | 115 | 91 | 91 | bb9ad2000e2ec42b6cadf3d6a5b9ed8608bba302 | bigcode/the-stack | train |
3e8ed1280415474dad01cc75 | train | function | def _versions_dependencies(dependencies):
# this is not the same as the requirements!
for mod in dependencies:
mod_name, dist_name = mod if isinstance(mod, tuple) else (mod, mod)
try:
imp = __import__(mod_name)
yield dist_name, imp.__version__
except (ImportError,... | def _versions_dependencies(dependencies):
# this is not the same as the requirements!
| for mod in dependencies:
mod_name, dist_name = mod if isinstance(mod, tuple) else (mod, mod)
try:
imp = __import__(mod_name)
yield dist_name, imp.__version__
except (ImportError, AttributeError):
pass
| '),
'statsmodels',
('igraph', 'python-igraph'),
'louvain',
'leidenalg',
]
_DEPENDENCIES_PLOTTING = ['matplotlib', 'seaborn']
def _versions_dependencies(dependencies):
# this is not the same as the requirements!
| 64 | 64 | 77 | 18 | 46 | mruffalo/epiScanpy | episcanpy/logging.py | Python | _versions_dependencies | _versions_dependencies | 139 | 147 | 139 | 140 | f25ef4601240dcc8a222d4e6af38265ef48c096d | bigcode/the-stack | train |
9c2d05c925833b315a894144 | train | class | class _RootLogger(logging.RootLogger):
def __init__(self, level):
super().__init__(level)
self.propagate = False
_RootLogger.manager = logging.Manager(self)
def log(
self,
level: int,
msg: str,
*,
extra: Optional[dict] = None,
time: dateti... | class _RootLogger(logging.RootLogger):
| def __init__(self, level):
super().__init__(level)
self.propagate = False
_RootLogger.manager = logging.Manager(self)
def log(
self,
level: int,
msg: str,
*,
extra: Optional[dict] = None,
time: datetime = None,
deep: Optional[str] ... | """Logging and Profiling
"""
#import time as time_module
#import datetime
#from anndata import logging
#from . import settings
"""Logging and Profiling
"""
import logging
from functools import update_wrapper, partial
from logging import CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET
from datetime import datetime, tim... | 112 | 124 | 415 | 8 | 104 | mruffalo/epiScanpy | episcanpy/logging.py | Python | _RootLogger | _RootLogger | 25 | 67 | 25 | 25 | 1c810319a258f8580a2fa89ce9de3374cc857534 | bigcode/the-stack | train |
d66ce5233a9f28747fa7488b | train | function | @_copy_docs_and_signature(error)
def debug(msg, *, time=None, deep=None, extra=None) -> datetime:
from ._settings import settings
return settings._root_logger.debug(msg, time=time, deep=deep, extra=extra) | @_copy_docs_and_signature(error)
def debug(msg, *, time=None, deep=None, extra=None) -> datetime:
| from ._settings import settings
return settings._root_logger.debug(msg, time=time, deep=deep, extra=extra) | , deep=None, extra=None) -> datetime:
from ._settings import settings
return settings._root_logger.hint(msg, time=time, deep=deep, extra=extra)
@_copy_docs_and_signature(error)
def debug(msg, *, time=None, deep=None, extra=None) -> datetime:
| 64 | 64 | 53 | 25 | 39 | mruffalo/epiScanpy | episcanpy/logging.py | Python | debug | debug | 226 | 229 | 226 | 227 | b9da1dbc743ef4a0e5bd39c9d622bb458ef1c0df | bigcode/the-stack | train |
a5b9ccc0ed9377f6f4a8fc13 | train | function | def print_versions():
"""\
Versions that might influence the numerical results.
Matplotlib and Seaborn are excluded from this.
"""
from ._settings import settings
modules = ['scanpy'] + _DEPENDENCIES_NUMERICS
print(' '.join(
f'{mod}=={ver}'
for mod, ver in _versions_dependenc... | def print_versions():
| """\
Versions that might influence the numerical results.
Matplotlib and Seaborn are excluded from this.
"""
from ._settings import settings
modules = ['scanpy'] + _DEPENDENCIES_NUMERICS
print(' '.join(
f'{mod}=={ver}'
for mod, ver in _versions_dependencies(modules)
), fi... | !
for mod in dependencies:
mod_name, dist_name = mod if isinstance(mod, tuple) else (mod, mod)
try:
imp = __import__(mod_name)
yield dist_name, imp.__version__
except (ImportError, AttributeError):
pass
def print_versions():
| 64 | 64 | 88 | 4 | 59 | mruffalo/epiScanpy | episcanpy/logging.py | Python | print_versions | print_versions | 150 | 160 | 150 | 150 | 5bed304aa3ff4fde9bcc82d027ed96ed9192fa2c | bigcode/the-stack | train |
7a7f72af0f14802dd5c829bc | train | function | @_copy_docs_and_signature(error)
def hint(msg, *, time=None, deep=None, extra=None) -> datetime:
from ._settings import settings
return settings._root_logger.hint(msg, time=time, deep=deep, extra=extra)
| @_copy_docs_and_signature(error)
def hint(msg, *, time=None, deep=None, extra=None) -> datetime:
| from ._settings import settings
return settings._root_logger.hint(msg, time=time, deep=deep, extra=extra)
| =None, deep=None, extra=None) -> datetime:
from ._settings import settings
return settings._root_logger.info(msg, time=time, deep=deep, extra=extra)
@_copy_docs_and_signature(error)
def hint(msg, *, time=None, deep=None, extra=None) -> datetime:
| 64 | 64 | 54 | 25 | 39 | mruffalo/epiScanpy | episcanpy/logging.py | Python | hint | hint | 220 | 223 | 220 | 221 | 0cd5db5aa90620e8199d2274cd2d2cf39fc0b844 | bigcode/the-stack | train |
77e97cba79b745c6a1273e36 | train | function | def _set_log_file(settings):
file = settings.logfile
name = settings.logpath
root = settings._root_logger
h = logging.StreamHandler(file) if name is None else logging.FileHandler(name)
h.setFormatter(_LogFormatter())
h.setLevel(root.level)
if len(root.handlers) == 1:
root.removeHandl... | def _set_log_file(settings):
| file = settings.logfile
name = settings.logpath
root = settings._root_logger
h = logging.StreamHandler(file) if name is None else logging.FileHandler(name)
h.setFormatter(_LogFormatter())
h.setLevel(root.level)
if len(root.handlers) == 1:
root.removeHandler(root.handlers[0])
elif... | self.log(HINT, msg, time=time, deep=deep, extra=extra)
def debug(self, msg, *, time=None, deep=None, extra=None) -> datetime:
return self.log(DEBUG, msg, time=time, deep=deep, extra=extra)
def _set_log_file(settings):
| 64 | 64 | 114 | 7 | 57 | mruffalo/epiScanpy | episcanpy/logging.py | Python | _set_log_file | _set_log_file | 70 | 81 | 70 | 70 | 67d7c6f56adef17a7435a8490a425257cc2d4e84 | bigcode/the-stack | train |
7f2f1322bb10bb0ba11b31df | train | function | @_copy_docs_and_signature(error)
def warning(msg, *, time=None, deep=None, extra=None) -> datetime:
from ._settings import settings
return settings._root_logger.warning(msg, time=time, deep=deep, extra=extra)
| @_copy_docs_and_signature(error)
def warning(msg, *, time=None, deep=None, extra=None) -> datetime:
| from ._settings import settings
return settings._root_logger.warning(msg, time=time, deep=deep, extra=extra)
| msg` like `{time_passed}`.
"""
from ._settings import settings
return settings._root_logger.error(msg, time=time, deep=deep, extra=extra)
@_copy_docs_and_signature(error)
def warning(msg, *, time=None, deep=None, extra=None) -> datetime:
| 64 | 64 | 53 | 25 | 39 | mruffalo/epiScanpy | episcanpy/logging.py | Python | warning | warning | 208 | 211 | 208 | 209 | 3a2e9c3ce878a43c45077eff320a1b82c564f656 | bigcode/the-stack | train |
b952a0244ed529eefadea975 | train | function | def print_version_and_date():
"""\
Useful for starting a notebook so you see when you started working.
"""
from . import __version__
from ._settings import settings
print(
f'Running Scanpy {__version__}, '
f'on {datetime.now():%Y-%m-%d %H:%M}.',
file=settings.logfile,
... | def print_version_and_date():
| """\
Useful for starting a notebook so you see when you started working.
"""
from . import __version__
from ._settings import settings
print(
f'Running Scanpy {__version__}, '
f'on {datetime.now():%Y-%m-%d %H:%M}.',
file=settings.logfile,
)
| from ._settings import settings
modules = ['scanpy'] + _DEPENDENCIES_NUMERICS
print(' '.join(
f'{mod}=={ver}'
for mod, ver in _versions_dependencies(modules)
), file=settings.logfile)
def print_version_and_date():
| 64 | 64 | 82 | 6 | 58 | mruffalo/epiScanpy | episcanpy/logging.py | Python | print_version_and_date | print_version_and_date | 163 | 173 | 163 | 163 | e6fb6f4ebb3e4632a642fd59941f8e5c23c51eca | bigcode/the-stack | train |
41468e4f73473f0c2ee1e538 | train | function | def _set_log_level(settings, level: int):
root = settings._root_logger
root.setLevel(level)
h, = root.handlers # may only be 1
h.setLevel(level)
| def _set_log_level(settings, level: int):
| root = settings._root_logger
root.setLevel(level)
h, = root.handlers # may only be 1
h.setLevel(level)
| )
if len(root.handlers) == 1:
root.removeHandler(root.handlers[0])
elif len(root.handlers) > 1:
raise RuntimeError('Scanpy’s root logger somehow got more than one handler')
root.addHandler(h)
def _set_log_level(settings, level: int):
| 64 | 64 | 45 | 11 | 53 | mruffalo/epiScanpy | episcanpy/logging.py | Python | _set_log_level | _set_log_level | 84 | 88 | 84 | 84 | d65ce6c7ba4baf0e440383ce3d95fce4fb8d393c | bigcode/the-stack | train |
87d9c6ac01d7091408ead430 | train | class | class FooTests(TestCase):
def test_foo(self):
pass
| class FooTests(TestCase):
| def test_foo(self):
pass
| from django.test import TestCase
'''
No tests here.
All of the tests are in $ROOT/tests folder and could be run with script $ROOT/runtests.py
'''
class FooTests(TestCase):
| 42 | 64 | 16 | 6 | 36 | kojdjak/django-reservations | reservations/tests.py | Python | FooTests | FooTests | 11 | 13 | 11 | 11 | c3f1f384e9d42709c4abb09a7f007d55fa18c8c9 | bigcode/the-stack | train |
e7e3674905d5159c2af1ff05 | train | function | def consult_plate(placa,save_csv=False):
def __get_info():
infos_to_get = ["Marca:","Modelo:","Importado:","Ano:","Cor:","Cilindrada:",
"Potencia:","Combustível:","UF:","Município:"]
infos_obtained = []
for info in infos_to_get:
try:
ret = tds_li... | def consult_plate(placa,save_csv=False):
| def __get_info():
infos_to_get = ["Marca:","Modelo:","Importado:","Ano:","Cor:","Cilindrada:",
"Potencia:","Combustível:","UF:","Município:"]
infos_obtained = []
for info in infos_to_get:
try:
ret = tds_list[tds_list.index(info) + 1]
... | from bs4 import BeautifulSoup as bs
import requests
import re
import cv2
import numpy as np
from PIL import Image, ImageFont, ImageDraw
def consult_plate(placa,save_csv=False):
| 46 | 132 | 441 | 11 | 34 | Z3t4Byt3/ALPR-YOLOv4 | plate_manager.py | Python | consult_plate | consult_plate | 8 | 40 | 8 | 8 | be78850d129c9627ebd44f06f0f9a8da8ccf8935 | bigcode/the-stack | train |
4e42eebdad6c96584c6ce6d2 | train | function | def treat_plate(plate_content):
try:
forbiden_symbols = [":",",",".","'",'"',";","[","{","]","}","\\","/"," ","-","="]
for symbol in forbiden_symbols:
plate_content = plate_content.replace(symbol,"")
plate_content = plate_content.strip()
re_plate = "[A-Z]{3}[0-9][0-9A-Z][... | def treat_plate(plate_content):
| try:
forbiden_symbols = [":",",",".","'",'"',";","[","{","]","}","\\","/"," ","-","="]
for symbol in forbiden_symbols:
plate_content = plate_content.replace(symbol,"")
plate_content = plate_content.strip()
re_plate = "[A-Z]{3}[0-9][0-9A-Z][0-9]{2}"
if re.match(re_... | 1]['data-src']
info = [venal,marca,modelo,importado,ano,cor,cilindrada,potencia,combustivel,uf,municipio,placa,placa_resource]
return info
except: return False
def treat_plate(plate_content):
| 64 | 64 | 131 | 7 | 56 | Z3t4Byt3/ALPR-YOLOv4 | plate_manager.py | Python | treat_plate | treat_plate | 42 | 52 | 42 | 42 | 96dbdf8c6f799c7f3e806b4f68ad9086333831de | bigcode/the-stack | train |
1d56a428fb05c6c90e56dab4 | train | function | def make_draw(image,position,plate_resource,venal,marca,cor):
#reading images
square = 'resource/square.png'
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.55"}
req = requests.get(plate_resource,h... | def make_draw(image,position,plate_resource,venal,marca,cor):
#reading images
| square = 'resource/square.png'
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.55"}
req = requests.get(plate_resource,headers=headers).content
plate = 'plate.webp'
with open(plate, 'wb+') as f:... | = cilindrada.replace("cc","").strip() if cilindrada != None else None
potencia = potencia.replace("cv","").strip() if potencia != None else None
placa_resource = cs.findAll("img")[1]['data-src']
info = [venal,marca,modelo,importado,ano,cor,cilindrada,potencia,combustivel,uf,municipio,p... | 256 | 256 | 1,119 | 22 | 233 | Z3t4Byt3/ALPR-YOLOv4 | plate_manager.py | Python | make_draw | make_draw | 54 | 141 | 54 | 55 | 30924902212b0a654930164476cd27fbf0bfb146 | bigcode/the-stack | train |
e6cdc32ec2a5f3b52325c8a6 | train | function | def tpub_update(args=None):
"""Interactively query ADS for new publications."""
parser = argparse.ArgumentParser(
description="Interactively query ADS for new publications.")
parser.add_argument('-f', metavar='dbfile',
type=str, default=DEFAULT_DB,
hel... | def tpub_update(args=None):
| """Interactively query ADS for new publications."""
parser = argparse.ArgumentParser(
description="Interactively query ADS for new publications.")
parser.add_argument('-f', metavar='dbfile',
type=str, default=DEFAULT_DB,
help="Location of the TESS publ... | .add_argument('-f', metavar='dbfile',
type=str, default=DEFAULT_DB,
help="Location of the TESS publication list db. "
"Defaults to ~/.tpub.db.")
args = parser.parse_args(args)
PublicationDB(args.f).plot()
def tpub_update(args=None):
| 64 | 64 | 126 | 7 | 57 | elisaquintana/wpub | tpub/tpub.py | Python | tpub_update | tpub_update | 596 | 608 | 596 | 596 | aa1982f110dded14cb480208f37b54c3609c21de | bigcode/the-stack | train |
25c620c3bc6ad47d559e49b7 | train | function | def tpub_add(args=None):
"""Add a publication with a known ADS bibcode."""
parser = argparse.ArgumentParser(
description="Add a paper to the TESS publication list.")
parser.add_argument('-f', metavar='dbfile',
type=str, default=DEFAULT_DB,
help="Locati... | def tpub_add(args=None):
| """Add a publication with a known ADS bibcode."""
parser = argparse.ArgumentParser(
description="Add a paper to the TESS publication list.")
parser.add_argument('-f', metavar='dbfile',
type=str, default=DEFAULT_DB,
help="Location of the TESS publicatio... | "Defaults to ~/.tpub.db.")
parser.add_argument('month', nargs='?', default=None,
help='Month to query, e.g. 2015-06.')
args = parser.parse_args(args)
PublicationDB(args.f).update(month=args.month)
def tpub_add(args=None):
| 64 | 64 | 144 | 7 | 57 | elisaquintana/wpub | tpub/tpub.py | Python | tpub_add | tpub_add | 611 | 625 | 611 | 611 | 53156b98095d40fe77b98ac14030ade94f287e49 | bigcode/the-stack | train |
73aa395146d840a2911ee704 | train | function | def tpub_export(args=None):
"""Export the bibcodes and classifications in CSV format."""
parser = argparse.ArgumentParser(
description="Export the TESS publication list in CSV format.")
parser.add_argument('-f', metavar='dbfile',
type=str, default=DEFAULT_DB,
... | def tpub_export(args=None):
| """Export the bibcodes and classifications in CSV format."""
parser = argparse.ArgumentParser(
description="Export the TESS publication list in CSV format.")
parser.add_argument('-f', metavar='dbfile',
type=str, default=DEFAULT_DB,
help="Location of th... | )
for line in ProgressBar(open(args.csvfile, 'r').readlines()):
col = line.split(',') # Naive csv parsing
db.add_by_bibcode(col[0], mission=col[1], science=col[2].strip())
def tpub_export(args=None):
| 64 | 64 | 152 | 7 | 57 | elisaquintana/wpub | tpub/tpub.py | Python | tpub_export | tpub_export | 671 | 685 | 671 | 671 | 698b1156fbbbb44dffc9f2ad1d890f335dd5fef2 | bigcode/the-stack | train |
21e68a85da5bd6b9d47eb821 | train | function | def tpub_import(args=None):
"""Import publications from a csv file.
The csv file must contain entries of the form "bibcode,mission,science".
The actual metadata of each publication will be grabbed using the ADS API,
hence this routine may take 10-20 minutes to complete.
"""
parser = argparse.Ar... | def tpub_import(args=None):
| """Import publications from a csv file.
The csv file must contain entries of the form "bibcode,mission,science".
The actual metadata of each publication will be grabbed using the ADS API,
hence this routine may take 10-20 minutes to complete.
"""
parser = argparse.ArgumentParser(
descri... | ESS publication list db. "
"Defaults to ~/.tpub.db.")
parser.add_argument('bibcode', nargs='+',
help='ADS bibcode that identifies the publication.')
args = parser.parse_args(args)
db = PublicationDB(args.f)
for bibcode in args.bibcode:
db.del... | 81 | 81 | 272 | 7 | 74 | elisaquintana/wpub | tpub/tpub.py | Python | tpub_import | tpub_import | 645 | 668 | 645 | 645 | 1a0136d40d183b05c6ad9538525a66a370b53361 | bigcode/the-stack | train |
6d0bdb320f0b5d78dde2fa57 | train | function | def tpub(args=None):
"""Lists the publications in the database in Markdown format."""
parser = argparse.ArgumentParser(
description="View the TESS publication list in markdown format.")
parser.add_argument('-f', metavar='dbfile',
type=str, default=DEFAULT_DB,
... | def tpub(args=None):
| """Lists the publications in the database in Markdown format."""
parser = argparse.ArgumentParser(
description="View the TESS publication list in markdown format.")
parser.add_argument('-f', metavar='dbfile',
type=str, default=DEFAULT_DB,
help="Locatio... | True
# Ignore articles already in the database
if article in self:
ignore = True
# Ignore all the unrefereed non-arxiv stuff
try:
if "NOT REFEREED" in article.property and article.pub != "ArXiv e-prints":
ignore = Tru... | 196 | 196 | 655 | 6 | 190 | elisaquintana/wpub | tpub/tpub.py | Python | tpub | tpub | 507 | 580 | 507 | 507 | 99830b2bc406e4a19fc519f9cd2ea465772d9e26 | bigcode/the-stack | train |
4dce3475c98c353a692acc5b | train | function | def tpub_spreadsheet(args=None):
"""Export the publication database to an Excel spreadsheet."""
try:
import pandas as pd
except ImportError:
print('ERROR: pandas needs to be installed for this feature.')
parser = argparse.ArgumentParser(
description="Export the TESS publication ... | def tpub_spreadsheet(args=None):
| """Export the publication database to an Excel spreadsheet."""
try:
import pandas as pd
except ImportError:
print('ERROR: pandas needs to be installed for this feature.')
parser = argparse.ArgumentParser(
description="Export the TESS publication list in XLS format.")
parser.... | type=str, default=DEFAULT_DB,
help="Location of the TESS publication list db. "
"Defaults to ~/.tpub.db.")
args = parser.parse_args(args)
db = PublicationDB(args.f)
cur = db.con.execute("SELECT bibcode, mission, science "
... | 110 | 111 | 373 | 9 | 101 | elisaquintana/wpub | tpub/tpub.py | Python | tpub_spreadsheet | tpub_spreadsheet | 688 | 729 | 688 | 688 | e009dac41f97acbff447bb49969b1e58b1fba911 | bigcode/the-stack | train |
f1c9a01a9a9e7b91c16627cd | train | function | def tpub_delete(args=None):
"""Deletes a publication using its ADS bibcode."""
parser = argparse.ArgumentParser(
description="Deletes a paper from the TESS publication list.")
parser.add_argument('-f', metavar='dbfile',
type=str, default=DEFAULT_DB,
he... | def tpub_delete(args=None):
| """Deletes a publication using its ADS bibcode."""
parser = argparse.ArgumentParser(
description="Deletes a paper from the TESS publication list.")
parser.add_argument('-f', metavar='dbfile',
type=str, default=DEFAULT_DB,
help="Location of the TESS pub... | bibcode', nargs='+',
help='ADS bibcode that identifies the publication.')
args = parser.parse_args(args)
db = PublicationDB(args.f)
for bibcode in args.bibcode:
db.add_by_bibcode(bibcode, interactive=True)
def tpub_delete(args=None):
| 64 | 64 | 140 | 7 | 57 | elisaquintana/wpub | tpub/tpub.py | Python | tpub_delete | tpub_delete | 628 | 642 | 628 | 628 | da703a5de129476691c02649f1d458f7621db072 | bigcode/the-stack | train |
e3c0a729481530e454c490c6 | train | function | def tpub_plot(args=None):
"""Creates beautiful plots of the database."""
parser = argparse.ArgumentParser(
description="Creates beautiful plots of the database.")
parser.add_argument('-f', metavar='dbfile',
type=str, default=DEFAULT_DB,
help="Location ... | def tpub_plot(args=None):
| """Creates beautiful plots of the database."""
parser = argparse.ArgumentParser(
description="Creates beautiful plots of the database.")
parser.add_argument('-f', metavar='dbfile',
type=str, default=DEFAULT_DB,
help="Location of the TESS publication li... | = None
mission = None
output = db.to_markdown(group_by_month=args.month,
mission=mission,
science=science)
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE, SIG_DFL)
print(output)
def tpub_plot(args=Non... | 64 | 64 | 92 | 7 | 57 | elisaquintana/wpub | tpub/tpub.py | Python | tpub_plot | tpub_plot | 583 | 593 | 583 | 583 | 3749f89a12828de103a7069400c021b8d47323ec | bigcode/the-stack | train |
8d7740467f464f14438c5e3d | train | class | class PublicationDB(object):
"""Class wrapping the SQLite database containing the publications.
Parameters
----------
filename : str
Path to the SQLite database file.
"""
def __init__(self, filename=DEFAULT_DB):
self.filename = filename
self.con = sql.connect(filename)
... | class PublicationDB(object):
| """Class wrapping the SQLite database containing the publications.
Parameters
----------
filename : str
Path to the SQLite database file.
"""
def __init__(self, filename=DEFAULT_DB):
self.filename = filename
self.con = sql.connect(filename)
pubs_table_exists = se... | date', 'pub', 'id', 'volume', 'links_data', 'citation', 'doi',
'eid', 'keyword_schema', 'citation_count', 'year', 'identifier',
'keyword_norm', 'reference', 'abstract', 'recid',
'alternate_bibcode', 'arxiv_class', 'bibcode', 'first_author_norm',
'pubdate', 'reader', 'doctype', 't... | 256 | 256 | 3,607 | 5 | 251 | elisaquintana/wpub | tpub/tpub.py | Python | PublicationDB | PublicationDB | 56 | 504 | 56 | 56 | d23da222c07dcdea6c9e835c3daa299c1d1bacc7 | bigcode/the-stack | train |
5a89d84a9e2a287b32ad543c | train | class | class Highlight:
"""Defines colors for highlighting words in the terminal."""
RED = "\033[4;31m"
GREEN = "\033[4;32m"
YELLOW = "\033[4;33m"
BLUE = "\033[4;34m"
PURPLE = "\033[4;35m"
CYAN = "\033[4;36m"
END = '\033[0m'
| class Highlight:
| """Defines colors for highlighting words in the terminal."""
RED = "\033[4;31m"
GREEN = "\033[4;32m"
YELLOW = "\033[4;33m"
BLUE = "\033[4;34m"
PURPLE = "\033[4;35m"
CYAN = "\033[4;36m"
END = '\033[0m'
| author', 'email', 'orcid', 'keyword', 'author_norm',
'cite_read_boost', 'database', 'classic_factor', 'ack', 'page',
'first_author', 'read_count', 'indexstamp', 'issue', 'keyword_facet',
'aff']
class Highlight:
| 64 | 64 | 92 | 3 | 61 | elisaquintana/wpub | tpub/tpub.py | Python | Highlight | Highlight | 45 | 53 | 45 | 45 | 7654c23c80613242bbadd200dcb615b70a638e68 | bigcode/the-stack | train |
ffff0a25224295ff49ca078a | train | function | def divisibleSumPairs(n, k, ar):
count=0
for i in range(len(ar)):
for j in range(i+1,len(ar)):
if((ar[i]+ar[j])%k==0):
count+=1
return count
| def divisibleSumPairs(n, k, ar):
| count=0
for i in range(len(ar)):
for j in range(i+1,len(ar)):
if((ar[i]+ar[j])%k==0):
count+=1
return count
| #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the divisibleSumPairs function below.
def divisibleSumPairs(n, k, ar):
| 39 | 64 | 57 | 10 | 29 | KusalR/Hackerrank-Problem-Solving-Python- | Divisible Sum Pairs/Divisible_Sum_Pairs.py | Python | divisibleSumPairs | divisibleSumPairs | 10 | 16 | 10 | 10 | 4bc0bfcbb9ae9848458d491a7b7d1f4689b5562e | bigcode/the-stack | train |
c9201b7e1b2decd5e98a42e1 | train | class | class Location(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value... | class Location(ModelNormal):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a c... | """
The Plaid API
The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from plaid.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal... | 141 | 256 | 1,632 | 5 | 136 | Aky87/plaid-python | plaid/model/location.py | Python | Location | Location | 28 | 201 | 28 | 28 | b92967baf777e64d2aaad11f32b5097645c2f07a | bigcode/the-stack | train |
a44ca9d32d944d5cda9032bf | train | function | def load_vector(filepath: str):
return gpd.read_file(filepath)
| def load_vector(filepath: str):
| return gpd.read_file(filepath)
|
arr = xr.open_dataset(file_path, chunks={'x': 512, 'y': 512})[layername]
arr['name'] = file_path
else:
raise TypeError(f"Unable to load raster {file_path}")
return arr
def load_vector(filepath: str):
| 64 | 64 | 15 | 7 | 56 | giancastro/mapshader | mapshader/io.py | Python | load_vector | load_vector | 38 | 39 | 38 | 38 | 3cb35c7edc4bfdff5834571973f5a312642ecf05 | bigcode/the-stack | train |
2cf87ab8a24170eb01945584 | train | function | def load_raster(file_path, xmin=None, ymin=None,
xmax=None, ymax=None, chunks=None,
layername='data'):
if file_path.endswith('.tif'):
arr = xr.open_rasterio(expanduser(file_path),
chunks={'y': 512, 'x': 512})
if hasattr(arr, 'nodatava... | def load_raster(file_path, xmin=None, ymin=None,
xmax=None, ymax=None, chunks=None,
layername='data'):
| if file_path.endswith('.tif'):
arr = xr.open_rasterio(expanduser(file_path),
chunks={'y': 512, 'x': 512})
if hasattr(arr, 'nodatavals'):
if np.issubdtype(arr.data.dtype, np.integer):
arr.data = arr.data.astype('f8')
for val i... | from os.path import expanduser
import geopandas as gpd
import numpy as np
import xarray as xr
def load_raster(file_path, xmin=None, ymin=None,
xmax=None, ymax=None, chunks=None,
layername='data'):
| 55 | 64 | 208 | 30 | 24 | giancastro/mapshader | mapshader/io.py | Python | load_raster | load_raster | 8 | 35 | 8 | 11 | 868e168a24f2770396b85eac83eef94609c68479 | bigcode/the-stack | train |
53632035b53d4b8f12ac014c | train | class | class RadioBrowserSearchWindow(object):
NUMBER_OF_WIDGETS_AFTER_SEARCH_SECTION = 3
_cnf = None
search_by_items = (
'Votes',
'Clicks',
'Recent click',
'Recently changed'
)
sort_by_items = (
'No sorting',
'Random',
'Name',
'Tag',
... | class RadioBrowserSearchWindow(object):
| NUMBER_OF_WIDGETS_AFTER_SEARCH_SECTION = 3
_cnf = None
search_by_items = (
'Votes',
'Clicks',
'Recent click',
'Recently changed'
)
sort_by_items = (
'No sorting',
'Random',
'Name',
'Tag',
'Country',
'State',
'... | for n in self._widgets():
try:
self._widgets[n].show()
except:
self._widgets[n].show(self._win)
self._win.addstr(3, 2, 'If True, no confirmation will be asked before saving', curses.color_pair(5))
self._win.addstr(6, 2, 'A value of -1 will disabl... | 256 | 256 | 9,897 | 7 | 248 | timgates42/pyradio | pyradio/browser.py | Python | RadioBrowserSearchWindow | RadioBrowserSearchWindow | 1,680 | 2,741 | 1,680 | 1,681 | 1c16c5064efefb9835d430c9a52e72978350f092 | bigcode/the-stack | train |
78c5621382881d0d51530c47 | train | function | def country_from_server(a_server):
if a_server:
country = a_server.split('.')[0]
up = country[:-1].upper()
if up in countries.keys():
return countries[up]
else:
return country
else:
return None
| def country_from_server(a_server):
| if a_server:
country = a_server.split('.')[0]
up = country[:-1].upper()
if up in countries.keys():
return countries[up]
else:
return country
else:
return None
| 'offset': -1,
}
RADIO_BROWSER_EXACT_SEARCH_TERM = {
'name': 'nameExact',
'country': 'countryExact',
'state': 'stateExact',
'language': 'languageExact',
'tag': 'tagExact'
}
def country_from_server(a_server):
| 64 | 64 | 57 | 7 | 57 | timgates42/pyradio | pyradio/browser.py | Python | country_from_server | country_from_server | 97 | 106 | 97 | 97 | c4ee5ddebdb202fc10e341c36f1185aa92b433ed | bigcode/the-stack | train |
b29f67c58d94e92d6918398f | train | class | class RadioBrowserServersSelect(object):
TITLE = ' Server Selection '
def __init__(self, parent, servers, current_server):
self._parent = parent
self.items = list(servers)
self.server = current_server
self.servers = RadioBrowserServers(
parent, servers, current_ser... | class RadioBrowserServersSelect(object):
| TITLE = ' Server Selection '
def __init__(self, parent, servers, current_server):
self._parent = parent
self.items = list(servers)
self.server = current_server
self.servers = RadioBrowserServers(
parent, servers, current_server
)
self.maxY = self.ser... | elif char in (curses.KEY_NPAGE, ):
if self.selection == len(self.items) - 1:
self.selection = 0
else:
self.selection += 5
if self.selection >= len(self.items):
self.selection = len(self.items) - 1
self._refre... | 166 | 166 | 556 | 7 | 158 | timgates42/pyradio | pyradio/browser.py | Python | RadioBrowserServersSelect | RadioBrowserServersSelect | 3,167 | 3,242 | 3,167 | 3,168 | d98b6579ac683274a79c14ad2a31ed6b02c50114 | bigcode/the-stack | train |
f4076a76ecea01d5e2f78c26 | train | class | class RadioBrowserConfigWindow(object):
TITLE = 'RadioBrowser Config'
_win = _widgets = _config = _history = _dns = None
_default_history_id = _focus = 0
_auto_save =_showed = False
invalid = False
def __init__(
self,
parent,
config,
current_hist... | class RadioBrowserConfigWindow(object):
| TITLE = 'RadioBrowser Config'
_win = _widgets = _config = _history = _dns = None
_default_history_id = _focus = 0
_auto_save =_showed = False
invalid = False
def __init__(
self,
parent,
config,
current_history=None,
default_history_id=... | += str(default_max_number_of_results)
txt += '''
# List of "search terms" (queries)
# An asterisk specifies the default search term (the
# one activated when RadioBrowser opens up)
# Default = {'type': 'topvote',
# 'term': '100',
# 'post_data': {'reverse': 'true'}
# }
#
'''
... | 256 | 256 | 1,385 | 7 | 248 | timgates42/pyradio | pyradio/browser.py | Python | RadioBrowserConfigWindow | RadioBrowserConfigWindow | 1,505 | 1,678 | 1,505 | 1,506 | ce82eeba01d86747a287c0ae50ecdbf67dfc0116 | bigcode/the-stack | train |
4e1bd1c4e66e7ab159ed8628 | train | class | class RadioBrowserDns(object):
''' Preforms query the DNS SRV record of
_api._tcp.radio-browser.info which
gives the list of server names directly
without reverse dns lookups '''
_urls = None
def __init__(self):
pass
@property
def server_urls(self):
''' Ret... | class RadioBrowserDns(object):
| ''' Preforms query the DNS SRV record of
_api._tcp.radio-browser.info which
gives the list of server names directly
without reverse dns lookups '''
_urls = None
def __init__(self):
pass
@property
def server_urls(self):
''' Returns server urls in a tuple '''... | countries':
ret, my_data['countries'] = get_countries(stop)
else:
ret, my_data[an_item] = get_data(an_item)
if stop():
if logger.isEnabledFor(logging.DEBUG):
logger.info('Asked to stop after working on "{}"...'.format(an_item))
... | 95 | 95 | 319 | 6 | 89 | timgates42/pyradio | pyradio/browser.py | Python | RadioBrowserDns | RadioBrowserDns | 2,934 | 2,988 | 2,934 | 2,934 | ff8a12602cd34030e3e6e91dacf02a38449369ed | bigcode/the-stack | train |
76d7f2c2f0c95488cefea622 | train | class | class RadioBrowserData(object):
''' Read search parameters for radio.browser.info service
parameters are:
tags, countries(and states), codecs, languages
'''
_data = {}
_connection_error = False
_lock = threading.Lock()
_stop_thread = False
_timeout = 3
data_thread =... | class RadioBrowserData(object):
| ''' Read search parameters for radio.browser.info service
parameters are:
tags, countries(and states), codecs, languages
'''
_data = {}
_connection_error = False
_lock = threading.Lock()
_stop_thread = False
_timeout = 3
data_thread = None
def __init__(self, ur... | col = {1}'.format(new_focus, col))
while True:
new_focus += 1
# logger.error('DE new_focus = {}'.format(new_focus))
if new_focus == len(col):
new_focus = 0
# logger.error('DE new_focus = {}'.format(new_focus))
# logger.error('DE col[ne... | 256 | 256 | 1,240 | 6 | 249 | timgates42/pyradio | pyradio/browser.py | Python | RadioBrowserData | RadioBrowserData | 2,743 | 2,931 | 2,743 | 2,743 | 1c46b618f23eaaf153371fb181eeaa3b9c2ff75b | bigcode/the-stack | train |
adbbb08451092ddaedd80082 | train | class | class PyRadioStationsBrowser(object):
''' A base class to get results from online radio directory services.
Actual implementations should be subclasses of this one.
'''
BROWSER_NAME = 'PyRadioStationsBrowser'
BASE_URL = ''
AUTO_SAVE_CONFIG = False
TITLE = ''
_parent = _outer_parent... | class PyRadioStationsBrowser(object):
| ''' A base class to get results from online radio directory services.
Actual implementations should be subclasses of this one.
'''
BROWSER_NAME = 'PyRadioStationsBrowser'
BASE_URL = ''
AUTO_SAVE_CONFIG = False
TITLE = ''
_parent = _outer_parent = None
_raw_stations = []
_la... | ': -1,
'state': 13,
'stateExact': 14,
'language': 10,
'languageExact': 9,
'tag': 12,
'tagList': 12,
'tagExact': 11,
'codec': 16,
'bitrateMin': -1,
'bitrateMax': -1,
'has_geo_info': -1,
'offset': -1,
}
RADIO_BROWSER_EXACT_SEARCH_TERM = {
'name': 'nameExact',
'coun... | 256 | 256 | 938 | 7 | 249 | timgates42/pyradio | pyradio/browser.py | Python | PyRadioStationsBrowser | PyRadioStationsBrowser | 114 | 280 | 114 | 114 | ceb70a5a6eaa7e7d1daebd24d574e831c193e1c8 | bigcode/the-stack | train |
92201decfc1d0e8f19faf484 | train | function | def probeBrowsers(a_browser_url):
base_url = a_browser_url.split('/')[2]
if not base_url:
base_url = a_browser_url
implementedBrowsers = PyRadioStationsBrowser.__subclasses__()
if logger.isEnabledFor(logging.INFO):
logger.info('Implemented browsers: {}'.format(implementedBrowsers))
... | def probeBrowsers(a_browser_url):
| base_url = a_browser_url.split('/')[2]
if not base_url:
base_url = a_browser_url
implementedBrowsers = PyRadioStationsBrowser.__subclasses__()
if logger.isEnabledFor(logging.INFO):
logger.info('Implemented browsers: {}'.format(implementedBrowsers))
for a_browser in implementedBrowse... | (self.items) - 1
self.show()
elif char in (ord('j'), curses.KEY_DOWN):
self.selection += 1
if self.selection == len(self.items):
self.selection = 0
self.show()
return 1
def probeBrowsers(a_browser_url):
| 64 | 64 | 144 | 8 | 55 | timgates42/pyradio | pyradio/browser.py | Python | probeBrowsers | probeBrowsers | 3,380 | 3,395 | 3,380 | 3,380 | 846af9da1a2673112a4536a1a74ae835025788b7 | bigcode/the-stack | train |
b0b8ccebecb048185b459bdb | train | class | class RadioBrowser(PyRadioStationsBrowser):
BROWSER_NAME = 'RadioBrowser'
BASE_URL = 'api.radio-browser.info'
TITLE = 'RadioBrowser '
browser_config = None
_headers = {'User-Agent': 'PyRadio/dev',
'Content-Type': 'application/json'}
_raw_stations = []
# the output f... | class RadioBrowser(PyRadioStationsBrowser):
| BROWSER_NAME = 'RadioBrowser'
BASE_URL = 'api.radio-browser.info'
TITLE = 'RadioBrowser '
browser_config = None
_headers = {'User-Agent': 'PyRadio/dev',
'Content-Type': 'application/json'}
_raw_stations = []
# the output format to use based on window width
# Defa... | of stations (0..len-1)
Returns
-------
Real/playable url or '' if failed (string)
'''
return ''
def set_played(self, id_in_list, played):
''' Note that a player has been played.
Parameters
----------
id_in_list
... | 256 | 256 | 9,959 | 8 | 247 | timgates42/pyradio | pyradio/browser.py | Python | RadioBrowser | RadioBrowser | 283 | 1,345 | 283 | 284 | a1019dae99d721512d0647d8dc92a6e60cabb316 | bigcode/the-stack | train |
6e0d2fc9573fc7b1ec79cb4c | train | class | class RadioBrowserServers(object):
''' Display RadioBrowser server
This is supposed to be pluged into
another widget
'''
_too_small = False
def __init__(self, parent, servers, current_server):
self._parent = parent
self.items = list(servers)
self.server = curren... | class RadioBrowserServers(object):
| ''' Display RadioBrowser server
This is supposed to be pluged into
another widget
'''
_too_small = False
def __init__(self, parent, servers, current_server):
self._parent = parent
self.items = list(servers)
self.server = current_server
s_max = 0
... | win = curses.newwin(
self.maxY, self.maxX,
Y + int((pY - self.maxY) / 2),
int((pX - self.maxX) / 2)
)
self._win.bkgdset(' ', curses.color_pair(3))
# self._win.erase()
self._win.box()
self._win.addstr(
0, int((self.maxX - len(self.TI... | 256 | 256 | 923 | 6 | 249 | timgates42/pyradio | pyradio/browser.py | Python | RadioBrowserServers | RadioBrowserServers | 3,245 | 3,377 | 3,245 | 3,245 | c6fe7cb9663830bdcf40e65fc98464c54507fafe | bigcode/the-stack | train |
dbe5f077f4a78865d6e453a7 | train | class | class RadioBrowserSort(object):
TITLE = ' Sort by '
items = collections.OrderedDict({
'Name': 'name',
'Votes': 'votes',
'Clicks': 'clickcount',
'Bitrate': 'bitrate',
'Codec': 'codec',
'Country': 'country',
'State': 'state',
'Language': 'language'... | class RadioBrowserSort(object):
| TITLE = ' Sort by '
items = collections.OrderedDict({
'Name': 'name',
'Votes': 'votes',
'Clicks': 'clickcount',
'Bitrate': 'bitrate',
'Codec': 'codec',
'Country': 'country',
'State': 'state',
'Language': 'language',
'Tag': 'tags'
})
... | ):
''' Returns server urls in a tuple '''
if self._urls is None:
self._get_urls()
return tuple(self._urls) if self._urls is not None else None
@server_urls.setter
def server_urls(self, val):
return
def _get_urls(self):
self._urls = []
result = N... | 256 | 256 | 1,234 | 6 | 249 | timgates42/pyradio | pyradio/browser.py | Python | RadioBrowserSort | RadioBrowserSort | 2,990 | 3,164 | 2,990 | 2,991 | ec694289c67d78add441ec1f4c84f281ad1172e1 | bigcode/the-stack | train |
be1777ad496838fa1488d848 | train | function | def capitalize_comma_separated_string(a_string):
sp = a_string.split(',')
for i, n in enumerate(sp):
sp[i] = n.strip().capitalize()
return ', '.join(sp)
| def capitalize_comma_separated_string(a_string):
| sp = a_string.split(',')
for i, n in enumerate(sp):
sp[i] = n.strip().capitalize()
return ', '.join(sp)
| _server(a_server):
if a_server:
country = a_server.split('.')[0]
up = country[:-1].upper()
if up in countries.keys():
return countries[up]
else:
return country
else:
return None
def capitalize_comma_separated_string(a_string):
| 64 | 64 | 43 | 10 | 53 | timgates42/pyradio | pyradio/browser.py | Python | capitalize_comma_separated_string | capitalize_comma_separated_string | 108 | 112 | 108 | 108 | 6417ea6cad8d6638e8175b46eb2da512ffbabf85 | bigcode/the-stack | train |
5de912801b1a0541c2f9d48f | train | class | class RadioBrowserConfig(object):
auto_save = False
server = ''
default = 1
limit = '100'
terms = []
dirty = False
def __init__(self, stations_dir):
self.config_file = path.join(stations_dir, 'radio-browser-config')
def read_config(self):
''' RadioBrowserConfig read con... | class RadioBrowserConfig(object):
| auto_save = False
server = ''
default = 1
limit = '100'
terms = []
dirty = False
def __init__(self, stations_dir):
self.config_file = path.join(stations_dir, 'radio-browser-config')
def read_config(self):
''' RadioBrowserConfig read config '''
self.terms = [{ 't... | _search_by = self.search_by
elif self.keyboard_handler == self._server_selection_window:
if ret == 0:
self._server = self._server_selection_window.server
if logger.isEnabledFor(logging.INFO):
logger.info('RadioBrowser: user sel... | 256 | 256 | 1,131 | 6 | 250 | timgates42/pyradio | pyradio/browser.py | Python | RadioBrowserConfig | RadioBrowserConfig | 1,347 | 1,503 | 1,347 | 1,347 | 71926682683fc5a0242088370d4cb85a7cda4920 | bigcode/the-stack | train |
17760fa178ca8c138a88bf4b | train | function | def pathed_config(configuration, *paths):
"""Use alternate configuration for files in the stack trace whose path
begins with one of these paths."""
for path in paths:
config_paths[os.path.normpath(path).lower()] = configuration
| def pathed_config(configuration, *paths):
| """Use alternate configuration for files in the stack trace whose path
begins with one of these paths."""
for path in paths:
config_paths[os.path.normpath(path).lower()] = configuration
| .normpath(path).lower())
def blacklist(*paths):
"""Files which begin with a path on the blacklist will not be
included in the stack trace.
"""
for path in paths:
blacklist_paths.append(os.path.normpath(path).lower())
def pathed_config(configuration, *paths):
| 63 | 64 | 53 | 9 | 54 | gonzaloetjo/Crypto_Trading_Bot | venv/lib/python3.6/site-packages/pretty_errors/__init__.py | Python | pathed_config | pathed_config | 374 | 378 | 374 | 374 | 3efd7a1be2486e48b7885c9246078dd68b5ca50a | bigcode/the-stack | train |
edd09e855437c5acda8a4445 | train | function | def configure(
always_display_bottom = None,
arrow_head_character = None,
arrow_tail_character = None,
arrow_head_color = None,
arrow_tail_color = None,
code_color = None,
display_arrow = None,
... | def configure(
always_display_bottom = None,
arrow_head_character = None,
arrow_tail_character = None,
arrow_head_color = None,
arrow_tail_color = None,
code_color = None,
display_arrow = None,
... | """Configure settings governing how exceptions are displayed."""
config.configure(
always_display_bottom = always_display_bottom,
arrow_head_character = arrow_head_character,
arrow_tail_character = arrow_tail_character,
arrow_head_color = arrow_head_co... | def configure(
always_display_bottom = None,
arrow_head_character = None,
arrow_tail_character = None,
arrow_head_color = None,
arrow_tail_color = None,
code_color = None,
display_arrow = None,
... | 372 | 248 | 828 | 372 | 0 | gonzaloetjo/Crypto_Trading_Bot | venv/lib/python3.6/site-packages/pretty_errors/__init__.py | Python | configure | configure | 226 | 328 | 226 | 276 | bf9898c4b533ad72e83ccad9599dbbf4ce721dbe | bigcode/the-stack | train |
866a1a7e09386cf80dad094e | train | function | def excepthook(exception_type, exception_value, traceback):
"Replaces sys.excepthook to output pretty errors."
writer = exception_writer
writer.config = writer.default_config = config
if (not writer.config.top_first and exception_value.__context__
and (not exception_value.__suppre... | def excepthook(exception_type, exception_value, traceback):
| "Replaces sys.excepthook to output pretty errors."
writer = exception_writer
writer.config = writer.default_config = config
if (not writer.config.top_first and exception_value.__context__
and (not exception_value.__suppress_context__ or config.show_suppressed)):
excepthook... | , line])
return '\n'.join(lines)
def exception_name(self, exception):
"""Name of exception."""
label = str(exception)
if label.startswith("<class '"):
label = label[8:-2]
return label
def write_exception(self, exception_type, exception_value)... | 255 | 256 | 1,218 | 12 | 243 | gonzaloetjo/Crypto_Trading_Bot | venv/lib/python3.6/site-packages/pretty_errors/__init__.py | Python | excepthook | excepthook | 643 | 776 | 643 | 643 | 20f5a2f6c2d427b3ecfeba838d7d8f185c8f9552 | bigcode/the-stack | train |
d864e4998d0c1fbedfad3d7c | train | class | class PrettyErrorsConfig():
def __init__(self, instance = None):
if instance is None:
self.name = "default"
self.line_length = 0
self.full_line_newline = False
self.filename_display = FILENAME_COMPACT
... | class PrettyErrorsConfig():
| def __init__(self, instance = None):
if instance is None:
self.name = "default"
self.line_length = 0
self.full_line_newline = False
self.filename_display = FILENAME_COMPACT
self.display_time... | 36m'
WHITE = '\033[0;37m'
BRIGHT_BLACK = GREY = '\033[1;30m'
BRIGHT_RED = '\033[1;31m'
BRIGHT_GREEN = '\033[1;32m'
BRIGHT_YELLOW = '\033[1;33m'
BRIGHT_BLUE = '\033[1;34m'
BRIGHT_MAGENTA = '\033[1;35m'
BRIGHT_CYAN = '\033[1;36m'
BRIGHT_WHITE = '\033[1;37m'
BLACK_BACKGROUND = '\033[40m'... | 255 | 256 | 1,664 | 5 | 250 | gonzaloetjo/Crypto_Trading_Bot | venv/lib/python3.6/site-packages/pretty_errors/__init__.py | Python | PrettyErrorsConfig | PrettyErrorsConfig | 53 | 219 | 53 | 53 | abfe41987dd640754e1750419f194db1e10f7d60 | bigcode/the-stack | train |
fab26f9ae4e12d396114a31e | train | function | def mono():
global RESET_COLOR
RESET_COLOR = ''
configure(
name = "mono",
infix = '\n---\n',
line_number_first = True,
code_color = '| ',
exception_arg_color = '',
exception_color = '',
except... | def mono():
| global RESET_COLOR
RESET_COLOR = ''
configure(
name = "mono",
infix = '\n---\n',
line_number_first = True,
code_color = '| ',
exception_arg_color = '',
exception_color = '',
exception_file_colo... | = timestamp_color,
timestamp_function = timestamp_function,
top_first = top_first,
trace_lines_after = trace_lines_after,
trace_lines_before = trace_lines_before,
truncate_code = truncate_code,
truncate_locals ... | 63 | 64 | 160 | 3 | 60 | gonzaloetjo/Crypto_Trading_Bot | venv/lib/python3.6/site-packages/pretty_errors/__init__.py | Python | mono | mono | 331 | 355 | 331 | 331 | 39dc95f020192f6eef71d7eb9b3e8e58c7cf5756 | bigcode/the-stack | train |
73a70ae4060144dffe6e8c40 | train | class | class StdErr():
"""Replaces sys.stderr in order to scrape it, when capturing stack trace is unavailable."""
def __init__(self):
self.__in_exception = False
self.__awaiting_code = False
self.__awaiting_end = 0
self.__frames = []
self.__point_at = None
def _... | class StdErr():
| """Replaces sys.stderr in order to scrape it, when capturing stack trace is unavailable."""
def __init__(self):
self.__in_exception = False
self.__awaiting_code = False
self.__awaiting_end = 0
self.__frames = []
self.__point_at = None
def __getattr__(self, ... | (spacer) + len(value) > line_length:
length = '[' + str(len(value)) + ']'
value = value[:line_length - (len(local) + len(spacer) + len(len_spacer) + len(length))]
output += [value, len_spacer, writer.config.local_len_color, length]
... | 255 | 256 | 1,400 | 4 | 252 | gonzaloetjo/Crypto_Trading_Bot | venv/lib/python3.6/site-packages/pretty_errors/__init__.py | Python | StdErr | StdErr | 782 | 966 | 782 | 782 | fc87ca5780353fe253d7c0e24173df5446a7d00c | bigcode/the-stack | train |
622006f64d1554fb3ac3d087 | train | class | class ExceptionWriter():
"""ExceptionWriter class for outputing exceptions to the screen.
Methods beginning 'write_' are the primary candidates for overriding.
Inherit from this class, then set:
pretty_errors.exception_writer = MyExceptionWriter()
"""
def __init__(self):
sel... | class ExceptionWriter():
| """ExceptionWriter class for outputing exceptions to the screen.
Methods beginning 'write_' are the primary candidates for overriding.
Inherit from this class, then set:
pretty_errors.exception_writer = MyExceptionWriter()
"""
def __init__(self):
self.config = None
d... | _file_color = '',
filename_color = '',
function_color = '',
header_color = '',
line_color = '> ',
line_number_color = '',
link_color = '',
local_len_color = '',
local_name_color = '= ',
l... | 256 | 256 | 1,850 | 4 | 251 | gonzaloetjo/Crypto_Trading_Bot | venv/lib/python3.6/site-packages/pretty_errors/__init__.py | Python | ExceptionWriter | ExceptionWriter | 382 | 635 | 382 | 382 | 93bc2fb2ee45c211c2bb64cddab20a71878599ce | bigcode/the-stack | train |
c3e10c3866726d5e776aff76 | train | function | def blacklist(*paths):
"""Files which begin with a path on the blacklist will not be
included in the stack trace.
"""
for path in paths:
blacklist_paths.append(os.path.normpath(path).lower())
| def blacklist(*paths):
| """Files which begin with a path on the blacklist will not be
included in the stack trace.
"""
for path in paths:
blacklist_paths.append(os.path.normpath(path).lower())
| ''
)
def whitelist(*paths):
"""If the whitelist has any entries, then only files which begin with
one of its entries will be included in the stack trace.
"""
for path in paths:
whitelist_paths.append(os.path.normpath(path).lower())
def blacklist(*paths):
| 63 | 64 | 47 | 5 | 58 | gonzaloetjo/Crypto_Trading_Bot | venv/lib/python3.6/site-packages/pretty_errors/__init__.py | Python | blacklist | blacklist | 366 | 371 | 366 | 366 | a0e15d2f6361964e1e6c81373b186393325b44ca | bigcode/the-stack | train |
f3eb07c643bbfa16baf29b82 | train | function | def replace_stderr(force = False):
"""Replace sys.stderr, for cases where standard use with activate() does not work."""
if (force or not interactive_tty_only or terminal_is_interactive):
sys.stderr = StdErr()
| def replace_stderr(force = False):
| """Replace sys.stderr, for cases where standard use with activate() does not work."""
if (force or not interactive_tty_only or terminal_is_interactive):
sys.stderr = StdErr()
| .__frames = []
elif self.__is_outer_exception(line):
if config.inner_exception_message != None:
if config.inner_exception_separator:
exception_writer.write_header()
output_stderr.write(config.inner_excep... | 63 | 64 | 50 | 8 | 55 | gonzaloetjo/Crypto_Trading_Bot | venv/lib/python3.6/site-packages/pretty_errors/__init__.py | Python | replace_stderr | replace_stderr | 970 | 973 | 970 | 970 | d19c8752b0dc13576c1860a0718de2584b67211e | bigcode/the-stack | train |
58f9d76601398af48c01745f | train | function | def activate():
"""Set sys.excepthook to use pretty errors."""
sys.excepthook = excepthook
| def activate():
| """Set sys.excepthook to use pretty errors."""
sys.excepthook = excepthook
| else:
output_stderr.write(line)
def replace_stderr(force = False):
"""Replace sys.stderr, for cases where standard use with activate() does not work."""
if (force or not interactive_tty_only or terminal_is_interactive):
sys.stderr = StdErr()
def activate():... | 64 | 64 | 28 | 3 | 61 | gonzaloetjo/Crypto_Trading_Bot | venv/lib/python3.6/site-packages/pretty_errors/__init__.py | Python | activate | activate | 976 | 978 | 976 | 976 | c2da370e848afd54f07c82a113fb4ad920fc80d9 | bigcode/the-stack | train |
1c3dd083c960d630297daa39 | train | function | def whitelist(*paths):
"""If the whitelist has any entries, then only files which begin with
one of its entries will be included in the stack trace.
"""
for path in paths:
whitelist_paths.append(os.path.normpath(path).lower())
| def whitelist(*paths):
| """If the whitelist has any entries, then only files which begin with
one of its entries will be included in the stack trace.
"""
for path in paths:
whitelist_paths.append(os.path.normpath(path).lower())
| link_color = '',
local_len_color = '',
local_name_color = '= ',
local_value_color = '',
timestamp_color = '',
arrow_head_color = '',
arrow_tail_color = '',
syntax_error_color = ''
)
def whitelist(*paths):
| 63 | 64 | 54 | 5 | 58 | gonzaloetjo/Crypto_Trading_Bot | venv/lib/python3.6/site-packages/pretty_errors/__init__.py | Python | whitelist | whitelist | 358 | 363 | 358 | 358 | 5bd208088bd0c4374ceab4478efe0f47c21a7554 | bigcode/the-stack | train |
7f746eecd5090e8c74c3d76e | train | class | class DynamicController(Controller):
def __init__(self, c_id, context):
super().__init__(c_id)
self.context = context
| class DynamicController(Controller):
| def __init__(self, c_id, context):
super().__init__(c_id)
self.context = context
| init__(self, c_id):
self.c_id = c_id
self.controller = {constant.ID: c_id}
def _build(self):
return self.controller
def __define_type(self, controller_type):
self.controller[constant.TYPE] = controller_type
class DynamicController(Controller):
| 64 | 64 | 32 | 6 | 57 | NinjaGeeks/cli-python-IOTNinja | presentation/base_controllers.py | Python | DynamicController | DynamicController | 29 | 32 | 29 | 29 | ec835620a5c52f8c1491bee1f554c9f183f84034 | bigcode/the-stack | train |
ce2cdbdf3a7c94398ca2b309 | train | class | class ControllerGroup(ControllerCore):
def __init__(self, cg_id):
self.__controllerGroup = {constant.ID: cg_id, constant.CHILDREN: []}
def _build(self):
return self.__controllerGroup
def add(self, controller: Controller):
if exceptions.is_valid_param(Controller, controller):
... | class ControllerGroup(ControllerCore):
| def __init__(self, cg_id):
self.__controllerGroup = {constant.ID: cg_id, constant.CHILDREN: []}
def _build(self):
return self.__controllerGroup
def add(self, controller: Controller):
if exceptions.is_valid_param(Controller, controller):
self.__controllerGroup[constant.C... | return self.controller
def __define_type(self, controller_type):
self.controller[constant.TYPE] = controller_type
class DynamicController(Controller):
def __init__(self, c_id, context):
super().__init__(c_id)
self.context = context
class ControllerGroup(ControllerCore):
| 64 | 64 | 107 | 7 | 56 | NinjaGeeks/cli-python-IOTNinja | presentation/base_controllers.py | Python | ControllerGroup | ControllerGroup | 35 | 47 | 35 | 35 | 79bf2ddd314edc06ecb3f5396f60765c6fdbb51f | bigcode/the-stack | train |
0383151c7616024bdec225db | train | class | class ControllerCore(ABC):
@abstractmethod
def _build(self):
pass
@abstractmethod
def __define_type(self, controller_type):
pass
| class ControllerCore(ABC):
@abstractmethod
| def _build(self):
pass
@abstractmethod
def __define_type(self, controller_type):
pass
| import key_constants as constant
from abc import ABC, abstractmethod
import exceptions
class ControllerCore(ABC):
@abstractmethod
| 28 | 64 | 38 | 11 | 16 | NinjaGeeks/cli-python-IOTNinja | presentation/base_controllers.py | Python | ControllerCore | ControllerCore | 6 | 13 | 6 | 7 | 3ca8afd22d0d87f6570c93c7ab2d8993ed842da4 | bigcode/the-stack | train |
f7a74b60398bf59d5a1bff3f | train | class | class Controller(ControllerCore):
def __init__(self, c_id):
self.c_id = c_id
self.controller = {constant.ID: c_id}
def _build(self):
return self.controller
def __define_type(self, controller_type):
self.controller[constant.TYPE] = controller_type
| class Controller(ControllerCore):
| def __init__(self, c_id):
self.c_id = c_id
self.controller = {constant.ID: c_id}
def _build(self):
return self.controller
def __define_type(self, controller_type):
self.controller[constant.TYPE] = controller_type
| import key_constants as constant
from abc import ABC, abstractmethod
import exceptions
class ControllerCore(ABC):
@abstractmethod
def _build(self):
pass
@abstractmethod
def __define_type(self, controller_type):
pass
class Controller(ControllerCore):
| 61 | 64 | 67 | 6 | 54 | NinjaGeeks/cli-python-IOTNinja | presentation/base_controllers.py | Python | Controller | Controller | 16 | 26 | 16 | 17 | da5de98ae14e34e7a03b1162f712d63ab15505ed | bigcode/the-stack | train |
90ace1c8c98003119a5c60fd | train | class | class PartnerInfo(Model):
"""Partner server information for the failover group.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:param id: Required. Resource identifier of the partner serv... | class PartnerInfo(Model):
| """Partner server information for the failover group.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:param id: Required. Resource identifier of the partner server.
:type id: str
... | -8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause in... | 85 | 85 | 286 | 5 | 79 | Mannan2812/azure-cli-extensions | src/db-up/azext_db_up/vendored_sdks/azure_mgmt_sql/sql/models/partner_info.py | Python | PartnerInfo | PartnerInfo | 15 | 49 | 15 | 15 | 1097b5b4883c80f849e82b2948d0d6d59826b169 | bigcode/the-stack | train |
8be5cd491ad18626724ed8e4 | train | function | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_seealso_index(app):
text = (".. index:: seealso: docutils; reStructuredText\n"
".. index:: seealso: Python; interpreter\n"
".. index:: seealso: Sphinx; documentation tool\n")
restructuredtext.parse(app, text)
index = IndexEn... | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_seealso_index(app):
| text = (".. index:: seealso: docutils; reStructuredText\n"
".. index:: seealso: Python; interpreter\n"
".. index:: seealso: Sphinx; documentation tool\n")
restructuredtext.parse(app, text)
index = IndexEntries(app.env).create_index(app.builder)
assert len(index) == 3
assert i... | ] == ('P', [('Python', [[], [('see interpreter', [])], None])])
assert index[2] == ('S', [('Sphinx', [[], [('see documentation tool', [])], None])])
@pytest.mark.sphinx('dummy', freshenv=True)
def test_create_seealso_index(app):
| 64 | 64 | 174 | 19 | 45 | mcmtroffaes/sphinx | tests/test_environment_indexentries.py | Python | test_create_seealso_index | test_create_seealso_index | 108 | 118 | 108 | 109 | a0dac4b056ade6e7895603b76264b38a62b97d79 | bigcode/the-stack | train |
bfb0917ccf9b460cd06de5ee | train | function | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_single_index(app):
text = (".. index:: docutils\n"
".. index:: Python\n"
".. index:: pip; install\n"
".. index:: pip; upgrade\n"
".. index:: Sphinx\n"
".. index:: Ель\n"
".. index:: ёл... | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_single_index(app):
| text = (".. index:: docutils\n"
".. index:: Python\n"
".. index:: pip; install\n"
".. index:: pip; upgrade\n"
".. index:: Sphinx\n"
".. index:: Ель\n"
".. index:: ёлка\n"
".. index:: עברית\n"
".. index:: 9-symbol\n"
... | """
test_environment_indexentries
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test the sphinx.environment.managers.indexentries.
:copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import pytest
from sphinx.environment.adapters.indexentries import Index... | 97 | 125 | 417 | 18 | 78 | mcmtroffaes/sphinx | tests/test_environment_indexentries.py | Python | test_create_single_index | test_create_single_index | 17 | 46 | 17 | 18 | b059c68c6a48a39b717f6fae28a835d52b29ac2a | bigcode/the-stack | train |
a813c50aa634600f1181c123 | train | function | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_index_by_key(app):
# At present, only glossary directive is able to create index key
text = (".. glossary::\n"
"\n"
" docutils\n"
" Python\n"
" スフィンクス : ス\n")
restructuredtext.parse(app, text)
... | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_index_by_key(app):
# At present, only glossary directive is able to create index key
| text = (".. glossary::\n"
"\n"
" docutils\n"
" Python\n"
" スフィンクス : ス\n")
restructuredtext.parse(app, text)
index = IndexEntries(app.env).create_index(app.builder)
assert len(index) == 3
assert index[0] == ('D', [('docutils', [[('main', '#term-do... | ['ref1'] == ('index', 'ref1')
assert std.anonlabels['ref2'] == ('index', 'ref2')
@pytest.mark.sphinx('dummy', freshenv=True)
def test_create_index_by_key(app):
# At present, only glossary directive is able to create index key
| 64 | 64 | 189 | 34 | 30 | mcmtroffaes/sphinx | tests/test_environment_indexentries.py | Python | test_create_index_by_key | test_create_index_by_key | 158 | 171 | 158 | 160 | 3dec0d5bc7b2dba72b69f967ea31ec40272d34a7 | bigcode/the-stack | train |
0375e6dc41b8222ec81fb7ce | train | function | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_triple_index(app):
text = (".. index:: triple: foo; bar; baz\n"
".. index:: triple: Python; Sphinx; reST\n")
restructuredtext.parse(app, text)
index = IndexEntries(app.env).create_index(app.builder)
assert len(index) == 5
assert... | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_triple_index(app):
| text = (".. index:: triple: foo; bar; baz\n"
".. index:: triple: Python; Sphinx; reST\n")
restructuredtext.parse(app, text)
index = IndexEntries(app.env).create_index(app.builder)
assert len(index) == 5
assert index[0] == ('B', [('bar', [[], [('baz, foo', [('', '#index-0')])], None]),
... | ],
None])])
assert index[6] == ('Е',
[('ёлка', [[], [('Sphinx', [('', '#index-5')])], None]),
('Ель', [[], [('Sphinx', [('', '#index-4')])], None])])
@pytest.mark.sphinx('dummy', freshenv=True)
def test_create_triple_index(app):
| 79 | 79 | 265 | 19 | 60 | mcmtroffaes/sphinx | tests/test_environment_indexentries.py | Python | test_create_triple_index | test_create_triple_index | 80 | 92 | 80 | 81 | feee04641902da1527c2b5876023f6856b2cd170 | bigcode/the-stack | train |
80a5467f9892cb51a3f2cd00 | train | function | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_main_index(app):
text = (".. index:: !docutils\n"
".. index:: docutils\n"
".. index:: pip; install\n"
".. index:: !pip; install\n")
restructuredtext.parse(app, text)
index = IndexEntries(app.env).create_index(app... | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_main_index(app):
| text = (".. index:: !docutils\n"
".. index:: docutils\n"
".. index:: pip; install\n"
".. index:: !pip; install\n")
restructuredtext.parse(app, text)
index = IndexEntries(app.env).create_index(app.builder)
assert len(index) == 2
assert index[0] == ('D', [('docutils... | == ('P', [('Python', [[], [('see also interpreter', [])], None])])
assert index[2] == ('S', [('Sphinx', [[], [('see also documentation tool', [])], None])])
@pytest.mark.sphinx('dummy', freshenv=True)
def test_create_main_index(app):
| 64 | 64 | 163 | 18 | 46 | mcmtroffaes/sphinx | tests/test_environment_indexentries.py | Python | test_create_main_index | test_create_main_index | 121 | 133 | 121 | 122 | f8744f14dc9220e0b33e3b17fc83411d40bc5d42 | bigcode/the-stack | train |
7a4f6ac6bca8fc3cbae4fa5c | train | function | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_pair_index(app):
text = (".. index:: pair: docutils; reStructuredText\n"
".. index:: pair: Python; interpreter\n"
".. index:: pair: Sphinx; documentation tool\n"
".. index:: pair: Sphinx; :+1:\n"
".. index:: ... | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_pair_index(app):
| text = (".. index:: pair: docutils; reStructuredText\n"
".. index:: pair: Python; interpreter\n"
".. index:: pair: Sphinx; documentation tool\n"
".. index:: pair: Sphinx; :+1:\n"
".. index:: pair: Sphinx; Ель\n"
".. index:: pair: Sphinx; ёлка\n")
restr... | ', [[('', '#index-4')], [], None])])
assert index[4] == ('Е',
[('ёлка', [[('', '#index-6')], [], None]),
('Ель', [[('', '#index-5')], [], None])])
# Here the word starts with U+200F RIGHT-TO-LEFT MARK, which should be
# ignored when getting the first letter.
... | 133 | 133 | 445 | 18 | 115 | mcmtroffaes/sphinx | tests/test_environment_indexentries.py | Python | test_create_pair_index | test_create_pair_index | 49 | 77 | 49 | 50 | 99c66c9f456edb2c8d4671aec4f6210bbf7e5a8e | bigcode/the-stack | train |
097b49ac0400d3d214c7b4d7 | train | function | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_index_with_name(app):
text = (".. index:: single: docutils\n"
" :name: ref1\n"
".. index:: single: Python\n"
" :name: ref2\n"
".. index:: Sphinx\n")
restructuredtext.parse(app, text)
index = Index... | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_index_with_name(app):
| text = (".. index:: single: docutils\n"
" :name: ref1\n"
".. index:: single: Python\n"
" :name: ref2\n"
".. index:: Sphinx\n")
restructuredtext.parse(app, text)
index = IndexEntries(app.env).create_index(app.builder)
# check index is created correctly... | ('', '#index-1')], [], None])])
assert index[1] == ('P', [('pip', [[], [('install', [('main', '#index-3'),
('', '#index-2')])], None])])
@pytest.mark.sphinx('dummy', freshenv=True)
def test_create_index_with_name(a... | 71 | 71 | 239 | 19 | 52 | mcmtroffaes/sphinx | tests/test_environment_indexentries.py | Python | test_create_index_with_name | test_create_index_with_name | 136 | 155 | 136 | 137 | e250cd6de9e30196d7fb8574440df4ccaed284c6 | bigcode/the-stack | train |
0e15c11f8d471739e3631cae | train | function | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_see_index(app):
text = (".. index:: see: docutils; reStructuredText\n"
".. index:: see: Python; interpreter\n"
".. index:: see: Sphinx; documentation tool\n")
restructuredtext.parse(app, text)
index = IndexEntries(app.env).c... | @pytest.mark.sphinx('dummy', freshenv=True)
def test_create_see_index(app):
| text = (".. index:: see: docutils; reStructuredText\n"
".. index:: see: Python; interpreter\n"
".. index:: see: Sphinx; documentation tool\n")
restructuredtext.parse(app, text)
index = IndexEntries(app.env).create_index(app.builder)
assert len(index) == 3
assert index[0] == (... | ('', '#index-1')])], None])])
assert index[4] == ('S', [('Sphinx', [[], [('reST, Python', [('', '#index-1')])], None])])
@pytest.mark.sphinx('dummy', freshenv=True)
def test_create_see_index(app):
| 64 | 64 | 168 | 19 | 45 | mcmtroffaes/sphinx | tests/test_environment_indexentries.py | Python | test_create_see_index | test_create_see_index | 95 | 105 | 95 | 96 | 303c75d5dc486b3b4baf046c97f6770113790d18 | bigcode/the-stack | train |
a894189d626e014cb071db90 | train | function | def load_key(pubkey):
"""Load public RSA key.
Work around keys with incorrect header/footer format.
Read more about RSA encryption with cryptography:
https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/
"""
try:
return load_pem_public_key(pubkey.encode(), default_backend())... | def load_key(pubkey):
| """Load public RSA key.
Work around keys with incorrect header/footer format.
Read more about RSA encryption with cryptography:
https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/
"""
try:
return load_pem_public_key(pubkey.encode(), default_backend())
except ValueError... | from urllib import urlopen
except ImportError:
from urllib.request import urlopen
GITHUB_REPO = 'michaelaye/vpython_utils'
TRAVIS_CONFIG_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), '.travis.yml')
def load_key(pubkey):
| 64 | 64 | 128 | 6 | 58 | michaelaye/vpython_utils | travis_pypi_setup.py | Python | load_key | load_key | 28 | 41 | 28 | 28 | a7025059f0dc1754c6dbec20eabe0ad5449dd38e | bigcode/the-stack | train |
3712e6c1185dbbbbd6839c86 | train | function | def encrypt(pubkey, password):
"""Encrypt password using given RSA public key and encode it with base64.
The encrypted password can only be decrypted by someone with the
private key (in this case, only Travis).
"""
key = load_key(pubkey)
encrypted_password = key.encrypt(password, PKCS1v15())
... | def encrypt(pubkey, password):
| """Encrypt password using given RSA public key and encode it with base64.
The encrypted password can only be decrypted by someone with the
private key (in this case, only Travis).
"""
key = load_key(pubkey)
encrypted_password = key.encrypt(password, PKCS1v15())
return base64.b64encode(encry... | ValueError:
# workaround for https://github.com/travis-ci/travis-api/issues/196
pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END')
return load_pem_public_key(pubkey.encode(), default_backend())
def encrypt(pubkey, password):
| 64 | 64 | 82 | 7 | 57 | michaelaye/vpython_utils | travis_pypi_setup.py | Python | encrypt | encrypt | 44 | 52 | 44 | 44 | e6076556ef9026ffa899b06aa1021e946fa8cc99 | bigcode/the-stack | train |
820b632cd30b05f821b82d9c | train | function | def update_travis_deploy_password(encrypted_password):
"""Put `encrypted_password` into the deploy section of .travis.yml."""
config = load_yaml_config(TRAVIS_CONFIG_FILE)
config['deploy']['password'] = dict(secure=encrypted_password)
save_yaml_config(TRAVIS_CONFIG_FILE, config)
line = ('# This f... | def update_travis_deploy_password(encrypted_password):
| """Put `encrypted_password` into the deploy section of .travis.yml."""
config = load_yaml_config(TRAVIS_CONFIG_FILE)
config['deploy']['password'] = dict(secure=encrypted_password)
save_yaml_config(TRAVIS_CONFIG_FILE, config)
line = ('# This file was autogenerated and will overwrite'
'... | (filepath) as f:
return yaml.load(f)
def save_yaml_config(filepath, config):
"""Save yaml config file at the given path."""
with open(filepath, 'w') as f:
yaml.dump(config, f, default_flow_style=False)
def update_travis_deploy_password(encrypted_password):
| 64 | 64 | 106 | 11 | 53 | michaelaye/vpython_utils | travis_pypi_setup.py | Python | update_travis_deploy_password | update_travis_deploy_password | 92 | 102 | 92 | 92 | 528c288238d4ff71fbd59fb0df2ef4ccb47833ec | bigcode/the-stack | train |
35be904705f53f515da0808d | train | function | def fetch_public_key(repo):
"""Download RSA public key Travis will use for this repo.
Travis API docs: http://docs.travis-ci.com/api/#repository-keys
"""
keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo)
data = json.loads(urlopen(keyurl).read().decode())
if 'key' not in data:
... | def fetch_public_key(repo):
| """Download RSA public key Travis will use for this repo.
Travis API docs: http://docs.travis-ci.com/api/#repository-keys
"""
keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo)
data = json.loads(urlopen(keyurl).read().decode())
if 'key' not in data:
errmsg = "Could not find... | The encrypted password can only be decrypted by someone with the
private key (in this case, only Travis).
"""
key = load_key(pubkey)
encrypted_password = key.encrypt(password, PKCS1v15())
return base64.b64encode(encrypted_password)
def fetch_public_key(repo):
| 64 | 64 | 130 | 6 | 58 | michaelaye/vpython_utils | travis_pypi_setup.py | Python | fetch_public_key | fetch_public_key | 55 | 66 | 55 | 55 | e4175eb7116efb488c649725594eac07877e9775 | bigcode/the-stack | train |
b316dd9fd7aa2ac840a66c5a | train | function | def prepend_line(filepath, line):
"""Rewrite a file adding a line to its beginning."""
with open(filepath) as f:
lines = f.readlines()
lines.insert(0, line)
with open(filepath, 'w') as f:
f.writelines(lines)
| def prepend_line(filepath, line):
| """Rewrite a file adding a line to its beginning."""
with open(filepath) as f:
lines = f.readlines()
lines.insert(0, line)
with open(filepath, 'w') as f:
f.writelines(lines)
| ())
if 'key' not in data:
errmsg = "Could not find public key for repo: {}.\n".format(repo)
errmsg += "Have you already added your GitHub repo to Travis?"
raise ValueError(errmsg)
return data['key']
def prepend_line(filepath, line):
| 64 | 64 | 59 | 7 | 57 | michaelaye/vpython_utils | travis_pypi_setup.py | Python | prepend_line | prepend_line | 69 | 77 | 69 | 69 | 8d274915528465203ab35aa4cb72e779cc224814 | bigcode/the-stack | train |
e35782456c03835aa2bc59bd | train | function | def main(args):
"""Add a PyPI password to .travis.yml so that Travis can deploy to PyPI.
Fetch the Travis public key for the repo, and encrypt the PyPI password
with it before adding, so that only Travis can decrypt and use the PyPI
password.
"""
public_key = fetch_public_key(args.repo)
pas... | def main(args):
| """Add a PyPI password to .travis.yml so that Travis can deploy to PyPI.
Fetch the Travis public key for the repo, and encrypt the PyPI password
with it before adding, so that only Travis can decrypt and use the PyPI
password.
"""
public_key = fetch_public_key(args.repo)
password = args.pas... | '] = dict(secure=encrypted_password)
save_yaml_config(TRAVIS_CONFIG_FILE, config)
line = ('# This file was autogenerated and will overwrite'
' each time you run travis_pypi_setup.py\n')
prepend_line(TRAVIS_CONFIG_FILE, line)
def main(args):
| 64 | 64 | 122 | 4 | 60 | michaelaye/vpython_utils | travis_pypi_setup.py | Python | main | main | 105 | 115 | 105 | 105 | ee31684b5762483695ab7885afbe0aa096ebc4b0 | bigcode/the-stack | train |
b323cb2b11ca103450fa7bc2 | train | function | def load_yaml_config(filepath):
"""Load yaml config file at the given path."""
with open(filepath) as f:
return yaml.load(f)
| def load_yaml_config(filepath):
| """Load yaml config file at the given path."""
with open(filepath) as f:
return yaml.load(f)
| prepend_line(filepath, line):
"""Rewrite a file adding a line to its beginning."""
with open(filepath) as f:
lines = f.readlines()
lines.insert(0, line)
with open(filepath, 'w') as f:
f.writelines(lines)
def load_yaml_config(filepath):
| 64 | 64 | 31 | 6 | 58 | michaelaye/vpython_utils | travis_pypi_setup.py | Python | load_yaml_config | load_yaml_config | 80 | 83 | 80 | 80 | ef5fc31119bf75e4771a275202242c0829e779c8 | bigcode/the-stack | train |
5eca326b48115b735b50dddf | train | function | def save_yaml_config(filepath, config):
"""Save yaml config file at the given path."""
with open(filepath, 'w') as f:
yaml.dump(config, f, default_flow_style=False)
| def save_yaml_config(filepath, config):
| """Save yaml config file at the given path."""
with open(filepath, 'w') as f:
yaml.dump(config, f, default_flow_style=False)
| lines.insert(0, line)
with open(filepath, 'w') as f:
f.writelines(lines)
def load_yaml_config(filepath):
"""Load yaml config file at the given path."""
with open(filepath) as f:
return yaml.load(f)
def save_yaml_config(filepath, config):
| 64 | 64 | 42 | 8 | 56 | michaelaye/vpython_utils | travis_pypi_setup.py | Python | save_yaml_config | save_yaml_config | 86 | 89 | 86 | 86 | 5067d6c5c5b248667987a06414824eed81401282 | bigcode/the-stack | train |
e7466427f19f366b4635706e | train | class | class IsOwnerOrChrisOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object or superuser
'chris' to modify/edit it. Read only is allowed to other users.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any req... | class IsOwnerOrChrisOrReadOnly(permissions.BasePermission):
| """
Custom permission to only allow owners of an object or superuser
'chris' to modify/edit it. Read only is allowed to other users.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS r... | ':
return True
if hasattr(obj, 'plugin_inst'):
related_feed = obj.plugin_inst.feed
else:
related_feed = obj.feed
if request.user in related_feed.owner.all():
return True
return False
class IsOwnerOrChrisOrReadOnly(permissions.BasePermission... | 64 | 64 | 136 | 13 | 50 | rudolphpienaar/ChRIS_ultron_backEnd | chris_backend/plugininstances/permissions.py | Python | IsOwnerOrChrisOrReadOnly | IsOwnerOrChrisOrReadOnly | 24 | 37 | 24 | 24 | 3d323ca2e30bc2365d3d0aa874adc24686e28618 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.