blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
db1d4a3da7a83ce12d74b4aaf8db23295dfee816 | [
"super(Attention, self).__init__()\nassert kernel_size % 2 == 1, \"Kernel size should be odd for 'same' conv.\"\npadding = (kernel_size - 1) // 2\nself.conv = nn.Conv1d(1, 1, kernel_size, padding=padding)\nself.log_t = log_t",
"pax = eh * dhx\npax = torch.sum(pax, dim=2)\nif ax is not None:\n ax = ax.unsqueeze... | <|body_start_0|>
super(Attention, self).__init__()
assert kernel_size % 2 == 1, "Kernel size should be odd for 'same' conv."
padding = (kernel_size - 1) // 2
self.conv = nn.Conv1d(1, 1, kernel_size, padding=padding)
self.log_t = log_t
<|end_body_0|>
<|body_start_1|>
pax ... | Attention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
def __init__(self, kernel_size=11, log_t=False):
"""Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' and 'location' based attention. The 'content' based attention is an inner product of the decoder hid... | stack_v2_sparse_classes_75kplus_train_074000 | 19,030 | no_license | [
{
"docstring": "Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' and 'location' based attention. The 'content' based attention is an inner product of the decoder hidden state with each time-step of the encoder state. The 'location' base... | 2 | stack_v2_sparse_classes_30k_train_034688 | Implement the Python class `Attention` described below.
Class description:
Implement the Attention class.
Method signatures and docstrings:
- def __init__(self, kernel_size=11, log_t=False): Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' an... | Implement the Python class `Attention` described below.
Class description:
Implement the Attention class.
Method signatures and docstrings:
- def __init__(self, kernel_size=11, log_t=False): Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' an... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Attention:
def __init__(self, kernel_size=11, log_t=False):
"""Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' and 'location' based attention. The 'content' based attention is an inner product of the decoder hid... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Attention:
def __init__(self, kernel_size=11, log_t=False):
"""Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' and 'location' based attention. The 'content' based attention is an inner product of the decoder hidden state with... | the_stack_v2_python_sparse | generated/test_awni_speech.py | jansel/pytorch-jit-paritybench | train | 35 | |
65ebd55fb08637b995af30bf28739df4e56c5cb4 | [
"Base.__init__(self, server, key)\nself.spider = spider\nself.key = key % {'spider': spider.name}",
"org_dict = request_to_dict(request, self.spider)\nred_dict = RequestDeCompress.reduce_request_dict(org_dict)\nreturn pickle.dumps(red_dict, protocol=1)",
"red_dict = pickle.loads(encoded_request)\norg_dict = Req... | <|body_start_0|>
Base.__init__(self, server, key)
self.spider = spider
self.key = key % {'spider': spider.name}
<|end_body_0|>
<|body_start_1|>
org_dict = request_to_dict(request, self.spider)
red_dict = RequestDeCompress.reduce_request_dict(org_dict)
return pickle.dumps... | RequestQueue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestQueue:
def __init__(self, server, spider, key):
"""Initialize per-spider redis queue. Parameters: server -- redis connection spider -- spider instance key -- key for this queue (e.g. "%(spider)s:queue")"""
<|body_0|>
def _encode_request(self, request):
"""Enco... | stack_v2_sparse_classes_75kplus_train_074001 | 8,663 | no_license | [
{
"docstring": "Initialize per-spider redis queue. Parameters: server -- redis connection spider -- spider instance key -- key for this queue (e.g. \"%(spider)s:queue\")",
"name": "__init__",
"signature": "def __init__(self, server, spider, key)"
},
{
"docstring": "Encode a request object",
... | 3 | stack_v2_sparse_classes_30k_train_005958 | Implement the Python class `RequestQueue` described below.
Class description:
Implement the RequestQueue class.
Method signatures and docstrings:
- def __init__(self, server, spider, key): Initialize per-spider redis queue. Parameters: server -- redis connection spider -- spider instance key -- key for this queue (e.... | Implement the Python class `RequestQueue` described below.
Class description:
Implement the RequestQueue class.
Method signatures and docstrings:
- def __init__(self, server, spider, key): Initialize per-spider redis queue. Parameters: server -- redis connection spider -- spider instance key -- key for this queue (e.... | 0dc40186a1d89da2b00f29d4f4edfdc5470eb4fc | <|skeleton|>
class RequestQueue:
def __init__(self, server, spider, key):
"""Initialize per-spider redis queue. Parameters: server -- redis connection spider -- spider instance key -- key for this queue (e.g. "%(spider)s:queue")"""
<|body_0|>
def _encode_request(self, request):
"""Enco... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RequestQueue:
def __init__(self, server, spider, key):
"""Initialize per-spider redis queue. Parameters: server -- redis connection spider -- spider instance key -- key for this queue (e.g. "%(spider)s:queue")"""
Base.__init__(self, server, key)
self.spider = spider
self.key = ... | the_stack_v2_python_sparse | deploy/vertical_crawler_realtime/le_crawler/core/queue.py | cash2one/crawl_youtube | train | 0 | |
a577d974c9da21494dcab37849ef72837c034fa8 | [
"db_start = time()\nprint('database start time is {}'.format(db_start))\ntry:\n user_profile = UserProfile.objects.get(pk=pk)\nexcept UserProfile.DoesNotExist:\n return Response({'message': 'The User Profile does not exist'}, status=status.HTTP_404_NOT_FOUND)\ndb_time = time() - db_start\nprint('database acce... | <|body_start_0|>
db_start = time()
print('database start time is {}'.format(db_start))
try:
user_profile = UserProfile.objects.get(pk=pk)
except UserProfile.DoesNotExist:
return Response({'message': 'The User Profile does not exist'}, status=status.HTTP_404_NOT_FO... | UserProfileView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileView:
def get(self, request, pk, *args, **kwargs):
""":param request: :param pk: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
""":param request: :param pk: :param args: :param kwargs: :return:"""
<|bo... | stack_v2_sparse_classes_75kplus_train_074002 | 2,896 | no_license | [
{
"docstring": ":param request: :param pk: :param args: :param kwargs: :return:",
"name": "get",
"signature": "def get(self, request, pk, *args, **kwargs)"
},
{
"docstring": ":param request: :param pk: :param args: :param kwargs: :return:",
"name": "post",
"signature": "def post(self, re... | 4 | stack_v2_sparse_classes_30k_train_010646 | Implement the Python class `UserProfileView` described below.
Class description:
Implement the UserProfileView class.
Method signatures and docstrings:
- def get(self, request, pk, *args, **kwargs): :param request: :param pk: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): :param requ... | Implement the Python class `UserProfileView` described below.
Class description:
Implement the UserProfileView class.
Method signatures and docstrings:
- def get(self, request, pk, *args, **kwargs): :param request: :param pk: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): :param requ... | 1808c866a28ae1d9424d6d929890688b95cb7605 | <|skeleton|>
class UserProfileView:
def get(self, request, pk, *args, **kwargs):
""":param request: :param pk: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
""":param request: :param pk: :param args: :param kwargs: :return:"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserProfileView:
def get(self, request, pk, *args, **kwargs):
""":param request: :param pk: :param args: :param kwargs: :return:"""
db_start = time()
print('database start time is {}'.format(db_start))
try:
user_profile = UserProfile.objects.get(pk=pk)
excep... | the_stack_v2_python_sparse | assignment/promantus/views.py | kshitijParashar/PromantusApp | train | 0 | |
1c6576e5a1eb917bdc4badfd9d64f4736caae5ca | [
"self.c = capacity\nself.dic = {}\nself.stack = []\nself.count = 0",
"if key in self.dic:\n self.stack.remove(key)\n self.stack.insert(0, key)\n return self.dic[key]\nelse:\n return -1",
"if self.count < self.c:\n if key not in self.dic:\n self.count += 1\n else:\n self.stack.rem... | <|body_start_0|>
self.c = capacity
self.dic = {}
self.stack = []
self.count = 0
<|end_body_0|>
<|body_start_1|>
if key in self.dic:
self.stack.remove(key)
self.stack.insert(0, key)
return self.dic[key]
else:
return -1
<|end... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_074003 | 1,228 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_003718 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | bccd0f6ebb00e9569093f8ec18ebf0e94035dce6 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.c = capacity
self.dic = {}
self.stack = []
self.count = 0
def get(self, key):
""":type key: int :rtype: int"""
if key in self.dic:
self.stack.remove(key)
... | the_stack_v2_python_sparse | LRU Cache.py | nan0445/Leetcode-Python | train | 0 | |
c10d3dfb627060f9508d0175efbd614cec5a8d7d | [
"import h5py\ndata_cls = data.__class__\nwith h5py.File(hdf_filename, 'a') as hdf_file:\n if key in hdf_file:\n del hdf_file[key]\n hdf_file.create_group(key)\n key_format = '{}/%0{}d'.format(key, len(str(len(data))))\n for index, obj in enumerate(data):\n obj.save_to_hdf5(hdf_file, key_fo... | <|body_start_0|>
import h5py
data_cls = data.__class__
with h5py.File(hdf_filename, 'a') as hdf_file:
if key in hdf_file:
del hdf_file[key]
hdf_file.create_group(key)
key_format = '{}/%0{}d'.format(key, len(str(len(data))))
for inde... | class that represents a collection of values that are only loaded when they are accessed | LazyHDFCollection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LazyHDFCollection:
"""class that represents a collection of values that are only loaded when they are accessed"""
def create_from_data(cls, key, data, hdf_filename):
"""store the data in a HDF file and return the storage object"""
<|body_0|>
def load(self):
"""lo... | stack_v2_sparse_classes_75kplus_train_074004 | 19,788 | permissive | [
{
"docstring": "store the data in a HDF file and return the storage object",
"name": "create_from_data",
"signature": "def create_from_data(cls, key, data, hdf_filename)"
},
{
"docstring": "load the data and return it",
"name": "load",
"signature": "def load(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005399 | Implement the Python class `LazyHDFCollection` described below.
Class description:
class that represents a collection of values that are only loaded when they are accessed
Method signatures and docstrings:
- def create_from_data(cls, key, data, hdf_filename): store the data in a HDF file and return the storage object... | Implement the Python class `LazyHDFCollection` described below.
Class description:
class that represents a collection of values that are only loaded when they are accessed
Method signatures and docstrings:
- def create_from_data(cls, key, data, hdf_filename): store the data in a HDF file and return the storage object... | 2afae32df4fe9609c792a3b608cad79833f4178f | <|skeleton|>
class LazyHDFCollection:
"""class that represents a collection of values that are only loaded when they are accessed"""
def create_from_data(cls, key, data, hdf_filename):
"""store the data in a HDF file and return the storage object"""
<|body_0|>
def load(self):
"""lo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LazyHDFCollection:
"""class that represents a collection of values that are only loaded when they are accessed"""
def create_from_data(cls, key, data, hdf_filename):
"""store the data in a HDF file and return the storage object"""
import h5py
data_cls = data.__class__
with... | the_stack_v2_python_sparse | utils/data_structures/nested_dict.py | david-zwicker/py-utils | train | 0 |
b7bdfcd7be53dd9cab52129cee67509fae226644 | [
"cryptor = AES.new(cls.key, cls.mode, cls.key)\ntext = text.encode('utf-8')\ncount = len(text)\nadd = cls.length - count % cls.length\ntext = text + b'\\x00' * add\nciphertext = cryptor.encrypt(text)\nreturn b2a_hex(ciphertext).decode('ASCII')",
"cryptor = AES.new(cls.key, cls.mode, cls.key)\nplain_text = cryptor... | <|body_start_0|>
cryptor = AES.new(cls.key, cls.mode, cls.key)
text = text.encode('utf-8')
count = len(text)
add = cls.length - count % cls.length
text = text + b'\x00' * add
ciphertext = cryptor.encrypt(text)
return b2a_hex(ciphertext).decode('ASCII')
<|end_body_... | Aes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Aes:
def encrypt(cls, text):
""":param text: 如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数 :return: 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题 所以这里统一把加密后的字符串转化为16进制字符串 Usage:: >>> Aes.encrypt(text)"""
<|body_0|>
def decrypt(cls, text):
"""解密后,去掉补足的空格用strip() 去掉 Usa... | stack_v2_sparse_classes_75kplus_train_074005 | 2,042 | no_license | [
{
"docstring": ":param text: 如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数 :return: 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题 所以这里统一把加密后的字符串转化为16进制字符串 Usage:: >>> Aes.encrypt(text)",
"name": "encrypt",
"signature": "def encrypt(cls, text)"
},
{
"docstring": "解密后,去掉补足的空格用strip() 去掉 Usage:: >>>... | 2 | null | Implement the Python class `Aes` described below.
Class description:
Implement the Aes class.
Method signatures and docstrings:
- def encrypt(cls, text): :param text: 如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数 :return: 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题 所以这里统一把加密后的字符串转化为16进制字符串 Usage:: >>> Aes.encrypt(te... | Implement the Python class `Aes` described below.
Class description:
Implement the Aes class.
Method signatures and docstrings:
- def encrypt(cls, text): :param text: 如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数 :return: 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题 所以这里统一把加密后的字符串转化为16进制字符串 Usage:: >>> Aes.encrypt(te... | 0b09280afe5b764a485b3bf6e760aaf9a68bc4d5 | <|skeleton|>
class Aes:
def encrypt(cls, text):
""":param text: 如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数 :return: 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题 所以这里统一把加密后的字符串转化为16进制字符串 Usage:: >>> Aes.encrypt(text)"""
<|body_0|>
def decrypt(cls, text):
"""解密后,去掉补足的空格用strip() 去掉 Usa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Aes:
def encrypt(cls, text):
""":param text: 如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数 :return: 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题 所以这里统一把加密后的字符串转化为16进制字符串 Usage:: >>> Aes.encrypt(text)"""
cryptor = AES.new(cls.key, cls.mode, cls.key)
text = text.encode('utf-8')
c... | the_stack_v2_python_sparse | utils/security.py | pickCloud/TenCloud_Backend | train | 0 | |
6ee119ef6d7d818043533f2c063e13e9bcb49b65 | [
"super(MenuScene, self).__init__(parent, style)\nself.audio = audio\nself.key_up = key_up\nself.key_down = key_down\nself.on_game_start = on_game_start\nself.cursor = Bomb(parent=self, style={})\nself.sel = Selections(parent=self, style={'left': '25%', 'top': '50%', 'width': '50%', 'height': '30%'}, font='MS Gothic... | <|body_start_0|>
super(MenuScene, self).__init__(parent, style)
self.audio = audio
self.key_up = key_up
self.key_down = key_down
self.on_game_start = on_game_start
self.cursor = Bomb(parent=self, style={})
self.sel = Selections(parent=self, style={'left': '25%', '... | The game scene that display the main menu from game start. | MenuScene | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuScene:
"""The game scene that display the main menu from game start."""
def __init__(self, parent, style, audio, key_down, key_up, on_game_start):
"""Create and put the components."""
<|body_0|>
def on_update(self, cr):
"""Simply display the background image ... | stack_v2_sparse_classes_75kplus_train_074006 | 4,460 | no_license | [
{
"docstring": "Create and put the components.",
"name": "__init__",
"signature": "def __init__(self, parent, style, audio, key_down, key_up, on_game_start)"
},
{
"docstring": "Simply display the background image (centered and touching the window from outside). Display of other GUI components ar... | 3 | stack_v2_sparse_classes_30k_train_044252 | Implement the Python class `MenuScene` described below.
Class description:
The game scene that display the main menu from game start.
Method signatures and docstrings:
- def __init__(self, parent, style, audio, key_down, key_up, on_game_start): Create and put the components.
- def on_update(self, cr): Simply display ... | Implement the Python class `MenuScene` described below.
Class description:
The game scene that display the main menu from game start.
Method signatures and docstrings:
- def __init__(self, parent, style, audio, key_down, key_up, on_game_start): Create and put the components.
- def on_update(self, cr): Simply display ... | 54662d17f7d7a6f00525629e6dc543127be67086 | <|skeleton|>
class MenuScene:
"""The game scene that display the main menu from game start."""
def __init__(self, parent, style, audio, key_down, key_up, on_game_start):
"""Create and put the components."""
<|body_0|>
def on_update(self, cr):
"""Simply display the background image ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MenuScene:
"""The game scene that display the main menu from game start."""
def __init__(self, parent, style, audio, key_down, key_up, on_game_start):
"""Create and put the components."""
super(MenuScene, self).__init__(parent, style)
self.audio = audio
self.key_up = key_u... | the_stack_v2_python_sparse | menuscene.py | konyavic/bombercan | train | 0 |
0d165e964441b323d680d2ffe8e2133785632579 | [
"if cls._jwt_token is None or time() + 30 > cls._exp:\n cls.update_authentication_token()\nreturn Authentication._jwt_token",
"if cls._credentials.access_key is None:\n raise UnauthorizedException('Environment variable smc_api_key is not set')\nelif cls._credentials.secret_access_key is None:\n raise Una... | <|body_start_0|>
if cls._jwt_token is None or time() + 30 > cls._exp:
cls.update_authentication_token()
return Authentication._jwt_token
<|end_body_0|>
<|body_start_1|>
if cls._credentials.access_key is None:
raise UnauthorizedException('Environment variable smc_api_key ... | Class to retrieve authentication token (jwt token). | Authentication | [
"MIT",
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Authentication:
"""Class to retrieve authentication token (jwt token)."""
def get_authentication_token(cls) -> str:
"""get a valid jwt token return: jwt-token"""
<|body_0|>
def update_authentication_token(cls) -> None:
"""update the jwt token (store the info in _... | stack_v2_sparse_classes_75kplus_train_074007 | 4,257 | permissive | [
{
"docstring": "get a valid jwt token return: jwt-token",
"name": "get_authentication_token",
"signature": "def get_authentication_token(cls) -> str"
},
{
"docstring": "update the jwt token (store the info in _jwt_token and _exp) :return: -",
"name": "update_authentication_token",
"signa... | 2 | stack_v2_sparse_classes_30k_train_022439 | Implement the Python class `Authentication` described below.
Class description:
Class to retrieve authentication token (jwt token).
Method signatures and docstrings:
- def get_authentication_token(cls) -> str: get a valid jwt token return: jwt-token
- def update_authentication_token(cls) -> None: update the jwt token... | Implement the Python class `Authentication` described below.
Class description:
Class to retrieve authentication token (jwt token).
Method signatures and docstrings:
- def get_authentication_token(cls) -> str: get a valid jwt token return: jwt-token
- def update_authentication_token(cls) -> None: update the jwt token... | 30f3b6c1fd80e5cfa5ce11e1daa08a09ab1e4e9b | <|skeleton|>
class Authentication:
"""Class to retrieve authentication token (jwt token)."""
def get_authentication_token(cls) -> str:
"""get a valid jwt token return: jwt-token"""
<|body_0|>
def update_authentication_token(cls) -> None:
"""update the jwt token (store the info in _... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Authentication:
"""Class to retrieve authentication token (jwt token)."""
def get_authentication_token(cls) -> str:
"""get a valid jwt token return: jwt-token"""
if cls._jwt_token is None or time() + 30 > cls._exp:
cls.update_authentication_token()
return Authenticatio... | the_stack_v2_python_sparse | swift_cloud_py/authentication/authentication.py | stijnfleuren/SwiftCloudApi | train | 3 |
3434a8cbe42e400ef22b03e3762039db62a57f72 | [
"if n == 0:\n return []\ncnts = [0] + [1] * 6 + [0] * (6 * n - 6)\nfor _ in range(n - 1):\n for i in range(6 * n, 0, -1):\n cnts[i] = sum(cnts[max(i - 6, 0):i])\nreturn list(filter(lambda a: a != 0, list(map(lambda a: a / 6 ** n, cnts))))",
"def diceCnt(n):\n if n == 1:\n return [0] + [1] *... | <|body_start_0|>
if n == 0:
return []
cnts = [0] + [1] * 6 + [0] * (6 * n - 6)
for _ in range(n - 1):
for i in range(6 * n, 0, -1):
cnts[i] = sum(cnts[max(i - 6, 0):i])
return list(filter(lambda a: a != 0, list(map(lambda a: a / 6 ** n, cnts))))
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_1(self, n: int) -> List[float]:
"""动态规划 迭代 :param n: :return:"""
<|body_0|>
def twoSum_2(self, n: int) -> List[float]:
"""动态规划 递归 :param n: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0:
return [... | stack_v2_sparse_classes_75kplus_train_074008 | 1,958 | no_license | [
{
"docstring": "动态规划 迭代 :param n: :return:",
"name": "twoSum_1",
"signature": "def twoSum_1(self, n: int) -> List[float]"
},
{
"docstring": "动态规划 递归 :param n: :return:",
"name": "twoSum_2",
"signature": "def twoSum_2(self, n: int) -> List[float]"
}
] | 2 | stack_v2_sparse_classes_30k_train_020210 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, n: int) -> List[float]: 动态规划 迭代 :param n: :return:
- def twoSum_2(self, n: int) -> List[float]: 动态规划 递归 :param n: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, n: int) -> List[float]: 动态规划 迭代 :param n: :return:
- def twoSum_2(self, n: int) -> List[float]: 动态规划 递归 :param n: :return:
<|skeleton|>
class Solution:
d... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def twoSum_1(self, n: int) -> List[float]:
"""动态规划 迭代 :param n: :return:"""
<|body_0|>
def twoSum_2(self, n: int) -> List[float]:
"""动态规划 递归 :param n: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def twoSum_1(self, n: int) -> List[float]:
"""动态规划 迭代 :param n: :return:"""
if n == 0:
return []
cnts = [0] + [1] * 6 + [0] * (6 * n - 6)
for _ in range(n - 1):
for i in range(6 * n, 0, -1):
cnts[i] = sum(cnts[max(i - 6, 0):i])
... | the_stack_v2_python_sparse | 剑指 Offer(第 2 版)/twoSum.py | MaoningGuan/LeetCode | train | 3 | |
e794ce18ddb07f3cfd0269d1942f8cab68b38b2b | [
"self.xmi_dir = xmi_dir\nself.partition = partition\nself.n_files = None if n_files == 'all' else int(n_files)",
"texts = []\nlabels = []\ntype_system_file = open(type_system_path, 'rb')\ntype_system = load_typesystem(type_system_file)\nxmi_paths = glob.glob(self.xmi_dir + '*.xmi')[:self.n_files]\ncaption = 'read... | <|body_start_0|>
self.xmi_dir = xmi_dir
self.partition = partition
self.n_files = None if n_files == 'all' else int(n_files)
<|end_body_0|>
<|body_start_1|>
texts = []
labels = []
type_system_file = open(type_system_path, 'rb')
type_system = load_typesystem(type_... | Make x and y from XMI files for train, dev, or test set | DTRData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DTRData:
"""Make x and y from XMI files for train, dev, or test set"""
def __init__(self, xmi_dir, partition='train', n_files='all'):
"""Constructor"""
<|body_0|>
def read(self):
"""Make x, y etc."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_074009 | 2,687 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, xmi_dir, partition='train', n_files='all')"
},
{
"docstring": "Make x, y etc.",
"name": "read",
"signature": "def read(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022103 | Implement the Python class `DTRData` described below.
Class description:
Make x and y from XMI files for train, dev, or test set
Method signatures and docstrings:
- def __init__(self, xmi_dir, partition='train', n_files='all'): Constructor
- def read(self): Make x, y etc. | Implement the Python class `DTRData` described below.
Class description:
Make x and y from XMI files for train, dev, or test set
Method signatures and docstrings:
- def __init__(self, xmi_dir, partition='train', n_files='all'): Constructor
- def read(self): Make x, y etc.
<|skeleton|>
class DTRData:
"""Make x an... | 7d44509621dcbd394d503301859002f8da132b5b | <|skeleton|>
class DTRData:
"""Make x and y from XMI files for train, dev, or test set"""
def __init__(self, xmi_dir, partition='train', n_files='all'):
"""Constructor"""
<|body_0|>
def read(self):
"""Make x, y etc."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DTRData:
"""Make x and y from XMI files for train, dev, or test set"""
def __init__(self, xmi_dir, partition='train', n_files='all'):
"""Constructor"""
self.xmi_dir = xmi_dir
self.partition = partition
self.n_files = None if n_files == 'all' else int(n_files)
def read... | the_stack_v2_python_sparse | Dtr/dtrdata.py | dmitriydligach/Thyme | train | 0 |
d372df81b583e370c42aec208c65edb12f45eddd | [
"self.n = int(n)\nself.p = float(p)\nif data is None:\n self.n = n\n self.p = p\n if n <= 0:\n raise ValueError('n must be a positive value')\n if not 0 < p < 1:\n raise ValueError('p must be greater than 0 and less than 1')\nelse:\n if not isinstance(data, list):\n raise TypeErr... | <|body_start_0|>
self.n = int(n)
self.p = float(p)
if data is None:
self.n = n
self.p = p
if n <= 0:
raise ValueError('n must be a positive value')
if not 0 < p < 1:
raise ValueError('p must be greater than 0 and les... | class that represents a binomial distribution | Binomial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Binomial:
"""class that represents a binomial distribution"""
def __init__(self, data=None, n=1, p=0.5):
"""initialize class"""
<|body_0|>
def pmf(self, k):
"""probability mass function"""
<|body_1|>
def cdf(self, k):
"""cumulative distributi... | stack_v2_sparse_classes_75kplus_train_074010 | 1,996 | no_license | [
{
"docstring": "initialize class",
"name": "__init__",
"signature": "def __init__(self, data=None, n=1, p=0.5)"
},
{
"docstring": "probability mass function",
"name": "pmf",
"signature": "def pmf(self, k)"
},
{
"docstring": "cumulative distribution function",
"name": "cdf",
... | 4 | null | Implement the Python class `Binomial` described below.
Class description:
class that represents a binomial distribution
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): initialize class
- def pmf(self, k): probability mass function
- def cdf(self, k): cumulative distribution function
- d... | Implement the Python class `Binomial` described below.
Class description:
class that represents a binomial distribution
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): initialize class
- def pmf(self, k): probability mass function
- def cdf(self, k): cumulative distribution function
- d... | cd386dd814ccb4869d33551b3ab8c3dd774fddf9 | <|skeleton|>
class Binomial:
"""class that represents a binomial distribution"""
def __init__(self, data=None, n=1, p=0.5):
"""initialize class"""
<|body_0|>
def pmf(self, k):
"""probability mass function"""
<|body_1|>
def cdf(self, k):
"""cumulative distributi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Binomial:
"""class that represents a binomial distribution"""
def __init__(self, data=None, n=1, p=0.5):
"""initialize class"""
self.n = int(n)
self.p = float(p)
if data is None:
self.n = n
self.p = p
if n <= 0:
raise Val... | the_stack_v2_python_sparse | math/0x03-probability/binomial.py | Noeuclides/holbertonschool-machine_learning | train | 0 |
1954606c6ec2884e57be0f4992d490f2853faf06 | [
"rng, inputs, shared_args = test_utils.get_common_model_test_inputs()\nmodel = bigbird.BigBirdEncoder(**shared_args, block_size=2)\nparams = model.init(rng, inputs)\ny = model.apply(params, inputs)\nself.assertEqual(y.shape, inputs.shape + (shared_args['emb_dim'],))",
"rng, inputs, shared_args = test_utils.get_sm... | <|body_start_0|>
rng, inputs, shared_args = test_utils.get_common_model_test_inputs()
model = bigbird.BigBirdEncoder(**shared_args, block_size=2)
params = model.init(rng, inputs)
y = model.apply(params, inputs)
self.assertEqual(y.shape, inputs.shape + (shared_args['emb_dim'],))
<... | Tests for the Big Bird model. | BigBirdTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BigBirdTest:
"""Tests for the Big Bird model."""
def test_bigbird(self):
"""Tests Big Bird model."""
<|body_0|>
def test_jit_bigbird(self):
"""Tests Big Bird model."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rng, inputs, shared_args = test_... | stack_v2_sparse_classes_75kplus_train_074011 | 1,726 | permissive | [
{
"docstring": "Tests Big Bird model.",
"name": "test_bigbird",
"signature": "def test_bigbird(self)"
},
{
"docstring": "Tests Big Bird model.",
"name": "test_jit_bigbird",
"signature": "def test_jit_bigbird(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012245 | Implement the Python class `BigBirdTest` described below.
Class description:
Tests for the Big Bird model.
Method signatures and docstrings:
- def test_bigbird(self): Tests Big Bird model.
- def test_jit_bigbird(self): Tests Big Bird model. | Implement the Python class `BigBirdTest` described below.
Class description:
Tests for the Big Bird model.
Method signatures and docstrings:
- def test_bigbird(self): Tests Big Bird model.
- def test_jit_bigbird(self): Tests Big Bird model.
<|skeleton|>
class BigBirdTest:
"""Tests for the Big Bird model."""
... | 1b4929016aba883d2f06fa1a51e343ccdbd631ed | <|skeleton|>
class BigBirdTest:
"""Tests for the Big Bird model."""
def test_bigbird(self):
"""Tests Big Bird model."""
<|body_0|>
def test_jit_bigbird(self):
"""Tests Big Bird model."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BigBirdTest:
"""Tests for the Big Bird model."""
def test_bigbird(self):
"""Tests Big Bird model."""
rng, inputs, shared_args = test_utils.get_common_model_test_inputs()
model = bigbird.BigBirdEncoder(**shared_args, block_size=2)
params = model.init(rng, inputs)
y ... | the_stack_v2_python_sparse | pegasus/flax/models/encoders/bigbird/test_bigbird.py | google-research/pegasus | train | 1,543 |
a6a56816dc507ade513c835b05d4d6f25b0741bd | [
"test = [1, 2, 32, 8, 17, 19, 42, 13, 0]\nself.assertTrue(sequential_search(test, 13))\nself.assertFalse(sequential_search(test, 3))",
"test = sorted([1, 2, 32, 8, 17, 19, 42, 13, 0])\nself.assertTrue(ordered_sequential_search(test, 13))\nself.assertFalse(ordered_sequential_search(test, 3))",
"test = sorted([1,... | <|body_start_0|>
test = [1, 2, 32, 8, 17, 19, 42, 13, 0]
self.assertTrue(sequential_search(test, 13))
self.assertFalse(sequential_search(test, 3))
<|end_body_0|>
<|body_start_1|>
test = sorted([1, 2, 32, 8, 17, 19, 42, 13, 0])
self.assertTrue(ordered_sequential_search(test, 13))... | Test Search methods. | TestSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSearch:
"""Test Search methods."""
def test_sequential(self):
"""Test Sequential Search method."""
<|body_0|>
def test_ordered_sequential(self):
"""Test Ordered Sequential Search method."""
<|body_1|>
def test_binary_search(self):
"""Test... | stack_v2_sparse_classes_75kplus_train_074012 | 993 | no_license | [
{
"docstring": "Test Sequential Search method.",
"name": "test_sequential",
"signature": "def test_sequential(self)"
},
{
"docstring": "Test Ordered Sequential Search method.",
"name": "test_ordered_sequential",
"signature": "def test_ordered_sequential(self)"
},
{
"docstring": "... | 3 | null | Implement the Python class `TestSearch` described below.
Class description:
Test Search methods.
Method signatures and docstrings:
- def test_sequential(self): Test Sequential Search method.
- def test_ordered_sequential(self): Test Ordered Sequential Search method.
- def test_binary_search(self): Test Binary Search ... | Implement the Python class `TestSearch` described below.
Class description:
Test Search methods.
Method signatures and docstrings:
- def test_sequential(self): Test Sequential Search method.
- def test_ordered_sequential(self): Test Ordered Sequential Search method.
- def test_binary_search(self): Test Binary Search ... | 8b01517c9cc3a9b07e6a103d52b87b5f56c4d394 | <|skeleton|>
class TestSearch:
"""Test Search methods."""
def test_sequential(self):
"""Test Sequential Search method."""
<|body_0|>
def test_ordered_sequential(self):
"""Test Ordered Sequential Search method."""
<|body_1|>
def test_binary_search(self):
"""Test... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestSearch:
"""Test Search methods."""
def test_sequential(self):
"""Test Sequential Search method."""
test = [1, 2, 32, 8, 17, 19, 42, 13, 0]
self.assertTrue(sequential_search(test, 13))
self.assertFalse(sequential_search(test, 3))
def test_ordered_sequential(self):
... | the_stack_v2_python_sparse | SortingAndSearching/test_search.py | ohduran/problemsolvingalgorithms | train | 0 |
d277cc6819383f75eb9462fb8f06f3b66478069b | [
"self.client = Client()\nself.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')\nself.test_user.is_superuser = True\nself.test_user.is_active = True\nself.test_user.save()\nself.assertEqual(self.test_user.is_superuser, True)\nlogin = self.client.login(username='testuser', password='t... | <|body_start_0|>
self.client = Client()
self.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')
self.test_user.is_superuser = True
self.test_user.is_active = True
self.test_user.save()
self.assertEqual(self.test_user.is_superuser, True)
... | This class tests various aspects of the :class:`~mousedb.veterinary.models.MedicalIssue` model. | MedicalIssueModelTests | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedicalIssueModelTests:
"""This class tests various aspects of the :class:`~mousedb.veterinary.models.MedicalIssue` model."""
def setUp(self):
"""Instantiate the test client. Creates a test user."""
<|body_0|>
def tearDown(self):
"""Depopulate created model insta... | stack_v2_sparse_classes_75kplus_train_074013 | 26,324 | permissive | [
{
"docstring": "Instantiate the test client. Creates a test user.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Depopulate created model instances from test database.",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "This test creat... | 6 | null | Implement the Python class `MedicalIssueModelTests` described below.
Class description:
This class tests various aspects of the :class:`~mousedb.veterinary.models.MedicalIssue` model.
Method signatures and docstrings:
- def setUp(self): Instantiate the test client. Creates a test user.
- def tearDown(self): Depopulat... | Implement the Python class `MedicalIssueModelTests` described below.
Class description:
This class tests various aspects of the :class:`~mousedb.veterinary.models.MedicalIssue` model.
Method signatures and docstrings:
- def setUp(self): Instantiate the test client. Creates a test user.
- def tearDown(self): Depopulat... | 7e423991f72c89468010c99865e3c70c22044df3 | <|skeleton|>
class MedicalIssueModelTests:
"""This class tests various aspects of the :class:`~mousedb.veterinary.models.MedicalIssue` model."""
def setUp(self):
"""Instantiate the test client. Creates a test user."""
<|body_0|>
def tearDown(self):
"""Depopulate created model insta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MedicalIssueModelTests:
"""This class tests various aspects of the :class:`~mousedb.veterinary.models.MedicalIssue` model."""
def setUp(self):
"""Instantiate the test client. Creates a test user."""
self.client = Client()
self.test_user = User.objects.create_user('testuser', 'blah... | the_stack_v2_python_sparse | mousedb/veterinary/tests.py | BridgesLab/mousedb | train | 0 |
1cc55762659acd6d08d73f179fcb41ad4ae806f4 | [
"config = g.user.get_api().get_configuration(configuration)\nview = config.get_view(view)\ntext_record = view.get_text_record(absolute_name)\nif text_record is None:\n return ('No matching Text Record(s) found', 404)\nresult = text_record.to_json()\nreturn jsonify(result)",
"config = g.user.get_api().get_confi... | <|body_start_0|>
config = g.user.get_api().get_configuration(configuration)
view = config.get_view(view)
text_record = view.get_text_record(absolute_name)
if text_record is None:
return ('No matching Text Record(s) found', 404)
result = text_record.to_json()
r... | TextRecord | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextRecord:
def get(self, configuration, view, absolute_name):
"""Get specified text record belonging to default or provided Configuration and View plus Zone hierarchy."""
<|body_0|>
def delete(self, configuration, view, absolute_name):
"""Delete specified text recor... | stack_v2_sparse_classes_75kplus_train_074014 | 33,507 | permissive | [
{
"docstring": "Get specified text record belonging to default or provided Configuration and View plus Zone hierarchy.",
"name": "get",
"signature": "def get(self, configuration, view, absolute_name)"
},
{
"docstring": "Delete specified text record belonging to default or provided Configuration ... | 3 | stack_v2_sparse_classes_30k_train_016406 | Implement the Python class `TextRecord` described below.
Class description:
Implement the TextRecord class.
Method signatures and docstrings:
- def get(self, configuration, view, absolute_name): Get specified text record belonging to default or provided Configuration and View plus Zone hierarchy.
- def delete(self, c... | Implement the Python class `TextRecord` described below.
Class description:
Implement the TextRecord class.
Method signatures and docstrings:
- def get(self, configuration, view, absolute_name): Get specified text record belonging to default or provided Configuration and View plus Zone hierarchy.
- def delete(self, c... | 60b36434e689c3ef852ab388ca2aae370e70c62d | <|skeleton|>
class TextRecord:
def get(self, configuration, view, absolute_name):
"""Get specified text record belonging to default or provided Configuration and View plus Zone hierarchy."""
<|body_0|>
def delete(self, configuration, view, absolute_name):
"""Delete specified text recor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextRecord:
def get(self, configuration, view, absolute_name):
"""Get specified text record belonging to default or provided Configuration and View plus Zone hierarchy."""
config = g.user.get_api().get_configuration(configuration)
view = config.get_view(view)
text_record = view... | the_stack_v2_python_sparse | Community/rest_api/dns_page.py | bluecatlabs/gateway-workflows | train | 45 | |
489580bddaec197759876c5efc0c5963b9f5383c | [
"try:\n automl_run(nnid)\n return Response(json.dumps([True]))\nexcept Exception as e:\n return_data = {'status': '404', 'result': str(e)}\n return Response(json.dumps(return_data))",
"try:\n return_data = ''\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {... | <|body_start_0|>
try:
automl_run(nnid)
return Response(json.dumps([True]))
except Exception as e:
return_data = {'status': '404', 'result': str(e)}
return Response(json.dumps(return_data))
<|end_body_0|>
<|body_start_1|>
try:
return_da... | RunManagerAutoTrain | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunManagerAutoTrain:
def post(self, request, nnid):
"""Bellow is the process of running automl on our framework (1) Define AutoML Graph definition (2) Select Type of Data (3) Select Type of Anal algorithm (4) Select range of hyper parameters (5) Run - AutoML (<- for this step) (6) Check ... | stack_v2_sparse_classes_75kplus_train_074015 | 3,403 | permissive | [
{
"docstring": "Bellow is the process of running automl on our framework (1) Define AutoML Graph definition (2) Select Type of Data (3) Select Type of Anal algorithm (4) Select range of hyper parameters (5) Run - AutoML (<- for this step) (6) Check result of each generation with UI/UX (7) Select Best model you ... | 4 | stack_v2_sparse_classes_30k_train_035972 | Implement the Python class `RunManagerAutoTrain` described below.
Class description:
Implement the RunManagerAutoTrain class.
Method signatures and docstrings:
- def post(self, request, nnid): Bellow is the process of running automl on our framework (1) Define AutoML Graph definition (2) Select Type of Data (3) Selec... | Implement the Python class `RunManagerAutoTrain` described below.
Class description:
Implement the RunManagerAutoTrain class.
Method signatures and docstrings:
- def post(self, request, nnid): Bellow is the process of running automl on our framework (1) Define AutoML Graph definition (2) Select Type of Data (3) Selec... | 6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f | <|skeleton|>
class RunManagerAutoTrain:
def post(self, request, nnid):
"""Bellow is the process of running automl on our framework (1) Define AutoML Graph definition (2) Select Type of Data (3) Select Type of Anal algorithm (4) Select range of hyper parameters (5) Run - AutoML (<- for this step) (6) Check ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RunManagerAutoTrain:
def post(self, request, nnid):
"""Bellow is the process of running automl on our framework (1) Define AutoML Graph definition (2) Select Type of Data (3) Select Type of Anal algorithm (4) Select range of hyper parameters (5) Run - AutoML (<- for this step) (6) Check result of each... | the_stack_v2_python_sparse | api/views/runmanager_auto_train.py | yurimkoo/tensormsa | train | 1 | |
db259b6d7f657989502622dc4ed41bb3a707fc0d | [
"self.model = model\nself.x_train = [tf.constant(x, dtype=tf.float32) for x in x_train]\nself.y_train = [tf.constant(y, dtype=tf.float32) for y in y_train]\nself.factr = factr\nself.m = m\nself.maxls = maxls\nself.maxiter = maxiter\nself.metrics = ['loss']\nself.progbar = tf.keras.callbacks.ProgbarLogger(count_mode... | <|body_start_0|>
self.model = model
self.x_train = [tf.constant(x, dtype=tf.float32) for x in x_train]
self.y_train = [tf.constant(y, dtype=tf.float32) for y in y_train]
self.factr = factr
self.m = m
self.maxls = maxls
self.maxiter = maxiter
self.metrics =... | Optimize the keras network model using L-BFGS-B algorithm. Attributes: model: optimization target model. samples: training samples. factr: convergence condition. typical values for factr are: 1e12 for low accuracy; 1e7 for moderate accuracy; 10 for extremely high accuracy. m: maximum number of variable metric correctio... | L_BFGS_B | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class L_BFGS_B:
"""Optimize the keras network model using L-BFGS-B algorithm. Attributes: model: optimization target model. samples: training samples. factr: convergence condition. typical values for factr are: 1e12 for low accuracy; 1e7 for moderate accuracy; 10 for extremely high accuracy. m: maximum... | stack_v2_sparse_classes_75kplus_train_074016 | 4,650 | permissive | [
{
"docstring": "Args: model: optimization target model. samples: training samples. factr: convergence condition. typical values for factr are: 1e12 for low accuracy; 1e7 for moderate accuracy; 10.0 for extremely high accuracy. m: maximum number of variable metric corrections used to define the limited memory ma... | 6 | null | Implement the Python class `L_BFGS_B` described below.
Class description:
Optimize the keras network model using L-BFGS-B algorithm. Attributes: model: optimization target model. samples: training samples. factr: convergence condition. typical values for factr are: 1e12 for low accuracy; 1e7 for moderate accuracy; 10 ... | Implement the Python class `L_BFGS_B` described below.
Class description:
Optimize the keras network model using L-BFGS-B algorithm. Attributes: model: optimization target model. samples: training samples. factr: convergence condition. typical values for factr are: 1e12 for low accuracy; 1e7 for moderate accuracy; 10 ... | 8385fbde566dca8a2baf715f32759fe07fdda4c4 | <|skeleton|>
class L_BFGS_B:
"""Optimize the keras network model using L-BFGS-B algorithm. Attributes: model: optimization target model. samples: training samples. factr: convergence condition. typical values for factr are: 1e12 for low accuracy; 1e7 for moderate accuracy; 10 for extremely high accuracy. m: maximum... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class L_BFGS_B:
"""Optimize the keras network model using L-BFGS-B algorithm. Attributes: model: optimization target model. samples: training samples. factr: convergence condition. typical values for factr are: 1e12 for low accuracy; 1e7 for moderate accuracy; 10 for extremely high accuracy. m: maximum number of va... | the_stack_v2_python_sparse | Thesis/PINN/pinn_wave-master/tester2/lib/optimizer.py | Teddyzander/PhysicsInformedNeuralNetwork | train | 5 |
63673cb6ca6ffd92a3b127858567658a7ea8be7e | [
"if val is not None:\n if isinstance(val, str):\n val = ipaddress.ip_address(val)\n return int(val)\nreturn None",
"if val is not None:\n return ipaddress.ip_address(val)\nreturn None"
] | <|body_start_0|>
if val is not None:
if isinstance(val, str):
val = ipaddress.ip_address(val)
return int(val)
return None
<|end_body_0|>
<|body_start_1|>
if val is not None:
return ipaddress.ip_address(val)
return None
<|end_body_1|>
| IP data field. | IPField | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPField:
"""IP data field."""
def db_value(self, val: 'Optional[Union[str, IPAddress]]') -> 'Optional[int]':
"""Dump the value for database storage. Args: value: Source IP address instance. Returns: Integral representation of the IP address."""
<|body_0|>
def python_valu... | stack_v2_sparse_classes_75kplus_train_074017 | 5,352 | permissive | [
{
"docstring": "Dump the value for database storage. Args: value: Source IP address instance. Returns: Integral representation of the IP address.",
"name": "db_value",
"signature": "def db_value(self, val: 'Optional[Union[str, IPAddress]]') -> 'Optional[int]'"
},
{
"docstring": "Load the value f... | 2 | stack_v2_sparse_classes_30k_train_025729 | Implement the Python class `IPField` described below.
Class description:
IP data field.
Method signatures and docstrings:
- def db_value(self, val: 'Optional[Union[str, IPAddress]]') -> 'Optional[int]': Dump the value for database storage. Args: value: Source IP address instance. Returns: Integral representation of t... | Implement the Python class `IPField` described below.
Class description:
IP data field.
Method signatures and docstrings:
- def db_value(self, val: 'Optional[Union[str, IPAddress]]') -> 'Optional[int]': Dump the value for database storage. Args: value: Source IP address instance. Returns: Integral representation of t... | ad8d7b3d6b55dd5654fcf55b6bce6ac290d5dfbf | <|skeleton|>
class IPField:
"""IP data field."""
def db_value(self, val: 'Optional[Union[str, IPAddress]]') -> 'Optional[int]':
"""Dump the value for database storage. Args: value: Source IP address instance. Returns: Integral representation of the IP address."""
<|body_0|>
def python_valu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IPField:
"""IP data field."""
def db_value(self, val: 'Optional[Union[str, IPAddress]]') -> 'Optional[int]':
"""Dump the value for database storage. Args: value: Source IP address instance. Returns: Integral representation of the IP address."""
if val is not None:
if isinstanc... | the_stack_v2_python_sparse | darc/model/utils.py | encryptedchoices/darc | train | 0 |
fcbd2917c5948a09fd84096c6bea32b5e1406fdc | [
"self.filename = filename\nself.filevalid = False\nself.exifvalid = False\nimg = self.initImage()\nif self.filevalid == True:\n self.initExif(img)\n self.initDates()",
"try:\n img = Image.open(self.filename)\n self.filevalid = True\nexcept IOError:\n print('Target image not found/valid %s' % self.f... | <|body_start_0|>
self.filename = filename
self.filevalid = False
self.exifvalid = False
img = self.initImage()
if self.filevalid == True:
self.initExif(img)
self.initDates()
<|end_body_0|>
<|body_start_1|>
try:
img = Image.open(self.fi... | Photo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Photo:
def __init__(self, filename):
"""Class constructor"""
<|body_0|>
def initImage(self):
"""opens the image and confirms if valid, returns Image"""
<|body_1|>
def initExif(self, image):
"""gets any Exif data from the photo"""
<|body_2... | stack_v2_sparse_classes_75kplus_train_074018 | 2,822 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "opens the image and confirms if valid, returns Image",
"name": "initImage",
"signature": "def initImage(self)"
},
{
"docstring": "gets any Exif data from the pho... | 6 | stack_v2_sparse_classes_30k_train_032847 | Implement the Python class `Photo` described below.
Class description:
Implement the Photo class.
Method signatures and docstrings:
- def __init__(self, filename): Class constructor
- def initImage(self): opens the image and confirms if valid, returns Image
- def initExif(self, image): gets any Exif data from the pho... | Implement the Python class `Photo` described below.
Class description:
Implement the Photo class.
Method signatures and docstrings:
- def __init__(self, filename): Class constructor
- def initImage(self): opens the image and confirms if valid, returns Image
- def initExif(self, image): gets any Exif data from the pho... | fde65012c8358b7089d5b49e10fc4c566175e12e | <|skeleton|>
class Photo:
def __init__(self, filename):
"""Class constructor"""
<|body_0|>
def initImage(self):
"""opens the image and confirms if valid, returns Image"""
<|body_1|>
def initExif(self, image):
"""gets any Exif data from the photo"""
<|body_2... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Photo:
def __init__(self, filename):
"""Class constructor"""
self.filename = filename
self.filevalid = False
self.exifvalid = False
img = self.initImage()
if self.filevalid == True:
self.initExif(img)
self.initDates()
def initImage(s... | the_stack_v2_python_sparse | Packt/PacktRPiPython/Chapter 03/photohandler_1stpart.py | floppyinfant/RaspberryPi | train | 0 | |
72a5672a6bae08e14ece7c8a608b058e163012e6 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('cici_fyl', 'cici_fyl')\npropertydata = repo['cici_fyl.property'].find()\nrestaurantdata = repo['cici_fyl.restaurant'].find()\ncoor = methods.selectcoordinate(restaurantdata)\nx = methods.appendattribute(... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('cici_fyl', 'cici_fyl')
propertydata = repo['cici_fyl.property'].find()
restaurantdata = repo['cici_fyl.restaurant'].find()
coor = methods.... | processrestaurant | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class processrestaurant:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everyt... | stack_v2_sparse_classes_75kplus_train_074019 | 3,335 | permissive | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_010336 | Implement the Python class `processrestaurant` described below.
Class description:
Implement the processrestaurant class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime... | Implement the Python class `processrestaurant` described below.
Class description:
Implement the processrestaurant class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class processrestaurant:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everyt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class processrestaurant:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('cici_fyl', 'cici_fyl')
pr... | the_stack_v2_python_sparse | cici_fyl/project/cici_fyl/processrestaurant.py | lingyigu/course-2017-spr-proj | train | 0 | |
e77b4e9442e97022883913cc634df9218ec149d0 | [
"super(RightBlock, self).__init__()\nself.up_layer = Sequential(Upsample(scale_factor=up_scale_factor, mode='bilinear', align_corners=True), ConvBlock(in_channels, out_channels, kernel_size, stride, padding))\nself.conv_layers = ConvBlock(in_channels, out_channels, kernel_size, stride, padding)",
"down_input = se... | <|body_start_0|>
super(RightBlock, self).__init__()
self.up_layer = Sequential(Upsample(scale_factor=up_scale_factor, mode='bilinear', align_corners=True), ConvBlock(in_channels, out_channels, kernel_size, stride, padding))
self.conv_layers = ConvBlock(in_channels, out_channels, kernel_size, str... | Right block of U-net model. Combines Upsampling and a block of two convolutional layers. | RightBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RightBlock:
"""Right block of U-net model. Combines Upsampling and a block of two convolutional layers."""
def __init__(self, in_channels: int, out_channels: int, kernel_size: tuple, stride: int, padding: int, up_scale_factor: int):
"""Initializes a Left Block. Parameters ---------- ... | stack_v2_sparse_classes_75kplus_train_074020 | 8,005 | permissive | [
{
"docstring": "Initializes a Left Block. Parameters ---------- in_channels : int Number of input channels to a convolutional block. out_channels : int Number of output channels to a convolutional block. kernel_size : tuple Size of a kernel in a convolutional layer. stride : int Stride used in a convolutional l... | 2 | stack_v2_sparse_classes_30k_train_037230 | Implement the Python class `RightBlock` described below.
Class description:
Right block of U-net model. Combines Upsampling and a block of two convolutional layers.
Method signatures and docstrings:
- def __init__(self, in_channels: int, out_channels: int, kernel_size: tuple, stride: int, padding: int, up_scale_facto... | Implement the Python class `RightBlock` described below.
Class description:
Right block of U-net model. Combines Upsampling and a block of two convolutional layers.
Method signatures and docstrings:
- def __init__(self, in_channels: int, out_channels: int, kernel_size: tuple, stride: int, padding: int, up_scale_facto... | 7187b78463136eef140893b216d1d311b20c827e | <|skeleton|>
class RightBlock:
"""Right block of U-net model. Combines Upsampling and a block of two convolutional layers."""
def __init__(self, in_channels: int, out_channels: int, kernel_size: tuple, stride: int, padding: int, up_scale_factor: int):
"""Initializes a Left Block. Parameters ---------- ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RightBlock:
"""Right block of U-net model. Combines Upsampling and a block of two convolutional layers."""
def __init__(self, in_channels: int, out_channels: int, kernel_size: tuple, stride: int, padding: int, up_scale_factor: int):
"""Initializes a Left Block. Parameters ---------- in_channels :... | the_stack_v2_python_sparse | carotids/segmentation/model_archive.py | kostelansky17/carotids | train | 2 |
6e5199c11a9801946035c9c29dfc5b829d2b6e66 | [
"self.screen_width = 1200\nself.screen_height = 600\nself.bg_color = (230, 230, 230)\nself.bullet_width = 2\nself.bullet_height = 12\nself.bullet_color = (60, 60, 60)\nself.bullet_allowed = 3\nself.fleet_drop_speed = 10\nself.ship_limit = 3\nself.speed_scale = 1.1\nself.score_scale = 1.5\nself.initialize_dynamic_se... | <|body_start_0|>
self.screen_width = 1200
self.screen_height = 600
self.bg_color = (230, 230, 230)
self.bullet_width = 2
self.bullet_height = 12
self.bullet_color = (60, 60, 60)
self.bullet_allowed = 3
self.fleet_drop_speed = 10
self.ship_limit = 3... | 存储这个游戏的所有基本设置 | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""存储这个游戏的所有基本设置"""
def __init__(self):
"""初始化游戏的设置"""
<|body_0|>
def initialize_dynamic_settings(self):
"""游戏变化设置初始化"""
<|body_1|>
def increase_speed(self):
"""提高速度"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_074021 | 1,673 | no_license | [
{
"docstring": "初始化游戏的设置",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "游戏变化设置初始化",
"name": "initialize_dynamic_settings",
"signature": "def initialize_dynamic_settings(self)"
},
{
"docstring": "提高速度",
"name": "increase_speed",
"signature": "de... | 3 | null | Implement the Python class `Settings` described below.
Class description:
存储这个游戏的所有基本设置
Method signatures and docstrings:
- def __init__(self): 初始化游戏的设置
- def initialize_dynamic_settings(self): 游戏变化设置初始化
- def increase_speed(self): 提高速度 | Implement the Python class `Settings` described below.
Class description:
存储这个游戏的所有基本设置
Method signatures and docstrings:
- def __init__(self): 初始化游戏的设置
- def initialize_dynamic_settings(self): 游戏变化设置初始化
- def increase_speed(self): 提高速度
<|skeleton|>
class Settings:
"""存储这个游戏的所有基本设置"""
def __init__(self):
... | 114bf86a071317d592cff2ba2ce92360b87cd48a | <|skeleton|>
class Settings:
"""存储这个游戏的所有基本设置"""
def __init__(self):
"""初始化游戏的设置"""
<|body_0|>
def initialize_dynamic_settings(self):
"""游戏变化设置初始化"""
<|body_1|>
def increase_speed(self):
"""提高速度"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Settings:
"""存储这个游戏的所有基本设置"""
def __init__(self):
"""初始化游戏的设置"""
self.screen_width = 1200
self.screen_height = 600
self.bg_color = (230, 230, 230)
self.bullet_width = 2
self.bullet_height = 12
self.bullet_color = (60, 60, 60)
self.bullet_all... | the_stack_v2_python_sparse | python实战项目/pygame_applications/shotGame/settings.py | iceAcmen/whole-Python | train | 0 |
1ba9d30db6dbfbd2f197dafd5e5ae136ed1b4a75 | [
"threading.Thread.__init__(self)\nself.name = xname\nself.forkOnLeft = forkOnLeft\nself.forkOnRight = forkOnRight",
"while self.running:\n time.sleep(random.uniform(3, 13))\n print('%s is hungry.' % self.name)\n self.dine()",
"fork1, fork2 = (self.forkOnLeft, self.forkOnRight)\nwhile self.running:\n ... | <|body_start_0|>
threading.Thread.__init__(self)
self.name = xname
self.forkOnLeft = forkOnLeft
self.forkOnRight = forkOnRight
<|end_body_0|>
<|body_start_1|>
while self.running:
time.sleep(random.uniform(3, 13))
print('%s is hungry.' % self.name)
... | Let's get philosophical up in here. | phil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class phil:
"""Let's get philosophical up in here."""
def __init__(self, xname, forkOnLeft, forkOnRight):
"""Initialize variables for each person and forks on either side."""
<|body_0|>
def run(self):
"""The philosopher is sleeping or thinking."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_074022 | 2,591 | no_license | [
{
"docstring": "Initialize variables for each person and forks on either side.",
"name": "__init__",
"signature": "def __init__(self, xname, forkOnLeft, forkOnRight)"
},
{
"docstring": "The philosopher is sleeping or thinking.",
"name": "run",
"signature": "def run(self)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_045353 | Implement the Python class `phil` described below.
Class description:
Let's get philosophical up in here.
Method signatures and docstrings:
- def __init__(self, xname, forkOnLeft, forkOnRight): Initialize variables for each person and forks on either side.
- def run(self): The philosopher is sleeping or thinking.
- d... | Implement the Python class `phil` described below.
Class description:
Let's get philosophical up in here.
Method signatures and docstrings:
- def __init__(self, xname, forkOnLeft, forkOnRight): Initialize variables for each person and forks on either side.
- def run(self): The philosopher is sleeping or thinking.
- d... | 448f9fe33ac71115e082ec9372bb9af68ca7f1c5 | <|skeleton|>
class phil:
"""Let's get philosophical up in here."""
def __init__(self, xname, forkOnLeft, forkOnRight):
"""Initialize variables for each person and forks on either side."""
<|body_0|>
def run(self):
"""The philosopher is sleeping or thinking."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class phil:
"""Let's get philosophical up in here."""
def __init__(self, xname, forkOnLeft, forkOnRight):
"""Initialize variables for each person and forks on either side."""
threading.Thread.__init__(self)
self.name = xname
self.forkOnLeft = forkOnLeft
self.forkOnRight ... | the_stack_v2_python_sparse | puzzles/philosopher.py | HussainAther/computerscience | train | 1 |
d44601b703d8c2dd1d7270e847125c0bb5c79035 | [
"self.path = path\nself.bot = bot\nself.user = user\nself.save_data = save_data\nself.overwrite = overwrite\nself.files_to_save = files_to_save",
"DataImporter.processor.prepare_training_data_for_validation(self.bot, self.path, REQUIREMENTS - self.files_to_save)\ndata_path = os.path.join(self.path, DEFAULT_DATA_P... | <|body_start_0|>
self.path = path
self.bot = bot
self.user = user
self.save_data = save_data
self.overwrite = overwrite
self.files_to_save = files_to_save
<|end_body_0|>
<|body_start_1|>
DataImporter.processor.prepare_training_data_for_validation(self.bot, self.p... | Class to import training data into kairon. A validation is run over training data before initiating the import process. | DataImporter | [
"MIT",
"CC0-1.0",
"CC-BY-3.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Python-2.0",
"ISC",
"Apache-2.0",
"BSD-2-Clause",
"AFL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataImporter:
"""Class to import training data into kairon. A validation is run over training data before initiating the import process."""
def __init__(self, path: Text, bot: Text, user: Text, files_to_save: set, save_data: bool=True, overwrite: bool=True):
"""Initialize data import... | stack_v2_sparse_classes_75kplus_train_074023 | 2,648 | permissive | [
{
"docstring": "Initialize data importer",
"name": "__init__",
"signature": "def __init__(self, path: Text, bot: Text, user: Text, files_to_save: set, save_data: bool=True, overwrite: bool=True)"
},
{
"docstring": "Validates domain and data files to check for possible mistakes and logs them into... | 3 | stack_v2_sparse_classes_30k_train_029552 | Implement the Python class `DataImporter` described below.
Class description:
Class to import training data into kairon. A validation is run over training data before initiating the import process.
Method signatures and docstrings:
- def __init__(self, path: Text, bot: Text, user: Text, files_to_save: set, save_data:... | Implement the Python class `DataImporter` described below.
Class description:
Class to import training data into kairon. A validation is run over training data before initiating the import process.
Method signatures and docstrings:
- def __init__(self, path: Text, bot: Text, user: Text, files_to_save: set, save_data:... | 6a2f0a056dbfe5c041fd9e00a6f5b878e339309e | <|skeleton|>
class DataImporter:
"""Class to import training data into kairon. A validation is run over training data before initiating the import process."""
def __init__(self, path: Text, bot: Text, user: Text, files_to_save: set, save_data: bool=True, overwrite: bool=True):
"""Initialize data import... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataImporter:
"""Class to import training data into kairon. A validation is run over training data before initiating the import process."""
def __init__(self, path: Text, bot: Text, user: Text, files_to_save: set, save_data: bool=True, overwrite: bool=True):
"""Initialize data importer"""
... | the_stack_v2_python_sparse | kairon/importer/data_importer.py | rtilabs/kairon | train | 0 |
9ff447e29b7d616b66e8ceb1c5b981d0c4128e5b | [
"self.start_delay = True\nself.persistent = True\nself.db.time_format = None\nself.db.event_name = 'time'\nself.db.number = None",
"if self.db.time_format:\n seconds = self.ndb.usual\n if seconds is None:\n seconds, usual, details = get_next_wait(self.db.time_format)\n self.ndb.usual = usual\n... | <|body_start_0|>
self.start_delay = True
self.persistent = True
self.db.time_format = None
self.db.event_name = 'time'
self.db.number = None
<|end_body_0|>
<|body_start_1|>
if self.db.time_format:
seconds = self.ndb.usual
if seconds is None:
... | Gametime-sensitive script. | TimeEventScript | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeEventScript:
"""Gametime-sensitive script."""
def at_script_creation(self):
"""The script is created."""
<|body_0|>
def at_repeat(self):
"""Call the event and reset interval. It is necessary to restart the script to reset its interval only twice after a reloa... | stack_v2_sparse_classes_75kplus_train_074024 | 23,990 | permissive | [
{
"docstring": "The script is created.",
"name": "at_script_creation",
"signature": "def at_script_creation(self)"
},
{
"docstring": "Call the event and reset interval. It is necessary to restart the script to reset its interval only twice after a reload. When the script has undergone down time,... | 2 | stack_v2_sparse_classes_30k_train_042291 | Implement the Python class `TimeEventScript` described below.
Class description:
Gametime-sensitive script.
Method signatures and docstrings:
- def at_script_creation(self): The script is created.
- def at_repeat(self): Call the event and reset interval. It is necessary to restart the script to reset its interval onl... | Implement the Python class `TimeEventScript` described below.
Class description:
Gametime-sensitive script.
Method signatures and docstrings:
- def at_script_creation(self): The script is created.
- def at_repeat(self): Call the event and reset interval. It is necessary to restart the script to reset its interval onl... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class TimeEventScript:
"""Gametime-sensitive script."""
def at_script_creation(self):
"""The script is created."""
<|body_0|>
def at_repeat(self):
"""Call the event and reset interval. It is necessary to restart the script to reset its interval only twice after a reloa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimeEventScript:
"""Gametime-sensitive script."""
def at_script_creation(self):
"""The script is created."""
self.start_delay = True
self.persistent = True
self.db.time_format = None
self.db.event_name = 'time'
self.db.number = None
def at_repeat(self)... | the_stack_v2_python_sparse | evennia/contrib/base_systems/ingame_python/scripts.py | evennia/evennia | train | 1,781 |
13b329e064c653a46d19f77e760f6495547e94f8 | [
"if 'UL' in year:\n print('>>> TauESTool: Warning! Using pre-UL (%r) TESs at high pT (for uncertainties only)...' % year)\n year_highpt = '2016Legacy' if '2016' in year else '2017ReReco' if '2017' in year else '2018ReReco'\nelse:\n year_highpt = year\nassert year in campaigns, 'You must choose a year from ... | <|body_start_0|>
if 'UL' in year:
print('>>> TauESTool: Warning! Using pre-UL (%r) TESs at high pT (for uncertainties only)...' % year)
year_highpt = '2016Legacy' if '2016' in year else '2017ReReco' if '2017' in year else '2018ReReco'
else:
year_highpt = year
... | TauESTool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TauESTool:
def __init__(self, year, id='DeepTau2017v2p1VSjet', path=datapath):
"""Choose the IDs and WPs for SFs."""
<|body_0|>
def getTES(self, pt, dm, genmatch=5, unc=None):
"""Get tau ES vs. tau DM."""
<|body_1|>
def getTES_highpt(self, dm, genmatch=5... | stack_v2_sparse_classes_75kplus_train_074025 | 11,627 | no_license | [
{
"docstring": "Choose the IDs and WPs for SFs.",
"name": "__init__",
"signature": "def __init__(self, year, id='DeepTau2017v2p1VSjet', path=datapath)"
},
{
"docstring": "Get tau ES vs. tau DM.",
"name": "getTES",
"signature": "def getTES(self, pt, dm, genmatch=5, unc=None)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_021229 | Implement the Python class `TauESTool` described below.
Class description:
Implement the TauESTool class.
Method signatures and docstrings:
- def __init__(self, year, id='DeepTau2017v2p1VSjet', path=datapath): Choose the IDs and WPs for SFs.
- def getTES(self, pt, dm, genmatch=5, unc=None): Get tau ES vs. tau DM.
- d... | Implement the Python class `TauESTool` described below.
Class description:
Implement the TauESTool class.
Method signatures and docstrings:
- def __init__(self, year, id='DeepTau2017v2p1VSjet', path=datapath): Choose the IDs and WPs for SFs.
- def getTES(self, pt, dm, genmatch=5, unc=None): Get tau ES vs. tau DM.
- d... | 7a4e7e58421b0be8bc25fc99cfb1dd007b52f3c7 | <|skeleton|>
class TauESTool:
def __init__(self, year, id='DeepTau2017v2p1VSjet', path=datapath):
"""Choose the IDs and WPs for SFs."""
<|body_0|>
def getTES(self, pt, dm, genmatch=5, unc=None):
"""Get tau ES vs. tau DM."""
<|body_1|>
def getTES_highpt(self, dm, genmatch=5... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TauESTool:
def __init__(self, year, id='DeepTau2017v2p1VSjet', path=datapath):
"""Choose the IDs and WPs for SFs."""
if 'UL' in year:
print('>>> TauESTool: Warning! Using pre-UL (%r) TESs at high pT (for uncertainties only)...' % year)
year_highpt = '2016Legacy' if '201... | the_stack_v2_python_sparse | python/postprocessing/helpers/TauIDSFTool.py | cms-nanoAOD/nanoAOD-tools | train | 50 | |
b30275f3102557688c5514da9702d07cb4902774 | [
"self.width = int(width)\nself.height = int(height)\nself.path_background = path_background\nself.path_uiuc = path_uiuc\nself.image_counter = 0",
"if not os.path.exists(path):\n os.makedirs(path)\nimages_background = [f for f in os.listdir(self.path_background) if f != '.DS_Store']\nimages_uiuc = [f for f in o... | <|body_start_0|>
self.width = int(width)
self.height = int(height)
self.path_background = path_background
self.path_uiuc = path_uiuc
self.image_counter = 0
<|end_body_0|>
<|body_start_1|>
if not os.path.exists(path):
os.makedirs(path)
images_backgroun... | UIUCGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UIUCGenerator:
def __init__(self, width, height, path_background, path_uiuc):
"""Input: width: width of each generated image height: height of each generated image path_background: path to the folder with background images path_uiuc: path to the folder with positive UIUC images"""
... | stack_v2_sparse_classes_75kplus_train_074026 | 6,758 | permissive | [
{
"docstring": "Input: width: width of each generated image height: height of each generated image path_background: path to the folder with background images path_uiuc: path to the folder with positive UIUC images",
"name": "__init__",
"signature": "def __init__(self, width, height, path_background, pat... | 3 | stack_v2_sparse_classes_30k_train_021581 | Implement the Python class `UIUCGenerator` described below.
Class description:
Implement the UIUCGenerator class.
Method signatures and docstrings:
- def __init__(self, width, height, path_background, path_uiuc): Input: width: width of each generated image height: height of each generated image path_background: path ... | Implement the Python class `UIUCGenerator` described below.
Class description:
Implement the UIUCGenerator class.
Method signatures and docstrings:
- def __init__(self, width, height, path_background, path_uiuc): Input: width: width of each generated image height: height of each generated image path_background: path ... | 6eca474ed3cae673afde010caef338cf7349f839 | <|skeleton|>
class UIUCGenerator:
def __init__(self, width, height, path_background, path_uiuc):
"""Input: width: width of each generated image height: height of each generated image path_background: path to the folder with background images path_uiuc: path to the folder with positive UIUC images"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UIUCGenerator:
def __init__(self, width, height, path_background, path_uiuc):
"""Input: width: width of each generated image height: height of each generated image path_background: path to the folder with background images path_uiuc: path to the folder with positive UIUC images"""
self.width =... | the_stack_v2_python_sparse | scripts/data/generators/uiuc_generator.py | Wavelet303/master_thesis_code | train | 0 | |
f6f240ec14e1a51b0869234c66f4c3ad43acdb4f | [
"s = 'Python is very interesting'\nl = s.split()\nstem_result = ['Python', 'is', 'veri', 'interest']\nstemmer = PorterStemmer()\nf_result = text_stem(l, stemmer)\nself.assertEqual(stem_result, f_result, msg='\\nThe stem result should be \\n{},\\n rather than \\n{}'.format(stem_result, f_res... | <|body_start_0|>
s = 'Python is very interesting'
l = s.split()
stem_result = ['Python', 'is', 'veri', 'interest']
stemmer = PorterStemmer()
f_result = text_stem(l, stemmer)
self.assertEqual(stem_result, f_result, msg='\nThe stem result should be ... | FeatureExtractionTestCase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureExtractionTestCase:
def test_test_stem(self):
"""Unittest for function test_stem."""
<|body_0|>
def test_tokenize(self):
"""Unittest for function tokenize."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s = 'Python is very interesting'
... | stack_v2_sparse_classes_75kplus_train_074027 | 1,234 | permissive | [
{
"docstring": "Unittest for function test_stem.",
"name": "test_test_stem",
"signature": "def test_test_stem(self)"
},
{
"docstring": "Unittest for function tokenize.",
"name": "test_tokenize",
"signature": "def test_tokenize(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039862 | Implement the Python class `FeatureExtractionTestCase` described below.
Class description:
Implement the FeatureExtractionTestCase class.
Method signatures and docstrings:
- def test_test_stem(self): Unittest for function test_stem.
- def test_tokenize(self): Unittest for function tokenize. | Implement the Python class `FeatureExtractionTestCase` described below.
Class description:
Implement the FeatureExtractionTestCase class.
Method signatures and docstrings:
- def test_test_stem(self): Unittest for function test_stem.
- def test_tokenize(self): Unittest for function tokenize.
<|skeleton|>
class Featur... | 52148c63dd1d1ad97ea7595503e3172ca9268a75 | <|skeleton|>
class FeatureExtractionTestCase:
def test_test_stem(self):
"""Unittest for function test_stem."""
<|body_0|>
def test_tokenize(self):
"""Unittest for function tokenize."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FeatureExtractionTestCase:
def test_test_stem(self):
"""Unittest for function test_stem."""
s = 'Python is very interesting'
l = s.split()
stem_result = ['Python', 'is', 'veri', 'interest']
stemmer = PorterStemmer()
f_result = text_stem(l, stemmer)
self.... | the_stack_v2_python_sparse | experiment/tools/test_feature_extraction.py | Shitaibin/tweets-spam-clustering | train | 0 | |
dbd068b9fc66f0fc7e11ffaee4621cd1fee585b5 | [
"self.model = trainer.model\nself.towers = trainer.config.predict_tower\n\ndef fn(_):\n self.model.build_graph(self.model.get_reused_placehdrs())\nself._tower_builder = PredictorTowerBuilder(fn)\nassert isinstance(self.towers, list), self.towers",
"tower = self.towers[tower]\nself._tower_builder.build(tower)\n... | <|body_start_0|>
self.model = trainer.model
self.towers = trainer.config.predict_tower
def fn(_):
self.model.build_graph(self.model.get_reused_placehdrs())
self._tower_builder = PredictorTowerBuilder(fn)
assert isinstance(self.towers, list), self.towers
<|end_body_0|... | Make predictors from a trainer. | PredictorFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PredictorFactory:
"""Make predictors from a trainer."""
def __init__(self, trainer):
"""Args: towers (list[int]): list of gpu id"""
<|body_0|>
def get_predictor(self, input_names, output_names, tower):
"""Args: tower (int): need the kth tower (not the gpu id, but... | stack_v2_sparse_classes_75kplus_train_074028 | 1,512 | permissive | [
{
"docstring": "Args: towers (list[int]): list of gpu id",
"name": "__init__",
"signature": "def __init__(self, trainer)"
},
{
"docstring": "Args: tower (int): need the kth tower (not the gpu id, but the id in TrainConfig.predict_tower) Returns: an online predictor (which has to be used under a ... | 2 | stack_v2_sparse_classes_30k_train_020056 | Implement the Python class `PredictorFactory` described below.
Class description:
Make predictors from a trainer.
Method signatures and docstrings:
- def __init__(self, trainer): Args: towers (list[int]): list of gpu id
- def get_predictor(self, input_names, output_names, tower): Args: tower (int): need the kth tower... | Implement the Python class `PredictorFactory` described below.
Class description:
Make predictors from a trainer.
Method signatures and docstrings:
- def __init__(self, trainer): Args: towers (list[int]): list of gpu id
- def get_predictor(self, input_names, output_names, tower): Args: tower (int): need the kth tower... | fd85d78fc83dc6d0fc9bd44114c7d7fee3689065 | <|skeleton|>
class PredictorFactory:
"""Make predictors from a trainer."""
def __init__(self, trainer):
"""Args: towers (list[int]): list of gpu id"""
<|body_0|>
def get_predictor(self, input_names, output_names, tower):
"""Args: tower (int): need the kth tower (not the gpu id, but... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PredictorFactory:
"""Make predictors from a trainer."""
def __init__(self, trainer):
"""Args: towers (list[int]): list of gpu id"""
self.model = trainer.model
self.towers = trainer.config.predict_tower
def fn(_):
self.model.build_graph(self.model.get_reused_pl... | the_stack_v2_python_sparse | tensorpack/train/predict.py | KuribohG/tensorpack | train | 3 |
9d59bba0dccd7be65a04b6256d17eb3a8cdef3fe | [
"if not start_bracket or not end_bracket:\n raise ValueError('Attempted to construct Bracketed segment without specifying brackets.')\nself.start_bracket = start_bracket\nself.end_bracket = end_bracket\nsuper().__init__(*args, **kwargs)",
"start_brackets = [start_bracket for _, start_bracket, _, persistent in ... | <|body_start_0|>
if not start_bracket or not end_bracket:
raise ValueError('Attempted to construct Bracketed segment without specifying brackets.')
self.start_bracket = start_bracket
self.end_bracket = end_bracket
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start... | A segment containing a bracketed expression. | BracketedSegment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BracketedSegment:
"""A segment containing a bracketed expression."""
def __init__(self, *args, start_bracket: Tuple[BaseSegment]=None, end_bracket: Tuple[BaseSegment]=None, **kwargs):
"""Stash the bracket segments for later."""
<|body_0|>
def simple(cls, parse_context: P... | stack_v2_sparse_classes_75kplus_train_074029 | 43,344 | permissive | [
{
"docstring": "Stash the bracket segments for later.",
"name": "__init__",
"signature": "def __init__(self, *args, start_bracket: Tuple[BaseSegment]=None, end_bracket: Tuple[BaseSegment]=None, **kwargs)"
},
{
"docstring": "Simple methods for bracketed and the persitent brackets.",
"name": "... | 3 | null | Implement the Python class `BracketedSegment` described below.
Class description:
A segment containing a bracketed expression.
Method signatures and docstrings:
- def __init__(self, *args, start_bracket: Tuple[BaseSegment]=None, end_bracket: Tuple[BaseSegment]=None, **kwargs): Stash the bracket segments for later.
- ... | Implement the Python class `BracketedSegment` described below.
Class description:
A segment containing a bracketed expression.
Method signatures and docstrings:
- def __init__(self, *args, start_bracket: Tuple[BaseSegment]=None, end_bracket: Tuple[BaseSegment]=None, **kwargs): Stash the bracket segments for later.
- ... | 98623974ecc816ac7e23843472d6bbd2c3936800 | <|skeleton|>
class BracketedSegment:
"""A segment containing a bracketed expression."""
def __init__(self, *args, start_bracket: Tuple[BaseSegment]=None, end_bracket: Tuple[BaseSegment]=None, **kwargs):
"""Stash the bracket segments for later."""
<|body_0|>
def simple(cls, parse_context: P... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BracketedSegment:
"""A segment containing a bracketed expression."""
def __init__(self, *args, start_bracket: Tuple[BaseSegment]=None, end_bracket: Tuple[BaseSegment]=None, **kwargs):
"""Stash the bracket segments for later."""
if not start_bracket or not end_bracket:
raise Va... | the_stack_v2_python_sparse | src/sqlfluff/core/parser/segments/base.py | andres-lowrie/sqlfluff | train | 1 |
8047289b9f6d2fc1a28e952a519c7ea304faae95 | [
"procrowre = re.compile('\\\\s*([-/_a-zA-Z0-9%]+)\\\\s*=\\\\s*\"([^\"]+)\"')\nlstss = []\nfor line in rules_file_contents.split('\\n'):\n s = line.strip()\n m = procrowre.match(s)\n if not m:\n continue\n lstss.append((m.group(1), m.group(2)))\nreturn lstss",
"rulerowre = re.compile('^\\\\s*([0... | <|body_start_0|>
procrowre = re.compile('\\s*([-/_a-zA-Z0-9%]+)\\s*=\\s*"([^"]+)"')
lstss = []
for line in rules_file_contents.split('\n'):
s = line.strip()
m = procrowre.match(s)
if not m:
continue
lstss.append((m.group(1), m.group... | ExtRulesParser | [
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtRulesParser:
def parseLstsFiles(self, rules_file_contents):
"""Parse the lsts files in the given string. The string is assumed to be in TVT extended rules format, that is <lsts#1> = "<lstsfilename1>" <lsts#2> = "<lstsfilename2>" ... Returns list of numbers and lsts filenames: [ (lsts#... | stack_v2_sparse_classes_75kplus_train_074030 | 3,149 | permissive | [
{
"docstring": "Parse the lsts files in the given string. The string is assumed to be in TVT extended rules format, that is <lsts#1> = \"<lstsfilename1>\" <lsts#2> = \"<lstsfilename2>\" ... Returns list of numbers and lsts filenames: [ (lsts#1, \"lstsfilename1\"), (lsts#2, \"lstsfilename2\"), ... ]",
"name"... | 2 | stack_v2_sparse_classes_30k_train_016274 | Implement the Python class `ExtRulesParser` described below.
Class description:
Implement the ExtRulesParser class.
Method signatures and docstrings:
- def parseLstsFiles(self, rules_file_contents): Parse the lsts files in the given string. The string is assumed to be in TVT extended rules format, that is <lsts#1> = ... | Implement the Python class `ExtRulesParser` described below.
Class description:
Implement the ExtRulesParser class.
Method signatures and docstrings:
- def parseLstsFiles(self, rules_file_contents): Parse the lsts files in the given string. The string is assumed to be in TVT extended rules format, that is <lsts#1> = ... | 9c3f119c8bf5cc565e6a3e8e9e6205037e326d89 | <|skeleton|>
class ExtRulesParser:
def parseLstsFiles(self, rules_file_contents):
"""Parse the lsts files in the given string. The string is assumed to be in TVT extended rules format, that is <lsts#1> = "<lstsfilename1>" <lsts#2> = "<lstsfilename2>" ... Returns list of numbers and lsts filenames: [ (lsts#... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExtRulesParser:
def parseLstsFiles(self, rules_file_contents):
"""Parse the lsts files in the given string. The string is assumed to be in TVT extended rules format, that is <lsts#1> = "<lstsfilename1>" <lsts#2> = "<lstsfilename2>" ... Returns list of numbers and lsts filenames: [ (lsts#1, "lstsfilena... | the_stack_v2_python_sparse | TemaLib/tema/rules/rules_parser.py | tema-tut/tema-tg | train | 1 | |
e8d6fb4131f44494825d4448c8fde31b67fb09ef | [
"try:\n extensions_config = getattr(current_app.extensions['invenio-app-ils'], 'document_metadata_extensions')\nexcept AttributeError:\n return {}\nExtensionSchema = extensions_config.to_schema()\nreturn ExtensionSchema().dump(obj)",
"try:\n extensions_config = getattr(current_app.extensions['invenio-app... | <|body_start_0|>
try:
extensions_config = getattr(current_app.extensions['invenio-app-ils'], 'document_metadata_extensions')
except AttributeError:
return {}
ExtensionSchema = extensions_config.to_schema()
return ExtensionSchema().dump(obj)
<|end_body_0|>
<|body_... | Document schema. | DocumentSchemaV1 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentSchemaV1:
"""Document schema."""
def dump_extensions(self, obj):
"""Dumps the extensions value. :params obj: content of the object's 'extensions' field"""
<|body_0|>
def load_extensions(self, value):
"""Loads the 'extensions' field. :params value: content... | stack_v2_sparse_classes_75kplus_train_074031 | 7,755 | permissive | [
{
"docstring": "Dumps the extensions value. :params obj: content of the object's 'extensions' field",
"name": "dump_extensions",
"signature": "def dump_extensions(self, obj)"
},
{
"docstring": "Loads the 'extensions' field. :params value: content of the input's 'extensions' field",
"name": "... | 3 | stack_v2_sparse_classes_30k_train_007263 | Implement the Python class `DocumentSchemaV1` described below.
Class description:
Document schema.
Method signatures and docstrings:
- def dump_extensions(self, obj): Dumps the extensions value. :params obj: content of the object's 'extensions' field
- def load_extensions(self, value): Loads the 'extensions' field. :... | Implement the Python class `DocumentSchemaV1` described below.
Class description:
Document schema.
Method signatures and docstrings:
- def dump_extensions(self, obj): Dumps the extensions value. :params obj: content of the object's 'extensions' field
- def load_extensions(self, value): Loads the 'extensions' field. :... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class DocumentSchemaV1:
"""Document schema."""
def dump_extensions(self, obj):
"""Dumps the extensions value. :params obj: content of the object's 'extensions' field"""
<|body_0|>
def load_extensions(self, value):
"""Loads the 'extensions' field. :params value: content... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DocumentSchemaV1:
"""Document schema."""
def dump_extensions(self, obj):
"""Dumps the extensions value. :params obj: content of the object's 'extensions' field"""
try:
extensions_config = getattr(current_app.extensions['invenio-app-ils'], 'document_metadata_extensions')
... | the_stack_v2_python_sparse | invenio_app_ils/documents/loaders/jsonschemas/document.py | inveniosoftware/invenio-app-ils | train | 64 |
5ce71d431b386d9a7d18ee0bed8b500c6326306e | [
"def helper(*args, **kwargs):\n helper.calls += 1\n return func(*args, **kwargs)\nhelper.calls = 0\nhelper.__name__ = func.__name__\nreturn helper",
"for attr in attributedict:\n if not callable(attr) and (not attr.startswith('__')):\n attributedict[attr] = cls.call_counter(attributedict[attr])\nr... | <|body_start_0|>
def helper(*args, **kwargs):
helper.calls += 1
return func(*args, **kwargs)
helper.calls = 0
helper.__name__ = func.__name__
return helper
<|end_body_0|>
<|body_start_1|>
for attr in attributedict:
if not callable(attr) and (n... | A Metaclass which decorates all the methods of the subclass using call_counter as the decorator | FuncCallCounter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FuncCallCounter:
"""A Metaclass which decorates all the methods of the subclass using call_counter as the decorator"""
def call_counter(func):
"""Decorator for counting the number of function or method calls to the function or method func"""
<|body_0|>
def __new__(cls, c... | stack_v2_sparse_classes_75kplus_train_074032 | 4,655 | no_license | [
{
"docstring": "Decorator for counting the number of function or method calls to the function or method func",
"name": "call_counter",
"signature": "def call_counter(func)"
},
{
"docstring": "Every method gets decorated with the decorator call_counter, which will do the actual call counting",
... | 2 | null | Implement the Python class `FuncCallCounter` described below.
Class description:
A Metaclass which decorates all the methods of the subclass using call_counter as the decorator
Method signatures and docstrings:
- def call_counter(func): Decorator for counting the number of function or method calls to the function or ... | Implement the Python class `FuncCallCounter` described below.
Class description:
A Metaclass which decorates all the methods of the subclass using call_counter as the decorator
Method signatures and docstrings:
- def call_counter(func): Decorator for counting the number of function or method calls to the function or ... | 25ef6e920c7173cce2c726b36fec53c4d633147b | <|skeleton|>
class FuncCallCounter:
"""A Metaclass which decorates all the methods of the subclass using call_counter as the decorator"""
def call_counter(func):
"""Decorator for counting the number of function or method calls to the function or method func"""
<|body_0|>
def __new__(cls, c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FuncCallCounter:
"""A Metaclass which decorates all the methods of the subclass using call_counter as the decorator"""
def call_counter(func):
"""Decorator for counting the number of function or method calls to the function or method func"""
def helper(*args, **kwargs):
helper... | the_stack_v2_python_sparse | Tutorial/OOP_metaclass3.py | aarontinn13/Winter-Quarter-History | train | 0 |
aa6e36ac8681973a3dd671df0794440d6671ea5c | [
"token = access_control.ACLToken(username='test', reason='fixture')\nwith aff4.FACTORY.Create('aff4:/stats/ClientFleetStats', 'ClientFleetStats', token=token) as fd:\n now = 1321057655\n for i in range(10, 15):\n histogram = fd.Schema.OS_HISTOGRAM(age=int((now + i * 60 * 60 * 24) * 1000000.0))\n ... | <|body_start_0|>
token = access_control.ACLToken(username='test', reason='fixture')
with aff4.FACTORY.Create('aff4:/stats/ClientFleetStats', 'ClientFleetStats', token=token) as fd:
now = 1321057655
for i in range(10, 15):
histogram = fd.Schema.OS_HISTOGRAM(age=int... | Test the statistics interface. | TestStats | [
"Apache-2.0",
"DOC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStats:
"""Test the statistics interface."""
def PopulateData():
"""Populates data into the stats object."""
<|body_0|>
def testStats(self):
"""Test the statistics interface. Unfortunately this test is pretty lame because we can not look into the canvas object... | stack_v2_sparse_classes_75kplus_train_074033 | 2,708 | permissive | [
{
"docstring": "Populates data into the stats object.",
"name": "PopulateData",
"signature": "def PopulateData()"
},
{
"docstring": "Test the statistics interface. Unfortunately this test is pretty lame because we can not look into the canvas object with selenium.",
"name": "testStats",
... | 2 | stack_v2_sparse_classes_30k_val_001940 | Implement the Python class `TestStats` described below.
Class description:
Test the statistics interface.
Method signatures and docstrings:
- def PopulateData(): Populates data into the stats object.
- def testStats(self): Test the statistics interface. Unfortunately this test is pretty lame because we can not look i... | Implement the Python class `TestStats` described below.
Class description:
Test the statistics interface.
Method signatures and docstrings:
- def PopulateData(): Populates data into the stats object.
- def testStats(self): Test the statistics interface. Unfortunately this test is pretty lame because we can not look i... | ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e | <|skeleton|>
class TestStats:
"""Test the statistics interface."""
def PopulateData():
"""Populates data into the stats object."""
<|body_0|>
def testStats(self):
"""Test the statistics interface. Unfortunately this test is pretty lame because we can not look into the canvas object... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestStats:
"""Test the statistics interface."""
def PopulateData():
"""Populates data into the stats object."""
token = access_control.ACLToken(username='test', reason='fixture')
with aff4.FACTORY.Create('aff4:/stats/ClientFleetStats', 'ClientFleetStats', token=token) as fd:
... | the_stack_v2_python_sparse | gui/plugins/statistics_test.py | defaultnamehere/grr | train | 3 |
a92e7599e90e27359dafd627bdb93df1bc198993 | [
"tuple_type = collections.namedtuple('fake_type', ['arg1', 'arg3'])\n\ndef args_loss(arg1, arg2, arg3=3, arg4=4):\n return arg1 + arg2 + arg3 + arg4\ngan_model_loss = args_to_gan_model(args_loss)\nself.assertEqual(1 + 2 + 5 + 6, gan_model_loss(tuple_type(1, 2), arg2=5, arg4=6))\nself.assertEqual(1 + 5 + 3 + 7, g... | <|body_start_0|>
tuple_type = collections.namedtuple('fake_type', ['arg1', 'arg3'])
def args_loss(arg1, arg2, arg3=3, arg4=4):
return arg1 + arg2 + arg3 + arg4
gan_model_loss = args_to_gan_model(args_loss)
self.assertEqual(1 + 2 + 5 + 6, gan_model_loss(tuple_type(1, 2), arg2... | ArgsToGanModelTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgsToGanModelTest:
def testargs_to_gan_model(self):
"""Test `args_to_gan_model`."""
<|body_0|>
def testargs_to_gan_model_name(self):
"""Test that `args_to_gan_model` produces correctly named functions."""
<|body_1|>
def test_tuple_respects_optional_args... | stack_v2_sparse_classes_75kplus_train_074034 | 11,985 | permissive | [
{
"docstring": "Test `args_to_gan_model`.",
"name": "testargs_to_gan_model",
"signature": "def testargs_to_gan_model(self)"
},
{
"docstring": "Test that `args_to_gan_model` produces correctly named functions.",
"name": "testargs_to_gan_model_name",
"signature": "def testargs_to_gan_model... | 4 | stack_v2_sparse_classes_30k_train_016912 | Implement the Python class `ArgsToGanModelTest` described below.
Class description:
Implement the ArgsToGanModelTest class.
Method signatures and docstrings:
- def testargs_to_gan_model(self): Test `args_to_gan_model`.
- def testargs_to_gan_model_name(self): Test that `args_to_gan_model` produces correctly named func... | Implement the Python class `ArgsToGanModelTest` described below.
Class description:
Implement the ArgsToGanModelTest class.
Method signatures and docstrings:
- def testargs_to_gan_model(self): Test `args_to_gan_model`.
- def testargs_to_gan_model_name(self): Test that `args_to_gan_model` produces correctly named func... | 9fcb4acee7e82918152ad52babf6c6097cf0d1e6 | <|skeleton|>
class ArgsToGanModelTest:
def testargs_to_gan_model(self):
"""Test `args_to_gan_model`."""
<|body_0|>
def testargs_to_gan_model_name(self):
"""Test that `args_to_gan_model` produces correctly named functions."""
<|body_1|>
def test_tuple_respects_optional_args... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArgsToGanModelTest:
def testargs_to_gan_model(self):
"""Test `args_to_gan_model`."""
tuple_type = collections.namedtuple('fake_type', ['arg1', 'arg3'])
def args_loss(arg1, arg2, arg3=3, arg4=4):
return arg1 + arg2 + arg3 + arg4
gan_model_loss = args_to_gan_model(ar... | the_stack_v2_python_sparse | tensorflow_gan/python/losses/tuple_losses_test.py | tensorflow/gan | train | 942 | |
d547a1ccd2e6444c34f6f0267c8311246272559c | [
"if self.year >= 2016:\n return [Holiday(self.locale, '', easter(self.year, self.easter_type).shift(days=-2), 'Velký pátek', 'NRV')]\nreturn []",
"if self.year < 2019:\n name = 'Den boje za svobodu a demokracii'\nelse:\n name = 'Den boje za svobodu a demokracii a Mezinárodní den studentstva'\nreturn [Hol... | <|body_start_0|>
if self.year >= 2016:
return [Holiday(self.locale, '', easter(self.year, self.easter_type).shift(days=-2), 'Velký pátek', 'NRV')]
return []
<|end_body_0|>
<|body_start_1|>
if self.year < 2019:
name = 'Den boje za svobodu a demokracii'
else:
... | 01-01: [NF] Nový rok 01-01: [NF] Den obnovy samostatného českého státu 05-01: [NF] Svátek práce 05-08: [NF] Den vítězství 07-05: [NRF] Den slovanských věrozvěstů Cyrila a Metoděje 07-06: [NRF] Den upálení mistra Jana Husa 09-28: [NRF] Den české státnosti 10-28: [NF] Den vzniku samostatného československého státu 12-24:... | cs_CZ | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cs_CZ:
"""01-01: [NF] Nový rok 01-01: [NF] Den obnovy samostatného českého státu 05-01: [NF] Svátek práce 05-08: [NF] Den vítězství 07-05: [NRF] Den slovanských věrozvěstů Cyrila a Metoděje 07-06: [NRF] Den upálení mistra Jana Husa 09-28: [NRF] Den české státnosti 10-28: [NF] Den vzniku samostatn... | stack_v2_sparse_classes_75kplus_train_074035 | 2,091 | permissive | [
{
"docstring": "2 days before Easter: [NRV] Velký pátek since 2016",
"name": "holiday_velky_patek",
"signature": "def holiday_velky_patek(self)"
},
{
"docstring": "11-17: [NF] before 2019-04-01: Den boje za svobodu a demokracii before 2019-04-01: Den boje za svobodu a demokracii a Mezinárodní de... | 2 | stack_v2_sparse_classes_30k_train_023850 | Implement the Python class `cs_CZ` described below.
Class description:
01-01: [NF] Nový rok 01-01: [NF] Den obnovy samostatného českého státu 05-01: [NF] Svátek práce 05-08: [NF] Den vítězství 07-05: [NRF] Den slovanských věrozvěstů Cyrila a Metoděje 07-06: [NRF] Den upálení mistra Jana Husa 09-28: [NRF] Den české stá... | Implement the Python class `cs_CZ` described below.
Class description:
01-01: [NF] Nový rok 01-01: [NF] Den obnovy samostatného českého státu 05-01: [NF] Svátek práce 05-08: [NF] Den vítězství 07-05: [NRF] Den slovanských věrozvěstů Cyrila a Metoděje 07-06: [NRF] Den upálení mistra Jana Husa 09-28: [NRF] Den české stá... | fdd02cd2cc1769236a10dfffab647375bc27f129 | <|skeleton|>
class cs_CZ:
"""01-01: [NF] Nový rok 01-01: [NF] Den obnovy samostatného českého státu 05-01: [NF] Svátek práce 05-08: [NF] Den vítězství 07-05: [NRF] Den slovanských věrozvěstů Cyrila a Metoděje 07-06: [NRF] Den upálení mistra Jana Husa 09-28: [NRF] Den české státnosti 10-28: [NF] Den vzniku samostatn... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class cs_CZ:
"""01-01: [NF] Nový rok 01-01: [NF] Den obnovy samostatného českého státu 05-01: [NF] Svátek práce 05-08: [NF] Den vítězství 07-05: [NRF] Den slovanských věrozvěstů Cyrila a Metoděje 07-06: [NRF] Den upálení mistra Jana Husa 09-28: [NRF] Den české státnosti 10-28: [NF] Den vzniku samostatného českoslov... | the_stack_v2_python_sparse | src/holidata/holidays/cs-CZ.py | GothenburgBitFactory/holidata | train | 45 |
9c698c722da2ed092ff5315f7dbe0df40d384fbf | [
"self.parser = argparse.ArgumentParser(description='This script automizes setup for various blockchain networks on aws and calculates aws costs after finshing', usage='run.py start --config /home/config.json or run.py terminate --config /home/config.json')\nsubparsers_start_terminate = self.parser.add_subparsers(he... | <|body_start_0|>
self.parser = argparse.ArgumentParser(description='This script automizes setup for various blockchain networks on aws and calculates aws costs after finshing', usage='run.py start --config /home/config.json or run.py terminate --config /home/config.json')
subparsers_start_terminate = se... | ArgParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgParser:
def __init__(self):
"""Initialize an ArgParser object. The general structure of calls from the command line is:"""
<|body_0|>
def storage_type(x):
"""Checks if the chosen storage is in a given range (Needs to be >1 else the mounting process of the UserData... | stack_v2_sparse_classes_75kplus_train_074036 | 4,845 | permissive | [
{
"docstring": "Initialize an ArgParser object. The general structure of calls from the command line is:",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Checks if the chosen storage is in a given range (Needs to be >1 else the mounting process of the UserData script fa... | 3 | null | Implement the Python class `ArgParser` described below.
Class description:
Implement the ArgParser class.
Method signatures and docstrings:
- def __init__(self): Initialize an ArgParser object. The general structure of calls from the command line is:
- def storage_type(x): Checks if the chosen storage is in a given r... | Implement the Python class `ArgParser` described below.
Class description:
Implement the ArgParser class.
Method signatures and docstrings:
- def __init__(self): Initialize an ArgParser object. The general structure of calls from the command line is:
- def storage_type(x): Checks if the chosen storage is in a given r... | 57bd131518f18ad4fc27a1957881d27a29710b16 | <|skeleton|>
class ArgParser:
def __init__(self):
"""Initialize an ArgParser object. The general structure of calls from the command line is:"""
<|body_0|>
def storage_type(x):
"""Checks if the chosen storage is in a given range (Needs to be >1 else the mounting process of the UserData... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArgParser:
def __init__(self):
"""Initialize an ArgParser object. The general structure of calls from the command line is:"""
self.parser = argparse.ArgumentParser(description='This script automizes setup for various blockchain networks on aws and calculates aws costs after finshing', usage='r... | the_stack_v2_python_sparse | BlockchainFormation/run.py | rodrigofolha/BlockchainFormation | train | 0 | |
d3a431c151d605c82207c6d0c44b1be4ae25cd0d | [
"super(CreateAdcPoolObjects, self).__init__(*args, **kwargs)\nself.pool_count = pool_count\nself.pool_member_count = pool_member_count\nself.bigip = bigip\nself.object_counter = 0\nself.context = ContextHelper(__name__)\nself.cfgifc = self.context.get_config()\nself.node_names = node_names\nself.node_addresses = no... | <|body_start_0|>
super(CreateAdcPoolObjects, self).__init__(*args, **kwargs)
self.pool_count = pool_count
self.pool_member_count = pool_member_count
self.bigip = bigip
self.object_counter = 0
self.context = ContextHelper(__name__)
self.cfgifc = self.context.get_co... | Create the specified number of ADC Pool objects on the BIG-IQ for the specified BIG-IP. Works for BIG-IQ 4.6.0 and later. You must deploy the ADC objects from the BIG-IQ to the BIG-IP(s) with a separate call. | CreateAdcPoolObjects | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateAdcPoolObjects:
"""Create the specified number of ADC Pool objects on the BIG-IQ for the specified BIG-IP. Works for BIG-IQ 4.6.0 and later. You must deploy the ADC objects from the BIG-IQ to the BIG-IP(s) with a separate call."""
def __init__(self, pool_count, pool_member_count, bigip... | stack_v2_sparse_classes_75kplus_train_074037 | 15,401 | permissive | [
{
"docstring": "Object initialization. @param pool_count: The number of ADC pools to create. @param pool_member_count: The number of members per ADC pool to create. @param bigip: BIG-IP device, as returned by MachineIdResolver. @param node_names: List of Node Names to use to link up with the pool members. @para... | 2 | stack_v2_sparse_classes_30k_train_016821 | Implement the Python class `CreateAdcPoolObjects` described below.
Class description:
Create the specified number of ADC Pool objects on the BIG-IQ for the specified BIG-IP. Works for BIG-IQ 4.6.0 and later. You must deploy the ADC objects from the BIG-IQ to the BIG-IP(s) with a separate call.
Method signatures and d... | Implement the Python class `CreateAdcPoolObjects` described below.
Class description:
Create the specified number of ADC Pool objects on the BIG-IQ for the specified BIG-IP. Works for BIG-IQ 4.6.0 and later. You must deploy the ADC objects from the BIG-IQ to the BIG-IP(s) with a separate call.
Method signatures and d... | 40264ac83b3f1d2a30ebc1107927044f42c86f8a | <|skeleton|>
class CreateAdcPoolObjects:
"""Create the specified number of ADC Pool objects on the BIG-IQ for the specified BIG-IP. Works for BIG-IQ 4.6.0 and later. You must deploy the ADC objects from the BIG-IQ to the BIG-IP(s) with a separate call."""
def __init__(self, pool_count, pool_member_count, bigip... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateAdcPoolObjects:
"""Create the specified number of ADC Pool objects on the BIG-IQ for the specified BIG-IP. Works for BIG-IQ 4.6.0 and later. You must deploy the ADC objects from the BIG-IQ to the BIG-IP(s) with a separate call."""
def __init__(self, pool_count, pool_member_count, bigip, node_names,... | the_stack_v2_python_sparse | f5test/commands/rest/adc.py | jonozzz/nosest | train | 1 |
e11dfdc5bfe800360131aaabfd2d705fff663d4c | [
"yerr = np.clip(yerr, a_min=0.001, a_max=1)\nyy = np.vstack([y + np.random.normal(loc=0, scale=yerr) for i in range(N)]).T\nself._splines = [spline(x, yy[:, i], *args, **kwargs) for i in range(N)]",
"x = np.atleast_1d(x)\ns = np.vstack([curve(x, *args, **kwargs) for curve in self._splines])\nt = np.arange(10, 40,... | <|body_start_0|>
yerr = np.clip(yerr, a_min=0.001, a_max=1)
yy = np.vstack([y + np.random.normal(loc=0, scale=yerr) for i in range(N)]).T
self._splines = [spline(x, yy[:, i], *args, **kwargs) for i in range(N)]
<|end_body_0|>
<|body_start_1|>
x = np.atleast_1d(x)
s = np.vstack([... | Does a spline fit, but returns both the spline value and associated uncertainty. | ErrorPropagationSpline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ErrorPropagationSpline:
"""Does a spline fit, but returns both the spline value and associated uncertainty."""
def __init__(self, x, y, yerr, N=1000, *args, **kwargs):
"""See docstring for InterpolatedUnivariateSpline"""
<|body_0|>
def __call__(self, x, *args, **kwargs):... | stack_v2_sparse_classes_75kplus_train_074038 | 2,179 | no_license | [
{
"docstring": "See docstring for InterpolatedUnivariateSpline",
"name": "__init__",
"signature": "def __init__(self, x, y, yerr, N=1000, *args, **kwargs)"
},
{
"docstring": "Get the spline value and uncertainty at point(s) x. args and kwargs are passed to spline.__call__ :param x: :return: a tu... | 2 | stack_v2_sparse_classes_30k_train_045156 | Implement the Python class `ErrorPropagationSpline` described below.
Class description:
Does a spline fit, but returns both the spline value and associated uncertainty.
Method signatures and docstrings:
- def __init__(self, x, y, yerr, N=1000, *args, **kwargs): See docstring for InterpolatedUnivariateSpline
- def __c... | Implement the Python class `ErrorPropagationSpline` described below.
Class description:
Does a spline fit, but returns both the spline value and associated uncertainty.
Method signatures and docstrings:
- def __init__(self, x, y, yerr, N=1000, *args, **kwargs): See docstring for InterpolatedUnivariateSpline
- def __c... | be67c4b1a624111eb915aba4e6650489972000fe | <|skeleton|>
class ErrorPropagationSpline:
"""Does a spline fit, but returns both the spline value and associated uncertainty."""
def __init__(self, x, y, yerr, N=1000, *args, **kwargs):
"""See docstring for InterpolatedUnivariateSpline"""
<|body_0|>
def __call__(self, x, *args, **kwargs):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ErrorPropagationSpline:
"""Does a spline fit, but returns both the spline value and associated uncertainty."""
def __init__(self, x, y, yerr, N=1000, *args, **kwargs):
"""See docstring for InterpolatedUnivariateSpline"""
yerr = np.clip(yerr, a_min=0.001, a_max=1)
yy = np.vstack([y... | the_stack_v2_python_sparse | error_interpolation.py | niliafsari/AnalyticLCModel | train | 2 |
0e0d0aebb7fe9a3db6c616d24d229877977ae6a0 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Throttler defines the throttler RPC calls. | ThrottlerServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThrottlerServicer:
"""Throttler defines the throttler RPC calls."""
def MaxRates(self, request, context):
"""MaxRates returns the current max rate for each throttler of the process."""
<|body_0|>
def SetMaxRate(self, request, context):
"""SetMaxRate allows to cha... | stack_v2_sparse_classes_75kplus_train_074039 | 5,345 | permissive | [
{
"docstring": "MaxRates returns the current max rate for each throttler of the process.",
"name": "MaxRates",
"signature": "def MaxRates(self, request, context)"
},
{
"docstring": "SetMaxRate allows to change the current max rate for all throttlers of the process.",
"name": "SetMaxRate",
... | 5 | null | Implement the Python class `ThrottlerServicer` described below.
Class description:
Throttler defines the throttler RPC calls.
Method signatures and docstrings:
- def MaxRates(self, request, context): MaxRates returns the current max rate for each throttler of the process.
- def SetMaxRate(self, request, context): Set... | Implement the Python class `ThrottlerServicer` described below.
Class description:
Throttler defines the throttler RPC calls.
Method signatures and docstrings:
- def MaxRates(self, request, context): MaxRates returns the current max rate for each throttler of the process.
- def SetMaxRate(self, request, context): Set... | c873c58fc95bc1b322d788bdb32f2305780cbcfd | <|skeleton|>
class ThrottlerServicer:
"""Throttler defines the throttler RPC calls."""
def MaxRates(self, request, context):
"""MaxRates returns the current max rate for each throttler of the process."""
<|body_0|>
def SetMaxRate(self, request, context):
"""SetMaxRate allows to cha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThrottlerServicer:
"""Throttler defines the throttler RPC calls."""
def MaxRates(self, request, context):
"""MaxRates returns the current max rate for each throttler of the process."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | py/vtproto/throttlerservice_pb2_grpc.py | HubSpot/vitess | train | 7 |
1afe882963cf1be0a5792cdf0429c20a087736f2 | [
"class ExceptionType1(Exception):\n pass\n\nclass ExceptionType2(Exception):\n pass\n\n@decorators.Memoize\ndef raiseExceptions():\n if raiseExceptions.count == 0:\n raiseExceptions.count += 1\n raise ExceptionType1()\n if raiseExceptions.count == 1:\n raise ExceptionType2()\nraiseE... | <|body_start_0|>
class ExceptionType1(Exception):
pass
class ExceptionType2(Exception):
pass
@decorators.Memoize
def raiseExceptions():
if raiseExceptions.count == 0:
raiseExceptions.count += 1
raise ExceptionType1()
... | MemoizeDecoratorTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemoizeDecoratorTest:
def testFunctionExceptionNotMemoized(self):
"""Tests that |Memoize| decorator does not cache exception results."""
<|body_0|>
def testFunctionResultMemoized(self):
"""Tests that |Memoize| decorator caches results."""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus_train_074040 | 2,847 | permissive | [
{
"docstring": "Tests that |Memoize| decorator does not cache exception results.",
"name": "testFunctionExceptionNotMemoized",
"signature": "def testFunctionExceptionNotMemoized(self)"
},
{
"docstring": "Tests that |Memoize| decorator caches results.",
"name": "testFunctionResultMemoized",
... | 3 | null | Implement the Python class `MemoizeDecoratorTest` described below.
Class description:
Implement the MemoizeDecoratorTest class.
Method signatures and docstrings:
- def testFunctionExceptionNotMemoized(self): Tests that |Memoize| decorator does not cache exception results.
- def testFunctionResultMemoized(self): Tests... | Implement the Python class `MemoizeDecoratorTest` described below.
Class description:
Implement the MemoizeDecoratorTest class.
Method signatures and docstrings:
- def testFunctionExceptionNotMemoized(self): Tests that |Memoize| decorator does not cache exception results.
- def testFunctionResultMemoized(self): Tests... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class MemoizeDecoratorTest:
def testFunctionExceptionNotMemoized(self):
"""Tests that |Memoize| decorator does not cache exception results."""
<|body_0|>
def testFunctionResultMemoized(self):
"""Tests that |Memoize| decorator caches results."""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MemoizeDecoratorTest:
def testFunctionExceptionNotMemoized(self):
"""Tests that |Memoize| decorator does not cache exception results."""
class ExceptionType1(Exception):
pass
class ExceptionType2(Exception):
pass
@decorators.Memoize
def raiseEx... | the_stack_v2_python_sparse | build/android/pylib/utils/decorators_test.py | chromium/chromium | train | 17,408 | |
9fa09a6aad4f71f5e633bda30f77afd6be8e4436 | [
"self.num_classes = num_classes\nself.shape = shape\nself.is_infer = is_infer\nself.image_vector_size = shape[0] * shape[1]\nself.__declare_input_layers__()\nself.__build_nn__()",
"self.image = paddle.layer.data(name='image', type=paddle.data_type.dense_vector(self.image_vector_size), height=self.shape[1], width=... | <|body_start_0|>
self.num_classes = num_classes
self.shape = shape
self.is_infer = is_infer
self.image_vector_size = shape[0] * shape[1]
self.__declare_input_layers__()
self.__build_nn__()
<|end_body_0|>
<|body_start_1|>
self.image = paddle.layer.data(name='image... | Model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
def __init__(self, num_classes, shape, is_infer=False):
""":param num_classes: 字符字典的大小 :type num_classes: int :param shape: 输入图像的大小 :type shape: tuple of 2 int :param is_infer: 是否用于预测 :type shape: bool"""
<|body_0|>
def __declare_input_layers__(self):
"""定义输入层... | stack_v2_sparse_classes_75kplus_train_074041 | 3,534 | permissive | [
{
"docstring": ":param num_classes: 字符字典的大小 :type num_classes: int :param shape: 输入图像的大小 :type shape: tuple of 2 int :param is_infer: 是否用于预测 :type shape: bool",
"name": "__init__",
"signature": "def __init__(self, num_classes, shape, is_infer=False)"
},
{
"docstring": "定义输入层",
"name": "__dec... | 3 | stack_v2_sparse_classes_30k_test_001173 | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def __init__(self, num_classes, shape, is_infer=False): :param num_classes: 字符字典的大小 :type num_classes: int :param shape: 输入图像的大小 :type shape: tuple of 2 int :param is_infer: 是否用于预测 :ty... | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def __init__(self, num_classes, shape, is_infer=False): :param num_classes: 字符字典的大小 :type num_classes: int :param shape: 输入图像的大小 :type shape: tuple of 2 int :param is_infer: 是否用于预测 :ty... | c4500904615149115535b66a67d3e5d06f8435c4 | <|skeleton|>
class Model:
def __init__(self, num_classes, shape, is_infer=False):
""":param num_classes: 字符字典的大小 :type num_classes: int :param shape: 输入图像的大小 :type shape: tuple of 2 int :param is_infer: 是否用于预测 :type shape: bool"""
<|body_0|>
def __declare_input_layers__(self):
"""定义输入层... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Model:
def __init__(self, num_classes, shape, is_infer=False):
""":param num_classes: 字符字典的大小 :type num_classes: int :param shape: 输入图像的大小 :type shape: tuple of 2 int :param is_infer: 是否用于预测 :type shape: bool"""
self.num_classes = num_classes
self.shape = shape
self.is_infer = ... | the_stack_v2_python_sparse | note6/code/network_conf.py | songkunhuang/LearnPaddle | train | 1 | |
965d2207a44e7ac9ad1265c5c7f37ea01bb96d3d | [
"if not contact:\n return False\ncontact_regex = re.compile('^[0-9]{10,13}$')\nif contact_regex.match(contact):\n return True\nreturn False",
"if not amount:\n return False\namount_regex = re.compile('^[0-9]+$')\ntry:\n if amount_regex.match(amount) and int(amount) > 0:\n return True\nexcept Ty... | <|body_start_0|>
if not contact:
return False
contact_regex = re.compile('^[0-9]{10,13}$')
if contact_regex.match(contact):
return True
return False
<|end_body_0|>
<|body_start_1|>
if not amount:
return False
amount_regex = re.compile(... | Defines validator functions. can be edited to add more | Validators | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Validators:
"""Defines validator functions. can be edited to add more"""
def validate_contact(contact) -> bool:
"""Validate contact number. Must be at least 10 digits and not more than 13 :param contact: :return:"""
<|body_0|>
def validate_number(amount) -> bool:
... | stack_v2_sparse_classes_75kplus_train_074042 | 1,699 | no_license | [
{
"docstring": "Validate contact number. Must be at least 10 digits and not more than 13 :param contact: :return:",
"name": "validate_contact",
"signature": "def validate_contact(contact) -> bool"
},
{
"docstring": "validate any number. ensure its a number :param amount: :return:",
"name": "... | 4 | stack_v2_sparse_classes_30k_train_009720 | Implement the Python class `Validators` described below.
Class description:
Defines validator functions. can be edited to add more
Method signatures and docstrings:
- def validate_contact(contact) -> bool: Validate contact number. Must be at least 10 digits and not more than 13 :param contact: :return:
- def validate... | Implement the Python class `Validators` described below.
Class description:
Defines validator functions. can be edited to add more
Method signatures and docstrings:
- def validate_contact(contact) -> bool: Validate contact number. Must be at least 10 digits and not more than 13 :param contact: :return:
- def validate... | 0118641376a58c3b336bd4514d191a4cbc1fc34a | <|skeleton|>
class Validators:
"""Defines validator functions. can be edited to add more"""
def validate_contact(contact) -> bool:
"""Validate contact number. Must be at least 10 digits and not more than 13 :param contact: :return:"""
<|body_0|>
def validate_number(amount) -> bool:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Validators:
"""Defines validator functions. can be edited to add more"""
def validate_contact(contact) -> bool:
"""Validate contact number. Must be at least 10 digits and not more than 13 :param contact: :return:"""
if not contact:
return False
contact_regex = re.compi... | the_stack_v2_python_sparse | api/utils/validators.py | reiosantos/ride-api | train | 0 |
82094a873fb42c04f18e66995f2612b2885fae41 | [
"super().__init__(self.PROBLEM_NAME)\nself.input_list = input_list\nself.K = K",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\ninput_list = self.input_list\nheapq.heapify(input_list)\nk = 1\nwhile True:\n element = heapq.heappop(input_list)\n if k == self.K:\n return element\n k = k ... | <|body_start_0|>
super().__init__(self.PROBLEM_NAME)
self.input_list = input_list
self.K = K
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
input_list = self.input_list
heapq.heapify(input_list)
k = 1
while True:... | Find Kth smallest in a unsorted array | FindKthSmallestInUnsortedArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FindKthSmallestInUnsortedArray:
"""Find Kth smallest in a unsorted array"""
def __init__(self, input_list, K):
"""Find Kth smallest in a unsorted array Args: input_list: Contains a list of integers K: th element to return Returns: None Raises: None"""
<|body_0|>
def solv... | stack_v2_sparse_classes_75kplus_train_074043 | 1,330 | no_license | [
{
"docstring": "Find Kth smallest in a unsorted array Args: input_list: Contains a list of integers K: th element to return Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, input_list, K)"
},
{
"docstring": "Solve the problem Note: O(N + KLogN) (runtime) complexi... | 2 | stack_v2_sparse_classes_30k_train_041553 | Implement the Python class `FindKthSmallestInUnsortedArray` described below.
Class description:
Find Kth smallest in a unsorted array
Method signatures and docstrings:
- def __init__(self, input_list, K): Find Kth smallest in a unsorted array Args: input_list: Contains a list of integers K: th element to return Retur... | Implement the Python class `FindKthSmallestInUnsortedArray` described below.
Class description:
Find Kth smallest in a unsorted array
Method signatures and docstrings:
- def __init__(self, input_list, K): Find Kth smallest in a unsorted array Args: input_list: Contains a list of integers K: th element to return Retur... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class FindKthSmallestInUnsortedArray:
"""Find Kth smallest in a unsorted array"""
def __init__(self, input_list, K):
"""Find Kth smallest in a unsorted array Args: input_list: Contains a list of integers K: th element to return Returns: None Raises: None"""
<|body_0|>
def solv... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FindKthSmallestInUnsortedArray:
"""Find Kth smallest in a unsorted array"""
def __init__(self, input_list, K):
"""Find Kth smallest in a unsorted array Args: input_list: Contains a list of integers K: th element to return Returns: None Raises: None"""
super().__init__(self.PROBLEM_NAME)
... | the_stack_v2_python_sparse | python/problems/array/find_kth_smallest_in_unsorted_array.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
95a00bf540728437bb745b9e5ca5eb3cdfbb087e | [
"super(ResBlock, self).__init__()\nif channels_in is None or channels_in == num_filters:\n channels_in = num_filters\n self.projection = None\nelse:\n self.projection = IdentityMapping(num_filters, channels_in, stride)\nself.conv1 = nn.Conv2d(channels_in, num_filters, 3, stride, 1)\nself.bn1 = nn.BatchNorm... | <|body_start_0|>
super(ResBlock, self).__init__()
if channels_in is None or channels_in == num_filters:
channels_in = num_filters
self.projection = None
else:
self.projection = IdentityMapping(num_filters, channels_in, stride)
self.conv1 = nn.Conv2d(ch... | Class for residual blocks in ResNet. | ResBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResBlock:
"""Class for residual blocks in ResNet."""
def __init__(self, num_filters, channels_in=None, stride=1):
"""Class initializer."""
<|body_0|>
def forward(self, x):
"""Forward propagation."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_75kplus_train_074044 | 4,467 | permissive | [
{
"docstring": "Class initializer.",
"name": "__init__",
"signature": "def __init__(self, num_filters, channels_in=None, stride=1)"
},
{
"docstring": "Forward propagation.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016426 | Implement the Python class `ResBlock` described below.
Class description:
Class for residual blocks in ResNet.
Method signatures and docstrings:
- def __init__(self, num_filters, channels_in=None, stride=1): Class initializer.
- def forward(self, x): Forward propagation. | Implement the Python class `ResBlock` described below.
Class description:
Class for residual blocks in ResNet.
Method signatures and docstrings:
- def __init__(self, num_filters, channels_in=None, stride=1): Class initializer.
- def forward(self, x): Forward propagation.
<|skeleton|>
class ResBlock:
"""Class for... | fe5d1eb5ab5453be70c4be473fd3da71afe4b06c | <|skeleton|>
class ResBlock:
"""Class for residual blocks in ResNet."""
def __init__(self, num_filters, channels_in=None, stride=1):
"""Class initializer."""
<|body_0|>
def forward(self, x):
"""Forward propagation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResBlock:
"""Class for residual blocks in ResNet."""
def __init__(self, num_filters, channels_in=None, stride=1):
"""Class initializer."""
super(ResBlock, self).__init__()
if channels_in is None or channels_in == num_filters:
channels_in = num_filters
self.... | the_stack_v2_python_sparse | src/kegnet/classifier/models/resnet.py | videoturingtest/KegNet | train | 0 |
678f0b217ef63cbff4f1c3189dcb58b82202d46b | [
"super(LabelSmoothing, self).__init__()\nself.smoothing = smoothing\nself.padding_token_index = padding_token_index",
"batch_size, target_sequence_length, caption_vocab_size = predicted_tensor.shape\npredicted_tensor = predicted_tensor.contiguous().view(-1, caption_vocab_size)\ntarget_tensor = target_tensor.conti... | <|body_start_0|>
super(LabelSmoothing, self).__init__()
self.smoothing = smoothing
self.padding_token_index = padding_token_index
<|end_body_0|>
<|body_start_1|>
batch_size, target_sequence_length, caption_vocab_size = predicted_tensor.shape
predicted_tensor = predicted_tensor.c... | The loss essentially drives your “gradients”, which in simple terms determines the “learning” of the model. Many manual annotations are the results of multiple participants. They might have different criteria. They might make some mistakes. So complete reliance on correct label probabilites for calculating loss is prob... | LabelSmoothing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelSmoothing:
"""The loss essentially drives your “gradients”, which in simple terms determines the “learning” of the model. Many manual annotations are the results of multiple participants. They might have different criteria. They might make some mistakes. So complete reliance on correct label... | stack_v2_sparse_classes_75kplus_train_074045 | 4,419 | no_license | [
{
"docstring": "Args: smoothing_factor: Smooting factor to be used in label smoothing padding_token_index: Padding token index",
"name": "__init__",
"signature": "def __init__(self, smoothing, padding_token_index)"
},
{
"docstring": "Apply label smoothing to obtained new loss for predicted token... | 2 | stack_v2_sparse_classes_30k_train_009666 | Implement the Python class `LabelSmoothing` described below.
Class description:
The loss essentially drives your “gradients”, which in simple terms determines the “learning” of the model. Many manual annotations are the results of multiple participants. They might have different criteria. They might make some mistakes... | Implement the Python class `LabelSmoothing` described below.
Class description:
The loss essentially drives your “gradients”, which in simple terms determines the “learning” of the model. Many manual annotations are the results of multiple participants. They might have different criteria. They might make some mistakes... | 921557ee2f63bec10d2d3edfdad32919df3b82cf | <|skeleton|>
class LabelSmoothing:
"""The loss essentially drives your “gradients”, which in simple terms determines the “learning” of the model. Many manual annotations are the results of multiple participants. They might have different criteria. They might make some mistakes. So complete reliance on correct label... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LabelSmoothing:
"""The loss essentially drives your “gradients”, which in simple terms determines the “learning” of the model. Many manual annotations are the results of multiple participants. They might have different criteria. They might make some mistakes. So complete reliance on correct label probabilites... | the_stack_v2_python_sparse | multiModalDense/src/loss/lossComputer.py | VP-0822/Video-Keyword-Extractor | train | 11 |
e998b49a3db66c22905d0c817517699f4fdd9e84 | [
"self.anneal = cfg.MODEL.LOSSES.SA.ANNEAL\nself.metric = cfg.MODEL.LOSSES.SA.METRIC\nself.num_id = cfg.SOLVER.IMS_PER_BATCH // cfg.DATALOADER.NUM_INSTANCE",
"embedding = F.normalize(embedding, dim=1)\nfeat_dim = embedding.size(1)\nif comm.get_world_size() > 1:\n all_embedding = concat_all_gather(embedding)\n ... | <|body_start_0|>
self.anneal = cfg.MODEL.LOSSES.SA.ANNEAL
self.metric = cfg.MODEL.LOSSES.SA.METRIC
self.num_id = cfg.SOLVER.IMS_PER_BATCH // cfg.DATALOADER.NUM_INSTANCE
<|end_body_0|>
<|body_start_1|>
embedding = F.normalize(embedding, dim=1)
feat_dim = embedding.size(1)
... | PyTorch implementation of the Smooth-AP loss. implementation of the Smooth-AP loss. Takes as input the mini-batch of CNN-produced feature embeddings and returns the value of the Smooth-AP loss. The mini-batch must be formed of a defined number of classes. Each class must have the same number of instances represented in... | SmoothAP | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmoothAP:
"""PyTorch implementation of the Smooth-AP loss. implementation of the Smooth-AP loss. Takes as input the mini-batch of CNN-produced feature embeddings and returns the value of the Smooth-AP loss. The mini-batch must be formed of a defined number of classes. Each class must have the sam... | stack_v2_sparse_classes_75kplus_train_074046 | 10,777 | permissive | [
{
"docstring": "Parameters ---------- cfg: (cfgNode) anneal : float the temperature of the sigmoid that is used to smooth the ranking function batch_size : int the batch size being used num_id : int the number of different classes that are represented in the batch feat_dims : int the dimension of the input feat... | 2 | stack_v2_sparse_classes_30k_train_053665 | Implement the Python class `SmoothAP` described below.
Class description:
PyTorch implementation of the Smooth-AP loss. implementation of the Smooth-AP loss. Takes as input the mini-batch of CNN-produced feature embeddings and returns the value of the Smooth-AP loss. The mini-batch must be formed of a defined number o... | Implement the Python class `SmoothAP` described below.
Class description:
PyTorch implementation of the Smooth-AP loss. implementation of the Smooth-AP loss. Takes as input the mini-batch of CNN-produced feature embeddings and returns the value of the Smooth-AP loss. The mini-batch must be formed of a defined number o... | d0eaee768e0be606417a27ce5ea2b3071b5a9bc2 | <|skeleton|>
class SmoothAP:
"""PyTorch implementation of the Smooth-AP loss. implementation of the Smooth-AP loss. Takes as input the mini-batch of CNN-produced feature embeddings and returns the value of the Smooth-AP loss. The mini-batch must be formed of a defined number of classes. Each class must have the sam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SmoothAP:
"""PyTorch implementation of the Smooth-AP loss. implementation of the Smooth-AP loss. Takes as input the mini-batch of CNN-produced feature embeddings and returns the value of the Smooth-AP loss. The mini-batch must be formed of a defined number of classes. Each class must have the same number of i... | the_stack_v2_python_sparse | fastreid/modeling/losses/smooth_ap.py | SZLSP/reid2020NAIC | train | 2 |
dda4d6fdf84bc343cdbe94d0be98fc87c12a55ef | [
"assert verifiers, 'At least one verifier is required'\nif __debug__:\n for verifier in verifiers:\n assert isinstance(verifier, IVerifier), 'Invalid verifier %s' % verifier\nself.verifiers = verifiers",
"for verifier in self.verifiers:\n assert isinstance(verifier, IVerifier), 'Invalid verifier %s' ... | <|body_start_0|>
assert verifiers, 'At least one verifier is required'
if __debug__:
for verifier in verifiers:
assert isinstance(verifier, IVerifier), 'Invalid verifier %s' % verifier
self.verifiers = verifiers
<|end_body_0|>
<|body_start_1|>
for verifier in... | Implementation for a @see: IVerifier that aplies an 'or' operator between verifiers. | VerifierOr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerifierOr:
"""Implementation for a @see: IVerifier that aplies an 'or' operator between verifiers."""
def __init__(self, *verifiers):
"""Construct the 'or' verifier. @param verifiers: arguments[IVerifier] The verifiers to apply the 'or' for."""
<|body_0|>
def prepare(se... | stack_v2_sparse_classes_75kplus_train_074047 | 15,633 | no_license | [
{
"docstring": "Construct the 'or' verifier. @param verifiers: arguments[IVerifier] The verifiers to apply the 'or' for.",
"name": "__init__",
"signature": "def __init__(self, *verifiers)"
},
{
"docstring": "@see: IVerifier.prepare",
"name": "prepare",
"signature": "def prepare(self, res... | 3 | stack_v2_sparse_classes_30k_train_053843 | Implement the Python class `VerifierOr` described below.
Class description:
Implementation for a @see: IVerifier that aplies an 'or' operator between verifiers.
Method signatures and docstrings:
- def __init__(self, *verifiers): Construct the 'or' verifier. @param verifiers: arguments[IVerifier] The verifiers to appl... | Implement the Python class `VerifierOr` described below.
Class description:
Implementation for a @see: IVerifier that aplies an 'or' operator between verifiers.
Method signatures and docstrings:
- def __init__(self, *verifiers): Construct the 'or' verifier. @param verifiers: arguments[IVerifier] The verifiers to appl... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class VerifierOr:
"""Implementation for a @see: IVerifier that aplies an 'or' operator between verifiers."""
def __init__(self, *verifiers):
"""Construct the 'or' verifier. @param verifiers: arguments[IVerifier] The verifiers to apply the 'or' for."""
<|body_0|>
def prepare(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VerifierOr:
"""Implementation for a @see: IVerifier that aplies an 'or' operator between verifiers."""
def __init__(self, *verifiers):
"""Construct the 'or' verifier. @param verifiers: arguments[IVerifier] The verifiers to apply the 'or' for."""
assert verifiers, 'At least one verifier is... | the_stack_v2_python_sparse | components/ally-core/ally/core/impl/definition.py | cristidomsa/Ally-Py | train | 0 |
d937b559c5bb5ba44707a57a0cf59cb814d68f9a | [
"super().__init__(**kwargs)\nself.player_df = pd.read_csv('../Data/DotaPlayer.csv', index_col=False, header=0)\nself.player_df['Date'] = pd.to_datetime(self.player_df['Date'])",
"urls = []\nfor _, row in self.player_df.iterrows():\n urls.append({'url': f\"https://api.opendota.com/api/players/{row['Account_ID']... | <|body_start_0|>
super().__init__(**kwargs)
self.player_df = pd.read_csv('../Data/DotaPlayer.csv', index_col=False, header=0)
self.player_df['Date'] = pd.to_datetime(self.player_df['Date'])
<|end_body_0|>
<|body_start_1|>
urls = []
for _, row in self.player_df.iterrows():
... | PlayerSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayerSpider:
def __init__(self, **kwargs):
"""initialize the data"""
<|body_0|>
def start_requests(self):
"""start the data gathering"""
<|body_1|>
def parse(self, response):
"""the response are all matches of a account. This method saves all ma... | stack_v2_sparse_classes_75kplus_train_074048 | 2,659 | permissive | [
{
"docstring": "initialize the data",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "start the data gathering",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "the response are all matches of a account. This... | 3 | null | Implement the Python class `PlayerSpider` described below.
Class description:
Implement the PlayerSpider class.
Method signatures and docstrings:
- def __init__(self, **kwargs): initialize the data
- def start_requests(self): start the data gathering
- def parse(self, response): the response are all matches of a acco... | Implement the Python class `PlayerSpider` described below.
Class description:
Implement the PlayerSpider class.
Method signatures and docstrings:
- def __init__(self, **kwargs): initialize the data
- def start_requests(self): start the data gathering
- def parse(self, response): the response are all matches of a acco... | 8082bb89d00d28ade774a445a1645dc07ac86127 | <|skeleton|>
class PlayerSpider:
def __init__(self, **kwargs):
"""initialize the data"""
<|body_0|>
def start_requests(self):
"""start the data gathering"""
<|body_1|>
def parse(self, response):
"""the response are all matches of a account. This method saves all ma... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlayerSpider:
def __init__(self, **kwargs):
"""initialize the data"""
super().__init__(**kwargs)
self.player_df = pd.read_csv('../Data/DotaPlayer.csv', index_col=False, header=0)
self.player_df['Date'] = pd.to_datetime(self.player_df['Date'])
def start_requests(self):
... | the_stack_v2_python_sparse | DotaDataAnalysis/DotaDataGathering/DotaDataGathering/spiders/PlayerMatchesSpider.py | PatrickKoss/BettingPrediction | train | 0 | |
b68d646b353f8a874c49c83555e2994664a3307d | [
"super().__init__()\nself.multioutputWrapper = False\nimport sklearn\nimport sklearn.linear_model\nself.model = sklearn.linear_model.RidgeCV",
"specs = super(RidgeCV, cls).getInputSpecification()\nspecs.description = 'The \\\\xmlNode{RidgeCV} regressor also known as\\n \\\\textit{linea... | <|body_start_0|>
super().__init__()
self.multioutputWrapper = False
import sklearn
import sklearn.linear_model
self.model = sklearn.linear_model.RidgeCV
<|end_body_0|>
<|body_start_1|>
specs = super(RidgeCV, cls).getInputSpecification()
specs.description = 'The \... | Ridge Regressor with cross-validation | RidgeCV | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RidgeCV:
"""Ridge Regressor with cross-validation"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class th... | stack_v2_sparse_classes_75kplus_train_074049 | 7,775 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 3 | null | Implement the Python class `RidgeCV` described below.
Class description:
Ridge Regressor with cross-validation
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a re... | Implement the Python class `RidgeCV` described below.
Class description:
Ridge Regressor with cross-validation
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a re... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class RidgeCV:
"""Ridge Regressor with cross-validation"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RidgeCV:
"""Ridge Regressor with cross-validation"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
self.multioutputWrapper = False
import sklearn
import sklearn.linear... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/LinearModel/RidgeCV.py | idaholab/raven | train | 201 |
413a5b924f634fe6df281469b00fac390470e748 | [
"self.c = db.c\nself.connection = db.connection\nself.c.execute(\"CREATE TABLE IF NOT EXISTS 'payment_channel' (deposit_txid text unique, state text,deposit_tx text, payment_tx text, refund_tx text, merchant_pubkey text, created_at timestamp, expires_at timestamp, amount integer, last_payment_amount integer)\")",
... | <|body_start_0|>
self.c = db.c
self.connection = db.connection
self.c.execute("CREATE TABLE IF NOT EXISTS 'payment_channel' (deposit_txid text unique, state text,deposit_tx text, payment_tx text, refund_tx text, merchant_pubkey text, created_at timestamp, expires_at timestamp, amount integer, la... | ChannelSQLite3 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChannelSQLite3:
def __init__(self, db):
"""Instantiate SQLite3 for storing channel transaction data."""
<|body_0|>
def create(self, refund_tx, merch_pubkey):
"""Create a payment channel entry."""
<|body_1|>
def lookup(self, deposit_txid):
"""Look... | stack_v2_sparse_classes_75kplus_train_074050 | 13,202 | permissive | [
{
"docstring": "Instantiate SQLite3 for storing channel transaction data.",
"name": "__init__",
"signature": "def __init__(self, db)"
},
{
"docstring": "Create a payment channel entry.",
"name": "create",
"signature": "def create(self, refund_tx, merch_pubkey)"
},
{
"docstring": ... | 6 | stack_v2_sparse_classes_30k_train_052187 | Implement the Python class `ChannelSQLite3` described below.
Class description:
Implement the ChannelSQLite3 class.
Method signatures and docstrings:
- def __init__(self, db): Instantiate SQLite3 for storing channel transaction data.
- def create(self, refund_tx, merch_pubkey): Create a payment channel entry.
- def l... | Implement the Python class `ChannelSQLite3` described below.
Class description:
Implement the ChannelSQLite3 class.
Method signatures and docstrings:
- def __init__(self, db): Instantiate SQLite3 for storing channel transaction data.
- def create(self, refund_tx, merch_pubkey): Create a payment channel entry.
- def l... | 6b3e73745bc2b6b7eff064a0f190af0e25ef32d6 | <|skeleton|>
class ChannelSQLite3:
def __init__(self, db):
"""Instantiate SQLite3 for storing channel transaction data."""
<|body_0|>
def create(self, refund_tx, merch_pubkey):
"""Create a payment channel entry."""
<|body_1|>
def lookup(self, deposit_txid):
"""Look... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChannelSQLite3:
def __init__(self, db):
"""Instantiate SQLite3 for storing channel transaction data."""
self.c = db.c
self.connection = db.connection
self.c.execute("CREATE TABLE IF NOT EXISTS 'payment_channel' (deposit_txid text unique, state text,deposit_tx text, payment_tx t... | the_stack_v2_python_sparse | two1/lib/bitserv/models.py | masonicGIT/two1 | train | 1 | |
478978f0e2708eee874427d2ee459781241abe3e | [
"self.title = 'Convert Miles to Kilometres'\nself.root = Builder.load_file('convert_miles_km.kv')\nreturn self.root",
"input_value = self.get_validated_input()\nresult = input_value * CONVERSION_FACTOR\nself.root.ids.output_label.text = str(result)",
"input_value = self.get_validated_input()\ninput_value += inc... | <|body_start_0|>
self.title = 'Convert Miles to Kilometres'
self.root = Builder.load_file('convert_miles_km.kv')
return self.root
<|end_body_0|>
<|body_start_1|>
input_value = self.get_validated_input()
result = input_value * CONVERSION_FACTOR
self.root.ids.output_label.... | Kivy App for squaring a number | MilesToKilometresApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MilesToKilometresApp:
"""Kivy App for squaring a number"""
def build(self):
"""Build the app from the .kv file"""
<|body_0|>
def calculate_result(self):
"""Convert from miles to kilometres"""
<|body_1|>
def handle_increment(self, increment_value):
... | stack_v2_sparse_classes_75kplus_train_074051 | 1,180 | no_license | [
{
"docstring": "Build the app from the .kv file",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "Convert from miles to kilometres",
"name": "calculate_result",
"signature": "def calculate_result(self)"
},
{
"docstring": "Increment the input by a given value",
... | 4 | stack_v2_sparse_classes_30k_train_040539 | Implement the Python class `MilesToKilometresApp` described below.
Class description:
Kivy App for squaring a number
Method signatures and docstrings:
- def build(self): Build the app from the .kv file
- def calculate_result(self): Convert from miles to kilometres
- def handle_increment(self, increment_value): Increm... | Implement the Python class `MilesToKilometresApp` described below.
Class description:
Kivy App for squaring a number
Method signatures and docstrings:
- def build(self): Build the app from the .kv file
- def calculate_result(self): Convert from miles to kilometres
- def handle_increment(self, increment_value): Increm... | eb1a205034ddcecd1ae771ca01168af7f83e4207 | <|skeleton|>
class MilesToKilometresApp:
"""Kivy App for squaring a number"""
def build(self):
"""Build the app from the .kv file"""
<|body_0|>
def calculate_result(self):
"""Convert from miles to kilometres"""
<|body_1|>
def handle_increment(self, increment_value):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MilesToKilometresApp:
"""Kivy App for squaring a number"""
def build(self):
"""Build the app from the .kv file"""
self.title = 'Convert Miles to Kilometres'
self.root = Builder.load_file('convert_miles_km.kv')
return self.root
def calculate_result(self):
"""Co... | the_stack_v2_python_sparse | prac_07/convert_miles_km.py | ishaqueahmed/cp5632practicals | train | 0 |
74e1196e322b18981339e8a17f085eeba04e6ebf | [
"argument_group.add_argument(u'--case_name', dest=u'case_name', type=str, action=u'store', default=cls._DEFAULT_CASE, help=u'Add a case name. This will be the name of the index in ElasticSearch.')\nargument_group.add_argument(u'--document_type', dest=u'document_type', type=str, action=u'store', default=cls._DEFAULT... | <|body_start_0|>
argument_group.add_argument(u'--case_name', dest=u'case_name', type=str, action=u'store', default=cls._DEFAULT_CASE, help=u'Add a case name. This will be the name of the index in ElasticSearch.')
argument_group.add_argument(u'--document_type', dest=u'document_type', type=str, action=u's... | CLI arguments helper class for an Elastic Search output module. | ElasticOutputHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElasticOutputHelper:
"""CLI arguments helper class for an Elastic Search output module."""
def AddArguments(cls, argument_group):
"""Add command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it ... | stack_v2_sparse_classes_75kplus_train_074052 | 2,989 | permissive | [
{
"docstring": "Add command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group: the argparse group (instance of argparse._ArgumentGroup or or argparse... | 2 | stack_v2_sparse_classes_30k_train_008617 | Implement the Python class `ElasticOutputHelper` described below.
Class description:
CLI arguments helper class for an Elastic Search output module.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Add command line arguments the helper supports to an argument group. This function takes an ar... | Implement the Python class `ElasticOutputHelper` described below.
Class description:
CLI arguments helper class for an Elastic Search output module.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Add command line arguments the helper supports to an argument group. This function takes an ar... | 923797fc00664fa9e3277781b0334d6eed5664fd | <|skeleton|>
class ElasticOutputHelper:
"""CLI arguments helper class for an Elastic Search output module."""
def AddArguments(cls, argument_group):
"""Add command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ElasticOutputHelper:
"""CLI arguments helper class for an Elastic Search output module."""
def AddArguments(cls, argument_group):
"""Add command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the comma... | the_stack_v2_python_sparse | plaso/cli/helpers/elastic_output.py | CNR-ITTIG/plasodfaxp | train | 1 |
be754ea7688001bd04b84fb87d6fcf6e4137453d | [
"PySparkDataAssetIO._check_spark_session(spark_session)\nif asset.declarations.is_parquet_output:\n data = spark_session.read.parquet(asset.ready_path)\nelif asset.declarations.is_csv_output:\n data = spark_session.read.csv(path=asset.ready_path, **reader_kwargs)\nelse:\n raise ValueError(f'Unsupported ass... | <|body_start_0|>
PySparkDataAssetIO._check_spark_session(spark_session)
if asset.declarations.is_parquet_output:
data = spark_session.read.parquet(asset.ready_path)
elif asset.declarations.is_csv_output:
data = spark_session.read.csv(path=asset.ready_path, **reader_kwargs... | IO interface for the Airtunnel PySparkDataAsset. | PySparkDataAssetIO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PySparkDataAssetIO:
"""IO interface for the Airtunnel PySparkDataAsset."""
def retrieve_data_asset(asset: PySparkDataAsset, spark_session: 'pyspark.sql.SparkSession'=None, **reader_kwargs) -> 'pyspark.sql.DataFrame':
"""Retrieves a PySparkDataAsset from the Airtunnel data store (usin... | stack_v2_sparse_classes_75kplus_train_074053 | 29,578 | permissive | [
{
"docstring": "Retrieves a PySparkDataAsset from the Airtunnel data store (using PySpark). :param asset: the data asset to retrieve :param spark_session: a live PySpark session to use (required) :param reader_kwargs: additional keyword arguments to pass into the PySpark reader function :return: the retrieved d... | 4 | stack_v2_sparse_classes_30k_train_011300 | Implement the Python class `PySparkDataAssetIO` described below.
Class description:
IO interface for the Airtunnel PySparkDataAsset.
Method signatures and docstrings:
- def retrieve_data_asset(asset: PySparkDataAsset, spark_session: 'pyspark.sql.SparkSession'=None, **reader_kwargs) -> 'pyspark.sql.DataFrame': Retriev... | Implement the Python class `PySparkDataAssetIO` described below.
Class description:
IO interface for the Airtunnel PySparkDataAsset.
Method signatures and docstrings:
- def retrieve_data_asset(asset: PySparkDataAsset, spark_session: 'pyspark.sql.SparkSession'=None, **reader_kwargs) -> 'pyspark.sql.DataFrame': Retriev... | bbed0a2d5addd0dd6221b75c06982f47e0d837d4 | <|skeleton|>
class PySparkDataAssetIO:
"""IO interface for the Airtunnel PySparkDataAsset."""
def retrieve_data_asset(asset: PySparkDataAsset, spark_session: 'pyspark.sql.SparkSession'=None, **reader_kwargs) -> 'pyspark.sql.DataFrame':
"""Retrieves a PySparkDataAsset from the Airtunnel data store (usin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PySparkDataAssetIO:
"""IO interface for the Airtunnel PySparkDataAsset."""
def retrieve_data_asset(asset: PySparkDataAsset, spark_session: 'pyspark.sql.SparkSession'=None, **reader_kwargs) -> 'pyspark.sql.DataFrame':
"""Retrieves a PySparkDataAsset from the Airtunnel data store (using PySpark). :... | the_stack_v2_python_sparse | src/airtunnel/data_asset.py | rufuspollock/airtunnel | train | 0 |
53462e24bbf36b43c2586f0361551c4b2ae92f57 | [
"if not root:\n return 0\nself.helper_sum(root, target_sum)\nself.path_sum(root.left, target_sum)\nself.path_sum(root.right, target_sum)\nreturn self.res",
"if not root:\n return\ntarget -= root.val\nif target == 0:\n self.res += 1\nself.helper_sum(root.left, target)\nself.helper_sum(root.right, target)"... | <|body_start_0|>
if not root:
return 0
self.helper_sum(root, target_sum)
self.path_sum(root.left, target_sum)
self.path_sum(root.right, target_sum)
return self.res
<|end_body_0|>
<|body_start_1|>
if not root:
return
target -= root.val
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def path_sum(self, root: TreeNode, target_sum: int) -> int:
"""路径距离 Args: root: 根节点 target_sum: 目标值 Returns: 得到目标值的种数"""
<|body_0|>
def helper_sum(self, root: TreeNode, target: int) -> None:
"""循环帮助类 Args: root: 根节点 target: 目标值 Returns: None"""
<|bo... | stack_v2_sparse_classes_75kplus_train_074054 | 2,286 | permissive | [
{
"docstring": "路径距离 Args: root: 根节点 target_sum: 目标值 Returns: 得到目标值的种数",
"name": "path_sum",
"signature": "def path_sum(self, root: TreeNode, target_sum: int) -> int"
},
{
"docstring": "循环帮助类 Args: root: 根节点 target: 目标值 Returns: None",
"name": "helper_sum",
"signature": "def helper_sum(s... | 2 | stack_v2_sparse_classes_30k_train_017009 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def path_sum(self, root: TreeNode, target_sum: int) -> int: 路径距离 Args: root: 根节点 target_sum: 目标值 Returns: 得到目标值的种数
- def helper_sum(self, root: TreeNode, target: int) -> None: 循环... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def path_sum(self, root: TreeNode, target_sum: int) -> int: 路径距离 Args: root: 根节点 target_sum: 目标值 Returns: 得到目标值的种数
- def helper_sum(self, root: TreeNode, target: int) -> None: 循环... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def path_sum(self, root: TreeNode, target_sum: int) -> int:
"""路径距离 Args: root: 根节点 target_sum: 目标值 Returns: 得到目标值的种数"""
<|body_0|>
def helper_sum(self, root: TreeNode, target: int) -> None:
"""循环帮助类 Args: root: 根节点 target: 目标值 Returns: None"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def path_sum(self, root: TreeNode, target_sum: int) -> int:
"""路径距离 Args: root: 根节点 target_sum: 目标值 Returns: 得到目标值的种数"""
if not root:
return 0
self.helper_sum(root, target_sum)
self.path_sum(root.left, target_sum)
self.path_sum(root.right, target_s... | the_stack_v2_python_sparse | src/leetcodepython/tree/path_sum_437.py | zhangyu345293721/leetcode | train | 101 | |
18927d88eab6aaf565372ecb99ee9e18706c1b6c | [
"ctx['x'] = x\nctx['y'] = y\nreturn x @ y",
"x, y = (ctx['x'], ctx['y'])\nx_grad = grad.clone()\ny_grad = grad.clone()\nif len(x.shape) < 2:\n x = x.unsqueeze(0)\n x_grad = x_grad.unsqueeze(0)\nif len(y.shape) < 2:\n y = y.unsqueeze(1)\n y_grad = y_grad.unsqueeze(1)\nx_grad = x_grad @ y.t()\ny_grad = ... | <|body_start_0|>
ctx['x'] = x
ctx['y'] = y
return x @ y
<|end_body_0|>
<|body_start_1|>
x, y = (ctx['x'], ctx['y'])
x_grad = grad.clone()
y_grad = grad.clone()
if len(x.shape) < 2:
x = x.unsqueeze(0)
x_grad = x_grad.unsqueeze(0)
if... | The multiplication gradient function. | GradMatMul | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradMatMul:
"""The multiplication gradient function."""
def forward(ctx: Dict[str, Any], x: MPCTensor, y: Any) -> MPCTensor:
"""Perform the feedforward and compute the result for the matrix multiplication operation. Args: ctx (Dict[str, Any]): Context used to save information needed ... | stack_v2_sparse_classes_75kplus_train_074055 | 27,230 | permissive | [
{
"docstring": "Perform the feedforward and compute the result for the matrix multiplication operation. Args: ctx (Dict[str, Any]): Context used to save information needed in the backward pass x (MPCTensor): 1st operand for the matrix multiplication operation y (Any): 2nd operand for the matrix multiplication o... | 2 | null | Implement the Python class `GradMatMul` described below.
Class description:
The multiplication gradient function.
Method signatures and docstrings:
- def forward(ctx: Dict[str, Any], x: MPCTensor, y: Any) -> MPCTensor: Perform the feedforward and compute the result for the matrix multiplication operation. Args: ctx (... | Implement the Python class `GradMatMul` described below.
Class description:
The multiplication gradient function.
Method signatures and docstrings:
- def forward(ctx: Dict[str, Any], x: MPCTensor, y: Any) -> MPCTensor: Perform the feedforward and compute the result for the matrix multiplication operation. Args: ctx (... | ee6ac74050acd03c3088104855d0b8e4ab3e03fa | <|skeleton|>
class GradMatMul:
"""The multiplication gradient function."""
def forward(ctx: Dict[str, Any], x: MPCTensor, y: Any) -> MPCTensor:
"""Perform the feedforward and compute the result for the matrix multiplication operation. Args: ctx (Dict[str, Any]): Context used to save information needed ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GradMatMul:
"""The multiplication gradient function."""
def forward(ctx: Dict[str, Any], x: MPCTensor, y: Any) -> MPCTensor:
"""Perform the feedforward and compute the result for the matrix multiplication operation. Args: ctx (Dict[str, Any]): Context used to save information needed in the backwa... | the_stack_v2_python_sparse | src/sympc/grads/grad_functions.py | shubhank-saxena/SyMPC | train | 1 |
707746385e561414d52c7e2c36c23d0979c010d8 | [
"self.column = column\nself.colour1 = colour1\nself.colour2 = colour2\nself.colour3 = colour3\nself.categorical = False",
"x = data[self.column].iget(index)\na = min(data[self.column])\nb = max(data[self.column])\nr1, g1, b1 = self.colour1\nr2, g2, b2 = self.colour2\nr3, g3, b3 = self.colour3\nx_scaled = (x - a) ... | <|body_start_0|>
self.column = column
self.colour1 = colour1
self.colour2 = colour2
self.colour3 = colour3
self.categorical = False
<|end_body_0|>
<|body_start_1|>
x = data[self.column].iget(index)
a = min(data[self.column])
b = max(data[self.column])
... | Create a mapping between a data attribute value and a point in colour space in a line of three specified colours. | ScaleGradient2 | [
"Python-2.0",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScaleGradient2:
"""Create a mapping between a data attribute value and a point in colour space in a line of three specified colours."""
def __init__(self, column, colour1, colour2, colour3):
"""Initialize ScaleGradient2 instance. Parameters: ----------- column: string, pandas DataFra... | stack_v2_sparse_classes_75kplus_train_074056 | 30,022 | permissive | [
{
"docstring": "Initialize ScaleGradient2 instance. Parameters: ----------- column: string, pandas DataFrame column name colour1: tuple 3 element tuple with float values representing an RGB colour colour2: tuple 3 element tuple with float values representing an RGB colour colour3: tuple 3 element tuple with flo... | 2 | null | Implement the Python class `ScaleGradient2` described below.
Class description:
Create a mapping between a data attribute value and a point in colour space in a line of three specified colours.
Method signatures and docstrings:
- def __init__(self, column, colour1, colour2, colour3): Initialize ScaleGradient2 instanc... | Implement the Python class `ScaleGradient2` described below.
Class description:
Create a mapping between a data attribute value and a point in colour space in a line of three specified colours.
Method signatures and docstrings:
- def __init__(self, column, colour1, colour2, colour3): Initialize ScaleGradient2 instanc... | 2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6 | <|skeleton|>
class ScaleGradient2:
"""Create a mapping between a data attribute value and a point in colour space in a line of three specified colours."""
def __init__(self, column, colour1, colour2, colour3):
"""Initialize ScaleGradient2 instance. Parameters: ----------- column: string, pandas DataFra... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScaleGradient2:
"""Create a mapping between a data attribute value and a point in colour space in a line of three specified colours."""
def __init__(self, column, colour1, colour2, colour3):
"""Initialize ScaleGradient2 instance. Parameters: ----------- column: string, pandas DataFrame column nam... | the_stack_v2_python_sparse | lib/python2.7/site-packages/pandas/tools/rplot.py | wangyum/Anaconda | train | 11 |
63b9ee0995fde029fb25fc0d11e86cc8c016b7ca | [
"AxisFormat.__init__(self, 'jetsreduced')\nself._axes['tracktpt'] = 0\nself._axes['tracketa'] = 1\nself._axes['trackphi'] = 2\nself._axes['vertexz'] = 3\nself._axes['mbtrigger'] = 4",
"newobj = AxisFormatReducedJetTHnSparse()\nnewobj._Deepcopy(other, memo)\nreturn newobj",
"newobj = AxisFormatReducedJetTHnSpars... | <|body_start_0|>
AxisFormat.__init__(self, 'jetsreduced')
self._axes['tracktpt'] = 0
self._axes['tracketa'] = 1
self._axes['trackphi'] = 2
self._axes['vertexz'] = 3
self._axes['mbtrigger'] = 4
<|end_body_0|>
<|body_start_1|>
newobj = AxisFormatReducedJetTHnSparse... | Axis format for projected THnSparse | AxisFormatReducedJetTHnSparse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxisFormatReducedJetTHnSparse:
"""Axis format for projected THnSparse"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __deepcopy__(self, other, memo):
"""Deep copy constructor"""
<|body_1|>
def __copy__(self, other):
"""Shallow copy c... | stack_v2_sparse_classes_75kplus_train_074057 | 7,138 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Deep copy constructor",
"name": "__deepcopy__",
"signature": "def __deepcopy__(self, other, memo)"
},
{
"docstring": "Shallow copy constructor",
"name": "__copy__",
"sig... | 3 | stack_v2_sparse_classes_30k_train_048353 | Implement the Python class `AxisFormatReducedJetTHnSparse` described below.
Class description:
Axis format for projected THnSparse
Method signatures and docstrings:
- def __init__(self): Constructor
- def __deepcopy__(self, other, memo): Deep copy constructor
- def __copy__(self, other): Shallow copy constructor | Implement the Python class `AxisFormatReducedJetTHnSparse` described below.
Class description:
Axis format for projected THnSparse
Method signatures and docstrings:
- def __init__(self): Constructor
- def __deepcopy__(self, other, memo): Deep copy constructor
- def __copy__(self, other): Shallow copy constructor
<|s... | 5df28b2b415e78e81273b0d9bf5c1b99feda3348 | <|skeleton|>
class AxisFormatReducedJetTHnSparse:
"""Axis format for projected THnSparse"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __deepcopy__(self, other, memo):
"""Deep copy constructor"""
<|body_1|>
def __copy__(self, other):
"""Shallow copy c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AxisFormatReducedJetTHnSparse:
"""Axis format for projected THnSparse"""
def __init__(self):
"""Constructor"""
AxisFormat.__init__(self, 'jetsreduced')
self._axes['tracktpt'] = 0
self._axes['tracketa'] = 1
self._axes['trackphi'] = 2
self._axes['vertexz'] = ... | the_stack_v2_python_sparse | PWGJE/EMCALJetTasks/Tracks/analysis/base/struct/JetTHnSparse.py | alisw/AliPhysics | train | 129 |
f7133524d0f50a791410d9a7575d85474a30cc3c | [
"super(Shuffler, self).__init__(**kwargs)\nassert isinstance(reseed, bool)\nself.reseed = reseed\nnp.random.seed(seed)",
"if self.reseed:\n np.random.seed(get_os_seed())\nshuffled_order = permutation(range(len(data_chunk)))\nfor key in data_chunk.keys():\n val = data_chunk[key]\n if isinstance(val, np.nd... | <|body_start_0|>
super(Shuffler, self).__init__(**kwargs)
assert isinstance(reseed, bool)
self.reseed = reseed
np.random.seed(seed)
<|end_body_0|>
<|body_start_1|>
if self.reseed:
np.random.seed(get_os_seed())
shuffled_order = permutation(range(len(data_chunk... | Shuffles data chunk values. Can be used to break sequential order dependency of data-units. A straightforward application of the shuffler is to shuffle large data-chunk produced by a reader and afterwards batch data units into smaller data-chunks For example, the architecture could look like this: Reader -> Shuffler ->... | Shuffler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Shuffler:
"""Shuffles data chunk values. Can be used to break sequential order dependency of data-units. A straightforward application of the shuffler is to shuffle large data-chunk produced by a reader and afterwards batch data units into smaller data-chunks For example, the architecture could l... | stack_v2_sparse_classes_75kplus_train_074058 | 1,820 | permissive | [
{
"docstring": ":param seed: initial seed. :param reseed: whether to reseed the shuffler based on OS random numbers every time transform is called. It's useful for running on multiple processes.",
"name": "__init__",
"signature": "def __init__(self, reseed=False, seed=None, **kwargs)"
},
{
"docs... | 2 | null | Implement the Python class `Shuffler` described below.
Class description:
Shuffles data chunk values. Can be used to break sequential order dependency of data-units. A straightforward application of the shuffler is to shuffle large data-chunk produced by a reader and afterwards batch data units into smaller data-chunk... | Implement the Python class `Shuffler` described below.
Class description:
Shuffles data chunk values. Can be used to break sequential order dependency of data-units. A straightforward application of the shuffler is to shuffle large data-chunk produced by a reader and afterwards batch data units into smaller data-chunk... | acc192bafc66b7661d541ef4f604b5e5ab7df5ca | <|skeleton|>
class Shuffler:
"""Shuffles data chunk values. Can be used to break sequential order dependency of data-units. A straightforward application of the shuffler is to shuffle large data-chunk produced by a reader and afterwards batch data units into smaller data-chunks For example, the architecture could l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Shuffler:
"""Shuffles data chunk values. Can be used to break sequential order dependency of data-units. A straightforward application of the shuffler is to shuffle large data-chunk produced by a reader and afterwards batch data units into smaller data-chunks For example, the architecture could look like this... | the_stack_v2_python_sparse | mldp/steps/transformers/general/shuffler.py | DanielGutmann/mltoolkit | train | 0 |
82d5c2a41a0f626df3341e8d0fa2b5d2afbc6233 | [
"for i in range(1, len(nums)):\n nums[i] = max(nums[i - 1] + nums[i], nums[i])\nreturn max(nums)",
"dp = [0] * len(nums)\ndp[0] = nums[0]\nfor i in range(1, len(nums)):\n dp[i] = max(dp[i - 1] + nums[i], nums[i])\nreturn max(dp)"
] | <|body_start_0|>
for i in range(1, len(nums)):
nums[i] = max(nums[i - 1] + nums[i], nums[i])
return max(nums)
<|end_body_0|>
<|body_start_1|>
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1, len(nums)):
dp[i] = max(dp[i - 1] + nums[i], nums[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray1(self, nums: list) -> int:
"""Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。"""
<|body_0|>
def maxSubArray2(self, nums: list) -> int:
"""动态规划"""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_074059 | 1,087 | no_license | [
{
"docstring": "Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。",
"name": "maxSubArray1",
"signature": "def maxSubArray1(self, nums: list) -> int"
},
{
"docstring": "动态规划",
"name": "maxSubArray2",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_047303 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray1(self, nums: list) -> int: Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。
- def max... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray1(self, nums: list) -> int: Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。
- def max... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def maxSubArray1(self, nums: list) -> int:
"""Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。"""
<|body_0|>
def maxSubArray2(self, nums: list) -> int:
"""动态规划"""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxSubArray1(self, nums: list) -> int:
"""Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。"""
for i in range(1, len(nums)):
nums[i] = max(nums[i - 1] + nums[i], nums[i])
return max(nu... | the_stack_v2_python_sparse | 053_maximum-subarray.py | helloocc/algorithm | train | 1 | |
d1357ffaa01016ccf6e1e2e8574ff6a4fc038bf4 | [
"self.quantiles = quantiles\nself.threshold1 = threshold1\nself.threshold2 = threshold2\nself.process_num = process_num\nself.chunk_size = chunk_size\nself.clear_cache = clear_cache\nself.column_names = list()\nself.dataset_name = ''\ncreate_cache_dirs()",
"self.dataset_name = dataset_name\nif self.clear_cache:\n... | <|body_start_0|>
self.quantiles = quantiles
self.threshold1 = threshold1
self.threshold2 = threshold2
self.process_num = process_num
self.chunk_size = chunk_size
self.clear_cache = clear_cache
self.column_names = list()
self.dataset_name = ''
creat... | A class that contains the data and methods required for the algorithms proposed in "Automatic Discovery of Attributes in Relational Databases" from M. Zhang et al. [1] Attributes ---------- threshold1: float The threshold for phase 1 threshold2: float The threshold for phase 2 quantiles: int the number of quantiles of ... | CorrelationClustering | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CorrelationClustering:
"""A class that contains the data and methods required for the algorithms proposed in "Automatic Discovery of Attributes in Relational Databases" from M. Zhang et al. [1] Attributes ---------- threshold1: float The threshold for phase 1 threshold2: float The threshold for p... | stack_v2_sparse_classes_75kplus_train_074060 | 8,109 | permissive | [
{
"docstring": "Parameters ---------- threshold1: float The threshold for phase 1 threshold2: float The threshold for phase 2 quantiles: int the number of quantiles of the histograms process_num: int The number of processes to spawn chunk_size: int, optional The size of each chunk to process clear_cache: bool, ... | 5 | stack_v2_sparse_classes_30k_train_003445 | Implement the Python class `CorrelationClustering` described below.
Class description:
A class that contains the data and methods required for the algorithms proposed in "Automatic Discovery of Attributes in Relational Databases" from M. Zhang et al. [1] Attributes ---------- threshold1: float The threshold for phase ... | Implement the Python class `CorrelationClustering` described below.
Class description:
A class that contains the data and methods required for the algorithms proposed in "Automatic Discovery of Attributes in Relational Databases" from M. Zhang et al. [1] Attributes ---------- threshold1: float The threshold for phase ... | 02dde7758076f78ff3cc4ec6da8ea755c4e00141 | <|skeleton|>
class CorrelationClustering:
"""A class that contains the data and methods required for the algorithms proposed in "Automatic Discovery of Attributes in Relational Databases" from M. Zhang et al. [1] Attributes ---------- threshold1: float The threshold for phase 1 threshold2: float The threshold for p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CorrelationClustering:
"""A class that contains the data and methods required for the algorithms proposed in "Automatic Discovery of Attributes in Relational Databases" from M. Zhang et al. [1] Attributes ---------- threshold1: float The threshold for phase 1 threshold2: float The threshold for phase 2 quanti... | the_stack_v2_python_sparse | algorithms/distribution_based/correlation_clustering.py | FChuleck/valentine | train | 0 |
9d9c376eacec86a434bafe3b5177d8117acfbadb | [
"assert owning_pipeline_reference is not None\nlong_epoch_name, short_epoch_name, global_epoch_name = owning_pipeline_reference.find_LongShortGlobal_epoch_names()\nlong_grid_bin_bounds, short_grid_bin_bounds, global_grid_bin_bounds = [owning_pipeline_reference.computation_results[a_name].computation_config['pf_para... | <|body_start_0|>
assert owning_pipeline_reference is not None
long_epoch_name, short_epoch_name, global_epoch_name = owning_pipeline_reference.find_LongShortGlobal_epoch_names()
long_grid_bin_bounds, short_grid_bin_bounds, global_grid_bin_bounds = [owning_pipeline_reference.computation_results[a... | MultiContextComparingDisplayFunctions These display functions compare results across several contexts. Must have a signature of: (owning_pipeline_reference, global_computation_results, computation_results, active_configs, ..., **kwargs) at a minimum | MultiContextComparingDisplayFunctions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiContextComparingDisplayFunctions:
"""MultiContextComparingDisplayFunctions These display functions compare results across several contexts. Must have a signature of: (owning_pipeline_reference, global_computation_results, computation_results, active_configs, ..., **kwargs) at a minimum"""
... | stack_v2_sparse_classes_75kplus_train_074061 | 22,222 | permissive | [
{
"docstring": "Renders a single figure that shows the 1D linearized position from several different sources to ensure sufficient overlap. Useful for validating that the grid_bin_bounds are chosen reasonably.",
"name": "_display_grid_bin_bounds_validation",
"signature": "def _display_grid_bin_bounds_val... | 2 | null | Implement the Python class `MultiContextComparingDisplayFunctions` described below.
Class description:
MultiContextComparingDisplayFunctions These display functions compare results across several contexts. Must have a signature of: (owning_pipeline_reference, global_computation_results, computation_results, active_con... | Implement the Python class `MultiContextComparingDisplayFunctions` described below.
Class description:
MultiContextComparingDisplayFunctions These display functions compare results across several contexts. Must have a signature of: (owning_pipeline_reference, global_computation_results, computation_results, active_con... | 212399d826284b394fce8894ff1a93133aef783f | <|skeleton|>
class MultiContextComparingDisplayFunctions:
"""MultiContextComparingDisplayFunctions These display functions compare results across several contexts. Must have a signature of: (owning_pipeline_reference, global_computation_results, computation_results, active_configs, ..., **kwargs) at a minimum"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiContextComparingDisplayFunctions:
"""MultiContextComparingDisplayFunctions These display functions compare results across several contexts. Must have a signature of: (owning_pipeline_reference, global_computation_results, computation_results, active_configs, ..., **kwargs) at a minimum"""
def _displ... | the_stack_v2_python_sparse | src/pyphoplacecellanalysis/General/Pipeline/Stages/DisplayFunctions/MultiContextComparingDisplayFunctions/MultiContextComparingDisplayFunctions.py | CommanderPho/pyPhoPlaceCellAnalysis | train | 1 |
39bbbabb2ce72434417b0f4dc82cbad7b02c1113 | [
"if fullname == _ASSOCIATED_TYPE_FULLNAME:\n return associated_type.variadic_generic\nif fullname == 'classes._typeclass.Supports':\n associated_type_node = self.lookup_fully_qualified(_ASSOCIATED_TYPE_FULLNAME)\n assert associated_type_node\n return supports.VariadicGeneric(associated_type_node)\nretur... | <|body_start_0|>
if fullname == _ASSOCIATED_TYPE_FULLNAME:
return associated_type.variadic_generic
if fullname == 'classes._typeclass.Supports':
associated_type_node = self.lookup_fully_qualified(_ASSOCIATED_TYPE_FULLNAME)
assert associated_type_node
retur... | Our plugin for typeclasses. It has four steps: - Creating typeclasses via ``typeclass`` function - Adding cases for typeclasses via ``.instance()`` calls with explicit types - Adding callbacks functions after the ``.instance()`` decorator - Converting typeclasses to simple callable via ``__call__`` method Hooks are in ... | _TypeClassPlugin | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TypeClassPlugin:
"""Our plugin for typeclasses. It has four steps: - Creating typeclasses via ``typeclass`` function - Adding cases for typeclasses via ``.instance()`` calls with explicit types - Adding callbacks functions after the ``.instance()`` decorator - Converting typeclasses to simple ca... | stack_v2_sparse_classes_75kplus_train_074062 | 3,708 | permissive | [
{
"docstring": "Hook that works on type analyzer phase.",
"name": "get_type_analyze_hook",
"signature": "def get_type_analyze_hook(self, fullname: str) -> Optional[Callable[[AnalyzeTypeContext], MypyType]]"
},
{
"docstring": "Here we adjust the typeclass constructor.",
"name": "get_function_... | 4 | null | Implement the Python class `_TypeClassPlugin` described below.
Class description:
Our plugin for typeclasses. It has four steps: - Creating typeclasses via ``typeclass`` function - Adding cases for typeclasses via ``.instance()`` calls with explicit types - Adding callbacks functions after the ``.instance()`` decorato... | Implement the Python class `_TypeClassPlugin` described below.
Class description:
Our plugin for typeclasses. It has four steps: - Creating typeclasses via ``typeclass`` function - Adding cases for typeclasses via ``.instance()`` calls with explicit types - Adding callbacks functions after the ``.instance()`` decorato... | 6f925f70285510d264a625c6afd0f26395b51475 | <|skeleton|>
class _TypeClassPlugin:
"""Our plugin for typeclasses. It has four steps: - Creating typeclasses via ``typeclass`` function - Adding cases for typeclasses via ``.instance()`` calls with explicit types - Adding callbacks functions after the ``.instance()`` decorator - Converting typeclasses to simple ca... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _TypeClassPlugin:
"""Our plugin for typeclasses. It has four steps: - Creating typeclasses via ``typeclass`` function - Adding cases for typeclasses via ``.instance()`` calls with explicit types - Adding callbacks functions after the ``.instance()`` decorator - Converting typeclasses to simple callable via ``... | the_stack_v2_python_sparse | classes/contrib/mypy/classes_plugin.py | dry-python/classes | train | 625 |
d3d0422bbd5eb2937afc6c090eab49d4c8170f69 | [
"item = super().transform_record(pid, record, links_factory=links_factory, **kwargs)\nfilter_circulation(item)\nreturn item",
"hit = super().transform_search_hit(pid, record_hit, links_factory=links_factory, **kwargs)\nfilter_circulation(hit)\nreturn hit"
] | <|body_start_0|>
item = super().transform_record(pid, record, links_factory=links_factory, **kwargs)
filter_circulation(item)
return item
<|end_body_0|>
<|body_start_1|>
hit = super().transform_search_hit(pid, record_hit, links_factory=links_factory, **kwargs)
filter_circulation... | Serialize and filter item circulation status. | ItemCSVSerializer | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemCSVSerializer:
"""Serialize and filter item circulation status."""
def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
<|body_0|>
def transform_search_hit(self, pid, record_hit, links_fact... | stack_v2_sparse_classes_75kplus_train_074063 | 2,583 | permissive | [
{
"docstring": "Transform record into an intermediate representation.",
"name": "transform_record",
"signature": "def transform_record(self, pid, record, links_factory=None, **kwargs)"
},
{
"docstring": "Transform search result hit into an intermediate representation.",
"name": "transform_se... | 2 | stack_v2_sparse_classes_30k_train_018202 | Implement the Python class `ItemCSVSerializer` described below.
Class description:
Serialize and filter item circulation status.
Method signatures and docstrings:
- def transform_record(self, pid, record, links_factory=None, **kwargs): Transform record into an intermediate representation.
- def transform_search_hit(s... | Implement the Python class `ItemCSVSerializer` described below.
Class description:
Serialize and filter item circulation status.
Method signatures and docstrings:
- def transform_record(self, pid, record, links_factory=None, **kwargs): Transform record into an intermediate representation.
- def transform_search_hit(s... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class ItemCSVSerializer:
"""Serialize and filter item circulation status."""
def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
<|body_0|>
def transform_search_hit(self, pid, record_hit, links_fact... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ItemCSVSerializer:
"""Serialize and filter item circulation status."""
def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
item = super().transform_record(pid, record, links_factory=links_factory, **kwargs)
... | the_stack_v2_python_sparse | invenio_app_ils/items/serializers/item.py | inveniosoftware/invenio-app-ils | train | 64 |
fe6f208cddc84bea8d5bca52e0bc3c6d2764cfcc | [
"tests = ['KIF.test1', 'KIF.test2']\nexpected = 'NAME:test1|test2'\nself.assertEqual(test_runner.get_kif_test_filter(tests), expected)",
"tests = ['KIF.test1', 'KIF.test2']\nexpected = '-NAME:test1|test2'\nself.assertEqual(test_runner.get_kif_test_filter(tests, invert=True), expected)"
] | <|body_start_0|>
tests = ['KIF.test1', 'KIF.test2']
expected = 'NAME:test1|test2'
self.assertEqual(test_runner.get_kif_test_filter(tests), expected)
<|end_body_0|>
<|body_start_1|>
tests = ['KIF.test1', 'KIF.test2']
expected = '-NAME:test1|test2'
self.assertEqual(test_ru... | Tests for test_runner.get_kif_test_filter. | GetKIFTestFilterTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetKIFTestFilterTest:
"""Tests for test_runner.get_kif_test_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
<|body_0|>
def test_correct_inverted(self):
"""Ensures correctness of inverted filter."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_074064 | 19,298 | permissive | [
{
"docstring": "Ensures correctness of filter.",
"name": "test_correct",
"signature": "def test_correct(self)"
},
{
"docstring": "Ensures correctness of inverted filter.",
"name": "test_correct_inverted",
"signature": "def test_correct_inverted(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026342 | Implement the Python class `GetKIFTestFilterTest` described below.
Class description:
Tests for test_runner.get_kif_test_filter.
Method signatures and docstrings:
- def test_correct(self): Ensures correctness of filter.
- def test_correct_inverted(self): Ensures correctness of inverted filter. | Implement the Python class `GetKIFTestFilterTest` described below.
Class description:
Tests for test_runner.get_kif_test_filter.
Method signatures and docstrings:
- def test_correct(self): Ensures correctness of filter.
- def test_correct_inverted(self): Ensures correctness of inverted filter.
<|skeleton|>
class Get... | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | <|skeleton|>
class GetKIFTestFilterTest:
"""Tests for test_runner.get_kif_test_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
<|body_0|>
def test_correct_inverted(self):
"""Ensures correctness of inverted filter."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetKIFTestFilterTest:
"""Tests for test_runner.get_kif_test_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
tests = ['KIF.test1', 'KIF.test2']
expected = 'NAME:test1|test2'
self.assertEqual(test_runner.get_kif_test_filter(tests), expected)
def ... | the_stack_v2_python_sparse | ios/build/bots/scripts/test_runner_test.py | Samsung/Castanets | train | 58 |
a4a8eff88cca940af60e459f2fcd1b5fad2ada5d | [
"self.file_extensions_list = file_extensions_list\nself.is_enabled = is_enabled\nself.mode = mode",
"if dictionary is None:\n return None\nfile_extensions_list = dictionary.get('fileExtensionsList')\nis_enabled = dictionary.get('isEnabled')\nmode = dictionary.get('mode')\nreturn cls(file_extensions_list, is_en... | <|body_start_0|>
self.file_extensions_list = file_extensions_list
self.is_enabled = is_enabled
self.mode = mode
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
file_extensions_list = dictionary.get('fileExtensionsList')
is_enabled = diction... | Implementation of the 'FileExtensionFilter' model. TODO: type description here. Attributes: file_extensions_list (list of string): The list of file extensions to apply is_enabled (bool): If set, it enables the file extension filter mode (ModeFileExtensionFilterEnum): The mode applied to the list of file extensions 'kWh... | FileExtensionFilter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileExtensionFilter:
"""Implementation of the 'FileExtensionFilter' model. TODO: type description here. Attributes: file_extensions_list (list of string): The list of file extensions to apply is_enabled (bool): If set, it enables the file extension filter mode (ModeFileExtensionFilterEnum): The m... | stack_v2_sparse_classes_75kplus_train_074065 | 2,043 | permissive | [
{
"docstring": "Constructor for the FileExtensionFilter class",
"name": "__init__",
"signature": "def __init__(self, file_extensions_list=None, is_enabled=None, mode=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary represen... | 2 | stack_v2_sparse_classes_30k_train_015907 | Implement the Python class `FileExtensionFilter` described below.
Class description:
Implementation of the 'FileExtensionFilter' model. TODO: type description here. Attributes: file_extensions_list (list of string): The list of file extensions to apply is_enabled (bool): If set, it enables the file extension filter mo... | Implement the Python class `FileExtensionFilter` described below.
Class description:
Implementation of the 'FileExtensionFilter' model. TODO: type description here. Attributes: file_extensions_list (list of string): The list of file extensions to apply is_enabled (bool): If set, it enables the file extension filter mo... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class FileExtensionFilter:
"""Implementation of the 'FileExtensionFilter' model. TODO: type description here. Attributes: file_extensions_list (list of string): The list of file extensions to apply is_enabled (bool): If set, it enables the file extension filter mode (ModeFileExtensionFilterEnum): The m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileExtensionFilter:
"""Implementation of the 'FileExtensionFilter' model. TODO: type description here. Attributes: file_extensions_list (list of string): The list of file extensions to apply is_enabled (bool): If set, it enables the file extension filter mode (ModeFileExtensionFilterEnum): The mode applied t... | the_stack_v2_python_sparse | cohesity_management_sdk/models/file_extension_filter.py | cohesity/management-sdk-python | train | 24 |
d020b4ba0f5d54bcc91221ef2c1503192c9c019c | [
"if not isinstance(expr, (str, list, int)):\n raise TypeError('expr must be a string, int or a list of string, int.'.format(expr))\nself.expr = expr\nself.to = to\nself.container = cont",
"if id(self.container) != id(col2.container):\n raise RuntimeError('Only one container is allowed.')\nif self.to is not ... | <|body_start_0|>
if not isinstance(expr, (str, list, int)):
raise TypeError('expr must be a string, int or a list of string, int.'.format(expr))
self.expr = expr
self.to = to
self.container = cont
<|end_body_0|>
<|body_start_1|>
if id(self.container) != id(col2.conta... | Column selector. | COL | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class COL:
"""Column selector."""
def __init__(self, expr, to=None, cont=None):
""":param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists), if not specified (None), the container is assumed to be ... | stack_v2_sparse_classes_75kplus_train_074066 | 35,835 | permissive | [
{
"docstring": ":param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists), if not specified (None), the container is assumed to be the previous transform in the pipeline",
"name": "__init__",
"signature": "def __... | 4 | stack_v2_sparse_classes_30k_train_029391 | Implement the Python class `COL` described below.
Class description:
Column selector.
Method signatures and docstrings:
- def __init__(self, expr, to=None, cont=None): :param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists),... | Implement the Python class `COL` described below.
Class description:
Column selector.
Method signatures and docstrings:
- def __init__(self, expr, to=None, cont=None): :param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists),... | b5f1c2e3422fadc81e21337bcddb7372682dd455 | <|skeleton|>
class COL:
"""Column selector."""
def __init__(self, expr, to=None, cont=None):
""":param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists), if not specified (None), the container is assumed to be ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class COL:
"""Column selector."""
def __init__(self, expr, to=None, cont=None):
""":param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists), if not specified (None), the container is assumed to be the previous ... | the_stack_v2_python_sparse | src/python/nimbusml/internal/utils/data_schema.py | zyw400/NimbusML-1 | train | 3 |
d2768f017b75ced09a939903a26908caf549ad11 | [
"self.img_size = img_size\nif data is not None:\n data = np.atleast_2d(data)\n self.mean = data.mean(axis=0)\n self.std = data.std(axis=0)\n self.nobservations = data.shape[0]\n self.ndimensions = data.shape[1]\nelse:\n self.nobservations = 0",
"data = transform.resize(io.imread(img_path), (self... | <|body_start_0|>
self.img_size = img_size
if data is not None:
data = np.atleast_2d(data)
self.mean = data.mean(axis=0)
self.std = data.std(axis=0)
self.nobservations = data.shape[0]
self.ndimensions = data.shape[1]
else:
se... | Class that performs per-channel (RGB) mean and stdev calculation. Computation is done online, one image at a time, thus memory efficient to compute RGB means/stdev for an entire dataset such as MSCOCO. | StatsRecorder | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatsRecorder:
"""Class that performs per-channel (RGB) mean and stdev calculation. Computation is done online, one image at a time, thus memory efficient to compute RGB means/stdev for an entire dataset such as MSCOCO."""
def __init__(self, data=None, img_size=512):
"""data: ndarray... | stack_v2_sparse_classes_75kplus_train_074067 | 13,290 | permissive | [
{
"docstring": "data: ndarray, shape (nobservations, ndimensions)",
"name": "__init__",
"signature": "def __init__(self, data=None, img_size=512)"
},
{
"docstring": "data: ndarray, shape (nobservations, ndimensions)",
"name": "update",
"signature": "def update(self, img_path)"
}
] | 2 | null | Implement the Python class `StatsRecorder` described below.
Class description:
Class that performs per-channel (RGB) mean and stdev calculation. Computation is done online, one image at a time, thus memory efficient to compute RGB means/stdev for an entire dataset such as MSCOCO.
Method signatures and docstrings:
- d... | Implement the Python class `StatsRecorder` described below.
Class description:
Class that performs per-channel (RGB) mean and stdev calculation. Computation is done online, one image at a time, thus memory efficient to compute RGB means/stdev for an entire dataset such as MSCOCO.
Method signatures and docstrings:
- d... | fd20debf7612656d615c6775b6a909a86665976b | <|skeleton|>
class StatsRecorder:
"""Class that performs per-channel (RGB) mean and stdev calculation. Computation is done online, one image at a time, thus memory efficient to compute RGB means/stdev for an entire dataset such as MSCOCO."""
def __init__(self, data=None, img_size=512):
"""data: ndarray... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StatsRecorder:
"""Class that performs per-channel (RGB) mean and stdev calculation. Computation is done online, one image at a time, thus memory efficient to compute RGB means/stdev for an entire dataset such as MSCOCO."""
def __init__(self, data=None, img_size=512):
"""data: ndarray, shape (nobs... | the_stack_v2_python_sparse | centernet-master/src/tools/calc_eig.py | rsl18/294-82 | train | 1 |
977bd45708752a474a3ea77af47bdfcd0af8c460 | [
"from collections import defaultdict\nself.loc = defaultdict(list)\nfor idx, word in enumerate(words):\n self.loc[word].append(idx)",
"loc1 = self.loc[word1]\nloc2 = self.loc[word2]\nl1, l2 = (0, 0)\nmin_diff = float('inf')\nwhile l1 < len(loc1) and l2 < len(loc2):\n min_diff = min(min_diff, abs(loc1[l1] - ... | <|body_start_0|>
from collections import defaultdict
self.loc = defaultdict(list)
for idx, word in enumerate(words):
self.loc[word].append(idx)
<|end_body_0|>
<|body_start_1|>
loc1 = self.loc[word1]
loc2 = self.loc[word2]
l1, l2 = (0, 0)
min_diff = fl... | WordDistance_II | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance_II:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from collections import defaultdic... | stack_v2_sparse_classes_75kplus_train_074068 | 3,430 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047381 | Implement the Python class `WordDistance_II` described below.
Class description:
Implement the WordDistance_II class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance_II` described below.
Class description:
Implement the WordDistance_II class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance... | 86d97d4dccf628e95c4bb9cdce9dab0a1e9fdffd | <|skeleton|>
class WordDistance_II:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordDistance_II:
def __init__(self, words):
""":type words: List[str]"""
from collections import defaultdict
self.loc = defaultdict(list)
for idx, word in enumerate(words):
self.loc[word].append(idx)
def shortest(self, word1, word2):
""":type word1: str... | the_stack_v2_python_sparse | algo/array/shortest-word-distance.py | GreenMarch/datasciencecoursera | train | 0 | |
d834640f05fce79682538d143639c783972b6f2b | [
"if set(s) & set(''.join(wordDict)) != set(s):\n return (False, {})\ndic_head, table, max_len = ({}, [0] * len(s) + [1], max(map(len, wordDict)))\nfor word in wordDict:\n if word[0] not in dic_head:\n dic_head[word[0]] = set([word])\n else:\n dic_head[word[0]].add(word)\nfor i in range(len(s)... | <|body_start_0|>
if set(s) & set(''.join(wordDict)) != set(s):
return (False, {})
dic_head, table, max_len = ({}, [0] * len(s) + [1], max(map(len, wordDict)))
for word in wordDict:
if word[0] not in dic_head:
dic_head[word[0]] = set([word])
els... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_074069 | 1,679 | no_license | [
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak1",
"signature": "def wordBreak1(self, s, wordDict)"
},
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: List[str]",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
... | 2 | stack_v2_sparse_classes_30k_train_022818 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: List[str... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: List[str... | c767e3794455c5105ca34714a3e15101f4962f4d | <|skeleton|>
class Solution:
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
if set(s) & set(''.join(wordDict)) != set(s):
return (False, {})
dic_head, table, max_len = ({}, [0] * len(s) + [1], max(map(len, wordDict)))
for word in wordDict:... | the_stack_v2_python_sparse | 140/WordBreakII.py | basto11/leetcode | train | 0 | |
7e033b92b0ca78a2ee2d82ba2c386e183281c9c0 | [
"self.reShouldIgnore = []\nfor expr in self.pathShouldIgnore:\n self.reShouldIgnore.append(re.compile(expr))",
"for expr in self.reShouldIgnore:\n if expr.search(dirname) is not None:\n return True\n if expr.search(filename) is not None:\n return True\nreturn False"
] | <|body_start_0|>
self.reShouldIgnore = []
for expr in self.pathShouldIgnore:
self.reShouldIgnore.append(re.compile(expr))
<|end_body_0|>
<|body_start_1|>
for expr in self.reShouldIgnore:
if expr.search(dirname) is not None:
return True
if expr... | this class represents a static "ignore" list of regexes, to be matched against directory and file names | IgnoreList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IgnoreList:
"""this class represents a static "ignore" list of regexes, to be matched against directory and file names"""
def __init__(self):
"""initialise the class by compiling the above list :return: None"""
<|body_0|>
def should_ignore(self, dirname, filename):
... | stack_v2_sparse_classes_75kplus_train_074070 | 1,822 | no_license | [
{
"docstring": "initialise the class by compiling the above list :return: None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Check the given path to see if either the directory name or the file name match :param dirname: directory name portion of the path :param file... | 2 | stack_v2_sparse_classes_30k_train_020644 | Implement the Python class `IgnoreList` described below.
Class description:
this class represents a static "ignore" list of regexes, to be matched against directory and file names
Method signatures and docstrings:
- def __init__(self): initialise the class by compiling the above list :return: None
- def should_ignore... | Implement the Python class `IgnoreList` described below.
Class description:
this class represents a static "ignore" list of regexes, to be matched against directory and file names
Method signatures and docstrings:
- def __init__(self): initialise the class by compiling the above list :return: None
- def should_ignore... | f17f918e63e02aa7efaadbe5efe6d4d224b5a425 | <|skeleton|>
class IgnoreList:
"""this class represents a static "ignore" list of regexes, to be matched against directory and file names"""
def __init__(self):
"""initialise the class by compiling the above list :return: None"""
<|body_0|>
def should_ignore(self, dirname, filename):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IgnoreList:
"""this class represents a static "ignore" list of regexes, to be matched against directory and file names"""
def __init__(self):
"""initialise the class by compiling the above list :return: None"""
self.reShouldIgnore = []
for expr in self.pathShouldIgnore:
... | the_stack_v2_python_sparse | src/asset_folder_importer/asset_folder_sweeper/ignore_list.py | guardian/assetsweeper | train | 2 |
99beadadea8a91626f6eff63d3b531a93dc7805d | [
"if root is None:\n return ''\nstack = [root]\nvalues = []\nwhile stack:\n node = stack.pop()\n if node is not None:\n values.append(str(node.val))\n stack.extend([node.right, node.left])\n else:\n values.append('null')\nwhile values[-1] == 'null':\n values.pop()\nreturn ','.join... | <|body_start_0|>
if root is None:
return ''
stack = [root]
values = []
while stack:
node = stack.pop()
if node is not None:
values.append(str(node.val))
stack.extend([node.right, node.left])
else:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_074071 | 2,218 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_039315 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 9687f8e743a8b6396fff192f22b5256d1025f86b | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root is None:
return ''
stack = [root]
values = []
while stack:
node = stack.pop()
if node is not None:
val... | the_stack_v2_python_sparse | 2021/37-xu-lie-hua-er-cha-shu-lcof.py | buhuipao/LeetCode | train | 5 | |
f957b4215e8463bda8e33cdffc3a250783e48b58 | [
"super(Conv_TasNet, self).__init__()\nself.n_sources = n_sources\nself.encoder_dim = encoder_dim\nself.feature_dim = feature_dim\nself.sr = sr\nself.win_length = win_length\nself.win_size = int(sr * win_length / 1000)\nself.stride = self.win_size // 2\nself.layers = layers\nself.stack = stack\nself.kernel = kernel\... | <|body_start_0|>
super(Conv_TasNet, self).__init__()
self.n_sources = n_sources
self.encoder_dim = encoder_dim
self.feature_dim = feature_dim
self.sr = sr
self.win_length = win_length
self.win_size = int(sr * win_length / 1000)
self.stride = self.win_size ... | Conv-TasNet Model Conv-TasNet Model for Waveform Source Separation (SS): - https://arxiv.org/pdf/1809.07454.pdf Attributes: n_sources {int} -- number of sources to seperate encoder_dim {int} -- encoder dimension feature_dim {int} -- feature dimension sr {int} -- sample rate win_length {float} -- window lenght in second... | Conv_TasNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv_TasNet:
"""Conv-TasNet Model Conv-TasNet Model for Waveform Source Separation (SS): - https://arxiv.org/pdf/1809.07454.pdf Attributes: n_sources {int} -- number of sources to seperate encoder_dim {int} -- encoder dimension feature_dim {int} -- feature dimension sr {int} -- sample rate win_le... | stack_v2_sparse_classes_75kplus_train_074072 | 7,327 | permissive | [
{
"docstring": "Initialization Keyword Arguments: encoder_dim {int} -- encoder dimension (default: {512}) feature_dim {int} -- feature dimension (default: {128}) sr {int} -- sample rate (default: {16000}) win_length {int} -- window length in seconds (default: {2}) layers {int} -- number of layers for ach block ... | 5 | stack_v2_sparse_classes_30k_train_038058 | Implement the Python class `Conv_TasNet` described below.
Class description:
Conv-TasNet Model Conv-TasNet Model for Waveform Source Separation (SS): - https://arxiv.org/pdf/1809.07454.pdf Attributes: n_sources {int} -- number of sources to seperate encoder_dim {int} -- encoder dimension feature_dim {int} -- feature d... | Implement the Python class `Conv_TasNet` described below.
Class description:
Conv-TasNet Model Conv-TasNet Model for Waveform Source Separation (SS): - https://arxiv.org/pdf/1809.07454.pdf Attributes: n_sources {int} -- number of sources to seperate encoder_dim {int} -- encoder dimension feature_dim {int} -- feature d... | 2415502fa8a38d4624b1c71e926f1723bdc8535c | <|skeleton|>
class Conv_TasNet:
"""Conv-TasNet Model Conv-TasNet Model for Waveform Source Separation (SS): - https://arxiv.org/pdf/1809.07454.pdf Attributes: n_sources {int} -- number of sources to seperate encoder_dim {int} -- encoder dimension feature_dim {int} -- feature dimension sr {int} -- sample rate win_le... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Conv_TasNet:
"""Conv-TasNet Model Conv-TasNet Model for Waveform Source Separation (SS): - https://arxiv.org/pdf/1809.07454.pdf Attributes: n_sources {int} -- number of sources to seperate encoder_dim {int} -- encoder dimension feature_dim {int} -- feature dimension sr {int} -- sample rate win_length {float} ... | the_stack_v2_python_sparse | SPK_SP_Master/wass/convtasnet/model.py | adamwhitakerwilson/speaker_separation | train | 0 |
3604b9e4fba0a9ab1d6fb2aff670ce0afeb7957f | [
"super().__init__()\nself.app = app\nself.jobs = self.db.query(JobEntity.job_id, JobEntity.status).filter(JobEntity.app_id == self.app.app_id).all()",
"all_jobs_count = len(self.jobs)\nif all_jobs_count == 0:\n return EmptyMetric(severity=Severity.NONE)\nfailed_jobs = [j for j in self.jobs if j.status in ['FAI... | <|body_start_0|>
super().__init__()
self.app = app
self.jobs = self.db.query(JobEntity.job_id, JobEntity.status).filter(JobEntity.app_id == self.app.app_id).all()
<|end_body_0|>
<|body_start_1|>
all_jobs_count = len(self.jobs)
if all_jobs_count == 0:
return EmptyMetr... | Class for analyzing jobs. | JobAnalyzer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobAnalyzer:
"""Class for analyzing jobs."""
def __init__(self, app):
"""Create the JobAnalyzer object :param app: Application object"""
<|body_0|>
def analyze_failed_jobs(self):
"""Analyze the Jobs of the defined apps and return the metric details :param app: Ap... | stack_v2_sparse_classes_75kplus_train_074073 | 1,745 | permissive | [
{
"docstring": "Create the JobAnalyzer object :param app: Application object",
"name": "__init__",
"signature": "def __init__(self, app)"
},
{
"docstring": "Analyze the Jobs of the defined apps and return the metric details :param app: Application object :return: Metric details",
"name": "an... | 2 | null | Implement the Python class `JobAnalyzer` described below.
Class description:
Class for analyzing jobs.
Method signatures and docstrings:
- def __init__(self, app): Create the JobAnalyzer object :param app: Application object
- def analyze_failed_jobs(self): Analyze the Jobs of the defined apps and return the metric d... | Implement the Python class `JobAnalyzer` described below.
Class description:
Class for analyzing jobs.
Method signatures and docstrings:
- def __init__(self, app): Create the JobAnalyzer object :param app: Application object
- def analyze_failed_jobs(self): Analyze the Jobs of the defined apps and return the metric d... | 53c33d1a889258a624645c5e9cb2343495f018a2 | <|skeleton|>
class JobAnalyzer:
"""Class for analyzing jobs."""
def __init__(self, app):
"""Create the JobAnalyzer object :param app: Application object"""
<|body_0|>
def analyze_failed_jobs(self):
"""Analyze the Jobs of the defined apps and return the metric details :param app: Ap... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobAnalyzer:
"""Class for analyzing jobs."""
def __init__(self, app):
"""Create the JobAnalyzer object :param app: Application object"""
super().__init__()
self.app = app
self.jobs = self.db.query(JobEntity.job_id, JobEntity.status).filter(JobEntity.app_id == self.app.app_... | the_stack_v2_python_sparse | sparkscope_web/analyzers/job_analyzer.py | stovicekjan/sparkscope | train | 1 |
16956b9bdbf64fb133ad83eceb86650249c2e027 | [
"super(BasicHyVs, self).__init__(input_file=input_file, params=params, BaselevelHandlerClass=BaselevelHandlerClass)\nself.K_sp = self.get_parameter_from_exponent('K_sp')\nlinear_diffusivity = self._length_factor ** 2 * self.get_parameter_from_exponent('linear_diffusivity')\nrecharge_rate = self._length_factor * sel... | <|body_start_0|>
super(BasicHyVs, self).__init__(input_file=input_file, params=params, BaselevelHandlerClass=BaselevelHandlerClass)
self.K_sp = self.get_parameter_from_exponent('K_sp')
linear_diffusivity = self._length_factor ** 2 * self.get_parameter_from_exponent('linear_diffusivity')
... | A BasicHyVs computes erosion using linear diffusion, hybrid alluvium fluvial erosion, and Q ~ A exp( -b S / A). "VSA" stands for "variable source area". | BasicHyVs | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicHyVs:
"""A BasicHyVs computes erosion using linear diffusion, hybrid alluvium fluvial erosion, and Q ~ A exp( -b S / A). "VSA" stands for "variable source area"."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the BasicHyVs."""
... | stack_v2_sparse_classes_75kplus_train_074074 | 5,887 | permissive | [
{
"docstring": "Initialize the BasicHyVs.",
"name": "__init__",
"signature": "def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None)"
},
{
"docstring": "Calculate and store effective drainage area. Effective drainage area is defined as: $A_{eff} = A \\\\exp ( \u0007lpha S /... | 3 | null | Implement the Python class `BasicHyVs` described below.
Class description:
A BasicHyVs computes erosion using linear diffusion, hybrid alluvium fluvial erosion, and Q ~ A exp( -b S / A). "VSA" stands for "variable source area".
Method signatures and docstrings:
- def __init__(self, input_file=None, params=None, Basel... | Implement the Python class `BasicHyVs` described below.
Class description:
A BasicHyVs computes erosion using linear diffusion, hybrid alluvium fluvial erosion, and Q ~ A exp( -b S / A). "VSA" stands for "variable source area".
Method signatures and docstrings:
- def __init__(self, input_file=None, params=None, Basel... | 1b756477b8a8ab6a8f1275b1b30ec84855c840ea | <|skeleton|>
class BasicHyVs:
"""A BasicHyVs computes erosion using linear diffusion, hybrid alluvium fluvial erosion, and Q ~ A exp( -b S / A). "VSA" stands for "variable source area"."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the BasicHyVs."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicHyVs:
"""A BasicHyVs computes erosion using linear diffusion, hybrid alluvium fluvial erosion, and Q ~ A exp( -b S / A). "VSA" stands for "variable source area"."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the BasicHyVs."""
super(Bas... | the_stack_v2_python_sparse | terrainbento/derived_models/model_210_basicHyVs/model_210_basicHyVs.py | mcflugen/terrainbento | train | 0 |
88d76a539b2cd4ad58c9520517732161b909e668 | [
"if uri == DOMAIN_UNIPROT:\n return KeywordType.DOMAIN\nelif uri == BIOLOGICAL_PROCESS_UNIPROT:\n return KeywordType.BIOLOGICAL_PROCESS\nelif uri == CELLULAR_COMPONENT_UNIPROT:\n return KeywordType.CELLULAR_COMPONENT\nelif uri == CODING_SEQUENCE_DIVERSITY_UNIPROT:\n return KeywordType.CODING_SEQUENCE_DI... | <|body_start_0|>
if uri == DOMAIN_UNIPROT:
return KeywordType.DOMAIN
elif uri == BIOLOGICAL_PROCESS_UNIPROT:
return KeywordType.BIOLOGICAL_PROCESS
elif uri == CELLULAR_COMPONENT_UNIPROT:
return KeywordType.CELLULAR_COMPONENT
elif uri == CODING_SEQUENCE... | Enum specifying the category of a Keyword. | KeywordType | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeywordType:
"""Enum specifying the category of a Keyword."""
def from_uniprot_uri(uri: str):
"""Helper function that returns a `KeywordType` (Keyword Category) from the UniProt URL."""
<|body_0|>
def from_obo_ns(obo_namespace: str):
"""Helper function that retur... | stack_v2_sparse_classes_75kplus_train_074075 | 5,246 | permissive | [
{
"docstring": "Helper function that returns a `KeywordType` (Keyword Category) from the UniProt URL.",
"name": "from_uniprot_uri",
"signature": "def from_uniprot_uri(uri: str)"
},
{
"docstring": "Helper function that returns a `KeywordType` (Keyword Category) from the Ontobee URL.",
"name":... | 2 | stack_v2_sparse_classes_30k_train_008511 | Implement the Python class `KeywordType` described below.
Class description:
Enum specifying the category of a Keyword.
Method signatures and docstrings:
- def from_uniprot_uri(uri: str): Helper function that returns a `KeywordType` (Keyword Category) from the UniProt URL.
- def from_obo_ns(obo_namespace: str): Helpe... | Implement the Python class `KeywordType` described below.
Class description:
Enum specifying the category of a Keyword.
Method signatures and docstrings:
- def from_uniprot_uri(uri: str): Helper function that returns a `KeywordType` (Keyword Category) from the UniProt URL.
- def from_obo_ns(obo_namespace: str): Helpe... | 40bab526af6562653c42dbb32b174524c44ce2ba | <|skeleton|>
class KeywordType:
"""Enum specifying the category of a Keyword."""
def from_uniprot_uri(uri: str):
"""Helper function that returns a `KeywordType` (Keyword Category) from the UniProt URL."""
<|body_0|>
def from_obo_ns(obo_namespace: str):
"""Helper function that retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeywordType:
"""Enum specifying the category of a Keyword."""
def from_uniprot_uri(uri: str):
"""Helper function that returns a `KeywordType` (Keyword Category) from the UniProt URL."""
if uri == DOMAIN_UNIPROT:
return KeywordType.DOMAIN
elif uri == BIOLOGICAL_PROCESS_... | the_stack_v2_python_sparse | PyStationB/libraries/UniProt/uniProt/keyword.py | mebristo/station-b-libraries | train | 0 |
1892e8e4307f9644d16ba1dfbd29c34ba585a73b | [
"super().__init__()\nself.mode = mode\nself.weight = weight\nself.uncertainty = UncertaintyLoss()\nself.dicebce = DiceBCELoss()",
"if y.shape[1] < x.shape[1]:\n dim = len(y.shape[2:])\n y = y.repeat([1, x.shape[1]] + [1] * dim)\nloss, dice, bce = self.dicebce(x, y)\nif self.mode == 'dicebce':\n return (l... | <|body_start_0|>
super().__init__()
self.mode = mode
self.weight = weight
self.uncertainty = UncertaintyLoss()
self.dicebce = DiceBCELoss()
<|end_body_0|>
<|body_start_1|>
if y.shape[1] < x.shape[1]:
dim = len(y.shape[2:])
y = y.repeat([1, x.shape... | AllLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllLoss:
def __init__(self, mode=None, weight=1):
"""mode: 'dicebce' or 'uncertainty' pos_weight:"""
<|body_0|>
def forward(self, x, y):
"""x: (batch, 1, h, w, d) or (batch, n, h, w, d) after sigmoid y: (batch, 1, h, w, d) or (batch, n, h, w, d)"""
<|body_1|>... | stack_v2_sparse_classes_75kplus_train_074076 | 1,408 | no_license | [
{
"docstring": "mode: 'dicebce' or 'uncertainty' pos_weight:",
"name": "__init__",
"signature": "def __init__(self, mode=None, weight=1)"
},
{
"docstring": "x: (batch, 1, h, w, d) or (batch, n, h, w, d) after sigmoid y: (batch, 1, h, w, d) or (batch, n, h, w, d)",
"name": "forward",
"sig... | 2 | stack_v2_sparse_classes_30k_train_045537 | Implement the Python class `AllLoss` described below.
Class description:
Implement the AllLoss class.
Method signatures and docstrings:
- def __init__(self, mode=None, weight=1): mode: 'dicebce' or 'uncertainty' pos_weight:
- def forward(self, x, y): x: (batch, 1, h, w, d) or (batch, n, h, w, d) after sigmoid y: (bat... | Implement the Python class `AllLoss` described below.
Class description:
Implement the AllLoss class.
Method signatures and docstrings:
- def __init__(self, mode=None, weight=1): mode: 'dicebce' or 'uncertainty' pos_weight:
- def forward(self, x, y): x: (batch, 1, h, w, d) or (batch, n, h, w, d) after sigmoid y: (bat... | 162fa3bfee3c31c1e1c6e3f0ab77397791e0f6a0 | <|skeleton|>
class AllLoss:
def __init__(self, mode=None, weight=1):
"""mode: 'dicebce' or 'uncertainty' pos_weight:"""
<|body_0|>
def forward(self, x, y):
"""x: (batch, 1, h, w, d) or (batch, n, h, w, d) after sigmoid y: (batch, 1, h, w, d) or (batch, n, h, w, d)"""
<|body_1|>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AllLoss:
def __init__(self, mode=None, weight=1):
"""mode: 'dicebce' or 'uncertainty' pos_weight:"""
super().__init__()
self.mode = mode
self.weight = weight
self.uncertainty = UncertaintyLoss()
self.dicebce = DiceBCELoss()
def forward(self, x, y):
... | the_stack_v2_python_sparse | Utils/UncertaintyLoss.py | yuruiqi/MCMD | train | 0 | |
ecfa48899df6ed01dd23b357346161becb632582 | [
"from .. import command\ncmd = command.ZCLCommand()\ncmd.one_byte = value\nreturn cmd",
"from .. import command\ncmd = command.ZCLCommand()\ncmd.low_byte = value & 255\ncmd.high_byte = value >> 8 & 255\nreturn cmd"
] | <|body_start_0|>
from .. import command
cmd = command.ZCLCommand()
cmd.one_byte = value
return cmd
<|end_body_0|>
<|body_start_1|>
from .. import command
cmd = command.ZCLCommand()
cmd.low_byte = value & 255
cmd.high_byte = value >> 8 & 255
return... | Command generator base class | CommandGen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandGen:
"""Command generator base class"""
def one_byte(self, value):
"""One byte command"""
<|body_0|>
def two_byte(self, value):
"""Two byte command"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from .. import command
cmd = comma... | stack_v2_sparse_classes_75kplus_train_074077 | 9,321 | no_license | [
{
"docstring": "One byte command",
"name": "one_byte",
"signature": "def one_byte(self, value)"
},
{
"docstring": "Two byte command",
"name": "two_byte",
"signature": "def two_byte(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041889 | Implement the Python class `CommandGen` described below.
Class description:
Command generator base class
Method signatures and docstrings:
- def one_byte(self, value): One byte command
- def two_byte(self, value): Two byte command | Implement the Python class `CommandGen` described below.
Class description:
Command generator base class
Method signatures and docstrings:
- def one_byte(self, value): One byte command
- def two_byte(self, value): Two byte command
<|skeleton|>
class CommandGen:
"""Command generator base class"""
def one_byt... | fff610a7d045a9611f07e7c46888b4fab5bca1f5 | <|skeleton|>
class CommandGen:
"""Command generator base class"""
def one_byte(self, value):
"""One byte command"""
<|body_0|>
def two_byte(self, value):
"""Two byte command"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommandGen:
"""Command generator base class"""
def one_byte(self, value):
"""One byte command"""
from .. import command
cmd = command.ZCLCommand()
cmd.one_byte = value
return cmd
def two_byte(self, value):
"""Two byte command"""
from .. import ... | the_stack_v2_python_sparse | sf/protocol/zigbee/zcl/base.py | stevenylai/pysf | train | 0 |
0ab76fa30a1b7b8ce7892e7c932e823dc5e94d85 | [
"WindowsBalloonTip._lock.acquire()\nval = WindowsBalloonTip._count\nWindowsBalloonTip._count += 1\nWindowsBalloonTip._lock.release()\nreturn val",
"atexit.register(self.__del__)\nwnd_class_ex = win_api_defs.get_WNDCLASSEXW()\nclass_name = 'PlyerTaskbar' + str(WindowsBalloonTip._get_unique_id())\nwnd_class_ex.lpsz... | <|body_start_0|>
WindowsBalloonTip._lock.acquire()
val = WindowsBalloonTip._count
WindowsBalloonTip._count += 1
WindowsBalloonTip._lock.release()
return val
<|end_body_0|>
<|body_start_1|>
atexit.register(self.__del__)
wnd_class_ex = win_api_defs.get_WNDCLASSEXW(... | Implementation of balloon tip notifications through Windows API. * Register Window class name: https://msdn.microsoft.com/en-us/library/windows/desktop/ms632596.aspx * Create an overlapped window using the registered class. - It's hidden everywhere in GUI unless ShowWindow(handle, SW_SHOW) function is called. * Show/re... | WindowsBalloonTip | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindowsBalloonTip:
"""Implementation of balloon tip notifications through Windows API. * Register Window class name: https://msdn.microsoft.com/en-us/library/windows/desktop/ms632596.aspx * Create an overlapped window using the registered class. - It's hidden everywhere in GUI unless ShowWindow(h... | stack_v2_sparse_classes_75kplus_train_074078 | 6,418 | permissive | [
{
"docstring": "Keep track of each created balloon tip notification names, so that they can be easily identified even from outside. Make sure the count is shared between all the instances i.e. use a lock, so that _count class variable is incremented safely when using balloon tip notifications with Threads.",
... | 5 | stack_v2_sparse_classes_30k_train_011506 | Implement the Python class `WindowsBalloonTip` described below.
Class description:
Implementation of balloon tip notifications through Windows API. * Register Window class name: https://msdn.microsoft.com/en-us/library/windows/desktop/ms632596.aspx * Create an overlapped window using the registered class. - It's hidde... | Implement the Python class `WindowsBalloonTip` described below.
Class description:
Implementation of balloon tip notifications through Windows API. * Register Window class name: https://msdn.microsoft.com/en-us/library/windows/desktop/ms632596.aspx * Create an overlapped window using the registered class. - It's hidde... | d8a2b3d16b12fc54667744a092a453ad007c9448 | <|skeleton|>
class WindowsBalloonTip:
"""Implementation of balloon tip notifications through Windows API. * Register Window class name: https://msdn.microsoft.com/en-us/library/windows/desktop/ms632596.aspx * Create an overlapped window using the registered class. - It's hidden everywhere in GUI unless ShowWindow(h... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WindowsBalloonTip:
"""Implementation of balloon tip notifications through Windows API. * Register Window class name: https://msdn.microsoft.com/en-us/library/windows/desktop/ms632596.aspx * Create an overlapped window using the registered class. - It's hidden everywhere in GUI unless ShowWindow(handle, SW_SHO... | the_stack_v2_python_sparse | plyer/platforms/win/libs/balloontip.py | kivy/plyer | train | 1,516 |
a19d171fcb14165b60561856997c16a57ca28b2d | [
"ts_start, ts_end, src_ip, src_port, dst_ip, dst_port, data_c2s, data_s2c = data_tuple\nself.data_tuple = data_tuple\nself.ts_start = ts_start\nself.ts_end = ts_end\nself.src_ip = src_ip\nself.src_port = src_port\nself.dst_ip = dst_ip\nself.dst_port = dst_port\nself.data_c2s = data_c2s\nself.data_s2c = data_s2c",
... | <|body_start_0|>
ts_start, ts_end, src_ip, src_port, dst_ip, dst_port, data_c2s, data_s2c = data_tuple
self.data_tuple = data_tuple
self.ts_start = ts_start
self.ts_end = ts_end
self.src_ip = src_ip
self.src_port = src_port
self.dst_ip = dst_ip
self.dst_po... | parse ssh auth protocol | SSHAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSHAuth:
"""parse ssh auth protocol"""
def __init__(self, data_tuple):
""":param data_tuple:"""
<|body_0|>
def parse_data(self, sep='\x00'):
""":param sep: :return:"""
<|body_1|>
def __parse_server_data(self):
""":return:"""
<|body_2|... | stack_v2_sparse_classes_75kplus_train_074079 | 3,095 | no_license | [
{
"docstring": ":param data_tuple:",
"name": "__init__",
"signature": "def __init__(self, data_tuple)"
},
{
"docstring": ":param sep: :return:",
"name": "parse_data",
"signature": "def parse_data(self, sep='\\x00')"
},
{
"docstring": ":return:",
"name": "__parse_server_data",... | 4 | stack_v2_sparse_classes_30k_test_000535 | Implement the Python class `SSHAuth` described below.
Class description:
parse ssh auth protocol
Method signatures and docstrings:
- def __init__(self, data_tuple): :param data_tuple:
- def parse_data(self, sep='\x00'): :param sep: :return:
- def __parse_server_data(self): :return:
- def __parse_client_data(self): :r... | Implement the Python class `SSHAuth` described below.
Class description:
parse ssh auth protocol
Method signatures and docstrings:
- def __init__(self, data_tuple): :param data_tuple:
- def parse_data(self, sep='\x00'): :param sep: :return:
- def __parse_server_data(self): :return:
- def __parse_client_data(self): :r... | 48161b29648908bcba22501927d7d1a49d9ffb1f | <|skeleton|>
class SSHAuth:
"""parse ssh auth protocol"""
def __init__(self, data_tuple):
""":param data_tuple:"""
<|body_0|>
def parse_data(self, sep='\x00'):
""":param sep: :return:"""
<|body_1|>
def __parse_server_data(self):
""":return:"""
<|body_2|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SSHAuth:
"""parse ssh auth protocol"""
def __init__(self, data_tuple):
""":param data_tuple:"""
ts_start, ts_end, src_ip, src_port, dst_ip, dst_port, data_c2s, data_s2c = data_tuple
self.data_tuple = data_tuple
self.ts_start = ts_start
self.ts_end = ts_end
... | the_stack_v2_python_sparse | protocol_parse/sshauth.py | sec-u/packet_analysis | train | 3 |
7bd1624ee91ec7bcc7f6087049622c5b66c6ec94 | [
"meta = self.get_meta(coordinate=coordinate, date=date, band=bands[0])\nmeta.update({'count': len(bands)})\nmemory_file = MemoryFile()\nwith memory_file.open(**meta) as target_raster:\n for idx, band in enumerate(bands):\n with self(coordinate=coordinate, date=date, bands=[band]) as source_raster:\n ... | <|body_start_0|>
meta = self.get_meta(coordinate=coordinate, date=date, band=bands[0])
meta.update({'count': len(bands)})
memory_file = MemoryFile()
with memory_file.open(**meta) as target_raster:
for idx, band in enumerate(bands):
with self(coordinate=coordin... | Extends SceneReader by for specific usage of separate band files reading | BandReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BandReader:
"""Extends SceneReader by for specific usage of separate band files reading"""
def _open_and_stack_bands(self, coordinate, date, bands):
"""Loads band file rasters at path specified by arguments and stacks bands into single raster Args: coordinate (object): coordinate inf... | stack_v2_sparse_classes_75kplus_train_074080 | 5,861 | no_license | [
{
"docstring": "Loads band file rasters at path specified by arguments and stacks bands into single raster Args: coordinate (object): coordinate information - to be precised in child class date (object): date information - to be precised in child class bands (list[str]): list of band files to load Returns: type... | 3 | stack_v2_sparse_classes_30k_train_022630 | Implement the Python class `BandReader` described below.
Class description:
Extends SceneReader by for specific usage of separate band files reading
Method signatures and docstrings:
- def _open_and_stack_bands(self, coordinate, date, bands): Loads band file rasters at path specified by arguments and stacks bands int... | Implement the Python class `BandReader` described below.
Class description:
Extends SceneReader by for specific usage of separate band files reading
Method signatures and docstrings:
- def _open_and_stack_bands(self, coordinate, date, bands): Loads band file rasters at path specified by arguments and stacks bands int... | 5519ec2fea784ba20bb37c21b59024a1f47519f6 | <|skeleton|>
class BandReader:
"""Extends SceneReader by for specific usage of separate band files reading"""
def _open_and_stack_bands(self, coordinate, date, bands):
"""Loads band file rasters at path specified by arguments and stacks bands into single raster Args: coordinate (object): coordinate inf... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BandReader:
"""Extends SceneReader by for specific usage of separate band files reading"""
def _open_and_stack_bands(self, coordinate, date, bands):
"""Loads band file rasters at path specified by arguments and stacks bands into single raster Args: coordinate (object): coordinate information - to... | the_stack_v2_python_sparse | src/prepare_data/io/readers/scene_reader.py | prhuppertz/ds-generative-reflectance-fusion | train | 0 |
fdcddb34ad7adda4320d3826e9ad5ce24805d888 | [
"self.logger = logger\nself.account_name = config[constants.azure_storage_account_name_key_name]\nself.access_key = config[constants.azure_storage_access_key_key_name]\nself.endpoint_suffix = config[constants.azure_storage_endpoint_suffix_key_name]\nself.connection_string = 'DefaultEndpointsProtocol=https;AccountNa... | <|body_start_0|>
self.logger = logger
self.account_name = config[constants.azure_storage_account_name_key_name]
self.access_key = config[constants.azure_storage_access_key_key_name]
self.endpoint_suffix = config[constants.azure_storage_endpoint_suffix_key_name]
self.connection_st... | This reader reads data from given table Attributes ---------- logger : AirbyteLogger Airbyte's Logger instance account_name : str The name of your storage account. access_key : str The access key to your storage account. Read more about access keys here - https://docs.microsoft.com/en-us/azure/storage/common/storage-ac... | AzureTableReader | [
"MIT",
"Elastic-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AzureTableReader:
"""This reader reads data from given table Attributes ---------- logger : AirbyteLogger Airbyte's Logger instance account_name : str The name of your storage account. access_key : str The access key to your storage account. Read more about access keys here - https://docs.microso... | stack_v2_sparse_classes_75kplus_train_074081 | 4,691 | permissive | [
{
"docstring": "Parameters ---------- config : dict Airbyte's configuration obect",
"name": "__init__",
"signature": "def __init__(self, logger: AirbyteLogger, config: dict)"
},
{
"docstring": "Returns azure table service client from connection string. Table service client facilitate interaction... | 5 | stack_v2_sparse_classes_30k_test_001444 | Implement the Python class `AzureTableReader` described below.
Class description:
This reader reads data from given table Attributes ---------- logger : AirbyteLogger Airbyte's Logger instance account_name : str The name of your storage account. access_key : str The access key to your storage account. Read more about ... | Implement the Python class `AzureTableReader` described below.
Class description:
This reader reads data from given table Attributes ---------- logger : AirbyteLogger Airbyte's Logger instance account_name : str The name of your storage account. access_key : str The access key to your storage account. Read more about ... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class AzureTableReader:
"""This reader reads data from given table Attributes ---------- logger : AirbyteLogger Airbyte's Logger instance account_name : str The name of your storage account. access_key : str The access key to your storage account. Read more about access keys here - https://docs.microso... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AzureTableReader:
"""This reader reads data from given table Attributes ---------- logger : AirbyteLogger Airbyte's Logger instance account_name : str The name of your storage account. access_key : str The access key to your storage account. Read more about access keys here - https://docs.microsoft.com/en-us/... | the_stack_v2_python_sparse | dts/airbyte/airbyte-integrations/connectors/source-azure-table/source_azure_table/azure_table.py | alldatacenter/alldata | train | 774 |
859a6a853023dee734f41a5663018a288f0de3cf | [
"tokens: List[str] = key.split('=')\nif len(tokens) != 2:\n raise Exception(f'Key {key} contains more than one occurrence of =.')\nif tokens[0] != key_type:\n raise Exception(f'Key {key} does not start from {key_type}=.')\nreturn tokens[1]",
"second_part: str = cls.remove_prefix(key, key_type)\ntokens: List... | <|body_start_0|>
tokens: List[str] = key.split('=')
if len(tokens) != 2:
raise Exception(f'Key {key} contains more than one occurrence of =.')
if tokens[0] != key_type:
raise Exception(f'Key {key} does not start from {key_type}=.')
return tokens[1]
<|end_body_0|>
... | Utilities for working with key strings. | KeyUtil | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyUtil:
"""Utilities for working with key strings."""
def remove_prefix(cls, key: str, key_type: str) -> str:
"""Parse key string in KeyType=A;B;C format, verify that the first part (KeyType) matches key_type argument, and return the second part (A;B;C). This method verifies that th... | stack_v2_sparse_classes_75kplus_train_074082 | 2,138 | permissive | [
{
"docstring": "Parse key string in KeyType=A;B;C format, verify that the first part (KeyType) matches key_type argument, and return the second part (A;B;C). This method verifies that the second part does not contain =, but does not verify how many semicolon delimiters it has.",
"name": "remove_prefix",
... | 2 | stack_v2_sparse_classes_30k_train_009706 | Implement the Python class `KeyUtil` described below.
Class description:
Utilities for working with key strings.
Method signatures and docstrings:
- def remove_prefix(cls, key: str, key_type: str) -> str: Parse key string in KeyType=A;B;C format, verify that the first part (KeyType) matches key_type argument, and ret... | Implement the Python class `KeyUtil` described below.
Class description:
Utilities for working with key strings.
Method signatures and docstrings:
- def remove_prefix(cls, key: str, key_type: str) -> str: Parse key string in KeyType=A;B;C format, verify that the first part (KeyType) matches key_type argument, and ret... | 40113ddfb68e62d98b880b3c7427db5cc9fbd8cd | <|skeleton|>
class KeyUtil:
"""Utilities for working with key strings."""
def remove_prefix(cls, key: str, key_type: str) -> str:
"""Parse key string in KeyType=A;B;C format, verify that the first part (KeyType) matches key_type argument, and return the second part (A;B;C). This method verifies that th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeyUtil:
"""Utilities for working with key strings."""
def remove_prefix(cls, key: str, key_type: str) -> str:
"""Parse key string in KeyType=A;B;C format, verify that the first part (KeyType) matches key_type argument, and return the second part (A;B;C). This method verifies that the second part... | the_stack_v2_python_sparse | py/datacentric/storage/key_util.py | datacentricorg/datacentric-py | train | 1 |
703526705d240d1800dd8a8f4e2c5f83ed5b9f17 | [
"self.backup_file_vec = backup_file_vec\nself.option_flags = option_flags\nself.site_info = site_info\nself.warning_vec = warning_vec",
"if dictionary is None:\n return None\nbackup_file_vec = None\nif dictionary.get('backupFileVec') != None:\n backup_file_vec = list()\n for structure in dictionary.get('... | <|body_start_0|>
self.backup_file_vec = backup_file_vec
self.option_flags = option_flags
self.site_info = site_info
self.warning_vec = warning_vec
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
backup_file_vec = None
if dictionary.... | Implementation of the 'SiteBackupStatus' model. TODO: type description here. Attributes: backup_file_vec (list of SiteBackupFile): List of backuped files. Its PnP package and any other files required to recover the site. option_flags (int): Actual options with which this site was backed up (BackupSiteArg.BackupSiteOpti... | SiteBackupStatus | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiteBackupStatus:
"""Implementation of the 'SiteBackupStatus' model. TODO: type description here. Attributes: backup_file_vec (list of SiteBackupFile): List of backuped files. Its PnP package and any other files required to recover the site. option_flags (int): Actual options with which this site... | stack_v2_sparse_classes_75kplus_train_074083 | 2,887 | permissive | [
{
"docstring": "Constructor for the SiteBackupStatus class",
"name": "__init__",
"signature": "def __init__(self, backup_file_vec=None, option_flags=None, site_info=None, warning_vec=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A di... | 2 | stack_v2_sparse_classes_30k_train_017790 | Implement the Python class `SiteBackupStatus` described below.
Class description:
Implementation of the 'SiteBackupStatus' model. TODO: type description here. Attributes: backup_file_vec (list of SiteBackupFile): List of backuped files. Its PnP package and any other files required to recover the site. option_flags (in... | Implement the Python class `SiteBackupStatus` described below.
Class description:
Implementation of the 'SiteBackupStatus' model. TODO: type description here. Attributes: backup_file_vec (list of SiteBackupFile): List of backuped files. Its PnP package and any other files required to recover the site. option_flags (in... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SiteBackupStatus:
"""Implementation of the 'SiteBackupStatus' model. TODO: type description here. Attributes: backup_file_vec (list of SiteBackupFile): List of backuped files. Its PnP package and any other files required to recover the site. option_flags (int): Actual options with which this site... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SiteBackupStatus:
"""Implementation of the 'SiteBackupStatus' model. TODO: type description here. Attributes: backup_file_vec (list of SiteBackupFile): List of backuped files. Its PnP package and any other files required to recover the site. option_flags (int): Actual options with which this site was backed u... | the_stack_v2_python_sparse | cohesity_management_sdk/models/site_backup_status.py | cohesity/management-sdk-python | train | 24 |
a744487c92965c81657725718f8310d99898b5a5 | [
"query = {'query': {'match': {'profile.first_name': 'here'}}}\npercolate_query = PercolateQueryFactory.create(query=query, original_query='original')\npercolate_query_id = 123\npercolate_query.id = percolate_query_id\nwith self.assertRaises(NotFoundError):\n es.get_percolate_query(percolate_query_id)\nindex_perc... | <|body_start_0|>
query = {'query': {'match': {'profile.first_name': 'here'}}}
percolate_query = PercolateQueryFactory.create(query=query, original_query='original')
percolate_query_id = 123
percolate_query.id = percolate_query_id
with self.assertRaises(NotFoundError):
... | Tests for indexing of percolate queries | PercolateQueryTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PercolateQueryTests:
"""Tests for indexing of percolate queries"""
def test_index_percolate_query(self):
"""Test that we index the percolate query"""
<|body_0|>
def test_delete_percolate_queries(self):
"""Test that we delete the percolate query from the index"""
... | stack_v2_sparse_classes_75kplus_train_074084 | 42,701 | permissive | [
{
"docstring": "Test that we index the percolate query",
"name": "test_index_percolate_query",
"signature": "def test_index_percolate_query(self)"
},
{
"docstring": "Test that we delete the percolate query from the index",
"name": "test_delete_percolate_queries",
"signature": "def test_d... | 5 | stack_v2_sparse_classes_30k_train_016074 | Implement the Python class `PercolateQueryTests` described below.
Class description:
Tests for indexing of percolate queries
Method signatures and docstrings:
- def test_index_percolate_query(self): Test that we index the percolate query
- def test_delete_percolate_queries(self): Test that we delete the percolate que... | Implement the Python class `PercolateQueryTests` described below.
Class description:
Tests for indexing of percolate queries
Method signatures and docstrings:
- def test_index_percolate_query(self): Test that we index the percolate query
- def test_delete_percolate_queries(self): Test that we delete the percolate que... | d6564caca0b7bbfd31e67a751564107fd17d6eb0 | <|skeleton|>
class PercolateQueryTests:
"""Tests for indexing of percolate queries"""
def test_index_percolate_query(self):
"""Test that we index the percolate query"""
<|body_0|>
def test_delete_percolate_queries(self):
"""Test that we delete the percolate query from the index"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PercolateQueryTests:
"""Tests for indexing of percolate queries"""
def test_index_percolate_query(self):
"""Test that we index the percolate query"""
query = {'query': {'match': {'profile.first_name': 'here'}}}
percolate_query = PercolateQueryFactory.create(query=query, original_q... | the_stack_v2_python_sparse | search/indexing_api_test.py | mitodl/micromasters | train | 35 |
e95afae6c9d93291c92cf434fa2a0f6b1f5094b0 | [
"fields = kwargs.pop('fields', None)\nmodel = kwargs.pop('model', None)\nself.validateRequired = kwargs.pop('required', None)\nif model:\n self.Meta.model = model\nkwargs['read_only'] = True\nsuper(DynamicLookupModelSerializer, self).__init__(*args, **kwargs)\nif fields:\n allowed = set(fields)\n existing ... | <|body_start_0|>
fields = kwargs.pop('fields', None)
model = kwargs.pop('model', None)
self.validateRequired = kwargs.pop('required', None)
if model:
self.Meta.model = model
kwargs['read_only'] = True
super(DynamicLookupModelSerializer, self).__init__(*args, *... | class DynamicLookupModelSerializer. A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. | DynamicLookupModelSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicLookupModelSerializer:
"""class DynamicLookupModelSerializer. A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed."""
def __init__(self, *args, **kwargs):
"""init. :param *args: :param **kwargs:"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_074085 | 14,223 | permissive | [
{
"docstring": "init. :param *args: :param **kwargs:",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "to internal value. :param data: :return ret_dict:",
"name": "to_internal_value",
"signature": "def to_internal_value(self, data)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_026237 | Implement the Python class `DynamicLookupModelSerializer` described below.
Class description:
class DynamicLookupModelSerializer. A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): init. ... | Implement the Python class `DynamicLookupModelSerializer` described below.
Class description:
class DynamicLookupModelSerializer. A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): init. ... | b8fd0f5fe7ff32209d198958d4f510ef4bb579b0 | <|skeleton|>
class DynamicLookupModelSerializer:
"""class DynamicLookupModelSerializer. A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed."""
def __init__(self, *args, **kwargs):
"""init. :param *args: :param **kwargs:"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DynamicLookupModelSerializer:
"""class DynamicLookupModelSerializer. A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed."""
def __init__(self, *args, **kwargs):
"""init. :param *args: :param **kwargs:"""
fields = kwargs.pop('fields'... | the_stack_v2_python_sparse | crams/api/v1/serializers/utilitySerializers.py | NeCTAR-RC/crams-api | train | 0 |
9aa33adfbb19220cf6c70b02a13ef07642702f94 | [
"if self.data is not None:\n return self.data\nwith helpers.ensure_open(self):\n text = self.read_text()\n return platform.yaml.safe_load(text) if self.format == 'yaml' else json.loads(text)",
"resource = target\nif not isinstance(resource, Resource):\n resource = Resource(target, **options)\nif not i... | <|body_start_0|>
if self.data is not None:
return self.data
with helpers.ensure_open(self):
text = self.read_text()
return platform.yaml.safe_load(text) if self.format == 'yaml' else json.loads(text)
<|end_body_0|>
<|body_start_1|>
resource = target
i... | JsonResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonResource:
def read_json(self) -> Any:
"""Read json data into memory Returns: any: json data"""
<|body_0|>
def write_json(self, target: Optional[Union[JsonResource, Any]]=None, **options: Any):
"""Write json data to the target"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus_train_074086 | 8,470 | permissive | [
{
"docstring": "Read json data into memory Returns: any: json data",
"name": "read_json",
"signature": "def read_json(self) -> Any"
},
{
"docstring": "Write json data to the target",
"name": "write_json",
"signature": "def write_json(self, target: Optional[Union[JsonResource, Any]]=None,... | 2 | null | Implement the Python class `JsonResource` described below.
Class description:
Implement the JsonResource class.
Method signatures and docstrings:
- def read_json(self) -> Any: Read json data into memory Returns: any: json data
- def write_json(self, target: Optional[Union[JsonResource, Any]]=None, **options: Any): Wr... | Implement the Python class `JsonResource` described below.
Class description:
Implement the JsonResource class.
Method signatures and docstrings:
- def read_json(self) -> Any: Read json data into memory Returns: any: json data
- def write_json(self, target: Optional[Union[JsonResource, Any]]=None, **options: Any): Wr... | 740319edeee58f12cc6956a53356f3065ff18cbb | <|skeleton|>
class JsonResource:
def read_json(self) -> Any:
"""Read json data into memory Returns: any: json data"""
<|body_0|>
def write_json(self, target: Optional[Union[JsonResource, Any]]=None, **options: Any):
"""Write json data to the target"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JsonResource:
def read_json(self) -> Any:
"""Read json data into memory Returns: any: json data"""
if self.data is not None:
return self.data
with helpers.ensure_open(self):
text = self.read_text()
return platform.yaml.safe_load(text) if self.format ... | the_stack_v2_python_sparse | frictionless/resources/json.py | frictionlessdata/frictionless-py | train | 295 | |
a231df3873944524faab61382378ea5c61f5beb3 | [
"task: Optional[BackgroundTask] = None\ntry:\n task = BackgroundTask.objects.get(pk=task_id)\n task.started = timezone.now()\n task.status = BackgroundTask.STATUS_PROCESSING\n task.save(update_fields=['status', 'started'])\n task.output = function() or 'Task completed.'\n task.status = BackgroundT... | <|body_start_0|>
task: Optional[BackgroundTask] = None
try:
task = BackgroundTask.objects.get(pk=task_id)
task.started = timezone.now()
task.status = BackgroundTask.STATUS_PROCESSING
task.save(update_fields=['status', 'started'])
task.output = ... | The background task consumer. | BackgroundTaskConsumer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackgroundTaskConsumer:
"""The background task consumer."""
def wrap_task(self, function: Callable, task_id: int):
"""Start the function and update background task status."""
<|body_0|>
async def duplicate_data(self, message: dict):
"""Duplicate the data and upda... | stack_v2_sparse_classes_75kplus_train_074087 | 9,008 | permissive | [
{
"docstring": "Start the function and update background task status.",
"name": "wrap_task",
"signature": "def wrap_task(self, function: Callable, task_id: int)"
},
{
"docstring": "Duplicate the data and update task status.",
"name": "duplicate_data",
"signature": "async def duplicate_da... | 5 | stack_v2_sparse_classes_30k_train_037431 | Implement the Python class `BackgroundTaskConsumer` described below.
Class description:
The background task consumer.
Method signatures and docstrings:
- def wrap_task(self, function: Callable, task_id: int): Start the function and update background task status.
- async def duplicate_data(self, message: dict): Duplic... | Implement the Python class `BackgroundTaskConsumer` described below.
Class description:
The background task consumer.
Method signatures and docstrings:
- def wrap_task(self, function: Callable, task_id: int): Start the function and update background task status.
- async def duplicate_data(self, message: dict): Duplic... | 25c0c45235ef37beb45c1af4c917fbbae6282016 | <|skeleton|>
class BackgroundTaskConsumer:
"""The background task consumer."""
def wrap_task(self, function: Callable, task_id: int):
"""Start the function and update background task status."""
<|body_0|>
async def duplicate_data(self, message: dict):
"""Duplicate the data and upda... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BackgroundTaskConsumer:
"""The background task consumer."""
def wrap_task(self, function: Callable, task_id: int):
"""Start the function and update background task status."""
task: Optional[BackgroundTask] = None
try:
task = BackgroundTask.objects.get(pk=task_id)
... | the_stack_v2_python_sparse | resolwe/observers/consumers.py | genialis/resolwe | train | 35 |
05bb353437463e2497d11fc5a097ee4c8b981432 | [
"def cmp(a, b):\n z = list(zip(a, b))\n n = len(z)\n for i in range(1, n):\n if z[i][0] < z[i][1]:\n return True\n if z[i][0] > z[i][1]:\n return False\n if len(a) > len(b):\n return False\n else:\n return a[0] <= b[0]\n\ndef partition(left, right):\n... | <|body_start_0|>
def cmp(a, b):
z = list(zip(a, b))
n = len(z)
for i in range(1, n):
if z[i][0] < z[i][1]:
return True
if z[i][0] > z[i][1]:
return False
if len(a) > len(b):
re... | SolutionQuickSort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionQuickSort:
def quick_sort(self, logs):
"""["let1 art","let3 art","let2 art own dig","dig1 8 1 5 1","dig2 3 6"]"""
<|body_0|>
def reorderLogFiles(self, logs: List[str]) -> List[str]:
"""d = ["dig1...", "dig2..."] ^ [dig1, 8, 1, 5, 1] l = ["let1...", "let2..."]... | stack_v2_sparse_classes_75kplus_train_074088 | 5,368 | no_license | [
{
"docstring": "[\"let1 art\",\"let3 art\",\"let2 art own dig\",\"dig1 8 1 5 1\",\"dig2 3 6\"]",
"name": "quick_sort",
"signature": "def quick_sort(self, logs)"
},
{
"docstring": "d = [\"dig1...\", \"dig2...\"] ^ [dig1, 8, 1, 5, 1] l = [\"let1...\", \"let2...\"] ^ convert to array [[let, art, ca... | 2 | stack_v2_sparse_classes_30k_train_028124 | Implement the Python class `SolutionQuickSort` described below.
Class description:
Implement the SolutionQuickSort class.
Method signatures and docstrings:
- def quick_sort(self, logs): ["let1 art","let3 art","let2 art own dig","dig1 8 1 5 1","dig2 3 6"]
- def reorderLogFiles(self, logs: List[str]) -> List[str]: d = ... | Implement the Python class `SolutionQuickSort` described below.
Class description:
Implement the SolutionQuickSort class.
Method signatures and docstrings:
- def quick_sort(self, logs): ["let1 art","let3 art","let2 art own dig","dig1 8 1 5 1","dig2 3 6"]
- def reorderLogFiles(self, logs: List[str]) -> List[str]: d = ... | 4619a23386bb62041a134afc782ff56918dd7b47 | <|skeleton|>
class SolutionQuickSort:
def quick_sort(self, logs):
"""["let1 art","let3 art","let2 art own dig","dig1 8 1 5 1","dig2 3 6"]"""
<|body_0|>
def reorderLogFiles(self, logs: List[str]) -> List[str]:
"""d = ["dig1...", "dig2..."] ^ [dig1, 8, 1, 5, 1] l = ["let1...", "let2..."]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SolutionQuickSort:
def quick_sort(self, logs):
"""["let1 art","let3 art","let2 art own dig","dig1 8 1 5 1","dig2 3 6"]"""
def cmp(a, b):
z = list(zip(a, b))
n = len(z)
for i in range(1, n):
if z[i][0] < z[i][1]:
return Tru... | the_stack_v2_python_sparse | 0937_reorder_data_in_log_files.py | Kcheung42/Leet_Code | train | 0 | |
7d95c64a7c47386bda20a9b09f6d1c98f3aa1e8f | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects",
"file_name = cls.__name__ + '.json'\nwith open(file_name, 'w') as file:\n if list_objs is None:\n file.write('[]')\n return\n file.write('[')\n for obj in range(len(list_objs)):\n ... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
<|end_body_0|>
<|body_start_1|>
file_name = cls.__name__ + '.json'
with open(file_name, 'w') as file:
if list_objs is None:
... | Defines Base | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""Defines Base"""
def __init__(self, id=None):
"""Initialization of instance variables"""
<|body_0|>
def save_to_file(cls, list_objs):
"""Writes the JSON representation of list_objs to a file"""
<|body_1|>
def create(cls, **dictionary):
... | stack_v2_sparse_classes_75kplus_train_074089 | 2,362 | no_license | [
{
"docstring": "Initialization of instance variables",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "Writes the JSON representation of list_objs to a file",
"name": "save_to_file",
"signature": "def save_to_file(cls, list_objs)"
},
{
"docstring... | 6 | stack_v2_sparse_classes_30k_test_000687 | Implement the Python class `Base` described below.
Class description:
Defines Base
Method signatures and docstrings:
- def __init__(self, id=None): Initialization of instance variables
- def save_to_file(cls, list_objs): Writes the JSON representation of list_objs to a file
- def create(cls, **dictionary): Returns an... | Implement the Python class `Base` described below.
Class description:
Defines Base
Method signatures and docstrings:
- def __init__(self, id=None): Initialization of instance variables
- def save_to_file(cls, list_objs): Writes the JSON representation of list_objs to a file
- def create(cls, **dictionary): Returns an... | 985fa5185dc0dd3c43c9770bd5c3e2da31f0b68e | <|skeleton|>
class Base:
"""Defines Base"""
def __init__(self, id=None):
"""Initialization of instance variables"""
<|body_0|>
def save_to_file(cls, list_objs):
"""Writes the JSON representation of list_objs to a file"""
<|body_1|>
def create(cls, **dictionary):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Base:
"""Defines Base"""
def __init__(self, id=None):
"""Initialization of instance variables"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
def save_to_file(cls, list_objs):
"""Writes th... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | miguel-dev/holbertonschool-higher_level_programming | train | 0 |
e41c0887645cd935cee0f21c74aae3fd014699ab | [
"super(ChannelsAttention, self).__init__()\nself.virtual_channels = virtual_channels\nself.attentions = []\nfor channel in range(virtual_channels):\n self.attentions += [Attention(input_dim=input_dim, context_size=context_size, activation=attention_activation)]\nfor i, attention in enumerate(self.attentions):\n ... | <|body_start_0|>
super(ChannelsAttention, self).__init__()
self.virtual_channels = virtual_channels
self.attentions = []
for channel in range(virtual_channels):
self.attentions += [Attention(input_dim=input_dim, context_size=context_size, activation=attention_activation)]
... | " Attention module similarly to Luong 2015 | ChannelsAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChannelsAttention:
"""" Attention module similarly to Luong 2015"""
def __init__(self, input_dim, context_size=32, virtual_channels=4, attention_activation='tanh'):
"""input_dim (int): Dimensions of the input/ Number of features_data context_size (int): number of dim to use from the ... | stack_v2_sparse_classes_75kplus_train_074090 | 2,621 | permissive | [
{
"docstring": "input_dim (int): Dimensions of the input/ Number of features_data context_size (int): number of dim to use from the context",
"name": "__init__",
"signature": "def __init__(self, input_dim, context_size=32, virtual_channels=4, attention_activation='tanh')"
},
{
"docstring": "x (t... | 2 | stack_v2_sparse_classes_30k_train_034116 | Implement the Python class `ChannelsAttention` described below.
Class description:
" Attention module similarly to Luong 2015
Method signatures and docstrings:
- def __init__(self, input_dim, context_size=32, virtual_channels=4, attention_activation='tanh'): input_dim (int): Dimensions of the input/ Number of feature... | Implement the Python class `ChannelsAttention` described below.
Class description:
" Attention module similarly to Luong 2015
Method signatures and docstrings:
- def __init__(self, input_dim, context_size=32, virtual_channels=4, attention_activation='tanh'): input_dim (int): Dimensions of the input/ Number of feature... | c8ff3f6f857299eb2bf2e9400483084d5ecd4106 | <|skeleton|>
class ChannelsAttention:
"""" Attention module similarly to Luong 2015"""
def __init__(self, input_dim, context_size=32, virtual_channels=4, attention_activation='tanh'):
"""input_dim (int): Dimensions of the input/ Number of features_data context_size (int): number of dim to use from the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChannelsAttention:
"""" Attention module similarly to Luong 2015"""
def __init__(self, input_dim, context_size=32, virtual_channels=4, attention_activation='tanh'):
"""input_dim (int): Dimensions of the input/ Number of features_data context_size (int): number of dim to use from the context"""
... | the_stack_v2_python_sparse | robust_sleep_net/models/modulo_net/modules/channels_attention.py | tmorshed/RobustSleepNet | train | 0 |
5b7e2aace18797a88f79ad8dc4cbe69ec88e73ce | [
"init_mu = 0\ninit_sigma = 0.0001\nself.params = {'weight': np.random.normal(init_mu, init_sigma, (out_features, in_features)), 'bias': np.zeros((1, out_features))}\nself.grads = {'weight': np.zeros((out_features, in_features)), 'bias': np.zeros((1, out_features))}",
"self.x = x\nout = np.matmul(x, self.params['w... | <|body_start_0|>
init_mu = 0
init_sigma = 0.0001
self.params = {'weight': np.random.normal(init_mu, init_sigma, (out_features, in_features)), 'bias': np.zeros((1, out_features))}
self.grads = {'weight': np.zeros((out_features, in_features)), 'bias': np.zeros((1, out_features))}
<|end_bod... | Linear module. Applies a linear transformation to the input data. | LinearModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearModule:
"""Linear module. Applies a linear transformation to the input data."""
def __init__(self, in_features, out_features):
"""Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize wei... | stack_v2_sparse_classes_75kplus_train_074091 | 7,539 | no_license | [
{
"docstring": "Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize weights self.params['weight'] using normal distribution with mean = 0 and std = 0.0001. Initialize biases self.params['bias'] with 0. Also, initialize ... | 3 | stack_v2_sparse_classes_30k_train_034311 | Implement the Python class `LinearModule` described below.
Class description:
Linear module. Applies a linear transformation to the input data.
Method signatures and docstrings:
- def __init__(self, in_features, out_features): Initializes the parameters of the module. Args: in_features: size of each input sample out_... | Implement the Python class `LinearModule` described below.
Class description:
Linear module. Applies a linear transformation to the input data.
Method signatures and docstrings:
- def __init__(self, in_features, out_features): Initializes the parameters of the module. Args: in_features: size of each input sample out_... | 4226202d497226970eeeb03d2c692b8baf5a73dc | <|skeleton|>
class LinearModule:
"""Linear module. Applies a linear transformation to the input data."""
def __init__(self, in_features, out_features):
"""Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize wei... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinearModule:
"""Linear module. Applies a linear transformation to the input data."""
def __init__(self, in_features, out_features):
"""Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize weights self.par... | the_stack_v2_python_sparse | assignment_1/1_mlp_cnn/code/modules.py | EuiYeonJang/uvadlc_2020 | train | 0 |
7a390cd85462a5e04ac2661a37eb5505404792fa | [
"order = []\nvowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\nans = list(s)\nleft, right = (0, len(ans) - 1)\nwhile left <= right:\n if ans[left] in vowels and ans[right] in vowels:\n ans[left], ans[right] = (ans[right], ans[left])\n left += 1\n right -= 1\n continue\n ... | <|body_start_0|>
order = []
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
ans = list(s)
left, right = (0, len(ans) - 1)
while left <= right:
if ans[left] in vowels and ans[right] in vowels:
ans[left], ans[right] = (ans[right], ans[left])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
order = []
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', '... | stack_v2_sparse_classes_75kplus_train_074092 | 1,572 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels",
"signature": "def reverseVowels(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels",
"signature": "def reverseVowels(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015435 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def reverseVowels(self, s):
... | dda63f5b196bfcdc4062bdad8d47076f36a9d89a | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
order = []
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
ans = list(s)
left, right = (0, len(ans) - 1)
while left <= right:
if ans[left] in vowels and ans[right] in vo... | the_stack_v2_python_sparse | Google/345_Reverse_Vowels_of_a_String.py | bwang8482/LeetCode | train | 1 | |
c872a9f25e5caf8821138cf19092fffc929d7961 | [
"try:\n self.request = self.authenticate_and_create_auth_header(access_token=access_token)\nexcept Exception:\n raise ValueError('User has not configured Pushbullet token')",
"try:\n auth_header = {'Authorization': f'Bearer {str(access_token)}'}\n request = getattr(requests, method.lower())\n respo... | <|body_start_0|>
try:
self.request = self.authenticate_and_create_auth_header(access_token=access_token)
except Exception:
raise ValueError('User has not configured Pushbullet token')
<|end_body_0|>
<|body_start_1|>
try:
auth_header = {'Authorization': f'Bear... | Handles all API requests/responses | Pushbullet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pushbullet:
"""Handles all API requests/responses"""
def __init__(self, access_token: str) -> None:
"""Check that user has configured pushbullet"""
<|body_0|>
def authenticate_and_create_auth_header(self, access_token, method: str='get') -> bool:
"""Authenticates... | stack_v2_sparse_classes_75kplus_train_074093 | 3,064 | no_license | [
{
"docstring": "Check that user has configured pushbullet",
"name": "__init__",
"signature": "def __init__(self, access_token: str) -> None"
},
{
"docstring": "Authenticates user token and stores auth header in auth_header instance var",
"name": "authenticate_and_create_auth_header",
"si... | 4 | null | Implement the Python class `Pushbullet` described below.
Class description:
Handles all API requests/responses
Method signatures and docstrings:
- def __init__(self, access_token: str) -> None: Check that user has configured pushbullet
- def authenticate_and_create_auth_header(self, access_token, method: str='get') -... | Implement the Python class `Pushbullet` described below.
Class description:
Handles all API requests/responses
Method signatures and docstrings:
- def __init__(self, access_token: str) -> None: Check that user has configured pushbullet
- def authenticate_and_create_auth_header(self, access_token, method: str='get') -... | 3eca46b1eb665487dbc661b026e6556bc6f4d18b | <|skeleton|>
class Pushbullet:
"""Handles all API requests/responses"""
def __init__(self, access_token: str) -> None:
"""Check that user has configured pushbullet"""
<|body_0|>
def authenticate_and_create_auth_header(self, access_token, method: str='get') -> bool:
"""Authenticates... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Pushbullet:
"""Handles all API requests/responses"""
def __init__(self, access_token: str) -> None:
"""Check that user has configured pushbullet"""
try:
self.request = self.authenticate_and_create_auth_header(access_token=access_token)
except Exception:
rai... | the_stack_v2_python_sparse | apps/notifications/utils.py | jyoung90ie/home-automation-at-home | train | 0 |
d4ba11fd5a9899cdfdc3bf550688a6ed4fc481fa | [
"super().define(spec)\nspec.input('nnkp_file', valid_type=SinglefileData, help='A SinglefileData containing the .nnkp file generated by wannier90.x -pp')\nspec.input('parent_folder', valid_type=(RemoteData, FolderData), help='The output folder of a pw.x calculation')\nspec.output('output_parameters', valid_type=Dic... | <|body_start_0|>
super().define(spec)
spec.input('nnkp_file', valid_type=SinglefileData, help='A SinglefileData containing the .nnkp file generated by wannier90.x -pp')
spec.input('parent_folder', valid_type=(RemoteData, FolderData), help='The output folder of a pw.x calculation')
spec.o... | `CalcJob` implementation for the pw2wannier.x code of Quantum ESPRESSO. For more information, refer to http://www.quantum-espresso.org/ and http://www.wannier.org/ | Pw2wannier90Calculation | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pw2wannier90Calculation:
"""`CalcJob` implementation for the pw2wannier.x code of Quantum ESPRESSO. For more information, refer to http://www.quantum-espresso.org/ and http://www.wannier.org/"""
def define(cls, spec):
"""Define the process specification."""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus_train_074094 | 2,758 | permissive | [
{
"docstring": "Define the process specification.",
"name": "define",
"signature": "def define(cls, spec)"
},
{
"docstring": "Prepare the calculation job for submission by transforming input nodes into input files. In addition to the input files being written to the sandbox folder, a `CalcInfo` ... | 2 | stack_v2_sparse_classes_30k_train_050723 | Implement the Python class `Pw2wannier90Calculation` described below.
Class description:
`CalcJob` implementation for the pw2wannier.x code of Quantum ESPRESSO. For more information, refer to http://www.quantum-espresso.org/ and http://www.wannier.org/
Method signatures and docstrings:
- def define(cls, spec): Define... | Implement the Python class `Pw2wannier90Calculation` described below.
Class description:
`CalcJob` implementation for the pw2wannier.x code of Quantum ESPRESSO. For more information, refer to http://www.quantum-espresso.org/ and http://www.wannier.org/
Method signatures and docstrings:
- def define(cls, spec): Define... | 7263f92ccabcfc9f828b9da5473e1aefbc4b8eca | <|skeleton|>
class Pw2wannier90Calculation:
"""`CalcJob` implementation for the pw2wannier.x code of Quantum ESPRESSO. For more information, refer to http://www.quantum-espresso.org/ and http://www.wannier.org/"""
def define(cls, spec):
"""Define the process specification."""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Pw2wannier90Calculation:
"""`CalcJob` implementation for the pw2wannier.x code of Quantum ESPRESSO. For more information, refer to http://www.quantum-espresso.org/ and http://www.wannier.org/"""
def define(cls, spec):
"""Define the process specification."""
super().define(spec)
sp... | the_stack_v2_python_sparse | src/aiida_quantumespresso/calculations/pw2wannier90.py | aiidateam/aiida-quantumespresso | train | 56 |
39ee5e954f28253675b777f1c30cabe3f094fa40 | [
"if not root:\n return True\n\ndef inorder_dfs(root: TreeNode):\n \"\"\" 中序遍历 \"\"\"\n if not root or not self.is_valid:\n return None\n inorder_dfs(root.left)\n if root.val > self.min_val:\n self.min_val = root.val\n else:\n self.is_valid = False\n inorder_dfs(root.right)\... | <|body_start_0|>
if not root:
return True
def inorder_dfs(root: TreeNode):
""" 中序遍历 """
if not root or not self.is_valid:
return None
inorder_dfs(root.left)
if root.val > self.min_val:
self.min_val = root.val
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
"""DFS(中序遍历,递归版)"""
<|body_0|>
def isValidBSTDFS(self, root: TreeNode) -> bool:
"""DFS(自底而上)"""
<|body_1|>
def isValidBSTNonRecursion(self, root: TreeNode) -> bool:
"""DFS(中序遍历,非递归)"""
... | stack_v2_sparse_classes_75kplus_train_074095 | 2,403 | no_license | [
{
"docstring": "DFS(中序遍历,递归版)",
"name": "isValidBST",
"signature": "def isValidBST(self, root: TreeNode) -> bool"
},
{
"docstring": "DFS(自底而上)",
"name": "isValidBSTDFS",
"signature": "def isValidBSTDFS(self, root: TreeNode) -> bool"
},
{
"docstring": "DFS(中序遍历,非递归)",
"name": ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root: TreeNode) -> bool: DFS(中序遍历,递归版)
- def isValidBSTDFS(self, root: TreeNode) -> bool: DFS(自底而上)
- def isValidBSTNonRecursion(self, root: TreeNode) -> boo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root: TreeNode) -> bool: DFS(中序遍历,递归版)
- def isValidBSTDFS(self, root: TreeNode) -> bool: DFS(自底而上)
- def isValidBSTNonRecursion(self, root: TreeNode) -> boo... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
"""DFS(中序遍历,递归版)"""
<|body_0|>
def isValidBSTDFS(self, root: TreeNode) -> bool:
"""DFS(自底而上)"""
<|body_1|>
def isValidBSTNonRecursion(self, root: TreeNode) -> bool:
"""DFS(中序遍历,非递归)"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isValidBST(self, root: TreeNode) -> bool:
"""DFS(中序遍历,递归版)"""
if not root:
return True
def inorder_dfs(root: TreeNode):
""" 中序遍历 """
if not root or not self.is_valid:
return None
inorder_dfs(root.left)
... | the_stack_v2_python_sparse | 98.验证二叉搜索树/solution.py | QtTao/daily_leetcode | train | 0 | |
a035bead6f3dd49725a7530632f23b687a5d5d2a | [
"min_num, max_num = (999999, 0)\nfor i in prices:\n min_num = min(min_num, i)\n max_num = max(max_num, i - min_num)\nreturn max_num",
"if not prices:\n return 0\nmin_num = prices[0]\nres = 0\nfor i in prices:\n if i < min_num:\n min_num = i\n else:\n res = max(res, i - min_num)\nretur... | <|body_start_0|>
min_num, max_num = (999999, 0)
for i in prices:
min_num = min(min_num, i)
max_num = max(max_num, i - min_num)
return max_num
<|end_body_0|>
<|body_start_1|>
if not prices:
return 0
min_num = prices[0]
res = 0
f... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
min_num, max_num = (999999, 0)
f... | stack_v2_sparse_classes_75kplus_train_074096 | 1,249 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit2",
"signature": "def maxProfit2(self, prices)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxPro... | b613718bf69982535b7c3c9f329a47d5741d8a9e | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
min_num, max_num = (999999, 0)
for i in prices:
min_num = min(min_num, i)
max_num = max(max_num, i - min_num)
return max_num
def maxProfit2(self, prices):
""":t... | the_stack_v2_python_sparse | Python3/Best Time to Buy and Sell Stock.py | liuyuhang791034063/LeetCode | train | 12 | |
c0db84f6826bbec42db7a70dc9f268188e1033cb | [
"self.operands = kwargs.pop('operands')\nself.wf_columns = kwargs.pop('columns')\nsuper().__init__(*args, **kwargs)\nself.fields['columns'].choices = [(idx, col.name) for idx, col in enumerate(self.wf_columns)]\nself.fields['op_type'].choices = [('', '---')] + [(op_name, op_value) for op_name, op_value, _ in self.o... | <|body_start_0|>
self.operands = kwargs.pop('operands')
self.wf_columns = kwargs.pop('columns')
super().__init__(*args, **kwargs)
self.fields['columns'].choices = [(idx, col.name) for idx, col in enumerate(self.wf_columns)]
self.fields['op_type'].choices = [('', '---')] + [(op_na... | Form to get columns to combine and the operand to use. | FormulaColumnAddForm | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormulaColumnAddForm:
"""Form to get columns to combine and the operand to use."""
def __init__(self, *args, **kwargs):
"""Store the workflow columns and operands."""
<|body_0|>
def clean(self) -> Dict:
"""Verify that the data types of the selected columns are co... | stack_v2_sparse_classes_75kplus_train_074097 | 17,634 | permissive | [
{
"docstring": "Store the workflow columns and operands.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Verify that the data types of the selected columns are correct.",
"name": "clean",
"signature": "def clean(self) -> Dict"
}
] | 2 | stack_v2_sparse_classes_30k_train_024385 | Implement the Python class `FormulaColumnAddForm` described below.
Class description:
Form to get columns to combine and the operand to use.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Store the workflow columns and operands.
- def clean(self) -> Dict: Verify that the data types of the se... | Implement the Python class `FormulaColumnAddForm` described below.
Class description:
Form to get columns to combine and the operand to use.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Store the workflow columns and operands.
- def clean(self) -> Dict: Verify that the data types of the se... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class FormulaColumnAddForm:
"""Form to get columns to combine and the operand to use."""
def __init__(self, *args, **kwargs):
"""Store the workflow columns and operands."""
<|body_0|>
def clean(self) -> Dict:
"""Verify that the data types of the selected columns are co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FormulaColumnAddForm:
"""Form to get columns to combine and the operand to use."""
def __init__(self, *args, **kwargs):
"""Store the workflow columns and operands."""
self.operands = kwargs.pop('operands')
self.wf_columns = kwargs.pop('columns')
super().__init__(*args, **k... | the_stack_v2_python_sparse | ontask/column/forms.py | abelardopardo/ontask_b | train | 43 |
cecfef6263a34a6fcb787a6b715b54d7459a23e0 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('kobesay', 'kobesay')\nrepo.dropCollection('income_infrastructure_ttest')\nrepo.createCollection('income_infrastructure_ttest')\nincome_infrastructure = repo.kobesay.income_infrastructure.find()\nincome_i... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('kobesay', 'kobesay')
repo.dropCollection('income_infrastructure_ttest')
repo.createCollection('income_infrastructure_ttest')
income_infras... | do_ttest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class do_ttest:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happ... | stack_v2_sparse_classes_75kplus_train_074098 | 5,851 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_003396 | Implement the Python class `do_ttest` described below.
Class description:
Implement the do_ttest class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=Non... | Implement the Python class `do_ttest` described below.
Class description:
Implement the do_ttest class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=Non... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class do_ttest:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class do_ttest:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('kobesay', 'kobesay')
repo.dropColl... | the_stack_v2_python_sparse | kobesay/do_ttest.py | lingyigu/course-2017-spr-proj | train | 0 | |
4fef52fd4a8284eee32ba3cbbb312e12e1593df7 | [
"if not builder:\n raise ValueError('Instance builder is not specified')\nself._builder = builder",
"osh = self._builder.buildNoNameInstance(number, hostname, system)\nosh.setContainer(containerOsh)\nreturn osh",
"if not pdo:\n raise ValueError('Instance information is not specified')\nif not containerOsh... | <|body_start_0|>
if not builder:
raise ValueError('Instance builder is not specified')
self._builder = builder
<|end_body_0|>
<|body_start_1|>
osh = self._builder.buildNoNameInstance(number, hostname, system)
osh.setContainer(containerOsh)
return osh
<|end_body_1|>
... | InstanceReporter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceReporter:
def __init__(self, builder):
"""@types: InstanceBuilder"""
<|body_0|>
def reportNoNameInst(self, number, hostname, system, containerOsh):
"""@types: str, str, System, osh -> osh"""
<|body_1|>
def reportInstance(self, pdo, containerOsh):... | stack_v2_sparse_classes_75kplus_train_074099 | 14,040 | no_license | [
{
"docstring": "@types: InstanceBuilder",
"name": "__init__",
"signature": "def __init__(self, builder)"
},
{
"docstring": "@types: str, str, System, osh -> osh",
"name": "reportNoNameInst",
"signature": "def reportNoNameInst(self, number, hostname, system, containerOsh)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_train_014869 | Implement the Python class `InstanceReporter` described below.
Class description:
Implement the InstanceReporter class.
Method signatures and docstrings:
- def __init__(self, builder): @types: InstanceBuilder
- def reportNoNameInst(self, number, hostname, system, containerOsh): @types: str, str, System, osh -> osh
- ... | Implement the Python class `InstanceReporter` described below.
Class description:
Implement the InstanceReporter class.
Method signatures and docstrings:
- def __init__(self, builder): @types: InstanceBuilder
- def reportNoNameInst(self, number, hostname, system, containerOsh): @types: str, str, System, osh -> osh
- ... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class InstanceReporter:
def __init__(self, builder):
"""@types: InstanceBuilder"""
<|body_0|>
def reportNoNameInst(self, number, hostname, system, containerOsh):
"""@types: str, str, System, osh -> osh"""
<|body_1|>
def reportInstance(self, pdo, containerOsh):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstanceReporter:
def __init__(self, builder):
"""@types: InstanceBuilder"""
if not builder:
raise ValueError('Instance builder is not specified')
self._builder = builder
def reportNoNameInst(self, number, hostname, system, containerOsh):
"""@types: str, str, S... | the_stack_v2_python_sparse | reference/ucmdb/discovery/sap_abap.py | madmonkyang/cda-record | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.