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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5a3d37be77720fc1887aa36b | train | class | class urlparts(NamedTuple):
"""Named tuple representing parts of the URL."""
scheme: str
hostname: str
port: int
username: str
password: str
path: str
query: Mapping
| class urlparts(NamedTuple):
| """Named tuple representing parts of the URL."""
scheme: str
hostname: str
port: int
username: str
password: str
path: str
query: Mapping
| quote, urlparse
try:
import ssl
ssl_available = True
except ImportError: # pragma: no cover
ssl_available = False
from ..log import get_logger
safequote = partial(quote, safe='')
logger = get_logger(__name__)
class urlparts(NamedTuple):
| 64 | 64 | 52 | 7 | 57 | kaiix/kombu | kombu/utils/url.py | Python | urlparts | urlparts | 21 | 30 | 21 | 21 | cc05dc3245f822a59d0b347c21e4bfc1301d95f3 | bigcode/the-stack | train |
f4ba294ab597c92d0325e538 | train | function | def url_to_parts(url):
# type: (str) -> urlparts
"""Parse URL into :class:`urlparts` tuple of components."""
scheme = urlparse(url).scheme
schemeless = url[len(scheme) + 3:]
# parse with HTTP URL semantics
parts = urlparse('http://' + schemeless)
path = parts.path or ''
path = path[1:] i... | def url_to_parts(url):
# type: (str) -> urlparts
| """Parse URL into :class:`urlparts` tuple of components."""
scheme = urlparse(url).scheme
schemeless = url[len(scheme) + 3:]
# parse with HTTP URL semantics
parts = urlparse('http://' + schemeless)
path = parts.path or ''
path = path[1:] if path and path[0] == '/' else path
return urlpar... | query['ssl'][key] = query[key]
del query[key]
return dict(transport=scheme, hostname=host,
port=port, userid=user,
password=password, virtual_host=path, **query)
def url_to_parts(url):
# type: (str) -> urlparts
| 64 | 64 | 163 | 17 | 47 | kaiix/kombu | kombu/utils/url.py | Python | url_to_parts | url_to_parts | 56 | 73 | 56 | 57 | 9ed01599a2595b70d6a75d3cfd71566a522917af | bigcode/the-stack | train |
5a95b827d5b26007cf5b05e0 | train | function | def maybe_sanitize_url(url, mask='**'):
# type: (Any, str) -> Any
"""Sanitize url, or do nothing if url undefined."""
if isinstance(url, str) and '://' in url:
return sanitize_url(url, mask)
return url
| def maybe_sanitize_url(url, mask='**'):
# type: (Any, str) -> Any
| """Sanitize url, or do nothing if url undefined."""
if isinstance(url, str) and '://' in url:
return sanitize_url(url, mask)
return url
| **'):
# type: (str, str) -> str
"""Return copy of URL with password removed."""
return as_url(*_parse_url(url), sanitize=True, mask=mask)
def maybe_sanitize_url(url, mask='**'):
# type: (Any, str) -> Any
| 64 | 64 | 61 | 23 | 41 | kaiix/kombu | kombu/utils/url.py | Python | maybe_sanitize_url | maybe_sanitize_url | 106 | 111 | 106 | 107 | 8807a94b5d8fedc9247fe8f8a01b3a5eb58ea799 | bigcode/the-stack | train |
c59aa7052f1cb86cd3b43c15 | train | function | def as_url(scheme, host=None, port=None, user=None, password=None,
path=None, query=None, sanitize=False, mask='**'):
# type: (str, str, int, str, str, str, str, bool, str) -> str
"""Generate URL from component parts."""
parts = [f'{scheme}://']
if user or password:
if user:
... | def as_url(scheme, host=None, port=None, user=None, password=None,
path=None, query=None, sanitize=False, mask='**'):
# type: (str, str, int, str, str, str, str, bool, str) -> str
| """Generate URL from component parts."""
parts = [f'{scheme}://']
if user or password:
if user:
parts.append(safequote(user))
if password:
if sanitize:
parts.extend([':', mask] if mask else [':'])
else:
parts.extend([':', sa... | _url = url_to_parts
def as_url(scheme, host=None, port=None, user=None, password=None,
path=None, query=None, sanitize=False, mask='**'):
# type: (str, str, int, str, str, str, str, bool, str) -> str
| 64 | 64 | 176 | 58 | 5 | kaiix/kombu | kombu/utils/url.py | Python | as_url | as_url | 79 | 97 | 79 | 81 | 7273b5593035fc9d1bc6ed3c6548f18ce3a5d1a8 | bigcode/the-stack | train |
cc65fceb52f3eef34cae053f | train | function | def sanitize_url(url, mask='**'):
# type: (str, str) -> str
"""Return copy of URL with password removed."""
return as_url(*_parse_url(url), sanitize=True, mask=mask)
| def sanitize_url(url, mask='**'):
# type: (str, str) -> str
| """Return copy of URL with password removed."""
return as_url(*_parse_url(url), sanitize=True, mask=mask)
| parts.append(safequote(host) if host else '')
if port:
parts.extend([':', port])
parts.extend(['/', path])
return ''.join(str(part) for part in parts if part)
def sanitize_url(url, mask='**'):
# type: (str, str) -> str
| 64 | 64 | 48 | 21 | 43 | kaiix/kombu | kombu/utils/url.py | Python | sanitize_url | sanitize_url | 100 | 103 | 100 | 101 | 5f9f0462af83c1782262f755ad2f6983e7afd35e | bigcode/the-stack | train |
0715ed65534d2e978bfc9a47 | train | function | def parse_url(url):
# type: (str) -> Dict
"""Parse URL into mapping of components."""
scheme, host, port, user, password, path, query = _parse_url(url)
if query:
keys = [key for key in query.keys() if key.startswith('ssl_')]
for key in keys:
if key == 'ssl_cert_reqs':
... | def parse_url(url):
# type: (str) -> Dict
| """Parse URL into mapping of components."""
scheme, host, port, user, password, path, query = _parse_url(url)
if query:
keys = [key for key in query.keys() if key.startswith('ssl_')]
for key in keys:
if key == 'ssl_cert_reqs':
query[key] = parse_ssl_cert_reqs(quer... | (NamedTuple):
"""Named tuple representing parts of the URL."""
scheme: str
hostname: str
port: int
username: str
password: str
path: str
query: Mapping
def parse_url(url):
# type: (str) -> Dict
| 64 | 64 | 178 | 15 | 48 | kaiix/kombu | kombu/utils/url.py | Python | parse_url | parse_url | 33 | 53 | 33 | 34 | ff659ec1bbc3d8ec6ee967edc299165dc9709b77 | bigcode/the-stack | train |
7ac78a64bdf2829b83a73658 | train | class | @pulumi.input_type
class UserPosixProfileArgs:
def __init__(__self__, *,
gid: pulumi.Input[int],
uid: pulumi.Input[int],
secondary_gids: Optional[pulumi.Input[Sequence[pulumi.Input[int]]]] = None):
"""
:param pulumi.Input[int] gid: The POSIX group I... | @pulumi.input_type
class UserPosixProfileArgs:
| def __init__(__self__, *,
gid: pulumi.Input[int],
uid: pulumi.Input[int],
secondary_gids: Optional[pulumi.Input[Sequence[pulumi.Input[int]]]] = None):
"""
:param pulumi.Input[int] gid: The POSIX group ID used for all EFS operations by this user.
... | (self) -> pulumi.Input[str]:
"""
Represents an entry and a target.
"""
return pulumi.get(self, "entry")
@entry.setter
def entry(self, value: pulumi.Input[str]):
pulumi.set(self, "entry", value)
@property
@pulumi.getter
def target(self) -> pulumi.Input[str]:
... | 141 | 141 | 472 | 13 | 128 | alexbowers/pulumi-aws | sdk/python/pulumi_aws/transfer/_inputs.py | Python | UserPosixProfileArgs | UserPosixProfileArgs | 125 | 175 | 125 | 126 | bbc76753356bc6bd381a555c1c31b6db0d6d5c87 | bigcode/the-stack | train |
14e3c12c46dd1dbedf91e800 | train | class | @pulumi.input_type
class UserHomeDirectoryMappingArgs:
def __init__(__self__, *,
entry: pulumi.Input[str],
target: pulumi.Input[str]):
"""
:param pulumi.Input[str] entry: Represents an entry and a target.
:param pulumi.Input[str] target: Represents the map t... | @pulumi.input_type
class UserHomeDirectoryMappingArgs:
| def __init__(__self__, *,
entry: pulumi.Input[str],
target: pulumi.Input[str]):
"""
:param pulumi.Input[str] entry: Represents an entry and a target.
:param pulumi.Input[str] target: Represents the map target.
"""
pulumi.set(__self__, "entry"... | ` is set to `VPC`.
"""
return pulumi.get(self, "vpc_id")
@vpc_id.setter
def vpc_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "vpc_id", value)
@pulumi.input_type
class UserHomeDirectoryMappingArgs:
| 72 | 72 | 240 | 13 | 59 | alexbowers/pulumi-aws | sdk/python/pulumi_aws/transfer/_inputs.py | Python | UserHomeDirectoryMappingArgs | UserHomeDirectoryMappingArgs | 88 | 122 | 88 | 89 | e086b66af95403ee1d031ce1fae9ca0724f95a62 | bigcode/the-stack | train |
f527fd05e6b78d762a3d5b02 | train | class | @pulumi.input_type
class ServerEndpointDetailsArgs:
def __init__(__self__, *,
address_allocation_ids: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
subnet_ids: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
vpc_endpoint_id: Optional[pulum... | @pulumi.input_type
class ServerEndpointDetailsArgs:
| def __init__(__self__, *,
address_allocation_ids: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
subnet_ids: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
vpc_endpoint_id: Optional[pulumi.Input[str]] = None,
vpc_id: Optio... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | 120 | 256 | 932 | 12 | 108 | alexbowers/pulumi-aws | sdk/python/pulumi_aws/transfer/_inputs.py | Python | ServerEndpointDetailsArgs | ServerEndpointDetailsArgs | 17 | 85 | 17 | 18 | 61d4b4b4560a6e0450c253063565acc0f17bc847 | bigcode/the-stack | train |
b3b934d0ed0d7d035a38e713 | train | class | class OBB(object):
"""
:class:`OBB` Oriented Bounding Box Class.
Requires an input meshName.
"""
meshName = None
def __init__(self, meshName=None, method=0, selectedPoints=False):
if not meshName:
raise RuntimeError("No mesh set in class.")
self.shape... | class OBB(object):
| """
:class:`OBB` Oriented Bounding Box Class.
Requires an input meshName.
"""
meshName = None
def __init__(self, meshName=None, method=0, selectedPoints=False):
if not meshName:
raise RuntimeError("No mesh set in class.")
self.shapeName = self.getShape... | # -*- coding: utf-8 -*-
from OBB.utils import eigh
try:
from maya import cmds
from maya import OpenMaya
except ImportError:
pass
try:
from scipy.spatial import ConvexHull
hullMethod = True
except ImportError:
RuntimeWarning("Unable to load scipy."
"The from_hul... | 93 | 256 | 4,238 | 5 | 87 | rBrenick/OBB | OBB/api.py | Python | OBB | OBB | 19 | 581 | 19 | 19 | fb6756f53058dca9ecdedf2aec5117b3e3e951f0 | bigcode/the-stack | train |
959c409c031c93e65edff50c | train | function | def _generic_problem(http_status: HTTPStatus, exc: Exception = None):
extra = None
if exc is not None:
loop = asyncio.get_event_loop()
if loop.get_debug():
tb = None
with suppress(Exception):
tb = traceback.format_exc()
if tb:
e... | def _generic_problem(http_status: HTTPStatus, exc: Exception = None):
| extra = None
if exc is not None:
loop = asyncio.get_event_loop()
if loop.get_debug():
tb = None
with suppress(Exception):
tb = traceback.format_exc()
if tb:
extra = {"traceback": tb}
return problem(
status=http_stat... | exionRequest, ConnexionResponse
from connexion.problem import problem
from connexion.utils import yamldumper
from werkzeug.exceptions import HTTPException as werkzeug_HTTPException
logger = logging.getLogger('connexion.apis.aiohttp_api')
def _generic_problem(http_status: HTTPStatus, exc: Exception = None):
| 64 | 64 | 102 | 16 | 48 | Jiehong/connexion | connexion/apis/aiohttp_api.py | Python | _generic_problem | _generic_problem | 27 | 43 | 27 | 27 | 8c146f1ae1436b33b76588997e7fe30877a9a9a5 | bigcode/the-stack | train |
511ce5886efdfd9ba7f2d3df | train | class | class AioHttpApi(AbstractAPI):
def __init__(self, *args, **kwargs):
# NOTE we use HTTPPermanentRedirect (308) because
# clients sometimes turn POST requests into GET requests
# on 301, 302, or 303
# see https://tools.ietf.org/html/rfc7538
trailing_slash_redirect = normalize_p... | class AioHttpApi(AbstractAPI):
| def __init__(self, *args, **kwargs):
# NOTE we use HTTPPermanentRedirect (308) because
# clients sometimes turn POST requests into GET requests
# on 301, 302, or 303
# see https://tools.ietf.org/html/rfc7538
trailing_slash_redirect = normalize_path_middleware(
app... | exc.name, detail=exc.description)
except web.HTTPError as exc:
if exc.text == "{}: {}".format(exc.status, exc.reason):
detail = HTTPStatus(exc.status).description
else:
detail = exc.text
response = problem(status=exc.status, title=exc.reason, detail=detail)
except... | 256 | 256 | 2,160 | 8 | 247 | Jiehong/connexion | connexion/apis/aiohttp_api.py | Python | AioHttpApi | AioHttpApi | 81 | 380 | 81 | 81 | dcddc272131c35de4abbc502ebab861f00268f7e | bigcode/the-stack | train |
686cc85c7ab312f2a9fb072f | train | class | class _HttpNotFoundError(HTTPNotFound):
def __init__(self):
self.name = 'Not Found'
self.description = (
'The requested URL was not found on the server. '
'If you entered the URL manually please check your spelling and '
'try again.'
)
self.code = ... | class _HttpNotFoundError(HTTPNotFound):
| def __init__(self):
self.name = 'Not Found'
self.description = (
'The requested URL was not found on the server. '
'If you entered the URL manually please check your spelling and '
'try again.'
)
self.code = type(self).status_code
self.empt... | or serialized_mimetype
return web.Response(body=body, text=text, headers=headers, status=status_code, content_type=content_type)
@classmethod
def _set_jsonifier(cls):
cls.jsonifier = Jsonifier(cls=JSONEncoder)
class _HttpNotFoundError(HTTPNotFound):
| 64 | 64 | 95 | 11 | 53 | Jiehong/connexion | connexion/apis/aiohttp_api.py | Python | _HttpNotFoundError | _HttpNotFoundError | 383 | 394 | 383 | 383 | 557fd38d79c8baece5b2bacb9ad1536da40b45b7 | bigcode/the-stack | train |
35077e743eca1328d7c3ac89 | train | function | @web.middleware
async def problems_middleware(request, handler):
try:
response = await handler(request)
except ProblemException as exc:
response = problem(status=exc.status, detail=exc.detail, title=exc.title,
type=exc.type, instance=exc.instance, headers=exc.headers, ... | @web.middleware
async def problems_middleware(request, handler):
| try:
response = await handler(request)
except ProblemException as exc:
response = problem(status=exc.status, detail=exc.detail, title=exc.title,
type=exc.type, instance=exc.instance, headers=exc.headers, ext=exc.ext)
except (werkzeug_HTTPException, _HttpNotFoundErr... | Exception = None):
extra = None
if exc is not None:
loop = asyncio.get_event_loop()
if loop.get_debug():
tb = None
with suppress(Exception):
tb = traceback.format_exc()
if tb:
extra = {"traceback": tb}
return problem(
... | 103 | 103 | 346 | 13 | 90 | Jiehong/connexion | connexion/apis/aiohttp_api.py | Python | problems_middleware | problems_middleware | 46 | 78 | 46 | 47 | fe192ee5c95242a166ec2962a3b1210f12d5d0ea | bigcode/the-stack | train |
d9d3d8a221d1eb704bc8ff35 | train | class | class AddrReceiver(P2PInterface):
def __init__(self):
super().__init__()
self.received_addrs = None
def get_received_addrs(self):
with p2p_lock:
return self.received_addrs
def on_addr(self, message):
self.received_addrs = []
for addr in message.addrs:
... | class AddrReceiver(P2PInterface):
| def __init__(self):
super().__init__()
self.received_addrs = None
def get_received_addrs(self):
with p2p_lock:
return self.received_addrs
def on_addr(self, message):
self.received_addrs = []
for addr in message.addrs:
self.received_addrs.appe... | p2p_lock
)
from test_framework.test_framework import XUEZTestFramework
from test_framework.util import (
assert_equal,
)
# As defined in net_processing.
MAX_ADDR_TO_SEND = 1000
MAX_PCT_ADDR_TO_SEND = 23
class AddrReceiver(P2PInterface):
| 64 | 64 | 103 | 8 | 55 | ComputerCraftr/Xuez-Core | test/functional/p2p_getaddr_caching.py | Python | AddrReceiver | AddrReceiver | 23 | 39 | 23 | 24 | b1d5d24648d45cab77f203cd46c5ec4a966a96bb | bigcode/the-stack | train |
e04965b65db1723edc0fe8f5 | train | class | class AddrTest(XUEZTestFramework):
def set_test_params(self):
self.setup_clean_chain = False
self.num_nodes = 1
def run_test(self):
self.log.info('Fill peer AddrMan with a lot of records')
for i in range(10000):
first_octet = i >> 8
second_octet = i % 256... | class AddrTest(XUEZTestFramework):
| def set_test_params(self):
self.setup_clean_chain = False
self.num_nodes = 1
def run_test(self):
self.log.info('Fill peer AddrMan with a lot of records')
for i in range(10000):
first_octet = i >> 8
second_octet = i % 256
a = "{}.{}.1.1".format... | assert_equal,
)
# As defined in net_processing.
MAX_ADDR_TO_SEND = 1000
MAX_PCT_ADDR_TO_SEND = 23
class AddrReceiver(P2PInterface):
def __init__(self):
super().__init__()
self.received_addrs = None
def get_received_addrs(self):
with p2p_lock:
return self.received_addrs
... | 142 | 142 | 475 | 9 | 132 | ComputerCraftr/Xuez-Core | test/functional/p2p_getaddr_caching.py | Python | AddrTest | AddrTest | 42 | 86 | 42 | 42 | 01adf28618b79faefb6eec44e95e2d3a1be28bfe | bigcode/the-stack | train |
f974f3dfd68d6ff3884fe5b8 | train | function | def _fever_to_fever_symmetric_mapper(preds: Tensor) -> Tensor:
# "SUPPORTS", "NOT ENOUGH INFO", "REFUTES" => "SUPPORTS", "REFUTES", "NOT ENOUGH INFO"
preds[:, [1, 2]] = preds[:, [2, 1]]
return preds
| def _fever_to_fever_symmetric_mapper(preds: Tensor) -> Tensor:
# "SUPPORTS", "NOT ENOUGH INFO", "REFUTES" => "SUPPORTS", "REFUTES", "NOT ENOUGH INFO"
| preds[:, [1, 2]] = preds[:, [2, 1]]
return preds
|
mapper: Callable[[Any], Any] = None
def _fever_to_fever_symmetric_mapper(preds: Tensor) -> Tensor:
# "SUPPORTS", "NOT ENOUGH INFO", "REFUTES" => "SUPPORTS", "REFUTES", "NOT ENOUGH INFO"
| 64 | 64 | 73 | 51 | 12 | technion-cs-nlp/bias-probing | bias_probing/data/datasets.py | Python | _fever_to_fever_symmetric_mapper | _fever_to_fever_symmetric_mapper | 26 | 29 | 26 | 27 | 4697e0ae18255118d03529f793e936e7091538b1 | bigcode/the-stack | train |
d70b1e410e781eb1a3b2950d | train | class | @dataclass
class DatasetInfo:
dataset_config_file: str = None
eval_datasets: List[str] = field(default_factory=lambda: [])
ignored_keys: List[str] = field(default_factory=lambda: [])
sentence1_key: str = 'premise'
sentence2_key: str = 'hypothesis'
train_dataset_name: str = 'train'
dev_datase... | @dataclass
class DatasetInfo:
| dataset_config_file: str = None
eval_datasets: List[str] = field(default_factory=lambda: [])
ignored_keys: List[str] = field(default_factory=lambda: [])
sentence1_key: str = 'premise'
sentence2_key: str = 'hypothesis'
train_dataset_name: str = 'train'
dev_dataset_name: str = 'validation'
... | import os
from dataclasses import field, dataclass
from os.path import join
from typing import List, Tuple, Any, Callable
from datasets import load_dataset, DatasetDict
from torch import Tensor
_DIR = os.path.dirname(os.path.abspath(__file__))
@dataclass
class DatasetInfo:
| 61 | 64 | 118 | 7 | 54 | technion-cs-nlp/bias-probing | bias_probing/data/datasets.py | Python | DatasetInfo | DatasetInfo | 12 | 23 | 12 | 13 | 6bbeec586b362cd1756a93c637cbccbc05fbbb88 | bigcode/the-stack | train |
4671d614facc726c1ccb01bc | train | function | def load_dataset_aux(train_dataset_name: str) -> Tuple[DatasetDict, DatasetInfo]:
if train_dataset_name in DATASETS:
dataset_info: DatasetInfo = DATASETS[train_dataset_name]
train_dataset_name = os.path.abspath(join(_DIR, dataset_info.dataset_config_file)) \
if dataset_info.dataset_confi... | def load_dataset_aux(train_dataset_name: str) -> Tuple[DatasetDict, DatasetInfo]:
| if train_dataset_name in DATASETS:
dataset_info: DatasetInfo = DATASETS[train_dataset_name]
train_dataset_name = os.path.abspath(join(_DIR, dataset_info.dataset_config_file)) \
if dataset_info.dataset_config_file is not None else train_dataset_name
else:
dataset_info = Datase... | _file='multi_nli_hard.py',
test_dataset_name='test_mismatched'
),
'snli_hard': DatasetInfo(
dataset_config_file='snli_hard.py'
)
}
def load_dataset_aux(train_dataset_name: str) -> Tuple[DatasetDict, DatasetInfo]:
| 64 | 64 | 102 | 19 | 45 | technion-cs-nlp/bias-probing | bias_probing/data/datasets.py | Python | load_dataset_aux | load_dataset_aux | 79 | 87 | 79 | 79 | 8f8854ec38976b0678364e6712343963f97ac840 | bigcode/the-stack | train |
eaa4998659964f42358546f6 | train | function | def get_provenance(setup_py_content):
"""Provenance for a setup.py file is the index of the line that contains `install_requires`"""
for index, line in enumerate(setup_py_content.splitlines()):
if re.search(r"(packages|install_requires)\s*=", line):
return index + 1
return -1
| def get_provenance(setup_py_content):
| """Provenance for a setup.py file is the index of the line that contains `install_requires`"""
for index, line in enumerate(setup_py_content.splitlines()):
if re.search(r"(packages|install_requires)\s*=", line):
return index + 1
return -1
| return globals()["passed_arguments"]
def parse_name_and_version(setup_py_content):
"""Extract the name and version from a setup.py file"""
passed_arguments = parse(setup_py_content)
return passed_arguments.get("name"), passed_arguments.get("version")
def get_provenance(setup_py_content):
| 64 | 64 | 75 | 10 | 54 | hom669/TestCognox | node_modules/snyk-python-plugin/pysrc/setup_file.py | Python | get_provenance | get_provenance | 26 | 31 | 26 | 26 | 9f7f4bcce7a737895e6b8f3f079f7498fd97dc93 | bigcode/the-stack | train |
23ec1a8e6dbec6b4b27ba84e | train | function | def parse(setup_py_content):
"""Parse a setup.py file and extract the arguments passed to the setup method"""
# Make the setup method return the arguments that are passed to it
def _save_passed_args(**kwargs):
return kwargs
distutils.core.setup = _save_passed_args
setuptools.setup = _save_p... | def parse(setup_py_content):
| """Parse a setup.py file and extract the arguments passed to the setup method"""
# Make the setup method return the arguments that are passed to it
def _save_passed_args(**kwargs):
return kwargs
distutils.core.setup = _save_passed_args
setuptools.setup = _save_passed_args
setup_py_conte... | import distutils.core
import re
import setuptools
def parse(setup_py_content):
| 18 | 64 | 123 | 7 | 10 | hom669/TestCognox | node_modules/snyk-python-plugin/pysrc/setup_file.py | Python | parse | parse | 5 | 17 | 5 | 5 | 0bfa5266cc476aabec6a864dd6b4c4cf2c190d41 | bigcode/the-stack | train |
edaf625b4126e6ce775d76af | train | function | def parse_name_and_version(setup_py_content):
"""Extract the name and version from a setup.py file"""
passed_arguments = parse(setup_py_content)
return passed_arguments.get("name"), passed_arguments.get("version")
| def parse_name_and_version(setup_py_content):
| """Extract the name and version from a setup.py file"""
passed_arguments = parse(setup_py_content)
return passed_arguments.get("name"), passed_arguments.get("version")
| save_passed_args
setup_py_content = setup_py_content.replace("setup(", "passed_arguments = setup(")
# Fetch the arguments that were passed to the setup.py
exec(setup_py_content, globals())
return globals()["passed_arguments"]
def parse_name_and_version(setup_py_content):
| 63 | 64 | 47 | 10 | 53 | hom669/TestCognox | node_modules/snyk-python-plugin/pysrc/setup_file.py | Python | parse_name_and_version | parse_name_and_version | 20 | 23 | 20 | 20 | c81527c7690a2349a71d4ba44068a575e95021a4 | bigcode/the-stack | train |
d82c3800ed441bf60bf428eb | train | function | def parse_requirements(setup_py_content):
"""Extract the dependencies from a setup.py file"""
passed_arguments = parse(setup_py_content)
requirements = passed_arguments.get("install_requires", passed_arguments.get("packages", []))
return "\n".join(requirements)
| def parse_requirements(setup_py_content):
| """Extract the dependencies from a setup.py file"""
passed_arguments = parse(setup_py_content)
requirements = passed_arguments.get("install_requires", passed_arguments.get("packages", []))
return "\n".join(requirements)
| is the index of the line that contains `install_requires`"""
for index, line in enumerate(setup_py_content.splitlines()):
if re.search(r"(packages|install_requires)\s*=", line):
return index + 1
return -1
def parse_requirements(setup_py_content):
| 64 | 64 | 57 | 9 | 54 | hom669/TestCognox | node_modules/snyk-python-plugin/pysrc/setup_file.py | Python | parse_requirements | parse_requirements | 34 | 38 | 34 | 34 | a89d5abb4d4cd8078f727fb17da5d7ab3895e782 | bigcode/the-stack | train |
8e152d8317f12529f9d59293 | train | function | def encode_params(params_dict):
'''
Take the dictionary of params and encode keys and
values to ascii if it's unicode
'''
encoded = [(smart_str(k), smart_str(v)) for k, v in list(params_dict.items())]
encoded_dict = dict(encoded)
return encoded_dict
| def encode_params(params_dict):
| '''
Take the dictionary of params and encode keys and
values to ascii if it's unicode
'''
encoded = [(smart_str(k), smart_str(v)) for k, v in list(params_dict.items())]
encoded_dict = dict(encoded)
return encoded_dict
| import base64
padding_factor = (4 - len(inp) % 4) % 4
inp += "=" * padding_factor
return base64.b64decode(str(inp).translate(
dict(list(zip(list(map(ord, '-_')), '+/')))))
def encode_params(params_dict):
| 63 | 64 | 64 | 6 | 57 | abendleiter/Django-facebook | open_facebook/utils.py | Python | encode_params | encode_params | 67 | 74 | 67 | 67 | 1ac887548b5a38b73f0bdb22011932aca0416b08 | bigcode/the-stack | train |
45063f02805ac366d782638e | train | function | def merge_urls(generated_url, human_url):
'''
merge the generated_url with the human_url following this rules:
params introduced by generated_url are kept
final params order comes from generated_url
there's an hack to support things like this http://url?param¶m=value
>>> gen = "http://mysi... | def merge_urls(generated_url, human_url):
| '''
merge the generated_url with the human_url following this rules:
params introduced by generated_url are kept
final params order comes from generated_url
there's an hack to support things like this http://url?param¶m=value
>>> gen = "http://mysite.com?p1=a&p2=b&p3=c&p4=d"
>>> hum =... | (s, Exception):
# An Exception subclass containing non-ASCII data that doesn't
# know how to print itself properly. We shouldn't raise a
# further exception.
return ' '.join([smart_str(arg, encoding, strings_only,
... | 256 | 256 | 897 | 10 | 246 | abendleiter/Django-facebook | open_facebook/utils.py | Python | merge_urls | merge_urls | 129 | 185 | 129 | 129 | 0828eed4b0a6645d928569149cfa96cfc264ef1b | bigcode/the-stack | train |
52937d831140910387315d9a | train | function | def import_statsd():
'''
Import only the statd by wolph not the mozilla statsd
TODO: Move to mozilla statds which is more widely used
'''
try:
# check to see if the django_statsd we found
# supports start (stop) timing.
import django_statsd
is_wolphs_statsd = hasattr(... | def import_statsd():
| '''
Import only the statd by wolph not the mozilla statsd
TODO: Move to mozilla statds which is more widely used
'''
try:
# check to see if the django_statsd we found
# supports start (stop) timing.
import django_statsd
is_wolphs_statsd = hasattr(
django_s... | (__name__)
URL_PARAM_RE = re.compile('(?P<k>[^(=|&)]+)=(?P<v>[^&]+)(&|$)')
URL_PARAM_NO_VALUE_RE = re.compile('(?P<k>[^(&|?)]+)(&|$)')
def import_statsd():
| 63 | 64 | 134 | 5 | 59 | abendleiter/Django-facebook | open_facebook/utils.py | Python | import_statsd | import_statsd | 18 | 34 | 18 | 18 | a01453cb6adf23ef4b17bba89a65da035a9ece30 | bigcode/the-stack | train |
811d15c6a97116fdbb6ef85c | train | function | def stop_statsd(path):
if django_statsd:
django_statsd.stop(path)
| def stop_statsd(path):
| if django_statsd:
django_statsd.stop(path)
|
except ImportError:
django_statsd = None
return django_statsd
django_statsd = import_statsd()
def start_statsd(path):
'''
Simple wrapper to save some typing
'''
if django_statsd:
django_statsd.start(path)
def stop_statsd(path):
| 64 | 64 | 19 | 6 | 58 | abendleiter/Django-facebook | open_facebook/utils.py | Python | stop_statsd | stop_statsd | 47 | 49 | 47 | 47 | a5f312d57a8cb739cf17882015281627b8ded31b | bigcode/the-stack | train |
0b0dba0cedee8c0533005aa4 | train | function | def send_warning(message, request=None, e=None, **extra_data):
'''
Uses the logging system to send a message to logging and sentry
'''
username = None
if request and request.user.is_authenticated():
username = request.user.username
error_message = None
if e:
error_message = ... | def send_warning(message, request=None, e=None, **extra_data):
| '''
Uses the logging system to send a message to logging and sentry
'''
username = None
if request and request.user.is_authenticated():
username = request.user.username
error_message = None
if e:
error_message = str(e)
data = {
'username': username,
'bod... | isinstance(s, str):
return s.encode(encoding, errors)
elif s and encoding != 'utf-8':
return s.decode('utf-8', errors).encode(encoding, errors)
else:
return s
def send_warning(message, request=None, e=None, **extra_data):
| 64 | 64 | 125 | 15 | 48 | abendleiter/Django-facebook | open_facebook/utils.py | Python | send_warning | send_warning | 105 | 126 | 105 | 105 | 0cd694f4bc77d0938e5074ee36eec18193895386 | bigcode/the-stack | train |
eaf64ca634e8a2f0c445eee7 | train | function | def camel_to_underscore(name):
'''Convert camelcase style naming to underscore style naming
e.g. SpamEggs -> spam_eggs '''
import string
for c in string.ascii_uppercase:
name = name.replace(c, '_%c' % c)
return name.strip('_').lower()
| def camel_to_underscore(name):
| '''Convert camelcase style naming to underscore style naming
e.g. SpamEggs -> spam_eggs '''
import string
for c in string.ascii_uppercase:
name = name.replace(c, '_%c' % c)
return name.strip('_').lower()
| .func(*args)
def __repr__(self):
'''Return the function's docstring.'''
return self.func.__doc__
def __get__(self, obj, objtype):
'''Support instance methods.'''
return functools.partial(self.__call__, obj)
def camel_to_underscore(name):
| 64 | 64 | 68 | 7 | 57 | abendleiter/Django-facebook | open_facebook/utils.py | Python | camel_to_underscore | camel_to_underscore | 220 | 227 | 220 | 220 | a01d82d1e23eb94323d0dad62a9ebbdda192af73 | bigcode/the-stack | train |
1c589f25f305b6893f5082a9 | train | function | def start_statsd(path):
'''
Simple wrapper to save some typing
'''
if django_statsd:
django_statsd.start(path)
| def start_statsd(path):
| '''
Simple wrapper to save some typing
'''
if django_statsd:
django_statsd.start(path)
| d, 'start') and hasattr(django_statsd, 'stop')
if not is_wolphs_statsd:
django_statsd = None
except ImportError:
django_statsd = None
return django_statsd
django_statsd = import_statsd()
def start_statsd(path):
| 64 | 64 | 31 | 6 | 58 | abendleiter/Django-facebook | open_facebook/utils.py | Python | start_statsd | start_statsd | 39 | 44 | 39 | 39 | 4f08e06133d4607f7e224f54e0c70c4dd310531c | bigcode/the-stack | train |
8ae37304b5608c39382d3512 | train | function | def base64_url_decode_php_style(inp):
'''
PHP follows a slightly different protocol for base64 url decode.
For a full explanation see:
http://stackoverflow.com/questions/3302946/how-to-base64-url-decode-in-python
and
http://sunilarora.org/parsing-signedrequest-parameter-in-python-bas
'''
... | def base64_url_decode_php_style(inp):
| '''
PHP follows a slightly different protocol for base64 url decode.
For a full explanation see:
http://stackoverflow.com/questions/3302946/how-to-base64-url-decode-in-python
and
http://sunilarora.org/parsing-signedrequest-parameter-in-python-bas
'''
import base64
padding_factor = (4... | = import_statsd()
def start_statsd(path):
'''
Simple wrapper to save some typing
'''
if django_statsd:
django_statsd.start(path)
def stop_statsd(path):
if django_statsd:
django_statsd.stop(path)
def base64_url_decode_php_style(inp):
| 64 | 64 | 132 | 9 | 55 | abendleiter/Django-facebook | open_facebook/utils.py | Python | base64_url_decode_php_style | base64_url_decode_php_style | 52 | 64 | 52 | 52 | 7ff2b53de5a38ce71ed8db29f75a7adc07d002c3 | bigcode/the-stack | train |
de3a8e1eec973e617cd0e84c | train | function | def validate_is_instance(instance, classes):
'''
Usage
validate_is_instance(10, int)
validate_is_instance('a', (str, unicode))
'''
if not isinstance(classes, tuple):
classes = (classes,)
correct_instance = isinstance(instance, classes)
if not correct_instance:
raise Value... | def validate_is_instance(instance, classes):
| '''
Usage
validate_is_instance(10, int)
validate_is_instance('a', (str, unicode))
'''
if not isinstance(classes, tuple):
classes = (classes,)
correct_instance = isinstance(instance, classes)
if not correct_instance:
raise ValueError(
'Expected instance type %s... | style naming to underscore style naming
e.g. SpamEggs -> spam_eggs '''
import string
for c in string.ascii_uppercase:
name = name.replace(c, '_%c' % c)
return name.strip('_').lower()
def validate_is_instance(instance, classes):
| 64 | 64 | 88 | 8 | 56 | abendleiter/Django-facebook | open_facebook/utils.py | Python | validate_is_instance | validate_is_instance | 230 | 241 | 230 | 230 | 4fb005ba021548ba8d9f10c8cf9a6ef9b1631e24 | bigcode/the-stack | train |
e0ca916238778c6cd0a80067 | train | class | class memoized(object):
'''Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
'''
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
... | class memoized(object):
| '''Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
'''
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
try:
ret... | param)
# replace gen url params
for k, v in get_args(gen_args):
out_args.append('%s=%s' % (k, hum_dict.get(k, v)))
return '%s?%s' % (gen_path, '&'.join(out_args))
class memoized(object):
| 64 | 64 | 204 | 5 | 59 | abendleiter/Django-facebook | open_facebook/utils.py | Python | memoized | memoized | 188 | 217 | 188 | 189 | bbc21573fa891fb67bc780cd512a5f6931501b3b | bigcode/the-stack | train |
8fde29e43b3a193108a3075b | train | function | def is_json(content):
'''
Unfortunately facebook returns 500s which mean they are down
Or 500s with a nice error message because you use open graph wrong
So we have to figure out which is which :)
'''
try:
json.loads(content)
is_json = True
except:
is_json = False
... | def is_json(content):
| '''
Unfortunately facebook returns 500s which mean they are down
Or 500s with a nice error message because you use open graph wrong
So we have to figure out which is which :)
'''
try:
json.loads(content)
is_json = True
except:
is_json = False
return is_json
| str, unicode))
'''
if not isinstance(classes, tuple):
classes = (classes,)
correct_instance = isinstance(instance, classes)
if not correct_instance:
raise ValueError(
'Expected instance type %s found %s' % (classes, type(instance)))
def is_json(content):
| 63 | 64 | 78 | 5 | 58 | abendleiter/Django-facebook | open_facebook/utils.py | Python | is_json | is_json | 244 | 256 | 244 | 244 | 27df15f3c861ca3e2141723b9469cca25e0af643 | bigcode/the-stack | train |
7b4b5d01e94662de2dfd8c98 | train | function | def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Adapted from django, needed for urlencoding
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
import types
if strings... | def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
| """
Adapted from django, needed for urlencoding
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
import types
if strings_only and isinstance(s, (type(None), int)):
return s
elif not... | of params and encode keys and
values to ascii if it's unicode
'''
encoded = [(smart_str(k), smart_str(v)) for k, v in list(params_dict.items())]
encoded_dict = dict(encoded)
return encoded_dict
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
| 71 | 71 | 238 | 19 | 51 | abendleiter/Django-facebook | open_facebook/utils.py | Python | smart_str | smart_str | 77 | 102 | 77 | 77 | 19a8dc247a711eed6cf6d80757022ffd0232499b | bigcode/the-stack | train |
f525917c494f1a99c59d5b60 | train | class | class Migration(migrations.Migration):
dependencies = [
('visitors', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='visitor',
name='ip_addr',
field=models.CharField(max_length=40, verbose_name='IP address'),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('visitors', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='visitor',
name='ip_addr',
field=models.CharField(max_length=40, verbose_name='IP address'),
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 31 | 64 | 64 | 7 | 23 | jomoore/threepins | visitors/migrations/0002_auto_20160916_1437.py | Python | Migration | Migration | 7 | 19 | 7 | 8 | 6551a553c5ad6565fb89c4b0fca78536874b5507 | bigcode/the-stack | train |
1f8300b36829295a7e54ed52 | train | class | class PatternWildCardNode(PatternNode):
def __init__(self, wildcard):
PatternNode.__init__(self)
if wildcard not in self.matching_wildcards():
raise ParserException("%s not in valid wildcards %s" % (wildcard, ", ".join(self.matching_wildcards())))
self._wildcard = wildcard
... | class PatternWildCardNode(PatternNode):
| def __init__(self, wildcard):
PatternNode.__init__(self)
if wildcard not in self.matching_wildcards():
raise ParserException("%s not in valid wildcards %s" % (wildcard, ", ".join(self.matching_wildcards())))
self._wildcard = wildcard
def is_wildcard(self):
return Tru... | , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import logging
from programy.parser.exceptions import ParserException
from programy.parser.pattern.nodes.base import PatternNode
from programy.parser.pattern.nodes.root import PatternRootNode
class PatternWildCardNode(Patter... | 64 | 64 | 146 | 9 | 54 | hiitsme123/python | src/programy/parser/pattern/nodes/wildcard.py | Python | PatternWildCardNode | PatternWildCardNode | 24 | 44 | 24 | 25 | 7145bafe0a448947c0d6229d7d0cbf2dcbecc531 | bigcode/the-stack | train |
c878fb96f263ffd9c0cb0600 | train | class | class TestNext(unittest.TestCase):
"""Next unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testNext(self):
"""Test Next"""
# FIXME: construct object with mandatory attributes with example values
# model = yapily.models.next.Next() # noqa:... | class TestNext(unittest.TestCase):
| """Next unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testNext(self):
"""Test Next"""
# FIXME: construct object with mandatory attributes with example values
# model = yapily.models.next.Next() # noqa: E501
pass
| 0.155
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import yapily
from yapily.models.next import Next # noqa: E501
from yapily.rest import ApiException
class TestNext(unittest.TestCase):
| 64 | 64 | 77 | 7 | 56 | bs-yapily/yapily-sdk-python | sdk/test/test_next.py | Python | TestNext | TestNext | 23 | 36 | 23 | 23 | cddf445467ef57ed5637aecfa0358ae0a1fda0c9 | bigcode/the-stack | train |
94aaf1c5c1c5d00e8942746e | train | function | @app.route('/dcm_plugin/<topic>', methods=['DELETE'])
def delete_topic(topic):
"""
Delete Kafka topic.
---
describe: delete Kafka topic
parameters:
- in: path
name: topic
type: string
description: topic name
responses:
200:
description: successful resu... | @app.route('/dcm_plugin/<topic>', methods=['DELETE'])
def delete_topic(topic):
| """
Delete Kafka topic.
---
describe: delete Kafka topic
parameters:
- in: path
name: topic
type: string
description: topic name
responses:
200:
description: successful result
500:
description: error during the execution
"""
logge... | ', '--partitions', '1', '--topic', topic])
except Exception as e:
logger.error("Error executing command")
logger.exception(e)
return str(e), 500
return '', 200
@app.route('/dcm_plugin/<topic>', methods=['DELETE'])
def delete_topic(topic):
| 64 | 64 | 166 | 18 | 45 | sofianinho/5geve-wp3-dcm-site-plugin | dcm_site_plugin_rest_client.py | Python | delete_topic | delete_topic | 71 | 95 | 71 | 72 | db4a514ade3d49742fc7e9dad3f81bb7131f7a07 | bigcode/the-stack | train |
13a17224fde0d3f69a528063 | train | function | def checkValidPort(value):
ivalue = int(value)
# RFC 793
if ivalue < 0 or ivalue > 65535:
raise argparse.ArgumentTypeError("%s is not a valid port" % value)
return value
| def checkValidPort(value):
| ivalue = int(value)
# RFC 793
if ivalue < 0 or ivalue > 65535:
raise argparse.ArgumentTypeError("%s is not a valid port" % value)
return value
| ', kafka_topics_script_route, '--delete', '--bootstrap-server', site_ip_address+":9092", '--topic', topic])
except Exception as e:
logger.error("Error executing command")
logger.exception(e)
return str(e), 500
return '', 200
def checkValidPort(value):
| 64 | 64 | 55 | 6 | 57 | sofianinho/5geve-wp3-dcm-site-plugin | dcm_site_plugin_rest_client.py | Python | checkValidPort | checkValidPort | 97 | 102 | 97 | 97 | d504eef4d358dcd2e4012fb1f33319b4e2a17a3a | bigcode/the-stack | train |
9544e724dd07d4838e5bc5f2 | train | function | @app.route('/', methods=['GET'])
def server_status():
"""
Get status.
---
describe: get status
responses:
200:
description: OK
"""
logger.info("GET /")
return '', 200
| @app.route('/', methods=['GET'])
def server_status():
| """
Get status.
---
describe: get status
responses:
200:
description: OK
"""
logger.info("GET /")
return '', 200
| agger import swagger
from waitress import serve
import subprocess
from kafka import KafkaProducer
from kafka.errors import KafkaError
from kafka.future import log
import json
app = Flask(__name__)
logger = logging.getLogger("DCMSitePluginRestClient")
@app.route('/', methods=['GET'])
def server_status():
| 64 | 64 | 52 | 11 | 53 | sofianinho/5geve-wp3-dcm-site-plugin | dcm_site_plugin_rest_client.py | Python | server_status | server_status | 17 | 28 | 17 | 18 | 45ea13935a4363f683eb41c69b3380f5b11825a5 | bigcode/the-stack | train |
2f854f15d10e90565cb0967b | train | function | @app.route('/dcm_plugin/<topic>', methods=['POST'])
def create_topic(topic):
"""
Create Kafka topic.
---
describe: create Kafka topic
parameters:
- in: path
name: topic
type: string
description: topic name
responses:
200:
description: successful result... | @app.route('/dcm_plugin/<topic>', methods=['POST'])
def create_topic(topic):
| """
Create Kafka topic.
---
describe: create Kafka topic
parameters:
- in: path
name: topic
type: string
description: topic name
responses:
200:
description: successful result
500:
description: error during the execution
"""
logge... | swagger specification
"""
swag = swagger(app)
swag['info']['version'] = "1.0"
swag['info']['title'] = "DCM Site Plugin REST API"
return jsonify(swag)
@app.route('/dcm_plugin/<topic>', methods=['POST'])
def create_topic(topic):
| 64 | 64 | 181 | 18 | 46 | sofianinho/5geve-wp3-dcm-site-plugin | dcm_site_plugin_rest_client.py | Python | create_topic | create_topic | 45 | 69 | 45 | 46 | 78a36d197b2a0cf888ac380c41c3eb21b625a0a8 | bigcode/the-stack | train |
7f9197309fc7e521f2d12ae1 | train | function | @app.route("/spec", methods=['GET'])
def spec():
"""
Get swagger specification.
---
describe: get swagger specification
responses:
swagger:
description: swagger specification
"""
swag = swagger(app)
swag['info']['version'] = "1.0"
swag['info']['title'] = "DCM Site Plugi... | @app.route("/spec", methods=['GET'])
def spec():
| """
Get swagger specification.
---
describe: get swagger specification
responses:
swagger:
description: swagger specification
"""
swag = swagger(app)
swag['info']['version'] = "1.0"
swag['info']['title'] = "DCM Site Plugin REST API"
return jsonify(swag)
| @app.route('/', methods=['GET'])
def server_status():
"""
Get status.
---
describe: get status
responses:
200:
description: OK
"""
logger.info("GET /")
return '', 200
@app.route("/spec", methods=['GET'])
def spec():
| 64 | 64 | 83 | 12 | 51 | sofianinho/5geve-wp3-dcm-site-plugin | dcm_site_plugin_rest_client.py | Python | spec | spec | 30 | 43 | 30 | 31 | 4d3925d5b9d5539d8e0221254af867753db98d4f | bigcode/the-stack | train |
f9c6031a140ad3773cf97cc0 | train | function | @app.route('/<path:page>')
def fallback(page):
global config_flag
if 'ua' in page:
config_flag = 'ua'
return render_template('index-ukr.html')
if 'en' in page:
config_flag = 'en'
return render_template('index-eng.html')
| @app.route('/<path:page>')
def fallback(page):
| global config_flag
if 'ua' in page:
config_flag = 'ua'
return render_template('index-ukr.html')
if 'en' in page:
config_flag = 'en'
return render_template('index-eng.html')
| :
if word in keyed_vectors.vocab:
exists.append(word)
return exists
@app.route('/')
def index():
return Response(render_template('index-ukr.html'), mimetype='text/html')
# let's Angular do the routs job
@app.route('/<path:page>')
def fallback(page):
| 64 | 64 | 67 | 12 | 51 | malakhovks/vec2read | server/server.py | Python | fallback | fallback | 100 | 108 | 100 | 101 | c0a016de06e989ea6356be5826cbf48628b58f81 | bigcode/the-stack | train |
c16a7631542a2080aa70974c | train | function | @app.route('/api/word2vec/similarity', methods=['POST'])
def similarity():
if not request.json or not 'word_1' in request.json or not 'word_2' in request.json:
abort(400)
try:
if request.args.get('model', type = int):
cosine_similarity = models_array[request.args.get('model', type = ... | @app.route('/api/word2vec/similarity', methods=['POST'])
def similarity():
| if not request.json or not 'word_1' in request.json or not 'word_2' in request.json:
abort(400)
try:
if request.args.get('model', type = int):
cosine_similarity = models_array[request.args.get('model', type = int)].similarity(request.json['word_1'], request.json['word_2'])
el... | /models')
def get_models_list():
if config_flag == 'ua':
return jsonify(models)
if config_flag == 'en':
return jsonify(models_en)
# return jsonify(models)
# * computational endpoints
@app.route('/api/word2vec/similarity', methods=['POST'])
def similarity():
| 64 | 64 | 168 | 19 | 44 | malakhovks/vec2read | server/server.py | Python | similarity | similarity | 143 | 154 | 143 | 144 | 5f0d7ee78121d62f443444f5e0e3af5c05c641d3 | bigcode/the-stack | train |
8af19b31fd9271a59e7d6dc4 | train | function | @app.route('/')
def index():
return Response(render_template('index-ukr.html'), mimetype='text/html')
| @app.route('/')
def index():
| return Response(render_template('index-ukr.html'), mimetype='text/html')
| word_vectors_suhomlinskyy.init_sims(replace=True)
del model
"""
def getExistsWordsInModel(words, keyed_vectors):
exists = []
for word in words:
if word in keyed_vectors.vocab:
exists.append(word)
return exists
@app.route('/')
def index():
| 64 | 64 | 24 | 6 | 57 | malakhovks/vec2read | server/server.py | Python | index | index | 95 | 97 | 95 | 96 | 175a8d2e7aa44f6fe0800651c31815dddc505597 | bigcode/the-stack | train |
ffb941b1f491478ec25a989d | train | function | def getExistsWordsInModel(words, keyed_vectors):
exists = []
for word in words:
if word in keyed_vectors.vocab:
exists.append(word)
return exists
| def getExistsWordsInModel(words, keyed_vectors):
| exists = []
for word in words:
if word in keyed_vectors.vocab:
exists.append(word)
return exists
| ased.lemmatized.word2vec.500d')
# * switch to the KeyedVectors instance
word_vectors_suhomlinskyy = model.wv
word_vectors_suhomlinskyy.init_sims(replace=True)
del model
"""
def getExistsWordsInModel(words, keyed_vectors):
| 64 | 64 | 39 | 11 | 53 | malakhovks/vec2read | server/server.py | Python | getExistsWordsInModel | getExistsWordsInModel | 88 | 93 | 88 | 88 | f575180b9e434c795feca05ab48cfdc73e7fe378 | bigcode/the-stack | train |
e8cd2eca4c2e39e7b82e1c73 | train | function | @app.route('/assets/sources-logos/<path:path>')
def send_logos(path):
if request.args.get('lang') == 'ukr':
return send_from_directory('static/ukr/sources-logos', path)
if request.args.get('lang') == 'eng':
return send_from_directory('static/eng/sources-logos', path)
return send_from_directo... | @app.route('/assets/sources-logos/<path:path>')
def send_logos(path):
| if request.args.get('lang') == 'ukr':
return send_from_directory('static/ukr/sources-logos', path)
if request.args.get('lang') == 'eng':
return send_from_directory('static/eng/sources-logos', path)
return send_from_directory('static/ukr/sources-logos', path)
| if request.args.get('lang') == 'eng':
return send_from_directory('static/eng/img', path)
return send_from_directory('static/ukr/img', path)
# serve static images about-sources
@app.route('/assets/sources-logos/<path:path>')
def send_logos(path):
| 64 | 64 | 93 | 18 | 45 | malakhovks/vec2read | server/server.py | Python | send_logos | send_logos | 125 | 131 | 125 | 126 | 4522d0a4cccb1752af27a87b25710fff999de915 | bigcode/the-stack | train |
952f7ac268dfcf616b2ed85b | train | function | @app.route('/api/word2vec/center', methods=['POST'])
def find_lexical_cluster_center():
if not request.json or not 'words' in request.json:
abort(400)
n = 100
try:
if request.args.get('model', type = int):
cosine_center = models_array[request.args.get('model', type = int)].most_s... | @app.route('/api/word2vec/center', methods=['POST'])
def find_lexical_cluster_center():
| if not request.json or not 'words' in request.json:
abort(400)
n = 100
try:
if request.args.get('model', type = int):
cosine_center = models_array[request.args.get('model', type = int)].most_similar(positive=getExistsWordsInModel(request.json['words'], models_array[request.args.g... | return jsonify({"Error": {"KeyError": "Word " + request.json['word'] + " does not exist in the word2vec model" , "Word": request.json['word']}})
@app.route('/api/word2vec/center', methods=['POST'])
def find_lexical_cluster_center():
| 63 | 64 | 197 | 23 | 41 | malakhovks/vec2read | server/server.py | Python | find_lexical_cluster_center | find_lexical_cluster_center | 170 | 182 | 170 | 171 | e8aae717e882f25d703a34b840ba41fb82d8670f | bigcode/the-stack | train |
957751d395777f1fcabd9ad6 | train | function | @app.route('/api/models')
def get_models_list():
if config_flag == 'ua':
return jsonify(models)
if config_flag == 'en':
return jsonify(models_en)
| @app.route('/api/models')
def get_models_list():
| if config_flag == 'ua':
return jsonify(models)
if config_flag == 'en':
return jsonify(models_en)
| ', path)
if request.args.get('lang') == 'eng':
return send_from_directory('static/eng/sources-logos', path)
return send_from_directory('static/ukr/sources-logos', path)
# * models list
@app.route('/api/models')
def get_models_list():
| 64 | 64 | 38 | 11 | 52 | malakhovks/vec2read | server/server.py | Python | get_models_list | get_models_list | 134 | 139 | 134 | 135 | b8e03334b8e5f4b03db87c944890e8ed13c41b00 | bigcode/the-stack | train |
ea5d0734d7c20dcb0f084064 | train | function | @app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
| @app.route('/favicon.ico')
def favicon():
| return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
| if 'ua' in page:
config_flag = 'ua'
return render_template('index-ukr.html')
if 'en' in page:
config_flag = 'en'
return render_template('index-eng.html')
# special file handlers
@app.route('/favicon.ico')
def favicon():
| 64 | 64 | 36 | 9 | 54 | malakhovks/vec2read | server/server.py | Python | favicon | favicon | 111 | 113 | 111 | 112 | 7f3fceaf4b69d083868e2ccd46019cd9570bef05 | bigcode/the-stack | train |
c05a6f30ff7d44e32b42f71b | train | function | @app.route('/assets/img/<path:path>')
def send_img(path):
if request.args.get('lang') == 'ukr':
return send_from_directory('static/ukr/img', path)
if request.args.get('lang') == 'eng':
return send_from_directory('static/eng/img', path)
return send_from_directory('static/ukr/img', path)
| @app.route('/assets/img/<path:path>')
def send_img(path):
| if request.args.get('lang') == 'ukr':
return send_from_directory('static/ukr/img', path)
if request.args.get('lang') == 'eng':
return send_from_directory('static/eng/img', path)
return send_from_directory('static/ukr/img', path)
| # special file handlers
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
# serve static images about-developers
@app.route('/assets/img/<path:path>')
def send_img(path):
| 64 | 64 | 80 | 14 | 49 | malakhovks/vec2read | server/server.py | Python | send_img | send_img | 116 | 122 | 116 | 117 | 9207c068cf3734b2eadd1f3a9b7c363ac4986681 | bigcode/the-stack | train |
c98402e4b813ad6426d7d9a7 | train | function | @app.route('/api/word2vec/similar', methods=['POST'])
def find_similar():
if not request.json or not 'word' in request.json:
abort(400)
n = 100
try:
if request.args.get('model', type = int):
cosine_similar = models_array[request.args.get('model', type = int)].most_similar(request... | @app.route('/api/word2vec/similar', methods=['POST'])
def find_similar():
| if not request.json or not 'word' in request.json:
abort(400)
n = 100
try:
if request.args.get('model', type = int):
cosine_similar = models_array[request.args.get('model', type = int)].most_similar(request.json['word'], topn=n)
else:
cosine_similar = models_a... | '])
return jsonify({"similarity": cosine_similarity.item()})
except KeyError:
return jsonify({"Error": {"KeyError": "One of the words is missing in the word2vec model"}})
@app.route('/api/word2vec/similar', methods=['POST'])
def find_similar():
| 64 | 64 | 172 | 21 | 43 | malakhovks/vec2read | server/server.py | Python | find_similar | find_similar | 156 | 168 | 156 | 157 | 4be72261dc064c43527530b0810014c082f2263c | bigcode/the-stack | train |
3a15594793edafbb703478ea | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(auto_created=True, primar... | class Migration(migrations.Migration):
| initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_nam... | # Generated by Django 2.2.5 on 2019-09-22 02:47
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 51 | 64 | 118 | 7 | 43 | ulubulu1/django_blog | users/migrations/0001_initial.py | Python | Migration | Migration | 8 | 25 | 8 | 9 | fda363d2330a201bfde82da99e83db93a3fa3bae | bigcode/the-stack | train |
7ebec310f670b2b9cb015ab0 | train | function | def Localxpose():
if True:
if 'Android' in str(check_output(('uname', '-a'))) or 'arm' in str(check_output(('uname', '-a'))):
filename = 'loclx-linux-arm.zip'
else:
ostype = systemos().lower()
if architecture()[0] == '64bit':
filename = 'loclx-lin... | def Localxpose():
| if True:
if 'Android' in str(check_output(('uname', '-a'))) or 'arm' in str(check_output(('uname', '-a'))):
filename = 'loclx-linux-arm.zip'
else:
ostype = systemos().lower()
if architecture()[0] == '64bit':
filename = 'loclx-linux-amd64.zip'.forma... | = 'https://bin.equinox.io/c/4VmDzA7iaHb/' + filename
download(url)
os.system('unzip ' + filename)
os.system('rm -Rf ' + filename)
os.system('clear')
#LOCALXPOSE
def Localxpose():
| 64 | 64 | 174 | 6 | 57 | Zusyaku/Termux-And-Lali-Linux-V2 | Recreator-Phishing-master/ServerInstall.py | Python | Localxpose | Localxpose | 25 | 40 | 25 | 25 | d960c3d3fff2a31934096e1221749b6eb79e33af | bigcode/the-stack | train |
696ed091ca4bfc0a8c97e49e | train | function | def Ngrok():
if True:
if 'Android' in str(check_output(('uname', '-a'))) or 'arm' in str(check_output(('uname', '-a'))):
filename = 'ngrok-stable-linux-arm.zip'
else:
ostype = systemos().lower()
if architecture()[0] == '64bit':
filename = 'ngrok-st... | def Ngrok():
| if True:
if 'Android' in str(check_output(('uname', '-a'))) or 'arm' in str(check_output(('uname', '-a'))):
filename = 'ngrok-stable-linux-arm.zip'
else:
ostype = systemos().lower()
if architecture()[0] == '64bit':
filename = 'ngrok-stable-{0}-amd6... |
from subprocess import check_output
import os
from platform import system as systemos, architecture
from wget import download
# NGROK
def Ngrok():
| 34 | 64 | 170 | 4 | 29 | Zusyaku/Termux-And-Lali-Linux-V2 | Recreator-Phishing-master/ServerInstall.py | Python | Ngrok | Ngrok | 8 | 22 | 8 | 8 | a124b076627dd55858985f972733d0de4ec5e60d | bigcode/the-stack | train |
728bb848fb75d5010f33a1a9 | train | class | class LibvirtScalityVolumeDriver(fs.LibvirtBaseFileSystemVolumeDriver):
"""Scality SOFS Nova driver. Provide hypervisors with access
to sparse files on SOFS.
"""
def _get_mount_point_base(self):
return CONF.libvirt.scality_sofs_mount_point
def _get_device_path(self, connection_info):
... | class LibvirtScalityVolumeDriver(fs.LibvirtBaseFileSystemVolumeDriver):
| """Scality SOFS Nova driver. Provide hypervisors with access
to sparse files on SOFS.
"""
def _get_mount_point_base(self):
return CONF.libvirt.scality_sofs_mount_point
def _get_device_path(self, connection_info):
"""Returns the hashed path to the device.
:param connection_... | the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for ... | 256 | 256 | 868 | 16 | 240 | nelsnelson/nova | nova/virt/libvirt/volume/scality.py | Python | LibvirtScalityVolumeDriver | LibvirtScalityVolumeDriver | 40 | 145 | 40 | 40 | f4b132978fddf97a59be8700ca8cbddc824e08f5 | bigcode/the-stack | train |
62b3a75c8516eea3f54c76da | train | function | def getSerialOrNone(portname):
try:
return serial.Serial(port=portname,
baudrate=115200,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS)
except:
return None
| def getSerialOrNone(portname):
| try:
return serial.Serial(port=portname,
baudrate=115200,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS)
except:
return None
| v > maxV):
v = maxV
b = (v - minV) / float(maxV - minV)
return (b)
controllerId = -1
serialSteps = 0
serialStepsUntilCheckVREvents = 3
def getSerialOrNone(portname):
| 64 | 64 | 64 | 8 | 55 | felipeek/bullet3 | examples/pybullet/examples/vrhand_vive_tracker.py | Python | getSerialOrNone | getSerialOrNone | 110 | 118 | 110 | 110 | b8c2acc6e6f07888dcffd3105d285e33614a4409 | bigcode/the-stack | train |
a3371f0dd7e6c1b1f5d0dd90 | train | function | def convertSensor(x):
v = minV
try:
v = float(x)
except ValueError:
v = minV
if (v < minV):
v = minV
if (v > maxV):
v = maxV
b = (v - minV) / float(maxV - minV)
return (b)
| def convertSensor(x):
| v = minV
try:
v = float(x)
except ValueError:
v = minV
if (v < minV):
v = minV
if (v > maxV):
v = maxV
b = (v - minV) / float(maxV - minV)
return (b)
| amp in range 400-600
#minV = 400
#maxV = 600
minV = 250
maxV = 450
POSITION = 1
ORIENTATION = 2
BUTTONS = 6
p.setRealTimeSimulation(1)
def convertSensor(x):
| 64 | 64 | 81 | 5 | 59 | felipeek/bullet3 | examples/pybullet/examples/vrhand_vive_tracker.py | Python | convertSensor | convertSensor | 90 | 101 | 90 | 90 | e1af906fea92b2d07c8aefc6b677990eff69844e | bigcode/the-stack | train |
36f204fef3b0eb417458ebaf | train | class | class AlertaHexgis(models.Model):
id = models.CharField(primary_key=True, max_length=-1)
geom = models.MultiPolygonField(srid=4674, blank=True, null=True)
img_n_ex = models.CharField(max_length=40, blank=True, null=True)
img_n_data = models.DateField(blank=True, null=True)
img_ex = models.CharField(... | class AlertaHexgis(models.Model):
| id = models.CharField(primary_key=True, max_length=-1)
geom = models.MultiPolygonField(srid=4674, blank=True, null=True)
img_n_ex = models.CharField(max_length=40, blank=True, null=True)
img_n_data = models.DateField(blank=True, null=True)
img_ex = models.CharField(max_length=40, blank=True, null=Tr... | has one field with primary_key=True
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
#
# Also note: You'll have to insert the output of 'django-admin sqlcustom [app_label]'
# into ... | 109 | 109 | 366 | 8 | 100 | ibamacsr/painelmma_api | painelmma_api/models.py | Python | AlertaHexgis | AlertaHexgis | 17 | 54 | 17 | 17 | 721c993d3bf2e12e09b1fd8413a28959640b40e7 | bigcode/the-stack | train |
2bbd5b50ef7a6752a1c202b1 | train | class | class HeaderOnlyLibTestClient(TestClient):
header = """
#include <iostream>
void hello() {{
std::cout << "Hello {build_type}!" << std::endl;
std::cout << " - options.shared: {shared}" << std::endl;
}}
"""
conanfile = """
import os
from conans import Cona... | class HeaderOnlyLibTestClient(TestClient):
| header = """
#include <iostream>
void hello() {{
std::cout << "Hello {build_type}!" << std::endl;
std::cout << " - options.shared: {shared}" << std::endl;
}}
"""
conanfile = """
import os
from conans import ConanFile, tools
class Pkg(ConanFile):
nam... | # coding=utf-8
import itertools
import os
import tempfile
import unittest
from parameterized import parameterized
from conans.model.editable_layout import DEFAULT_LAYOUT_FILE, LAYOUTS_FOLDER
from conans.test import CONAN_TEST_FOLDER
from conans.test.utils.tools import TestClient
from conans.util.files import save
cl... | 79 | 143 | 479 | 9 | 69 | uilianries/conan-freeglut | conan/conans/test/functional/editable/consume_settings_and_options_test.py | Python | HeaderOnlyLibTestClient | HeaderOnlyLibTestClient | 16 | 77 | 16 | 16 | e10c195cbd076f8da8d9948f8f3babc6da37d589 | bigcode/the-stack | train |
146f04d9b6d96d36832d46fd | train | class | class SettingsAndOptionsTest(unittest.TestCase):
@parameterized.expand(itertools.product(["Debug", "Release", ], # build_type
[True, False, ], # shared
[True, False, ])) # use_repo_file
def test_settings_options(self, bu... | class SettingsAndOptionsTest(unittest.TestCase):
@parameterized.expand(itertools.product(["Debug", "Release", ], # build_type
[True, False, ], # shared
[True, False, ])) # use_repo_file
| def test_settings_options(self, build_type, shared, use_repo_file):
# We need two clients sharing the same Conan cache
base_folder = tempfile.mkdtemp(suffix='conans', dir=CONAN_TEST_FOLDER)
# Editable project
client_editable = HeaderOnlyLibTestClient(use_repo_file=use_repo_file,
... | Release",
shared="True"),
"src/include/Release/False/hello.hpp": self.header.format(build_type="Release",
shared="False"),
}
if ... | 163 | 163 | 544 | 54 | 109 | uilianries/conan-freeglut | conan/conans/test/functional/editable/consume_settings_and_options_test.py | Python | SettingsAndOptionsTest | SettingsAndOptionsTest | 80 | 147 | 80 | 84 | 1b46bc72a29a5b3f4663471eec705ee708a71eb9 | bigcode/the-stack | train |
89fe01fa6c3e0ccd6ee436dd | train | class | class CUHK03(object):
"""
CUHK03
Reference:
Li et al. DeepReID: Deep Filter Pairing Neural Network for Person Re-identification. CVPR 2014.
URL: http://www.ee.cuhk.edu.hk/~xgwang/CUHK_identification.html#!
Dataset statistics:
# identities: 1360
# images: 13164
# ca... | class CUHK03(object):
| """
CUHK03
Reference:
Li et al. DeepReID: Deep Filter Pairing Neural Network for Person Re-identification. CVPR 2014.
URL: http://www.ee.cuhk.edu.hk/~xgwang/CUHK_identification.html#!
Dataset statistics:
# identities: 1360
# images: 13164
# cameras: 6
# splits:... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import glob
import re
import sys
import urllib
import tarfile
import zipfile
import os.path as osp
from scipy.io import loadmat
import numpy as np
import h5py
from scipy.misc import ims... | 103 | 256 | 3,074 | 6 | 96 | Joxis/Relation-Aware-Global-Attention-Networks | reid/data_manager/cuhk03.py | Python | CUHK03 | CUHK03 | 22 | 283 | 22 | 22 | dfaad56fecbb5169d64ca13449904ed43b4a1002 | bigcode/the-stack | train |
37c2239c3df7b7f1501e53b1 | train | class | class IntNBitTableBatchedEmbeddingBagsCodegen(nn.Module):
"""
Table-batched version of nn.EmbeddingBag(sparse=False)
Inference version, with FP16/INT8/INT4 supports
"""
def __init__(
self,
embedding_specs: List[
Tuple[str, int, int, SparseType, EmbeddingLocation]
... | class IntNBitTableBatchedEmbeddingBagsCodegen(nn.Module):
| """
Table-batched version of nn.EmbeddingBag(sparse=False)
Inference version, with FP16/INT8/INT4 supports
"""
def __init__(
self,
embedding_specs: List[
Tuple[str, int, int, SparseType, EmbeddingLocation]
], # tuple of (feature_names, rows, dims, SparseType, Em... | (a, 128)
embedding_dim = rounded_row_size_in_bytes(embedding_dim, weight_ty)
state_size = align_to_cacheline(num_embeddings * embedding_dim)
if location == EmbeddingLocation.HOST:
placements.append(EmbeddingLocation.HOST)
offsets.append(host_size)
host_size +... | 256 | 256 | 3,509 | 15 | 241 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | IntNBitTableBatchedEmbeddingBagsCodegen | IntNBitTableBatchedEmbeddingBagsCodegen | 1,531 | 1,966 | 1,531 | 1,531 | eb07f3acaceb8cc5fbbb7b078214bc9c793ecd89 | bigcode/the-stack | train |
aa22f8603b8e84a8f3b327c3 | train | function | def construct_split_state(
embedding_specs: List[Tuple[int, int, EmbeddingLocation, ComputeDevice]],
rowwise: bool,
cacheable: bool,
precision: SparseType = SparseType.FP32,
int8_emb_row_dim_offset: int = INT8_EMB_ROW_DIM_OFFSET,
) -> SplitState:
placements = []
offsets = []
dev_size = 0... | def construct_split_state(
embedding_specs: List[Tuple[int, int, EmbeddingLocation, ComputeDevice]],
rowwise: bool,
cacheable: bool,
precision: SparseType = SparseType.FP32,
int8_emb_row_dim_offset: int = INT8_EMB_ROW_DIM_OFFSET,
) -> SplitState:
| placements = []
offsets = []
dev_size = 0
host_size = 0
uvm_size = 0
for (num_embeddings, embedding_dim, location, _) in embedding_specs:
assert embedding_dim % 4 == 0, f"{embedding_dim}"
if precision == SparseType.INT8:
embedding_dim += int8_emb_row_dim_offset
... | _cache_miss", bool)],
)
@dataclass
class SplitState:
dev_size: int
host_size: int
uvm_size: int
placements: List[EmbeddingLocation]
offsets: List[int]
def construct_split_state(
embedding_specs: List[Tuple[int, int, EmbeddingLocation, ComputeDevice]],
rowwise: bool,
cacheable: bool,
... | 117 | 117 | 391 | 70 | 47 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | construct_split_state | construct_split_state | 83 | 124 | 83 | 89 | 853806b3bf75cb427447d325408e72d202e976fe | bigcode/the-stack | train |
f12860f0892cd877cb07f2db | train | function | def intn_construct_split_state(
embedding_specs: List[Tuple[str, int, int, SparseType, EmbeddingLocation]],
cacheable: bool,
) -> SplitState:
placements = []
offsets = []
dev_size = 0
host_size = 0
uvm_size = 0
for (_, num_embeddings, embedding_dim, weight_ty, location) in embedding_spec... | def intn_construct_split_state(
embedding_specs: List[Tuple[str, int, int, SparseType, EmbeddingLocation]],
cacheable: bool,
) -> SplitState:
| placements = []
offsets = []
dev_size = 0
host_size = 0
uvm_size = 0
for (_, num_embeddings, embedding_dim, weight_ty, location) in embedding_specs:
def align_to_cacheline(a: int) -> int:
# align each table to 128b cache line boundary.
return round_up(a, 128)
... | 4,
SparseType.FP16.value: dim * 2,
SparseType.INT8.value: dim + 4,
SparseType.INT4.value: dim // 2 + 4,
SparseType.INT2.value: dim // 4 + 4,
}[weight_ty.value]
return r
def intn_construct_split_state(
embedding_specs: List[Tuple[str, int, int, SparseType, EmbeddingLocation]]... | 107 | 107 | 357 | 38 | 68 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | intn_construct_split_state | intn_construct_split_state | 1,486 | 1,528 | 1,486 | 1,489 | 0cc122e9055a26862207e68fd8782a02b91101eb | bigcode/the-stack | train |
aad93af0813802c86fd8c27d | train | class | @dataclass
class CacheState:
# T + 1 elements and cache_hash_size_cumsum[-1] == total_cache_hash_size
cache_hash_size_cumsum: List[int]
cache_index_table_map: List[int]
total_cache_hash_size: int
| @dataclass
class CacheState:
# T + 1 elements and cache_hash_size_cumsum[-1] == total_cache_hash_size
| cache_hash_size_cumsum: List[int]
cache_index_table_map: List[int]
total_cache_hash_size: int
| dev_size=dev_size,
host_size=host_size,
uvm_size=uvm_size,
placements=placements,
offsets=offsets,
)
@dataclass
class CacheState:
# T + 1 elements and cache_hash_size_cumsum[-1] == total_cache_hash_size
| 64 | 64 | 56 | 29 | 35 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | CacheState | CacheState | 127 | 132 | 127 | 129 | 389b015055aa450210a097c44eb2a866e0113053 | bigcode/the-stack | train |
485d257542952994a4e14dee | train | class | class CacheAlgorithm(enum.Enum):
LRU = 0
LFU = 1
| class CacheAlgorithm(enum.Enum):
| LRU = 0
LFU = 1
| pass
class EmbeddingLocation(enum.IntEnum):
DEVICE = 0
MANAGED = 1
MANAGED_CACHING = 2
HOST = 3
class ComputeDevice(enum.IntEnum):
CPU = 0
CUDA = 1
class CacheAlgorithm(enum.Enum):
| 64 | 64 | 20 | 6 | 57 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | CacheAlgorithm | CacheAlgorithm | 46 | 48 | 46 | 46 | 4e98387a831e8a2a5d79bf0c9f52d41439e21f61 | bigcode/the-stack | train |
6fd103775d528e0166c316bc | train | class | class BoundsCheckMode(enum.IntEnum):
# Raise an exception (CPU) or device-side assert (CUDA)
FATAL = 0
# Log the first out-of-bounds instance per kernel, and set to zero.
WARNING = 1
# Set to zero.
IGNORE = 2
# No bounds checks.
NONE = 3
| class BoundsCheckMode(enum.IntEnum):
# Raise an exception (CPU) or device-side assert (CUDA)
| FATAL = 0
# Log the first out-of-bounds instance per kernel, and set to zero.
WARNING = 1
# Set to zero.
IGNORE = 2
# No bounds checks.
NONE = 3
| LRU = 0
LFU = 1
class PoolingMode(enum.IntEnum):
SUM = 0
MEAN = 1
NONE = 2
class BoundsCheckMode(enum.IntEnum):
# Raise an exception (CPU) or device-side assert (CUDA)
| 64 | 64 | 79 | 23 | 40 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | BoundsCheckMode | BoundsCheckMode | 57 | 65 | 57 | 58 | 1b3e1fadf4a7af5b5c5cac389f4b4da41621e785 | bigcode/the-stack | train |
6333756e0e59c666aaf0b548 | train | class | @dataclass
class SplitState:
dev_size: int
host_size: int
uvm_size: int
placements: List[EmbeddingLocation]
offsets: List[int]
| @dataclass
class SplitState:
| dev_size: int
host_size: int
uvm_size: int
placements: List[EmbeddingLocation]
offsets: List[int]
| IGNORE = 2
# No bounds checks.
NONE = 3
RecordCacheMetrics: NamedTuple = NamedTuple(
"RecordCacheMetrics",
[("record_cache_miss_counter", bool), ("record_tablewise_cache_miss", bool)],
)
@dataclass
class SplitState:
| 64 | 64 | 40 | 7 | 57 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | SplitState | SplitState | 74 | 80 | 74 | 75 | 98d10ccfddf42f6042e44d8de1ee6fe5110e3710 | bigcode/the-stack | train |
8c90956746a1170b31edae25 | train | function | def construct_cache_state(
embedding_specs: List[Tuple[int, int, EmbeddingLocation, ComputeDevice]],
feature_table_map: List[int],
) -> CacheState:
_cache_hash_size_cumsum = [0]
total_cache_hash_size = 0
for (num_embeddings, _, location, _) in embedding_specs:
if location == EmbeddingLocatio... | def construct_cache_state(
embedding_specs: List[Tuple[int, int, EmbeddingLocation, ComputeDevice]],
feature_table_map: List[int],
) -> CacheState:
| _cache_hash_size_cumsum = [0]
total_cache_hash_size = 0
for (num_embeddings, _, location, _) in embedding_specs:
if location == EmbeddingLocation.MANAGED_CACHING:
total_cache_hash_size += num_embeddings
_cache_hash_size_cumsum.append(total_cache_hash_size)
# [T], -1: non-cach... | ,
)
@dataclass
class CacheState:
# T + 1 elements and cache_hash_size_cumsum[-1] == total_cache_hash_size
cache_hash_size_cumsum: List[int]
cache_index_table_map: List[int]
total_cache_hash_size: int
def construct_cache_state(
embedding_specs: List[Tuple[int, int, EmbeddingLocation, ComputeDev... | 95 | 95 | 319 | 36 | 58 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | construct_cache_state | construct_cache_state | 135 | 163 | 135 | 138 | 00d566507e5721bbda2888da9c2a14930bda9a72 | bigcode/the-stack | train |
d094c8ed211bcac9fab26db5 | train | class | class SplitTableBatchedEmbeddingBagsCodegen(nn.Module):
"""
Multiple sparse features can share one embedding table.
'feature_table_map' specifies the feature-table mapping.
T: number of logical tables
T_: number of physical tables
T >= T_
"""
embedding_specs: List[Tuple[int, int, Embed... | class SplitTableBatchedEmbeddingBagsCodegen(nn.Module):
| """
Multiple sparse features can share one embedding table.
'feature_table_map' specifies the feature-table mapping.
T: number of logical tables
T_: number of physical tables
T >= T_
"""
embedding_specs: List[Tuple[int, int, EmbeddingLocation, ComputeDevice]]
optimizer_args: invoke... | Location.MANAGED_CACHING:
total_cache_hash_size += num_embeddings
_cache_hash_size_cumsum.append(total_cache_hash_size)
# [T], -1: non-cached table
cache_hash_size_cumsum = []
# [total_cache_hash_size], linear cache index -> table index
cache_index_table_map = [-1] * total_cache_hash... | 256 | 256 | 9,061 | 13 | 242 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | SplitTableBatchedEmbeddingBagsCodegen | SplitTableBatchedEmbeddingBagsCodegen | 166 | 1,243 | 166 | 166 | f7ee1632f7ae6cb3481ddde4a78946b28885ad9f | bigcode/the-stack | train |
02984f44bebcd1a0250d8e9c | train | class | class SequenceEmbeddingCodegen(SplitTableBatchedEmbeddingBagsCodegen):
"""
This class wraps around SplitTableBatchedEmbeddingBagsCodegen to get
sequence embedding op: nn.EmbeddingBag(sparse=True)
"""
def __init__(
self,
**kwargs: Any,
) -> None:
# assert T == 1
a... | class SequenceEmbeddingCodegen(SplitTableBatchedEmbeddingBagsCodegen):
| """
This class wraps around SplitTableBatchedEmbeddingBagsCodegen to get
sequence embedding op: nn.EmbeddingBag(sparse=True)
"""
def __init__(
self,
**kwargs: Any,
) -> None:
# assert T == 1
assert "embedding_specs" in kwargs
assert len(kwargs["embedding_... | (rows, dim)
)
return splits
def init_embedding_weights_uniform(self, min_val: float, max_val: float) -> None:
splits = self.split_embedding_weights()
for param in splits:
param.uniform_(min_val, max_val)
class SequenceEmbeddingCodegen(SplitTableBatchedEmbeddingBagsCo... | 71 | 71 | 239 | 16 | 55 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | SequenceEmbeddingCodegen | SequenceEmbeddingCodegen | 1,387 | 1,423 | 1,387 | 1,387 | 21aff62085dec80165bb8bad8f80cb67d838a522 | bigcode/the-stack | train |
df14ed09b958cd1f59a1934f | train | function | def rounded_row_size_in_bytes(dim: int, weight_ty: SparseType) -> int:
r = unpadded_row_size_in_bytes(dim, weight_ty)
# align each row to 16-byte boundaries.
return round_up(r, 16)
| def rounded_row_size_in_bytes(dim: int, weight_ty: SparseType) -> int:
| r = unpadded_row_size_in_bytes(dim, weight_ty)
# align each row to 16-byte boundaries.
return round_up(r, 16)
| offsets,
per_sample_weights,
feature_requires_grad,
)
def round_up(a: int, b: int) -> int:
return int((a + b - 1) // b) * b
def rounded_row_size_in_bytes(dim: int, weight_ty: SparseType) -> int:
| 64 | 64 | 54 | 19 | 44 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | rounded_row_size_in_bytes | rounded_row_size_in_bytes | 1,469 | 1,472 | 1,469 | 1,469 | 9dc6b2456a36179140e22f4c423bf73eba4bbcd1 | bigcode/the-stack | train |
b7fc7eaf25f71829d4e48c71 | train | class | class EmbeddingLocation(enum.IntEnum):
DEVICE = 0
MANAGED = 1
MANAGED_CACHING = 2
HOST = 3
| class EmbeddingLocation(enum.IntEnum):
| DEVICE = 0
MANAGED = 1
MANAGED_CACHING = 2
HOST = 3
|
ASSOC = 32
# Maximum number of times prefetch() can be called without
# a corresponding forward() call
MAX_PREFETCH_DEPTH = 100
INT8_EMB_ROW_DIM_OFFSET = 8
class DoesNotHavePrefix(Exception):
pass
class EmbeddingLocation(enum.IntEnum):
| 64 | 64 | 37 | 8 | 55 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | EmbeddingLocation | EmbeddingLocation | 34 | 38 | 34 | 34 | 02f4672cfae815ac739f9e34ff2a159c1ccfd551 | bigcode/the-stack | train |
b67351c78f5a358a929ca9a1 | train | class | class DenseSequenceEmbeddingCodegen(DenseTableBatchedEmbeddingBagsCodegen):
"""
This class wraps around DenseTableBatchedEmbeddingBagsCodegen to get
sequence embedding op, nn.EmbeddingBag(sparse=False)
"""
def __init__(
self,
**kwargs: Any,
) -> None:
# assert T == 1
... | class DenseSequenceEmbeddingCodegen(DenseTableBatchedEmbeddingBagsCodegen):
| """
This class wraps around DenseTableBatchedEmbeddingBagsCodegen to get
sequence embedding op, nn.EmbeddingBag(sparse=False)
"""
def __init__(
self,
**kwargs: Any,
) -> None:
# assert T == 1
assert "embedding_specs" in kwargs
assert len(kwargs["embedding... | ,
indices.numel() + 1,
device=indices.device,
dtype=torch.int64,
)
return super(SequenceEmbeddingCodegen, self).forward(
indices,
offsets,
per_sample_weights,
feature_requires_grad,
)
class DenseSequenceEmbedding... | 71 | 71 | 239 | 16 | 55 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | DenseSequenceEmbeddingCodegen | DenseSequenceEmbeddingCodegen | 1,426 | 1,462 | 1,426 | 1,426 | 6f3a42e44e85d9c5eaa9966639e97bb56ee55e0a | bigcode/the-stack | train |
47a458203bfb7dcb7e937fcb | train | function | def unpadded_row_size_in_bytes(dim: int, weight_ty: SparseType) -> int:
r = {
SparseType.FP32.value: dim * 4,
SparseType.FP16.value: dim * 2,
SparseType.INT8.value: dim + 4,
SparseType.INT4.value: dim // 2 + 4,
SparseType.INT2.value: dim // 4 + 4,
}[weight_ty.value]
r... | def unpadded_row_size_in_bytes(dim: int, weight_ty: SparseType) -> int:
| r = {
SparseType.FP32.value: dim * 4,
SparseType.FP16.value: dim * 2,
SparseType.INT8.value: dim + 4,
SparseType.INT4.value: dim // 2 + 4,
SparseType.INT2.value: dim // 4 + 4,
}[weight_ty.value]
return r
| _ty: SparseType) -> int:
r = unpadded_row_size_in_bytes(dim, weight_ty)
# align each row to 16-byte boundaries.
return round_up(r, 16)
def unpadded_row_size_in_bytes(dim: int, weight_ty: SparseType) -> int:
| 64 | 64 | 104 | 21 | 43 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | unpadded_row_size_in_bytes | unpadded_row_size_in_bytes | 1,475 | 1,483 | 1,475 | 1,475 | 624ea40876c3c4ea8d519fae3a50aa2052a37622 | bigcode/the-stack | train |
cf3461edd1abdfd3a7f93b7b | train | class | class DoesNotHavePrefix(Exception):
pass
| class DoesNotHavePrefix(Exception):
| pass
| _configs import SparseType
from torch import Tensor, nn
ASSOC = 32
# Maximum number of times prefetch() can be called without
# a corresponding forward() call
MAX_PREFETCH_DEPTH = 100
INT8_EMB_ROW_DIM_OFFSET = 8
class DoesNotHavePrefix(Exception):
| 64 | 64 | 10 | 7 | 56 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | DoesNotHavePrefix | DoesNotHavePrefix | 30 | 31 | 30 | 30 | 771c514df3bb767a23a9da424c536bdc88ccbbdd | bigcode/the-stack | train |
3669daeb7ae0aa2f1a9e4257 | train | class | class PoolingMode(enum.IntEnum):
SUM = 0
MEAN = 1
NONE = 2
| class PoolingMode(enum.IntEnum):
| SUM = 0
MEAN = 1
NONE = 2
|
MANAGED_CACHING = 2
HOST = 3
class ComputeDevice(enum.IntEnum):
CPU = 0
CUDA = 1
class CacheAlgorithm(enum.Enum):
LRU = 0
LFU = 1
class PoolingMode(enum.IntEnum):
| 64 | 64 | 27 | 8 | 55 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | PoolingMode | PoolingMode | 51 | 54 | 51 | 51 | a4c1887a4cb5d0f524f239144f82fff253c7cd07 | bigcode/the-stack | train |
5b514498e41037b6b67b977c | train | class | class ComputeDevice(enum.IntEnum):
CPU = 0
CUDA = 1
| class ComputeDevice(enum.IntEnum):
| CPU = 0
CUDA = 1
| 8_EMB_ROW_DIM_OFFSET = 8
class DoesNotHavePrefix(Exception):
pass
class EmbeddingLocation(enum.IntEnum):
DEVICE = 0
MANAGED = 1
MANAGED_CACHING = 2
HOST = 3
class ComputeDevice(enum.IntEnum):
| 64 | 64 | 19 | 7 | 56 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | ComputeDevice | ComputeDevice | 41 | 43 | 41 | 41 | c979093b70a39e5216694354078f0756227f9adf | bigcode/the-stack | train |
b7c61a6a10876f58a70ab2bf | train | function | def round_up(a: int, b: int) -> int:
return int((a + b - 1) // b) * b
| def round_up(a: int, b: int) -> int:
| return int((a + b - 1) // b) * b
| () + 1,
device=indices.device,
dtype=torch.int64,
)
return super(DenseSequenceEmbeddingCodegen, self).forward(
indices,
offsets,
per_sample_weights,
feature_requires_grad,
)
def round_up(a: int, b: int) -> int:
| 64 | 64 | 31 | 14 | 50 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | round_up | round_up | 1,465 | 1,466 | 1,465 | 1,465 | 021d4c3139b72c9a1f69f4e22f599e35132134a5 | bigcode/the-stack | train |
93b6920981113cee43032fd6 | train | class | class DenseTableBatchedEmbeddingBagsCodegen(nn.Module):
"""
Table-batched version of nn.EmbeddingBag(sparse=False)
"""
weights: Tensor
weights_offsets: Tensor
D_offsets: Tensor
total_D: int
max_D: int
hash_size_cumsum: Tensor
total_hash_size_bits: int
embedding_specs: List[T... | class DenseTableBatchedEmbeddingBagsCodegen(nn.Module):
| """
Table-batched version of nn.EmbeddingBag(sparse=False)
"""
weights: Tensor
weights_offsets: Tensor
D_offsets: Tensor
total_D: int
max_D: int
hash_size_cumsum: Tensor
total_hash_size_bits: int
embedding_specs: List[Tuple[int, int]]
def __init__(
self,
... | 28]: Unexpected keyword argument `size`.
torch.zeros(
size=(self.total_cache_hash_size + 1,)
if cache_algorithm == CacheAlgorithm.LFU
else (cache_sets, ASSOC),
device=self.current_device,
dtype=torch.int64,
),
... | 256 | 256 | 1,116 | 13 | 242 | RenfeiChen-FB/FBGEMM | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | Python | DenseTableBatchedEmbeddingBagsCodegen | DenseTableBatchedEmbeddingBagsCodegen | 1,246 | 1,384 | 1,246 | 1,246 | 9394bc6e1f80579b84c083076b65dd4d7c047f94 | bigcode/the-stack | train |
ae1fced394c38b88c1c15c44 | train | class | class VideoRepositoryInterface(ABC):
@abstractmethod
def insert(cls, video: Video) -> Video:
raise NotImplementedError
@abstractmethod
def update(cls, id: int, data: Dict) -> Video:
raise NotImplementedError
@abstractmethod
def delete_by_id(cls, id: int):
raise NotImple... | class VideoRepositoryInterface(ABC):
@abstractmethod
| def insert(cls, video: Video) -> Video:
raise NotImplementedError
@abstractmethod
def update(cls, id: int, data: Dict) -> Video:
raise NotImplementedError
@abstractmethod
def delete_by_id(cls, id: int):
raise NotImplementedError
@abstractmethod
def select_by_id(cls... | from abc import ABC, abstractmethod
from typing import Dict, List, Union
from src.domain.entities import Video
class VideoRepositoryInterface(ABC):
@abstractmethod
| 36 | 64 | 155 | 12 | 23 | regisfbrilhante/challenge-alura-backend | src/repositories/video_repository_interface.py | Python | VideoRepositoryInterface | VideoRepositoryInterface | 6 | 29 | 6 | 7 | 98ab1f4925053dda6f2ff9b41b23d6713f998562 | bigcode/the-stack | train |
6d052bc44838dcba3d6ec582 | train | function | def printout(*args):
if IsInteractive:
print(*args)
| def printout(*args):
| if IsInteractive:
print(*args)
| ty()
Prompt = None
# Default values for user and topic
DefaultUser = None
DefaultTopic = None
# Variables: results of command execution
Variables = {}
# Flag to enable extended logging. Useful for debugging.
Verbose = False
# Print prompts in interactive mode only.
def printout(*args):
| 64 | 64 | 16 | 6 | 58 | devmastery0319/chatting-with-bot | tn-cli/tn_globals.py | Python | printout | printout | 48 | 50 | 48 | 48 | f54d56aef1d64569ecb280618a2f7907183e9726 | bigcode/the-stack | train |
0cd36adf03bc1d6d4f14f651 | train | function | def printerr(*args):
text = ""
for a in args:
text = text + str(a) + " "
# Strip just the spaces here, don't strip the newline or tabs.
text = text.strip(" ")
if text:
sys.stderr.write(text + "\n")
| def printerr(*args):
| text = ""
for a in args:
text = text + str(a) + " "
# Strip just the spaces here, don't strip the newline or tabs.
text = text.strip(" ")
if text:
sys.stderr.write(text + "\n")
| = None
DefaultTopic = None
# Variables: results of command execution
Variables = {}
# Flag to enable extended logging. Useful for debugging.
Verbose = False
# Print prompts in interactive mode only.
def printout(*args):
if IsInteractive:
print(*args)
def printerr(*args):
| 64 | 64 | 62 | 6 | 58 | devmastery0319/chatting-with-bot | tn-cli/tn_globals.py | Python | printerr | printerr | 52 | 59 | 52 | 52 | 23bf05238c2b92deb9fc9f9f13e3099e8a9371cd | bigcode/the-stack | train |
a0ae84204fffd2a8d0ab1bb9 | train | function | def stdout(*args):
text = ""
for a in args:
text = text + str(a) + " "
# Strip just the spaces here, don't strip the newline or tabs.
text = text.strip(" ")
if text:
OutputQueue.put(text)
| def stdout(*args):
| text = ""
for a in args:
text = text + str(a) + " "
# Strip just the spaces here, don't strip the newline or tabs.
text = text.strip(" ")
if text:
OutputQueue.put(text)
| + " "
# Strip just the spaces here, don't strip the newline or tabs.
text = text.strip(" ")
if text:
sys.stderr.write(text + "\n")
# Support for asynchronous input-output to/from stdin/stdout
# Stdout asynchronously writes to sys.stdout
def stdout(*args):
| 64 | 64 | 58 | 5 | 58 | devmastery0319/chatting-with-bot | tn-cli/tn_globals.py | Python | stdout | stdout | 64 | 71 | 64 | 64 | 4ac253d2b84caf20329d06df4d79a78318863348 | bigcode/the-stack | train |
cf6b6d9b2e77e24140e79c61 | train | function | def stdoutln(*args):
args = args + ("\n",)
stdout(*args)
| def stdoutln(*args):
| args = args + ("\n",)
stdout(*args)
| = text + str(a) + " "
# Strip just the spaces here, don't strip the newline or tabs.
text = text.strip(" ")
if text:
OutputQueue.put(text)
# Stdoutln asynchronously writes to sys.stdout and adds a new line to input.
def stdoutln(*args):
| 64 | 64 | 20 | 6 | 58 | devmastery0319/chatting-with-bot | tn-cli/tn_globals.py | Python | stdoutln | stdoutln | 74 | 76 | 74 | 74 | 7d1e155b3fdad56944522f660df69e8e2bb21002 | bigcode/the-stack | train |
6e5494dd2bf592a86cc29aaf | train | function | def clip_long_string(obj):
if isinstance(obj, str) or isinstance(obj, unicode):
if len(obj) > 64:
return '<' + str(len(obj)) + ' bytes: ' + obj[:12] + '...' + obj[-12:] + '>'
return obj
elif isinstance(obj, (list, tuple)):
return [clip_long_string(item) for item in obj]
e... | def clip_long_string(obj):
| if isinstance(obj, str) or isinstance(obj, unicode):
if len(obj) > 64:
return '<' + str(len(obj)) + ' bytes: ' + obj[:12] + '...' + obj[-12:] + '>'
return obj
elif isinstance(obj, (list, tuple)):
return [clip_long_string(item) for item in obj]
elif isinstance(obj, dict):
... | .strip(" ")
if text:
OutputQueue.put(text)
# Stdoutln asynchronously writes to sys.stdout and adds a new line to input.
def stdoutln(*args):
args = args + ("\n",)
stdout(*args)
# Shorten long strings for logging.
def clip_long_string(obj):
| 64 | 64 | 118 | 6 | 58 | devmastery0319/chatting-with-bot | tn-cli/tn_globals.py | Python | clip_long_string | clip_long_string | 79 | 89 | 79 | 79 | 53aa438cf8a1b14a2649009714b748a6b7b81475 | bigcode/the-stack | train |
8a4f09d85b81a035d4f7a7ee | train | function | def to_json(msg):
if not msg:
return 'null'
try:
return json.dumps(clip_long_string(MessageToDict(msg)))
except Exception as err:
stdoutln("Exception: {}".format(err))
return 'exception'
| def to_json(msg):
| if not msg:
return 'null'
try:
return json.dumps(clip_long_string(MessageToDict(msg)))
except Exception as err:
stdoutln("Exception: {}".format(err))
return 'exception'
| [clip_long_string(item) for item in obj]
elif isinstance(obj, dict):
return dict((key, clip_long_string(val)) for key, val in obj.items())
else:
return obj
# Convert protobuff message to json. Shorten very long strings.
def to_json(msg):
| 64 | 64 | 52 | 5 | 59 | devmastery0319/chatting-with-bot | tn-cli/tn_globals.py | Python | to_json | to_json | 92 | 100 | 92 | 92 | 63752deda5a2fa503bf5c3fe446d2b788152aa54 | bigcode/the-stack | train |
f047003d428aa2b44af8e966 | train | class | class Migration(migrations.Migration):
dependencies = [
('polls', '0011_question_follow_up'),
]
operations = [
migrations.AddField(
model_name='question',
name='question_owner',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCA... | class Migration(migrations.Migration):
| dependencies = [
('polls', '0011_question_follow_up'),
]
operations = [
migrations.AddField(
model_name='question',
name='question_owner',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='polls.Student'),
),
... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-03 18:42
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 61 | 64 | 74 | 7 | 53 | ReedyChen/opra | compsocsite/polls/migrations/0012_question_question_owner.py | Python | Migration | Migration | 9 | 21 | 9 | 10 | 7333ef5a0459336daad45431ab29cfe94c7c3dd7 | bigcode/the-stack | train |
c4a52c42ad89b98447bf2b56 | train | class | class TestDomains(unittest.TestCase, AbstractTestCase):
@classmethod
def setUpClass(cls):
cls.mock_client_class()
def setUp(self):
self.build_client()
def test_list(self):
self.client.get.return_value = self.mock_response('/v3/domains',
... | class TestDomains(unittest.TestCase, AbstractTestCase):
@classmethod
| def setUpClass(cls):
cls.mock_client_class()
def setUp(self):
self.build_client()
def test_list(self):
self.client.get.return_value = self.mock_response('/v3/domains',
HTTPStatus.OK,
... | import sys
import unittest
from http import HTTPStatus
from unittest.mock import patch
import cloudfoundry_client.main.main as main
from abstract_test_case import AbstractTestCase
from cloudfoundry_client.v3.domains import Domain
from cloudfoundry_client.v3.entities import Entity, ToManyRelationship, ToOneRelationship... | 83 | 256 | 1,289 | 15 | 67 | alogishetty/cf-python-client | test/v3/test_domains.py | Python | TestDomains | TestDomains | 12 | 159 | 12 | 13 | 78e76be54d45eb951033fd51bdfa1274db898ba4 | bigcode/the-stack | train |
424fa9e7f71586a252812fa8 | train | function | def main():
processed = preprocess.get_transform(augment=False)
if args.isgray.lower() == 'true':
print ('reading gray images')
imgL_o = cv2.cvtColor(cv2.imread(args.leftimg, 0), cv2.COLOR_GRAY2RGB)
imgR_o = cv2.cvtColor(cv2.imread(args.rightimg, 0), cv2.COLOR_GRAY2RGB)
else:
... | def main():
| processed = preprocess.get_transform(augment=False)
if args.isgray.lower() == 'true':
print ('reading gray images')
imgL_o = cv2.cvtColor(cv2.imread(args.leftimg, 0), cv2.COLOR_GRAY2RGB)
imgR_o = cv2.cvtColor(cv2.imread(args.rightimg, 0), cv2.COLOR_GRAY2RGB)
else:
#imgL_o = ... | device_ids=[0])
model.cuda()
if args.loadmodel is not None:
print('load PSMNet')
state_dict = torch.load(args.loadmodel)
model.load_state_dict(state_dict['state_dict'])
print('Number of model parameters: {}'.format(
sum([p.data.nelement() for p in model.parameters()])))
def test(imgL, imgR):
m... | 169 | 169 | 566 | 3 | 165 | ccj5351/DAFStereoNets | src/baselines/PSMNet/test_img.py | Python | main | main | 96 | 142 | 96 | 96 | ed146dc3a83dd646e5e37762cbbeeaf0158f48cc | bigcode/the-stack | train |
858b316cab7ab225945ddd0d | train | function | def test(imgL, imgR):
model.eval()
if args.cuda:
imgL = torch.FloatTensor(imgL).cuda()
imgR = torch.FloatTensor(imgR).cuda()
imgL, imgR = Variable(imgL), Variable(imgR)
with torch.no_grad():
disp = model(imgL, imgR)
disp = torch.squeeze(disp)
pred_disp = disp.data.cpu... | def test(imgL, imgR):
| model.eval()
if args.cuda:
imgL = torch.FloatTensor(imgL).cuda()
imgR = torch.FloatTensor(imgR).cuda()
imgL, imgR = Variable(imgL), Variable(imgR)
with torch.no_grad():
disp = model(imgL, imgR)
disp = torch.squeeze(disp)
pred_disp = disp.data.cpu().numpy()
return... | :
print('load PSMNet')
state_dict = torch.load(args.loadmodel)
model.load_state_dict(state_dict['state_dict'])
print('Number of model parameters: {}'.format(
sum([p.data.nelement() for p in model.parameters()])))
def test(imgL, imgR):
| 63 | 64 | 95 | 8 | 55 | ccj5351/DAFStereoNets | src/baselines/PSMNet/test_img.py | Python | test | test | 78 | 93 | 78 | 78 | 50f02efdb0842d82c50a2849a2b60a515567f28e | bigcode/the-stack | train |
821b8e41f7f2be9c02e4e3e4 | train | class | class LuaImplPackage(MakefilePackage):
"""Specialized class for lua *implementations*
This exists to ensure that lua, luajit and luajit-openresty all initialize extension
packages the same way and provide luarocks the same way."""
extendable = True
variant(
"fetcher",
default="cur... | class LuaImplPackage(MakefilePackage):
| """Specialized class for lua *implementations*
This exists to ensure that lua, luajit and luajit-openresty all initialize extension
packages the same way and provide luarocks the same way."""
extendable = True
variant(
"fetcher",
default="curl",
values=("curl", "wget"),
... | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import glob
import os
import spack.build_environment
from spack.package import *
from spack.util.executable import Execut... | 86 | 256 | 1,680 | 9 | 76 | jeanbez/spack | var/spack/repos/builtin/packages/lua/package.py | Python | LuaImplPackage | LuaImplPackage | 14 | 211 | 14 | 14 | 89d5b80cfaf83120f311cf6f6e999cf1a54c5bb8 | bigcode/the-stack | train |
e3216ff639b1fddf2b56ce21 | train | class | class Lua(LuaImplPackage):
"""The Lua programming language interpreter and library."""
homepage = "https://www.lua.org"
url = "https://www.lua.org/ftp/lua-5.3.4.tar.gz"
version('5.3.5', sha256='0c2eed3f960446e1a3e4b9a1ca2f3ff893b6ce41942cf54d5dd59ab4b3b058ac')
version('5.3.4', sha256='f681aa518233... | class Lua(LuaImplPackage):
| """The Lua programming language interpreter and library."""
homepage = "https://www.lua.org"
url = "https://www.lua.org/ftp/lua-5.3.4.tar.gz"
version('5.3.5', sha256='0c2eed3f960446e1a3e4b9a1ca2f3ff893b6ce41942cf54d5dd59ab4b3b058ac')
version('5.3.4', sha256='f681aa518233bc407e23acf0f5887c884f17436... | )
env.prepend_path(
"LUA_PATH",
os.path.join(self.spec.prefix, self.lua_lib_dir, "?.lua"),
separator=";",
)
env.prepend_path(
"LUA_PATH",
os.path.join(self.spec.prefix, self.lua_lib_dir, "?", "init.lua"),
separator=";",
... | 256 | 256 | 1,377 | 7 | 249 | jeanbez/spack | var/spack/repos/builtin/packages/lua/package.py | Python | Lua | Lua | 214 | 299 | 214 | 214 | d62db676da2bc2cc5cb7d60ebf7900802a94c561 | bigcode/the-stack | train |
c0e4d2af90a8e41c25322068 | train | class | class ProviderOperations(object):
"""ProviderOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type mo... | class ProviderOperations(object):
| """ProviderOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.web.v2019_08_01.... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | 235 | 256 | 2,244 | 5 | 230 | rsdoherty/azure-sdk-for-python | sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2019_08_01/operations/_provider_operations.py | Python | ProviderOperations | ProviderOperations | 26 | 259 | 26 | 26 | a9b54993a960e015d9d4894a35671361eb5c59e6 | bigcode/the-stack | train |
ae681d60768bdcf4ecae7da0 | train | function | def test():
"""
Send all output to a log file
"""
# get the channel
from journal.ext.journal import Firewall as firewall
# send output to a log file
firewall.logfile(name="firewall_file_mode.log", mode="a")
# make a channel
channel = firewall(name="test.journal.firewall")
# add... | def test():
| """
Send all output to a log file
"""
# get the channel
from journal.ext.journal import Firewall as firewall
# send output to a log file
firewall.logfile(name="firewall_file_mode.log", mode="a")
# make a channel
channel = firewall(name="test.journal.firewall")
# add some metada... | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
# (c) 1998-2022 all rights reserved
def test():
| 57 | 64 | 186 | 3 | 53 | PyreFramework/pyre | tests/journal.ext/firewall_file_mode.py | Python | test | test | 8 | 36 | 8 | 8 | 71b7762ae6ea38a2f00d11999fb965c27f08b6a3 | bigcode/the-stack | train |
dfb6a91d1296d54b01323cf7 | train | class | class Room(object):
def __init__(self,name,description):
self.name=name
self.description=description
self.paths={}
def go(self,direction):
return self.paths.get(direction,None)
def add_paths(self,paths):
self.paths.update(paths)
| class Room(object):
| def __init__(self,name,description):
self.name=name
self.description=description
self.paths={}
def go(self,direction):
return self.paths.get(direction,None)
def add_paths(self,paths):
self.paths.update(paths)
| class Room(object):
| 4 | 64 | 58 | 4 | 0 | Nandarlynnn/python-exercises | ex47.py | Python | Room | Room | 1 | 9 | 1 | 1 | fbc747164c4575d5985433d59a8086cf33f8d68f | bigcode/the-stack | train |
006d6ae32c6f821be8631a07 | train | function | @wallet_cmd.command("add_token", short_help="Add/Rename a CAT to the wallet by its asset ID")
@click.option(
"-wp",
"--wallet-rpc-port",
help="Set the port where the Wallet is hosting the RPC interface. See the rpc_port under wallet in config.yaml",
type=int,
default=None,
)
@click.option(
"-id"... | @wallet_cmd.command("add_token", short_help="Add/Rename a CAT to the wallet by its asset ID")
@click.option(
"-wp",
"--wallet-rpc-port",
help="Set the port where the Wallet is hosting the RPC interface. See the rpc_port under wallet in config.yaml",
type=int,
default=None,
)
@click.option(
"-id"... | extra_params = {"asset_id": asset_id, "token_name": token_name}
import asyncio
from .wallet_funcs import execute_with_wallet, add_token
asyncio.run(execute_with_wallet(wallet_rpc_port, fingerprint, extra_params, add_token))
| @wallet_cmd.command("add_token", short_help="Add/Rename a CAT to the wallet by its asset ID")
@click.option(
"-wp",
"--wallet-rpc-port",
help="Set the port where the Wallet is hosting the RPC interface. See the rpc_port under wallet in config.yaml",
type=int,
default=None,
)
@click.option(
"-id"... | 203 | 77 | 257 | 203 | 0 | ageorge95/chia-blockchain | chia/cmds/wallet.py | Python | add_token_cmd | add_token_cmd | 186 | 217 | 186 | 212 | c464cfeff13fc5c14ea8916e83423fccabbbd816 | bigcode/the-stack | train |
df84a4a4de253b68119433a6 | train | function | @wallet_cmd.command("get_transaction", short_help="Get a transaction")
@click.option(
"-wp",
"--wallet-rpc-port",
help="Set the port where the Wallet is hosting the RPC interface. See the rpc_port under wallet in config.yaml",
type=int,
default=None,
)
@click.option("-f", "--fingerprint", help="Set ... | @wallet_cmd.command("get_transaction", short_help="Get a transaction")
@click.option(
"-wp",
"--wallet-rpc-port",
help="Set the port where the Wallet is hosting the RPC interface. See the rpc_port under wallet in config.yaml",
type=int,
default=None,
)
@click.option("-f", "--fingerprint", help="Set ... | extra_params = {"id": id, "tx_id": tx_id, "verbose": verbose}
import asyncio
from .wallet_funcs import execute_with_wallet, get_transaction
asyncio.run(execute_with_wallet(wallet_rpc_port, fingerprint, extra_params, get_transaction))
| @wallet_cmd.command("get_transaction", short_help="Get a transaction")
@click.option(
"-wp",
"--wallet-rpc-port",
help="Set the port where the Wallet is hosting the RPC interface. See the rpc_port under wallet in config.yaml",
type=int,
default=None,
)
@click.option("-f", "--fingerprint", help="Set ... | 186 | 72 | 243 | 186 | 0 | ageorge95/chia-blockchain | chia/cmds/wallet.py | Python | get_transaction_cmd | get_transaction_cmd | 12 | 29 | 12 | 24 | 0c24ae7ea20e017768ee2701a8ee091e44bdc174 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.