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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11d00855960edbc6eda8ad14 | train | function | def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n, "qc")
target = QuantumRegister(1, "qt")
prog = QuantumCircuit(input_qubit, target)
# inverse last one (can be omitted if using O_f^\pm)
prog.x(target)
# apply H to get superposition
for i in ... | def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
| input_qubit = QuantumRegister(n, "qc")
target = QuantumRegister(1, "qt")
prog = QuantumCircuit(input_qubit, target)
# inverse last one (can be omitted if using O_f^\pm)
prog.x(target)
# apply H to get superposition
for i in range(n):
prog.h(input_qubit[i])
prog.h(input_qubit[1... | rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.barrier()
# oracle.draw('mpl', filename='circuit/deutsch-oracl... | 100 | 100 | 335 | 17 | 82 | UCLA-SEAL/QDiff | data/p2DJ/New/R2/benchmark/startQiskit78.py | Python | make_circuit | make_circuit | 38 | 78 | 38 | 40 | eb5cf8b2500d9dd8a42d824288a8ecf2bd196a78 | bigcode/the-stack | train |
1b92ea976731e9cd6e598abb | train | function | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name... | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
| controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(... | import networkx as nx
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
| 64 | 64 | 215 | 58 | 5 | UCLA-SEAL/QDiff | data/p2DJ/New/R2/benchmark/startQiskit78.py | Python | build_oracle | build_oracle | 15 | 35 | 15 | 19 | 302e74650a62d7a5d566c9872793076e90aaf1f5 | bigcode/the-stack | train |
6ebbf321f72cf71371b1d92e | train | function | def get_block_hashes(settings, max_blocks_per_call=10000):
rpc = BitcoinRPC(settings['host'], settings['port'],
settings['rpcuser'], settings['rpcpassword'])
height = settings['min_height']
while height < settings['max_height']+1:
num_blocks = min(settings['max_height']+1-height, max_blocks_per_call)
batch ... | def get_block_hashes(settings, max_blocks_per_call=10000):
| rpc = BitcoinRPC(settings['host'], settings['port'],
settings['rpcuser'], settings['rpcpassword'])
height = settings['min_height']
while height < settings['max_height']+1:
num_blocks = min(settings['max_height']+1-height, max_blocks_per_call)
batch = []
for x in range(num_blocks):
batch.append(rpc.buil... | if params is None:
obj['params'] = []
else:
obj['params'] = params
return obj
@staticmethod
def response_is_error(resp_obj):
return 'error' in resp_obj and resp_obj['error'] is not None
def get_block_hashes(settings, max_blocks_per_call=10000):
| 72 | 72 | 243 | 15 | 56 | StutzCoin/stutz | contrib/linearize/linearize-hashes.py | Python | get_block_hashes | get_block_hashes | 69 | 94 | 69 | 69 | 59378ab6e5b9432500db56f36784da151a019e12 | bigcode/the-stack | train |
f85c727097fe4a2055b96f0c | train | class | class BitcoinRPC:
def __init__(self, host, port, username, password):
authpair = "%s:%s" % (username, password)
authpair = authpair.encode('utf-8')
self.authhdr = b"Basic " + base64.b64encode(authpair)
self.conn = httplib.HTTPConnection(host, port=port, timeout=30)
def execute(self, obj):
try:
self.conn... | class BitcoinRPC:
| def __init__(self, host, port, username, password):
authpair = "%s:%s" % (username, password)
authpair = authpair.encode('utf-8')
self.authhdr = b"Basic " + base64.b64encode(authpair)
self.conn = httplib.HTTPConnection(host, port=port, timeout=30)
def execute(self, obj):
try:
self.conn.request('POST', '... | httplib
import json
import re
import base64
import sys
settings = {}
##### Switch endian-ness #####
def hex_switchEndian(s):
""" Switches the endianness of a hex string (in pairs of hex chars) """
pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
return b''.join(pairList[::-1]).decode()
class BitcoinRPC... | 93 | 93 | 310 | 4 | 89 | StutzCoin/stutz | contrib/linearize/linearize-hashes.py | Python | BitcoinRPC | BitcoinRPC | 28 | 67 | 28 | 28 | 6d88869dda5fe4b55b5b0a050576fdaf5a3432e5 | bigcode/the-stack | train |
84fef0525f07cdbf08f3fa29 | train | function | def hex_switchEndian(s):
""" Switches the endianness of a hex string (in pairs of hex chars) """
pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
return b''.join(pairList[::-1]).decode()
| def hex_switchEndian(s):
| """ Switches the endianness of a hex string (in pairs of hex chars) """
pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
return b''.join(pairList[::-1]).decode()
| future__ import print_function
try: # Python 3
import http.client as httplib
except ImportError: # Python 2
import httplib
import json
import re
import base64
import sys
settings = {}
##### Switch endian-ness #####
def hex_switchEndian(s):
| 64 | 64 | 63 | 6 | 57 | StutzCoin/stutz | contrib/linearize/linearize-hashes.py | Python | hex_switchEndian | hex_switchEndian | 23 | 26 | 23 | 23 | 06fe94ecea69d999173eeac03747f220d716a545 | bigcode/the-stack | train |
52a4471882d0421472d2b6c3 | train | function | def run(self):
# create module
module = self.module_fn()
module = module.to(self.device)
module = module.type(self.dtype)
module = module.eval()
# create inputs for conversion
inputs_conversion = ()
for shape in self.input_shapes:
inputs_conversion += (torch.zeros(shape).to(... | def run(self):
# create module
| module = self.module_fn()
module = module.to(self.device)
module = module.type(self.dtype)
module = module.eval()
# create inputs for conversion
inputs_conversion = ()
for shape in self.input_shapes:
inputs_conversion += (torch.zeros(shape).to(self.device).type(self.dtype), )
... | from torch2trt import *
from .module_test import ModuleTest, MODULE_TESTS
import time
import argparse
import re
import runpy
from termcolor import colored
def run(self):
# create module
| 47 | 191 | 637 | 9 | 37 | ahangchen/torch2trt | torch2trt/test.py | Python | run | run | 10 | 92 | 10 | 11 | 29160bb201b5c35bf0ce81057df201cbba8a9ac2 | bigcode/the-stack | train |
ca4c6f20c68881adde493ab0 | train | class | class Testando:
def __init__(self,lista):
self.estado=self.nome=self.user=self.senha=self.email= ''
self.idade=0
self.lista=lista
def menu(self):
print(f'\033[35m-\033[m'*42)
print(f'\033[35mRadiante\033[m'.center(47))
print(f'\033[35m-\033[m' * 42)
print... | class Testando:
| def __init__(self,lista):
self.estado=self.nome=self.user=self.senha=self.email= ''
self.idade=0
self.lista=lista
def menu(self):
print(f'\033[35m-\033[m'*42)
print(f'\033[35mRadiante\033[m'.center(47))
print(f'\033[35m-\033[m' * 42)
print('\033[34m[1]- P... | import re
class Testando:
| 7 | 256 | 1,291 | 4 | 2 | XandeDevv/Sistema-de-Cadastro | Projetocadastro.py | Python | Testando | Testando | 3 | 138 | 3 | 3 | 183fd19c7403bc5dcaefcebb6390917d0b8c2602 | bigcode/the-stack | train |
7f14959088b627556bcf022c | train | class | class TatorAuth(ModelBackend):
"""
Authenticates against settings.AUTH_USER_MODEL but enforces account
lockouts based on bad password attempts
"""
def authenticate(self, request, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get(UserModel.USERNAM... | class TatorAuth(ModelBackend):
| """
Authenticates against settings.AUTH_USER_MODEL but enforces account
lockouts based on bad password attempts
"""
def authenticate(self, request, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
if username is... | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.conf import settings
from .notify import Notify
from datetime import datetime,timezone,timedelta
from .ses import TatorSES
import logging
logger = logging.getLogger(__name__)
UserModel = get_user_model()... | 88 | 203 | 677 | 7 | 81 | cvisionai/tator | main/auth.py | Python | TatorAuth | TatorAuth | 18 | 85 | 18 | 18 | d7adebd942ed6590466de59c9b44a6a7e4c5318c | bigcode/the-stack | train |
5d494b3d936c93caa601665c | train | class | class UpdateSecretStageRequestBody:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensiti... | class UpdateSecretStageRequestBody:
| """
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class UpdateSecretStageRequestBody:
| 35 | 187 | 625 | 7 | 27 | huaweicloud/huaweicloud-sdk-python-v3 | huaweicloud-sdk-kms/huaweicloudsdkkms/v1/model/update_secret_stage_request_body.py | Python | UpdateSecretStageRequestBody | UpdateSecretStageRequestBody | 11 | 113 | 11 | 13 | 3e1ceab8944cfc7317595d482e59707e7e24791b | bigcode/the-stack | train |
a6ab5aaea3399fe14f81df73 | train | class | @dataclass
class Base:
class Meta:
name = "base"
foo_or_bar: List[object] = field(
default_factory=list,
metadata={
"type": "Elements",
"choices": (
{
"name": "foo",
"type": Foo,
"namespa... | @dataclass
class Base:
| class Meta:
name = "base"
foo_or_bar: List[object] = field(
default_factory=list,
metadata={
"type": "Elements",
"choices": (
{
"name": "foo",
"type": Foo,
"namespace": "http://xsdtesting... | :
class Meta:
name = "foo"
namespace = "http://xsdtesting"
any_element: Optional[object] = field(
default=None,
metadata={
"type": "Wildcard",
"namespace": "##any",
}
)
@dataclass
class Base:
| 64 | 64 | 119 | 6 | 58 | tefra/xsdata-w3c-tests | output/models/ms_data/particles/particles_ib005_xsd/particles_ib005.py | Python | Base | Base | 22 | 45 | 22 | 23 | 0e1d221640705170e84fe437b47ddeb46bda9238 | bigcode/the-stack | train |
f32c5badb83b17a6510218b8 | train | class | @dataclass
class Doc(Base):
class Meta:
name = "doc"
namespace = "http://xsdtesting"
| @dataclass
class Doc(Base):
| class Meta:
name = "doc"
namespace = "http://xsdtesting"
| ,
"namespace": "http://xsdtesting",
},
{
"name": "bar",
"type": object,
"namespace": "http://xsdtesting",
},
),
"max_occurs": 4,
}
)
@dataclass
class Doc(Ba... | 64 | 64 | 27 | 7 | 57 | tefra/xsdata-w3c-tests | output/models/ms_data/particles/particles_ib005_xsd/particles_ib005.py | Python | Doc | Doc | 48 | 52 | 48 | 49 | b053cc06e0701f82df6215a29064f0ce52d39e79 | bigcode/the-stack | train |
d8ffbbe435dc529d79cc01bf | train | class | @dataclass
class Foo:
class Meta:
name = "foo"
namespace = "http://xsdtesting"
any_element: Optional[object] = field(
default=None,
metadata={
"type": "Wildcard",
"namespace": "##any",
}
)
| @dataclass
class Foo:
| class Meta:
name = "foo"
namespace = "http://xsdtesting"
any_element: Optional[object] = field(
default=None,
metadata={
"type": "Wildcard",
"namespace": "##any",
}
)
| from dataclasses import dataclass, field
from typing import List, Optional
__NAMESPACE__ = "http://xsdtesting"
@dataclass
class Foo:
| 34 | 64 | 63 | 6 | 28 | tefra/xsdata-w3c-tests | output/models/ms_data/particles/particles_ib005_xsd/particles_ib005.py | Python | Foo | Foo | 7 | 19 | 7 | 8 | 0936820033831cc311e061019701fe3941b9ac8f | bigcode/the-stack | train |
612cd7afa1eb9a0601b19e02 | train | function | @parametrize_extensions
@parametrize_filename
@parametrize_script
def test_match(ext, tar_error, filename, unquoted, quoted, script, fixed):
tar_error(unquoted.format(ext))
assert match(Command(script.format(filename.format(ext)), ''))
| @parametrize_extensions
@parametrize_filename
@parametrize_script
def test_match(ext, tar_error, filename, unquoted, quoted, script, fixed):
| tar_error(unquoted.format(ext))
assert match(Command(script.format(filename.format(ext)), ''))
| '),
('tar --extract -f {}', 'mkdir -p {dir} && tar --extract -f {filename} -C {dir}')])
@parametrize_extensions
@parametrize_filename
@parametrize_script
def test_match(ext, tar_error, filename, unquoted, quoted, script, fixed):
| 63 | 64 | 51 | 31 | 32 | WorkInProgress-Development/theplease | tests/rules/test_dirty_untar.py | Python | test_match | test_match | 50 | 55 | 50 | 53 | 90d5ee0891703eab990452a4f6e5814115b23afd | bigcode/the-stack | train |
3fe1ad721dc2b01f6855e957 | train | function | @parametrize_extensions
@parametrize_filename
@parametrize_script
def test_get_new_command(ext, tar_error, filename, unquoted, quoted, script, fixed):
tar_error(unquoted.format(ext))
assert (get_new_command(Command(script.format(filename.format(ext)), ''))
== fixed.format(dir=quoted.format(''), file... | @parametrize_extensions
@parametrize_filename
@parametrize_script
def test_get_new_command(ext, tar_error, filename, unquoted, quoted, script, fixed):
| tar_error(unquoted.format(ext))
assert (get_new_command(Command(script.format(filename.format(ext)), ''))
== fixed.format(dir=quoted.format(''), filename=filename.format(ext)))
| side_effect(Command(script.format(filename.format(ext)), ''), None)
assert set(os.listdir('.')) == {unquoted.format(ext), 'd'}
@parametrize_extensions
@parametrize_filename
@parametrize_script
def test_get_new_command(ext, tar_error, filename, unquoted, quoted, script, fixed):
| 63 | 64 | 72 | 33 | 30 | WorkInProgress-Development/theplease | tests/rules/test_dirty_untar.py | Python | test_get_new_command | test_get_new_command | 67 | 73 | 67 | 70 | e0a6d842c6581c4063c4529e7d5a2d0208e579ff | bigcode/the-stack | train |
02675b3354899089aff62966 | train | function | @pytest.fixture
def tar_error(tmpdir):
def fixture(filename):
path = os.path.join(str(tmpdir), filename)
def reset(path):
os.mkdir('d')
with tarfile.TarFile(path, 'w') as archive:
for file in ('a', 'b', 'c', 'd/e'):
with open(file, 'w') as... | @pytest.fixture
def tar_error(tmpdir):
| def fixture(filename):
path = os.path.join(str(tmpdir), filename)
def reset(path):
os.mkdir('d')
with tarfile.TarFile(path, 'w') as archive:
for file in ('a', 'b', 'c', 'd/e'):
with open(file, 'w') as f:
f.write('*'... | import os
import pytest
import tarfile
from theplease.rules.dirty_untar import match, get_new_command, side_effect, \
tar_extensions # noqa: E126
from theplease.types import Command
@pytest.fixture
def tar_error(tmpdir):
| 55 | 64 | 165 | 9 | 45 | WorkInProgress-Development/theplease | tests/rules/test_dirty_untar.py | Python | tar_error | tar_error | 9 | 34 | 9 | 10 | 6d25e1fe8392480cb3c95da5b98eee3552678f12 | bigcode/the-stack | train |
29c97255c4d20826c7e7d39c | train | function | @parametrize_extensions
@parametrize_filename
@parametrize_script
def test_side_effect(ext, tar_error, filename, unquoted, quoted, script, fixed):
tar_error(unquoted.format(ext))
side_effect(Command(script.format(filename.format(ext)), ''), None)
assert set(os.listdir('.')) == {unquoted.format(ext), 'd'}
| @parametrize_extensions
@parametrize_filename
@parametrize_script
def test_side_effect(ext, tar_error, filename, unquoted, quoted, script, fixed):
| tar_error(unquoted.format(ext))
side_effect(Command(script.format(filename.format(ext)), ''), None)
assert set(os.listdir('.')) == {unquoted.format(ext), 'd'}
| filename, unquoted, quoted, script, fixed):
tar_error(unquoted.format(ext))
assert match(Command(script.format(filename.format(ext)), ''))
@parametrize_extensions
@parametrize_filename
@parametrize_script
def test_side_effect(ext, tar_error, filename, unquoted, quoted, script, fixed):
| 63 | 64 | 71 | 32 | 31 | WorkInProgress-Development/theplease | tests/rules/test_dirty_untar.py | Python | test_side_effect | test_side_effect | 58 | 64 | 58 | 61 | ac79cc98cc21e83c5ab098e9c0b970922a4a1885 | bigcode/the-stack | train |
77fb4826278671e502b034ac | train | class | class ModelAgeRestrictionResponseV3(Model):
"""Model age restriction response V3
Properties:
age_restriction: (ageRestriction) REQUIRED int
enable: (enable) REQUIRED bool
"""
# region fields
age_restriction: int ... | class ModelAgeRestrictionResponseV3(Model):
| """Model age restriction response V3
Properties:
age_restriction: (ageRestriction) REQUIRED int
enable: (enable) REQUIRED bool
"""
# region fields
age_restriction: int # REQUIRED
enable: bool ... | disable=line-too-long
# pylint: disable=missing-function-docstring
# pylint: disable=missing-module-docstring
# pylint: disable=too-many-arguments
# pylint: disable=too-many-branches
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-lines
# pylint: disable=too-many-locals
# pylint: disable=too-... | 153 | 153 | 513 | 9 | 143 | encyphered/accelbyte-python-sdk | accelbyte_py_sdk/api/iam/models/model_age_restriction_response_v3.py | Python | ModelAgeRestrictionResponseV3 | ModelAgeRestrictionResponseV3 | 28 | 105 | 28 | 28 | e5faf3c95269489d225252ec945426d234d3342a | bigcode/the-stack | train |
4e05dea947c73c77b3df0da1 | train | class | class TaggerConfigurationError(StandardError):
pass
| class TaggerConfigurationError(StandardError):
| pass
|
if show_tb:
import traceback, sys
self.tb_str = "".join(traceback.format_tb(sys.exc_info()[2]))
def __str__(self):
return self.prefix + ": " + self.errstr + "\n" + self.tb_str
class TaggerConfigurationError(StandardError):
| 64 | 64 | 11 | 8 | 55 | wake-forest-ctsi/mist-toolkit | src/MAT/lib/mat/python/MAT/Error.py | Python | TaggerConfigurationError | TaggerConfigurationError | 21 | 22 | 21 | 21 | 4a6a94a47ef3c6fe89284571b5e6776a3b10026e | bigcode/the-stack | train |
689e9089df904d303f5f5067 | train | class | class MATError(StandardError):
def __init__(self, phase, errstr, show_tb = False, file = None):
self.phase = phase
self.errstr = errstr
self.tb_str = ""
self.file = file
self.prefix = "for phase " + self.phase
if self.file:
self.prefix += ", file " + self.... | class MATError(StandardError):
| def __init__(self, phase, errstr, show_tb = False, file = None):
self.phase = phase
self.errstr = errstr
self.tb_str = ""
self.file = file
self.prefix = "for phase " + self.phase
if self.file:
self.prefix += ", file " + self.file
if show_tb:
... | # Copyright (C) 2007 - 2009 The MITRE Corporation. See the toplevel
# file LICENSE for license terms.
# The error class
class MATError(StandardError):
| 41 | 64 | 136 | 6 | 34 | wake-forest-ctsi/mist-toolkit | src/MAT/lib/mat/python/MAT/Error.py | Python | MATError | MATError | 6 | 19 | 6 | 6 | b297aff85d38ed5ff1ffbd90958e3afcc25f0fd6 | bigcode/the-stack | train |
aa8ed333ba3d1b0ffc8fadfd | train | class | class TaggingError(StandardError):
pass
| class TaggingError(StandardError):
| pass
| sys
self.tb_str = "".join(traceback.format_tb(sys.exc_info()[2]))
def __str__(self):
return self.prefix + ": " + self.errstr + "\n" + self.tb_str
class TaggerConfigurationError(StandardError):
pass
class TaggingError(StandardError):
| 64 | 64 | 10 | 7 | 56 | wake-forest-ctsi/mist-toolkit | src/MAT/lib/mat/python/MAT/Error.py | Python | TaggingError | TaggingError | 24 | 25 | 24 | 24 | afe1f376b8c8154439150e3082d63d5af17c4769 | bigcode/the-stack | train |
5a113f3708801fe5c91742d0 | train | class | class Render:
def __init__(self, size=512, device=torch.device("cuda:0")):
self.device = device
self.mesh_y_center = 100.0
self.dis = 100.0
self.scale = 1.0
self.size = size
self.cam_pos = [(0, 100, 100)]
self.mesh = None
self.deform_mesh = None
... | class Render:
| def __init__(self, size=512, device=torch.device("cuda:0")):
self.device = device
self.mesh_y_center = 100.0
self.dis = 100.0
self.scale = 1.0
self.size = size
self.cam_pos = [(0, 100, 100)]
self.mesh = None
self.deform_mesh = None
self.pcd = ... | .0) * 0.5 * 255.0
).detach().cpu() * visibility
# mesh = trimesh.Trimesh(verts.detach().cpu(), faces.detach().cpu(), process=False, maintains_order=True)
# mesh.visual.vertex_colors = colors
# mesh.show()
return colors
class cleanShader(torch.nn.Module):
def __init__(self, device="cpu", came... | 256 | 256 | 3,841 | 3 | 252 | YuliangXiu/ICON | lib/common/render.py | Python | Render | Render | 117 | 570 | 117 | 117 | 207da170721d4c5fd36ab69741c07f9e4105afe2 | bigcode/the-stack | train |
d8a2cf1ac559efa666d593d7 | train | function | def query_color(verts, faces, image, device):
"""query colors from points and image
Args:
verts ([B, 3]): [query verts]
faces ([M, 3]): [query faces]
image ([B, 3, H, W]): [full image]
Returns:
[np.float]: [return colors]
"""
verts = verts.float().to(device)
fa... | def query_color(verts, faces, image, device):
| """query colors from points and image
Args:
verts ([B, 3]): [query verts]
faces ([M, 3]): [query faces]
image ([B, 3, H, W]): [full image]
Returns:
[np.float]: [return colors]
"""
verts = verts.float().to(device)
faces = faces.long().to(device)
(xy, z) = v... | [0].size
videodims = (w, h)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video = cv2.VideoWriter(vid_path, fourcc, 30, videodims)
for image in images:
video.write(cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR))
video.release()
def query_color(verts, faces, image, device):
| 92 | 92 | 308 | 12 | 80 | YuliangXiu/ICON | lib/common/render.py | Python | query_color | query_color | 60 | 90 | 60 | 60 | 6951284ce8e7036204520d15322670e219683bde | bigcode/the-stack | train |
b1191a4f331925c715759bb4 | train | class | class cleanShader(torch.nn.Module):
def __init__(self, device="cpu", cameras=None, blend_params=None):
super().__init__()
self.cameras = cameras
self.blend_params = blend_params if blend_params is not None else BlendParams()
def forward(self, fragments, meshes, **kwargs):
camera... | class cleanShader(torch.nn.Module):
| def __init__(self, device="cpu", cameras=None, blend_params=None):
super().__init__()
self.cameras = cameras
self.blend_params = blend_params if blend_params is not None else BlendParams()
def forward(self, fragments, meshes, **kwargs):
cameras = kwargs.get("cameras", self.camer... | .0
).detach().cpu() * visibility
# mesh = trimesh.Trimesh(verts.detach().cpu(), faces.detach().cpu(), process=False, maintains_order=True)
# mesh.visual.vertex_colors = colors
# mesh.show()
return colors
class cleanShader(torch.nn.Module):
| 64 | 64 | 185 | 7 | 56 | YuliangXiu/ICON | lib/common/render.py | Python | cleanShader | cleanShader | 93 | 114 | 93 | 93 | 26e248422c0e1f7aed4cc0f2235d6fbf6fc4a366 | bigcode/the-stack | train |
603e2db3ca08623afbb8aa30 | train | function | def image2vid(images, vid_path):
w, h = images[0].size
videodims = (w, h)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video = cv2.VideoWriter(vid_path, fourcc, 30, videodims)
for image in images:
video.write(cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR))
video.release()
| def image2vid(images, vid_path):
| w, h = images[0].size
videodims = (w, h)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video = cv2.VideoWriter(vid_path, fourcc, 30, videodims)
for image in images:
video.write(cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR))
video.release()
| import SMPLX, get_visibility
import lib.common.render_utils as util
import torch
import numpy as np
from PIL import Image
from pytorch3d.io import load_obj
import os
import cv2
import math
from termcolor import colored
def image2vid(images, vid_path):
| 64 | 64 | 95 | 9 | 54 | YuliangXiu/ICON | lib/common/render.py | Python | image2vid | image2vid | 49 | 57 | 49 | 50 | 964e19839c049f0b15b19c5d84aa70a02052c7a1 | bigcode/the-stack | train |
dd7cc576ad4593ee8ac64f3f | train | class | class TestGetPools(TestBasePoolEndpoints):
def test_response_200(self, session):
pool_model = Pool(pool="test_pool_a", slots=3)
session.add(pool_model)
session.commit()
result = session.query(Pool).all()
assert len(result) == 2 # accounts for the default pool as well
... | class TestGetPools(TestBasePoolEndpoints):
| def test_response_200(self, session):
pool_model = Pool(pool="test_pool_a", slots=3)
session.add(pool_model)
session.commit()
result = session.query(Pool).all()
assert len(result) == 2 # accounts for the default pool as well
response = self.client.get("/api/v1/pools"... | (app, username="test_no_permissions") # type: ignore
class TestBasePoolEndpoints:
@pytest.fixture(autouse=True)
def setup_attrs(self, configured_app) -> None:
self.app = configured_app
self.client = self.app.test_client() # type:ignore
clear_db_pools()
def teardown_method(self) ... | 93 | 93 | 310 | 9 | 84 | raspberryfield/airflow | tests/api_connexion/endpoints/test_pool_endpoint.py | Python | TestGetPools | TestGetPools | 64 | 102 | 64 | 64 | 94f6f3945cd79ab4514d6433d9d6d072ea717834 | bigcode/the-stack | train |
da7b49e8d1421fdcbe1cf6da | train | class | class TestPatchPoolWithUpdateMask(TestBasePoolEndpoints):
@parameterized.expand(
[
(
"api/v1/pools/test_pool?update_mask=name, slots",
{"name": "test_pool_a", "slots": 2},
"test_pool_a",
2,
),
(
... | class TestPatchPoolWithUpdateMask(TestBasePoolEndpoints):
@parameterized.expand(
[
(
"api/v1/pools/test_pool?update_mask=name, slots",
{"name": "test_pool_a", "slots": 2},
"test_pool_a",
2,
),
(
... | def test_response_200(self, url, patch_json, expected_name, expected_slots, session):
pool = Pool(pool="test_pool", slots=3)
session.add(pool)
session.commit()
response = self.client.patch(url, json=patch_json, environ_overrides={'REMOTE_USER': "test"})
assert response.status... | .status_code == status_code
assert response.json == expected_response
class TestPatchPoolWithUpdateMask(TestBasePoolEndpoints):
@parameterized.expand(
[
(
"api/v1/pools/test_pool?update_mask=name, slots",
{"name": "test_pool_a", "slots": 2},
... | 209 | 209 | 699 | 195 | 13 | raspberryfield/airflow | tests/api_connexion/endpoints/test_pool_endpoint.py | Python | TestPatchPoolWithUpdateMask | TestPatchPoolWithUpdateMask | 458 | 544 | 458 | 487 | 928ab41153ed988993087e7805f01a46525d5b9a | bigcode/the-stack | train |
fef469c2e8f4f68d8fcefa69 | train | class | class TestDeletePool(TestBasePoolEndpoints):
def test_response_204(self, session):
pool_name = "test_pool"
pool_instance = Pool(pool=pool_name, slots=3)
session.add(pool_instance)
session.commit()
response = self.client.delete(f"api/v1/pools/{pool_name}", environ_overrides={... | class TestDeletePool(TestBasePoolEndpoints):
| def test_response_204(self, session):
pool_name = "test_pool"
pool_instance = Pool(pool=pool_name, slots=3)
session.add(pool_instance)
session.commit()
response = self.client.delete(f"api/v1/pools/{pool_name}", environ_overrides={'REMOTE_USER': "test"})
assert respon... | response.status_code == 404
assert {
"detail": "Pool with name:'invalid_pool' not found",
"status": 404,
"title": "Not Found",
"type": EXCEPTIONS_LINK_MAP[404],
} == response.json
def test_should_raises_401_unauthenticated(self):
response = s... | 102 | 102 | 342 | 9 | 93 | raspberryfield/airflow | tests/api_connexion/endpoints/test_pool_endpoint.py | Python | TestDeletePool | TestDeletePool | 192 | 227 | 192 | 192 | 6989cbe4de35c887452e04c2d81554b51c76487f | bigcode/the-stack | train |
6d255349f8e8542a44adf0b4 | train | class | class TestGetPoolsPagination(TestBasePoolEndpoints):
@parameterized.expand(
[
# Offset test data
("/api/v1/pools?offset=1", [f"test_pool{i}" for i in range(1, 101)]),
("/api/v1/pools?offset=3", [f"test_pool{i}" for i in range(3, 103)]),
# Limit test data
... | class TestGetPoolsPagination(TestBasePoolEndpoints):
@parameterized.expand(
[
# Offset test data
("/api/v1/pools?offset=1", [f"test_pool{i}" for i in range(1, 101)]),
("/api/v1/pools?offset=3", [f"test_pool{i}" for i in range(3, 103)]),
# Limit test data
... | def test_limit_and_offset(self, url, expected_pool_ids, session):
pools = [Pool(pool=f"test_pool{i}", slots=1) for i in range(1, 121)]
session.add_all(pools)
session.commit()
result = session.query(Pool).count()
assert result == 121 # accounts for default pool as well
... | class TestGetPoolsPagination(TestBasePoolEndpoints):
@parameterized.expand(
[
# Offset test data
("/api/v1/pools?offset=1", [f"test_pool{i}" for i in range(1, 101)]),
("/api/v1/pools?offset=3", [f"test_pool{i}" for i in range(3, 103)]),
# Limit test data
... | 249 | 189 | 631 | 249 | 0 | raspberryfield/airflow | tests/api_connexion/endpoints/test_pool_endpoint.py | Python | TestGetPoolsPagination | TestGetPoolsPagination | 105 | 157 | 105 | 126 | ff1df0c969801e24fe42af875271894f0e401b64 | bigcode/the-stack | train |
65bf1185b7d8acb9d90b46d4 | train | function | @pytest.fixture(scope="module")
def configured_app(minimal_app_for_api):
app = minimal_app_for_api
create_user(
app, # type: ignore
username="test",
role_name="Test",
permissions=[
(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_POOL),
(permissions.... | @pytest.fixture(scope="module")
def configured_app(minimal_app_for_api):
| app = minimal_app_for_api
create_user(
app, # type: ignore
username="test",
role_name="Test",
permissions=[
(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_POOL),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_POOL),
(permissions.ACT... | permissions
from airflow.utils.session import provide_session
from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
from tests.test_utils.config import conf_vars
from tests.test_utils.db import clear_db_pools
@pytest.fixture(scope="module")
def configured_app(minimal_app_for_api):
| 64 | 64 | 162 | 15 | 48 | raspberryfield/airflow | tests/api_connexion/endpoints/test_pool_endpoint.py | Python | configured_app | configured_app | 30 | 50 | 30 | 31 | e01065d11e499a33475083f04027827aa166b09b | bigcode/the-stack | train |
4a7d549e5183682f7a865c11 | train | class | class TestPatchPool(TestBasePoolEndpoints):
def test_response_200(self, session):
pool = Pool(pool="test_pool", slots=2)
session.add(pool)
session.commit()
response = self.client.patch(
"api/v1/pools/test_pool",
json={"name": "test_pool_a", "slots": 3},
... | class TestPatchPool(TestBasePoolEndpoints):
| def test_response_200(self, session):
pool = Pool(pool="test_pool", slots=2)
session.add(pool)
session.commit()
response = self.client.patch(
"api/v1/pools/test_pool",
json={"name": "test_pool_a", "slots": 3},
environ_overrides={'REMOTE_USER': "tes... |
response = self.client.post(
"api/v1/pools", json=request_json, environ_overrides={'REMOTE_USER': "test"}
)
assert response.status_code == 400
assert {
"detail": error_detail,
"status": 400,
"title": "Bad Request",
"type": EXCE... | 141 | 141 | 471 | 9 | 132 | raspberryfield/airflow | tests/api_connexion/endpoints/test_pool_endpoint.py | Python | TestPatchPool | TestPatchPool | 308 | 367 | 308 | 308 | 6db081a296aeb8a55dde0fa3482200a2237e496d | bigcode/the-stack | train |
5f9477fc9928f7686d634a1d | train | class | class TestGetPool(TestBasePoolEndpoints):
def test_response_200(self, session):
pool_model = Pool(pool="test_pool_a", slots=3)
session.add(pool_model)
session.commit()
response = self.client.get("/api/v1/pools/test_pool_a", environ_overrides={'REMOTE_USER': "test"})
assert re... | class TestGetPool(TestBasePoolEndpoints):
| def test_response_200(self, session):
pool_model = Pool(pool="test_pool_a", slots=3)
session.add(pool_model)
session.commit()
response = self.client.get("/api/v1/pools/test_pool_a", environ_overrides={'REMOTE_USER': "test"})
assert response.status_code == 200
assert {... | session.commit()
result = session.query(Pool).count()
assert result == 200
response = self.client.get("/api/v1/pools?limit=180", environ_overrides={'REMOTE_USER': "test"})
assert response.status_code == 200
assert len(response.json['pools']) == 150
class TestGetPool(TestB... | 79 | 79 | 265 | 9 | 69 | raspberryfield/airflow | tests/api_connexion/endpoints/test_pool_endpoint.py | Python | TestGetPool | TestGetPool | 160 | 189 | 160 | 160 | 1311bce78159f9906905a6b19b8633d6e9018c85 | bigcode/the-stack | train |
6ba8a56ce36df9f97a25bb22 | train | class | class TestModifyDefaultPool(TestBasePoolEndpoints):
def test_delete_400(self):
response = self.client.delete("api/v1/pools/default_pool", environ_overrides={'REMOTE_USER': "test"})
assert response.status_code == 400
assert {
"detail": "Default Pool can't be deleted",
... | class TestModifyDefaultPool(TestBasePoolEndpoints):
| def test_delete_400(self):
response = self.client.delete("api/v1/pools/default_pool", environ_overrides={'REMOTE_USER': "test"})
assert response.status_code == 400
assert {
"detail": "Default Pool can't be deleted",
"status": 400,
"title": "Bad Request",
... | _pool", slots=2)
session.add(pool)
session.commit()
response = self.client.patch(
"api/v1/pools/test_pool", json=request_json, environ_overrides={'REMOTE_USER': "test"}
)
assert response.status_code == 400
assert {
"detail": error_detail,
... | 189 | 189 | 633 | 10 | 179 | raspberryfield/airflow | tests/api_connexion/endpoints/test_pool_endpoint.py | Python | TestModifyDefaultPool | TestModifyDefaultPool | 370 | 455 | 370 | 370 | 39bf23409567d89f4d2acc7f000dd844994a190a | bigcode/the-stack | train |
052f5b8f90f1bf9dbfd61064 | train | class | class TestPostPool(TestBasePoolEndpoints):
def test_response_200(self):
response = self.client.post(
"api/v1/pools",
json={"name": "test_pool_a", "slots": 3},
environ_overrides={'REMOTE_USER': "test"},
)
assert response.status_code == 200
assert {
... | class TestPostPool(TestBasePoolEndpoints):
| def test_response_200(self):
response = self.client.post(
"api/v1/pools",
json={"name": "test_pool_a", "slots": 3},
environ_overrides={'REMOTE_USER': "test"},
)
assert response.status_code == 200
assert {
"name": "test_pool_a",
... | {
"detail": "Pool with name:'invalid_pool' not found",
"status": 404,
"title": "Not Found",
"type": EXCEPTIONS_LINK_MAP[404],
} == response.json
def test_should_raises_401_unauthenticated(self, session):
pool_name = "test_pool"
pool_instance ... | 171 | 171 | 573 | 9 | 161 | raspberryfield/airflow | tests/api_connexion/endpoints/test_pool_endpoint.py | Python | TestPostPool | TestPostPool | 230 | 305 | 230 | 230 | b42b4260d3407f70c642da254ec4a88a0aedbb27 | bigcode/the-stack | train |
75be320d82780cc796497c8f | train | class | class TestBasePoolEndpoints:
@pytest.fixture(autouse=True)
def setup_attrs(self, configured_app) -> None:
self.app = configured_app
self.client = self.app.test_client() # type:ignore
clear_db_pools()
def teardown_method(self) -> None:
clear_db_pools()
| class TestBasePoolEndpoints:
@pytest.fixture(autouse=True)
| def setup_attrs(self, configured_app) -> None:
self.app = configured_app
self.client = self.app.test_client() # type:ignore
clear_db_pools()
def teardown_method(self) -> None:
clear_db_pools()
| role_name="TestNoPermissions") # type: ignore
yield app
delete_user(app, username="test") # type: ignore
delete_user(app, username="test_no_permissions") # type: ignore
class TestBasePoolEndpoints:
@pytest.fixture(autouse=True)
| 64 | 64 | 70 | 15 | 48 | raspberryfield/airflow | tests/api_connexion/endpoints/test_pool_endpoint.py | Python | TestBasePoolEndpoints | TestBasePoolEndpoints | 53 | 61 | 53 | 54 | 55e081fab159fc46fedf465a10f99fd06ba73d21 | bigcode/the-stack | train |
3be65a750aff8e6cec2691ba | train | function | def polyfit(dates, levels, p):
x = matplotlib.dates.date2num(dates)
y = levels
p_coeff = np.polyfit(x-x[0],y,p)
poly = np.poly1d(p_coeff)
d0=x[0]
return poly, d0
| def polyfit(dates, levels, p):
| x = matplotlib.dates.date2num(dates)
y = levels
p_coeff = np.polyfit(x-x[0],y,p)
poly = np.poly1d(p_coeff)
d0=x[0]
return poly, d0
| import matplotlib
import numpy as np
import matplotlib.pyplot as plt
def polyfit(dates, levels, p):
| 24 | 64 | 67 | 10 | 13 | Tim-Bonner-1825/Flood-Warning-System | floodsystem/analysis.py | Python | polyfit | polyfit | 5 | 11 | 5 | 5 | 95f0547575287bcd081f6eced50abdca8121e6f4 | bigcode/the-stack | train |
a8d32bd33ee839bc7d5e1e98 | train | function | def ParseIntBlob64(_hash: str) -> str:
if (len(_hash) % 3 != 0):
raise ValueError(f'Failed to convert {_hash} to Blob 64')
hex_str = ""
i = 0
while i < len(_hash):
num_str = hex(int((str(_hash[i]) + str(_hash[i+1]) + str(_hash[i+2]))))[2:]
if len(num_str) == 1:
num_s... | def ParseIntBlob64(_hash: str) -> str:
| if (len(_hash) % 3 != 0):
raise ValueError(f'Failed to convert {_hash} to Blob 64')
hex_str = ""
i = 0
while i < len(_hash):
num_str = hex(int((str(_hash[i]) + str(_hash[i+1]) + str(_hash[i+2]))))[2:]
if len(num_str) == 1:
num_str = f'0{num_str}'
hex... | numstr = int(_hash[i] + _hash[i+1] + _hash[i+2])
numbers.append(numstr)
i += 3
return int.from_bytes(bytearray(numbers), byteorder='little', signed=False)
def ParseIntBlob64(_hash: str) -> str:
| 64 | 64 | 137 | 13 | 51 | ryryburge/UEManifestReader | UEManifestReader/converter.py | Python | ParseIntBlob64 | ParseIntBlob64 | 44 | 58 | 44 | 44 | e6d329316efc4b24c7797944119f49e0433db605 | bigcode/the-stack | train |
64ccc9012e1c4e074f166fd5 | train | function | def ParseIntBlob32(_hash: str) -> str:
if (4 < (len(_hash) % 3) or len(_hash) % 3 != 0):
raise ValueError(f'Failed to convert {_hash} to Blob 32')
numbers = []
i = 0
while i < len(_hash):
numstr = int(_hash[i] + _hash[i+1] + _hash[i+2])
numbers.append(numstr)
i += 3
... | def ParseIntBlob32(_hash: str) -> str:
| if (4 < (len(_hash) % 3) or len(_hash) % 3 != 0):
raise ValueError(f'Failed to convert {_hash} to Blob 32')
numbers = []
i = 0
while i < len(_hash):
numstr = int(_hash[i] + _hash[i+1] + _hash[i+2])
numbers.append(numstr)
i += 3
return int.from_bytes(bytearray(nu... | ]
data[4] = hex_str[2]
data[5] = hex_str[3]
data[6] = hex_str[0]
data[7] = hex_str[1]
return ''.join(data)
def ParseIntBlob32(_hash: str) -> str:
| 64 | 64 | 127 | 13 | 51 | ryryburge/UEManifestReader | UEManifestReader/converter.py | Python | ParseIntBlob32 | ParseIntBlob32 | 31 | 42 | 31 | 31 | 437c332cf3c88f49c13f4ddc942a7ef204dd1d0d | bigcode/the-stack | train |
97223e74bd0606e41d75bf97 | train | function | def SwapOrder(data: bytes) -> bytes:
hex_str = data.hex()
data = [None] * len(hex_str)
# TODO: Improve this ^
if len(hex_str) == 8:
data[0] = hex_str[6]
data[1] = hex_str[7]
data[2] = hex_str[4]
data[3] = hex_str[5]
data[4] = hex_str[2]
data[5] = hex_str[... | def SwapOrder(data: bytes) -> bytes:
| hex_str = data.hex()
data = [None] * len(hex_str)
# TODO: Improve this ^
if len(hex_str) == 8:
data[0] = hex_str[6]
data[1] = hex_str[7]
data[2] = hex_str[4]
data[3] = hex_str[5]
data[4] = hex_str[2]
data[5] = hex_str[3]
data[6] = hex_str[0]
... | (long >> 8).to_bytes(28,byteorder='little').hex()[:2]
buffer[7] = (long).to_bytes(28,byteorder='little').hex()[:2]
return (''.join(buffer)).upper()
def SwapOrder(data: bytes) -> bytes:
| 64 | 64 | 139 | 10 | 54 | ryryburge/UEManifestReader | UEManifestReader/converter.py | Python | SwapOrder | SwapOrder | 14 | 29 | 14 | 14 | fa72b624c80527dff7331121dc8bda89a12ee8ec | bigcode/the-stack | train |
efd948ea8f6f24363e383e24 | train | function | def ULongToHexHash(long: int):
buffer = [None] * 8
buffer[0] = (long >> 56).to_bytes(28,byteorder='little').hex()[:2]
buffer[1] = (long >> 48).to_bytes(28,byteorder='little').hex()[:2]
buffer[2] = (long >> 40).to_bytes(28,byteorder='little').hex()[:2]
buffer[3] = (long >> 32).to_bytes(28,byteorder='... | def ULongToHexHash(long: int):
| buffer = [None] * 8
buffer[0] = (long >> 56).to_bytes(28,byteorder='little').hex()[:2]
buffer[1] = (long >> 48).to_bytes(28,byteorder='little').hex()[:2]
buffer[2] = (long >> 40).to_bytes(28,byteorder='little').hex()[:2]
buffer[3] = (long >> 32).to_bytes(28,byteorder='little').hex()[:2]
buffer[4... | # -*- coding: utf-8 -*-
def ULongToHexHash(long: int):
| 18 | 72 | 242 | 10 | 8 | ryryburge/UEManifestReader | UEManifestReader/converter.py | Python | ULongToHexHash | ULongToHexHash | 2 | 12 | 2 | 2 | 656498cebaf5ec25a57cf5e3e5363bfcf30ead0e | bigcode/the-stack | train |
dde452e07ae23c8e4267a3e0 | train | class | @dataclasses.dataclass
class SetParameterValue(Command):
parameter_uuid: UUID
value: float
async def do(self, harness):
parameter: Union[
BusParameter, CallbackParameter
] = harness.domain_application.registry[self.parameter_uuid]
await parameter.set_(self.value)
| @dataclasses.dataclass
class SetParameterValue(Command):
| parameter_uuid: UUID
value: float
async def do(self, harness):
parameter: Union[
BusParameter, CallbackParameter
] = harness.domain_application.registry[self.parameter_uuid]
await parameter.set_(self.value)
| aclass
class SetParameterBuffer(Command):
parameter_uuid: UUID
path: str
async def do(self, harness):
parameter: BufferParameter = harness.domain_application.registry[
self.parameter_uuid
]
await parameter.set_(self.path)
@dataclasses.dataclass
class SetParameterValue(Co... | 64 | 64 | 61 | 11 | 53 | josiah-wolf-oberholtzer/tloen | tloen/commands/parameters.py | Python | SetParameterValue | SetParameterValue | 21 | 30 | 21 | 22 | 7d5c42b305d7fd4c8b265e9b0fe6637afb4cbf10 | bigcode/the-stack | train |
e1b5e717b811da4f6eb4bf13 | train | class | @dataclasses.dataclass
class SetParameterBuffer(Command):
parameter_uuid: UUID
path: str
async def do(self, harness):
parameter: BufferParameter = harness.domain_application.registry[
self.parameter_uuid
]
await parameter.set_(self.path)
| @dataclasses.dataclass
class SetParameterBuffer(Command):
| parameter_uuid: UUID
path: str
async def do(self, harness):
parameter: BufferParameter = harness.domain_application.registry[
self.parameter_uuid
]
await parameter.set_(self.path)
| import dataclasses
from typing import Union
from uuid import UUID
from ..bases import Command
from ..domain import BufferParameter, BusParameter, CallbackParameter
@dataclasses.dataclass
class SetParameterBuffer(Command):
| 44 | 64 | 56 | 11 | 32 | josiah-wolf-oberholtzer/tloen | tloen/commands/parameters.py | Python | SetParameterBuffer | SetParameterBuffer | 9 | 18 | 9 | 10 | 75b378bae86d5eaffa77ca0dac5ce3ba2d6a6009 | bigcode/the-stack | train |
146756612cbedccf9e52cf1d | train | function | def transform(events, location):
transformed_events = []
for event in events:
start = datetime.datetime.fromtimestamp(int(event["time"] / 1000)).strftime(
"%Y-%m-%d %H:%M:%SZ"
)
# TODO update to end time
end = datetime.datetime.fromtimestamp(int(event["time"] / 1000)... | def transform(events, location):
| transformed_events = []
for event in events:
start = datetime.datetime.fromtimestamp(int(event["time"] / 1000)).strftime(
"%Y-%m-%d %H:%M:%SZ"
)
# TODO update to end time
end = datetime.datetime.fromtimestamp(int(event["time"] / 1000)).strftime(
"%Y-%m-%d... | import datetime
def transform(events, location):
| 9 | 64 | 205 | 6 | 2 | muxer-dev/event-pipeline | src/transformers/meetup.py | Python | transform | transform | 4 | 35 | 4 | 4 | e5e0e6a772d9fd6376f6196f5667dd6ebd16d718 | bigcode/the-stack | train |
c11bc28100609ae91777d3b8 | train | class | class SentryHandler(logging.Handler, object):
def __init__(self, *args, **kwargs):
client = kwargs.get('client_cls', Client)
if len(args) == 1:
arg = args[0]
if isinstance(arg, six.string_types):
self.client = client(dsn=arg)
elif isinstance(arg, C... | class SentryHandler(logging.Handler, object):
| def __init__(self, *args, **kwargs):
client = kwargs.get('client_cls', Client)
if len(args) == 1:
arg = args[0]
if isinstance(arg, six.string_types):
self.client = client(dsn=arg)
elif isinstance(arg, Client):
self.client = arg
... | """
raven.handlers.logging
~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from __future__ import print_function
import datetime
import logging
import sys
import traceback
from ... | 171 | 256 | 1,009 | 9 | 162 | RAMilewski/airmozilla | vendor-local/lib/python/raven/handlers/logging.py | Python | SentryHandler | SentryHandler | 25 | 164 | 25 | 25 | 449aea27db14a435e7ca78295351e2edd410826e | bigcode/the-stack | train |
3878e17f4a7bff3954f0ee41 | train | function | def qmul(q, r):
"""
Multiply quaternion(s) q with quaternion(s) r.
Expects two equally-sized tensors of shape (*, 4), where * denotes any number of dimensions.
Returns q*r as a tensor of shape (*, 4).
"""
assert q.shape[-1] == 4
assert r.shape[-1] == 4
original_shape = q.shape
# Co... | def qmul(q, r):
| """
Multiply quaternion(s) q with quaternion(s) r.
Expects two equally-sized tensors of shape (*, 4), where * denotes any number of dimensions.
Returns q*r as a tensor of shape (*, 4).
"""
assert q.shape[-1] == 4
assert r.shape[-1] == 4
original_shape = q.shape
# Compute outer prod... | import torch
import numpy as np
def qmul(q, r):
| 15 | 88 | 295 | 7 | 7 | EricLee12138/assignment1 | common/ForwardKinematics.py | Python | qmul | qmul | 5 | 23 | 5 | 5 | 990fe58da7c32f1c6e7525f419a4100a4d42bc0e | bigcode/the-stack | train |
197127ff3721ec81c42cf547 | train | function | def qrot(q, v):
"""
Rotate vector(s) v about the rotation described by quaternion(s) q.
Expects a tensor of shape (*, 4) for q and a tensor of shape (*, 3) for v,
where * denotes any number of dimensions.
Returns a tensor of shape (*, 3).
"""
assert q.shape[-1] == 4
assert v.shape[-1] ==... | def qrot(q, v):
| """
Rotate vector(s) v about the rotation described by quaternion(s) q.
Expects a tensor of shape (*, 4) for q and a tensor of shape (*, 3) for v,
where * denotes any number of dimensions.
Returns a tensor of shape (*, 3).
"""
assert q.shape[-1] == 4
assert v.shape[-1] == 3
assert q.... | z = terms[:, 0, 3] - terms[:, 1, 2] + terms[:, 2, 1] + terms[:, 3, 0]
return torch.stack((w, x, y, z), dim=1).view(original_shape)
def qrot(q, v):
| 65 | 65 | 217 | 7 | 58 | EricLee12138/assignment1 | common/ForwardKinematics.py | Python | qrot | qrot | 26 | 45 | 26 | 26 | a1bb8a133a34a66bd786251a7d3dd1d8e939d67e | bigcode/the-stack | train |
17f98206d2239cd2912d9cef | train | function | def expmap_to_quaternion(e):
# Convert axis-angle rotations (aka exponential maps) to quaternions.
# Stable formula from "Practical Parameterization of Rotations Using the Exponential Map".
# Expects a tensor of shape (*, 3), where * denotes any number of dimensions.
# Returns a tensor of shape (*, 4).
... | def expmap_to_quaternion(e):
# Convert axis-angle rotations (aka exponential maps) to quaternions.
# Stable formula from "Practical Parameterization of Rotations Using the Exponential Map".
# Expects a tensor of shape (*, 3), where * denotes any number of dimensions.
# Returns a tensor of shape (*, 4).
| assert e.shape[-1] == 3
original_shape = list(e.shape)
original_shape[-1] = 4
e = e.reshape(-1, 3)
theta = np.linalg.norm(e, axis=1).reshape(-1, 1)
e = e / (theta + 1e-5)
w = np.cos(0.5 * theta).reshape(-1, 1)
xyz = np.sin(0.5 * theta) * e
return np.concatenate((w, xyz), axis=1... | def expmap_to_quaternion(e):
# Convert axis-angle rotations (aka exponential maps) to quaternions.
# Stable formula from "Practical Parameterization of Rotations Using the Exponential Map".
# Expects a tensor of shape (*, 3), where * denotes any number of dimensions.
# Returns a tensor of shape (*, 4).
| 76 | 64 | 201 | 76 | 0 | EricLee12138/assignment1 | common/ForwardKinematics.py | Python | expmap_to_quaternion | expmap_to_quaternion | 50 | 65 | 50 | 54 | c9043b949f9bb2835e18133bdf6e265305a973b8 | bigcode/the-stack | train |
d684e160170e6fa4171d61f0 | train | class | class ForwardKinematics:
def __init__(self, offsets, parents):
self.offsets = torch.from_numpy(offsets.astype(np.float32))
self.parents = parents
self.num_joint = len(parents)
self.has_children = np.zeros(len(parents)).astype(bool)
for i, parent in enumerate(parents):
... | class ForwardKinematics:
| def __init__(self, offsets, parents):
self.offsets = torch.from_numpy(offsets.astype(np.float32))
self.parents = parents
self.num_joint = len(parents)
self.has_children = np.zeros(len(parents)).astype(bool)
for i, parent in enumerate(parents):
if parent != -1:
... | )).view(original_shape)
# note(yanzhey): Corrected the expmap implementation in Quaternet
# ref: https://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
def expmap_to_quaternion(e):
# Convert axis-angle rotations (aka exponential maps) to quaternions.
# Stable formula f... | 256 | 256 | 1,215 | 5 | 251 | EricLee12138/assignment1 | common/ForwardKinematics.py | Python | ForwardKinematics | ForwardKinematics | 68 | 182 | 68 | 68 | 202af735a3d98cd81b457de1d388f6e2de38ecc3 | bigcode/the-stack | train |
fb754730bf4f746b6ba4bed5 | train | function | @cvt.test('RequestParameters dictionary')
def test_dictionaries():
# Prepare an instance.
input_dict = {
'x': [
{
'y': {
'z': 1
}
}
]
}
rp = RequestParameters(input_dict)
rp.allowed_key = 1
rp.datetime = serialize_datetime(datetime.now())
rp.propagate_and_lock()
# Perform assertions.
wi... | @cvt.test('RequestParameters dictionary')
def test_dictionaries():
# Prepare an instance.
| input_dict = {
'x': [
{
'y': {
'z': 1
}
}
]
}
rp = RequestParameters(input_dict)
rp.allowed_key = 1
rp.datetime = serialize_datetime(datetime.now())
rp.propagate_and_lock()
# Perform assertions.
with cvt.assertion('Lock applies', Immutable):
rp.new_key = 2
with cvt.assertion('Missing ... | class X:
@cached_property
def f(self):
y[0] = not y[0]
x = X(); x.f; x.f
assert y[0]
@cvt.test('RequestParameters dictionary')
def test_dictionaries():
# Prepare an instance.
| 64 | 64 | 177 | 21 | 43 | robinsax/canvas | tests/utils.py | Python | test_dictionaries | test_dictionaries | 42 | 67 | 42 | 44 | 6e24acf802e8ff11b32c66d87e802f64b11239e6 | bigcode/the-stack | train |
40f2f05618ea7c66363ade94 | train | function | @cvt.test('Utilities')
def test_utilities():
with cvt.assertion('Unlooped callback registration'):
registrar = create_callback_registrar()
x = list()
registrar(lambda: x.append(1))
registrar.invoke()
assert len(x) == 1
with cvt.assertion('Looped callback registration'):
registrar = create_callback_reg... | @cvt.test('Utilities')
def test_utilities():
| with cvt.assertion('Unlooped callback registration'):
registrar = create_callback_registrar()
x = list()
registrar(lambda: x.append(1))
registrar.invoke()
assert len(x) == 1
with cvt.assertion('Looped callback registration'):
registrar = create_callback_registrar(loop_arg=True)
registrar(lambda x: x... | packages.
'''
from datetime import datetime
import canvas.tests as cvt
from canvas.exceptions import Immutable, BadRequest
from canvas.utils import create_callback_registrar, cached_property
from canvas.dictionaries import RequestParameters
from canvas.json_io import serialize_datetime
@cvt.test('Utilities')
def te... | 64 | 64 | 170 | 12 | 51 | robinsax/canvas | tests/utils.py | Python | test_utilities | test_utilities | 15 | 40 | 15 | 16 | 7dff611b0c9119d106279a8e744767f491be244b | bigcode/the-stack | train |
5997cb4ae831c94b6222ef43 | train | function | def _normalize_store_arg(store, clobber=False, storage_options=None):
return normalize_store_arg(store, clobber=clobber, default=MemoryStore,
storage_options=storage_options)
| def _normalize_store_arg(store, clobber=False, storage_options=None):
| return normalize_store_arg(store, clobber=clobber, default=MemoryStore,
storage_options=storage_options)
| # Ensure groups needed for `dest` exist.
if "/" in dest:
self.require_group("/" + dest.rsplit("/", 1)[0])
self._write_op(self._move_nosync, source, dest)
def _normalize_store_arg(store, clobber=False, storage_options=None):
| 64 | 64 | 43 | 16 | 48 | srinivas32/zarr-python | zarr/hierarchy.py | Python | _normalize_store_arg | _normalize_store_arg | 1,038 | 1,040 | 1,038 | 1,038 | 25dbdb56d1b8904765b8e9c93352a9cc847a7e8d | bigcode/the-stack | train |
640561cf1d43ed97ed9382d7 | train | class | class Group(MutableMapping):
"""Instantiate a group from an initialized store.
Parameters
----------
store : MutableMapping
Group store, already initialized.
If the Group is used in a context manager, and the store has a ``close`` method,
it will be called on exit.
path : st... | class Group(MutableMapping):
| """Instantiate a group from an initialized store.
Parameters
----------
store : MutableMapping
Group store, already initialized.
If the Group is used in a context manager, and the store has a ``close`` method,
it will be called on exit.
path : string, optional
Group ... | from collections.abc import MutableMapping
from itertools import islice
import numpy as np
from zarr.attrs import Attributes
from zarr.core import Array
from zarr.creation import (array, create, empty, empty_like, full, full_like,
normalize_store_arg, ones, ones_like, zeros,
... | 175 | 256 | 7,752 | 6 | 169 | srinivas32/zarr-python | zarr/hierarchy.py | Python | Group | Group | 25 | 1,035 | 25 | 25 | 020905d786e173dd3603088e5c96c1e714a1e2cb | bigcode/the-stack | train |
a0eb82bb0b669a65806c4f4f | train | function | def open_group(store=None, mode='a', cache_attrs=True, synchronizer=None, path=None,
chunk_store=None, storage_options=None):
"""Open a group using file-mode-like semantics.
Parameters
----------
store : MutableMapping or string, optional
Store or path to directory in file system... | def open_group(store=None, mode='a', cache_attrs=True, synchronizer=None, path=None,
chunk_store=None, storage_options=None):
| """Open a group using file-mode-like semantics.
Parameters
----------
store : MutableMapping or string, optional
Store or path to directory in file system or name of zip file.
mode : {'r', 'r+', 'a', 'w', 'w-'}, optional
Persistence mode: 'r' means read only (must exist); 'r+' means... | zarr.hierarchy.Group
Examples
--------
Create a group in memory::
>>> import zarr
>>> g = zarr.group()
>>> g
<zarr.hierarchy.Group '/'>
Create a group with a different store::
>>> store = zarr.DirectoryStore('data/example.zarr')
>>> g = zarr.group(sto... | 219 | 219 | 732 | 30 | 189 | srinivas32/zarr-python | zarr/hierarchy.py | Python | open_group | open_group | 1,101 | 1,185 | 1,101 | 1,102 | f01d98de3af1bade34f40a338aef02347caa7019 | bigcode/the-stack | train |
d36c09965da12eecd071405e | train | function | def group(store=None, overwrite=False, chunk_store=None,
cache_attrs=True, synchronizer=None, path=None):
"""Create a group.
Parameters
----------
store : MutableMapping or string, optional
Store or path to directory in file system.
overwrite : bool, optional
If True, dele... | def group(store=None, overwrite=False, chunk_store=None,
cache_attrs=True, synchronizer=None, path=None):
| """Create a group.
Parameters
----------
store : MutableMapping or string, optional
Store or path to directory in file system.
overwrite : bool, optional
If True, delete any pre-existing data in `store` at `path` before
creating the group.
chunk_store : MutableMapping, o... | )
# Ensure groups needed for `dest` exist.
if "/" in dest:
self.require_group("/" + dest.rsplit("/", 1)[0])
self._write_op(self._move_nosync, source, dest)
def _normalize_store_arg(store, clobber=False, storage_options=None):
return normalize_store_arg(store, clobber=clobber,... | 117 | 117 | 390 | 24 | 93 | srinivas32/zarr-python | zarr/hierarchy.py | Python | group | group | 1,043 | 1,098 | 1,043 | 1,044 | f3f04363ec45ee55637f3e1107cda392ead5aca8 | bigcode/the-stack | train |
1fb5e75862dc7de3cf2efe5d | train | function | def _convert_param(name: str, bound: BoundArguments, param: Parameter) -> Union[T, Tuple[T]]:
if isinstance(param.annotation, Callable) and param.annotation != Parameter.empty:
func = param.annotation
else:
def func(x): return x
if param.kind == Parameter.VAR_POSITIONAL:
return *map(... | def _convert_param(name: str, bound: BoundArguments, param: Parameter) -> Union[T, Tuple[T]]:
| if isinstance(param.annotation, Callable) and param.annotation != Parameter.empty:
func = param.annotation
else:
def func(x): return x
if param.kind == Parameter.VAR_POSITIONAL:
return *map(func, bound.arguments[name]),
elif param.kind == Parameter.VAR_KEYWORD:
return {k:... | , BoundArguments
from typing import Callable, TypeVar, Tuple, Union
from functools import wraps, WRAPPER_ASSIGNMENTS
__all__ = ['convert']
T = TypeVar('T')
def _convert_param(name: str, bound: BoundArguments, param: Parameter) -> Union[T, Tuple[T]]:
| 64 | 64 | 117 | 24 | 40 | jemand2001/python-utils | utils/decorators/convert.py | Python | _convert_param | _convert_param | 12 | 22 | 12 | 12 | 1f787a8e0471f18e1d1fb6f6345ba8f6557404ee | bigcode/the-stack | train |
7170d841f302a89c24c80aa3 | train | function | def convert(f: Callable):
"""The `convert` decorator.
This decorator allows you to implicitly convert arguments to a function.
It treats the parameter annotations as converters, if they're callable;
otherwise it just passes the parameter through.
# variadic arguments
If the decorator finds a v... | def convert(f: Callable):
| """The `convert` decorator.
This decorator allows you to implicitly convert arguments to a function.
It treats the parameter annotations as converters, if they're callable;
otherwise it just passes the parameter through.
# variadic arguments
If the decorator finds a variadic parameter with an ... | Var, Tuple, Union
from functools import wraps, WRAPPER_ASSIGNMENTS
__all__ = ['convert']
T = TypeVar('T')
def _convert_param(name: str, bound: BoundArguments, param: Parameter) -> Union[T, Tuple[T]]:
if isinstance(param.annotation, Callable) and param.annotation != Parameter.empty:
func = param.annota... | 153 | 153 | 511 | 6 | 147 | jemand2001/python-utils | utils/decorators/convert.py | Python | convert | convert | 25 | 81 | 25 | 25 | 64db753e072bbae0dcbdad3fd176eb1fa3052ee8 | bigcode/the-stack | train |
3c9bdba46fdd872cb9d1f609 | train | function | @pytest.fixture(scope="function")
def test_attributes():
yield {
"revision_id": 1,
"hardware_id": 1,
"mode_id": 1,
"mechanism_id": 1,
"load_id": 1,
"test_id": 1,
"description": "",
"boundary_conditions": "",
"remarks": "",
}
| @pytest.fixture(scope="function")
def test_attributes():
| yield {
"revision_id": 1,
"hardware_id": 1,
"mode_id": 1,
"mechanism_id": 1,
"load_id": 1,
"test_id": 1,
"description": "",
"boundary_conditions": "",
"remarks": "",
}
| _test_method_2.boundary_conditions = "Sands"
_test_method_2.remarks = ""
DAO = MockDAO()
DAO.table = [
_test_method_1,
_test_method_2,
]
yield DAO
@pytest.fixture(scope="function")
def test_attributes():
| 64 | 64 | 80 | 10 | 53 | TahaEntezari/ramstk | tests/models/programdb/test_method/conftest.py | Python | test_attributes | test_attributes | 42 | 54 | 42 | 43 | 1b25aaa9f33b50b8760ebdb6ceb75ba03a6485f3 | bigcode/the-stack | train |
1a50ef680a5b5c5aed2e3f01 | train | function | @pytest.fixture(scope="function")
def test_recordmodel(mock_program_dao):
"""Get a record model instance for each test function."""
dut = mock_program_dao.do_select_all(RAMSTKTestMethodRecord, _all=False)
yield dut
# Delete the device under test.
del dut
| @pytest.fixture(scope="function")
def test_recordmodel(mock_program_dao):
| """Get a record model instance for each test function."""
dut = mock_program_dao.do_select_all(RAMSTKTestMethodRecord, _all=False)
yield dut
# Delete the device under test.
del dut
| mode_id": 1,
"mechanism_id": 1,
"load_id": 1,
"test_id": 1,
"description": "",
"boundary_conditions": "",
"remarks": "",
}
@pytest.fixture(scope="function")
def test_recordmodel(mock_program_dao):
| 64 | 64 | 65 | 15 | 49 | TahaEntezari/ramstk | tests/models/programdb/test_method/conftest.py | Python | test_recordmodel | test_recordmodel | 57 | 65 | 57 | 58 | 6c87c708ed4230bd10c354a6111de544451604ed | bigcode/the-stack | train |
019a85b73f21738185aee3f4 | train | function | @pytest.fixture
def mock_program_dao(monkeypatch):
_test_method_1 = RAMSTKTestMethodRecord()
_test_method_1.revision_id = 1
_test_method_1.hardware_id = 1
_test_method_1.mode_id = 1
_test_method_1.mechanism_id = 1
_test_method_1.load_id = 1
_test_method_1.test_id = 1
_test_method_1.descr... | @pytest.fixture
def mock_program_dao(monkeypatch):
| _test_method_1 = RAMSTKTestMethodRecord()
_test_method_1.revision_id = 1
_test_method_1.hardware_id = 1
_test_method_1.mode_id = 1
_test_method_1.mechanism_id = 1
_test_method_1.load_id = 1
_test_method_1.test_id = 1
_test_method_1.description = "Test Test Method #1"
_test_method_1.b... | # Third Party Imports
import pytest
from mocks import MockDAO
# RAMSTK Package Imports
from ramstk.models import RAMSTKTestMethodRecord
@pytest.fixture
def mock_program_dao(monkeypatch):
| 45 | 89 | 299 | 12 | 32 | TahaEntezari/ramstk | tests/models/programdb/test_method/conftest.py | Python | mock_program_dao | mock_program_dao | 9 | 39 | 9 | 10 | 89cadd7adc97834c328309af41910ab8623b5232 | bigcode/the-stack | train |
58e6565de143d77194d76c04 | train | function | def render_response_message(response):
try:
tmpl = get_template('requests_tracker/response.tmpl')
context = {'response': response}
return tmpl.render(context)
except Exception:
return response.text if response else ""
| def render_response_message(response):
| try:
tmpl = get_template('requests_tracker/response.tmpl')
context = {'response': response}
return tmpl.render(context)
except Exception:
return response.text if response else ""
| :
tmpl = get_template('requests_tracker/request.tmpl')
context = {
'prep': prepared_request,
'host': parse.urlsplit(prepared_request.url).netloc,
}
return tmpl.render(context)
except Exception as e:
return str(e)
def render_response_message(response):
| 64 | 64 | 48 | 6 | 58 | ZhuoZhuoCrayon/bk-nodeman | requests_tracker/utils/http_message.py | Python | render_response_message | render_response_message | 21 | 27 | 21 | 21 | 27ed192720a71b84cdc605f7e8549872c1e359df | bigcode/the-stack | train |
f01ccfee4ac7e80516faf168 | train | function | def render_request_message(prepared_request):
try:
tmpl = get_template('requests_tracker/request.tmpl')
context = {
'prep': prepared_request,
'host': parse.urlsplit(prepared_request.url).netloc,
}
return tmpl.render(context)
except Exception as e:
... | def render_request_message(prepared_request):
| try:
tmpl = get_template('requests_tracker/request.tmpl')
context = {
'prep': prepared_request,
'host': parse.urlsplit(prepared_request.url).netloc,
}
return tmpl.render(context)
except Exception as e:
return str(e)
| """
requests_tracker.utils.http_message
===================================
"""
from django.template.loader import get_template
from six.moves.urllib import parse
def render_request_message(prepared_request):
| 34 | 64 | 68 | 8 | 25 | ZhuoZhuoCrayon/bk-nodeman | requests_tracker/utils/http_message.py | Python | render_request_message | render_request_message | 9 | 18 | 9 | 9 | 02812852214dab0ffc0cef0d490200fb8d94d4ae | bigcode/the-stack | train |
75c7d6400ee0d33a1352d588 | train | class | class JwtTest(parameterized.TestCase):
def test_genenerate_token_generates_example(self):
token = generate_token(
'{"typ":"JWT",\r\n "alg":"HS256"}',
'{"iss":"joe",\r\n "exp":1300819380,\r\n '
'"http://example.com/is_root":true}')
self.assertEqual(token, EXAMPLE_TOKEN)
@parameteriz... | class JwtTest(parameterized.TestCase):
| def test_genenerate_token_generates_example(self):
token = generate_token(
'{"typ":"JWT",\r\n "alg":"HS256"}',
'{"iss":"joe",\r\n "exp":1300819380,\r\n '
'"http://example.com/is_root":true}')
self.assertEqual(token, EXAMPLE_TOKEN)
@parameterized.parameters(SUPPORTED_LANGUAGES)
def... | .status = tink_pb2.ENABLED
key.key_id = 123
key.output_prefix_type = tink_pb2.RAW
keyset.primary_key_id = 123
keyset_handle = cleartext_keyset_handle.from_keyset(keyset)
return keyset_handle.primitive(mac.Mac)
def setUpModule():
global KEYSET, MAC
jwt.register_jwt_mac()
mac.register()
testing_server... | 255 | 256 | 4,409 | 8 | 247 | Matir/tink | testing/cross_language/jwt_validation_test.py | Python | JwtTest | JwtTest | 122 | 526 | 122 | 123 | 7bb8c1b6871e3f8a17d36847785e6be0c26c138a | bigcode/the-stack | train |
25cc624ba875810383296e43 | train | function | def _keyset() -> bytes:
jwt_hmac_key = jwt_hmac_pb2.JwtHmacKey(
version=0,
algorithm=jwt_hmac_pb2.HS256,
key_value=base64.urlsafe_b64decode(KEY_VALUE))
keyset = tink_pb2.Keyset()
key = keyset.key.add()
key.key_data.type_url = ('type.googleapis.com/google.crypto.tink.JwtHmacKey')
key.key_data... | def _keyset() -> bytes:
| jwt_hmac_key = jwt_hmac_pb2.JwtHmacKey(
version=0,
algorithm=jwt_hmac_pb2.HS256,
key_value=base64.urlsafe_b64decode(KEY_VALUE))
keyset = tink_pb2.Keyset()
key = keyset.key.add()
key.key_data.type_url = ('type.googleapis.com/google.crypto.tink.JwtHmacKey')
key.key_data.value = jwt_hmac_key.Se... | None
EMPTY_VALIDATOR = jwt.new_validator(allow_missing_expiration=True)
def _base64_encode(data: bytes) -> bytes:
"""Does a URL-safe base64 encoding without padding."""
return base64.urlsafe_b64encode(data).rstrip(b'=')
def _keyset() -> bytes:
| 64 | 64 | 174 | 8 | 55 | Matir/tink | testing/cross_language/jwt_validation_test.py | Python | _keyset | _keyset | 61 | 75 | 61 | 61 | be850d93e57b85d76cfa73087a6ecdebaf94e3f2 | bigcode/the-stack | train |
77f259ce18e4e64ec84d9ccf | train | function | def setUpModule():
global KEYSET, MAC
jwt.register_jwt_mac()
mac.register()
testing_servers.start('jwt')
KEYSET = _keyset()
MAC = _mac()
| def setUpModule():
| global KEYSET, MAC
jwt.register_jwt_mac()
mac.register()
testing_servers.start('jwt')
KEYSET = _keyset()
MAC = _mac()
| ABLED
key.key_id = 123
key.output_prefix_type = tink_pb2.RAW
keyset.primary_key_id = 123
keyset_handle = cleartext_keyset_handle.from_keyset(keyset)
return keyset_handle.primitive(mac.Mac)
def setUpModule():
| 64 | 64 | 44 | 5 | 59 | Matir/tink | testing/cross_language/jwt_validation_test.py | Python | setUpModule | setUpModule | 96 | 102 | 96 | 96 | a66ae219f43b4d961e4141cda3ba86a98237c5f3 | bigcode/the-stack | train |
92efc6a7980b04162b2fff5a | train | function | def tearDownModule():
testing_servers.stop()
| def tearDownModule():
| testing_servers.stop()
| set(keyset)
return keyset_handle.primitive(mac.Mac)
def setUpModule():
global KEYSET, MAC
jwt.register_jwt_mac()
mac.register()
testing_servers.start('jwt')
KEYSET = _keyset()
MAC = _mac()
def tearDownModule():
| 64 | 64 | 10 | 5 | 59 | Matir/tink | testing/cross_language/jwt_validation_test.py | Python | tearDownModule | tearDownModule | 105 | 106 | 105 | 105 | c02d3c0536eb89eb123da4ed3aeaca9636a103b3 | bigcode/the-stack | train |
ece63c9f5e775bc50099e8f7 | train | function | def _base64_encode(data: bytes) -> bytes:
"""Does a URL-safe base64 encoding without padding."""
return base64.urlsafe_b64encode(data).rstrip(b'=')
| def _base64_encode(data: bytes) -> bytes:
| """Does a URL-safe base64 encoding without padding."""
return base64.urlsafe_b64encode(data).rstrip(b'=')
| gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow==')
KEYSET = None
MAC = None
EMPTY_VALIDATOR = jwt.new_validator(allow_missing_expiration=True)
def _base64_encode(data: bytes) -> bytes:
| 64 | 64 | 40 | 12 | 52 | Matir/tink | testing/cross_language/jwt_validation_test.py | Python | _base64_encode | _base64_encode | 56 | 58 | 56 | 56 | 39f1db5b45cd775144ed5846f508a3e2f3e86e9e | bigcode/the-stack | train |
7a60aaed3a10bac00c5e3d82 | train | function | def _mac() -> mac.Mac:
hmac_key = hmac_pb2.HmacKey(
version=0, key_value=base64.urlsafe_b64decode(KEY_VALUE))
hmac_key.params.hash = common_pb2.SHA256
hmac_key.params.tag_size = 32
keyset = tink_pb2.Keyset()
key = keyset.key.add()
key.key_data.type_url = ('type.googleapis.com/google.crypto.tink.HmacKe... | def _mac() -> mac.Mac:
| hmac_key = hmac_pb2.HmacKey(
version=0, key_value=base64.urlsafe_b64decode(KEY_VALUE))
hmac_key.params.hash = common_pb2.SHA256
hmac_key.params.tag_size = 32
keyset = tink_pb2.Keyset()
key = keyset.key.add()
key.key_data.type_url = ('type.googleapis.com/google.crypto.tink.HmacKey')
key.key_data.valu... | Data.SYMMETRIC
key.status = tink_pb2.ENABLED
key.key_id = 123
key.output_prefix_type = tink_pb2.RAW
keyset.primary_key_id = 123
return keyset.SerializeToString()
def _mac() -> mac.Mac:
| 64 | 64 | 201 | 9 | 55 | Matir/tink | testing/cross_language/jwt_validation_test.py | Python | _mac | _mac | 78 | 93 | 78 | 78 | 113c9289750662b452d80965bd418f9d235e859f | bigcode/the-stack | train |
3f855b0d35779da84df225ff | train | function | def generate_token(header: Text, payload: Text) -> Text:
"""Generates tokens with valid MACs."""
return generate_token_from_bytes(
header.encode('utf8'), payload.encode('utf8'))
| def generate_token(header: Text, payload: Text) -> Text:
| """Generates tokens with valid MACs."""
return generate_token_from_bytes(
header.encode('utf8'), payload.encode('utf8'))
| base64_encode(header) + b'.' + _base64_encode(payload))
mac_value = MAC.compute_mac(unsigned_compact)
return (unsigned_compact + b'.' + _base64_encode(mac_value)).decode('utf8')
def generate_token(header: Text, payload: Text) -> Text:
| 64 | 64 | 44 | 14 | 50 | Matir/tink | testing/cross_language/jwt_validation_test.py | Python | generate_token | generate_token | 116 | 119 | 116 | 116 | 8e26dcb9db5d92cfc6051c5f4ef3a543197f754e | bigcode/the-stack | train |
876d30af2c083772f449ca0b | train | function | def generate_token_from_bytes(header: bytes, payload: bytes) -> Text:
"""Generates tokens from bytes with valid MACs."""
unsigned_compact = (_base64_encode(header) + b'.' + _base64_encode(payload))
mac_value = MAC.compute_mac(unsigned_compact)
return (unsigned_compact + b'.' + _base64_encode(mac_value)).decode(... | def generate_token_from_bytes(header: bytes, payload: bytes) -> Text:
| """Generates tokens from bytes with valid MACs."""
unsigned_compact = (_base64_encode(header) + b'.' + _base64_encode(payload))
mac_value = MAC.compute_mac(unsigned_compact)
return (unsigned_compact + b'.' + _base64_encode(mac_value)).decode('utf8')
| global KEYSET, MAC
jwt.register_jwt_mac()
mac.register()
testing_servers.start('jwt')
KEYSET = _keyset()
MAC = _mac()
def tearDownModule():
testing_servers.stop()
def generate_token_from_bytes(header: bytes, payload: bytes) -> Text:
| 64 | 64 | 84 | 16 | 48 | Matir/tink | testing/cross_language/jwt_validation_test.py | Python | generate_token_from_bytes | generate_token_from_bytes | 109 | 113 | 109 | 109 | c97e824e4b6201959b088eae831e183231c7894c | bigcode/the-stack | train |
b4f72a47140fcc28e33119b4 | train | function | def get_action_size_from_env(env: gym.Env) -> int:
if isinstance(env.action_space, Discrete):
return cast(int, env.action_space.n)
return cast(int, env.action_space.shape[0])
| def get_action_size_from_env(env: gym.Env) -> int:
| if isinstance(env.action_space, Discrete):
return cast(int, env.action_space.n)
return cast(int, env.action_space.shape[0])
| from typing import cast
import gym
from gym.spaces import Discrete
def get_action_size_from_env(env: gym.Env) -> int:
| 30 | 64 | 46 | 14 | 15 | ningyixue/AIPI530_Final_Project | d3rlpy/online/utility.py | Python | get_action_size_from_env | get_action_size_from_env | 7 | 10 | 7 | 7 | 2e5b13b2c9b71af9edc45227c806ba118fe96921 | bigcode/the-stack | train |
bf388495deee8b33bc3c7c2e | train | function | def add(
dispatcher,
thread_pool,
consensus_proxy,
consensus_notifier,
):
handler = handlers.ConsensusRegisterHandler(
consensus_proxy, consensus_notifier)
dispatcher.add_handler(handler.request_type, handler, thread_pool)
handler = handlers.ConsensusSendToHandler(c... | def add(
dispatcher,
thread_pool,
consensus_proxy,
consensus_notifier,
):
| handler = handlers.ConsensusRegisterHandler(
consensus_proxy, consensus_notifier)
dispatcher.add_handler(handler.request_type, handler, thread_pool)
handler = handlers.ConsensusSendToHandler(consensus_proxy)
dispatcher.add_handler(handler.request_type, handler, thread_pool)
handler = handl... | you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES ... | 134 | 134 | 447 | 20 | 113 | hariharan-avs/sawtooth-core | validator/sawtooth_validator/server/consensus_handlers.py | Python | add | add | 19 | 74 | 19 | 25 | 0152da6fbbac5bcf30b855bd7ca3a90dc6280dc7 | bigcode/the-stack | train |
a93444a7e7e30b7ec6e288a2 | train | function | def get_data(
file_name: pd.DataFrame = "../data/WA_Fn-UseC_-Telco-Customer-Churn.csv", save=False
) -> pd.DataFrame:
"""Reads in the data from the specified file and returns a pandas dataframe.
Args:
file_name (pd.DataFrame, optional): Data csv file. Defaults to '../data/WA_Fn-UseC_-Telco-Customer... | def get_data(
file_name: pd.DataFrame = "../data/WA_Fn-UseC_-Telco-Customer-Churn.csv", save=False
) -> pd.DataFrame:
| """Reads in the data from the specified file and returns a pandas dataframe.
Args:
file_name (pd.DataFrame, optional): Data csv file. Defaults to '../data/WA_Fn-UseC_-Telco-Customer-Churn.csv'.
save (bool, optional): Whether to save the generated train and test file to csv. Defaults to False.
... | import pandas as pd
import os
from sklearn.model_selection import train_test_split
def get_data(
file_name: pd.DataFrame = "../data/WA_Fn-UseC_-Telco-Customer-Churn.csv", save=False
) -> pd.DataFrame:
| 56 | 108 | 361 | 39 | 16 | ashishthomaschempolil/Telco-customer-churn | utils/get_data.py | Python | get_data | get_data | 6 | 43 | 6 | 8 | 40b04444ce1264480e0b5a21d66d5b4bd765ce30 | bigcode/the-stack | train |
d4c480500e45bcddacfd438c | train | class | class TestProductPriceAttributes(unittest.TestCase):
""" ProductPriceAttributes unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testProductPriceAttributes(self):
"""
Test ProductPriceAttributes
"""
model = kinow_client.models.prod... | class TestProductPriceAttributes(unittest.TestCase):
| """ ProductPriceAttributes unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testProductPriceAttributes(self):
"""
Test ProductPriceAttributes
"""
model = kinow_client.models.product_price_attributes.ProductPriceAttributes()
| ://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kinow_client
from kinow_client.rest import ApiException
from kinow_client.models.product_price_attributes import ProductPriceAttributes
class TestProductPriceAttributes(unittest.TestC... | 64 | 64 | 69 | 9 | 54 | kinow-io/kinow-python-sdk | test/test_product_price_attributes.py | Python | TestProductPriceAttributes | TestProductPriceAttributes | 25 | 38 | 25 | 25 | 3b6bf59e90b8bf7243826d1a5a7cafca233dcc7c | bigcode/the-stack | train |
21ac19e8ac9710f0a875e297 | train | class | class CustomFieldServiceTest(unittest.TestCase):
"""Unittest suite for CustomFieldService."""
client.debug = False
loaded = False
def setUp(self):
"""Prepare unittest."""
if not self.__class__.loaded:
advertiser_id = util.CreateTestAdvertiser(
client, SERVER_V201211, VERSION_V201211)
... | class CustomFieldServiceTest(unittest.TestCase):
| """Unittest suite for CustomFieldService."""
client.debug = False
loaded = False
def setUp(self):
"""Prepare unittest."""
if not self.__class__.loaded:
advertiser_id = util.CreateTestAdvertiser(
client, SERVER_V201211, VERSION_V201211)
trafficker_id = util.GetTrafficker(
... | _options
from examples.adspygoogle.dfp.v201211.custom_field_service import create_custom_fields
from examples.adspygoogle.dfp.v201211.custom_field_service import deactivate_all_line_item_custom_fields
from examples.adspygoogle.dfp.v201211.custom_field_service import get_all_custom_fields
from examples.adspygoogle.dfp.v... | 189 | 189 | 631 | 9 | 179 | krux/adspygoogle | tests/adspygoogle/dfp/v201211/custom_field_service_unittest.py | Python | CustomFieldServiceTest | CustomFieldServiceTest | 41 | 107 | 41 | 41 | a14fe12b734b779b0fa3f0022623f50fa2ddee36 | bigcode/the-stack | train |
d94f5fd4d32bd8ecf12e0287 | train | function | @pytest.mark.parametrize("word,is_done,priority", [
(word, is_done, priority)
for word in ['A', '内容', '']
for is_done in ['true', 'false', True, False]
for priority in ['high', 'medium', 'low']
])
def test_existing_task_and_requested_by_task_owner(word, is_done, priority, context, ulid_mock):
event ... | @pytest.mark.parametrize("word,is_done,priority", [
(word, is_done, priority)
for word in ['A', '内容', '']
for is_done in ['true', 'false', True, False]
for priority in ['high', 'medium', 'low']
])
def test_existing_task_and_requested_by_task_owner(word, is_done, priority, context, ulid_mock):
| event = {
"resource": "/task/",
"path": "/task",
"httpMethod": 'POST',
"headers": {},
"multiValueHeaders": {},
"queryStringParameters": None,
"multiValueQueryStringParameters": None,
"pathParameters": {},
"stageVariables": None,
"reques... | import pytest
from datetime import datetime
from create import lambda_handler
import boto3
import os
import json
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['TABLE_NAME'])
# ------------------------------------------
# valid pattern
# ----------------------------------------... | 140 | 159 | 531 | 83 | 57 | kohski/serverless_todo | function/tests/testTask/test_create.py | Python | test_existing_task_and_requested_by_task_owner | test_existing_task_and_requested_by_task_owner | 16 | 74 | 16 | 22 | f8d18c4ee8b3a46c378688e0012b788d8572a0e5 | bigcode/the-stack | train |
4fece408e38ce23edbd160f2 | train | function | @pytest.fixture(params=INVALID_PAYLOAD_LIST)
def test_raise_invalid_case(request, invalid_event, context, ulid_mock):
event = {
"resource": "/task/",
"path": "/task",
"httpMethod": 'POST',
"headers": {},
"multiValueHeaders": {},
"queryStringParameters": None,
... | @pytest.fixture(params=INVALID_PAYLOAD_LIST)
def test_raise_invalid_case(request, invalid_event, context, ulid_mock):
| event = {
"resource": "/task/",
"path": "/task",
"httpMethod": 'POST',
"headers": {},
"multiValueHeaders": {},
"queryStringParameters": None,
"multiValueQueryStringParameters": None,
"pathParameters": {},
"stageVariables": None,
"reques... | 'Task:ABCDEFGHIJKLMNOPQRSTUVW999',
'meta': 'latest'
}
)
assert 'Item' in item
# ------------------------------------------
# invalid pattern
# ------------------------------------------
INVALID_PAYLOAD_LIST = [
{
"title": ""
},
{
"title": None
... | 148 | 148 | 495 | 25 | 123 | kohski/serverless_todo | function/tests/testTask/test_create.py | Python | test_raise_invalid_case | test_raise_invalid_case | 104 | 150 | 104 | 105 | 2fee355fb2044805179a18bb8f60e873f945b325 | bigcode/the-stack | train |
d0491cc900bd87cf2cc3efcb | train | function | def _adjust_config():
vega.get_quota().adjuest_pipeline_by_runtime(UserConfig().data)
| def _adjust_config():
| vega.get_quota().adjuest_pipeline_by_runtime(UserConfig().data)
| logging.info(" task id: {}".format(General.task.task_id))
logging.info("-" * 48)
logger.info("configure: %s", json.dumps(UserConfig().data, indent=4))
logging.info("-" * 48)
Pipeline().run()
def _adjust_config():
| 64 | 64 | 23 | 5 | 59 | zjzh/vega | vega/core/run.py | Python | _adjust_config | _adjust_config | 75 | 76 | 75 | 75 | 3765c652a6a7b32e957a10ca99120a65b15a1b55 | bigcode/the-stack | train |
79aadbc1ed9bb7dbf8ffa649 | train | function | def init_cluster_args():
"""Initialize local_cluster."""
if not General.cluster.master_ip:
master_ip = '127.0.0.1'
General.cluster.master_ip = master_ip
env = Config({
"init_method": "tcp://{}:{}".format(master_ip, General.cluster.listen_port),
"world_size": 1,
... | def init_cluster_args():
| """Initialize local_cluster."""
if not General.cluster.master_ip:
master_ip = '127.0.0.1'
General.cluster.master_ip = master_ip
env = Config({
"init_method": "tcp://{}:{}".format(master_ip, General.cluster.listen_port),
"world_size": 1,
"rank": 0
... | vega.get_quota().adjuest_pipeline_by_runtime(UserConfig().data)
@lazy
def env_args(args=None):
"""Call lazy function return args.
:param args: args need to save and parse
:return: args
"""
return args
def init_cluster_args():
| 64 | 64 | 175 | 5 | 58 | zjzh/vega | vega/core/run.py | Python | init_cluster_args | init_cluster_args | 89 | 109 | 89 | 89 | 280de4542b4469161c683ae427aa18a303556197 | bigcode/the-stack | train |
76c63f435dc8aa5b891205cd | train | function | def run(cfg_path):
"""Run vega automl.
:param cfg_path: config path.
"""
if sys.version_info < (3, 6):
sys.exit('Sorry, Python < 3.6 is not supported.')
_init_env(cfg_path)
_adjust_config()
_run_pipeline()
| def run(cfg_path):
| """Run vega automl.
:param cfg_path: config path.
"""
if sys.version_info < (3, 6):
sys.exit('Sorry, Python < 3.6 is not supported.')
_init_env(cfg_path)
_adjust_config()
_run_pipeline()
|
from vega.common import Config, UserConfig
from vega.common import TaskOps
from vega import set_backend
from vega.common.general import General
from vega.core.pipeline.conf import PipelineConfig
from .pipeline.pipeline import Pipeline
logger = logging.getLogger(__name__)
def run(cfg_path):
| 64 | 64 | 69 | 5 | 59 | zjzh/vega | vega/core/run.py | Python | run | run | 34 | 43 | 34 | 34 | ba87590b24082c20556cd27e43ef276a60caaa94 | bigcode/the-stack | train |
b8ee88c0cc7154a7c31607e3 | train | function | def _run_pipeline():
"""Run pipeline."""
logging.info("-" * 48)
logging.info(" task id: {}".format(General.task.task_id))
logging.info("-" * 48)
logger.info("configure: %s", json.dumps(UserConfig().data, indent=4))
logging.info("-" * 48)
Pipeline().run()
| def _run_pipeline():
| """Run pipeline."""
logging.info("-" * 48)
logging.info(" task id: {}".format(General.task.task_id))
logging.info("-" * 48)
logger.info("configure: %s", json.dumps(UserConfig().data, indent=4))
logging.info("-" * 48)
Pipeline().run()
| ",
log_path=TaskOps().local_log_path)
General.env = env_args()
if not General.env:
General.env = init_cluster_args()
setattr(PipelineConfig, "steps", UserConfig().data.pipeline)
set_backend(General.backend, General.device_category)
def _run_pipeline():
| 64 | 64 | 78 | 5 | 59 | zjzh/vega | vega/core/run.py | Python | _run_pipeline | _run_pipeline | 65 | 72 | 65 | 65 | ee5358c00502304a750106078900f678e83921e0 | bigcode/the-stack | train |
820d5ecde21fff963b2c1832 | train | function | @lazy
def env_args(args=None):
"""Call lazy function return args.
:param args: args need to save and parse
:return: args
"""
return args
| @lazy
def env_args(args=None):
| """Call lazy function return args.
:param args: args need to save and parse
:return: args
"""
return args
| .info("configure: %s", json.dumps(UserConfig().data, indent=4))
logging.info("-" * 48)
Pipeline().run()
def _adjust_config():
vega.get_quota().adjuest_pipeline_by_runtime(UserConfig().data)
@lazy
def env_args(args=None):
| 64 | 64 | 41 | 9 | 55 | zjzh/vega | vega/core/run.py | Python | env_args | env_args | 79 | 86 | 79 | 80 | c1635c9650db31fb6215fb1192e3a103a61f4d95 | bigcode/the-stack | train |
3ec58b610ca321ba91e22a38 | train | function | def _init_env(cfg_path):
"""Init config and env parameters.
:param cfg_path: config file path
"""
logging.getLogger().setLevel(logging.DEBUG)
UserConfig().load(cfg_path)
# load general
General.from_dict(UserConfig().data.get("general"), skip_check=False)
init_log(level=General.logger.le... | def _init_env(cfg_path):
| """Init config and env parameters.
:param cfg_path: config file path
"""
logging.getLogger().setLevel(logging.DEBUG)
UserConfig().load(cfg_path)
# load general
General.from_dict(UserConfig().data.get("general"), skip_check=False)
init_log(level=General.logger.level,
log_fil... | .
:param cfg_path: config path.
"""
if sys.version_info < (3, 6):
sys.exit('Sorry, Python < 3.6 is not supported.')
_init_env(cfg_path)
_adjust_config()
_run_pipeline()
def _init_env(cfg_path):
| 64 | 64 | 140 | 7 | 57 | zjzh/vega | vega/core/run.py | Python | _init_env | _init_env | 46 | 62 | 46 | 46 | eb1bcec2b0a7392aafcf3fba5a67f04853fbae20 | bigcode/the-stack | train |
f380a4e2f45acfcef235ecbf | train | class | class MixParser:
# 初始化
def __init__(
self,
mix_id,
query_handle: NotionQuery,
export_child_pages=False,
page_parser_type=NotionDump.PARSER_TYPE_MD,
db_parser_type=NotionDump.PARSER_TYPE_PLAIN,
col_name_list=None, # 数据库使用的字段
... | class MixParser:
# 初始化
| def __init__(
self,
mix_id,
query_handle: NotionQuery,
export_child_pages=False,
page_parser_type=NotionDump.PARSER_TYPE_MD,
db_parser_type=NotionDump.PARSER_TYPE_PLAIN,
col_name_list=None, # 数据库使用的字段
):
self.mix_id = m... | # author: delta1037
# Date: 2022/01/10
# mail:geniusrabbit@qq.com
import copy
import os
import NotionDump
from NotionDump.Notion.Notion import NotionQuery
from NotionDump.Parser.block_parser import BlockParser
from NotionDump.Parser.database_parser import DatabaseParser
from NotionDump.Parser.download_parser import Do... | 120 | 256 | 1,533 | 8 | 111 | GatherStar/notion-dump-kernel | NotionDump/Parser/mix_parser.py | Python | MixParser | MixParser | 16 | 159 | 16 | 17 | 454a0f3808bdda04f2e04c02c4986109cad77613 | bigcode/the-stack | train |
b019e89f3013cf651d730c77 | train | function | @app.route('/')
def helloWorld():
resp = {
"message": "flask is running"
}
return jsonify(resp)
| @app.route('/')
def helloWorld():
| resp = {
"message": "flask is running"
}
return jsonify(resp)
| from flask import Flask, render_template, request, jsonify
import pandas as pd
from bokeh.plotting import figure
from bokeh.charts import Histogram
from bokeh.embed import components
app = Flask(__name__)
@app.route('/')
def helloWorld():
| 53 | 64 | 28 | 7 | 46 | frankcash/flask-docker-example | app.py | Python | helloWorld | helloWorld | 9 | 14 | 9 | 10 | 15b2173ad246e284c160fd8f821251f205ed4238 | bigcode/the-stack | train |
843a3bb589690bf3e94e922e | train | function | @app.route("/bokeh/<column>")
def dynamic(column):
df = pd.read_csv("./data/shoes.csv")
y = df[column]
x = df["size"]
plot = figure(title=column + " by Size", x_axis_label='size', y_axis_label=column)
plot.line(x, y, legend=column, line_width=2)
script, div = components(plot)
return render_t... | @app.route("/bokeh/<column>")
def dynamic(column):
| df = pd.read_csv("./data/shoes.csv")
y = df[column]
x = df["size"]
plot = figure(title=column + " by Size", x_axis_label='size', y_axis_label=column)
plot.line(x, y, legend=column, line_width=2)
script, div = components(plot)
return render_template('graph.html', script=script, div=div)
| x_axis_label='size', y_axis_label='sales')
plot.line(x, y, legend="Sales", line_width=2)
script, div = components(plot)
return render_template('graph.html', script=script, div=div)
@app.route("/bokeh/<column>")
def dynamic(column):
| 64 | 64 | 101 | 12 | 52 | frankcash/flask-docker-example | app.py | Python | dynamic | dynamic | 27 | 35 | 27 | 28 | 1e5f7ee0fc03bb0d2e13e8db8d9cbca6bfe7706f | bigcode/the-stack | train |
aa67f68879dedfc8511b0088 | train | function | @app.route("/bokeh")
def default_bokeh():
df = pd.read_csv("./data/shoes.csv")
y = df["sales"]
x = df["size"]
plot = figure(title="Sales by Size", x_axis_label='size', y_axis_label='sales')
plot.line(x, y, legend="Sales", line_width=2)
script, div = components(plot)
return render_template('g... | @app.route("/bokeh")
def default_bokeh():
| df = pd.read_csv("./data/shoes.csv")
y = df["sales"]
x = df["size"]
plot = figure(title="Sales by Size", x_axis_label='size', y_axis_label='sales')
plot.line(x, y, legend="Sales", line_width=2)
script, div = components(plot)
return render_template('graph.html', script=script, div=div)
| ting import figure
from bokeh.charts import Histogram
from bokeh.embed import components
app = Flask(__name__)
@app.route('/')
def helloWorld():
resp = {
"message": "flask is running"
}
return jsonify(resp)
@app.route("/bokeh")
def default_bokeh():
| 64 | 64 | 99 | 11 | 53 | frankcash/flask-docker-example | app.py | Python | default_bokeh | default_bokeh | 17 | 25 | 17 | 18 | 690320e5b1ecb7f12654b963c473f928e4368b7e | bigcode/the-stack | train |
fc88a506a599e78c7b8bdbdd | train | class | class Module:
'''# Base Module Class
This class serves as a template for brute force modules within this
example directory. It builds the interface subcommands by
inspecting the __init__ method while also enforcing restrictions on
the __call__ method to ensure BruteLoops can make authentication
... | class Module:
| '''# Base Module Class
This class serves as a template for brute force modules within this
example directory. It builds the interface subcommands by
inspecting the __init__ method while also enforcing restrictions on
the __call__ method to ensure BruteLoops can make authentication
callbacks.
... | import argparse
import inspect
import re
class Module:
| 12 | 256 | 1,572 | 3 | 8 | rev10d/BruteLoops | BruteLoops/example/module.py | Python | Module | Module | 5 | 228 | 5 | 6 | 23baf6dd835be4c63eae320ee35b2763b178bad0 | bigcode/the-stack | train |
514d8015081abe01ab049137 | train | class | class DataFrameNaFunctions(object):
"""Functionality for working with missing data in :class:`DataFrame`.
.. versionadded:: 1.4
"""
def __init__(self, df):
self.df = df
def drop(self, how='any', thresh=None, subset=None):
return self.df.dropna(how=how, thresh=thresh, subset=subset... | class DataFrameNaFunctions(object):
| """Functionality for working with missing data in :class:`DataFrame`.
.. versionadded:: 1.4
"""
def __init__(self, df):
self.df = df
def drop(self, how='any', thresh=None, subset=None):
return self.df.dropna(how=how, thresh=thresh, subset=subset)
drop.__doc__ = DataFrame.drop... | .",
FutureWarning,
)
return self.to_pandas_on_spark(index_col)
def _to_scala_map(sc, jm):
"""
Convert a dict into a JVM Map.
"""
return sc._jvm.PythonUtils.toScalaMap(jm)
class DataFrameNaFunctions(object):
| 64 | 64 | 174 | 7 | 57 | xuanyuanking/spark | python/pyspark/sql/dataframe.py | Python | DataFrameNaFunctions | DataFrameNaFunctions | 2,957 | 2,979 | 2,957 | 2,957 | bbfc08981ddcb1251e21764f43b1007e7f766bf8 | bigcode/the-stack | train |
9e57731b4415f7c133475142 | train | function | def _to_scala_map(sc, jm):
"""
Convert a dict into a JVM Map.
"""
return sc._jvm.PythonUtils.toScalaMap(jm)
| def _to_scala_map(sc, jm):
| """
Convert a dict into a JVM Map.
"""
return sc._jvm.PythonUtils.toScalaMap(jm)
| to_koalas(self, index_col=None):
warnings.warn(
"DataFrame.to_koalas is deprecated. Use DataFrame.to_pandas_on_spark instead.",
FutureWarning,
)
return self.to_pandas_on_spark(index_col)
def _to_scala_map(sc, jm):
| 64 | 64 | 38 | 10 | 54 | xuanyuanking/spark | python/pyspark/sql/dataframe.py | Python | _to_scala_map | _to_scala_map | 2,950 | 2,954 | 2,950 | 2,950 | 0417b835b4133e344091f7af00801f280a722d37 | bigcode/the-stack | train |
2fef8a6d855530e6cae41e00 | train | class | class DataFrame(PandasMapOpsMixin, PandasConversionMixin):
"""A distributed collection of data grouped into named columns.
A :class:`DataFrame` is equivalent to a relational table in Spark SQL,
and can be created using various functions in :class:`SparkSession`::
people = spark.read.parquet("...")... | class DataFrame(PandasMapOpsMixin, PandasConversionMixin):
| """A distributed collection of data grouped into named columns.
A :class:`DataFrame` is equivalent to a relational table in Spark SQL,
and can be created using various functions in :class:`SparkSession`::
people = spark.read.parquet("...")
Once created, it can be manipulated using the various... | json
import sys
import random
import warnings
from collections.abc import Iterable
from functools import reduce
from html import escape as html_escape
from pyspark import copy_func, since, _NoValue
from pyspark.context import SparkContext
from pyspark.rdd import RDD, _load_from_socket, _local_iterator_from_socket
fro... | 255 | 256 | 25,205 | 14 | 241 | xuanyuanking/spark | python/pyspark/sql/dataframe.py | Python | DataFrame | DataFrame | 44 | 2,947 | 44 | 44 | 671db2133129346f2793c1f730aebdc543856dd0 | bigcode/the-stack | train |
114159f1625b7f0cca4dee4e | train | function | def _test():
import doctest
from pyspark.context import SparkContext
from pyspark.sql import Row, SQLContext, SparkSession
import pyspark.sql.dataframe
globs = pyspark.sql.dataframe.__dict__.copy()
sc = SparkContext('local[4]', 'PythonTest')
globs['sc'] = sc
globs['sqlContext'] = SQLCont... | def _test():
| import doctest
from pyspark.context import SparkContext
from pyspark.sql import Row, SQLContext, SparkSession
import pyspark.sql.dataframe
globs = pyspark.sql.dataframe.__dict__.copy()
sc = SparkContext('local[4]', 'PythonTest')
globs['sc'] = sc
globs['sqlContext'] = SQLContext(sc)
g... | )
cov.__doc__ = DataFrame.cov.__doc__
def crosstab(self, col1, col2):
return self.df.crosstab(col1, col2)
crosstab.__doc__ = DataFrame.crosstab.__doc__
def freqItems(self, cols, support=None):
return self.df.freqItems(cols, support)
freqItems.__doc__ = DataFrame.freqItems.__doc_... | 134 | 135 | 453 | 4 | 130 | xuanyuanking/spark | python/pyspark/sql/dataframe.py | Python | _test | _test | 3,022 | 3,053 | 3,022 | 3,022 | 0b1743d16a8b4bf7aaddaf7ae4ea035d2a9eaf89 | bigcode/the-stack | train |
01a1ac8891d9acd85b3fe861 | train | class | class DataFrameStatFunctions(object):
"""Functionality for statistic functions with :class:`DataFrame`.
.. versionadded:: 1.4
"""
def __init__(self, df):
self.df = df
def approxQuantile(self, col, probabilities, relativeError):
return self.df.approxQuantile(col, probabilities, rel... | class DataFrameStatFunctions(object):
| """Functionality for statistic functions with :class:`DataFrame`.
.. versionadded:: 1.4
"""
def __init__(self, df):
self.df = df
def approxQuantile(self, col, probabilities, relativeError):
return self.df.approxQuantile(col, probabilities, relativeError)
approxQuantile.__doc_... | doc__
def fill(self, value, subset=None):
return self.df.fillna(value=value, subset=subset)
fill.__doc__ = DataFrame.fillna.__doc__
def replace(self, to_replace, value=_NoValue, subset=None):
return self.df.replace(to_replace, value, subset)
replace.__doc__ = DataFrame.replace.__doc_... | 85 | 86 | 287 | 7 | 78 | xuanyuanking/spark | python/pyspark/sql/dataframe.py | Python | DataFrameStatFunctions | DataFrameStatFunctions | 2,982 | 3,019 | 2,982 | 2,982 | 40e13dcf39cc90c6ad08829b7c66bee4c569f047 | bigcode/the-stack | train |
411ade33772ffcc9697e8913 | train | function | def format_img_size(img, C):
""" formats the image size based on config """
img_min_side = float(C.im_size)
(height,width,_) = img.shape
if width <= height:
ratio = img_min_side/width
new_height = int(ratio * height)
new_width = int(img_min_side)
else:
ratio = img_min_side/height
new_width = int(ratio... | def format_img_size(img, C):
| """ formats the image size based on config """
img_min_side = float(C.im_size)
(height,width,_) = img.shape
if width <= height:
ratio = img_min_side/width
new_height = int(ratio * height)
new_width = int(img_min_side)
else:
ratio = img_min_side/height
new_width = int(ratio * width)
new_height = int(... | .network == 'vgg':
import keras_frcnn.vgg as nn
# turn off any data augmentation at test time
C.use_horizontal_flips = False
C.use_vertical_flips = False
C.rot_90 = False
img_path = options.test_path
def format_img_size(img, C):
| 64 | 64 | 128 | 8 | 55 | skimkoh/cv_keras | test_frcnn.py | Python | format_img_size | format_img_size | 56 | 70 | 56 | 56 | c0053365abe12a795a2dc27edf3085e186c07146 | bigcode/the-stack | train |
9164137e1a15ba4f07515ab7 | train | function | def get_real_coordinates(ratio, x1, y1, x2, y2):
real_x1 = int(round(x1 // ratio))
real_y1 = int(round(y1 // ratio))
real_x2 = int(round(x2 // ratio))
real_y2 = int(round(y2 // ratio))
return (real_x1, real_y1, real_x2 ,real_y2)
| def get_real_coordinates(ratio, x1, y1, x2, y2):
| real_x1 = int(round(x1 // ratio))
real_y1 = int(round(y1 // ratio))
real_x2 = int(round(x2 // ratio))
real_y2 = int(round(y2 // ratio))
return (real_x1, real_y1, real_x2 ,real_y2)
| prediction based on config """
img, ratio = format_img_size(img, C)
img = format_img_channels(img, C)
return img, ratio
# Method to transform the coordinates of the bounding box to its original size
def get_real_coordinates(ratio, x1, y1, x2, y2):
| 64 | 64 | 85 | 19 | 44 | skimkoh/cv_keras | test_frcnn.py | Python | get_real_coordinates | get_real_coordinates | 91 | 98 | 91 | 92 | b2a234f60c8305934f68811ec6b0e166fe52d1b3 | bigcode/the-stack | train |
4013baf64cdfa6365d2966a2 | train | function | def format_img_channels(img, C):
""" formats the image channels based on config """
img = img[:, :, (2, 1, 0)]
img = img.astype(np.float32)
img[:, :, 0] -= C.img_channel_mean[0]
img[:, :, 1] -= C.img_channel_mean[1]
img[:, :, 2] -= C.img_channel_mean[2]
img /= C.img_scaling_factor
img = np.transpose(img, (2, 0,... | def format_img_channels(img, C):
| """ formats the image channels based on config """
img = img[:, :, (2, 1, 0)]
img = img.astype(np.float32)
img[:, :, 0] -= C.img_channel_mean[0]
img[:, :, 1] -= C.img_channel_mean[1]
img[:, :, 2] -= C.img_channel_mean[2]
img /= C.img_scaling_factor
img = np.transpose(img, (2, 0, 1))
img = np.expand_dims(img, a... | ratio = img_min_side/height
new_width = int(ratio * width)
new_height = int(img_min_side)
img = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_CUBIC)
return img, ratio
def format_img_channels(img, C):
| 64 | 64 | 119 | 8 | 55 | skimkoh/cv_keras | test_frcnn.py | Python | format_img_channels | format_img_channels | 72 | 82 | 72 | 72 | ef7fa851c51b0bf6be37b4aeaf6cb0853e6a0c0e | bigcode/the-stack | train |
c40e0af82e58f723da495c12 | train | function | def format_img(img, C):
""" formats an image for model prediction based on config """
img, ratio = format_img_size(img, C)
img = format_img_channels(img, C)
return img, ratio
| def format_img(img, C):
| """ formats an image for model prediction based on config """
img, ratio = format_img_size(img, C)
img = format_img_channels(img, C)
return img, ratio
| .img_channel_mean[1]
img[:, :, 2] -= C.img_channel_mean[2]
img /= C.img_scaling_factor
img = np.transpose(img, (2, 0, 1))
img = np.expand_dims(img, axis=0)
return img
def format_img(img, C):
| 64 | 64 | 44 | 7 | 56 | skimkoh/cv_keras | test_frcnn.py | Python | format_img | format_img | 84 | 88 | 84 | 84 | 64652d6bf783302bafa19ed7a6c7fbfc42a3c2c6 | bigcode/the-stack | train |
a8237f75050383c8dbd7cd34 | train | class | class Context(discord.abc.Messageable, Generic[BotT]):
r"""Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as th... | class Context(discord.abc.Messageable, Generic[BotT]):
| r"""Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.
This class implements the :clas... | THE SOFTWARE.
"""
from __future__ import annotations
import inspect
import re
from typing import TYPE_CHECKING, Any, Dict, Generic, List, Optional, TypeVar, Union
import discord.abc
import discord.utils
from discord.message import Message
if TYPE_CHECKING:
from typing_extensions import ParamSpec
from disco... | 256 | 256 | 2,758 | 14 | 242 | jab416171/pycord | discord/ext/commands/context.py | Python | Context | Context | 66 | 399 | 66 | 66 | 91f00021a9610f9f7352773955ec96dc7ef4c857 | bigcode/the-stack | train |
ef8fcda34dd98a1b99c2ec4b | train | function | def lazy_import():
from cryptoapis.model.new_confirmed_tokens_transactions_and_each_confirmation_response_item import NewConfirmedTokensTransactionsAndEachConfirmationResponseItem
globals()['NewConfirmedTokensTransactionsAndEachConfirmationResponseItem'] = NewConfirmedTokensTransactionsAndEachConfirmationRespon... | def lazy_import():
| from cryptoapis.model.new_confirmed_tokens_transactions_and_each_confirmation_response_item import NewConfirmedTokensTransactionsAndEachConfirmationResponseItem
globals()['NewConfirmedTokensTransactionsAndEachConfirmationResponseItem'] = NewConfirmedTokensTransactionsAndEachConfirmationResponseItem
|
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
def lazy_import():
| 64 | 64 | 54 | 4 | 60 | xan187/Crypto_APIs_2.0_SDK_Python | cryptoapis/model/new_confirmed_tokens_transactions_and_each_confirmation_response_data.py | Python | lazy_import | lazy_import | 30 | 32 | 30 | 30 | 01c0aef983fc666666ce1128e4109e4bf33bf005 | bigcode/the-stack | train |
fda7b7700741c844f2a35027 | train | class | class NewConfirmedTokensTransactionsAndEachConfirmationResponseData(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
... | class NewConfirmedTokensTransactionsAndEachConfirmationResponseData(ModelNormal):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a c... | Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of their blockchain applications. Crypto APIs 2.0 provides unified endpoints and data, raw data, automatic tokens and coins forwardings, callback functionalities, and much more. # noqa: E501
The version of... | 256 | 256 | 1,139 | 13 | 242 | xan187/Crypto_APIs_2.0_SDK_Python | cryptoapis/model/new_confirmed_tokens_transactions_and_each_confirmation_response_data.py | Python | NewConfirmedTokensTransactionsAndEachConfirmationResponseData | NewConfirmedTokensTransactionsAndEachConfirmationResponseData | 35 | 175 | 35 | 35 | 5f5d90737ce349b6aae663b8aaf0be32614f0dde | bigcode/the-stack | train |
215bca595f14a2afbd6e9260 | train | function | @paper.route("/paper/request-predict")
def request_predict():
data = {
"title": "Masukkan Hasil Paper Kamu",
"selected": "paper"
}
return render_template("paper/request-paper.html", data=data)
| @paper.route("/paper/request-predict")
def request_predict():
| data = {
"title": "Masukkan Hasil Paper Kamu",
"selected": "paper"
}
return render_template("paper/request-paper.html", data=data)
| name__)
# paper page
@paper.route("/paper")
def paper_index():
data = {
"title": "Prediksi Tema Paper",
"selected": "paper"
}
return render_template("paper/index.html", data=data)
@paper.route("/paper/request-predict")
def request_predict():
| 64 | 64 | 51 | 13 | 51 | ArtificialIfElse/AIC-COMPFEST13 | Deployment/paper.py | Python | request_predict | request_predict | 23 | 30 | 23 | 24 | 729d31f973bd28cc0675196ce37d5ea7b59034c3 | bigcode/the-stack | train |
2ac95cceea3dfd0c2ff5566b | train | function | @paper.route("/api/v1/paper/predict", methods=["POST"])
def api_predict_paper():
try:
if request.get_json() is None or request.get_json()['abstract'] is None or request.get_json()['language'] is None:
data = {
"status": False,
"response_code": 400,
... | @paper.route("/api/v1/paper/predict", methods=["POST"])
def api_predict_paper():
| try:
if request.get_json() is None or request.get_json()['abstract'] is None or request.get_json()['language'] is None:
data = {
"status": False,
"response_code": 400,
"message": "Bad Request"
}
return jsonify(data)
... | result["labels"][0]
best_score = np.round(result["scores"][0] * 100)
data = {
"title": "Prediksi Tema Paper",
"selected": "paper",
"scores": result["scores"],
"labels": result["labels"],
"best_score": best_score,
"best_label": label
}
return render_temp... | 111 | 111 | 370 | 22 | 89 | ArtificialIfElse/AIC-COMPFEST13 | Deployment/paper.py | Python | api_predict_paper | api_predict_paper | 59 | 107 | 59 | 60 | 2dc4ece517c72bbae8b2cd964b94156306c07acd | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.