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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9483c28f5c0029c9ebc4bab6 | train | function | def build_p2sh_lookup(scripts):
d1 = dict((hash160(s), s) for s in scripts)
d1.update((hashlib.sha256(s).digest(), s) for s in scripts)
return d1
| def build_p2sh_lookup(scripts):
| d1 = dict((hash160(s), s) for s in scripts)
d1.update((hashlib.sha256(s).digest(), s) for s in scripts)
return d1
| secret_exponent * generator
for compressed in (True, False):
hash160 = public_pair_to_hash160_sec(public_pair, compressed=compressed)
d[hash160] = (secret_exponent, public_pair, compressed, generator)
return d
def build_p2sh_lookup(scripts):
| 64 | 64 | 51 | 9 | 54 | jaschadub/pycoin | pycoin/solve/utils.py | Python | build_p2sh_lookup | build_p2sh_lookup | 18 | 21 | 18 | 18 | 2ce25837aecf2f42b2a38683c640c0d9519cec79 | bigcode/the-stack | train |
e73333f757cba8e10e931eb5 | train | function | def build_sec_lookup(sec_values):
d = {}
for sec in sec_values or []:
d[hash160(sec)] = sec
return d
| def build_sec_lookup(sec_values):
| d = {}
for sec in sec_values or []:
d[hash160(sec)] = sec
return d
| generator)
return d
def build_p2sh_lookup(scripts):
d1 = dict((hash160(s), s) for s in scripts)
d1.update((hashlib.sha256(s).digest(), s) for s in scripts)
return d1
def build_sec_lookup(sec_values):
| 64 | 64 | 34 | 7 | 56 | jaschadub/pycoin | pycoin/solve/utils.py | Python | build_sec_lookup | build_sec_lookup | 24 | 28 | 24 | 24 | 223eeb6603990c4e5a4b5b234563e7310f114a48 | bigcode/the-stack | train |
33994a8ee3ab8c93466cea96 | train | class | class TestTensorSum(unittest.TestCase):
def test_simple_add(self):
t1 = Tensor([1,2,3],requires_grad=True)
t2 = Tensor([4,5,6],requires_grad=True)
t3 = t1 + t2
assert t3.data.asnumpy().tolist() == [5,7,9]
t3.backward(Tensor([-1,-2,-3]))
assert t1.grad.data.asnumpy()... | class TestTensorSum(unittest.TestCase):
| def test_simple_add(self):
t1 = Tensor([1,2,3],requires_grad=True)
t2 = Tensor([4,5,6],requires_grad=True)
t3 = t1 + t2
assert t3.data.asnumpy().tolist() == [5,7,9]
t3.backward(Tensor([-1,-2,-3]))
assert t1.grad.data.asnumpy().tolist() == [-1,-2,-3]
assert t... | import unittest
from autograd.tensor import Tensor
class TestTensorSum(unittest.TestCase):
| 18 | 197 | 659 | 8 | 9 | lvyufeng/autograd_ms | tests/test_tensor_add.py | Python | TestTensorSum | TestTensorSum | 4 | 50 | 4 | 4 | b8c35c97578d50ae960ba4deb150595a7625f3d6 | bigcode/the-stack | train |
e19888384428a971ceb8089d | train | class | class RouteUpdater(MIBUpdater):
def __init__(self):
super().__init__()
self.tos = 0 # ipCidrRouteTos
self.db_conn = Namespace.init_namespace_dbs()
self.route_dest_map = {}
self.route_dest_list = []
## loopback ip string -> ip address object
self.loips = {}
... | class RouteUpdater(MIBUpdater):
| def __init__(self):
super().__init__()
self.tos = 0 # ipCidrRouteTos
self.db_conn = Namespace.init_namespace_dbs()
self.route_dest_map = {}
self.route_dest_list = []
## loopback ip string -> ip address object
self.loips = {}
def reinit_data(self):
... | import ipaddress
from sonic_ax_impl import mibs
from sonic_ax_impl.mibs import Namespace
from ax_interface import MIBMeta, ValueType, MIBUpdater, SubtreeMIBEntry
from ax_interface.util import ip2byte_tuple
from bisect import bisect_right
from sonic_py_common import multi_asic
class RouteUpdater(MIBUpdater):
| 76 | 256 | 914 | 7 | 68 | RayWang910012/sonic-snmpagent | src/sonic_ax_impl/mibs/ietf/rfc4292.py | Python | RouteUpdater | RouteUpdater | 10 | 107 | 10 | 10 | c8a1cc90db8a1aebc8a0434b43b83cb595ebdf9d | bigcode/the-stack | train |
2457ff990fbfdff228eb1f64 | train | class | class IpCidrRouteTable(metaclass=MIBMeta, prefix='.1.3.6.1.2.1.4.24.4'):
"""
'ipCidrRouteDest table in IP Forwarding Table MIB' https://tools.ietf.org/html/rfc4292
"""
route_updater = RouteUpdater()
ipCidrRouteDest = \
SubtreeMIBEntry('1.1', route_updater, ValueType.IP_ADDRESS, route_updat... | class IpCidrRouteTable(metaclass=MIBMeta, prefix='.1.3.6.1.2.1.4.24.4'):
| """
'ipCidrRouteDest table in IP Forwarding Table MIB' https://tools.ietf.org/html/rfc4292
"""
route_updater = RouteUpdater()
ipCidrRouteDest = \
SubtreeMIBEntry('1.1', route_updater, ValueType.IP_ADDRESS, route_updater.route_dest)
ipCidrRouteStatus = \
SubtreeMIBEntry('1.16',... | _right(self.route_dest_list, sub_id)
if right >= len(self.route_dest_list):
return None
return self.route_dest_list[right]
class IpCidrRouteTable(metaclass=MIBMeta, prefix='.1.3.6.1.2.1.4.24.4'):
| 64 | 64 | 140 | 33 | 31 | RayWang910012/sonic-snmpagent | src/sonic_ax_impl/mibs/ietf/rfc4292.py | Python | IpCidrRouteTable | IpCidrRouteTable | 109 | 120 | 109 | 109 | 6a75e605c9a3255f2084b0ebcc5e83ab19697727 | bigcode/the-stack | train |
4ccc965d622240cdd4a82d84 | train | class | class RedisCache:
"""
A simplified interface for a Redis connection.
We implement several convenient methods that are fairly similar to have a dict
behaves, and should be familiar to Python users. The biggest difference is that
all the public methods in this class are coroutines, and must be awaite... | class RedisCache:
| """
A simplified interface for a Redis connection.
We implement several convenient methods that are fairly similar to have a dict
behaves, and should be familiar to Python users. The biggest difference is that
all the public methods in this class are coroutines, and must be awaited.
Because of... | from __future__ import annotations
import asyncio
import logging
from functools import partialmethod
from typing import Any, Dict, ItemsView, Optional, Tuple, Union
from bot.bot import Bot
log = logging.getLogger(__name__)
# Type aliases
RedisKeyType = Union[str, int]
RedisValueType = Union[str, int, float]
RedisKe... | 242 | 256 | 3,372 | 4 | 238 | crazygmr101/bot | bot/utils/redis_cache.py | Python | RedisCache | RedisCache | 42 | 409 | 42 | 42 | 2761239ace2fa809d00c2514f754372c3f7ba854 | bigcode/the-stack | train |
9016411738eff58f20ef8050 | train | class | class NoNamespaceError(RuntimeError):
"""Raised when RedisCache has no namespace, for example if it is not assigned to a class attribute."""
| class NoNamespaceError(RuntimeError):
| """Raised when RedisCache has no namespace, for example if it is not assigned to a class attribute."""
| int),
("s|", str),
)
_KEY_PREFIXES = (
("i|", int),
("s|", str),
)
class NoBotInstanceError(RuntimeError):
"""Raised when RedisCache is created without an available bot instance on the owner class."""
class NoNamespaceError(RuntimeError):
| 63 | 64 | 29 | 7 | 56 | crazygmr101/bot | bot/utils/redis_cache.py | Python | NoNamespaceError | NoNamespaceError | 34 | 35 | 34 | 34 | 707095ce4b5dbfc16dfefb955c080c28565df535 | bigcode/the-stack | train |
2bd3116b6be548581ffda9d5 | train | class | class NoParentInstanceError(RuntimeError):
"""Raised when the parent instance is available, for example if called by accessing the parent class directly."""
| class NoParentInstanceError(RuntimeError):
| """Raised when the parent instance is available, for example if called by accessing the parent class directly."""
| NoBotInstanceError(RuntimeError):
"""Raised when RedisCache is created without an available bot instance on the owner class."""
class NoNamespaceError(RuntimeError):
"""Raised when RedisCache has no namespace, for example if it is not assigned to a class attribute."""
class NoParentInstanceError(RuntimeError... | 63 | 64 | 29 | 8 | 55 | crazygmr101/bot | bot/utils/redis_cache.py | Python | NoParentInstanceError | NoParentInstanceError | 38 | 39 | 38 | 38 | 2682f65ca682ef1063a8ff70db84b17a85c84363 | bigcode/the-stack | train |
e3dc1c5bd4138d9ce45302f2 | train | class | class NoBotInstanceError(RuntimeError):
"""Raised when RedisCache is created without an available bot instance on the owner class."""
| class NoBotInstanceError(RuntimeError):
| """Raised when RedisCache is created without an available bot instance on the owner class."""
| Tuple[Tuple[str, Any], ...]
_VALUE_PREFIXES = (
("f|", float),
("i|", int),
("s|", str),
)
_KEY_PREFIXES = (
("i|", int),
("s|", str),
)
class NoBotInstanceError(RuntimeError):
| 64 | 64 | 26 | 8 | 56 | crazygmr101/bot | bot/utils/redis_cache.py | Python | NoBotInstanceError | NoBotInstanceError | 30 | 31 | 30 | 30 | 217cfc0980d22a8aac0e24499f2a68bbb9207b0d | bigcode/the-stack | train |
5420cbbd603cc77c3282d84c | train | function | def plot_timeseries(ax, data, countries, ylabel, file_name="test.pdf"):
for country in countries:
mask = data["Country/Region"] == country
data_country = data.loc[mask].iloc[:, 40:]
x = [date[:-3] for date in data_country.columns]
y = data_country.values.sum(axis=0)
ax.p... | def plot_timeseries(ax, data, countries, ylabel, file_name="test.pdf"):
| for country in countries:
mask = data["Country/Region"] == country
data_country = data.loc[mask].iloc[:, 40:]
x = [date[:-3] for date in data_country.columns]
y = data_country.values.sum(axis=0)
ax.plot(x, y, label=country)
ax.legend(frameon=False)
ax.set_ylabel(... | import matplotlib.pyplot as plt
def plot_timeseries(ax, data, countries, ylabel, file_name="test.pdf"):
| 25 | 64 | 156 | 19 | 5 | LucaMantani/covid19 | utils/plots.py | Python | plot_timeseries | plot_timeseries | 4 | 25 | 4 | 5 | 7e3ef4d5be2968f2a5fb5ee6d05b6b03b6ba8d0d | bigcode/the-stack | train |
6d0f4518ecf8e6a56c6cbb81 | train | class | class _BaseHSP(_BaseSearchObject):
"""Abstract base class for HSP objects."""
def _str_hsp_header(self):
"""Print the alignment header info (PRIVATE)."""
lines = []
# set query id line
qid_line = trim_str(' Query: %s %s' %
(self.query_id, self.qu... | class _BaseHSP(_BaseSearchObject):
| """Abstract base class for HSP objects."""
def _str_hsp_header(self):
"""Print the alignment header info (PRIVATE)."""
lines = []
# set query id line
qid_line = trim_str(' Query: %s %s' %
(self.query_id, self.query_description), 80, '...')
... | found in the search output
file. Ideally, we want these attributes to 'stick' with any new instance
object created from the original one.
"""
# list of attribute names we don't want to transfer
for attr in self.__dict__:
if attr not in self._NON_STICKY_ATTRS:
... | 91 | 91 | 304 | 10 | 81 | oz90210/Pyto | site-packages/Bio/SearchIO/_model/_base.py | Python | _BaseHSP | _BaseHSP | 37 | 70 | 37 | 37 | 939a15ab6f33f32e9915cf07ea123e7447cfc3be | bigcode/the-stack | train |
0d41a9d9d78113d6c7c1964b | train | class | class _BaseSearchObject(object):
"""Abstract class for SearchIO objects."""
_NON_STICKY_ATTRS = ()
def _transfer_attrs(self, obj):
"""Transfer instance attributes to the given object (PRIVATE).
This method is used to transfer attributes set externally (for example
using ``setattr`... | class _BaseSearchObject(object):
| """Abstract class for SearchIO objects."""
_NON_STICKY_ATTRS = ()
def _transfer_attrs(self, obj):
"""Transfer instance attributes to the given object (PRIVATE).
This method is used to transfer attributes set externally (for example
using ``setattr``) to a new object created from t... | Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Abstract base classes for the SearchIO object model."""
from Bio._utils import getattr_str, trim_str
class _BaseSearchObject(object):
| 64 | 64 | 206 | 7 | 56 | oz90210/Pyto | site-packages/Bio/SearchIO/_model/_base.py | Python | _BaseSearchObject | _BaseSearchObject | 12 | 34 | 12 | 12 | 48ec84739cc23638b0336862a524fd587bf7a9c0 | bigcode/the-stack | train |
ce96f9be88bf164d81bb72f4 | train | function | def main():
args = parser.parse_args()
with open(args.config) as f:
config = yaml.load(f, Loader=yaml.FullLoader)
config = EasyDict(config['config'])
temporal_helper = TemporalHelper(config, inference_only=True)
if not os.path.exists(args.activations_dir):
os.makedirs(args.activati... | def main():
| args = parser.parse_args()
with open(args.config) as f:
config = yaml.load(f, Loader=yaml.FullLoader)
config = EasyDict(config['config'])
temporal_helper = TemporalHelper(config, inference_only=True)
if not os.path.exists(args.activations_dir):
os.makedirs(args.activations_dir)
... | TCP or shared file-system",
default="tcp://localhost:9999", type=str)
parser.add_argument('--dist_backend', default='nccl', type=str)
parser.add_argument('--activations_dir', default='/scratch/kshitijd/Algonauts2020/activations/', type=str)
def main():
| 64 | 64 | 85 | 3 | 61 | kshitijd20/X-Temporal | x_temporal/extract_activations_random.py | Python | main | main | 22 | 32 | 22 | 22 | 72354933bc0807894cc36e664086e86e7ca9a447 | bigcode/the-stack | train |
8bbe5a786dae026fd413cb3f | train | function | def test_aggregation_type():
assert_equal(sofwarex.aggregation_type, "journal")
assert_equal(oecd.aggregation_type, "journal")
| def test_aggregation_type():
| assert_equal(sofwarex.aggregation_type, "journal")
assert_equal(oecd.aggregation_type, "journal")
| ometrics.scopus import SerialTitle
# SoftwareX
sofwarex = SerialTitle("2352-7110", refresh=30, years="2019-2020")
# OECD Economic Studies
oecd = SerialTitle("0255-0822", refresh=30)
def test_aggregation_type():
| 64 | 64 | 32 | 6 | 58 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_aggregation_type | test_aggregation_type | 16 | 18 | 16 | 16 | 420773409ef93df20b75505a68b31cabe8b08e6d | bigcode/the-stack | train |
e5392927b1aa16944ec519ab | train | function | def test_eissn():
assert_equal(sofwarex.eissn, "2352-7110")
assert_equal(oecd.eissn, "1609-7491")
| def test_eissn():
| assert_equal(sofwarex.eissn, "2352-7110")
assert_equal(oecd.eissn, "1609-7491")
| folist():
expected1 = [(2020, 2.8), (2021, 2.9)]
assert_equal(sofwarex.citescoreyearinfolist, expected1)
assert_equal(oecd.citescoreyearinfolist, None)
def test_eissn():
| 64 | 64 | 40 | 6 | 58 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_eissn | test_eissn | 27 | 29 | 27 | 27 | f5fe9e2e251137b109ab51db995adff064e48b54 | bigcode/the-stack | train |
3e7a2d28923af623ee59388d | train | function | def test_oaallowsauthorpaid():
assert_equal(sofwarex.oaallowsauthorpaid, None)
assert_equal(oecd.oaallowsauthorpaid, None)
| def test_oaallowsauthorpaid():
| assert_equal(sofwarex.oaallowsauthorpaid, None)
assert_equal(oecd.oaallowsauthorpaid, None)
| 2-7110")
assert_equal(oecd.eissn, "1609-7491")
def test_issn():
assert_equal(sofwarex.issn, None)
assert_equal(oecd.issn, "0255-0822")
def test_oaallowsauthorpaid():
| 64 | 64 | 36 | 8 | 56 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_oaallowsauthorpaid | test_oaallowsauthorpaid | 37 | 39 | 37 | 37 | 5c5b9fe0e01f9a73a95b11a13dd2f6b9eb75bc3d | bigcode/the-stack | train |
f993aef4dcc295e9ad601153 | train | function | def test_title():
assert_equal(sofwarex.title, "SoftwareX")
assert_equal(oecd.title, "OECD Economic Studies")
| def test_title():
| assert_equal(sofwarex.title, "SoftwareX")
assert_equal(oecd.title, "OECD Economic Studies")
| ', code=1706)
]
assert_equal(sofwarex.subject_area, expected1)
expected2 = [
area(area='Geography, Planning and Development', abbreviation='SOCI', code=3305)
]
assert_equal(oecd.subject_area, expected2)
def test_title():
| 64 | 64 | 30 | 4 | 60 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_title | test_title | 123 | 125 | 123 | 123 | 5429ee899c1d7045cd3ee82af9536c1c4e44f500 | bigcode/the-stack | train |
2d02a111b0f2baf1e0d6c851 | train | function | def test_citescoreyearinfolist():
expected1 = [(2020, 2.8), (2021, 2.9)]
assert_equal(sofwarex.citescoreyearinfolist, expected1)
assert_equal(oecd.citescoreyearinfolist, None)
| def test_citescoreyearinfolist():
| expected1 = [(2020, 2.8), (2021, 2.9)]
assert_equal(sofwarex.citescoreyearinfolist, expected1)
assert_equal(oecd.citescoreyearinfolist, None)
| ")
# OECD Economic Studies
oecd = SerialTitle("0255-0822", refresh=30)
def test_aggregation_type():
assert_equal(sofwarex.aggregation_type, "journal")
assert_equal(oecd.aggregation_type, "journal")
def test_citescoreyearinfolist():
| 64 | 64 | 65 | 10 | 54 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_citescoreyearinfolist | test_citescoreyearinfolist | 21 | 24 | 21 | 21 | 1815c3c864ae81cf20a51eff7df3fd0e711a5406 | bigcode/the-stack | train |
fa4759219191563926de8d38 | train | function | def test_source_id():
assert_equal(sofwarex.source_id, 21100422153)
assert_equal(oecd.source_id, 24107)
| def test_source_id():
| assert_equal(sofwarex.source_id, 21100422153)
assert_equal(oecd.source_id, 24107)
| jrlist, [(1999, 2.723)])
def test_sniplist():
assert_equal(sofwarex.sniplist, [(2019, 1.013), (2020, 1.093)])
assert_equal(oecd.sniplist, None)
def test_source_id():
| 64 | 64 | 33 | 5 | 59 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_source_id | test_source_id | 105 | 107 | 105 | 105 | 3e2aa2c2854baf1c1ccefceb3b355d0c4f96a59e | bigcode/the-stack | train |
4b3e2166b6bfc814b0fdacc2 | train | function | def test_openaccess():
assert_equal(sofwarex.openaccess, 1)
assert_equal(oecd.openaccess, None)
| def test_openaccess():
| assert_equal(sofwarex.openaccess, 1)
assert_equal(oecd.openaccess, None)
| x.issn, None)
assert_equal(oecd.issn, "0255-0822")
def test_oaallowsauthorpaid():
assert_equal(sofwarex.oaallowsauthorpaid, None)
assert_equal(oecd.oaallowsauthorpaid, None)
def test_openaccess():
| 64 | 64 | 28 | 5 | 59 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_openaccess | test_openaccess | 42 | 44 | 42 | 42 | 58f76d3984323bbd51ffc2742682d5b2afa7f111 | bigcode/the-stack | train |
d001519f43302aef613dc849 | train | function | def test_sjrlist():
assert_equal(sofwarex.sjrlist, [(2019, 0.445), (2020, 0.528)])
assert_equal(oecd.sjrlist, [(1999, 2.723)])
| def test_sjrlist():
| assert_equal(sofwarex.sjrlist, [(2019, 0.445), (2020, 0.528)])
assert_equal(oecd.sjrlist, [(1999, 2.723)])
| serial/title/issn/23527110"
assert_equal(sofwarex.self_link, expected1)
expected2 = "https://api.elsevier.com/content/serial/title/issn/02550822"
assert_equal(oecd.self_link, expected2)
def test_sjrlist():
| 64 | 64 | 53 | 6 | 58 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_sjrlist | test_sjrlist | 95 | 97 | 95 | 95 | 2ec0e0508ccf566c94705734ef4ac9ca9549695f | bigcode/the-stack | train |
97f3ca7afba1591354d09d01 | train | function | def test_sniplist():
assert_equal(sofwarex.sniplist, [(2019, 1.013), (2020, 1.093)])
assert_equal(oecd.sniplist, None)
| def test_sniplist():
| assert_equal(sofwarex.sniplist, [(2019, 1.013), (2020, 1.093)])
assert_equal(oecd.sniplist, None)
| , expected2)
def test_sjrlist():
assert_equal(sofwarex.sjrlist, [(2019, 0.445), (2020, 0.528)])
assert_equal(oecd.sjrlist, [(1999, 2.723)])
def test_sniplist():
| 63 | 64 | 46 | 6 | 57 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_sniplist | test_sniplist | 100 | 102 | 100 | 100 | be4f63afb0528aa06fb5110aa3a0689d2c9105e1 | bigcode/the-stack | train |
b87853bc686ddf6883ac59eb | train | function | def test_openaccesstype():
assert_equal(sofwarex.openaccesstype, None)
assert_equal(oecd.openaccesstype, None)
| def test_openaccesstype():
| assert_equal(sofwarex.openaccesstype, None)
assert_equal(oecd.openaccesstype, None)
| ():
assert_equal(sofwarex.openaccess, 1)
assert_equal(oecd.openaccess, None)
def test_openaccessstartdate():
assert_equal(sofwarex.openaccessstartdate, None)
assert_equal(oecd.openaccessstartdate, None)
def test_openaccesstype():
| 64 | 64 | 33 | 7 | 57 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_openaccesstype | test_openaccesstype | 52 | 54 | 52 | 52 | df318c9ec7534fcae6a152028a24d73f463d7c4c | bigcode/the-stack | train |
e40ca44bc65abf855ce7cbb7 | train | function | def test_openaccessarticle():
assert_equal(sofwarex.openaccessarticle, True)
assert_equal(oecd.openaccessarticle, None)
| def test_openaccessarticle():
| assert_equal(sofwarex.openaccessarticle, True)
assert_equal(oecd.openaccessarticle, None)
| assert_equal(sofwarex.openaccessstartdate, None)
assert_equal(oecd.openaccessstartdate, None)
def test_openaccesstype():
assert_equal(sofwarex.openaccesstype, None)
assert_equal(oecd.openaccesstype, None)
def test_openaccessarticle():
| 64 | 64 | 30 | 6 | 58 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_openaccessarticle | test_openaccessarticle | 57 | 59 | 57 | 57 | a571e043ce4ec08558014b8594f6ae70187ce758 | bigcode/the-stack | train |
1b617bd9202fb4f8d6b23891 | train | function | def test_openarchivearticle():
assert_equal(sofwarex.openarchivearticle, None)
assert_equal(oecd.openarchivearticle, None)
| def test_openarchivearticle():
| assert_equal(sofwarex.openarchivearticle, None)
assert_equal(oecd.openarchivearticle, None)
| stype():
assert_equal(sofwarex.openaccesstype, None)
assert_equal(oecd.openaccesstype, None)
def test_openaccessarticle():
assert_equal(sofwarex.openaccessarticle, True)
assert_equal(oecd.openaccessarticle, None)
def test_openarchivearticle():
| 64 | 64 | 30 | 6 | 58 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_openarchivearticle | test_openarchivearticle | 62 | 64 | 62 | 62 | 47cbc8a7f29144b761ec77e050b1fe4b5b7f538d | bigcode/the-stack | train |
c536c1635c039a13bf3b64b5 | train | function | def test_openaccessuserlicense():
assert_equal(sofwarex.openaccessuserlicense, None)
assert_equal(oecd.openaccessuserlicense, None)
| def test_openaccessuserlicense():
| assert_equal(sofwarex.openaccessuserlicense, None)
assert_equal(oecd.openaccessuserlicense, None)
| (sofwarex.openarchivearticle, None)
assert_equal(oecd.openarchivearticle, None)
def test_openaccesssponsorname():
assert_equal(sofwarex.openaccesssponsorname, None)
assert_equal(oecd.openaccesssponsorname, None)
def test_openaccessuserlicense():
| 64 | 64 | 33 | 7 | 57 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_openaccessuserlicense | test_openaccessuserlicense | 72 | 74 | 72 | 72 | 5a97564ac54c7d4a3a4ec143940b09ad04881d0a | bigcode/the-stack | train |
a12e30fed88f5fd72d759376 | train | function | def test_scopus_source_link():
expected1 = "https://www.scopus.com/source/sourceInfo.url?sourceId=21100422153"
assert_equal(sofwarex.scopus_source_link, expected1)
expected2 = "https://www.scopus.com/source/sourceInfo.url?sourceId=24107"
assert_equal(oecd.scopus_source_link, expected2)
| def test_scopus_source_link():
| expected1 = "https://www.scopus.com/source/sourceInfo.url?sourceId=21100422153"
assert_equal(sofwarex.scopus_source_link, expected1)
expected2 = "https://www.scopus.com/source/sourceInfo.url?sourceId=24107"
assert_equal(oecd.scopus_source_link, expected2)
| ():
assert_equal(sofwarex.openaccessuserlicense, None)
assert_equal(oecd.openaccessuserlicense, None)
def test_publisher():
assert_equal(sofwarex.publisher, "Elsevier BV")
assert_equal(oecd.publisher, "OECD")
def test_scopus_source_link():
| 64 | 64 | 81 | 7 | 57 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_scopus_source_link | test_scopus_source_link | 82 | 86 | 82 | 82 | 54fa7b824e36132df8ef445342ae71f34461e3a6 | bigcode/the-stack | train |
d375d616b79f1f1a2c55f7af | train | function | def test_openaccesssponsorname():
assert_equal(sofwarex.openaccesssponsorname, None)
assert_equal(oecd.openaccesssponsorname, None)
| def test_openaccesssponsorname():
| assert_equal(sofwarex.openaccesssponsorname, None)
assert_equal(oecd.openaccesssponsorname, None)
| article():
assert_equal(sofwarex.openaccessarticle, True)
assert_equal(oecd.openaccessarticle, None)
def test_openarchivearticle():
assert_equal(sofwarex.openarchivearticle, None)
assert_equal(oecd.openarchivearticle, None)
def test_openaccesssponsorname():
| 64 | 64 | 36 | 8 | 56 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_openaccesssponsorname | test_openaccesssponsorname | 67 | 69 | 67 | 67 | 317bebbd3609e3d8d5c346022ffe78cf24228604 | bigcode/the-stack | train |
227e6e519d4e3450c92ca8f6 | train | function | def test_issn():
assert_equal(sofwarex.issn, None)
assert_equal(oecd.issn, "0255-0822")
| def test_issn():
| assert_equal(sofwarex.issn, None)
assert_equal(oecd.issn, "0255-0822")
| expected1)
assert_equal(oecd.citescoreyearinfolist, None)
def test_eissn():
assert_equal(sofwarex.eissn, "2352-7110")
assert_equal(oecd.eissn, "1609-7491")
def test_issn():
| 64 | 64 | 35 | 6 | 58 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_issn | test_issn | 32 | 34 | 32 | 32 | b87bcdbfb2f99d71d5b99a3dc9c9a94917eda664 | bigcode/the-stack | train |
35f25cde7ff4d3d133a6c141 | train | function | def test_publisher():
assert_equal(sofwarex.publisher, "Elsevier BV")
assert_equal(oecd.publisher, "OECD")
| def test_publisher():
| assert_equal(sofwarex.publisher, "Elsevier BV")
assert_equal(oecd.publisher, "OECD")
| _equal(sofwarex.openaccesssponsorname, None)
assert_equal(oecd.openaccesssponsorname, None)
def test_openaccessuserlicense():
assert_equal(sofwarex.openaccessuserlicense, None)
assert_equal(oecd.openaccessuserlicense, None)
def test_publisher():
| 64 | 64 | 30 | 5 | 59 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_publisher | test_publisher | 77 | 79 | 77 | 77 | 4713ec201d1c99b99da41a49aac76ff16e8ff905 | bigcode/the-stack | train |
0af2c4faab0468839bd73945 | train | function | def test_subject_area():
area = namedtuple('Subjectarea', 'area abbreviation code')
expected1 = [
area(area='Software', abbreviation='COMP', code=1712),
area(area='Computer Science Applications', abbreviation='COMP', code=1706)
]
assert_equal(sofwarex.subject_area, expected1)
expecte... | def test_subject_area():
| area = namedtuple('Subjectarea', 'area abbreviation code')
expected1 = [
area(area='Software', abbreviation='COMP', code=1712),
area(area='Computer Science Applications', abbreviation='COMP', code=1706)
]
assert_equal(sofwarex.subject_area, expected1)
expected2 = [
area(area=... | , 1.013), (2020, 1.093)])
assert_equal(oecd.sniplist, None)
def test_source_id():
assert_equal(sofwarex.source_id, 21100422153)
assert_equal(oecd.source_id, 24107)
def test_subject_area():
| 64 | 64 | 110 | 5 | 59 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_subject_area | test_subject_area | 110 | 120 | 110 | 110 | b2a42c1bdc78990a94aea7fd31707a35d52ed146 | bigcode/the-stack | train |
af3c55512d8c0bb3d1149a44 | train | function | def test_openaccessstartdate():
assert_equal(sofwarex.openaccessstartdate, None)
assert_equal(oecd.openaccessstartdate, None)
| def test_openaccessstartdate():
| assert_equal(sofwarex.openaccessstartdate, None)
assert_equal(oecd.openaccessstartdate, None)
| ():
assert_equal(sofwarex.oaallowsauthorpaid, None)
assert_equal(oecd.oaallowsauthorpaid, None)
def test_openaccess():
assert_equal(sofwarex.openaccess, 1)
assert_equal(oecd.openaccess, None)
def test_openaccessstartdate():
| 64 | 64 | 33 | 7 | 57 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_openaccessstartdate | test_openaccessstartdate | 47 | 49 | 47 | 47 | 72af41641274558420f8d080509224ca872e104a | bigcode/the-stack | train |
5580a3af408c49e42a89d310 | train | function | def test_self_link():
expected1 = "https://api.elsevier.com/content/serial/title/issn/23527110"
assert_equal(sofwarex.self_link, expected1)
expected2 = "https://api.elsevier.com/content/serial/title/issn/02550822"
assert_equal(oecd.self_link, expected2)
| def test_self_link():
| expected1 = "https://api.elsevier.com/content/serial/title/issn/23527110"
assert_equal(sofwarex.self_link, expected1)
expected2 = "https://api.elsevier.com/content/serial/title/issn/02550822"
assert_equal(oecd.self_link, expected2)
| ?sourceId=21100422153"
assert_equal(sofwarex.scopus_source_link, expected1)
expected2 = "https://www.scopus.com/source/sourceInfo.url?sourceId=24107"
assert_equal(oecd.scopus_source_link, expected2)
def test_self_link():
| 64 | 64 | 77 | 5 | 59 | JLoDoesIt/pybliometrics | pybliometrics/scopus/tests/test_SerialTitle.py | Python | test_self_link | test_self_link | 89 | 93 | 89 | 89 | cd064693f9cbc21bedcb2afb13c2bd35fc054e1e | bigcode/the-stack | train |
405eca78093c425166ac8893 | train | class | class DataException(Exception):
pass
| class DataException(Exception):
| pass
| import h5py
import numpy as np
from pydata.increment import __next_index__
from contextlib import contextmanager
import time
class DataException(Exception):
| 34 | 64 | 8 | 5 | 28 | NS2LPS/pyslave | pydata/h5pydata.py | Python | DataException | DataException | 7 | 8 | 7 | 7 | dacbf4facd3553b559b78f7140d75bf2c82923fe | bigcode/the-stack | train |
61f11d178048ddc973b5f816 | train | function | def createh5(filename, mode=None, **kwargs):
"""Create a HDF5 file. Syntax is similar to h5py.File with the
extra possibility to set the attributes directly. Default mode
is append ('a')."""
if mode is None:
mode = 'a'
params = {'libver':'latest', 'track_order':True}
params.update(kwarg... | def createh5(filename, mode=None, **kwargs):
| """Create a HDF5 file. Syntax is similar to h5py.File with the
extra possibility to set the attributes directly. Default mode
is append ('a')."""
if mode is None:
mode = 'a'
params = {'libver':'latest', 'track_order':True}
params.update(kwargs)
attrs = params.pop('attrs') if 'attrs'... | res
def __repr__(self):
return self.file.filename+self.name+' '+super().__repr__()
class __h5file__:
def __init__(self, filename, params):
self.filename = filename
self.params = params
def createh5(filename, mode=None, **kwargs):
| 64 | 64 | 138 | 12 | 51 | NS2LPS/pyslave | pydata/h5pydata.py | Python | createh5 | createh5 | 85 | 96 | 85 | 85 | f4d6f2783ac9abb800034c6b6d9df29e980fecbd | bigcode/the-stack | train |
c379b090f2f412c678c16504 | train | class | class __autoiter__:
def __init__(self):
self.__data_counter__ = dict()
def __next_dataset__(self, dataset, ndigits):
if not dataset in self.__data_counter__ :
counter = __next_index__(dataset, '', self.keys())
else:
counter = self.__data_counter__[dataset] + 1
... | class __autoiter__:
| def __init__(self):
self.__data_counter__ = dict()
def __next_dataset__(self, dataset, ndigits):
if not dataset in self.__data_counter__ :
counter = __next_index__(dataset, '', self.keys())
else:
counter = self.__data_counter__[dataset] + 1
return counter,... | ...")
time.sleep(1)
retry -= 1
else:
raise DataException(f"Unable to open {filename} after 10 retries.")
try:
yield resource
finally:
# Code to release resource, e.g.:
resource.close()
class __autoiter__:
| 64 | 64 | 113 | 6 | 58 | NS2LPS/pyslave | pydata/h5pydata.py | Python | __autoiter__ | __autoiter__ | 32 | 42 | 32 | 32 | cb0a2beb6a2b975f328bf9e56c4309342780ee00 | bigcode/the-stack | train |
7676e5363f16b1d530430592 | train | class | class __h5file__:
def __init__(self, filename, params):
self.filename = filename
self.params = params
| class __h5file__:
| def __init__(self, filename, params):
self.filename = filename
self.params = params
| with h5file(self.file.filename, 'r', **self.file.params) as f:
g = f[self.name]
res = list(g.keys())
return res
def __repr__(self):
return self.file.filename+self.name+' '+super().__repr__()
class __h5file__:
| 64 | 64 | 30 | 7 | 58 | NS2LPS/pyslave | pydata/h5pydata.py | Python | __h5file__ | __h5file__ | 80 | 83 | 80 | 80 | a3b41e3cd8c39f4e0495e987151b06c282840bce | bigcode/the-stack | train |
16ea39ea7c0dfbd5645035e3 | train | class | class loadh5:
"""Load all datasets of a H5 file or group into numpy arrays.
Example :
d = loadh5('Sij_vs_Temperature.h5')
print(d)
Loaded from Sij_vs_Temperature.h5 with 70 datasets
Data fields : freq,Sij
Attributes : T
plot(d.T, abs(d.Sij).max(1))
"""
def __init_... | class loadh5:
| """Load all datasets of a H5 file or group into numpy arrays.
Example :
d = loadh5('Sij_vs_Temperature.h5')
print(d)
Loaded from Sij_vs_Temperature.h5 with 70 datasets
Data fields : freq,Sij
Attributes : T
plot(d.T, abs(d.Sij).max(1))
"""
def __init__(self, filena... | 5 is no longer required.")
def keys(self):
with h5file(self.file.filename, 'r', **self.file.params) as f:
g = f[self.name]
res = list(g.keys())
return res
def __repr__(self):
return self.file.filename+self.name+' '+super().__repr__()
class __h5file__:
def __i... | 242 | 242 | 808 | 5 | 236 | NS2LPS/pyslave | pydata/h5pydata.py | Python | loadh5 | loadh5 | 98 | 189 | 98 | 98 | 5c2005910794774ab3eef1035e80cb18c2f7fd9e | bigcode/the-stack | train |
83e7890d8cbed22d61a6f8c8 | train | class | class Group_autoiter(__autoiter__):
def __init__(self, file, name):
super().__init__()
self.file = file
self.name = name
def create_group(self, name, attrs={}, track_order=True):
"""Create a group. Syntax is similar to h5py create_dataset with the
extra possibility to set... | class Group_autoiter(__autoiter__):
| def __init__(self, file, name):
super().__init__()
self.file = file
self.name = name
def create_group(self, name, attrs={}, track_order=True):
"""Create a group. Syntax is similar to h5py create_dataset with the
extra possibility to set the attributes directly."""
... | __:
def __init__(self):
self.__data_counter__ = dict()
def __next_dataset__(self, dataset, ndigits):
if not dataset in self.__data_counter__ :
counter = __next_index__(dataset, '', self.keys())
else:
counter = self.__data_counter__[dataset] + 1
return coun... | 118 | 118 | 395 | 9 | 109 | NS2LPS/pyslave | pydata/h5pydata.py | Python | Group_autoiter | Group_autoiter | 44 | 78 | 44 | 44 | aee3892388d6e49e6534fe35f17ef11dbeff0f3c | bigcode/the-stack | train |
43ca020e197261fd2678c46b | train | function | @contextmanager
def h5file(filename, mode, **kwargs):
# Code to acquire resource, e.g.:
retry = 10
while retry:
try:
resource = h5py.File(filename, mode, **kwargs)
break
except OSError:
print(f"Unable to open {filename}, retrying...")
time.slee... | @contextmanager
def h5file(filename, mode, **kwargs):
# Code to acquire resource, e.g.:
| retry = 10
while retry:
try:
resource = h5py.File(filename, mode, **kwargs)
break
except OSError:
print(f"Unable to open {filename}, retrying...")
time.sleep(1)
retry -= 1
else:
raise DataException(f"Unable to open {filename... | import h5py
import numpy as np
from pydata.increment import __next_index__
from contextlib import contextmanager
import time
class DataException(Exception):
pass
@contextmanager
def h5file(filename, mode, **kwargs):
# Code to acquire resource, e.g.:
| 63 | 64 | 131 | 26 | 36 | NS2LPS/pyslave | pydata/h5pydata.py | Python | h5file | h5file | 11 | 29 | 11 | 13 | ed39c36984432e1ee0fd88c916866152454264a3 | bigcode/the-stack | train |
b46fdc0d10867c182e3da084 | train | function | def test_post_table():
response = client.post(
"/table", json={"name": "test", "email": "test@gmail.com"})
assert response.status_code == 200
| def test_post_table():
| response = client.post(
"/table", json={"name": "test", "email": "test@gmail.com"})
assert response.status_code == 200
| )
def test_hello():
response = client.get("/hello")
assert response.status_code == 200
assert response.json() == {"payload": "Hello World!"}
def test_get_table():
response = client.get("/table")
assert response.status_code == 200
def test_post_table():
| 64 | 64 | 39 | 5 | 58 | ramoseh/wizeline-challenge | tests/test_app.py | Python | test_post_table | test_post_table | 19 | 22 | 19 | 19 | f5d82bfee5c2eb9e1641b704d3f107a620a3279e | bigcode/the-stack | train |
d55118390f61057ad083f546 | train | function | def test_post_table_no_name():
response = client.post("/table", json={"email": "test"})
assert response.status_code == 422
| def test_post_table_no_name():
| response = client.post("/table", json={"email": "test"})
assert response.status_code == 422
| table", json={"name": "test", "email": "test@gmail.com"})
assert response.status_code == 200
def test_post_table_no_email():
response = client.post("/table", json={"name": "test"})
assert response.status_code == 422
def test_post_table_no_name():
| 64 | 64 | 31 | 7 | 56 | ramoseh/wizeline-challenge | tests/test_app.py | Python | test_post_table_no_name | test_post_table_no_name | 30 | 32 | 30 | 30 | 05031e87ecf35d798246f1c3cd6aa6dfe157d87b | bigcode/the-stack | train |
6fe3dbc3181d9e437348e03f | train | function | def test_get_weather():
response = client.get("/weather")
assert response.status_code == 200
| def test_get_weather():
| response = client.get("/weather")
assert response.status_code == 200
| _table_no_email():
response = client.post("/table", json={"name": "test"})
assert response.status_code == 422
def test_post_table_no_name():
response = client.post("/table", json={"email": "test"})
assert response.status_code == 422
def test_get_weather():
| 64 | 64 | 22 | 5 | 58 | ramoseh/wizeline-challenge | tests/test_app.py | Python | test_get_weather | test_get_weather | 35 | 37 | 35 | 35 | 7e087b746b3bc00468af40be53b2a721739add86 | bigcode/the-stack | train |
19943c8456b77b46f331c409 | train | function | def test_hello():
response = client.get("/hello")
assert response.status_code == 200
assert response.json() == {"payload": "Hello World!"}
| def test_hello():
| response = client.get("/hello")
assert response.status_code == 200
assert response.json() == {"payload": "Hello World!"}
| from fastapi.testclient import TestClient
from app import app
client = TestClient(app)
def test_hello():
| 25 | 64 | 36 | 5 | 20 | ramoseh/wizeline-challenge | tests/test_app.py | Python | test_hello | test_hello | 8 | 11 | 8 | 8 | 4ab8f69aed34924f29f483646927456a9dc2cf10 | bigcode/the-stack | train |
81a089ffc390c3f97060fcbe | train | function | def test_post_table_no_email():
response = client.post("/table", json={"name": "test"})
assert response.status_code == 422
| def test_post_table_no_email():
| response = client.post("/table", json={"name": "test"})
assert response.status_code == 422
| ():
response = client.get("/table")
assert response.status_code == 200
def test_post_table():
response = client.post(
"/table", json={"name": "test", "email": "test@gmail.com"})
assert response.status_code == 200
def test_post_table_no_email():
| 64 | 64 | 31 | 7 | 56 | ramoseh/wizeline-challenge | tests/test_app.py | Python | test_post_table_no_email | test_post_table_no_email | 25 | 27 | 25 | 25 | bdc23e32749d506475561c02e135017adee96c40 | bigcode/the-stack | train |
e49e586bad9b6378f3a5aa4e | train | function | def test_get_table():
response = client.get("/table")
assert response.status_code == 200
| def test_get_table():
| response = client.get("/table")
assert response.status_code == 200
| from fastapi.testclient import TestClient
from app import app
client = TestClient(app)
def test_hello():
response = client.get("/hello")
assert response.status_code == 200
assert response.json() == {"payload": "Hello World!"}
def test_get_table():
| 61 | 64 | 22 | 5 | 56 | ramoseh/wizeline-challenge | tests/test_app.py | Python | test_get_table | test_get_table | 14 | 16 | 14 | 14 | 9eababb374788e060215b89b34114e1f99670956 | bigcode/the-stack | train |
47e575f0d75b6e40d7ba9d90 | train | function | def decently_distributed(positives, negative):
if abs(len(positives) / float(lines) - len(negatives) / float(lines)) <= 0.05:
return True
else:
return False
| def decently_distributed(positives, negative):
| if abs(len(positives) / float(lines) - len(negatives) / float(lines)) <= 0.05:
return True
else:
return False
| ', type=int, default=100, help='Number of lines to extract!')
args = parser.parse_args()
path = 'data/training.1600000.processed.noemoticon.csv'
size = os.path.getsize(path)
lines = args.lines
def decently_distributed(positives, negative):
| 64 | 64 | 48 | 11 | 52 | galnegus/smiley-sentiment | stc_extract.py | Python | decently_distributed | decently_distributed | 15 | 19 | 15 | 15 | cb3955237e692274f21286f0f1321811f24016b3 | bigcode/the-stack | train |
9a903545d8afa893fff8b4a6 | train | function | def pop_n(list, n):
for i in xrange(n):
list.pop()
| def pop_n(list, n):
| for i in xrange(n):
list.pop()
| .getsize(path)
lines = args.lines
def decently_distributed(positives, negative):
if abs(len(positives) / float(lines) - len(negatives) / float(lines)) <= 0.05:
return True
else:
return False
def pop_n(list, n):
| 64 | 64 | 17 | 7 | 56 | galnegus/smiley-sentiment | stc_extract.py | Python | pop_n | pop_n | 21 | 23 | 21 | 21 | 8ddccd092e73fe5b717a9c702a5858abe522302d | bigcode/the-stack | train |
7c476dbc72036d867e19541d | train | class | class TestParamsPassArrayStruct(unittest.TestCase):
def test_params_pass_array_struct(self):
r = _schema.parse_file('src/position_to_end.bin')
self.assertEqual(len(r.pass_structs.structs), 2)
self.assertEqual(r.pass_structs.structs[0].f, 1)
self.assertEqual(r.pass_structs.structs[1]... | class TestParamsPassArrayStruct(unittest.TestCase):
| def test_params_pass_array_struct(self):
r = _schema.parse_file('src/position_to_end.bin')
self.assertEqual(len(r.pass_structs.structs), 2)
self.assertEqual(r.pass_structs.structs[0].f, 1)
self.assertEqual(r.pass_structs.structs[1].b, 2)
| # Autogenerated from KST: please remove this line if doing any edits by hand!
import unittest
from params_pass_array_struct import _schema
class TestParamsPassArrayStruct(unittest.TestCase):
| 40 | 64 | 85 | 10 | 29 | DarkShadow44/kaitai_struct_tests | spec/construct/test_params_pass_array_struct.py | Python | TestParamsPassArrayStruct | TestParamsPassArrayStruct | 7 | 13 | 7 | 7 | 69b802b2c74c376ce35436a967e4ecff78fcc64e | bigcode/the-stack | train |
b7d06fd9f7510704edff30bb | train | class | class SpeechActivityDetection(LabelingTask):
"""Train speech activity (and overlap) detection
Parameters
----------
duration : float, optional
Duration of sub-sequences. Defaults to 3.2s.
batch_size : int, optional
Batch size. Defaults to 32.
per_epoch : float, optional
... | class SpeechActivityDetection(LabelingTask):
| """Train speech activity (and overlap) detection
Parameters
----------
duration : float, optional
Duration of sub-sequences. Defaults to 3.2s.
batch_size : int, optional
Batch size. Defaults to 32.
per_epoch : float, optional
Total audio duration per epoch, in days.
... | ']['classes'] = ['non_speech', 'speech']
for key, classes in self.file_labels_.items():
# TODO. add an option to handle this list
# TODO. especially useful for domain-adversarial stuff
if key in ['duration', 'audio', 'uri']:
continue
specs[key] =... | 87 | 87 | 290 | 8 | 78 | NgvTue/test2 | speech_dia_@/src/pyannote_xxx/audio/labeling/tasks/speech_activity_detection.py | Python | SpeechActivityDetection | SpeechActivityDetection | 109 | 142 | 109 | 109 | 11fcf86ba5a0cc11439638206544578e7c4d916f | bigcode/the-stack | train |
cd5071f40adb42f1fc0d2ea0 | train | class | class DomainAwareSpeechActivityDetection(SpeechActivityDetection):
"""Domain-aware speech activity detection
Trains speech activity detection and domain classification jointly.
Parameters
----------
domain : `str`, optional
Batch key to use as domain. Defaults to 'domain'.
Could be... | class DomainAwareSpeechActivityDetection(SpeechActivityDetection):
| """Domain-aware speech activity detection
Trains speech activity detection and domain classification jointly.
Parameters
----------
domain : `str`, optional
Batch key to use as domain. Defaults to 'domain'.
Could be 'database' or 'uri' for instance.
attachment : `int`, optional... | .
batch_size : int, optional
Batch size. Defaults to 32.
per_epoch : float, optional
Total audio duration per epoch, in days.
Defaults to one day (1).
"""
def get_batch_generator(self, feature_extraction, protocol, subset='train',
resolution=None, ali... | 256 | 256 | 963 | 11 | 245 | NgvTue/test2 | speech_dia_@/src/pyannote_xxx/audio/labeling/tasks/speech_activity_detection.py | Python | DomainAwareSpeechActivityDetection | DomainAwareSpeechActivityDetection | 145 | 289 | 145 | 145 | 6d856937905b9f97225aceb8597d13e59703555e | bigcode/the-stack | train |
57ef8779fa09db07bdc01c8a | train | class | class SpeechActivityDetectionGenerator(LabelingTaskGenerator):
"""Batch generator for training speech activity detection
Parameters
----------
feature_extraction : `pyannote_xxx.audio.features.FeatureExtraction`
Feature extraction
protocol : `pyannote_xxx.database.Protocol`
subset : {'t... | class SpeechActivityDetectionGenerator(LabelingTaskGenerator):
| """Batch generator for training speech activity detection
Parameters
----------
feature_extraction : `pyannote_xxx.audio.features.FeatureExtraction`
Feature extraction
protocol : `pyannote_xxx.database.Protocol`
subset : {'train', 'development', 'test'}, optional
Protocol and su... | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# AUTHORS
# Hervé BREDIN - http://herve.niderb.fr
"""Speech activity detection"""
import numpy... | 155 | 155 | 519 | 10 | 144 | NgvTue/test2 | speech_dia_@/src/pyannote_xxx/audio/labeling/tasks/speech_activity_detection.py | Python | SpeechActivityDetectionGenerator | SpeechActivityDetectionGenerator | 41 | 106 | 41 | 41 | f589d07376431e19ebbfb32931062ea36e968419 | bigcode/the-stack | train |
f838649a021f05d93c72b4a0 | train | class | class DomainAdversarialSpeechActivityDetection(DomainAwareSpeechActivityDetection):
"""Domain Adversarial speech activity detection
Parameters
----------
domain : `str`, optional
Batch key to use as domain. Defaults to 'domain'.
Could be 'database' or 'uri' for instance.
attachment ... | class DomainAdversarialSpeechActivityDetection(DomainAwareSpeechActivityDetection):
| """Domain Adversarial speech activity detection
Parameters
----------
domain : `str`, optional
Batch key to use as domain. Defaults to 'domain'.
Could be 'database' or 'uri' for instance.
attachment : `int`, optional
Intermediate level where to attach the domain classifier.
... | .tensor(
batch['y'],
dtype=torch.int64,
device=self.device_).contiguous().view((-1, ))
weight = self.weight
if weight is not None:
weight = weight.to(device=self.device_)
loss = self.loss_func_(fX, target, weight=weight)
# domain classifi... | 162 | 162 | 540 | 15 | 147 | NgvTue/test2 | speech_dia_@/src/pyannote_xxx/audio/labeling/tasks/speech_activity_detection.py | Python | DomainAdversarialSpeechActivityDetection | DomainAdversarialSpeechActivityDetection | 292 | 366 | 292 | 292 | b3e1e0ec42ba27a7251f0fff172a385174cb072e | bigcode/the-stack | train |
46cf39a592ee7a05127cb965 | train | function | def pattern_recognition(ball, image_w, image_h, model):
if len(ball["trace"]) < 2: return
print(ball)
if len(ball["trace"]) == 5 and len(ball["hand_seq"]) == 1:
return str(2)
"""data proprocessing"""
# calculate ball vertical distance - y (height)
h1_y = ball["trace"][0][1]
... | def pattern_recognition(ball, image_w, image_h, model):
| if len(ball["trace"]) < 2: return
print(ball)
if len(ball["trace"]) == 5 and len(ball["hand_seq"]) == 1:
return str(2)
"""data proprocessing"""
# calculate ball vertical distance - y (height)
h1_y = ball["trace"][0][1]
h2_y = ball["trace"][-1][1]
h_y = (h2_y + h1_y)... | import numpy as np
def pattern_recognition(ball, image_w, image_h, model):
| 19 | 91 | 305 | 14 | 4 | kaijaz123/Juggling_Pattern_Recognition | core/pattern.py | Python | pattern_recognition | pattern_recognition | 3 | 38 | 3 | 3 | 43bde5cc7e25ada0047488f84184289a7fc20f84 | bigcode/the-stack | train |
2490c41a81ffd96cd581428a | train | function | def phone_book():
print("Welcome to the Phone Book!")
while True:
print("-" * 40)
print("Press 1 to search.")
print("Press 2 to add.")
print("Press 3 to change an entry.")
print("Press 4 to remove.")
print("Press 5 to exit.")
print("-" * 40)
try:
... | def phone_book():
| print("Welcome to the Phone Book!")
while True:
print("-" * 40)
print("Press 1 to search.")
print("Press 2 to add.")
print("Press 3 to change an entry.")
print("Press 4 to remove.")
print("Press 5 to exit.")
print("-" * 40)
try:
choice ... | dictionary.pop(name.lower())
print("%s has been removed." % name)
running = False
if choice == "no" or choice == "n":
running = False
except ValueError:
print("That is not a valid entry. Please try again.")
def phone_book():... | 63 | 64 | 160 | 4 | 59 | probinso/Intro-to-Python | example-files/phonebook.py | Python | phone_book | phone_book | 71 | 94 | 71 | 71 | b213eb727ae7faa309bebf16f338f38a49ecdd82 | bigcode/the-stack | train |
8da112d471554f6869db4aa8 | train | function | def change():
name = input("What is the first name of the person you wish to change?: ")
print("Do you: really want to change %s?" % name)
print("Yes or No")
running = True
while running:
try:
choice = input('> ').lower()
if choice == "yes" or choice == "y":
... | def change():
| name = input("What is the first name of the person you wish to change?: ")
print("Do you: really want to change %s?" % name)
print("Yes or No")
running = True
while running:
try:
choice = input('> ').lower()
if choice == "yes" or choice == "y":
name_ch... | of the person you wish to add?: ")
dictionary[name.lower()] = {'name': name, 'phone': phone}
print("Entry added:")
print("Name: " + dictionary[name.lower()]['name'])
print("Phone Number: " + dictionary[name.lower()]['phone'])
def change():
| 63 | 64 | 186 | 3 | 60 | probinso/Intro-to-Python | example-files/phonebook.py | Python | change | change | 25 | 42 | 25 | 25 | 7609feb0f7f5dde72f5ee44789f6549fbdbe6232 | bigcode/the-stack | train |
87ac1bff95b3b88c561aa661 | train | function | def remove():
running = True
running = True
while running:
name = input("What is the first name of the person you wish to remove?: ").lower()
try:
dictionary[name]
except KeyError:
print("That is name does not exist. Please try again.")
continue
... | def remove():
| running = True
running = True
while running:
name = input("What is the first name of the person you wish to remove?: ").lower()
try:
dictionary[name]
except KeyError:
print("That is name does not exist. Please try again.")
continue
print("... | name_change, 'phone': phone}
deleted_thing = dictionary.pop(name.lower())
running = False
if choice == "no" or choice == "n":
running = False
except ValueError:
print("That is not a valid entry. Please try again.")
def remove():
| 63 | 64 | 174 | 3 | 60 | probinso/Intro-to-Python | example-files/phonebook.py | Python | remove | remove | 45 | 68 | 45 | 45 | aef91507bb3984b8468abc577b816cc5b8530528 | bigcode/the-stack | train |
678737466168ac9d492e5c08 | train | function | def search():
try:
srch = input("Please enter the first name of the person you are searching for: ").lower()
print("Name: " + dictionary[srch]['name'])
print("Phone Number: " + dictionary[srch]['phone'])
except KeyError:
print("Entry not found.")
| def search():
| try:
srch = input("Please enter the first name of the person you are searching for: ").lower()
print("Name: " + dictionary[srch]['name'])
print("Phone Number: " + dictionary[srch]['phone'])
except KeyError:
print("Entry not found.")
| dictionary = {
'chris': {'name': 'Chris', 'phone': "503-277-9710"},
'sam': {'name': 'Sam', 'phone': "503-277-9710"}
}
def search():
| 50 | 64 | 67 | 3 | 47 | probinso/Intro-to-Python | example-files/phonebook.py | Python | search | search | 7 | 13 | 7 | 7 | f278e1fc9d85cef87856970e9408216e58877855 | bigcode/the-stack | train |
42c8736f616ca1fffc5aa340 | train | function | def add():
name = input("What is the first name of the person you wish to add?: ")
phone = input("What is the phone number of the person you wish to add?: ")
dictionary[name.lower()] = {'name': name, 'phone': phone}
print("Entry added:")
print("Name: " + dictionary[name.lower()]['name'])
print("... | def add():
| name = input("What is the first name of the person you wish to add?: ")
phone = input("What is the phone number of the person you wish to add?: ")
dictionary[name.lower()] = {'name': name, 'phone': phone}
print("Entry added:")
print("Name: " + dictionary[name.lower()]['name'])
print("Phone Numbe... | srch = input("Please enter the first name of the person you are searching for: ").lower()
print("Name: " + dictionary[srch]['name'])
print("Phone Number: " + dictionary[srch]['phone'])
except KeyError:
print("Entry not found.")
def add():
| 63 | 64 | 92 | 3 | 60 | probinso/Intro-to-Python | example-files/phonebook.py | Python | add | add | 16 | 22 | 16 | 16 | d5ffb8dce47df77efecf0f51541d1967137ebd7a | bigcode/the-stack | train |
3d5ec9a8c6a327e774ac7dc9 | train | class | @pytest.mark.usefixtures('patch_io', 'truncate', 'remove_media')
class TestMirrorTruncatedNoMedia(TestMirrorNoMedia):
@pytest.fixture
def full_text(self, mocker):
return mocker.PropertyMock(spec_set=str, name='full_text')
@pytest.fixture
def truncate(self, full_text, inject_full_text, inject_e... | @pytest.mark.usefixtures('patch_io', 'truncate', 'remove_media')
class TestMirrorTruncatedNoMedia(TestMirrorNoMedia):
@pytest.fixture
| def full_text(self, mocker):
return mocker.PropertyMock(spec_set=str, name='full_text')
@pytest.fixture
def truncate(self, full_text, inject_full_text, inject_extended):
inject_full_text(full_text)
inject_extended(True)
@pytest.mark.usefixtures('mock_downloader')
def test_m... | media_outputs, mock_downloader):
MirrorThread.mirror(api, status, dirname)
mock_downloader.download_media.assert_called_once_with(status, dirname)
@pytest.mark.usefixtures('patch_io', 'truncate', 'remove_media')
class TestMirrorTruncatedNoMedia(TestMirrorNoMedia):
@pytest.fixture
| 64 | 64 | 182 | 32 | 32 | TidalPaladin/twitlib | test/test_streaming/test_statics.py | Python | TestMirrorTruncatedNoMedia | TestMirrorTruncatedNoMedia | 128 | 147 | 128 | 131 | da20ab9fb5c3671b1c6c92520339a5536cb4667f | bigcode/the-stack | train |
e96fe90d8fd612dc1280369a | train | class | class TestWrite():
@pytest.fixture
def output_file(self):
return 'out_file.json'
def test_return_filename(self, status, output_file):
"""Tests process_status() returns name of written file"""
ret = WriterThread.write_status(status=status, filename=output_file)
assert(ret ==... | class TestWrite():
@pytest.fixture
| def output_file(self):
return 'out_file.json'
def test_return_filename(self, status, output_file):
"""Tests process_status() returns name of written file"""
ret = WriterThread.write_status(status=status, filename=output_file)
assert(ret == output_file)
def test_opened_corre... | import pytest
import logging
import json
import requests
import twitter
import os
from twitlib.streaming import WorkerThread
from twitlib.streaming import MirrorThread, WriterThread, MediaDownloaderThread
import twitlib
class TestWrite():
@pytest.fixture
| 57 | 64 | 199 | 9 | 47 | TidalPaladin/twitlib | test/test_streaming/test_statics.py | Python | TestWrite | TestWrite | 12 | 31 | 12 | 14 | fa40d1d009acbf10c636248f550a7b71125e8eda | bigcode/the-stack | train |
c56a7d4f657bd5acccc42922 | train | class | @pytest.mark.usefixtures('patch_remove_urls', 'remove_media')
class TestMirrorNoMedia():
def test_calls_PostUpdate(self, status, api, dirname):
MirrorThread.mirror(api, status, dirname)
api.PostUpdate.assert_called_once()
@pytest.mark.usefixtures('mock_downloader')
def test_mirrored_text(s... | @pytest.mark.usefixtures('patch_remove_urls', 'remove_media')
class TestMirrorNoMedia():
| def test_calls_PostUpdate(self, status, api, dirname):
MirrorThread.mirror(api, status, dirname)
api.PostUpdate.assert_called_once()
@pytest.mark.usefixtures('mock_downloader')
def test_mirrored_text(self, status, api, dirname):
MirrorThread.mirror(api, status, dirname)
args... | _mkdir_on_missing(self, mocker, status, dirname, mock_open):
os.path.exists.return_value = False
MediaDownloaderThread.download_media(status, dirname)
os.path.exists.assert_called_once()
os.makedirs.assert_called_once_with(dirname)
@pytest.mark.usefixtures('patch_remove_urls', 'remove_me... | 71 | 71 | 238 | 19 | 52 | TidalPaladin/twitlib | test/test_streaming/test_statics.py | Python | TestMirrorNoMedia | TestMirrorNoMedia | 72 | 95 | 72 | 74 | 33488b43210208d487c7249ce41f26d6b28af992 | bigcode/the-stack | train |
274085cdc1c40bc25f1f937b | train | class | @pytest.mark.usefixtures('truncate', 'add_media')
class TestMirrorTruncated(TestMirror):
@pytest.fixture
def full_text(self, mocker):
return mocker.PropertyMock(spec_set=str, name='full_text')
@pytest.fixture
def truncate(self, full_text, inject_full_text, inject_extended):
inject_full... | @pytest.mark.usefixtures('truncate', 'add_media')
class TestMirrorTruncated(TestMirror):
@pytest.fixture
| def full_text(self, mocker):
return mocker.PropertyMock(spec_set=str, name='full_text')
@pytest.fixture
def truncate(self, full_text, inject_full_text, inject_extended):
inject_full_text(full_text)
inject_extended(True)
@pytest.mark.usefixtures('mock_downloader')
def test_m... | .full_text)
args, kwargs = api.PostUpdate.call_args
expected = twitlib.util.remove_urls.return_value
actual = kwargs.get('status', None)
assert(actual == expected)
@pytest.mark.usefixtures('truncate', 'add_media')
class TestMirrorTruncated(TestMirror):
@pytest.fixture
| 66 | 66 | 223 | 24 | 42 | TidalPaladin/twitlib | test/test_streaming/test_statics.py | Python | TestMirrorTruncated | TestMirrorTruncated | 149 | 172 | 149 | 152 | 04dfccba72b26f98c5ae0a06611a32d694f258b4 | bigcode/the-stack | train |
fdc2f6085838a8d23315f7a2 | train | class | @pytest.mark.usefixtures('add_media')
class TestDownload():
@pytest.fixture
def expected_files(self, mocker, media_outputs):
expected = [
mocker.call(f, 'wb')
for f in media_outputs
]
return expected
def test_opened_correct_files(self, status, mock_o... | @pytest.mark.usefixtures('add_media')
class TestDownload():
@pytest.fixture
| def expected_files(self, mocker, media_outputs):
expected = [
mocker.call(f, 'wb')
for f in media_outputs
]
return expected
def test_opened_correct_files(self, status, mock_open, dirname, expected_files):
"""Tests process_status() opens correct fi... | (output_file, 'w', encoding='utf-32')
def test_wrote_correct_content(self, status, output_file):
"""Tests process_status() opens correct output_file for writing"""
ret = WriterThread.write_status(status=status, filename=output_file)
json.dump.assert_called_once_with(status.AsDict(), twitlib... | 96 | 96 | 320 | 17 | 79 | TidalPaladin/twitlib | test/test_streaming/test_statics.py | Python | TestDownload | TestDownload | 33 | 70 | 33 | 36 | b83367f1fd5037cf5d329b0fe840aa1bdb690916 | bigcode/the-stack | train |
5e54b9906ba928568a0399e4 | train | class | @pytest.mark.usefixtures("patch_io", 'patch_remove_urls', 'add_media')
class TestMirror(TestMirrorNoMedia):
"""Non-truncated mirroring"""
def test_posts_media_files(self, mocker, status, api, dirname, media_outputs, mock_open):
MirrorThread.mirror(api, status, dirname)
args, kwargs = api.PostUp... | @pytest.mark.usefixtures("patch_io", 'patch_remove_urls', 'add_media')
class TestMirror(TestMirrorNoMedia):
| """Non-truncated mirroring"""
def test_posts_media_files(self, mocker, status, api, dirname, media_outputs, mock_open):
MirrorThread.mirror(api, status, dirname)
args, kwargs = api.PostUpdate.call_args
actual = kwargs.get('media', None)
expected = media_outputs
assert(e... | , dirname)
@pytest.mark.skip
def test_catch_tweep_err(self, mocker, status, api, dirname):
mocker.patch.object(api, 'PostUpdate', side_effect=twitter.TwitterError(''))
MirrorThread.mirror(api, status, dirname)
@pytest.mark.usefixtures("patch_io", 'patch_remove_urls', 'add_media')
class TestMirr... | 84 | 84 | 281 | 25 | 59 | TidalPaladin/twitlib | test/test_streaming/test_statics.py | Python | TestMirror | TestMirror | 98 | 125 | 98 | 99 | 1e807a969a1633e9b421b585766d639519cc2d1e | bigcode/the-stack | train |
01f0ece742bf53ade02c9d71 | train | function | def pytest_html_report_title(report):
package = "urlstd"
title = "web-platform-tests: " + package
if sys.version_info[:2] >= (3, 8):
from importlib.metadata import version
title += " " + version(package)
title += " with ICU " + icu.U_ICU_VERSION
report.title = title
| def pytest_html_report_title(report):
| package = "urlstd"
title = "web-platform-tests: " + package
if sys.version_info[:2] >= (3, 8):
from importlib.metadata import version
title += " " + version(package)
title += " with ICU " + icu.U_ICU_VERSION
report.title = title
| import sys
import icupy.icu as icu
import pytest
from py.xml import html
def pytest_html_report_title(report):
| 28 | 64 | 79 | 7 | 20 | miute/url-standard | tests/wpt/conftest.py | Python | pytest_html_report_title | pytest_html_report_title | 8 | 16 | 8 | 8 | d47ef9a74b69ccdc9e49420fc65cbff87224b5b0 | bigcode/the-stack | train |
b1186c20a988a984c3692879 | train | function | @pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
report.description = item.function.__doc__ or ""
| @pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
| outcome = yield
report = outcome.get_result()
report.description = item.function.__doc__ or ""
| ):
cells.insert(2, html.th("Description"))
cells.pop()
def pytest_html_results_table_row(report, cells):
cells.insert(2, html.td(report.description))
cells.pop()
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
| 64 | 64 | 45 | 22 | 42 | miute/url-standard | tests/wpt/conftest.py | Python | pytest_runtest_makereport | pytest_runtest_makereport | 29 | 33 | 29 | 30 | 2f4ee345078482e07e5ce05d057ebe0a62a6f7e6 | bigcode/the-stack | train |
6cda8311c091880a236736ad | train | function | def pytest_html_results_table_header(cells):
cells.insert(2, html.th("Description"))
cells.pop()
| def pytest_html_results_table_header(cells):
| cells.insert(2, html.th("Description"))
cells.pop()
| package
if sys.version_info[:2] >= (3, 8):
from importlib.metadata import version
title += " " + version(package)
title += " with ICU " + icu.U_ICU_VERSION
report.title = title
def pytest_html_results_table_header(cells):
| 64 | 64 | 24 | 9 | 54 | miute/url-standard | tests/wpt/conftest.py | Python | pytest_html_results_table_header | pytest_html_results_table_header | 19 | 21 | 19 | 19 | dc6c61b0bbd93133147b12d67f9c0b6be964c2c9 | bigcode/the-stack | train |
34aa8bd78a9baf4d4465cdc3 | train | function | def pytest_html_results_table_row(report, cells):
cells.insert(2, html.td(report.description))
cells.pop()
| def pytest_html_results_table_row(report, cells):
| cells.insert(2, html.td(report.description))
cells.pop()
| title += " " + version(package)
title += " with ICU " + icu.U_ICU_VERSION
report.title = title
def pytest_html_results_table_header(cells):
cells.insert(2, html.th("Description"))
cells.pop()
def pytest_html_results_table_row(report, cells):
| 64 | 64 | 26 | 10 | 54 | miute/url-standard | tests/wpt/conftest.py | Python | pytest_html_results_table_row | pytest_html_results_table_row | 24 | 26 | 24 | 24 | ec40c2aef4451d67f2741b91e2a3db9683e41bc6 | bigcode/the-stack | train |
8fbd5339a542316d66506f77 | train | class | class OrderPaymentView(EventOrderDetailFormView):
template_name = 'payments/order_payment.html'
def get_context_data(self, **kwargs):
context = super().get_context_data()
context['PAYPAL_ADDITIONAL_CHARGE'] = settings.PAYPAL_ADDITIONAL_CHARGE
return context
def get_success_url(sel... | class OrderPaymentView(EventOrderDetailFormView):
| template_name = 'payments/order_payment.html'
def get_context_data(self, **kwargs):
context = super().get_context_data()
context['PAYPAL_ADDITIONAL_CHARGE'] = settings.PAYPAL_ADDITIONAL_CHARGE
return context
def get_success_url(self):
return reverse('konfera_payments:payme... | from django.urls import reverse
logger = logging.getLogger(__name__)
paypalrestsdk.configure({
"mode": settings.PAYPAL_MODE,
"client_id": settings.PAYPAL_CLIENT_ID,
"client_secret": settings.PAYPAL_CLIENT_SECRET,
})
class OrderPaymentView(EventOrderDetailFormView):
| 64 | 64 | 94 | 10 | 54 | pyconsk/django-konfera | payments/views.py | Python | OrderPaymentView | OrderPaymentView | 36 | 46 | 36 | 36 | b5ff67a7eabbe9761e8235b748b40e57fa50e912 | bigcode/the-stack | train |
3181a64c3bc353b3afa7c644 | train | class | class PayOrderByPaypal(TemplateView):
@staticmethod
def calculate_processing_fee(order):
""" Calculate the total price for order when paid by paypal """
return order.left_to_pay * Decimal(settings.PAYPAL_ADDITIONAL_CHARGE) / Decimal('100')
@staticmethod
def get_paypal_url(payment):
... | class PayOrderByPaypal(TemplateView):
@staticmethod
| def calculate_processing_fee(order):
""" Calculate the total price for order when paid by paypal """
return order.left_to_pay * Decimal(settings.PAYPAL_ADDITIONAL_CHARGE) / Decimal('100')
@staticmethod
def get_paypal_url(payment):
""" Return the PayPal URL where the user can pay for... | URRENCY
from konfera.event.views import EventOrderDetailFormView
from payments import settings
from payments.utils import _process_payment
if VERSION[1] in (8, 9):
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
logger = logging.getLogger(__name__)
paypalrestsdk.configur... | 256 | 256 | 954 | 13 | 242 | pyconsk/django-konfera | payments/views.py | Python | PayOrderByPaypal | PayOrderByPaypal | 58 | 176 | 58 | 60 | 5328171e38fba6f5882a81e74e03a037ff32e9c0 | bigcode/the-stack | train |
8ef271cddf0a5db7a28d27a6 | train | class | class OrderPaymentThanksView(OrderPaymentView):
def get_context_data(self, **kwargs):
context = super().get_context_data()
generate_ga_ecommerce_context(self.object, context)
return context
| class OrderPaymentThanksView(OrderPaymentView):
| def get_context_data(self, **kwargs):
context = super().get_context_data()
generate_ga_ecommerce_context(self.object, context)
return context
| context['PAYPAL_ADDITIONAL_CHARGE'] = settings.PAYPAL_ADDITIONAL_CHARGE
return context
def get_success_url(self):
return reverse('konfera_payments:payment_options', kwargs={'order_uuid': self.object.order.uuid})
class OrderPaymentThanksView(OrderPaymentView):
| 64 | 64 | 43 | 9 | 55 | pyconsk/django-konfera | payments/views.py | Python | OrderPaymentThanksView | OrderPaymentThanksView | 49 | 55 | 49 | 50 | c2e77d7f5cf64f1d02b86bc767f502c35b30f267 | bigcode/the-stack | train |
7e8214906f6f24df4ca16f21 | train | class | class TextField(SequenceField[Dict[str, torch.Tensor]]):
"""
This ``Field`` represents a list of string tokens. Before constructing this object, you need
to tokenize raw strings using a :class:`~stog.data.tokenizers.tokenizer.Tokenizer`.
Because string tokens can be represented as indexed arrays in a ... | class TextField(SequenceField[Dict[str, torch.Tensor]]):
| """
This ``Field`` represents a list of string tokens. Before constructing this object, you need
to tokenize raw strings using a :class:`~stog.data.tokenizers.tokenizer.Tokenizer`.
Because string tokens can be represented as indexed arrays in a number of ways, we also take a
dictionary of :class:`... | """
A ``TextField`` represents a string of text, the kind that you might want to represent with
standard word vectors, or pass through an LSTM.
"""
from typing import Dict, List, Optional
import textwrap
from overrides import overrides
from spacy.tokens import Token as SpacyToken
import torch
from stog.utils.checks i... | 165 | 256 | 1,849 | 14 | 150 | emorynlp/levi-graph-amr-parser | stog/data/fields/text_field.py | Python | TextField | TextField | 22 | 177 | 22 | 22 | 0f66405a595e1a9c6c2f0a83a7c82e7fa6e4f934 | bigcode/the-stack | train |
89bf88d3e8aac2028bb4417a | train | class | class Kernel(Enum):
"""Enum containing possible kernels for Kernel Density Estimation."""
GAUSSIAN = "gaussian"
TOPHAT = "tophat"
EPANECHNIKOV = "epanechnikov"
EXPONENTIAL = "exponential"
LINEAR = "linear"
COSINE = "cosine"
| class Kernel(Enum):
| """Enum containing possible kernels for Kernel Density Estimation."""
GAUSSIAN = "gaussian"
TOPHAT = "tophat"
EPANECHNIKOV = "epanechnikov"
EXPONENTIAL = "exponential"
LINEAR = "linear"
COSINE = "cosine"
| from enum import Enum
class Kernel(Enum):
| 9 | 64 | 74 | 4 | 4 | dlasecki/QaoaParamsPredictor | predictor/data_structures/enums/kernel.py | Python | Kernel | Kernel | 4 | 11 | 4 | 4 | 0e9e688821d8c7ead6b51b16b414e55e514d029d | bigcode/the-stack | train |
ba4532af70c925386540caca | train | function | def sanitize_k8s_name(name, allow_capital_underscore=False):
"""Cleans and converts the names in the workflow.
Args:
name: original name,
allow_capital_underscore: whether to allow capital letter and underscore in this name.
Returns:
A sanitized name.
"""
if allow_capital_underscore:
return ... | def sanitize_k8s_name(name, allow_capital_underscore=False):
| """Cleans and converts the names in the workflow.
Args:
name: original name,
allow_capital_underscore: whether to allow capital letter and underscore in this name.
Returns:
A sanitized name.
"""
if allow_capital_underscore:
return re.sub('-+', '-', re.sub('[^-_0-9A-Za-z]+', '-', name)).lstri... | class
# For now, this identifies a condition with only "==" operator supported.
ConditionOperator = namedtuple('ConditionOperator', 'operator operand1 operand2')
PipelineParamTuple = namedtuple('PipelineParamTuple', 'name op pattern')
def sanitize_k8s_name(name, allow_capital_underscore=False):
| 64 | 64 | 134 | 15 | 49 | deepk2u/pipelines | sdk/python/kfp/dsl/_pipeline_param.py | Python | sanitize_k8s_name | sanitize_k8s_name | 25 | 38 | 25 | 25 | 3504827d21ba10d93d228b03530e884eeaf7ffba | bigcode/the-stack | train |
8b2a3945e1fcbdddc2618648 | train | function | def _extract_pipelineparams(payloads: Union[str, List[str]]) -> List['PipelineParam']:
"""Extracts a list of PipelineParam instances from the payload string.
Note: this function removes all duplicate matches.
Args:
payload: a string/a list of strings that contains serialized pipelineparams
Return:
Lis... | def _extract_pipelineparams(payloads: Union[str, List[str]]) -> List['PipelineParam']:
| """Extracts a list of PipelineParam instances from the payload string.
Note: this function removes all duplicate matches.
Args:
payload: a string/a list of strings that contains serialized pipelineparams
Return:
List[]
"""
if isinstance(payloads, str):
payloads = [payloads]
param_tuples = []... | .append(PipelineParamTuple(
name=sanitize_k8s_name(match[1], True),
op=sanitize_k8s_name(match[0]),
pattern=pattern))
return param_tuples
def _extract_pipelineparams(payloads: Union[str, List[str]]) -> List['PipelineParam']:
| 64 | 64 | 157 | 20 | 43 | deepk2u/pipelines | sdk/python/kfp/dsl/_pipeline_param.py | Python | _extract_pipelineparams | _extract_pipelineparams | 61 | 81 | 61 | 61 | 796e652ae02d4cf9e35927e8956236637dbfa39a | bigcode/the-stack | train |
b0b19595a95d325cdbd068d3 | train | function | def extract_pipelineparams_from_any(payload: Union['PipelineParam', str, list, tuple, dict]) -> List['PipelineParam']:
"""Recursively extract PipelineParam instances or serialized string from any object or list of objects.
Args:
payload (str or k8_obj or list[str or k8_obj]): a string/a list
of string... | def extract_pipelineparams_from_any(payload: Union['PipelineParam', str, list, tuple, dict]) -> List['PipelineParam']:
| """Recursively extract PipelineParam instances or serialized string from any object or list of objects.
Args:
payload (str or k8_obj or list[str or k8_obj]): a string/a list
of strings that contains serialized pipelineparams or a k8 definition
object.
Return:
List[PipelineParam]
"""
... | param_tuples = []
for payload in payloads:
param_tuples += match_serialized_pipelineparam(payload)
pipeline_params = []
for param_tuple in list(set(param_tuples)):
pipeline_params.append(PipelineParam(param_tuple.name,
param_tuple.op,
... | 96 | 96 | 322 | 27 | 68 | deepk2u/pipelines | sdk/python/kfp/dsl/_pipeline_param.py | Python | extract_pipelineparams_from_any | extract_pipelineparams_from_any | 84 | 129 | 84 | 84 | 4665310c83137efc2e5b03f8ad5571851d50cd29 | bigcode/the-stack | train |
fee1ecb86e4e440297287901 | train | class | class PipelineParam(object):
"""Representing a future value that is passed between pipeline components.
A PipelineParam object can be used as a pipeline function argument so that it will be a
pipeline parameter that shows up in ML Pipelines system UI. It can also represent an intermediate
value passed between ... | class PipelineParam(object):
| """Representing a future value that is passed between pipeline components.
A PipelineParam object can be used as a pipeline function argument so that it will be a
pipeline parameter that shows up in ML Pipelines system UI. It can also represent an intermediate
value passed between components.
Args:
name... | strings that contains serialized pipelineparams or a k8 definition
object.
Return:
List[PipelineParam]
"""
if not payload:
return []
# PipelineParam
if isinstance(payload, PipelineParam):
return [payload]
# str
if isinstance(payload, str):
return list(set(_extract_pipelinepara... | 255 | 256 | 936 | 5 | 250 | deepk2u/pipelines | sdk/python/kfp/dsl/_pipeline_param.py | Python | PipelineParam | PipelineParam | 132 | 229 | 132 | 132 | ec5d35aa75d261999053260288aba7b6f26027a9 | bigcode/the-stack | train |
04332f5a8cd066682df9e013 | train | function | def match_serialized_pipelineparam(payload: str) -> List[PipelineParamTuple]:
"""Matches the supplied serialized pipelineparam.
Args:
payloads: The search space for the serialized pipelineparams.
Returns:
The matched pipeline params we found in the supplied payload.
"""
matches = re.findall(r'{{pipe... | def match_serialized_pipelineparam(payload: str) -> List[PipelineParamTuple]:
| """Matches the supplied serialized pipelineparam.
Args:
payloads: The search space for the serialized pipelineparams.
Returns:
The matched pipeline params we found in the supplied payload.
"""
matches = re.findall(r'{{pipelineparam:op=([\w\s_-]*);name=([\w\s_-]+)}}', payload)
param_tuples = []
f... | A-Za-z]+', '-', name)).lstrip('-').rstrip('-')
else:
return re.sub('-+', '-', re.sub('[^-0-9a-z]+', '-', name.lower())).lstrip('-').rstrip('-')
def match_serialized_pipelineparam(payload: str) -> List[PipelineParamTuple]:
| 64 | 64 | 175 | 17 | 47 | deepk2u/pipelines | sdk/python/kfp/dsl/_pipeline_param.py | Python | match_serialized_pipelineparam | match_serialized_pipelineparam | 41 | 58 | 41 | 41 | e68a1b84ad9dba13f70707f802f76ad39af26522 | bigcode/the-stack | train |
a6f78f8e145e405cf45affe2 | train | function | def main(argv):
ipcsList = []
result = os.popen('ipcs -m')
res = result.read()
findshmid = 0
for line in res.splitlines():
print(line)
if findshmid == 1:
line = line.strip()
if len(line) == 0:
continue
tmplist = line.split(" "... | def main(argv):
| ipcsList = []
result = os.popen('ipcs -m')
res = result.read()
findshmid = 0
for line in res.splitlines():
print(line)
if findshmid == 1:
line = line.strip()
if len(line) == 0:
continue
tmplist = line.split(" ")
ipcsLis... | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import sys
import getopt
import os
import time
import datetime
def main(argv):
| 35 | 64 | 155 | 5 | 29 | SZU-SE/PERIOD | tool/staticAnalysis/clean_shm.py | Python | main | main | 10 | 34 | 10 | 11 | d0085c656ea1dbb94ffc2df22535f8874935c576 | bigcode/the-stack | train |
5c0999cc8fcce55019eb27fb | train | class | class MyPlayer:
def __init__(self, name=[], go=None, piece_type=None, expansion_limit=None,
verbose=None, b_tune=None, w_tune=None):
self.name = name
self.verbose = verbose
self.state = go
self.piece_type = piece_type
self.expansion_limit = expan... | class MyPlayer:
| def __init__(self, name=[], go=None, piece_type=None, expansion_limit=None,
verbose=None, b_tune=None, w_tune=None):
self.name = name
self.verbose = verbose
self.state = go
self.piece_type = piece_type
self.expansion_limit = expansion_limit
... | from go import *
from util import *
from os import path
import random
from math import inf
class MyPlayer:
| 25 | 256 | 2,875 | 4 | 20 | rsyamil/minimax-seven-go | my_player.py | Python | MyPlayer | MyPlayer | 7 | 275 | 7 | 8 | 20871ffc97b7952eb8d3f3f9c307fee0a649db15 | bigcode/the-stack | train |
5bae0b67edf842931faf5c2d | train | class | class FacilityGeometryCollection(FacilityGeoBase, GeometryCollection):
geometries: List[Geometry]
| class FacilityGeometryCollection(FacilityGeoBase, GeometryCollection):
| geometries: List[Geometry]
| Polygon,
)
from pydantic import BaseModel
Geometry = Union[Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon]
class FacilityGeoBase(BaseModel):
class Config:
arbitrary_types_allowed = True
class FacilityGeometryCollection(FacilityGeoBase, GeometryCollection):
| 64 | 64 | 21 | 13 | 50 | paulculmsee/opennem | opennem/api/geo/schema.py | Python | FacilityGeometryCollection | FacilityGeometryCollection | 32 | 33 | 32 | 32 | daf663e5f839e8cf648174129562770d5a724e29 | bigcode/the-stack | train |
63e8e286eab8d6066db870b5 | train | class | class FacilityGeoBase(BaseModel):
class Config:
arbitrary_types_allowed = True
| class FacilityGeoBase(BaseModel):
| class Config:
arbitrary_types_allowed = True
| GeometryCollection,
LineString,
MultiLineString,
MultiPoint,
MultiPolygon,
Point,
Polygon,
)
from pydantic import BaseModel
Geometry = Union[Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon]
class FacilityGeoBase(BaseModel):
| 64 | 64 | 18 | 7 | 57 | paulculmsee/opennem | opennem/api/geo/schema.py | Python | FacilityGeoBase | FacilityGeoBase | 27 | 29 | 27 | 27 | c750f5b6c05fd24c35081769d73d57c22cdf8e79 | bigcode/the-stack | train |
8e7165051c90bf31adbcd780 | train | class | class FacilityGeo(FacilityGeoBase, FeatureCollection):
name: str = "opennem"
crs: Optional[Dict]
features: Sequence[FacilityFeature] # type: ignore
| class FacilityGeo(FacilityGeoBase, FeatureCollection):
| name: str = "opennem"
crs: Optional[Dict]
features: Sequence[FacilityFeature] # type: ignore
| """
Update to default to GeometryCollection
"""
# @TODO - correct schema for GeoJSON that supports both versions
bbox: Optional[Any]
properties: Optional[Any]
geometry: Optional[Geometry] # type: ignore
class FacilityGeo(FacilityGeoBase, FeatureCollection):
| 64 | 64 | 43 | 12 | 51 | paulculmsee/opennem | opennem/api/geo/schema.py | Python | FacilityGeo | FacilityGeo | 47 | 50 | 47 | 47 | 4feeaa7877c0fb664ff16dbfec7eeffeefe40633 | bigcode/the-stack | train |
cb7e047d2caec92528cd8102 | train | class | class FacilityFeature(BaseModel):
"""
Update to default to GeometryCollection
"""
# @TODO - correct schema for GeoJSON that supports both versions
bbox: Optional[Any]
properties: Optional[Any]
geometry: Optional[Geometry] # type: ignore
| class FacilityFeature(BaseModel):
| """
Update to default to GeometryCollection
"""
# @TODO - correct schema for GeoJSON that supports both versions
bbox: Optional[Any]
properties: Optional[Any]
geometry: Optional[Geometry] # type: ignore
| Union[Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon]
class FacilityGeoBase(BaseModel):
class Config:
arbitrary_types_allowed = True
class FacilityGeometryCollection(FacilityGeoBase, GeometryCollection):
geometries: List[Geometry]
class FacilityFeature(BaseModel):
| 64 | 64 | 58 | 6 | 58 | paulculmsee/opennem | opennem/api/geo/schema.py | Python | FacilityFeature | FacilityFeature | 36 | 44 | 36 | 36 | b954e4c070d6de3f1d3fafe2a53c054309449aad | bigcode/the-stack | train |
4189e2df4b85e2a05064512a | train | class | class Nothing:
""" A utility class to represent nothing where None does not suffice """
| class Nothing:
| """ A utility class to represent nothing where None does not suffice """
| class Nothing:
| 3 | 64 | 17 | 3 | 0 | khunspoonzi/pyob | pyob/utils/__init__.py | Python | Nothing | Nothing | 1 | 2 | 1 | 1 | 698e45cd01e0d66fb2a7451777449e413abb4e0c | bigcode/the-stack | train |
6a13591682f64b3eaa4734c0 | train | class | class AdminCliRequestHandler(object):
"""
Class to handles requests from admin CLI
"""
def __init__(self, event, context):
"""
Initializes handle instance
:param event: event to handle
:param context: lambda context
"""
self._event = event
self._c... | class AdminCliRequestHandler(object):
| """
Class to handles requests from admin CLI
"""
def __init__(self, event, context):
"""
Initializes handle instance
:param event: event to handle
:param context: lambda context
"""
self._event = event
self._context = context
self._logger ... | ######################################################################################################################
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... | 230 | 256 | 1,026 | 7 | 223 | linuxplayground/aws-instance-scheduler | source/lambda/requesthandlers/admin_cli_request_handler.py | Python | AdminCliRequestHandler | AdminCliRequestHandler | 28 | 177 | 28 | 28 | 1ed20411ebe9e6836e3f37a6653e0aed6c4368bd | bigcode/the-stack | train |
74c60711a86b01cf72d6070e | train | class | class FoodItem(SurrogatePK, Model, AWS_Mixin):
"""Store an actual dish the user uploads"""
# list of fields containing data that should be uploaded to s3; if the class extends AWS_Mixin, it must also include the list of fields to send to AWS
__sendtos3__ = ['image']
__tablename__ = "food"
... | class FoodItem(SurrogatePK, Model, AWS_Mixin):
| """Store an actual dish the user uploads"""
# list of fields containing data that should be uploaded to s3; if the class extends AWS_Mixin, it must also include the list of fields to send to AWS
__sendtos3__ = ['image']
__tablename__ = "food"
title = Column(db.String(80), nullable=False... | _to_s3:
#current_app.logger.info("SEND TO S3 FAILED - REMOVING OBJ FROM SESSION")
session.expunge(model)
# setting this field to signal to the UI (view) that we did not save this obj
model.persistent = False
else:
... | 104 | 104 | 349 | 14 | 89 | ariesunique/food-journal | food_journal/public/models.py | Python | FoodItem | FoodItem | 77 | 111 | 77 | 77 | 73481d0cb6907b9d5da371b14b42d2a5845aa6f7 | bigcode/the-stack | train |
b3f580c0638ed90f83e4d0f7 | train | class | class AWS_Mixin(object):
@classmethod
def upload_to_s3(cls, model):
current_app.logger.info("SENDINGTO S3")
BUCKET = current_app.config["S3_BUCKET_NAME"]
for field in model.__sendtos3__:
obj = getattr(model, field)
filename = secure_filename(obj.filename)
... | class AWS_Mixin(object):
@classmethod
| def upload_to_s3(cls, model):
current_app.logger.info("SENDINGTO S3")
BUCKET = current_app.config["S3_BUCKET_NAME"]
for field in model.__sendtos3__:
obj = getattr(model, field)
filename = secure_filename(obj.filename)
with tempfile.TemporaryDirectory() as ... | """Food models"""
import datetime as dt
from werkzeug.utils import secure_filename
import os
import boto3
import requests
import tempfile
from botocore.exceptions import ClientError, ParamValidationError
from flask import current_app
from flask_login import UserMixin
from food_journal.database import (
Column,... | 95 | 132 | 441 | 10 | 85 | ariesunique/food-journal | food_journal/public/models.py | Python | AWS_Mixin | AWS_Mixin | 25 | 73 | 25 | 26 | 821329e928b8cdbb1fb247f4cf6b09a248b42ad9 | bigcode/the-stack | train |
9b346fa71b652d8ecece8353 | train | class | class ResourceProviderResponse:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_l... | class ResourceProviderResponse:
| """
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import pprint
import re
import six
class ResourceProviderResponse:
| 21 | 256 | 1,133 | 5 | 15 | wuchen-huawei/huaweicloud-sdk-python-v3 | huaweicloud-sdk-rms/huaweicloudsdkrms/v1/model/resource_provider_response.py | Python | ResourceProviderResponse | ResourceProviderResponse | 12 | 191 | 12 | 14 | def9d7a9b0c9d8fffc340906c9948616cb518706 | bigcode/the-stack | train |
e62426c587b1e346f225a106 | train | class | class TestDataSourceExpressions(SimpleTestCase):
data_source_name = None
def get_expression(self, column_id, column_type):
column = self.get_column(column_id)
if column['type'] == 'boolean':
return FilterFactory.from_spec(
column['filter'],
context=F... | class TestDataSourceExpressions(SimpleTestCase):
| data_source_name = None
def get_expression(self, column_id, column_type):
column = self.get_column(column_id)
if column['type'] == 'boolean':
return FilterFactory.from_spec(
column['filter'],
context=FactoryContext(self.named_expressions, {})
... | ):
self.factory = RequestFactory()
domain = Domain.get_or_create_with_name('champ-cameroon')
domain.is_active = True
domain.save()
self.domain = domain
user = WebUser.all().first()
if not user:
user = WebUser.create(domain.name, 'test', 'passwordtest')... | 114 | 114 | 381 | 9 | 104 | kkrampa/commcare-hq | custom/champ/tests/utils.py | Python | TestDataSourceExpressions | TestDataSourceExpressions | 41 | 92 | 41 | 42 | f1ea383b32330387b69cb5efd98b70e809ac10aa | bigcode/the-stack | train |
c871a1fa95e1d64c14a96968 | train | class | class ChampTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
domain = Domain.get_or_create_with_name('champ-cameroon')
domain.is_active = True
domain.save()
self.domain = domain
user = WebUser.all().first()
if not user:
user = W... | class ChampTestCase(TestCase):
| def setUp(self):
self.factory = RequestFactory()
domain = Domain.get_or_create_with_name('champ-cameroon')
domain.is_active = True
domain.save()
self.domain = domain
user = WebUser.all().first()
if not user:
user = WebUser.create(domain.name, 'test... | .factory import FilterFactory
from corehq.apps.userreports.models import DataSourceConfiguration
from corehq.apps.userreports.specs import FactoryContext
from corehq.apps.users.models import CommCareUser
from couchforms.models import XFormInstance
import os
from io import open
class ChampTestCase(TestCase):
| 64 | 64 | 117 | 7 | 56 | kkrampa/commcare-hq | custom/champ/tests/utils.py | Python | ChampTestCase | ChampTestCase | 23 | 38 | 23 | 24 | e00af9e058e63e82b254b4223b0b43af6260e9ce | bigcode/the-stack | train |
47d5c90a0610efd56236bb08 | train | function | def launch_local(
runner: Runner,
command: List[str],
env_overrides: Dict[str, str],
replace_dns_tools: bool,
) -> Popen:
# Compute user process environment
env = os.environ.copy()
env.update(env_overrides)
env["PROMPT_COMMAND"] = (
'PS1="@{}|$PS1";unset PROMPT_COMMAND'.format(ru... | def launch_local(
runner: Runner,
command: List[str],
env_overrides: Dict[str, str],
replace_dns_tools: bool,
) -> Popen:
# Compute user process environment
| env = os.environ.copy()
env.update(env_overrides)
env["PROMPT_COMMAND"] = (
'PS1="@{}|$PS1";unset PROMPT_COMMAND'.format(runner.kubectl.context)
)
env["PATH"] = apply_workarounds(runner, env["PATH"], replace_dns_tools)
# Launch the user process
runner.show("Setup complete. Launching... | else:
runner.write("Local process is already dead (ret={})".format(ret))
def launch_local(
runner: Runner,
command: List[str],
env_overrides: Dict[str, str],
replace_dns_tools: bool,
) -> Popen:
# Compute user process environment
| 64 | 64 | 194 | 44 | 20 | Xide/telepresence | telepresence/outbound/local.py | Python | launch_local | launch_local | 85 | 108 | 85 | 91 | 99b49a3d483510b7f8fa5f3e09cc65252a0778f6 | bigcode/the-stack | train |
51152f0b2a54dd5d1d1d269e | train | function | def set_up_torsocks(runner: Runner, socks_port: int) -> Dict[str, str]:
"""
Set up environment variables and configuration to make torsocks work
correctly. Wait for connectivity.
"""
span = runner.span()
# Create custom torsocks.conf, since some options we want (in particular,
# port) aren't... | def set_up_torsocks(runner: Runner, socks_port: int) -> Dict[str, str]:
| """
Set up environment variables and configuration to make torsocks work
correctly. Wait for connectivity.
"""
span = runner.span()
# Create custom torsocks.conf, since some options we want (in particular,
# port) aren't accessible via env variables in older versions of torsocks:
tor_con... | import RemoteInfo
from telepresence.runner import Runner
from telepresence.utilities import kill_process
from .vpn import connect_sshuttle
from .workarounds import apply_workarounds
TORSOCKS_CONFIG = """
# Allow process to listen on ports:
AllowInbound 1
# Allow process to connect to localhost:
AllowOutboundLocalhos... | 109 | 109 | 366 | 22 | 87 | Xide/telepresence | telepresence/outbound/local.py | Python | set_up_torsocks | set_up_torsocks | 37 | 73 | 37 | 37 | 95ab5c074375dd57782cd2bb543f69f0c332edf3 | bigcode/the-stack | train |
0ea71ff073907b30d3fc7473 | train | function | def launch_vpn(
runner: Runner,
remote_info: RemoteInfo,
command: List[str],
also_proxy: List[str],
env_overrides: Dict[str, str],
ssh: SSH,
) -> Popen:
"""
Launch sshuttle and the user's command
"""
connect_sshuttle(runner, remote_info, also_proxy, ssh)
_flush_dns_cache(runn... | def launch_vpn(
runner: Runner,
remote_info: RemoteInfo,
command: List[str],
also_proxy: List[str],
env_overrides: Dict[str, str],
ssh: SSH,
) -> Popen:
| """
Launch sshuttle and the user's command
"""
connect_sshuttle(runner, remote_info, also_proxy, ssh)
_flush_dns_cache(runner)
return launch_local(runner, command, env_overrides, False)
| return launch_local(runner, command, env_overrides, True)
def launch_vpn(
runner: Runner,
remote_info: RemoteInfo,
command: List[str],
also_proxy: List[str],
env_overrides: Dict[str, str],
ssh: SSH,
) -> Popen:
| 64 | 64 | 102 | 50 | 14 | Xide/telepresence | telepresence/outbound/local.py | Python | launch_vpn | launch_vpn | 125 | 139 | 125 | 132 | 79ea05e2065dcb0d814a9dd9984bb1c9dd7ec5de | bigcode/the-stack | train |
66b00b6e9704910f94ae0204 | train | function | def terminate_local_process(runner: Runner, process: Popen) -> None:
ret = process.poll()
if ret is None:
runner.write("Killing local process...")
kill_process(process)
else:
runner.write("Local process is already dead (ret={})".format(ret))
| def terminate_local_process(runner: Runner, process: Popen) -> None:
| ret = process.poll()
if ret is None:
runner.write("Killing local process...")
kill_process(process)
else:
runner.write("Local process is already dead (ret={})".format(ret))
| (test_proxying_cmd, env=launch_env)
return torsocks_env
except CalledProcessError:
pass
raise RuntimeError("SOCKS network proxying failed to start...")
finally:
span.end()
def terminate_local_process(runner: Runner, process: Popen) -> None:
| 64 | 64 | 63 | 17 | 47 | Xide/telepresence | telepresence/outbound/local.py | Python | terminate_local_process | terminate_local_process | 76 | 82 | 76 | 76 | c0a467db40c9654849e253fffa1942c1528f86cf | bigcode/the-stack | train |
f62eda57e68561b7828e163a | train | function | def launch_inject(
runner: Runner,
command: List[str],
socks_port: int,
env_overrides: Dict[str, str],
) -> Popen:
"""
Launch the user's command under torsocks
"""
torsocks_env = set_up_torsocks(runner, socks_port)
env_overrides.update(torsocks_env)
return launch_local(runner, co... | def launch_inject(
runner: Runner,
command: List[str],
socks_port: int,
env_overrides: Dict[str, str],
) -> Popen:
| """
Launch the user's command under torsocks
"""
torsocks_env = set_up_torsocks(runner, socks_port)
env_overrides.update(torsocks_env)
return launch_local(runner, command, env_overrides, True)
| (exc))
runner.add_cleanup(
"Terminate local process", terminate_local_process, runner, process
)
return process
def launch_inject(
runner: Runner,
command: List[str],
socks_port: int,
env_overrides: Dict[str, str],
) -> Popen:
| 64 | 64 | 91 | 37 | 26 | Xide/telepresence | telepresence/outbound/local.py | Python | launch_inject | launch_inject | 111 | 122 | 111 | 116 | 7422d5f1a5aea4648dab7d31af0c0eddbb7ae932 | bigcode/the-stack | train |
e8d1c724db9b02827392c432 | train | function | def _flush_dns_cache(runner: Runner):
if runner.platform == "darwin":
runner.show("Connected. Flushing DNS cache.")
pkill_cmd = ["sudo", "-n", "/usr/bin/pkill", "-HUP", "mDNSResponder"]
try:
runner.check_call(pkill_cmd)
except (OSError, CalledProcessError):
pa... | def _flush_dns_cache(runner: Runner):
| if runner.platform == "darwin":
runner.show("Connected. Flushing DNS cache.")
pkill_cmd = ["sudo", "-n", "/usr/bin/pkill", "-HUP", "mDNSResponder"]
try:
runner.check_call(pkill_cmd)
except (OSError, CalledProcessError):
pass
| open:
"""
Launch sshuttle and the user's command
"""
connect_sshuttle(runner, remote_info, also_proxy, ssh)
_flush_dns_cache(runner)
return launch_local(runner, command, env_overrides, False)
def _flush_dns_cache(runner: Runner):
| 64 | 64 | 80 | 10 | 54 | Xide/telepresence | telepresence/outbound/local.py | Python | _flush_dns_cache | _flush_dns_cache | 142 | 149 | 142 | 142 | e6a0fc36baaa3d5485332d3c2278195e1dee67e9 | bigcode/the-stack | train |
badd0c30af3b30ddeaf75fa9 | train | class | class Application(tk.Frame):
def __init__(self, master):
super().__init__(master)
master.protocol("WM_DELETE_WINDOW", self.exit)
with open('./calib.txt') as f:
s = f.read()
c = s.split(',')
for i, val in enumerate(c):
send_command([i, 12100+int(val)])... | class Application(tk.Frame):
| def __init__(self, master):
super().__init__(master)
master.protocol("WM_DELETE_WINDOW", self.exit)
with open('./calib.txt') as f:
s = f.read()
c = s.split(',')
for i, val in enumerate(c):
send_command([i, 12100+int(val)])
self.status = 2
... | # coding:utf-8
from controller import set_status, send_command
from cube_main import solve, shuffle
import tkinter as tk
import threading
class Application(tk.Frame):
| 37 | 172 | 574 | 6 | 30 | artec-kk/Studth | gui_solve.py | Python | Application | Application | 8 | 81 | 8 | 8 | 2b5d9eea9a1753c083a41c56ab9ef0964145789e | bigcode/the-stack | train |
2f4f86b8d8ffd549a8df5072 | train | class | class HadoopJob(GenieJob):
"""Hadoop job."""
def __init__(self, conf=None):
super(HadoopJob, self).__init__(conf=conf)
self._property_file = None
self._script = None
@property
def cmd_args(self):
"""
The constructed command line arguments using the job's defini... | class HadoopJob(GenieJob):
| """Hadoop job."""
def __init__(self, conf=None):
super(HadoopJob, self).__init__(conf=conf)
self._property_file = None
self._script = None
@property
def cmd_args(self):
"""
The constructed command line arguments using the job's definition. If the
comman... | """
genie.jobs.hadoop
This module implements creating Hadoop jobs.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import os
from ..utils import unicodify
from .core import GenieJob
from .utils import (add_to_repr,
arg_string)
logger = lo... | 85 | 231 | 773 | 8 | 77 | cclauss/pygenie | pygenie/jobs/hadoop.py | Python | HadoopJob | HadoopJob | 23 | 140 | 23 | 23 | 556df03aba79048c6714e325863a4fe1a3f630c8 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.