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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9df5c96d76ac8f5abbbb5839 | train | function | def create_attach_decorator(router: MessageRouter):
def decorator(message_handler: Type[T]) -> Callable[[Any], Any]:
def _decorator(message):
if not isclass(message):
raise TypeError("Message must be valid class declaration")
router.attach(message, message_handler)
... | def create_attach_decorator(router: MessageRouter):
| def decorator(message_handler: Type[T]) -> Callable[[Any], Any]:
def _decorator(message):
if not isclass(message):
raise TypeError("Message must be valid class declaration")
router.attach(message, message_handler)
return message
return _decorato... | , message: Any) -> Callable:
if message.__class__ not in self.routes:
raise NoHandlerAttachedError(f"Handler for message {message} could not be found")
return self.routes[message.__class__]
message_router = MessageRouter()
def create_attach_decorator(router: MessageRouter):
| 64 | 64 | 74 | 10 | 54 | kodemore/troopy | troopy/message_router.py | Python | create_attach_decorator | create_attach_decorator | 28 | 40 | 28 | 28 | b8a5d3e8ff4f75fb8cc7da0e7d4ef55f10e72e6a | bigcode/the-stack | train |
294e111b8a65b6bc50944736 | train | class | class UserCreate(UserBase):
email: EmailStr
password: str
"""
You'll often want to use this together with pre,
since otherwise with always=True pydantic would try to validate the default None
which would cause an error.
"""
@validator("scopes", pre=True, always=True)
def... | class UserCreate(UserBase):
| email: EmailStr
password: str
"""
You'll often want to use this together with pre,
since otherwise with always=True pydantic would try to validate the default None
which would cause an error.
"""
@validator("scopes", pre=True, always=True)
def scopes_validate_default_valu... | -> EmailStr:
if settings.EMAIL_PROVIDER_RESTRICTION:
if not any(
provider in v for provider in settings.ALLOWED_EMAIL_PROVIDER_LIST
):
raise ValueError("Invalid email provider")
return v
# Properties to receive via API on creation
class... | 64 | 64 | 158 | 6 | 57 | benlau6/fastapi-fullstack | backend/app/app/schemas/user.py | Python | UserCreate | UserCreate | 33 | 54 | 33 | 33 | 982b160df5824668e3e579c79a43d5f36f5dc374 | bigcode/the-stack | train |
0f64898e05202465256c4ce3 | train | class | class UserBase(BaseModel):
email: Optional[EmailStr] = None
is_active: bool = True
is_superuser: bool = False
# regex meaning
# first str before ':' should only be in a-z, 0-9, -, _
# second or after str after first ':' should only be in a-z, 0-9, -, _, @, . (think of email)
# ':some_... | class UserBase(BaseModel):
| email: Optional[EmailStr] = None
is_active: bool = True
is_superuser: bool = False
# regex meaning
# first str before ':' should only be in a-z, 0-9, -, _
# second or after str after first ':' should only be in a-z, 0-9, -, _, @, . (think of email)
# ':some_str' should appear at least ... | , TypedDict
from pydantic import BaseModel, Field, EmailStr, validator
from bson.objectid import ObjectId
from app.schemas.utils import PyObjectId, Scope
from app.core.config import settings
from app.core.security import get_password_hash
# Shared properties
class UserBase(BaseModel):
| 64 | 64 | 190 | 6 | 57 | benlau6/fastapi-fullstack | backend/app/app/schemas/user.py | Python | UserBase | UserBase | 12 | 29 | 12 | 12 | d2482e2b195cb901e0e561735d22556e9278752a | bigcode/the-stack | train |
f5e3c8047854e4f936db37b1 | train | class | class UserToDB(UserBase):
hashed_password: Optional[str] = Field(None, alias="password")
class Config:
allow_population_by_field_name = True
@validator("hashed_password")
def hash_password(cls, v: str) -> str:
return get_password_hash(v)
| class UserToDB(UserBase):
| hashed_password: Optional[str] = Field(None, alias="password")
class Config:
allow_population_by_field_name = True
@validator("hashed_password")
def hash_password(cls, v: str) -> str:
return get_password_hash(v)
| (default_scope)
if values["is_superuser"] is True:
v.append("role:admin")
return v
# Properties to receive via API on update
class UserUpdate(UserBase):
password: Optional[str] = None
# Additional properties stored in DB
class UserToDB(UserBase):
| 64 | 64 | 62 | 7 | 56 | benlau6/fastapi-fullstack | backend/app/app/schemas/user.py | Python | UserToDB | UserToDB | 63 | 71 | 63 | 63 | 987ed78955a01ab155c77f92b2510f014d3244f9 | bigcode/the-stack | train |
af8dac9e1f3c448b01893b02 | train | class | class UserFromDB(UserBase):
id: Optional[PyObjectId] = Field(None, alias="_id")
class Config:
"""
Reference: https://pydantic-docs.helpmanual.io/usage/model_config/
allow_population_by_field_name: whether an aliased field may be populated by its name as given by the model attribut... | class UserFromDB(UserBase):
| id: Optional[PyObjectId] = Field(None, alias="_id")
class Config:
"""
Reference: https://pydantic-docs.helpmanual.io/usage/model_config/
allow_population_by_field_name: whether an aliased field may be populated by its name as given by the model attribute, as well as the alias
... | ")
class Config:
allow_population_by_field_name = True
@validator("hashed_password")
def hash_password(cls, v: str) -> str:
return get_password_hash(v)
# Additional properties to return via API
# not showing password or hashed_password
class UserFromDB(UserBase):
| 64 | 64 | 154 | 7 | 56 | benlau6/fastapi-fullstack | backend/app/app/schemas/user.py | Python | UserFromDB | UserFromDB | 76 | 89 | 76 | 76 | a400fbfbe53dfc60edc2b825aed1d089f37f0804 | bigcode/the-stack | train |
7f9b7410c4403f4d1ed436a2 | train | class | class UserCheckScopes(BaseModel):
email: Optional[EmailStr] = None
scopes: Optional[List[Scope]] = None
| class UserCheckScopes(BaseModel):
| email: Optional[EmailStr] = None
scopes: Optional[List[Scope]] = None
| value is not an instance of the type
json_encoders: a dict used to customise the way types are encoded to JSON
"""
allow_population_by_field_name = True
arbitrary_types_allowed = True
json_encoders = {ObjectId: str}
class UserCheckScopes(BaseModel):
| 64 | 64 | 29 | 7 | 57 | benlau6/fastapi-fullstack | backend/app/app/schemas/user.py | Python | UserCheckScopes | UserCheckScopes | 92 | 94 | 92 | 92 | 2234c5f3b679641499ef91eb0048eb101b0228d6 | bigcode/the-stack | train |
678bc457c79369bf40c415e7 | train | class | class UserInDB(TypedDict):
_id: ObjectId
email: EmailStr
hashed_password: str
is_active: bool
is_superuser: bool
scopes: List[Scope]
| class UserInDB(TypedDict):
| _id: ObjectId
email: EmailStr
hashed_password: str
is_active: bool
is_superuser: bool
scopes: List[Scope]
|
arbitrary_types_allowed = True
json_encoders = {ObjectId: str}
class UserCheckScopes(BaseModel):
email: Optional[EmailStr] = None
scopes: Optional[List[Scope]] = None
# just for type check in crud
class UserInDB(TypedDict):
| 64 | 64 | 47 | 8 | 55 | benlau6/fastapi-fullstack | backend/app/app/schemas/user.py | Python | UserInDB | UserInDB | 98 | 104 | 98 | 98 | e860ab5b6a555b1d9b79cd968eed81af2b8586f5 | bigcode/the-stack | train |
58817b84556786db2c3b4278 | train | class | class UserUpdate(UserBase):
password: Optional[str] = None
| class UserUpdate(UserBase):
| password: Optional[str] = None
| default_scope = "user:" + values["email"]
if default_scope not in v:
v.append(default_scope)
if values["is_superuser"] is True:
v.append("role:admin")
return v
# Properties to receive via API on update
class UserUpdate(UserBase):
| 64 | 64 | 15 | 6 | 57 | benlau6/fastapi-fullstack | backend/app/app/schemas/user.py | Python | UserUpdate | UserUpdate | 58 | 59 | 58 | 58 | c8e4ffcf06208d8d3259eff73a9c4f2f14a6294e | bigcode/the-stack | train |
0c2d49c3542ccfd0a1b6e251 | train | function | async def test_get_books_by_filters():
filters = BookFilterParams(title='test book')
# print(filters)
result = await get_books_by_filters(conn, filters)
pprint.pprint(result)
| async def test_get_books_by_filters():
| filters = BookFilterParams(title='test book')
# print(filters)
result = await get_books_by_filters(conn, filters)
pprint.pprint(result)
| OMotorClient
from app.crud.book import (
get_books_by_filters, create_books,
delete_book_by_filters, update_book_by_filters
)
from app.models.book import BookFilterParams, BookBase, BookInServer
conn = AsyncIOMotorClient()
async def test_get_books_by_filters():
| 64 | 64 | 42 | 8 | 56 | lokhiufung/bookshelf-backend | python/tests/test_crud.py | Python | test_get_books_by_filters | test_get_books_by_filters | 16 | 20 | 16 | 16 | 3f39f09ae070bc9152272491c01a59cc348ffc36 | bigcode/the-stack | train |
c885f4469ca40b9b49a94183 | train | function | async def test_update_books_by_filters():
filters = BookFilterParams(title='test book')
update_book = BookInServer(title='test book', url='http://zzz.com', tags=['str'])
result = await update_book_by_filters(conn, filters, update_book)
pprint.pprint(result)
| async def test_update_books_by_filters():
| filters = BookFilterParams(title='test book')
update_book = BookInServer(title='test book', url='http://zzz.com', tags=['str'])
result = await update_book_by_filters(conn, filters, update_book)
pprint.pprint(result)
| '),
BookBase(title='test book 2', tags=['test2', 'test2222'], url='http://yyy.com'),
]
result = await create_books(conn, books)
pprint.pprint(result)
# async def test_delete_books_by_ids():/
async def test_update_books_by_filters():
| 64 | 64 | 63 | 8 | 56 | lokhiufung/bookshelf-backend | python/tests/test_crud.py | Python | test_update_books_by_filters | test_update_books_by_filters | 33 | 37 | 33 | 33 | df8f34c5a460f4da8ba492bafc7cb7125daae4fe | bigcode/the-stack | train |
147d9cc4d8a41092c862f635 | train | function | async def test_create_books():
books = [
BookBase(title='test book', tags=['test', 'test2'], url='http://xxx.com'),
BookBase(title='test book 2', tags=['test2', 'test2222'], url='http://yyy.com'),
]
result = await create_books(conn, books)
pprint.pprint(result)
| async def test_create_books():
| books = [
BookBase(title='test book', tags=['test', 'test2'], url='http://xxx.com'),
BookBase(title='test book 2', tags=['test2', 'test2222'], url='http://yyy.com'),
]
result = await create_books(conn, books)
pprint.pprint(result)
| , BookBase, BookInServer
conn = AsyncIOMotorClient()
async def test_get_books_by_filters():
filters = BookFilterParams(title='test book')
# print(filters)
result = await get_books_by_filters(conn, filters)
pprint.pprint(result)
async def test_create_books():
| 64 | 64 | 78 | 6 | 58 | lokhiufung/bookshelf-backend | python/tests/test_crud.py | Python | test_create_books | test_create_books | 23 | 29 | 23 | 23 | 4a4c632c1c58327a73163a958e311e4a11607598 | bigcode/the-stack | train |
7bdf42b3171bb5a4459a20d9 | train | function | async def test_delete_books_by_filters():
filters = BookFilterParams(title='test book 2')
result = await delete_book_by_filters(conn, filters=filters)
pprint.pprint(result)
| async def test_delete_books_by_filters():
| filters = BookFilterParams(title='test book 2')
result = await delete_book_by_filters(conn, filters=filters)
pprint.pprint(result)
| ():
filters = BookFilterParams(title='test book')
update_book = BookInServer(title='test book', url='http://zzz.com', tags=['str'])
result = await update_book_by_filters(conn, filters, update_book)
pprint.pprint(result)
async def test_delete_books_by_filters():
| 64 | 64 | 41 | 8 | 56 | lokhiufung/bookshelf-backend | python/tests/test_crud.py | Python | test_delete_books_by_filters | test_delete_books_by_filters | 40 | 43 | 40 | 40 | 0613f1c0ec157db321b29b13aab6838317399a27 | bigcode/the-stack | train |
68171f3813b751bca15cfae9 | train | function | def _getattr_r(obj: Any, attr: str, default):
if hasattr(obj, attr):
return getattr(obj, attr)
if hasattr(obj, '__supertype__'):
return _getattr_r(obj.__supertype__, attr, default)
return default
| def _getattr_r(obj: Any, attr: str, default):
| if hasattr(obj, attr):
return getattr(obj, attr)
if hasattr(obj, '__supertype__'):
return _getattr_r(obj.__supertype__, attr, default)
return default
| (obj: Any, attr: str) -> bool:
if hasattr(obj, attr):
return True
if hasattr(obj, '__supertype__'):
return _hasattr_r(obj.__supertype__, attr)
return False
def _getattr_r(obj: Any, attr: str, default):
| 64 | 64 | 58 | 15 | 48 | sungmin-park/config.py | sconfig/__init__.py | Python | _getattr_r | _getattr_r | 89 | 94 | 89 | 89 | 4350fa0d1b1b55726a42055dc5f5ca16c0a65ea5 | bigcode/the-stack | train |
2ec78d6d3060f6c0202a392c | train | function | def _to_env_config_name(config_name: str) -> str:
return uppercase(snakecase(config_name))
| def _to_env_config_name(config_name: str) -> str:
| return uppercase(snakecase(config_name))
| for c in s:
if c.islower():
return True
return False
def _to_env_name(config_name, property_name):
return f'{_to_env_config_name(config_name)}_{property_name.upper()}'
def _to_env_config_name(config_name: str) -> str:
| 63 | 64 | 23 | 14 | 49 | sungmin-park/config.py | sconfig/__init__.py | Python | _to_env_config_name | _to_env_config_name | 108 | 109 | 108 | 108 | 495d04d0f88b5aa04e2ae9fd2df614cef5a64a1c | bigcode/the-stack | train |
6e70e31d9aad05f87562fa9e | train | function | def _hasattr_r(obj: Any, attr: str) -> bool:
if hasattr(obj, attr):
return True
if hasattr(obj, '__supertype__'):
return _hasattr_r(obj.__supertype__, attr)
return False
| def _hasattr_r(obj: Any, attr: str) -> bool:
| if hasattr(obj, attr):
return True
if hasattr(obj, '__supertype__'):
return _hasattr_r(obj.__supertype__, attr)
return False
| , Any]:
ret = {}
for attr_name in dir(obj):
if _has_lower(attr_name) or attr_name.startswith('_'):
continue
ret[attr_name] = getattr(obj, attr_name)
return ret
def _hasattr_r(obj: Any, attr: str) -> bool:
| 64 | 64 | 54 | 16 | 47 | sungmin-park/config.py | sconfig/__init__.py | Python | _hasattr_r | _hasattr_r | 81 | 86 | 81 | 81 | 3712c027c95cf586775b9df9cb0bb67a9d0b732f | bigcode/the-stack | train |
1bc0f5d166dcd101f7ae944c | train | function | def _to_env_name(config_name, property_name):
return f'{_to_env_config_name(config_name)}_{property_name.upper()}'
| def _to_env_name(config_name, property_name):
| return f'{_to_env_config_name(config_name)}_{property_name.upper()}'
| type__'):
return _getattr_r(obj.__supertype__, attr, default)
return default
def _has_lower(s: str) -> bool:
for c in s:
if c.islower():
return True
return False
def _to_env_name(config_name, property_name):
| 64 | 64 | 29 | 11 | 52 | sungmin-park/config.py | sconfig/__init__.py | Python | _to_env_name | _to_env_name | 104 | 105 | 104 | 104 | d599b41ba0388884f5043ded661cf8c8203665ca | bigcode/the-stack | train |
1362e915d9767ea86c808c50 | train | function | def _has_lower(s: str) -> bool:
for c in s:
if c.islower():
return True
return False
| def _has_lower(s: str) -> bool:
| for c in s:
if c.islower():
return True
return False
| (obj: Any, attr: str, default):
if hasattr(obj, attr):
return getattr(obj, attr)
if hasattr(obj, '__supertype__'):
return _getattr_r(obj.__supertype__, attr, default)
return default
def _has_lower(s: str) -> bool:
| 64 | 64 | 31 | 11 | 52 | sungmin-park/config.py | sconfig/__init__.py | Python | _has_lower | _has_lower | 97 | 101 | 97 | 97 | e246a271be83bf6725b8590c614e1920fe618bbb | bigcode/the-stack | train |
7c5d9f721a74384483e82cdf | train | function | def env(override_name, type_: Type[T]) -> Type[T]:
new_type = NewType(f'secret_{type_.__name__}', type_)
setattr(new_type, __SCONFIG_ENV_OVERRIDE_NAME__, override_name)
return new_type
| def env(override_name, type_: Type[T]) -> Type[T]:
| new_type = NewType(f'secret_{type_.__name__}', type_)
setattr(new_type, __SCONFIG_ENV_OVERRIDE_NAME__, override_name)
return new_type
| '
def secret(type_: Type[T]) -> Type[T]:
new_type = NewType(f'secret_{type_.__name__}', type_)
setattr(new_type, __SCONFIG_SECRET__, True)
return new_type
def env(override_name, type_: Type[T]) -> Type[T]:
| 64 | 64 | 55 | 15 | 48 | sungmin-park/config.py | sconfig/__init__.py | Python | env | env | 66 | 69 | 66 | 66 | 97847e597c6270fd62ecf772b4b6e1417eeba1c6 | bigcode/the-stack | train |
c3d88a7a6e71cb95c4543898 | train | function | def configure(cls: Type[Any]) -> str:
hints = get_type_hints(cls)
config_name = cls.__name__
env_config_name = _to_env_config_name(config_name)
toml_config = {}
config_file_name = os.environ.get(
f'SCONFIG_{env_config_name}', 'sconfig.toml'
)
if Path(config_file_name).is_file():
... | def configure(cls: Type[Any]) -> str:
| hints = get_type_hints(cls)
config_name = cls.__name__
env_config_name = _to_env_config_name(config_name)
toml_config = {}
config_file_name = os.environ.get(
f'SCONFIG_{env_config_name}', 'sconfig.toml'
)
if Path(config_file_name).is_file():
with open(config_file_name, 'r') ... | import os
from pathlib import Path
from typing import Any, Dict, Type, TypeVar, NewType, get_type_hints
import toml
from stringcase import snakecase, uppercase
def configure(cls: Type[Any]) -> str:
| 51 | 120 | 401 | 10 | 40 | sungmin-park/config.py | sconfig/__init__.py | Python | configure | configure | 9 | 51 | 9 | 9 | 6b5f967baf625eb868d913f884715dccf15947f2 | bigcode/the-stack | train |
d371bffd513c0bb558ddd928 | train | function | def _attrs(obj: Any) -> Dict[str, Any]:
ret = {}
for attr_name in dir(obj):
if _has_lower(attr_name) or attr_name.startswith('_'):
continue
ret[attr_name] = getattr(obj, attr_name)
return ret
| def _attrs(obj: Any) -> Dict[str, Any]:
| ret = {}
for attr_name in dir(obj):
if _has_lower(attr_name) or attr_name.startswith('_'):
continue
ret[attr_name] = getattr(obj, attr_name)
return ret
| _name, type_: Type[T]) -> Type[T]:
new_type = NewType(f'secret_{type_.__name__}', type_)
setattr(new_type, __SCONFIG_ENV_OVERRIDE_NAME__, override_name)
return new_type
def _attrs(obj: Any) -> Dict[str, Any]:
| 64 | 64 | 58 | 13 | 50 | sungmin-park/config.py | sconfig/__init__.py | Python | _attrs | _attrs | 72 | 78 | 72 | 72 | 621e1e935d5dc760e162a202e7588edabeff7ad5 | bigcode/the-stack | train |
2a1807ac8b4095567703da5e | train | function | def secret(type_: Type[T]) -> Type[T]:
new_type = NewType(f'secret_{type_.__name__}', type_)
setattr(new_type, __SCONFIG_SECRET__, True)
return new_type
| def secret(type_: Type[T]) -> Type[T]:
| new_type = NewType(f'secret_{type_.__name__}', type_)
setattr(new_type, __SCONFIG_SECRET__, True)
return new_type
| _name: ret_toml_config, env_config_name: ret_env_config})
T = TypeVar('T')
__SCONFIG_SECRET__ = '__sconfig_secret__'
__SCONFIG_ENV_OVERRIDE_NAME__ = '__sconfig_env_override_name__'
def secret(type_: Type[T]) -> Type[T]:
| 64 | 64 | 48 | 11 | 53 | sungmin-park/config.py | sconfig/__init__.py | Python | secret | secret | 60 | 63 | 60 | 60 | a5741023176d6a07a88cc6cec5309526c8c2205e | bigcode/the-stack | train |
12bf038e2719e08118edde29 | train | class | class SupplyPointDBAccessorsTest(TestCase):
def setUp(self):
super(SupplyPointDBAccessorsTest, self).setUp()
self.domain = 'supply-point-dbaccessors'
self.project = bootstrap_domain(self.domain)
self.interface = SupplyInterface(self.domain)
self.locations = [
ma... | class SupplyPointDBAccessorsTest(TestCase):
| def setUp(self):
super(SupplyPointDBAccessorsTest, self).setUp()
self.domain = 'supply-point-dbaccessors'
self.project = bootstrap_domain(self.domain)
self.interface = SupplyInterface(self.domain)
self.locations = [
make_loc('1234', name='ben', domain=self.domain... | from django.test import TestCase
from casexml.apps.case.tests.util import delete_all_cases
from corehq.apps.commtrack.tests.util import bootstrap_domain, make_loc
from corehq.form_processor.interfaces.supply import SupplyInterface
class SupplyPointDBAccessorsTest(TestCase):
| 57 | 87 | 290 | 10 | 46 | akashkj/commcare-hq | corehq/apps/commtrack/tests/test_dbaccessors.py | Python | SupplyPointDBAccessorsTest | SupplyPointDBAccessorsTest | 9 | 45 | 9 | 10 | 5963dd87581e8f4529685bdb22a45a4e71d97871 | bigcode/the-stack | train |
732d18b9ff79ec09e547e2a7 | train | class | class QLearner(object):
def __init__(self, state_dim,
num_actions,
init_exp=0.9, # initial exploration prob
final_exp=0.0, # final exploration prob
anneal_steps=500000, # N steps for annealing exploration
... | class QLearner(object):
| def __init__(self, state_dim,
num_actions,
init_exp=0.9, # initial exploration prob
final_exp=0.0, # final exploration prob
anneal_steps=500000, # N steps for annealing exploration
alpha = 0.2,
... | import random
import numpy as np
import sys
# tabular Q-learning where states and actions
# are discrete and stored in a table
class QLearner(object):
| 36 | 182 | 608 | 6 | 29 | TonnyTran/07_backscatter_blockchain | rl/agents/tabular_q_learner.py | Python | QLearner | QLearner | 7 | 74 | 7 | 8 | 084260714603737049431629b50a3fe427c71436 | bigcode/the-stack | train |
8a7b4da05b22cc41c4b106d5 | train | function | def handle_aurora_crud(event, context):
request_body = event['body']
event_type = request_body['eventType']
databaseName = os.environ['DatabaseName']
awsSecretStoreArn = os.environ['AwsSecretStoreArn']
dbClusterOrInstanceArn = os.environ['DbClusterArn']
if event_type == "createTable":
s... | def handle_aurora_crud(event, context):
| request_body = event['body']
event_type = request_body['eventType']
databaseName = os.environ['DatabaseName']
awsSecretStoreArn = os.environ['AwsSecretStoreArn']
dbClusterOrInstanceArn = os.environ['DbClusterArn']
if event_type == "createTable":
sql.create_table(databaseName, awsSecretS... | import json
import os
import boto3
from random import *
import sql
def handle_aurora_crud(event, context):
| 28 | 83 | 279 | 11 | 16 | CodeRecipe-dev/LambdaToAuroraNoVPC | handler.py | Python | handle_aurora_crud | handle_aurora_crud | 7 | 31 | 7 | 7 | cbe6d2195b5cca40b7409cb02c777e511757adc0 | bigcode/the-stack | train |
6866beeea303a73281bee869 | train | class | class NumpyPluginDetector(NuitkaPluginBase):
"""Only used if plugin is NOT activated.
Notes:
We are given the chance to issue a warning if we think we may be required.
"""
detector_for = NumpyPlugin
@classmethod
def isRelevant(cls):
"""Check whether plugin might be required.
... | class NumpyPluginDetector(NuitkaPluginBase):
| """Only used if plugin is NOT activated.
Notes:
We are given the chance to issue a warning if we think we may be required.
"""
detector_for = NumpyPlugin
@classmethod
def isRelevant(cls):
"""Check whether plugin might be required.
Returns:
True if this is ... | MATPLOTLIBDATA"] = os.path.join(__nuitka_binary_dir, "matplotlib", "mpl-data")
"""
return (
code,
"Setting 'MATPLOTLIBDATA' environment variable for matplotlib to find package data.",
)
class NumpyPluginDetector(NuitkaPluginBase):
| 66 | 66 | 221 | 11 | 55 | RESP3CT88/Nuitka | nuitka/plugins/standard/NumpyPlugin.py | Python | NumpyPluginDetector | NumpyPluginDetector | 443 | 478 | 443 | 443 | a30a0f1f164c5974ae1b5db24c222caee96ff04f | bigcode/the-stack | train |
9d8b75429b75d0b1e6ed8cb5 | train | class | class NumpyPlugin(NuitkaPluginBase):
"""This class represents the main logic of the plugin.
This is a plugin to ensure scripts using numpy, scipy, matplotlib, pandas,
scikit-learn, etc. work well in standalone mode.
While there already are relevant entries in the "ImplicitImports.py" plugin,
this ... | class NumpyPlugin(NuitkaPluginBase):
| """This class represents the main logic of the plugin.
This is a plugin to ensure scripts using numpy, scipy, matplotlib, pandas,
scikit-learn, etc. work well in standalone mode.
While there already are relevant entries in the "ImplicitImports.py" plugin,
this plugin copies any additional binary o... | re_anylib.match(f)]
binaries += [[os.path.join(numpy_core_dir, f), suffix_start] for f in dlls_pkg]
# Also look for MKL libraries in folder "above" numpy.
# This should meet the layout of Anaconda installs.
if isWin32Windows():
lib_dir = os.path.join(base_prefix, "Library", "bin")
suf... | 256 | 256 | 2,676 | 10 | 245 | RESP3CT88/Nuitka | nuitka/plugins/standard/NumpyPlugin.py | Python | NumpyPlugin | NumpyPlugin | 99 | 440 | 99 | 99 | 8c255dc06e15e178231c64bc36727fb4da08dbce | bigcode/the-stack | train |
bae49dcff2b575370eeaae60 | train | function | def getNumpyCoreBinaries(module):
"""Return any binaries in numpy/core and/or numpy/.libs.
Notes:
This covers the special cases like MKL binaries.
Returns:
tuple of abspaths of binaries.
"""
numpy_dir = module.getCompileTimeDirectory()
numpy_core_dir = os.path.join(numpy_dir, "... | def getNumpyCoreBinaries(module):
| """Return any binaries in numpy/core and/or numpy/.libs.
Notes:
This covers the special cases like MKL binaries.
Returns:
tuple of abspaths of binaries.
"""
numpy_dir = module.getCompileTimeDirectory()
numpy_core_dir = os.path.join(numpy_dir, "core")
base_prefix = getSystem... | limitations under the License.
#
""" Details see below in class definition.
"""
import os
import re
import shutil
import sys
from collections import namedtuple
from nuitka import Options
from nuitka.freezer.IncludedEntryPoints import makeDllEntryPoint
from nuitka.plugins.PluginBase import NuitkaPluginBase
from nu... | 148 | 148 | 496 | 9 | 138 | RESP3CT88/Nuitka | nuitka/plugins/standard/NumpyPlugin.py | Python | getNumpyCoreBinaries | getNumpyCoreBinaries | 41 | 96 | 41 | 41 | 2560c0ebc60b501fef3c25d1559e4492637c41bf | bigcode/the-stack | train |
cfaa6f337b77384fd1f110fd | train | class | class Lanefinder():
"""docstring for ."""
def __init__(self):
self.ym_per_pix = 30/720 # meters per pixel in y dimension
self.xm_per_pix = 3.7/880 # meters per pixel in x dimension
self.src_points = np.float32([[240, 690],
[1070, 690],
... | class Lanefinder():
| """docstring for ."""
def __init__(self):
self.ym_per_pix = 30/720 # meters per pixel in y dimension
self.xm_per_pix = 3.7/880 # meters per pixel in x dimension
self.src_points = np.float32([[240, 690],
[1070, 690],
... | """Pipeline to find lanes on images or movies."""
import numpy as np
import cv2
import glob
from os import path
import pickle
from lane import Lane
class Lanefinder():
| 40 | 256 | 5,146 | 5 | 34 | DominikMa/P5-Vehicle-Detection | P4.py | Python | Lanefinder | Lanefinder | 11 | 483 | 11 | 11 | 957ad6ba1e76c29b963808ae13a0eef097b6bbfd | bigcode/the-stack | train |
3049d33085d2d736929edc36 | train | function | def setup(app):
app.add_config_value('recommonmark_config', {
# 'url_resolver': lambda url: github_doc_root + url,
'auto_toc_tree_section': 'Contents',
'enable_eval_rst': True,
'enable_math': True,
'enable_inline_math': True,
}, True)
app.add_transform(AutoStructi... | def setup(app):
| app.add_config_value('recommonmark_config', {
# 'url_resolver': lambda url: github_doc_root + url,
'auto_toc_tree_section': 'Contents',
'enable_eval_rst': True,
'enable_math': True,
'enable_inline_math': True,
}, True)
app.add_transform(AutoStructify)
| show URL addresses after external links.
#man_show_urls = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
# app setup hook to enable AutoStructify (for ```eval_rst blocks)
def setup(app):
| 64 | 64 | 79 | 4 | 60 | r-rojo/opae-sdk | mybuild_docs/sphinx/_build/conf.py | Python | setup | setup | 197 | 205 | 197 | 197 | 0d77da698348808197c21243b0120f817a008fc5 | bigcode/the-stack | train |
7c7a649ccb7513742ae43277 | train | class | class FileStoreTIFFSquashing(FileStorePluginBase):
'''Write out 'squashed' tiffs
.. note::
See :class:`FileStoreBase` for the rest of the required parametrs
This mixin will also configure the ``cam`` and ``proc`` plugins
on the parent.
This is useful to work around the dynamic range of de... | class FileStoreTIFFSquashing(FileStorePluginBase):
| '''Write out 'squashed' tiffs
.. note::
See :class:`FileStoreBase` for the rest of the required parametrs
This mixin will also configure the ``cam`` and ``proc`` plugins
on the parent.
This is useful to work around the dynamic range of detectors
and minimizing disk spaced used by synt... | self.file_name.get(),
'frame_per_point': self.get_frames_per_point()}
self._generate_resource(resource_kwargs)
class FileStoreTIFF(FileStorePluginBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.filestore_spec = 'AD_TIFF' # spe... | 243 | 243 | 813 | 12 | 231 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | FileStoreTIFFSquashing | FileStoreTIFFSquashing | 519 | 610 | 519 | 519 | 95fa0145aa6f03ae38b45f15cb3b05cea5bb1c8c | bigcode/the-stack | train |
d29458d20106b182323bd558 | train | class | class FileStoreBase(BlueskyInterface, GenerateDatumInterface):
"""Base class for FileStore mixin classes
This class provides
- python side path management (root, seperate write / read paths)
- provides :meth:`generate_datum` to work with
:meth:`~ophyd.areadetector.detectors.DetectorBase.di... | class FileStoreBase(BlueskyInterface, GenerateDatumInterface):
| """Base class for FileStore mixin classes
This class provides
- python side path management (root, seperate write / read paths)
- provides :meth:`generate_datum` to work with
:meth:`~ophyd.areadetector.detectors.DetectorBase.dispatch`
- cooperative stage / unstage methods
- coo... | The specification of data wrapped, used to pick the handler to
be used on retrieval
root : Path or str
The 'root' path (the non-semantic mount point). AssetRegistry has
tooling to easily change this temporarily and permanently.
resource_path : Path or str
The rest of the pa... | 256 | 256 | 2,309 | 14 | 241 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | FileStoreBase | FileStoreBase | 105 | 387 | 105 | 105 | 653100815f5e0ee1b1d1e3ae5342f8e7aa42fc78 | bigcode/the-stack | train |
e89b619d145f63c672b41c5c | train | class | class FileStoreHDF5(FileStorePluginBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.filestore_spec = 'AD_HDF5' # spec name stored in resource doc
self.stage_sigs.update([('file_template', '%s%s_%6.6d.h5'),
('file_write_mode',... | class FileStoreHDF5(FileStorePluginBase):
| def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.filestore_spec = 'AD_HDF5' # spec name stored in resource doc
self.stage_sigs.update([('file_template', '%s%s_%6.6d.h5'),
('file_write_mode', 'Stream'),
... | () - 1)
# file_number is *next* iteration
self._fp = read_path
if not self.file_path_exists.get():
raise IOError("Path %s does not exist on IOC."
"" % self.file_path.get())
class FileStoreHDF5(FileStorePluginBase):
| 64 | 64 | 144 | 11 | 53 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | FileStoreHDF5 | FileStoreHDF5 | 448 | 463 | 448 | 448 | 31de8befcb4db5fffa825fd55c6233ebb0bd7180 | bigcode/the-stack | train |
efe7157606f75266768ddb3a | train | class | class FileStoreIterativeWrite(FileStoreBase):
"""
This adds 'point_number' to datum_kwargs.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._point_counter = None
def stage(self):
super().stage()
self._point_counter = count()
def u... | class FileStoreIterativeWrite(FileStoreBase):
| """
This adds 'point_number' to datum_kwargs.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._point_counter = None
def stage(self):
super().stage()
self._point_counter = count()
def unstage(self):
self._point_counter = No... | the base stage
self._fn = self._fp
resource_kwargs = {'template': self.file_template.get(),
'filename': self.file_name.get(),
'frame_per_point': self.get_frames_per_point()}
self._generate_resource(resource_kwargs)
class FileStoreIterativeWr... | 64 | 64 | 149 | 10 | 54 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | FileStoreIterativeWrite | FileStoreIterativeWrite | 613 | 633 | 613 | 613 | 52d547121d72e72291d0fee87b3ac8f52cdae176 | bigcode/the-stack | train |
bdfc203954c589cee3116491 | train | class | class FileStorePluginBase(FileStoreBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.stage_sigs.update([('auto_increment', 'Yes'),
('array_counter', 0),
('auto_save', 'Yes'),
... | class FileStorePluginBase(FileStoreBase):
| def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.stage_sigs.update([('auto_increment', 'Yes'),
('array_counter', 0),
('auto_save', 'Yes'),
('num_capture', 0),
... | .
self._locked_key_list = (self._staged == Staged.yes)
res = super().read()
for k, v in self._datum_uids.items():
res[k] = v[-1]
return res
def collect_asset_docs(self):
items = list(self._asset_docs_cache)
self._asset_docs_cache.clear()
for item ... | 134 | 134 | 448 | 9 | 125 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | FileStorePluginBase | FileStorePluginBase | 390 | 445 | 390 | 390 | dbdfa5369f67f8f9fd15d1adfe6e80982c7cc400 | bigcode/the-stack | train |
1f27ed5fdb78957f2d91318e | train | class | class FileStoreTIFF(FileStorePluginBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.filestore_spec = 'AD_TIFF' # spec name stored in resource doc
self.stage_sigs.update([('file_template', '%s%s_%6.6d.tiff'),
('file_write_mode... | class FileStoreTIFF(FileStorePluginBase):
| def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.filestore_spec = 'AD_TIFF' # spec name stored in resource doc
self.stage_sigs.update([('file_template', '%s%s_%6.6d.tiff'),
('file_write_mode', 'Single'),
... | the base stage
self._fn = self._fp
resource_kwargs = {'template': self.file_template.get(),
'filename': self.file_name.get(),
'frame_per_point': self.get_frames_per_point()}
self._generate_resource(resource_kwargs)
class FileStoreTIFF(FileS... | 64 | 64 | 206 | 10 | 54 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | FileStoreTIFF | FileStoreTIFF | 495 | 516 | 495 | 495 | 3721c27864e496fa2722271491c9075cdf80d3bf | bigcode/the-stack | train |
b872a2756e91d8590568b2eb | train | function | def resource_factory(spec, root, resource_path, resource_kwargs,
path_semantics):
"""Helper to create resource document and datum factory.
Parameters
----------
spec : str
The specification of data wrapped, used to pick the handler to
be used on retrieval
root : ... | def resource_factory(spec, root, resource_path, resource_kwargs,
path_semantics):
| """Helper to create resource document and datum factory.
Parameters
----------
spec : str
The specification of data wrapped, used to pick the handler to
be used on retrieval
root : Path or str
The 'root' path (the non-semantic mount point). AssetRegistry has
tooling to... | """
'a/b/c' -> 'a/b/c/'
EPICS adds the trailing slash itself if we do not, so in order for the
setpoint filepath to match the readback filepath, we need to add the
trailing slash ourselves.
"""
return os.path.join(path, '')
def resource_factory(spec, root, resource_path, resource_kwargs,
... | 83 | 84 | 281 | 18 | 65 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | resource_factory | resource_factory | 60 | 102 | 60 | 61 | 403f05f9d97c52d271bad6a29294c483129cdcca | bigcode/the-stack | train |
1c5cb197a06eac422aa5141b | train | class | class FileStoreTIFFIterativeWrite(FileStoreTIFF, FileStoreIterativeWrite):
pass
| class FileStoreTIFFIterativeWrite(FileStoreTIFF, FileStoreIterativeWrite):
| pass
| Single,
FileStoreIterativeWrite):
'''
Used for running Areadetectors hdf5 plugin in `Single` mode, with
`point_number` in the kwargs.
'''
pass
class FileStoreTIFFIterativeWrite(FileStoreTIFF, FileStoreIterativeWrite):
| 64 | 64 | 22 | 19 | 44 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | FileStoreTIFFIterativeWrite | FileStoreTIFFIterativeWrite | 651 | 652 | 651 | 651 | 115102b87d1a8d99b6b2189ad2d3794cedb27ac4 | bigcode/the-stack | train |
4c5b1f28bc501f4e7394e652 | train | function | def new_uid():
"uuid4 as a string"
return str(uuid.uuid4())
| def new_uid():
| "uuid4 as a string"
return str(uuid.uuid4())
| logging
import warnings
import uuid
from pathlib import PurePath
from datetime import datetime
from collections import defaultdict
from itertools import count
from ..device import GenerateDatumInterface, BlueskyInterface, Staged
from ..utils import set_and_wait
logger = logging.getLogger(__name__)
def new_uid():
| 64 | 64 | 19 | 4 | 60 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | new_uid | new_uid | 39 | 41 | 39 | 39 | c519a3ac7601d736212769e41db4640e7cdca7a0 | bigcode/the-stack | train |
e719c3b3779f10a875618619 | train | function | def _ensure_trailing_slash(path):
"""
'a/b/c' -> 'a/b/c/'
EPICS adds the trailing slash itself if we do not, so in order for the
setpoint filepath to match the readback filepath, we need to add the
trailing slash ourselves.
"""
return os.path.join(path, '')
| def _ensure_trailing_slash(path):
| """
'a/b/c' -> 'a/b/c/'
EPICS adds the trailing slash itself if we do not, so in order for the
setpoint filepath to match the readback filepath, we need to add the
trailing slash ourselves.
"""
return os.path.join(path, '')
| name__)
def new_uid():
"uuid4 as a string"
return str(uuid.uuid4())
def new_short_uid():
"uuid4, skipping the last stanza because of AD length restrictions."
return '-'.join(new_uid().split('-')[:-1])
def _ensure_trailing_slash(path):
| 64 | 64 | 75 | 9 | 55 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | _ensure_trailing_slash | _ensure_trailing_slash | 49 | 57 | 49 | 49 | 4f304dcc4c8046fee8885fe6f88dcf704a7cd67b | bigcode/the-stack | train |
9d675895b12be074fc49eae1 | train | function | def new_short_uid():
"uuid4, skipping the last stanza because of AD length restrictions."
return '-'.join(new_uid().split('-')[:-1])
| def new_short_uid():
| "uuid4, skipping the last stanza because of AD length restrictions."
return '-'.join(new_uid().split('-')[:-1])
| collections import defaultdict
from itertools import count
from ..device import GenerateDatumInterface, BlueskyInterface, Staged
from ..utils import set_and_wait
logger = logging.getLogger(__name__)
def new_uid():
"uuid4 as a string"
return str(uuid.uuid4())
def new_short_uid():
| 64 | 64 | 34 | 5 | 59 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | new_short_uid | new_short_uid | 44 | 46 | 44 | 44 | 154248d07513cf31a9bef85079b7477c85304a74 | bigcode/the-stack | train |
b6ddb65b873fc4f99b5037b2 | train | class | class FileStoreHDF5SingleIterativeWrite(FileStoreHDF5Single,
FileStoreIterativeWrite):
'''
Used for running Areadetectors hdf5 plugin in `Single` mode, with
`point_number` in the kwargs.
'''
pass
| class FileStoreHDF5SingleIterativeWrite(FileStoreHDF5Single,
FileStoreIterativeWrite):
| '''
Used for running Areadetectors hdf5 plugin in `Single` mode, with
`point_number` in the kwargs.
'''
pass
| generate_datum(key, timestamp, datum_kwargs)
# ready-to-use combinations
class FileStoreHDF5IterativeWrite(FileStoreHDF5, FileStoreIterativeWrite):
pass
class FileStoreHDF5SingleIterativeWrite(FileStoreHDF5Single,
FileStoreIterativeWrite):
| 64 | 64 | 60 | 24 | 39 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | FileStoreHDF5SingleIterativeWrite | FileStoreHDF5SingleIterativeWrite | 642 | 648 | 642 | 643 | dd1e167544ccc69112be413ba6b0faa52de29deb | bigcode/the-stack | train |
3dc502ce3fed4aba8b289b15 | train | class | class FileStoreHDF5IterativeWrite(FileStoreHDF5, FileStoreIterativeWrite):
pass
| class FileStoreHDF5IterativeWrite(FileStoreHDF5, FileStoreIterativeWrite):
| pass
| (self._point_counter)
datum_kwargs = datum_kwargs or {}
datum_kwargs.update({'point_number': i})
return super().generate_datum(key, timestamp, datum_kwargs)
# ready-to-use combinations
class FileStoreHDF5IterativeWrite(FileStoreHDF5, FileStoreIterativeWrite):
| 64 | 64 | 24 | 21 | 42 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | FileStoreHDF5IterativeWrite | FileStoreHDF5IterativeWrite | 638 | 639 | 638 | 638 | 540e0a5d232101e0aef6de7641e68a9896ddb79d | bigcode/the-stack | train |
72773d836650704e8234ed5a | train | class | class FileStoreHDF5Single(FileStorePluginBase):
'''This FileStore mixin is used when running the AreaDetector hdf5 plugin
in `Single` mode (ie. one hdf5 file per trigger).
'''
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.filestore_spec = 'AD_HDF5_SINGLE' ... | class FileStoreHDF5Single(FileStorePluginBase):
| '''This FileStore mixin is used when running the AreaDetector hdf5 plugin
in `Single` mode (ie. one hdf5 file per trigger).
'''
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.filestore_spec = 'AD_HDF5_SINGLE' # spec name stored in res. doc
self.sta... | _mode', 'Stream'),
('capture', 1)
])
def get_frames_per_point(self):
return self.num_capture.get()
def stage(self):
super().stage()
res_kwargs = {'frame_per_point': self.get_frames_per_point()}
self._generate_resou... | 74 | 74 | 249 | 12 | 62 | ke-zhang-rd/ophyd | ophyd/areadetector/filestore_mixins.py | Python | FileStoreHDF5Single | FileStoreHDF5Single | 466 | 492 | 466 | 466 | fc590eb34efe62d47e88e1ec4b4e5a26f4393a10 | bigcode/the-stack | train |
64e0f2c68ff305919a66a9cc | train | class | class NumberInAdvancedFilter(AdvancedFilter):
"""NumberIn Advanced Filter.
All required parameters must be populated in order to send to Azure.
:param key: The field/property in the event based on which you want to
filter.
:type key: str
:param operator_type: Required. Constant filled by serv... | class NumberInAdvancedFilter(AdvancedFilter):
| """NumberIn Advanced Filter.
All required parameters must be populated in order to send to Azure.
:param key: The field/property in the event based on which you want to
filter.
:type key: str
:param operator_type: Required. Constant filled by server.
:type operator_type: str
:param va... | License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .advanced_filter_... | 69 | 69 | 232 | 9 | 59 | michimune/azure-cli-extensions | src/eventgrid/azext_eventgrid/vendored_sdks/eventgrid/models/number_in_advanced_filter_py3.py | Python | NumberInAdvancedFilter | NumberInAdvancedFilter | 15 | 42 | 15 | 15 | 0ab517f1eb834f7d630cc48d527d59ee9a8ab3c3 | bigcode/the-stack | train |
1d4f6bab0452f4e9a0922add | train | function | def variant_dict(variant):
"""
Create a dict from a variant
"""
return {
"g_notation": str(variant),
"tags": []
}
| def variant_dict(variant):
| """
Create a dict from a variant
"""
return {
"g_notation": str(variant),
"tags": []
}
| mask this repeat region in the query sequence
masked_query = masked_query[:f["start"]] + "$" * (f["end"] + 1 - f["start"]) + masked_query[f["end"] + 1:]
return list(strs), masked_query
def variant_dict(variant):
| 64 | 64 | 38 | 6 | 57 | lumc-pgx/variant-calling | scripts/call_variants.py | Python | variant_dict | variant_dict | 54 | 61 | 54 | 54 | e32d2a13dbfdfa57d5331b23284dfce7ddafc826 | bigcode/the-stack | train |
361f26e8244770eee3ede372 | train | function | def find_and_mask_repeats(query_seq, ref_seq):
locus_strs = [str_search.parse_hgvs(s.g_notation) for s in locus.snps if s.tags is not None and 'short_tandem_repeat' in s.tags]
strs = set()
masked_query = query_seq
for repeat in set((s["start"], s["unit"]) for s in locus_strs):
# current... | def find_and_mask_repeats(query_seq, ref_seq):
| locus_strs = [str_search.parse_hgvs(s.g_notation) for s in locus.snps if s.tags is not None and 'short_tandem_repeat' in s.tags]
strs = set()
masked_query = query_seq
for repeat in set((s["start"], s["unit"]) for s in locus_strs):
# currently, we can only handle str nomenclature that IN... | import WorkflowError
locus = locus_processing.load_locus_yaml(snakemake.input.locus)
try:
with open(snakemake.config["EXPERIMENT"], "r") as infile:
experiment = yaml.safe_load(infile)
start_pos = experiment["targets"][0]["primers"][0]["forward"]["start"]
except (KeyError, IOError):
start_pos ... | 96 | 96 | 322 | 13 | 82 | lumc-pgx/variant-calling | scripts/call_variants.py | Python | find_and_mask_repeats | find_and_mask_repeats | 22 | 51 | 22 | 22 | a914fa809dff155a513a1e6bc5a4f450477021f2 | bigcode/the-stack | train |
cf1aaff965db6ef0842e141b | train | function | def counterPage(route=None):
return Div(
className="container",
children=[
Router().render("counter", route)
]
)
| def counterPage(route=None):
| return Div(
className="container",
children=[
Router().render("counter", route)
]
)
| from core.components.div import Div
from core.router import Router
def counterPage(route=None):
| 19 | 64 | 32 | 6 | 12 | gabssanto/pizzaPy | pages/counter.py | Python | counterPage | counterPage | 5 | 11 | 5 | 5 | 1805eba1d91a117da7190249a6c737304bf2b159 | bigcode/the-stack | train |
35e158f089b542348ddd5dc3 | train | function | def make_serializer_cls(fields_mapping: Dict[str, serializers.Field]) -> Type[serializers.Serializer]:
cls_name = uuid.uuid4().hex + 'AnonymousSerializer'
bases = (serializers.Serializer,)
# noinspection PyTypeChecker
return type(cls_name, bases, fields_mapping)
| def make_serializer_cls(fields_mapping: Dict[str, serializers.Field]) -> Type[serializers.Serializer]:
| cls_name = uuid.uuid4().hex + 'AnonymousSerializer'
bases = (serializers.Serializer,)
# noinspection PyTypeChecker
return type(cls_name, bases, fields_mapping)
| .response import Response
from rest_framework.views import APIView
_ValidationSchema = Union[
Dict[str, serializers.Field],
Type[serializers.Serializer]
]
_C = TypeVar('_C', bound=Callable)
def make_serializer_cls(fields_mapping: Dict[str, serializers.Field]) -> Type[serializers.Serializer]:
| 64 | 64 | 61 | 20 | 44 | micro-fan/fan_tools | fan_tools/drf/validation.py | Python | make_serializer_cls | make_serializer_cls | 20 | 24 | 20 | 20 | aa64ae1652efed3207cbb9a0827bd2ee854028bf | bigcode/the-stack | train |
7f56a7593276bc86552fbeb8 | train | class | class validate_request:
def __init__(self, *,
query_params: Optional[_ValidationSchema] = None,
data: Optional[_ValidationSchema] = None
) -> None:
if isinstance(query_params, dict):
query_params = make_serializer_cls(query_params)
self.... | class validate_request:
| def __init__(self, *,
query_params: Optional[_ValidationSchema] = None,
data: Optional[_ValidationSchema] = None
) -> None:
if isinstance(query_params, dict):
query_params = make_serializer_cls(query_params)
self.query_params_serializer_... | elif isinstance(data, dict):
form = serializer_cls(data={**data, **kwargs})
else:
form = serializer_cls(data=data, **kwargs)
form.is_valid(raise_exception=True)
return form
if request:
kwargs = {}
if request.resolver_match:
kwargs = {**re... | 105 | 105 | 351 | 4 | 100 | micro-fan/fan_tools | fan_tools/drf/validation.py | Python | validate_request | validate_request | 61 | 99 | 61 | 61 | d41d41e9c226b98396ca8750921cde6c504eecfa | bigcode/the-stack | train |
64f898629a5df12e2615587a | train | function | def validate_with_serializer(serializer_cls: Type[serializers.Serializer], data: Any) -> Any:
serializer = serializer_cls(data=data)
try:
serializer.is_valid(raise_exception=True)
return serializer.validated_data
except serializers.ValidationError as exc:
raise exceptions.ParseError... | def validate_with_serializer(serializer_cls: Type[serializers.Serializer], data: Any) -> Any:
| serializer = serializer_cls(data=data)
try:
serializer.is_valid(raise_exception=True)
return serializer.validated_data
except serializers.ValidationError as exc:
raise exceptions.ParseError(exc.detail)
| izers.Serializer]:
cls_name = uuid.uuid4().hex + 'AnonymousSerializer'
bases = (serializers.Serializer,)
# noinspection PyTypeChecker
return type(cls_name, bases, fields_mapping)
def validate_with_serializer(serializer_cls: Type[serializers.Serializer], data: Any) -> Any:
| 64 | 64 | 63 | 20 | 44 | micro-fan/fan_tools | fan_tools/drf/validation.py | Python | validate_with_serializer | validate_with_serializer | 27 | 34 | 27 | 27 | 161db813bab938a73a4f335998d72299bcf6761d | bigcode/the-stack | train |
dc8f4d94f6af60f84e66f5b6 | train | function | def validate_request_data(serializer_cls: Type[serializers.Serializer],
request: Union[Request, HttpRequest],
**top_kwargs) -> Any:
def validated_form(request, **kwargs):
data = request.query_params.dict() if request.method in ['GET'] else request.data
... | def validate_request_data(serializer_cls: Type[serializers.Serializer],
request: Union[Request, HttpRequest],
**top_kwargs) -> Any:
| def validated_form(request, **kwargs):
data = request.query_params.dict() if request.method in ['GET'] else request.data
if isinstance(data, QueryDict):
form = serializer_cls(data={**data.dict(), **kwargs})
elif isinstance(data, dict):
form = serializer_cls(data={**da... | :
serializer.is_valid(raise_exception=True)
return serializer.validated_data
except serializers.ValidationError as exc:
raise exceptions.ParseError(exc.detail)
def validate_request_data(serializer_cls: Type[serializers.Serializer],
request: Union[Request, HttpReque... | 64 | 64 | 183 | 31 | 33 | micro-fan/fan_tools | fan_tools/drf/validation.py | Python | validate_request_data | validate_request_data | 37 | 58 | 37 | 39 | d4ab62277383f41e49c46b637bf7b96bd9aa5ec8 | bigcode/the-stack | train |
e1e55ada824f8f0fc117c614 | train | class | class TestPod:
"""Pod OpenAPI 相关接口测试"""
pod_name = 'pod-for-test-{}'.format(generate_random_string(8))
@pytest.fixture(autouse=True)
def common_patch(self):
ctx_cluster = CtxCluster.create(TEST_CLUSTER_ID, TEST_PROJECT_ID, token='token')
Pod(ctx_cluster).update_or_create(
n... | class TestPod:
| """Pod OpenAPI 相关接口测试"""
pod_name = 'pod-for-test-{}'.format(generate_random_string(8))
@pytest.fixture(autouse=True)
def common_patch(self):
ctx_cluster = CtxCluster.create(TEST_CLUSTER_ID, TEST_PROJECT_ID, token='token')
Pod(ctx_cluster).update_or_create(
namespace=TEST_N... | implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from typing import Dict
import pytest
from backend.container_service.clusters.base.models import CtxCluster
from backend.resources.workloads.pod import Pod
from backend.tests.conftest import TEST_CLUSTER_I... | 92 | 92 | 307 | 4 | 87 | kayinli/bk-bcs | bcs-ui/backend/tests/container_service/clusters/open_apis/test_pod.py | Python | TestPod | TestPod | 27 | 61 | 27 | 27 | ae8ec4c2361c5d9d3f45c0788ef3ded847bd482d | bigcode/the-stack | train |
a20d7ccc7a0420c20254f811 | train | function | def gen_pod_body(name: str) -> Dict:
"""生成用于测试的 Pod 配置 TODO 后续接入 load_demo_manifest"""
return {
'apiVersion': 'v1',
'kind': 'Pod',
'metadata': {'name': name},
'spec': {'containers': [{'name': "main", 'image': "busybox"}]},
}
| def gen_pod_body(name: str) -> Dict:
| """生成用于测试的 Pod 配置 TODO 后续接入 load_demo_manifest"""
return {
'apiVersion': 'v1',
'kind': 'Pod',
'metadata': {'name': name},
'spec': {'containers': [{'name': "main", 'image': "busybox"}]},
}
| Formatter 是否生效
assert set(response_data[0].keys()) == {
'data',
'clusterId',
'resourceType',
'resourceName',
'namespace',
'createTime',
'updateTime',
}
def gen_pod_body(name: str) -> Dict:
| 64 | 64 | 81 | 12 | 52 | kayinli/bk-bcs | bcs-ui/backend/tests/container_service/clusters/open_apis/test_pod.py | Python | gen_pod_body | gen_pod_body | 64 | 71 | 64 | 64 | b3b78a621ea7ff46c981073e11d91e8884304180 | bigcode/the-stack | train |
94f51185b104da27917bfcf2 | train | class | class PrintTimings(TimingClient):
def timing(self, metric_name, timing, tags):
logging.info(f'{metric_name=} {timing=}, {tags=}')
| class PrintTimings(TimingClient):
| def timing(self, metric_name, timing, tags):
logging.info(f'{metric_name=} {timing=}, {tags=}')
| Templates
from timing_asgi import TimingClient, TimingMiddleware
from timing_asgi.integrations import StarletteScopeToName
html_fir = pathlib.Path(__file__).parent.joinpath('templates').absolute()
html_templates = Jinja2Templates(directory=html_fir)
class PrintTimings(TimingClient):
| 64 | 64 | 37 | 8 | 56 | esemi/ibtax_web_ui | web_ui/webapp.py | Python | PrintTimings | PrintTimings | 16 | 18 | 16 | 16 | 2545df8291e682e6c5ceee3670e29be3e3f0d477 | bigcode/the-stack | train |
2841902f47b835a3f8d450ab | train | function | async def index_html(request):
logging.info('index page request')
return html_templates.TemplateResponse('index.html', {
'request': request,
})
| async def index_html(request):
| logging.info('index page request')
return html_templates.TemplateResponse('index.html', {
'request': request,
})
| .joinpath('templates').absolute()
html_templates = Jinja2Templates(directory=html_fir)
class PrintTimings(TimingClient):
def timing(self, metric_name, timing, tags):
logging.info(f'{metric_name=} {timing=}, {tags=}')
async def index_html(request):
| 63 | 64 | 33 | 6 | 57 | esemi/ibtax_web_ui | web_ui/webapp.py | Python | index_html | index_html | 21 | 26 | 21 | 21 | 8477db80bfb0fb9d037063ac5c1171ea62ad6754 | bigcode/the-stack | train |
aec1c9dbb0d6c229dc4d1ac5 | train | class | class AaaUserEpFsm(ManagedObject):
"""This is AaaUserEpFsm class."""
consts = AaaUserEpFsmConsts()
naming_props = set([])
mo_meta = MoMeta("AaaUserEpFsm", "aaaUserEpFsm", "fsm", VersionMeta.Version141a, "OutputOnly", 0xf, [], [""], [u'aaaUserEp'], [u'aaaUserEpFsmStage'], [None])
prop_meta = {
... | class AaaUserEpFsm(ManagedObject):
| """This is AaaUserEpFsm class."""
consts = AaaUserEpFsmConsts()
naming_props = set([])
mo_meta = MoMeta("AaaUserEpFsm", "aaaUserEpFsm", "fsm", VersionMeta.Version141a, "OutputOnly", 0xf, [], [""], [u'aaaUserEp'], [u'aaaUserEpFsmStage'], [None])
prop_meta = {
"child_action": MoPropertyMeta... | -error"
RMT_ERR_CODE_ERR_RADIUS_SET_ERROR = "ERR-radius-set-error"
RMT_ERR_CODE_ERR_ROLE_SET_ERROR = "ERR-role-set-error"
RMT_ERR_CODE_ERR_SERVICE_NOT_READY = "ERR-service-not-ready"
RMT_ERR_CODE_ERR_SESSION_CACHE_FULL = "ERR-session-cache-full"
RMT_ERR_CODE_ERR_SESSION_NOT_FOUND = "ERR-session-not-... | 256 | 256 | 2,215 | 11 | 245 | ragupta-git/ucscentralsdk | ucscentralsdk/mometa/aaa/AaaUserEpFsm.py | Python | AaaUserEpFsm | AaaUserEpFsm | 112 | 166 | 112 | 112 | 6da03e0db84e5684341685cca5ff7b7aa5c6ae2e | bigcode/the-stack | train |
c33b0721509a16bef0bafdfd | train | class | class AaaUserEpFsmConsts():
COMPLETION_TIME_ = ""
CURRENT_FSM_NOP = "nop"
CURRENT_FSM_UPDATE_USER_EP = "updateUserEp"
FSM_STATUS_FAIL = "fail"
FSM_STATUS_IN_PROGRESS = "inProgress"
FSM_STATUS_NOP = "nop"
FSM_STATUS_PENDING = "pending"
FSM_STATUS_SKIP = "skip"
FSM_STATUS_SUCCESS = "su... | class AaaUserEpFsmConsts():
| COMPLETION_TIME_ = ""
CURRENT_FSM_NOP = "nop"
CURRENT_FSM_UPDATE_USER_EP = "updateUserEp"
FSM_STATUS_FAIL = "fail"
FSM_STATUS_IN_PROGRESS = "inProgress"
FSM_STATUS_NOP = "nop"
FSM_STATUS_PENDING = "pending"
FSM_STATUS_SKIP = "skip"
FSM_STATUS_SUCCESS = "success"
FSM_STATUS_THROTT... | """This module contains the general information for AaaUserEpFsm ManagedObject."""
from ...ucscentralmo import ManagedObject
from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta
from ...ucscentralmeta import VersionMeta
class AaaUserEpFsmConsts():
| 63 | 256 | 1,883 | 9 | 53 | ragupta-git/ucscentralsdk | ucscentralsdk/mometa/aaa/AaaUserEpFsm.py | Python | AaaUserEpFsmConsts | AaaUserEpFsmConsts | 8 | 109 | 8 | 8 | 49cf89a79afa21a02e62fe61dd25ecf025c0eabc | bigcode/the-stack | train |
e27afbcfdfb2845f280fb864 | train | function | def doit(opts, args):
if opts.debug:
print("gdal_calc.py starting calculation %s" %(opts.calc))
################################################################
# fetch details of input layers
################################################################
# set up some lists to store da... | def doit(opts, args):
| if opts.debug:
print("gdal_calc.py starting calculation %s" %(opts.calc))
################################################################
# fetch details of input layers
################################################################
# set up some lists to store data for each band
my... | calc="(A+B)/2"
# example 3 - set values of zero and below to null
# gdal_calc.py -A input.tif --outfile=result.tif --calc="A*(A>0)" --NoDataValue=0
################################################################
from optparse import OptionParser
import os
import sys
import numpy
from osgeo import gdal
from osgeo i... | 256 | 256 | 2,081 | 6 | 249 | szekerest/gdal | gdal/swig/python/scripts/gdal_calc.py | Python | doit | doit | 65 | 290 | 65 | 66 | e8e523201bd4b098839efba7d7a2f873301b28cc | bigcode/the-stack | train |
1d088160023839119867e321 | train | function | def main():
usage = "usage: %prog [-A <filename>] [--A_band] [-B...-Z filename] [other_options]"
parser = OptionParser(usage)
# define options
parser.add_option("--calc", dest="calc", help="calculation in gdalnumeric syntax using +-/* or any numpy array functions (i.e. logical_and())")
# hack to li... | def main():
| usage = "usage: %prog [-A <filename>] [--A_band] [-B...-Z filename] [other_options]"
parser = OptionParser(usage)
# define options
parser.add_option("--calc", dest="calc", help="calculation in gdalnumeric syntax using +-/* or any numpy array functions (i.e. logical_and())")
# hack to limit the numb... | .calc)
except:
print("evaluation of calculation %s failed" %(opts.calc))
raise
# Propagate nodata values (set nodata cells to zero
# then add nodata value to these cells).
myResult = ((1*(myNDVs==0))*myResult) + (my... | 155 | 155 | 518 | 3 | 151 | szekerest/gdal | gdal/swig/python/scripts/gdal_calc.py | Python | main | main | 293 | 325 | 293 | 293 | db22e8693743dce34356810235b22a8ef378aae9 | bigcode/the-stack | train |
95dc2dcf875ac94a9d573235 | train | class | class LogItem:
def __init__(self):
self.timestamp = ''
self.host_name = ''
self.source_name = ''
self.process_id = ''
self.facility = ''
self.severity = ''
self.system = ''
self.message = ''
def __str__(self):
attributes = vars(self)
... | class LogItem:
| def __init__(self):
self.timestamp = ''
self.host_name = ''
self.source_name = ''
self.process_id = ''
self.facility = ''
self.severity = ''
self.system = ''
self.message = ''
def __str__(self):
attributes = vars(self)
return ' | '... | class LogItem:
| 4 | 64 | 86 | 4 | 0 | code10ftn/siem-monitor | SiemAgent/src/model/log_item.py | Python | LogItem | LogItem | 1 | 14 | 1 | 1 | 9f940d40b014e6005fdfaa557f49407476d49c01 | bigcode/the-stack | train |
e2f65071ead1665d32c8b463 | train | class | class Neighbor(object):
_GLOBAL = {'uid': 1}
def __init__(self):
self.description = None
self.router_id = None
self.host_name = None
self.domain_name = None
self.local_address = None
self.range_size = 1
# local_address uses auto discovery
self.aut... | class Neighbor(object):
| _GLOBAL = {'uid': 1}
def __init__(self):
self.description = None
self.router_id = None
self.host_name = None
self.domain_name = None
self.local_address = None
self.range_size = 1
# local_address uses auto discovery
self.auto_discovery = False
... | # encoding: utf-8
"""
neighbor.py
Created by Thomas Mangin on 2009-11-05.
Copyright (c) 2009-2017 Exa Networks. All rights reserved.
License: 3-clause BSD. (See the COPYRIGHT file)
"""
from collections import deque
from collections import Counter
from exabgp.protocol.family import AFI
from exabgp.bgp.message impor... | 128 | 256 | 3,633 | 4 | 124 | criteo-forks/exabgp | lib/exabgp/bgp/neighbor.py | Python | Neighbor | Neighbor | 23 | 399 | 23 | 23 | 5b25bd517811539f9f85ecd1157222fd3e66aeb1 | bigcode/the-stack | train |
6a2f2123b5ef1cd0ca2b1483 | train | class | class TestAutogradLfilterCPU(Autograd, common_utils.PytorchTestCase):
dtype = torch.float64
device = torch.device("cpu")
| class TestAutogradLfilterCPU(Autograd, common_utils.PytorchTestCase):
| dtype = torch.float64
device = torch.device("cpu")
| import torch
from torchaudio_unittest import common_utils
from .autograd_impl import Autograd, AutogradFloat32
class TestAutogradLfilterCPU(Autograd, common_utils.PytorchTestCase):
| 45 | 64 | 33 | 18 | 26 | popcornell/audio | test/torchaudio_unittest/functional/autograd_cpu_test.py | Python | TestAutogradLfilterCPU | TestAutogradLfilterCPU | 7 | 9 | 7 | 7 | 22a5fa88f478307b0aaa646bee25c5f19894394f | bigcode/the-stack | train |
90cdf67b857a882a804af600 | train | class | class TestAutogradRNNTCPU(AutogradFloat32, common_utils.PytorchTestCase):
dtype = torch.float32
device = torch.device("cpu")
| class TestAutogradRNNTCPU(AutogradFloat32, common_utils.PytorchTestCase):
| dtype = torch.float32
device = torch.device("cpu")
| ograd_impl import Autograd, AutogradFloat32
class TestAutogradLfilterCPU(Autograd, common_utils.PytorchTestCase):
dtype = torch.float64
device = torch.device("cpu")
class TestAutogradRNNTCPU(AutogradFloat32, common_utils.PytorchTestCase):
| 64 | 64 | 35 | 20 | 44 | popcornell/audio | test/torchaudio_unittest/functional/autograd_cpu_test.py | Python | TestAutogradRNNTCPU | TestAutogradRNNTCPU | 12 | 14 | 12 | 12 | 827ff02561bc04983e3b3725173af95fe024cf72 | bigcode/the-stack | train |
38ae53a886fc1c95f9637c25 | train | function | def display_scores(scores):
print(("Scores:", scores))
print(("Mean:", scores.mean()))
print(("Standard deviation:", scores.std()))
| def display_scores(scores):
| print(("Scores:", scores))
print(("Mean:", scores.mean()))
print(("Standard deviation:", scores.std()))
| (X_train)
# In[ ]:
# Fitting Multiple Linear Regression to the Training set
LinReg = LinearRegression()
LinReg.fit(X_train,y_train)
y_predict = LinReg.predict(X_test)
LinReg.score(X_train,y_train) # R squared
# In[ ]:
def display_scores(scores):
| 64 | 64 | 29 | 5 | 59 | josepablocam/common-code-extraction | downloaded_kernels/house_sales/parsed_kernels/kernel_52.py | Python | display_scores | display_scores | 196 | 199 | 196 | 196 | 3cd48908e357bf914b3477e23d9af65d810b2025 | bigcode/the-stack | train |
a9d2f7c8ad8d6e5a8a275097 | train | function | @pytest.mark.parametrize(
"with_dbd", [
pytest.param(True, id="with_dbd"),
pytest.param(False, id="without_dbd"),
]
)
def test_graph_db(with_dbd):
db_path = conftest.MODULE_PATH / "iocs" / "streamdevice" / "test.db"
if with_dbd:
dbd_path = str(conftest.MODULE_PATH / "iocs" / "sof... | @pytest.mark.parametrize(
"with_dbd", [
pytest.param(True, id="with_dbd"),
pytest.param(False, id="without_dbd"),
]
)
def test_graph_db(with_dbd):
| db_path = conftest.MODULE_PATH / "iocs" / "streamdevice" / "test.db"
if with_dbd:
dbd_path = str(conftest.MODULE_PATH / "iocs" / "softIoc.dbd")
else:
dbd_path = None
main(filenames=[db_path], dbd=dbd_path)
| def test_graph_smoke_startup_script(startup_script):
main(filenames=[startup_script])
@pytest.mark.parametrize(
"with_dbd", [
pytest.param(True, id="with_dbd"),
pytest.param(False, id="without_dbd"),
]
)
def test_graph_db(with_dbd):
| 64 | 64 | 124 | 44 | 20 | pcdshub/whatrecord | whatrecord/tests/test_bin_graph.py | Python | test_graph_db | test_graph_db | 14 | 26 | 14 | 20 | 7963ef6fe7c2113f94e83e9b287cf436c771303e | bigcode/the-stack | train |
b01c6522c31afe6f62986cab | train | function | @pytest.mark.parametrize(
"with_dbd", [
pytest.param(True, id="with_dbd"),
pytest.param(False, id="without_dbd"),
]
)
def test_graph_multiple_db(with_dbd):
db_paths = [
conftest.MODULE_PATH / "iocs" / "streamdevice" / "test.db",
conftest.MODULE_PATH / "iocs" / "ioc_a" / "ioc_... | @pytest.mark.parametrize(
"with_dbd", [
pytest.param(True, id="with_dbd"),
pytest.param(False, id="without_dbd"),
]
)
def test_graph_multiple_db(with_dbd):
| db_paths = [
conftest.MODULE_PATH / "iocs" / "streamdevice" / "test.db",
conftest.MODULE_PATH / "iocs" / "ioc_a" / "ioc_a.db",
]
if with_dbd:
dbd_path = str(conftest.MODULE_PATH / "iocs" / "softIoc.dbd")
else:
dbd_path = None
main(filenames=db_paths, dbd=dbd_path)
| d_path = None
main(filenames=[db_path], dbd=dbd_path)
@pytest.mark.parametrize(
"with_dbd", [
pytest.param(True, id="with_dbd"),
pytest.param(False, id="without_dbd"),
]
)
def test_graph_multiple_db(with_dbd):
| 64 | 64 | 151 | 45 | 19 | pcdshub/whatrecord | whatrecord/tests/test_bin_graph.py | Python | test_graph_multiple_db | test_graph_multiple_db | 29 | 44 | 29 | 35 | 114f6e5f752f644ef1d4ef33a022b1e2b2f8dc14 | bigcode/the-stack | train |
174ce2261e04f60920f6f71c | train | function | @conftest.startup_scripts
def test_graph_smoke_startup_script(startup_script):
main(filenames=[startup_script])
| @conftest.startup_scripts
def test_graph_smoke_startup_script(startup_script):
| main(filenames=[startup_script])
| """Smoke tests to see if the provided IOCs load without crashing."""
import pytest
from ..bin.graph import main
from . import conftest
@conftest.startup_scripts
def test_graph_smoke_startup_script(startup_script):
| 51 | 64 | 28 | 20 | 30 | pcdshub/whatrecord | whatrecord/tests/test_bin_graph.py | Python | test_graph_smoke_startup_script | test_graph_smoke_startup_script | 9 | 11 | 9 | 10 | 74f545a6d9569a347b668072cfc9ae784d41da6c | bigcode/the-stack | train |
4c7549199b60558ab65daae9 | train | function | def is_valid_url(url):
"""
Validates URL input
"""
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\... | def is_valid_url(url):
| """
Validates URL input
"""
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv... | #coding: utf-8
import re
def is_valid_url(url):
| 16 | 68 | 228 | 6 | 9 | abandonedbyrochacbruno/Flask-Shorteners | flaskext/utils.py | Python | is_valid_url | is_valid_url | 6 | 21 | 6 | 6 | b19fdaa2386374c329ef42d1345420e870edb502 | bigcode/the-stack | train |
47a645f80b6cee0979bb0898 | train | function | def test_insert_base(idx):
result = idx[1:4]
# test 0th element
assert idx[0:4].equals(result.insert(0, idx[0]))
| def test_insert_base(idx):
| result = idx[1:4]
# test 0th element
assert idx[0:4].equals(result.insert(0, idx[0]))
| names = np.array(["foo", "bar"])
m = MultiIndex.from_product([numbers, names], names=names)
expected = MultiIndex.from_product([numbers, names.repeat(reps)], names=names)
tm.assert_index_equal(m.repeat(reps), expected)
def test_insert_base(idx):
| 64 | 64 | 41 | 6 | 58 | naomi172839/pandas | pandas/tests/indexes/multi/test_reshape.py | Python | test_insert_base | test_insert_base | 158 | 163 | 158 | 159 | c0ba3844b9adc80df66465c8fac47e999c94b2ef | bigcode/the-stack | train |
b4b231762dace083282b64d3 | train | function | def test_append_index():
idx1 = Index([1.1, 1.2, 1.3])
idx2 = pd.date_range("2011-01-01", freq="D", periods=3, tz="Asia/Tokyo")
idx3 = Index(["A", "B", "C"])
midx_lv2 = MultiIndex.from_arrays([idx1, idx2])
midx_lv3 = MultiIndex.from_arrays([idx1, idx2, idx3])
result = idx1.append(midx_lv2)
... | def test_append_index():
| idx1 = Index([1.1, 1.2, 1.3])
idx2 = pd.date_range("2011-01-01", freq="D", periods=3, tz="Asia/Tokyo")
idx3 = Index(["A", "B", "C"])
midx_lv2 = MultiIndex.from_arrays([idx1, idx2])
midx_lv3 = MultiIndex.from_arrays([idx1, idx2, idx3])
result = idx1.append(midx_lv2)
# see gh-7112
tz = ... | test", 17)] = 11
left.loc[("test", 18)] = 12
right = pd.Series(np.linspace(0, 12, 13), pd.MultiIndex.from_tuples(idx))
tm.assert_series_equal(left, right)
def test_append(idx):
result = idx[:3].append(idx[3:])
assert result.equals(idx)
foos = [idx[:1], idx[1:3], idx[3:]]
result = foos[0... | 141 | 141 | 471 | 5 | 136 | naomi172839/pandas | pandas/tests/indexes/multi/test_reshape.py | Python | test_append_index | test_append_index | 101 | 145 | 101 | 101 | 7986b8c275ea8777aa84c81f50dc294eda3a30b1 | bigcode/the-stack | train |
c2e32c4065b0bb3c0a6ad239 | train | function | def test_append(idx):
result = idx[:3].append(idx[3:])
assert result.equals(idx)
foos = [idx[:1], idx[1:3], idx[3:]]
result = foos[0].append(foos[1:])
assert result.equals(idx)
# empty
result = idx.append([])
assert result.equals(idx)
| def test_append(idx):
| result = idx[:3].append(idx[3:])
assert result.equals(idx)
foos = [idx[:1], idx[1:3], idx[3:]]
result = foos[0].append(foos[1:])
assert result.equals(idx)
# empty
result = idx.append([])
assert result.equals(idx)
| .loc[("test", 17)] = 11
left.loc[("test", 18)] = 12
right = pd.Series(np.linspace(0, 12, 13), pd.MultiIndex.from_tuples(idx))
tm.assert_series_equal(left, right)
def test_append(idx):
| 64 | 64 | 80 | 5 | 59 | naomi172839/pandas | pandas/tests/indexes/multi/test_reshape.py | Python | test_append | test_append | 88 | 98 | 88 | 88 | 2982b6169c6c5c7d928b15854f9df4ded176dd14 | bigcode/the-stack | train |
322ac802eeac77c7ba81920d | train | function | def test_insert(idx):
# key contained in all levels
new_index = idx.insert(0, ("bar", "two"))
assert new_index.equal_levels(idx)
assert new_index[0] == ("bar", "two")
# key not contained in all levels
new_index = idx.insert(0, ("abc", "three"))
exp0 = Index(list(idx.levels[0]) + ["abc"], n... | def test_insert(idx):
# key contained in all levels
| new_index = idx.insert(0, ("bar", "two"))
assert new_index.equal_levels(idx)
assert new_index[0] == ("bar", "two")
# key not contained in all levels
new_index = idx.insert(0, ("abc", "three"))
exp0 = Index(list(idx.levels[0]) + ["abc"], name="first")
tm.assert_index_equal(new_index.levels[... | from datetime import datetime
import numpy as np
import pytest
import pytz
import pandas as pd
from pandas import Index, MultiIndex
import pandas._testing as tm
def test_insert(idx):
# key contained in all levels
| 50 | 232 | 776 | 13 | 36 | naomi172839/pandas | pandas/tests/indexes/multi/test_reshape.py | Python | test_insert | test_insert | 12 | 85 | 12 | 13 | f98eafacda8c957e1d96efde1a53ddc57c1a1352 | bigcode/the-stack | train |
ab3666df206c4c8bb272faa3 | train | function | def test_repeat():
reps = 2
numbers = [1, 2, 3]
names = np.array(["foo", "bar"])
m = MultiIndex.from_product([numbers, names], names=names)
expected = MultiIndex.from_product([numbers, names.repeat(reps)], names=names)
tm.assert_index_equal(m.repeat(reps), expected)
| def test_repeat():
| reps = 2
numbers = [1, 2, 3]
names = np.array(["foo", "bar"])
m = MultiIndex.from_product([numbers, names], names=names)
expected = MultiIndex.from_product([numbers, names.repeat(reps)], names=names)
tm.assert_index_equal(m.repeat(reps), expected)
| 1, 2)), "B"),
(1.3, tz.localize(datetime(2011, 1, 3)), "C"),
]
+ expected_tuples,
dtype=object,
),
None,
)
tm.assert_index_equal(result, expected)
def test_repeat():
| 64 | 64 | 80 | 4 | 60 | naomi172839/pandas | pandas/tests/indexes/multi/test_reshape.py | Python | test_repeat | test_repeat | 148 | 155 | 148 | 148 | bc17057d1a8c02dbb01d22040f6493a630a43448 | bigcode/the-stack | train |
5d30f5235d27ec131401c4c3 | train | function | def test_delete_base(idx):
expected = idx[1:]
result = idx.delete(0)
assert result.equals(expected)
assert result.name == expected.name
expected = idx[:-1]
result = idx.delete(-1)
assert result.equals(expected)
assert result.name == expected.name
with pytest.raises((IndexError, Va... | def test_delete_base(idx):
| expected = idx[1:]
result = idx.delete(0)
assert result.equals(expected)
assert result.name == expected.name
expected = idx[:-1]
result = idx.delete(-1)
assert result.equals(expected)
assert result.name == expected.name
with pytest.raises((IndexError, ValueError)):
# Except... | names=names)
tm.assert_index_equal(m.repeat(reps), expected)
def test_insert_base(idx):
result = idx[1:4]
# test 0th element
assert idx[0:4].equals(result.insert(0, idx[0]))
def test_delete_base(idx):
| 63 | 64 | 91 | 6 | 57 | naomi172839/pandas | pandas/tests/indexes/multi/test_reshape.py | Python | test_delete_base | test_delete_base | 166 | 180 | 166 | 167 | 6a5a53e7991919209b7c209c0d365ef42b186236 | bigcode/the-stack | train |
768280aeda88d2e79e43ad62 | train | class | class ListTopicSnapshotsRequest(proto.Message):
r"""Request for the ``ListTopicSnapshots`` method.
Attributes:
topic (str):
Required. The name of the topic that snapshots are attached
to. Format is ``projects/{project}/topics/{topic}``.
page_size (int):
Maxim... | class ListTopicSnapshotsRequest(proto.Message):
| r"""Request for the ``ListTopicSnapshots`` method.
Attributes:
topic (str):
Required. The name of the topic that snapshots are attached
to. Format is ``projects/{project}/topics/{topic}``.
page_size (int):
Maximum number of snapshot names to return.
p... | ``ListTopicSubscriptionsRequest`` to get more subscriptions.
"""
@property
def raw_page(self):
return self
subscriptions = proto.RepeatedField(proto.STRING, number=1,)
next_page_token = proto.Field(proto.STRING, number=2,)
class ListTopicSnapshotsRequest(proto.Message):
| 63 | 64 | 167 | 8 | 55 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ListTopicSnapshotsRequest | ListTopicSnapshotsRequest | 372 | 390 | 372 | 372 | 9bc37915ac96435912a618a04f469dbbb0812bcc | bigcode/the-stack | train |
8ab3274b0977b86429852f1d | train | class | class PullResponse(proto.Message):
r"""Response for the ``Pull`` method.
Attributes:
received_messages (Sequence[google.pubsub_v1.types.ReceivedMessage]):
Received Pub/Sub messages. The list will be empty if there
are no more messages available in the backlog. For JSON, the
... | class PullResponse(proto.Message):
| r"""Response for the ``Pull`` method.
Attributes:
received_messages (Sequence[google.pubsub_v1.types.ReceivedMessage]):
Received Pub/Sub messages. The list will be empty if there
are no more messages available in the backlog. For JSON, the
response can be entirely em... | The Pub/Sub system may return fewer
than the number specified.
"""
subscription = proto.Field(proto.STRING, number=1,)
return_immediately = proto.Field(proto.BOOL, number=2,)
max_messages = proto.Field(proto.INT32, number=3,)
class PullResponse(proto.Message):
| 63 | 64 | 127 | 6 | 57 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | PullResponse | PullResponse | 945 | 959 | 945 | 945 | cc96d9dafad465168f15b13fbfa7dedc165f040b | bigcode/the-stack | train |
2b75c9b852427f0d833b4de0 | train | class | class MessageStoragePolicy(proto.Message):
r"""A policy constraining the storage of messages published to
the topic.
Attributes:
allowed_persistence_regions (Sequence[str]):
A list of IDs of GCP regions where messages
that are published to the topic may be persisted
... | class MessageStoragePolicy(proto.Message):
| r"""A policy constraining the storage of messages published to
the topic.
Attributes:
allowed_persistence_regions (Sequence[str]):
A list of IDs of GCP regions where messages
that are published to the topic may be persisted
in storage. Messages published by publi... | StreamingPullResponse",
"CreateSnapshotRequest",
"UpdateSnapshotRequest",
"Snapshot",
"GetSnapshotRequest",
"ListSnapshotsRequest",
"ListSnapshotsResponse",
"DeleteSnapshotRequest",
"SeekRequest",
"SeekResponse",
},
)
class MessageStoragePolicy... | 64 | 64 | 143 | 7 | 57 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | MessageStoragePolicy | MessageStoragePolicy | 75 | 91 | 75 | 75 | 7173565062a379830b0a692d2eb0a5f1cdec430c | bigcode/the-stack | train |
d0bb4f8f2728f9a9093f8766 | train | class | class UpdateSubscriptionRequest(proto.Message):
r"""Request for the UpdateSubscription method.
Attributes:
subscription (google.pubsub_v1.types.Subscription):
Required. The updated subscription object.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Required. Ind... | class UpdateSubscriptionRequest(proto.Message):
| r"""Request for the UpdateSubscription method.
Attributes:
subscription (google.pubsub_v1.types.Subscription):
Required. The updated subscription object.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Required. Indicates which fields in the
provided ... | r"""Request for the GetSubscription method.
Attributes:
subscription (str):
Required. The name of the subscription to get. Format is
``projects/{project}/subscriptions/{sub}``.
"""
subscription = proto.Field(proto.STRING, number=1,)
class UpdateSubscriptionRequest(proto.Me... | 63 | 64 | 121 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | UpdateSubscriptionRequest | UpdateSubscriptionRequest | 822 | 837 | 822 | 822 | 93ed2cd889bee7f6e14441f30924f410e2ad3098 | bigcode/the-stack | train |
6caed9dd476e8456395a6536 | train | class | class DetachSubscriptionResponse(proto.Message):
r"""Response for the DetachSubscription method.
Reserved for future use.
"""
| class DetachSubscriptionResponse(proto.Message):
| r"""Response for the DetachSubscription method.
Reserved for future use.
"""
| r"""Request for the DetachSubscription method.
Attributes:
subscription (str):
Required. The subscription to detach. Format is
``projects/{project}/subscriptions/{subscription}``.
"""
subscription = proto.Field(proto.STRING, number=1,)
class DetachSubscriptionResponse(p... | 63 | 64 | 27 | 8 | 55 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | DetachSubscriptionResponse | DetachSubscriptionResponse | 438 | 442 | 438 | 438 | ade6f3636f7753650919adf0f1279773dab4b80b | bigcode/the-stack | train |
32c564a736ee5b96e0b6b871 | train | class | class RetryPolicy(proto.Message):
r"""A policy that specifies how Cloud Pub/Sub retries message delivery.
Retry delay will be exponential based on provided minimum and
maximum backoffs. https://en.wikipedia.org/wiki/Exponential_backoff.
RetryPolicy will be triggered on NACKs or acknowledgement deadlin... | class RetryPolicy(proto.Message):
| r"""A policy that specifies how Cloud Pub/Sub retries message delivery.
Retry delay will be exponential based on provided minimum and
maximum backoffs. https://en.wikipedia.org/wiki/Exponential_backoff.
RetryPolicy will be triggered on NACKs or acknowledgement deadline
exceeded events for a given ... | .MESSAGE, number=13, message="DeadLetterPolicy",
)
retry_policy = proto.Field(proto.MESSAGE, number=14, message="RetryPolicy",)
detached = proto.Field(proto.BOOL, number=15,)
topic_message_retention_duration = proto.Field(
proto.MESSAGE, number=17, message=duration_pb2.Duration,
)
class Retr... | 79 | 79 | 266 | 6 | 73 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | RetryPolicy | RetryPolicy | 596 | 628 | 596 | 596 | 1b1715974126914a4d2ff7d30dbe03c83efe5ddc | bigcode/the-stack | train |
8898a6487b7c0745e871bbe8 | train | class | class ListTopicSubscriptionsRequest(proto.Message):
r"""Request for the ``ListTopicSubscriptions`` method.
Attributes:
topic (str):
Required. The name of the topic that subscriptions are
attached to. Format is
``projects/{project}/topics/{topic}``.
page_size ... | class ListTopicSubscriptionsRequest(proto.Message):
| r"""Request for the ``ListTopicSubscriptions`` method.
Attributes:
topic (str):
Required. The name of the topic that subscriptions are
attached to. Format is
``projects/{project}/topics/{topic}``.
page_size (int):
Maximum number of subscription na... | ``ListTopicsRequest``.
"""
@property
def raw_page(self):
return self
topics = proto.RepeatedField(proto.MESSAGE, number=1, message="Topic",)
next_page_token = proto.Field(proto.STRING, number=2,)
class ListTopicSubscriptionsRequest(proto.Message):
| 63 | 64 | 171 | 8 | 55 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ListTopicSubscriptionsRequest | ListTopicSubscriptionsRequest | 328 | 348 | 328 | 328 | 1f04d18d817e7c61bc988281b5b73b0682adf44c | bigcode/the-stack | train |
ecea01166beb3588e888e504 | train | class | class PublishResponse(proto.Message):
r"""Response for the ``Publish`` method.
Attributes:
message_ids (Sequence[str]):
The server-assigned ID of each published
message, in the same order as the messages in
the request. IDs are guaranteed to be unique
wit... | class PublishResponse(proto.Message):
| r"""Response for the ``Publish`` method.
Attributes:
message_ids (Sequence[str]):
The server-assigned ID of each published
message, in the same order as the messages in
the request. IDs are guaranteed to be unique
within the topic.
"""
message_id... | messages (Sequence[google.pubsub_v1.types.PubsubMessage]):
Required. The messages to publish.
"""
topic = proto.Field(proto.STRING, number=1,)
messages = proto.RepeatedField(proto.MESSAGE, number=2, message="PubsubMessage",)
class PublishResponse(proto.Message):
| 64 | 64 | 82 | 6 | 58 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | PublishResponse | PublishResponse | 273 | 284 | 273 | 273 | 67eb85bc2755b0448351a8f2d39f230fcd4088bd | bigcode/the-stack | train |
3124ea962593bf47e93dc87a | train | class | class DeadLetterPolicy(proto.Message):
r"""Dead lettering is done on a best effort basis. The same
message might be dead lettered multiple times.
If validation on any of the fields fails at subscription
creation/updation, the create/update subscription request will
fail.
Attributes:
de... | class DeadLetterPolicy(proto.Message):
| r"""Dead lettering is done on a best effort basis. The same
message might be dead lettered multiple times.
If validation on any of the fields fails at subscription
creation/updation, the create/update subscription request will
fail.
Attributes:
dead_letter_topic (str):
The ... | .
maximum_backoff (google.protobuf.duration_pb2.Duration):
The maximum delay between consecutive
deliveries of a given message. Value should be
between 0 and 600 seconds. Defaults to 600
seconds.
"""
minimum_backoff = proto.Field(
proto.MESSAGE, n... | 107 | 107 | 359 | 7 | 100 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | DeadLetterPolicy | DeadLetterPolicy | 631 | 671 | 631 | 631 | 1c0d0dc2be4995efa613e4a0a935c53fa254bc5d | bigcode/the-stack | train |
c87cfc7fc9fd4c28f1bff054 | train | class | class SchemaSettings(proto.Message):
r"""Settings for validating messages published against a schema.
Attributes:
schema (str):
Required. The name of the schema that messages published
should be validated against. Format is
``projects/{project}/schemas/{schema}``. Th... | class SchemaSettings(proto.Message):
| r"""Settings for validating messages published against a schema.
Attributes:
schema (str):
Required. The name of the schema that messages published
should be validated against. Format is
``projects/{project}/schemas/{schema}``. The value of this
field wil... | CP altogether) will be routed for
storage in one of the allowed regions. An empty
list means that no regions are allowed, and is
not a valid configuration.
"""
allowed_persistence_regions = proto.RepeatedField(proto.STRING, number=1,)
class SchemaSettings(proto.Message):
| 63 | 64 | 137 | 6 | 57 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | SchemaSettings | SchemaSettings | 94 | 109 | 94 | 94 | 8ba4240d44b148f781aab91225ef6d551b252bd1 | bigcode/the-stack | train |
7f50f26907b20fea70c44b65 | train | class | class CreateSnapshotRequest(proto.Message):
r"""Request for the ``CreateSnapshot`` method.
Attributes:
name (str):
Required. User-provided name for this snapshot. If the name
is not provided in the request, the server will assign a
random name for this snapshot on th... | class CreateSnapshotRequest(proto.Message):
| r"""Request for the ``CreateSnapshot`` method.
Attributes:
name (str):
Required. User-provided name for this snapshot. If the name
is not provided in the request, the server will assign a
random name for this snapshot on the same project as the
subscripti... | Attributes:
message_ordering_enabled (bool):
True iff message ordering is enabled for this
subscription.
"""
message_ordering_enabled = proto.Field(proto.BOOL, number=2,)
received_messages = proto.RepeatedField(
proto.MESSAGE, number=1, message=... | 95 | 95 | 318 | 7 | 88 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | CreateSnapshotRequest | CreateSnapshotRequest | 1,132 | 1,162 | 1,132 | 1,132 | 59b604e1547728c5f838974ab50c44a12eb8df61 | bigcode/the-stack | train |
759a4f2fc01a6de8333a1c11 | train | class | class DeleteTopicRequest(proto.Message):
r"""Request for the ``DeleteTopic`` method.
Attributes:
topic (str):
Required. Name of the topic to delete. Format is
``projects/{project}/topics/{topic}``.
"""
topic = proto.Field(proto.STRING, number=1,)
| class DeleteTopicRequest(proto.Message):
| r"""Request for the ``DeleteTopic`` method.
Attributes:
topic (str):
Required. Name of the topic to delete. Format is
``projects/{project}/topics/{topic}``.
"""
topic = proto.Field(proto.STRING, number=1,)
| ``ListTopicSnapshotsRequest`` to get more snapshots.
"""
@property
def raw_page(self):
return self
snapshots = proto.RepeatedField(proto.STRING, number=1,)
next_page_token = proto.Field(proto.STRING, number=2,)
class DeleteTopicRequest(proto.Message):
| 63 | 64 | 65 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | DeleteTopicRequest | DeleteTopicRequest | 414 | 423 | 414 | 414 | 38b56f8c064115caa0ce8625d88a5be54063763d | bigcode/the-stack | train |
57afbc2dd16c30fea70b4dc4 | train | class | class SeekRequest(proto.Message):
r"""Request for the ``Seek`` method.
This message has `oneof`_ fields (mutually exclusive fields).
For each oneof, at most one member field can be set at the same time.
Setting any member of the oneof automatically clears all other
members.
.. _oneof: https://... | class SeekRequest(proto.Message):
| r"""Request for the ``Seek`` method.
This message has `oneof`_ fields (mutually exclusive fields).
For each oneof, at most one member field can be set at the same time.
Setting any member of the oneof automatically clears all other
members.
.. _oneof: https://proto-plus-python.readthedocs.io/e... | """
@property
def raw_page(self):
return self
snapshots = proto.RepeatedField(proto.MESSAGE, number=1, message="Snapshot",)
next_page_token = proto.Field(proto.STRING, number=2,)
class DeleteSnapshotRequest(proto.Message):
r"""Request for the ``DeleteSnapshot`` method.
Attributes:
... | 122 | 123 | 413 | 6 | 116 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | SeekRequest | SeekRequest | 1,286 | 1,327 | 1,286 | 1,286 | 806d8f4510bd3f8766a6a87ffa9466837987cd96 | bigcode/the-stack | train |
7ea5e1d7a575dfc94354146d | train | class | class DetachSubscriptionRequest(proto.Message):
r"""Request for the DetachSubscription method.
Attributes:
subscription (str):
Required. The subscription to detach. Format is
``projects/{project}/subscriptions/{subscription}``.
"""
subscription = proto.Field(proto.STRIN... | class DetachSubscriptionRequest(proto.Message):
| r"""Request for the DetachSubscription method.
Attributes:
subscription (str):
Required. The subscription to detach. Format is
``projects/{project}/subscriptions/{subscription}``.
"""
subscription = proto.Field(proto.STRING, number=1,)
| Request for the ``DeleteTopic`` method.
Attributes:
topic (str):
Required. Name of the topic to delete. Format is
``projects/{project}/topics/{topic}``.
"""
topic = proto.Field(proto.STRING, number=1,)
class DetachSubscriptionRequest(proto.Message):
| 63 | 64 | 63 | 8 | 55 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | DetachSubscriptionRequest | DetachSubscriptionRequest | 426 | 435 | 426 | 426 | bdf69c2e2df3ce83a8083ce6e9288bc362c18224 | bigcode/the-stack | train |
f17c66dad3b6ce9654deb409 | train | class | class SeekResponse(proto.Message):
r"""Response for the ``Seek`` method (this response is empty).
"""
| class SeekResponse(proto.Message):
| r"""Response for the ``Seek`` method (this response is empty).
"""
| subscription = proto.Field(proto.STRING, number=1,)
time = proto.Field(
proto.MESSAGE, number=2, oneof="target", message=timestamp_pb2.Timestamp,
)
snapshot = proto.Field(proto.STRING, number=3, oneof="target",)
class SeekResponse(proto.Message):
| 64 | 64 | 24 | 6 | 58 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | SeekResponse | SeekResponse | 1,330 | 1,332 | 1,330 | 1,330 | 4a7a7116a89a4a48c1f3434c17c5b22a385392bf | bigcode/the-stack | train |
f77446b03d859be40bee35e1 | train | class | class PublishRequest(proto.Message):
r"""Request for the Publish method.
Attributes:
topic (str):
Required. The messages in the request will be published on
this topic. Format is ``projects/{project}/topics/{topic}``.
messages (Sequence[google.pubsub_v1.types.PubsubMessa... | class PublishRequest(proto.Message):
| r"""Request for the Publish method.
Attributes:
topic (str):
Required. The messages in the request will be published on
this topic. Format is ``projects/{project}/topics/{topic}``.
messages (Sequence[google.pubsub_v1.types.PubsubMessage]):
Required. The messa... | by the
policy configured at the project or organization level.
"""
topic = proto.Field(proto.MESSAGE, number=1, message="Topic",)
update_mask = proto.Field(
proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,
)
class PublishRequest(proto.Message):
| 64 | 64 | 111 | 6 | 58 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | PublishRequest | PublishRequest | 258 | 270 | 258 | 258 | 7e7ff379706df9272058cd1a71c64100e2f156d1 | bigcode/the-stack | train |
86bfcdbbb26912ed42fe0be7 | train | class | class GetSnapshotRequest(proto.Message):
r"""Request for the GetSnapshot method.
Attributes:
snapshot (str):
Required. The name of the snapshot to get. Format is
``projects/{project}/snapshots/{snap}``.
"""
snapshot = proto.Field(proto.STRING, number=1,)
| class GetSnapshotRequest(proto.Message):
| r"""Request for the GetSnapshot method.
Attributes:
snapshot (str):
Required. The name of the snapshot to get. Format is
``projects/{project}/snapshots/{snap}``.
"""
snapshot = proto.Field(proto.STRING, number=1,)
| .Field(proto.STRING, number=1,)
topic = proto.Field(proto.STRING, number=2,)
expire_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,)
labels = proto.MapField(proto.STRING, proto.STRING, number=4,)
class GetSnapshotRequest(proto.Message):
| 63 | 64 | 65 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | GetSnapshotRequest | GetSnapshotRequest | 1,221 | 1,230 | 1,221 | 1,221 | 5b49a87807fa798aa2334aacc8f3716cf86170de | bigcode/the-stack | train |
3667bafeeda13c3a44558e10 | train | class | class StreamingPullRequest(proto.Message):
r"""Request for the ``StreamingPull`` streaming RPC method. This request
is used to establish the initial stream as well as to stream
acknowledgements and ack deadline modifications from the client to
the server.
Attributes:
subscription (str):
... | class StreamingPullRequest(proto.Message):
| r"""Request for the ``StreamingPull`` streaming RPC method. This request
is used to establish the initial stream as well as to stream
acknowledgements and ack deadline modifications from the client to
the server.
Attributes:
subscription (str):
Required. The subscription for whi... | was made. Specifying
zero might immediately make the message available for
delivery to another subscriber client. This typically
results in an increase in the rate of message redeliveries
(that is, duplicates). The minimum deadline you can specify
is 0 second... | 255 | 256 | 1,097 | 7 | 248 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | StreamingPullRequest | StreamingPullRequest | 1,007 | 1,098 | 1,007 | 1,007 | c9c4e64dcea7f89810cb1d744b12c13fa6c95fb0 | bigcode/the-stack | train |
ab4a33dcffc1f02ba5d4e462 | train | class | class UpdateTopicRequest(proto.Message):
r"""Request for the UpdateTopic method.
Attributes:
topic (google.pubsub_v1.types.Topic):
Required. The updated topic object.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Required. Indicates which fields in the provided... | class UpdateTopicRequest(proto.Message):
| r"""Request for the UpdateTopic method.
Attributes:
topic (google.pubsub_v1.types.Topic):
Required. The updated topic object.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Required. Indicates which fields in the provided topic to
update. Must be spe... | r"""Request for the GetTopic method.
Attributes:
topic (str):
Required. The name of the topic to get. Format is
``projects/{project}/topics/{topic}``.
"""
topic = proto.Field(proto.STRING, number=1,)
class UpdateTopicRequest(proto.Message):
| 63 | 64 | 175 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | UpdateTopicRequest | UpdateTopicRequest | 237 | 255 | 237 | 237 | c9bee556cd4d574ec584461a6c4492489ff2cbc5 | bigcode/the-stack | train |
a8a1b2edb9082344fc3fe8f0 | train | class | class StreamingPullResponse(proto.Message):
r"""Response for the ``StreamingPull`` method. This response is used to
stream messages from the server to the client.
Attributes:
received_messages (Sequence[google.pubsub_v1.types.ReceivedMessage]):
Received Pub/Sub messages. This will not b... | class StreamingPullResponse(proto.Message):
| r"""Response for the ``StreamingPull`` method. This response is used to
stream messages from the server to the client.
Attributes:
received_messages (Sequence[google.pubsub_v1.types.ReceivedMessage]):
Received Pub/Sub messages. This will not be
empty.
subscription_pr... | = proto.Field(proto.INT32, number=5,)
client_id = proto.Field(proto.STRING, number=6,)
max_outstanding_messages = proto.Field(proto.INT64, number=7,)
max_outstanding_bytes = proto.Field(proto.INT64, number=8,)
class StreamingPullResponse(proto.Message):
| 63 | 64 | 202 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | StreamingPullResponse | StreamingPullResponse | 1,101 | 1,129 | 1,101 | 1,101 | dac66e147ad2ec53604d9043da634cf772b09724 | bigcode/the-stack | train |
81d786de5d6a1bdad70774af | train | class | class GetSubscriptionRequest(proto.Message):
r"""Request for the GetSubscription method.
Attributes:
subscription (str):
Required. The name of the subscription to get. Format is
``projects/{project}/subscriptions/{sub}``.
"""
subscription = proto.Field(proto.STRING, num... | class GetSubscriptionRequest(proto.Message):
| r"""Request for the GetSubscription method.
Attributes:
subscription (str):
Required. The name of the subscription to get. Format is
``projects/{project}/subscriptions/{sub}``.
"""
subscription = proto.Field(proto.STRING, number=1,)
| this
will be 0.
"""
ack_id = proto.Field(proto.STRING, number=1,)
message = proto.Field(proto.MESSAGE, number=2, message="PubsubMessage",)
delivery_attempt = proto.Field(proto.INT32, number=3,)
class GetSubscriptionRequest(proto.Message):
| 63 | 64 | 64 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | GetSubscriptionRequest | GetSubscriptionRequest | 810 | 819 | 810 | 810 | 99c2531286be66aefa923db9f22ef0b2edfee92b | bigcode/the-stack | train |
30842247211f2b8b0516d445 | train | class | class DeleteSubscriptionRequest(proto.Message):
r"""Request for the DeleteSubscription method.
Attributes:
subscription (str):
Required. The subscription to delete. Format is
``projects/{project}/subscriptions/{sub}``.
"""
subscription = proto.Field(proto.STRING, number... | class DeleteSubscriptionRequest(proto.Message):
| r"""Request for the DeleteSubscription method.
Attributes:
subscription (str):
Required. The subscription to delete. Format is
``projects/{project}/subscriptions/{sub}``.
"""
subscription = proto.Field(proto.STRING, number=1,)
| get more subscriptions.
"""
@property
def raw_page(self):
return self
subscriptions = proto.RepeatedField(
proto.MESSAGE, number=1, message="Subscription",
)
next_page_token = proto.Field(proto.STRING, number=2,)
class DeleteSubscriptionRequest(proto.Message):
| 63 | 64 | 61 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | DeleteSubscriptionRequest | DeleteSubscriptionRequest | 883 | 892 | 883 | 883 | c9c5ee1be8a50db7751d5b2ca963b3cd0bb08091 | bigcode/the-stack | train |
9f9f54a7b8a91710c1c09721 | train | class | class ListSubscriptionsResponse(proto.Message):
r"""Response for the ``ListSubscriptions`` method.
Attributes:
subscriptions (Sequence[google.pubsub_v1.types.Subscription]):
The subscriptions that match the request.
next_page_token (str):
If not empty, indicates that the... | class ListSubscriptionsResponse(proto.Message):
| r"""Response for the ``ListSubscriptions`` method.
Attributes:
subscriptions (Sequence[google.pubsub_v1.types.Subscription]):
The subscriptions that match the request.
next_page_token (str):
If not empty, indicates that there may be more subscriptions
that ma... | , and that
the system should return the next page of data.
"""
project = proto.Field(proto.STRING, number=1,)
page_size = proto.Field(proto.INT32, number=2,)
page_token = proto.Field(proto.STRING, number=3,)
class ListSubscriptionsResponse(proto.Message):
| 63 | 64 | 141 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ListSubscriptionsResponse | ListSubscriptionsResponse | 861 | 880 | 861 | 861 | 5c1bd9ed2af1a3f5062609a61b87b59a1dcac6c6 | bigcode/the-stack | train |
8db52fd434f67685957ef444 | train | class | class PubsubMessage(proto.Message):
r"""A message that is published by publishers and consumed by
subscribers. The message must contain either a non-empty data field
or at least one attribute. Note that client libraries represent this
object differently depending on the language. See the corresponding
... | class PubsubMessage(proto.Message):
| r"""A message that is published by publishers and consumed by
subscribers. The message must contain either a non-empty data field
or at least one attribute. Note that client libraries represent this
object differently depending on the language. See the corresponding
`client library
documentation... | by
settings on individual subscriptions. Cannot be more than 7
days or less than 10 minutes.
"""
name = proto.Field(proto.STRING, number=1,)
labels = proto.MapField(proto.STRING, proto.STRING, number=2,)
message_storage_policy = proto.Field(
proto.MESSAGE, number=3, mes... | 159 | 159 | 531 | 7 | 152 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | PubsubMessage | PubsubMessage | 173 | 222 | 173 | 173 | 55b46b62a2ba52f233f3426df7b74eb27edbf0ac | bigcode/the-stack | train |
3953b9e9971750e1e45e15bb | train | class | class GetTopicRequest(proto.Message):
r"""Request for the GetTopic method.
Attributes:
topic (str):
Required. The name of the topic to get. Format is
``projects/{project}/topics/{topic}``.
"""
topic = proto.Field(proto.STRING, number=1,)
| class GetTopicRequest(proto.Message):
| r"""Request for the GetTopic method.
Attributes:
topic (str):
Required. The name of the topic to get. Format is
``projects/{project}/topics/{topic}``.
"""
topic = proto.Field(proto.STRING, number=1,)
| .STRING, number=2,)
message_id = proto.Field(proto.STRING, number=3,)
publish_time = proto.Field(
proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,
)
ordering_key = proto.Field(proto.STRING, number=5,)
class GetTopicRequest(proto.Message):
| 63 | 64 | 64 | 7 | 56 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | GetTopicRequest | GetTopicRequest | 225 | 234 | 225 | 225 | 241f3543aa3265d1fbff6d2b64bd6894710f625c | bigcode/the-stack | train |
8325ab3a7336d5f44077631a | train | class | class ListTopicSnapshotsResponse(proto.Message):
r"""Response for the ``ListTopicSnapshots`` method.
Attributes:
snapshots (Sequence[str]):
The names of the snapshots that match the
request.
next_page_token (str):
If not empty, indicates that there may be mor... | class ListTopicSnapshotsResponse(proto.Message):
| r"""Response for the ``ListTopicSnapshots`` method.
Attributes:
snapshots (Sequence[str]):
The names of the snapshots that match the
request.
next_page_token (str):
If not empty, indicates that there may be more snapshots
that match the request; t... | and
that the system should return the next page of data.
"""
topic = proto.Field(proto.STRING, number=1,)
page_size = proto.Field(proto.INT32, number=2,)
page_token = proto.Field(proto.STRING, number=3,)
class ListTopicSnapshotsResponse(proto.Message):
| 63 | 64 | 134 | 8 | 55 | huydinhle/python-pubsub | google/pubsub_v1/types/pubsub.py | Python | ListTopicSnapshotsResponse | ListTopicSnapshotsResponse | 393 | 411 | 393 | 393 | dc9c3ef882d3862a5ea67eee21404a14a4eb6f25 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.