blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f163413944d747da568e3daa022813b03070f873 | [
"response = list()\ndata = request.DATA\njson_validate(SPECS.get('vlan_post')).validate(data)\nuser = request.user\nfor vlan in data['vlans']:\n task_obj = tasks.create_vlan.apply_async(args=[vlan, user.id], queue='napi.network')\n task = {'task_id': task_obj.id}\n response.append(task)\nreturn Response(re... | <|body_start_0|>
response = list()
data = request.DATA
json_validate(SPECS.get('vlan_post')).validate(data)
user = request.user
for vlan in data['vlans']:
task_obj = tasks.create_vlan.apply_async(args=[vlan, user.id], queue='napi.network')
task = {'task_id... | VlanAsyncView | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VlanAsyncView:
def post(self, request, *args, **kwargs):
"""Creates list of vlans."""
<|body_0|>
def put(self, request, *args, **kwargs):
"""Updates list of vlans."""
<|body_1|>
def delete(self, request, *args, **kwargs):
"""Deletes list of vlans... | stack_v2_sparse_classes_36k_train_024500 | 6,313 | permissive | [
{
"docstring": "Creates list of vlans.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Updates list of vlans.",
"name": "put",
"signature": "def put(self, request, *args, **kwargs)"
},
{
"docstring": "Deletes list of vlans.",
"name... | 3 | stack_v2_sparse_classes_30k_train_018376 | Implement the Python class `VlanAsyncView` described below.
Class description:
Implement the VlanAsyncView class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Creates list of vlans.
- def put(self, request, *args, **kwargs): Updates list of vlans.
- def delete(self, request, *args, **... | Implement the Python class `VlanAsyncView` described below.
Class description:
Implement the VlanAsyncView class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Creates list of vlans.
- def put(self, request, *args, **kwargs): Updates list of vlans.
- def delete(self, request, *args, **... | eb27e1d977a1c4bb1fee8fb51b8d8050c64696d9 | <|skeleton|>
class VlanAsyncView:
def post(self, request, *args, **kwargs):
"""Creates list of vlans."""
<|body_0|>
def put(self, request, *args, **kwargs):
"""Updates list of vlans."""
<|body_1|>
def delete(self, request, *args, **kwargs):
"""Deletes list of vlans... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VlanAsyncView:
def post(self, request, *args, **kwargs):
"""Creates list of vlans."""
response = list()
data = request.DATA
json_validate(SPECS.get('vlan_post')).validate(data)
user = request.user
for vlan in data['vlans']:
task_obj = tasks.create_vl... | the_stack_v2_python_sparse | networkapi/api_vlan/views/v3.py | globocom/GloboNetworkAPI | train | 86 | |
0ca44ce02b0706ccdc523abe6eb0cef31a720582 | [
"first = second = third = float('-inf')\nfor n in nums:\n if n > first:\n first, second, third = (n, first, third)\n elif first > n > second:\n second, third = (n, second)\n elif second > n > third:\n third = n\n print(first, second, third)\nreturn third if third > float('-inf') els... | <|body_start_0|>
first = second = third = float('-inf')
for n in nums:
if n > first:
first, second, third = (n, first, third)
elif first > n > second:
second, third = (n, second)
elif second > n > third:
third = n
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def thirdMax(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def thirdMax_refer(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
first = second = third = float('-inf')
... | stack_v2_sparse_classes_36k_train_024501 | 1,879 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "thirdMax",
"signature": "def thirdMax(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "thirdMax_refer",
"signature": "def thirdMax_refer(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000035 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def thirdMax(self, nums): :type nums: List[int] :rtype: int
- def thirdMax_refer(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def thirdMax(self, nums): :type nums: List[int] :rtype: int
- def thirdMax_refer(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def thirdMax(se... | f3fc71f344cd758cfce77f16ab72992c99ab288e | <|skeleton|>
class Solution:
def thirdMax(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def thirdMax_refer(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def thirdMax(self, nums):
""":type nums: List[int] :rtype: int"""
first = second = third = float('-inf')
for n in nums:
if n > first:
first, second, third = (n, first, third)
elif first > n > second:
second, third = (n, ... | the_stack_v2_python_sparse | 414_thirdMax.py | jennyChing/leetCode | train | 2 | |
79fb176e5b6772f84a41cfce9d4452b6a6354ff2 | [
"def dfs(root, array):\n if not root:\n array.append('None')\n else:\n array.append(root.val)\n dfs(root.left, array)\n dfs(root.right, array)\n return array\nreturn dfs(root, [])",
"def dfs(data):\n if data[0] == 'None':\n data.pop(0)\n return None\n root ... | <|body_start_0|>
def dfs(root, array):
if not root:
array.append('None')
else:
array.append(root.val)
dfs(root.left, array)
dfs(root.right, array)
return array
return dfs(root, [])
<|end_body_0|>
<|body_... | 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_36k_train_024502 | 1,265 | 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 | null | 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:... | 1bcf3206cd3acc428ec690cb883c612aaf708aac | <|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_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def dfs(root, array):
if not root:
array.append('None')
else:
array.append(root.val)
dfs(root.left, array)
... | the_stack_v2_python_sparse | problem-list/Tree/297.serialize-and-deserialize-binary-tree.py | KevinChen1994/leetcode-algorithm | train | 2 | |
df7de30f0e318bd536ed509e2988a4ff61e781e0 | [
"self._db_update_task = None\nself._is_db_update_completed = False\nself._last_db_update_task_failure = None\nself._when_db_update_completed = None\nself._services = [MessagingService()]\nself._lock = threading.Lock()",
"services_list = []\nwith self._lock:\n is_db_update_completed = self._is_db_update_complet... | <|body_start_0|>
self._db_update_task = None
self._is_db_update_completed = False
self._last_db_update_task_failure = None
self._when_db_update_completed = None
self._services = [MessagingService()]
self._lock = threading.Lock()
<|end_body_0|>
<|body_start_1|>
se... | This class manages all Scale system tasks. This class is thread-safe. | SystemTaskManager | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemTaskManager:
"""This class manages all Scale system tasks. This class is thread-safe."""
def __init__(self):
"""Constructor"""
<|body_0|>
def generate_status_json(self, status_dict):
"""Generates the portion of the status JSON that describes system-level in... | stack_v2_sparse_classes_36k_train_024503 | 4,680 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Generates the portion of the status JSON that describes system-level information :param status_dict: The status JSON dict :type status_dict: dict",
"name": "generate_status_json",
"sign... | 5 | null | Implement the Python class `SystemTaskManager` described below.
Class description:
This class manages all Scale system tasks. This class is thread-safe.
Method signatures and docstrings:
- def __init__(self): Constructor
- def generate_status_json(self, status_dict): Generates the portion of the status JSON that desc... | Implement the Python class `SystemTaskManager` described below.
Class description:
This class manages all Scale system tasks. This class is thread-safe.
Method signatures and docstrings:
- def __init__(self): Constructor
- def generate_status_json(self, status_dict): Generates the portion of the status JSON that desc... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class SystemTaskManager:
"""This class manages all Scale system tasks. This class is thread-safe."""
def __init__(self):
"""Constructor"""
<|body_0|>
def generate_status_json(self, status_dict):
"""Generates the portion of the status JSON that describes system-level in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SystemTaskManager:
"""This class manages all Scale system tasks. This class is thread-safe."""
def __init__(self):
"""Constructor"""
self._db_update_task = None
self._is_db_update_completed = False
self._last_db_update_task_failure = None
self._when_db_update_compl... | the_stack_v2_python_sparse | scale/scheduler/tasks/manager.py | kfconsultant/scale | train | 0 |
5bb142f077e7a28805d934e8b15676ce973ad8c9 | [
"if serialized_batches is not None:\n make_variant_fn = partial(core_ops.io_arrow_serialized_dataset, serialized_batches)\nelif arrow_buffer is None:\n raise ValueError('Must set either serialzied_batches or arrow_buffer')\nelif not tf.executing_eagerly():\n raise ValueError('Using arrow_buffer for zero-co... | <|body_start_0|>
if serialized_batches is not None:
make_variant_fn = partial(core_ops.io_arrow_serialized_dataset, serialized_batches)
elif arrow_buffer is None:
raise ValueError('Must set either serialzied_batches or arrow_buffer')
elif not tf.executing_eagerly():
... | An Arrow Dataset from record batches in memory, or a Pandas DataFrame. | ArrowDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArrowDataset:
"""An Arrow Dataset from record batches in memory, or a Pandas DataFrame."""
def __init__(self, serialized_batches, columns, output_types, output_shapes=None, batch_size=None, batch_mode='keep_remainder', arrow_buffer=None):
"""Create an ArrowDataset from a Tensor of se... | stack_v2_sparse_classes_36k_train_024504 | 27,598 | permissive | [
{
"docstring": "Create an ArrowDataset from a Tensor of serialized batches. This constructor requires pyarrow to be installed. Args: serialized_batches: A string Tensor as a serialized buffer containing Arrow record batches in Arrow File format columns: A list of column indices to be used in the Dataset output_... | 3 | stack_v2_sparse_classes_30k_train_001869 | Implement the Python class `ArrowDataset` described below.
Class description:
An Arrow Dataset from record batches in memory, or a Pandas DataFrame.
Method signatures and docstrings:
- def __init__(self, serialized_batches, columns, output_types, output_shapes=None, batch_size=None, batch_mode='keep_remainder', arrow... | Implement the Python class `ArrowDataset` described below.
Class description:
An Arrow Dataset from record batches in memory, or a Pandas DataFrame.
Method signatures and docstrings:
- def __init__(self, serialized_batches, columns, output_types, output_shapes=None, batch_size=None, batch_mode='keep_remainder', arrow... | e219e295aa6a00b4b749487d56a79c18cc121574 | <|skeleton|>
class ArrowDataset:
"""An Arrow Dataset from record batches in memory, or a Pandas DataFrame."""
def __init__(self, serialized_batches, columns, output_types, output_shapes=None, batch_size=None, batch_mode='keep_remainder', arrow_buffer=None):
"""Create an ArrowDataset from a Tensor of se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArrowDataset:
"""An Arrow Dataset from record batches in memory, or a Pandas DataFrame."""
def __init__(self, serialized_batches, columns, output_types, output_shapes=None, batch_size=None, batch_mode='keep_remainder', arrow_buffer=None):
"""Create an ArrowDataset from a Tensor of serialized batc... | the_stack_v2_python_sparse | tensorflow_io/python/ops/arrow_dataset_ops.py | tensorflow/io | train | 694 |
8ffc9c9751c7c3359485d7cd0d38d0020955f1e8 | [
"self.pid = pid\nself.returnCode = None\nself.done = False\nself.d = threads.deferToThread(self._wait)\nself.d.addCallback(self._on_process_done)\nself.d.addErrback(self._on_process_done)",
"if System.IS_WINDOWS:\n self.returnCode = System.wait_for_pid(self.pid)\n return True\nelse:\n done = False\n w... | <|body_start_0|>
self.pid = pid
self.returnCode = None
self.done = False
self.d = threads.deferToThread(self._wait)
self.d.addCallback(self._on_process_done)
self.d.addErrback(self._on_process_done)
<|end_body_0|>
<|body_start_1|>
if System.IS_WINDOWS:
... | NOTE: linux cannot wait on non-child processes! A class to allow us to pretend that all running processes are Popen objects, even if they aren't. | Process | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Process:
"""NOTE: linux cannot wait on non-child processes! A class to allow us to pretend that all running processes are Popen objects, even if they aren't."""
def __init__(self, pid):
"""Requires the pid of the process to watch."""
<|body_0|>
def _wait(self):
"... | stack_v2_sparse_classes_36k_train_024505 | 2,527 | no_license | [
{
"docstring": "Requires the pid of the process to watch.",
"name": "__init__",
"signature": "def __init__(self, pid)"
},
{
"docstring": "Runs in a Twisted thread, just waiting for the process to finish",
"name": "_wait",
"signature": "def _wait(self)"
},
{
"docstring": "Used as ... | 5 | null | Implement the Python class `Process` described below.
Class description:
NOTE: linux cannot wait on non-child processes! A class to allow us to pretend that all running processes are Popen objects, even if they aren't.
Method signatures and docstrings:
- def __init__(self, pid): Requires the pid of the process to wat... | Implement the Python class `Process` described below.
Class description:
NOTE: linux cannot wait on non-child processes! A class to allow us to pretend that all running processes are Popen objects, even if they aren't.
Method signatures and docstrings:
- def __init__(self, pid): Requires the pid of the process to wat... | a47152d558081a9ebeb5630acfe5f46a49ab4246 | <|skeleton|>
class Process:
"""NOTE: linux cannot wait on non-child processes! A class to allow us to pretend that all running processes are Popen objects, even if they aren't."""
def __init__(self, pid):
"""Requires the pid of the process to watch."""
<|body_0|>
def _wait(self):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Process:
"""NOTE: linux cannot wait on non-child processes! A class to allow us to pretend that all running processes are Popen objects, even if they aren't."""
def __init__(self, pid):
"""Requires the pid of the process to watch."""
self.pid = pid
self.returnCode = None
s... | the_stack_v2_python_sparse | client/common/system/Process.py | clawplach/BitBlinder | train | 0 |
39c40f6306e92855a045c0841c63d574ffe680c0 | [
"binning = '1,1' if hdu is None else self.get_meta_value(self.get_headarr(hdu), 'binning')\ndetector_dict = dict(binning=binning, det=1, dataext=1, specaxis=0, specflip=False, spatflip=False, platescale=0.22, darkcurr=0.0, saturation=65535.0, nonlinear=0.76, mincounts=-10000000000.0, numamplifiers=1, gain=np.atleas... | <|body_start_0|>
binning = '1,1' if hdu is None else self.get_meta_value(self.get_headarr(hdu), 'binning')
detector_dict = dict(binning=binning, det=1, dataext=1, specaxis=0, specflip=False, spatflip=False, platescale=0.22, darkcurr=0.0, saturation=65535.0, nonlinear=0.76, mincounts=-10000000000.0, numa... | Child to handle WHT/ISISr red specific code | WHTISISRedSpectrograph | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WHTISISRedSpectrograph:
"""Child to handle WHT/ISISr red specific code"""
def get_detector_par(self, det, hdu=None):
"""Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with th... | stack_v2_sparse_classes_36k_train_024506 | 16,230 | permissive | [
{
"docstring": "Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with the raw image of interest. If not provided, frame-dependent parameters are set to a default. Returns: :class:`~pypeit.images.detector_... | 4 | stack_v2_sparse_classes_30k_train_020336 | Implement the Python class `WHTISISRedSpectrograph` described below.
Class description:
Child to handle WHT/ISISr red specific code
Method signatures and docstrings:
- def get_detector_par(self, det, hdu=None): Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy... | Implement the Python class `WHTISISRedSpectrograph` described below.
Class description:
Child to handle WHT/ISISr red specific code
Method signatures and docstrings:
- def get_detector_par(self, det, hdu=None): Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy... | 0d2e2196afc6904050b1af4d572f5c643bb07e38 | <|skeleton|>
class WHTISISRedSpectrograph:
"""Child to handle WHT/ISISr red specific code"""
def get_detector_par(self, det, hdu=None):
"""Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WHTISISRedSpectrograph:
"""Child to handle WHT/ISISr red specific code"""
def get_detector_par(self, det, hdu=None):
"""Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with the raw image o... | the_stack_v2_python_sparse | pypeit/spectrographs/wht_isis.py | pypeit/PypeIt | train | 136 |
e04f660e854cf23b02870e606a9ea8a1c0070240 | [
"if init_W is None:\n self.W = np.random.randn(n, m)\nelse:\n self.W = init_W\nif init_B is None:\n self.B = np.zeros((1, m))\nelse:\n self.B = init_B",
"self.X = X\nself.Y = self.B + np.dot(self.X, self.W)\nreturn self.Y",
"dJ_dW = np.dot(self.X.T, dJ_dY)\ndJ_dB = dJ_dY\ndJ_dX = np.dot(dJ_dY, self.... | <|body_start_0|>
if init_W is None:
self.W = np.random.randn(n, m)
else:
self.W = init_W
if init_B is None:
self.B = np.zeros((1, m))
else:
self.B = init_B
<|end_body_0|>
<|body_start_1|>
self.X = X
self.Y = self.B + np.dot... | Couche linéaire dense. Y=WX+B | CoucheDenseLineaire | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoucheDenseLineaire:
"""Couche linéaire dense. Y=WX+B"""
def __init__(self, n, m, init_W=None, init_B=None):
"""Initilalise les paramètres de la couche. W et B sont initialisés avec init_W et init_B lorsque spécifiés. Sinon, des valeurs aléatoires sont générés pour W une distribution... | stack_v2_sparse_classes_36k_train_024507 | 13,175 | no_license | [
{
"docstring": "Initilalise les paramètres de la couche. W et B sont initialisés avec init_W et init_B lorsque spécifiés. Sinon, des valeurs aléatoires sont générés pour W une distribution normale N(0,1) et B est initialisée avec des 0 si les paramètres init_W et init_B ne sont pas spécifiés. n : int, taille du... | 3 | stack_v2_sparse_classes_30k_train_001398 | Implement the Python class `CoucheDenseLineaire` described below.
Class description:
Couche linéaire dense. Y=WX+B
Method signatures and docstrings:
- def __init__(self, n, m, init_W=None, init_B=None): Initilalise les paramètres de la couche. W et B sont initialisés avec init_W et init_B lorsque spécifiés. Sinon, de... | Implement the Python class `CoucheDenseLineaire` described below.
Class description:
Couche linéaire dense. Y=WX+B
Method signatures and docstrings:
- def __init__(self, n, m, init_W=None, init_B=None): Initilalise les paramètres de la couche. W et B sont initialisés avec init_W et init_B lorsque spécifiés. Sinon, de... | fb051d2b627cf43d55944b5f09626eb618de7411 | <|skeleton|>
class CoucheDenseLineaire:
"""Couche linéaire dense. Y=WX+B"""
def __init__(self, n, m, init_W=None, init_B=None):
"""Initilalise les paramètres de la couche. W et B sont initialisés avec init_W et init_B lorsque spécifiés. Sinon, des valeurs aléatoires sont générés pour W une distribution... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CoucheDenseLineaire:
"""Couche linéaire dense. Y=WX+B"""
def __init__(self, n, m, init_W=None, init_B=None):
"""Initilalise les paramètres de la couche. W et B sont initialisés avec init_W et init_B lorsque spécifiés. Sinon, des valeurs aléatoires sont générés pour W une distribution normale N(0,... | the_stack_v2_python_sparse | RNAParCoucheLot.py | RobertGodin/CodePython | train | 0 |
b1c7bd0c25b6456e76be4e4dd33a42ec2539d435 | [
"serializer = LessonDetailSerializer2(data=request.data)\nif serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\nelse:\n return Response(serializer.errors)",
"serializer = LessonDetailSerializer2(data=request.data)\ntemp = Lesson.objects.get(id=pk)\nif serializer.is_valid():\n ... | <|body_start_0|>
serializer = LessonDetailSerializer2(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors)
<|end_body_0|>
<|body_start_1|>
serializer = LessonDetailSer... | StudentLessonListViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudentLessonListViewSet:
def create(self, request):
"""Створення предмету"""
<|body_0|>
def update(self, request, pk):
"""Редагування предмету за айді"""
<|body_1|>
def delete(self, request, pk):
"""Видалення предмету за айді"""
<|body_2... | stack_v2_sparse_classes_36k_train_024508 | 8,171 | no_license | [
{
"docstring": "Створення предмету",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "Редагування предмету за айді",
"name": "update",
"signature": "def update(self, request, pk)"
},
{
"docstring": "Видалення предмету за айді",
"name": "delete",
... | 5 | stack_v2_sparse_classes_30k_val_000676 | Implement the Python class `StudentLessonListViewSet` described below.
Class description:
Implement the StudentLessonListViewSet class.
Method signatures and docstrings:
- def create(self, request): Створення предмету
- def update(self, request, pk): Редагування предмету за айді
- def delete(self, request, pk): Видал... | Implement the Python class `StudentLessonListViewSet` described below.
Class description:
Implement the StudentLessonListViewSet class.
Method signatures and docstrings:
- def create(self, request): Створення предмету
- def update(self, request, pk): Редагування предмету за айді
- def delete(self, request, pk): Видал... | c21c0df4974ff625f78cb967edb86ec18e2d062d | <|skeleton|>
class StudentLessonListViewSet:
def create(self, request):
"""Створення предмету"""
<|body_0|>
def update(self, request, pk):
"""Редагування предмету за айді"""
<|body_1|>
def delete(self, request, pk):
"""Видалення предмету за айді"""
<|body_2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StudentLessonListViewSet:
def create(self, request):
"""Створення предмету"""
serializer = LessonDetailSerializer2(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serialize... | the_stack_v2_python_sparse | OpenEduApi/Lessons/views.py | AkiroToshira/OpenEdu | train | 0 | |
fa56b493c8f0ba1fa99314f211606f6390823b7f | [
"start = 1081827\ncigar = '2557M97N26M1371N135M1126N66M297N96M2755N' + '76=1043N94=425N113=23956N38='\nassert compute_transcript_end(start, cigar) == 1116097",
"start = 203305518\ncigar = '231M1355N1013M1D1504M'\nassert compute_transcript_end(start, cigar) == 203309621",
"start = 167936402\ncigar = '136S114M152... | <|body_start_0|>
start = 1081827
cigar = '2557M97N26M1371N135M1126N66M297N96M2755N' + '76=1043N94=425N113=23956N38='
assert compute_transcript_end(start, cigar) == 1116097
<|end_body_0|>
<|body_start_1|>
start = 203305518
cigar = '231M1355N1013M1D1504M'
assert compute_tr... | TestComputeTranscriptEnd | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestComputeTranscriptEnd:
def test_MN_Only(self):
"""This example (from transcript c3098/f3p2/3199 in GM12878_chr1_clean.sam) contains only M and N operations. The transcript is on the minus strand, but the sequence and CIGAR in BAM are relative to the forward strand."""
<|body_0... | stack_v2_sparse_classes_36k_train_024509 | 2,001 | permissive | [
{
"docstring": "This example (from transcript c3098/f3p2/3199 in GM12878_chr1_clean.sam) contains only M and N operations. The transcript is on the minus strand, but the sequence and CIGAR in BAM are relative to the forward strand.",
"name": "test_MN_Only",
"signature": "def test_MN_Only(self)"
},
{... | 4 | null | Implement the Python class `TestComputeTranscriptEnd` described below.
Class description:
Implement the TestComputeTranscriptEnd class.
Method signatures and docstrings:
- def test_MN_Only(self): This example (from transcript c3098/f3p2/3199 in GM12878_chr1_clean.sam) contains only M and N operations. The transcript ... | Implement the Python class `TestComputeTranscriptEnd` described below.
Class description:
Implement the TestComputeTranscriptEnd class.
Method signatures and docstrings:
- def test_MN_Only(self): This example (from transcript c3098/f3p2/3199 in GM12878_chr1_clean.sam) contains only M and N operations. The transcript ... | 8014faed5f982e5e106ec05239e47d65878e76c3 | <|skeleton|>
class TestComputeTranscriptEnd:
def test_MN_Only(self):
"""This example (from transcript c3098/f3p2/3199 in GM12878_chr1_clean.sam) contains only M and N operations. The transcript is on the minus strand, but the sequence and CIGAR in BAM are relative to the forward strand."""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestComputeTranscriptEnd:
def test_MN_Only(self):
"""This example (from transcript c3098/f3p2/3199 in GM12878_chr1_clean.sam) contains only M and N operations. The transcript is on the minus strand, but the sequence and CIGAR in BAM are relative to the forward strand."""
start = 1081827
... | the_stack_v2_python_sparse | archived/talon_3.0down_testing_suite/test_compute_transcript_end.py | kopardev/TALON | train | 0 | |
d4d6e81a1e4182c269cdaac531e29d97b4ce5c53 | [
"mask_changed = False\nzero_positions = get_zero_positions_in_binary_mask(input_mask_list[0])\nif zero_positions:\n original_out_mask = output_mask_list[0]\n output_mask_list[0] = input_mask_list[0]\n if output_mask_list[0] != original_out_mask:\n mask_changed = True\n logger.debug('Direct Co... | <|body_start_0|>
mask_changed = False
zero_positions = get_zero_positions_in_binary_mask(input_mask_list[0])
if zero_positions:
original_out_mask = output_mask_list[0]
output_mask_list[0] = input_mask_list[0]
if output_mask_list[0] != original_out_mask:
... | Models DIRECT internal connectivity for an Op. | DirectInternalConnectivity | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectInternalConnectivity:
"""Models DIRECT internal connectivity for an Op."""
def forward_propagate_the_masks(self, input_mask_list: List[List[int]], output_mask_list: List[List[int]]) -> bool:
"""Based on the internal connectivity and input mask(s), updates the output mask(s). :p... | stack_v2_sparse_classes_36k_train_024510 | 39,659 | permissive | [
{
"docstring": "Based on the internal connectivity and input mask(s), updates the output mask(s). :param input_mask_list: The input mask(s) to be propagated :param output_mask_list: The output mask(s) to be updated based on the Op's Internal Connectivity",
"name": "forward_propagate_the_masks",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_014748 | Implement the Python class `DirectInternalConnectivity` described below.
Class description:
Models DIRECT internal connectivity for an Op.
Method signatures and docstrings:
- def forward_propagate_the_masks(self, input_mask_list: List[List[int]], output_mask_list: List[List[int]]) -> bool: Based on the internal conne... | Implement the Python class `DirectInternalConnectivity` described below.
Class description:
Models DIRECT internal connectivity for an Op.
Method signatures and docstrings:
- def forward_propagate_the_masks(self, input_mask_list: List[List[int]], output_mask_list: List[List[int]]) -> bool: Based on the internal conne... | 5a406e657082b6a4f6e4bf48f0e46e085cb1e351 | <|skeleton|>
class DirectInternalConnectivity:
"""Models DIRECT internal connectivity for an Op."""
def forward_propagate_the_masks(self, input_mask_list: List[List[int]], output_mask_list: List[List[int]]) -> bool:
"""Based on the internal connectivity and input mask(s), updates the output mask(s). :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DirectInternalConnectivity:
"""Models DIRECT internal connectivity for an Op."""
def forward_propagate_the_masks(self, input_mask_list: List[List[int]], output_mask_list: List[List[int]]) -> bool:
"""Based on the internal connectivity and input mask(s), updates the output mask(s). :param input_ma... | the_stack_v2_python_sparse | TrainingExtensions/common/src/python/aimet_common/winnow/mask.py | quic/aimet | train | 1,676 |
3070ecbfb3bbaf03d8c0c35bfab713000f6f806d | [
"def heapify(nums, root, n):\n left = 2 * root + 1\n right = 2 * root + 2\n if left < n and nums[root] < nums[left]:\n largest = left\n else:\n largest = root\n if right < n and nums[largest] < nums[right]:\n largest = right\n if root != largest:\n nums[root], nums[larg... | <|body_start_0|>
def heapify(nums, root, n):
left = 2 * root + 1
right = 2 * root + 2
if left < n and nums[root] < nums[left]:
largest = left
else:
largest = root
if right < n and nums[largest] < nums[right]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def quicksortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead... | stack_v2_sparse_classes_36k_train_024511 | 4,451 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.",
"name": "qu... | 5 | stack_v2_sparse_classes_30k_train_016578 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.
- def quicksortColors(self, nums): :type nums: List[int] :rty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.
- def quicksortColors(self, nums): :type nums: List[int] :rty... | 8595b04cf5a024c2cd8a97f750d890a818568401 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def quicksortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
def heapify(nums, root, n):
left = 2 * root + 1
right = 2 * root + 2
if left < n and nums[root] < nums[left]:
... | the_stack_v2_python_sparse | python/75.sort-colors.py | tainenko/Leetcode2019 | train | 5 | |
a84e35c21fa897b03e69e27b9b9452dacc46a491 | [
"cls.maxDiff = None\ncls.has_settings = False\ncls.job_types = {'conformers': True, 'opt': True, 'fine_grid': False, 'freq': True, 'sp': True, 'rotors': False, 'irc': False}\ncls.species_list_1 = [ARCSpecies(label='2-propanol', smiles='CC(O)C'), ARCSpecies(label='1-propanol', smiles='CCCO'), ARCSpecies(label='NN', ... | <|body_start_0|>
cls.maxDiff = None
cls.has_settings = False
cls.job_types = {'conformers': True, 'opt': True, 'fine_grid': False, 'freq': True, 'sp': True, 'rotors': False, 'irc': False}
cls.species_list_1 = [ARCSpecies(label='2-propanol', smiles='CC(O)C'), ARCSpecies(label='1-propanol'... | Contains functional tests for ARC. | TestFunctional | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFunctional:
"""Contains functional tests for ARC."""
def setUpClass(cls):
"""A method that is run before all unit tests in this class."""
<|body_0|>
def testThermo(self):
"""Test thermo"""
<|body_1|>
def testKinetic(self):
"""Test kinetic... | stack_v2_sparse_classes_36k_train_024512 | 5,244 | permissive | [
{
"docstring": "A method that is run before all unit tests in this class.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Test thermo",
"name": "testThermo",
"signature": "def testThermo(self)"
},
{
"docstring": "Test kinetics",
"name": "testKine... | 4 | stack_v2_sparse_classes_30k_train_013539 | Implement the Python class `TestFunctional` described below.
Class description:
Contains functional tests for ARC.
Method signatures and docstrings:
- def setUpClass(cls): A method that is run before all unit tests in this class.
- def testThermo(self): Test thermo
- def testKinetic(self): Test kinetics
- def tearDow... | Implement the Python class `TestFunctional` described below.
Class description:
Contains functional tests for ARC.
Method signatures and docstrings:
- def setUpClass(cls): A method that is run before all unit tests in this class.
- def testThermo(self): Test thermo
- def testKinetic(self): Test kinetics
- def tearDow... | 617b2c5430e409271e241eda0de3dd673ec41835 | <|skeleton|>
class TestFunctional:
"""Contains functional tests for ARC."""
def setUpClass(cls):
"""A method that is run before all unit tests in this class."""
<|body_0|>
def testThermo(self):
"""Test thermo"""
<|body_1|>
def testKinetic(self):
"""Test kinetic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFunctional:
"""Contains functional tests for ARC."""
def setUpClass(cls):
"""A method that is run before all unit tests in this class."""
cls.maxDiff = None
cls.has_settings = False
cls.job_types = {'conformers': True, 'opt': True, 'fine_grid': False, 'freq': True, 'sp... | the_stack_v2_python_sparse | functional/functional_test.py | ReactionMechanismGenerator/ARC | train | 40 |
9efb847a581cbc89d8147542307f60526ce16579 | [
"ElementCollection.__init__(self, agent, 'CP.%s' % competence_name)\nself._name = competence_name\nself._elements = elements\nself.log.debug('Created')",
"self.log.debug('Reset')\nfor element in self._elements:\n element.reset()",
"self.log.debug('Fired')\nfor element in self._elements:\n if element.isRea... | <|body_start_0|>
ElementCollection.__init__(self, agent, 'CP.%s' % competence_name)
self._name = competence_name
self._elements = elements
self.log.debug('Created')
<|end_body_0|>
<|body_start_1|>
self.log.debug('Reset')
for element in self._elements:
element... | A competence priority element, containing competence elements. | CompetencePriorityElement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompetencePriorityElement:
"""A competence priority element, containing competence elements."""
def __init__(self, agent, competence_name, elements):
"""Initialises the competence priority element. The log domain is set to [AgentName].CP.[competence_name] @param agent: The element's ... | stack_v2_sparse_classes_36k_train_024513 | 10,006 | no_license | [
{
"docstring": "Initialises the competence priority element. The log domain is set to [AgentName].CP.[competence_name] @param agent: The element's agent. @type agent: L{POSH.strict.Agent} @param competence_name: The name of the competence. @type competence_name: string @param elements: The set of competence ele... | 4 | null | Implement the Python class `CompetencePriorityElement` described below.
Class description:
A competence priority element, containing competence elements.
Method signatures and docstrings:
- def __init__(self, agent, competence_name, elements): Initialises the competence priority element. The log domain is set to [Age... | Implement the Python class `CompetencePriorityElement` described below.
Class description:
A competence priority element, containing competence elements.
Method signatures and docstrings:
- def __init__(self, agent, competence_name, elements): Initialises the competence priority element. The log domain is set to [Age... | ed0907d5172efd5e8752fd989c78cd878e32cb49 | <|skeleton|>
class CompetencePriorityElement:
"""A competence priority element, containing competence elements."""
def __init__(self, agent, competence_name, elements):
"""Initialises the competence priority element. The log domain is set to [AgentName].CP.[competence_name] @param agent: The element's ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompetencePriorityElement:
"""A competence priority element, containing competence elements."""
def __init__(self, agent, competence_name, elements):
"""Initialises the competence priority element. The log domain is set to [AgentName].CP.[competence_name] @param agent: The element's agent. @type ... | the_stack_v2_python_sparse | posh/POSH/strict/competence.py | olrunsrc/fc-public | train | 0 |
34c44257a98ee3941af3424f64baee7f5150444f | [
"if not nums:\n return True\nn = len(nums)\ncount0 = nums.count(nums[0])\nif n % 3 != 0 and count0 == 2 and (self.isHu(nums[2:]) == True):\n return True\nif count0 == 3 and self.isHu(nums[3:]) == True:\n return True\nif nums[0] + 1 in nums and nums[0] + 2 in nums:\n last_nums = nums.copy()\n last_num... | <|body_start_0|>
if not nums:
return True
n = len(nums)
count0 = nums.count(nums[0])
if n % 3 != 0 and count0 == 2 and (self.isHu(nums[2:]) == True):
return True
if count0 == 3 and self.isHu(nums[3:]) == True:
return True
if nums[0] + 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isHu(self, nums):
"""判断是否能胡牌"""
<|body_0|>
def add_card_main(self, array):
"""建立每个元素与数目的字典映射"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return True
n = len(nums)
count0 = nums.count(nums[0]... | stack_v2_sparse_classes_36k_train_024514 | 2,884 | no_license | [
{
"docstring": "判断是否能胡牌",
"name": "isHu",
"signature": "def isHu(self, nums)"
},
{
"docstring": "建立每个元素与数目的字典映射",
"name": "add_card_main",
"signature": "def add_card_main(self, array)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002735 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isHu(self, nums): 判断是否能胡牌
- def add_card_main(self, array): 建立每个元素与数目的字典映射 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isHu(self, nums): 判断是否能胡牌
- def add_card_main(self, array): 建立每个元素与数目的字典映射
<|skeleton|>
class Solution:
def isHu(self, nums):
"""判断是否能胡牌"""
<|body_0|>
... | 4e4f739402b95691f6c91411da26d7d3bfe042b6 | <|skeleton|>
class Solution:
def isHu(self, nums):
"""判断是否能胡牌"""
<|body_0|>
def add_card_main(self, array):
"""建立每个元素与数目的字典映射"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isHu(self, nums):
"""判断是否能胡牌"""
if not nums:
return True
n = len(nums)
count0 = nums.count(nums[0])
if n % 3 != 0 and count0 == 2 and (self.isHu(nums[2:]) == True):
return True
if count0 == 3 and self.isHu(nums[3:]) == True:... | the_stack_v2_python_sparse | Interview/practice/tt_03.雀魂启动.py | hugechuanqi/Algorithms-and-Data-Structures | train | 3 | |
57faac99ec7b0e115389236db36e1ff455913a71 | [
"XmlConfigTools.read_base_UUID_object_xml(p_obj, p_xml)\ntry:\n p_obj.DeviceFamily = PutGetXML.get_text_from_xml(p_xml, 'DeviceFamily')\n p_obj.DeviceType = PutGetXML.get_text_from_xml(p_xml, 'DeviceType')\n p_obj.DeviceSubType = PutGetXML.get_text_from_xml(p_xml, 'DeviceSubType')\n utils.read_room_refe... | <|body_start_0|>
XmlConfigTools.read_base_UUID_object_xml(p_obj, p_xml)
try:
p_obj.DeviceFamily = PutGetXML.get_text_from_xml(p_xml, 'DeviceFamily')
p_obj.DeviceType = PutGetXML.get_text_from_xml(p_xml, 'DeviceType')
p_obj.DeviceSubType = PutGetXML.get_text_from_xml(p... | XML | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XML:
def read_base_device_object_xml(p_obj, p_xml):
"""Get the BaseUUIDObject entries from the XML element. Adds: Device Info, Room Info. @param p_obj: is the object we wish to populate with data @param p_xml: is the element we will extract data from (including children)."""
<|bo... | stack_v2_sparse_classes_36k_train_024515 | 2,452 | no_license | [
{
"docstring": "Get the BaseUUIDObject entries from the XML element. Adds: Device Info, Room Info. @param p_obj: is the object we wish to populate with data @param p_xml: is the element we will extract data from (including children).",
"name": "read_base_device_object_xml",
"signature": "def read_base_d... | 2 | stack_v2_sparse_classes_30k_train_012244 | Implement the Python class `XML` described below.
Class description:
Implement the XML class.
Method signatures and docstrings:
- def read_base_device_object_xml(p_obj, p_xml): Get the BaseUUIDObject entries from the XML element. Adds: Device Info, Room Info. @param p_obj: is the object we wish to populate with data ... | Implement the Python class `XML` described below.
Class description:
Implement the XML class.
Method signatures and docstrings:
- def read_base_device_object_xml(p_obj, p_xml): Get the BaseUUIDObject entries from the XML element. Adds: Device Info, Room Info. @param p_obj: is the object we wish to populate with data ... | 8ccbbd1494b7b33ff5099d321cda634fbb254ceb | <|skeleton|>
class XML:
def read_base_device_object_xml(p_obj, p_xml):
"""Get the BaseUUIDObject entries from the XML element. Adds: Device Info, Room Info. @param p_obj: is the object we wish to populate with data @param p_xml: is the element we will extract data from (including children)."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XML:
def read_base_device_object_xml(p_obj, p_xml):
"""Get the BaseUUIDObject entries from the XML element. Adds: Device Info, Room Info. @param p_obj: is the object we wish to populate with data @param p_xml: is the element we will extract data from (including children)."""
XmlConfigTools.rea... | the_stack_v2_python_sparse | Project/src/Modules/Core/Utilities/device_tools.py | bopopescu/PyHouse | train | 0 | |
33f01f6a41f63f4a22c9c3457d71ed2d44853e5e | [
"super(TriggerVelocity, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._actor = actor\nself._target_velocity = target_velocity",
"new_status = py_trees.common.Status.RUNNING\ndelta_velocity = self._target_velocity - CarlaDataProvider.get_velocity(self._actor)\nif delta_ve... | <|body_start_0|>
super(TriggerVelocity, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._actor = actor
self._target_velocity = target_velocity
<|end_body_0|>
<|body_start_1|>
new_status = py_trees.common.Status.RUNNING
delta_velocit... | This class contains the trigger velocity (condition) of a scenario The behavior is successful, if the actor is at least as fast as requested | TriggerVelocity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriggerVelocity:
"""This class contains the trigger velocity (condition) of a scenario The behavior is successful, if the actor is at least as fast as requested"""
def __init__(self, actor, target_velocity, name='TriggerVelocity'):
"""Setup trigger velocity"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_024516 | 25,380 | permissive | [
{
"docstring": "Setup trigger velocity",
"name": "__init__",
"signature": "def __init__(self, actor, target_velocity, name='TriggerVelocity')"
},
{
"docstring": "Check if the actor has the trigger velocity",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010277 | Implement the Python class `TriggerVelocity` described below.
Class description:
This class contains the trigger velocity (condition) of a scenario The behavior is successful, if the actor is at least as fast as requested
Method signatures and docstrings:
- def __init__(self, actor, target_velocity, name='TriggerVelo... | Implement the Python class `TriggerVelocity` described below.
Class description:
This class contains the trigger velocity (condition) of a scenario The behavior is successful, if the actor is at least as fast as requested
Method signatures and docstrings:
- def __init__(self, actor, target_velocity, name='TriggerVelo... | 1d3e8339f8e60f7bdcaefeff49ec238b1746b047 | <|skeleton|>
class TriggerVelocity:
"""This class contains the trigger velocity (condition) of a scenario The behavior is successful, if the actor is at least as fast as requested"""
def __init__(self, actor, target_velocity, name='TriggerVelocity'):
"""Setup trigger velocity"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TriggerVelocity:
"""This class contains the trigger velocity (condition) of a scenario The behavior is successful, if the actor is at least as fast as requested"""
def __init__(self, actor, target_velocity, name='TriggerVelocity'):
"""Setup trigger velocity"""
super(TriggerVelocity, self)... | the_stack_v2_python_sparse | srunner/scenariomanager/atomic_scenario_behavior.py | chauvinSimon/scenario_runner | train | 2 |
4d04000bbfd7b31da67ec881d1b5c193611892ad | [
"self.args = args = self.args.strip().lower()\nrecipe, ingredients, tools = ('', '', '')\nif 'from' in args:\n recipe, *rest = args.split(' from ', 1)\n rest = rest[0] if rest else ''\n ingredients, *tools = rest.split(' using ', 1)\nelif 'using' in args:\n recipe, *tools = args.split(' using ', 1)\ntoo... | <|body_start_0|>
self.args = args = self.args.strip().lower()
recipe, ingredients, tools = ('', '', '')
if 'from' in args:
recipe, *rest = args.split(' from ', 1)
rest = rest[0] if rest else ''
ingredients, *tools = rest.split(' using ', 1)
elif 'using... | Craft an item using ingredients and tools Usage: craft <recipe> [from <ingredient>,...] [using <tool>, ...] Examples: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, bowl, roller craft fireball using wand, spellbook Notes: Ingredients must be... | CmdCraft | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CmdCraft:
"""Craft an item using ingredients and tools Usage: craft <recipe> [from <ingredient>,...] [using <tool>, ...] Examples: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, bowl, roller craft fireball using wand, ... | stack_v2_sparse_classes_36k_train_024517 | 41,597 | permissive | [
{
"docstring": "Handle parsing of: :: <recipe> [FROM <ingredients>] [USING <tools>] Examples: :: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, bowl, roller craft fireball using wand, spellbook",
"name": "parse",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_020467 | Implement the Python class `CmdCraft` described below.
Class description:
Craft an item using ingredients and tools Usage: craft <recipe> [from <ingredient>,...] [using <tool>, ...] Examples: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, b... | Implement the Python class `CmdCraft` described below.
Class description:
Craft an item using ingredients and tools Usage: craft <recipe> [from <ingredient>,...] [using <tool>, ...] Examples: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, b... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class CmdCraft:
"""Craft an item using ingredients and tools Usage: craft <recipe> [from <ingredient>,...] [using <tool>, ...] Examples: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, bowl, roller craft fireball using wand, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CmdCraft:
"""Craft an item using ingredients and tools Usage: craft <recipe> [from <ingredient>,...] [using <tool>, ...] Examples: craft snowball from snow craft puppet from piece of wood using knife craft bread from flour, butter, water, yeast using owen, bowl, roller craft fireball using wand, spellbook Not... | the_stack_v2_python_sparse | evennia/contrib/game_systems/crafting/crafting.py | evennia/evennia | train | 1,781 |
775c4e98a11283314c39bc56d3be0b1b42ab3c1d | [
"re = ''\nself.d[self.idx] = longUrl\nn = self.idx\nwhile n:\n re += self.code[n % 62]\n n /= 62\nself.idx += 1\nreturn re",
"i = 0\nfor x in shortUrl:\n if 'a' <= x <= 'z':\n i = i * 62 + ord(x) - ord('a')\n elif 'A' <= x <= 'Z':\n i = i * 62 + ord(x) - ord('A') + 26\n else:\n ... | <|body_start_0|>
re = ''
self.d[self.idx] = longUrl
n = self.idx
while n:
re += self.code[n % 62]
n /= 62
self.idx += 1
return re
<|end_body_0|>
<|body_start_1|>
i = 0
for x in shortUrl:
if 'a' <= x <= 'z':
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_024518 | 1,069 | no_license | [
{
"docstring": "Encodes a URL to a shortened URL. :type longUrl: str :rtype: str",
"name": "encode",
"signature": "def encode(self, longUrl)"
},
{
"docstring": "Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str",
"name": "decode",
"signature": "def decode(self,... | 2 | stack_v2_sparse_classes_30k_train_016792 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | 20623defecf65cbc35b194d8b60d8b211816ee4f | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
re = ''
self.d[self.idx] = longUrl
n = self.idx
while n:
re += self.code[n % 62]
n /= 62
self.idx += 1
return re
def dec... | the_stack_v2_python_sparse | in_Python/0535 Encode and Decode TinyURL.py | YangLiyli131/Leetcode2020 | train | 0 | |
0538a9ca72119847168c6aac82aa7df1b261d462 | [
"user_id = uid\nride_request_ref = RideRequestGenericDao().rideRequestCollectionRef.document(rideRequestId)\nride_request = RideRequestGenericDao().get(ride_request_ref)\nprint('userId: {}, rideRequestId: {}'.format(user_id, rideRequestId))\nresponse_dict = ride_request.to_dict_view()['baggages']\nreturn (response_... | <|body_start_0|>
user_id = uid
ride_request_ref = RideRequestGenericDao().rideRequestCollectionRef.document(rideRequestId)
ride_request = RideRequestGenericDao().get(ride_request_ref)
print('userId: {}, rideRequestId: {}'.format(user_id, rideRequestId))
response_dict = ride_reque... | /rideRequest/:rideRequestId/luggage/ | LuggageService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LuggageService:
"""/rideRequest/:rideRequestId/luggage/"""
def get(self, rideRequestId, uid):
"""Get the JSON for the luggage associatedd with ride request :param rideRequestId: :param uid: :return:"""
<|body_0|>
def put(self, rideRequestId, uid):
""":param rideR... | stack_v2_sparse_classes_36k_train_024519 | 6,960 | no_license | [
{
"docstring": "Get the JSON for the luggage associatedd with ride request :param rideRequestId: :param uid: :return:",
"name": "get",
"signature": "def get(self, rideRequestId, uid)"
},
{
"docstring": ":param rideRequestId: :param uid: :return:",
"name": "put",
"signature": "def put(sel... | 2 | stack_v2_sparse_classes_30k_train_012017 | Implement the Python class `LuggageService` described below.
Class description:
/rideRequest/:rideRequestId/luggage/
Method signatures and docstrings:
- def get(self, rideRequestId, uid): Get the JSON for the luggage associatedd with ride request :param rideRequestId: :param uid: :return:
- def put(self, rideRequestI... | Implement the Python class `LuggageService` described below.
Class description:
/rideRequest/:rideRequestId/luggage/
Method signatures and docstrings:
- def get(self, rideRequestId, uid): Get the JSON for the luggage associatedd with ride request :param rideRequestId: :param uid: :return:
- def put(self, rideRequestI... | ff6b4d99764d2b9cc1a100489e4a0bce7aa69e2d | <|skeleton|>
class LuggageService:
"""/rideRequest/:rideRequestId/luggage/"""
def get(self, rideRequestId, uid):
"""Get the JSON for the luggage associatedd with ride request :param rideRequestId: :param uid: :return:"""
<|body_0|>
def put(self, rideRequestId, uid):
""":param rideR... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LuggageService:
"""/rideRequest/:rideRequestId/luggage/"""
def get(self, rideRequestId, uid):
"""Get the JSON for the luggage associatedd with ride request :param rideRequestId: :param uid: :return:"""
user_id = uid
ride_request_ref = RideRequestGenericDao().rideRequestCollectionR... | the_stack_v2_python_sparse | gravitate/api_server/ride_request/services.py | lw75251/Gravitate-Backend | train | 1 |
b65d05b115860dda9377cd9da396bf67eb5f016a | [
"super().__init__()\nself.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)\nself.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)\nself.linear = tf.keras.layers.Dense(target_vocab)",
"enc_output = self.encoder(inputs, training, encoder_mask)\ndec_output = self... | <|body_start_0|>
super().__init__()
self.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)
self.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)
self.linear = tf.keras.layers.Dense(target_vocab)
<|end_body_0|>
<|body_start_1|>
... | Class transformer | Transformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""Class transformer"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""ARGS: -N - the number of blocks in the encoder and decoder -dm - the dimensionality of the model -h - the number of heads -hidden - t... | stack_v2_sparse_classes_36k_train_024520 | 2,562 | no_license | [
{
"docstring": "ARGS: -N - the number of blocks in the encoder and decoder -dm - the dimensionality of the model -h - the number of heads -hidden - the number of hidden units in the fully connected layers -input_vocab - the size of the input vocabulary -target_vocab - the size of the target vocabulary -max_seq_... | 2 | stack_v2_sparse_classes_30k_train_014445 | Implement the Python class `Transformer` described below.
Class description:
Class transformer
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): ARGS: -N - the number of blocks in the encoder and decoder -dm - the dimensi... | Implement the Python class `Transformer` described below.
Class description:
Class transformer
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): ARGS: -N - the number of blocks in the encoder and decoder -dm - the dimensi... | 7dafc37d306fcf2ea0f5af5bd97dfd78d388100c | <|skeleton|>
class Transformer:
"""Class transformer"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""ARGS: -N - the number of blocks in the encoder and decoder -dm - the dimensionality of the model -h - the number of heads -hidden - t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transformer:
"""Class transformer"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""ARGS: -N - the number of blocks in the encoder and decoder -dm - the dimensionality of the model -h - the number of heads -hidden - the number of ... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/11-transformer.py | AndresSern/holbertonschool-machine_learning-1 | train | 0 |
fad82d9b83f6f23d647de771f1a132ad23bc9ecb | [
"di_eo = (data_container._ids, data_container.data_inputs, data_container.expected_outputs)\nnew_ids, new_data_inputs, new_expected_outputs = self.transform(di_eo)\ndata_container.set_data_inputs((new_ids, new_data_inputs, new_expected_outputs))\nreturn data_container",
"new_self = self.fit((data_container._ids, ... | <|body_start_0|>
di_eo = (data_container._ids, data_container.data_inputs, data_container.expected_outputs)
new_ids, new_data_inputs, new_expected_outputs = self.transform(di_eo)
data_container.set_data_inputs((new_ids, new_data_inputs, new_expected_outputs))
return data_container
<|end_... | Base output transformer step that can modify ids, data inputs, and expected_outputs at the same time. | IdsAndInputAndOutputTransformerMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdsAndInputAndOutputTransformerMixin:
"""Base output transformer step that can modify ids, data inputs, and expected_outputs at the same time."""
def _transform_data_container(self, data_container: DACT, context: CX) -> DACT:
"""Handle inverse transform by updating the data inputs, a... | stack_v2_sparse_classes_36k_train_024521 | 13,057 | permissive | [
{
"docstring": "Handle inverse transform by updating the data inputs, and expected outputs inside the data container. :param context: execution context :param data_container: :return:",
"name": "_transform_data_container",
"signature": "def _transform_data_container(self, data_container: DACT, context: ... | 3 | stack_v2_sparse_classes_30k_train_004226 | Implement the Python class `IdsAndInputAndOutputTransformerMixin` described below.
Class description:
Base output transformer step that can modify ids, data inputs, and expected_outputs at the same time.
Method signatures and docstrings:
- def _transform_data_container(self, data_container: DACT, context: CX) -> DACT... | Implement the Python class `IdsAndInputAndOutputTransformerMixin` described below.
Class description:
Base output transformer step that can modify ids, data inputs, and expected_outputs at the same time.
Method signatures and docstrings:
- def _transform_data_container(self, data_container: DACT, context: CX) -> DACT... | af917c984241178436a759be3b830e6d8b03245f | <|skeleton|>
class IdsAndInputAndOutputTransformerMixin:
"""Base output transformer step that can modify ids, data inputs, and expected_outputs at the same time."""
def _transform_data_container(self, data_container: DACT, context: CX) -> DACT:
"""Handle inverse transform by updating the data inputs, a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdsAndInputAndOutputTransformerMixin:
"""Base output transformer step that can modify ids, data inputs, and expected_outputs at the same time."""
def _transform_data_container(self, data_container: DACT, context: CX) -> DACT:
"""Handle inverse transform by updating the data inputs, and expected o... | the_stack_v2_python_sparse | neuraxle/steps/output_handlers.py | Neuraxio/Neuraxle | train | 597 |
b43904996bf497d2d6b1728a9f411135ed9c2e61 | [
"super().__init__(unique_id, model)\nself.pos = np.array(pos)\nself.speed = speed\nself.velocity = velocity\nself.vision = vision\nself.separation = separation\nself.cohere_factor = cohere\nself.separate_factor = separate\nself.match_factor = match\nself.tag = tag",
"cohere = np.zeros(2)\nother_fish = [n for n in... | <|body_start_0|>
super().__init__(unique_id, model)
self.pos = np.array(pos)
self.speed = speed
self.velocity = velocity
self.vision = vision
self.separation = separation
self.cohere_factor = cohere
self.separate_factor = separate
self.match_factor... | A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance from any other Boid. | Fish | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fish:
"""A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance fr... | stack_v2_sparse_classes_36k_train_024522 | 12,295 | no_license | [
{
"docstring": "Create a new Boid (bird, fish) agent. Args: unique_id: Unique agent identifier. pos: Starting position speed: Distance to move per step. velocity: numpy vector for the Boid's direction of movement. vision: Radius to look around for nearby Boids. separation: Minimum distance to maintain from othe... | 6 | stack_v2_sparse_classes_30k_val_000612 | Implement the Python class `Fish` described below.
Class description:
A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separati... | Implement the Python class `Fish` described below.
Class description:
A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separati... | 18166af285d2a40f903bc178f5c37b7d758fb0bd | <|skeleton|>
class Fish:
"""A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance fr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fish:
"""A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance from any other ... | the_stack_v2_python_sparse | shoal_model.py | sowasser/fish-shoaling-model | train | 1 |
2bcf0cc7e7c6718e9d8bfec07058cb2e656241a4 | [
"n = len(nums)\nfor i in range(n):\n nums[nums[i] % (n + 1) - 1] += n + 1\ndissappeared = []\nfor i in range(n):\n if nums[i] / (n + 1) == 2:\n dissappeared.append(i + 1)\nreturn dissappeared",
"res = []\nfor x in nums:\n if nums[abs(x) - 1] < 0:\n res.append(abs(x))\n else:\n num... | <|body_start_0|>
n = len(nums)
for i in range(n):
nums[nums[i] % (n + 1) - 1] += n + 1
dissappeared = []
for i in range(n):
if nums[i] / (n + 1) == 2:
dissappeared.append(i + 1)
return dissappeared
<|end_body_0|>
<|body_start_1|>
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDisappearedNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findDuplicates(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
... | stack_v2_sparse_classes_36k_train_024523 | 1,575 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findDisappearedNumbers",
"signature": "def findDisappearedNumbers(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findDuplicates",
"signature": "def findDuplicates(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020305 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDisappearedNumbers(self, nums): :type nums: List[int] :rtype: List[int]
- def findDuplicates(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDisappearedNumbers(self, nums): :type nums: List[int] :rtype: List[int]
- def findDuplicates(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class Solu... | 058b6d6139a0d9b019547ae7b53a4e74fa114a8b | <|skeleton|>
class Solution:
def findDisappearedNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findDuplicates(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDisappearedNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
n = len(nums)
for i in range(n):
nums[nums[i] % (n + 1) - 1] += n + 1
dissappeared = []
for i in range(n):
if nums[i] / (n + 1) == 2:
... | the_stack_v2_python_sparse | 01_Arrays/442_Number_Duplicates/NumberDuplicates.py | dtran39/Programming_Preparation | train | 0 | |
36689514b90c50c01e5ba943d41560a44b93c2d6 | [
"self.current = 0\nself.accumToIndex = {}\nself.accum = []\nfor i, num in enumerate(w):\n self.current += num\n self.accum.append(self.current)\n self.accumToIndex[self.current] = i",
"randomNum = random.randint(1, self.current)\nl, r = (0, len(self.accum) - 1)\nwhile l < r:\n m = (l + r) / 2\n if ... | <|body_start_0|>
self.current = 0
self.accumToIndex = {}
self.accum = []
for i, num in enumerate(w):
self.current += num
self.accum.append(self.current)
self.accumToIndex[self.current] = i
<|end_body_0|>
<|body_start_1|>
randomNum = random.ran... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.current = 0
self.accumToIndex = {}
self.accum = []
for i, num in en... | stack_v2_sparse_classes_36k_train_024524 | 1,254 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013403 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 76d767ec001649b2df07aac211ac4b43b415ebdd | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.current = 0
self.accumToIndex = {}
self.accum = []
for i, num in enumerate(w):
self.current += num
self.accum.append(self.current)
self.accumToIndex[self.current] = i
... | the_stack_v2_python_sparse | leetcode528 Random Pick with Weight.py | whglamrock/leetcode_series | train | 2 | |
86f97b8c054208f2634d85aefbfb0843e3b78bc1 | [
"from evdev import InputDevice\nself.dev = InputDevice(device_descriptor)\nthreading.Thread.__init__(self)\nself.stopped = threading.Event()\nself.hass = hass\nself.key_value = key_value",
"from evdev import categorize, ecodes\n_LOGGER.debug('KeyboardRemote interface started for %s', self.dev)\nself.dev.grab()\nw... | <|body_start_0|>
from evdev import InputDevice
self.dev = InputDevice(device_descriptor)
threading.Thread.__init__(self)
self.stopped = threading.Event()
self.hass = hass
self.key_value = key_value
<|end_body_0|>
<|body_start_1|>
from evdev import categorize, eco... | This interfaces with the inputdevice using evdev. | KeyboardRemote | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyboardRemote:
"""This interfaces with the inputdevice using evdev."""
def __init__(self, hass, device_descriptor, key_value):
"""Construct a KeyboardRemote interface object."""
<|body_0|>
def run(self):
"""Main loop of the KeyboardRemote."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_024525 | 3,867 | permissive | [
{
"docstring": "Construct a KeyboardRemote interface object.",
"name": "__init__",
"signature": "def __init__(self, hass, device_descriptor, key_value)"
},
{
"docstring": "Main loop of the KeyboardRemote.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013137 | Implement the Python class `KeyboardRemote` described below.
Class description:
This interfaces with the inputdevice using evdev.
Method signatures and docstrings:
- def __init__(self, hass, device_descriptor, key_value): Construct a KeyboardRemote interface object.
- def run(self): Main loop of the KeyboardRemote. | Implement the Python class `KeyboardRemote` described below.
Class description:
This interfaces with the inputdevice using evdev.
Method signatures and docstrings:
- def __init__(self, hass, device_descriptor, key_value): Construct a KeyboardRemote interface object.
- def run(self): Main loop of the KeyboardRemote.
... | ca0e92aba83de2fd6cb1cc4d14f3b4471f17cf3d | <|skeleton|>
class KeyboardRemote:
"""This interfaces with the inputdevice using evdev."""
def __init__(self, hass, device_descriptor, key_value):
"""Construct a KeyboardRemote interface object."""
<|body_0|>
def run(self):
"""Main loop of the KeyboardRemote."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeyboardRemote:
"""This interfaces with the inputdevice using evdev."""
def __init__(self, hass, device_descriptor, key_value):
"""Construct a KeyboardRemote interface object."""
from evdev import InputDevice
self.dev = InputDevice(device_descriptor)
threading.Thread.__ini... | the_stack_v2_python_sparse | homeassistant/components/keyboard_remote.py | Smart-Torvy/torvy-home-assistant | train | 2 |
5848cf562da9013ac09021dc63198d1b28e7268b | [
"self.id = id\nself.raw_policy_str = raw_policy_str\nself.statement_vec = statement_vec\nself.version = version",
"if dictionary is None:\n return None\nid = dictionary.get('id')\nraw_policy_str = dictionary.get('rawPolicyStr')\nstatement_vec = None\nif dictionary.get('statementVec') != None:\n statement_ve... | <|body_start_0|>
self.id = id
self.raw_policy_str = raw_policy_str
self.statement_vec = statement_vec
self.version = version
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
id = dictionary.get('id')
raw_policy_str = dictionary.get('... | Implementation of the 'BucketPolicy' model. TODO: type description here. Attributes: id (string): The identifier for the bucket policy. raw_policy_str (string): Raw JSON string of the stored policy. statement_vec (list of Statement): This field defines the statement to execute for each request. version (string): This f... | BucketPolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BucketPolicy:
"""Implementation of the 'BucketPolicy' model. TODO: type description here. Attributes: id (string): The identifier for the bucket policy. raw_policy_str (string): Raw JSON string of the stored policy. statement_vec (list of Statement): This field defines the statement to execute fo... | stack_v2_sparse_classes_36k_train_024526 | 2,411 | permissive | [
{
"docstring": "Constructor for the BucketPolicy class",
"name": "__init__",
"signature": "def __init__(self, id=None, raw_policy_str=None, statement_vec=None, version=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary repres... | 2 | stack_v2_sparse_classes_30k_train_009392 | Implement the Python class `BucketPolicy` described below.
Class description:
Implementation of the 'BucketPolicy' model. TODO: type description here. Attributes: id (string): The identifier for the bucket policy. raw_policy_str (string): Raw JSON string of the stored policy. statement_vec (list of Statement): This fi... | Implement the Python class `BucketPolicy` described below.
Class description:
Implementation of the 'BucketPolicy' model. TODO: type description here. Attributes: id (string): The identifier for the bucket policy. raw_policy_str (string): Raw JSON string of the stored policy. statement_vec (list of Statement): This fi... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class BucketPolicy:
"""Implementation of the 'BucketPolicy' model. TODO: type description here. Attributes: id (string): The identifier for the bucket policy. raw_policy_str (string): Raw JSON string of the stored policy. statement_vec (list of Statement): This field defines the statement to execute fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BucketPolicy:
"""Implementation of the 'BucketPolicy' model. TODO: type description here. Attributes: id (string): The identifier for the bucket policy. raw_policy_str (string): Raw JSON string of the stored policy. statement_vec (list of Statement): This field defines the statement to execute for each reques... | the_stack_v2_python_sparse | cohesity_management_sdk/models/bucket_policy.py | cohesity/management-sdk-python | train | 24 |
ea7efa50be86af5da879c21c491a699497fe0adb | [
"from fcntl import fcntl, F_GETFL, F_SETFL\nfrom subprocess import Popen, PIPE\nimport os\nself._command = command\nself._executable = command.split(' ', 1)[0]\n_Log.debug('Starting the interactive process: {}'.format(command))\nself._process = Popen(command, shell=True, stdout=PIPE, stdin=PIPE, stderr=PIPE)\nfcntl... | <|body_start_0|>
from fcntl import fcntl, F_GETFL, F_SETFL
from subprocess import Popen, PIPE
import os
self._command = command
self._executable = command.split(' ', 1)[0]
_Log.debug('Starting the interactive process: {}'.format(command))
self._process = Popen(com... | Class representing an object that interacts with a binary multiple times | InteractiveProcess | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InteractiveProcess:
"""Class representing an object that interacts with a binary multiple times"""
def __init__(self, command):
"""Creates an interactive process to interact with out of a command :param str command: the command to be executed"""
<|body_0|>
def write(self... | stack_v2_sparse_classes_36k_train_024527 | 15,038 | permissive | [
{
"docstring": "Creates an interactive process to interact with out of a command :param str command: the command to be executed",
"name": "__init__",
"signature": "def __init__(self, command)"
},
{
"docstring": "Writes a command into the interactive process :param str command: the command to be ... | 5 | stack_v2_sparse_classes_30k_train_011910 | Implement the Python class `InteractiveProcess` described below.
Class description:
Class representing an object that interacts with a binary multiple times
Method signatures and docstrings:
- def __init__(self, command): Creates an interactive process to interact with out of a command :param str command: the command... | Implement the Python class `InteractiveProcess` described below.
Class description:
Class representing an object that interacts with a binary multiple times
Method signatures and docstrings:
- def __init__(self, command): Creates an interactive process to interact with out of a command :param str command: the command... | dd393666aa1ba1117d1c472cfdef4d0b18216904 | <|skeleton|>
class InteractiveProcess:
"""Class representing an object that interacts with a binary multiple times"""
def __init__(self, command):
"""Creates an interactive process to interact with out of a command :param str command: the command to be executed"""
<|body_0|>
def write(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InteractiveProcess:
"""Class representing an object that interacts with a binary multiple times"""
def __init__(self, command):
"""Creates an interactive process to interact with out of a command :param str command: the command to be executed"""
from fcntl import fcntl, F_GETFL, F_SETFL
... | the_stack_v2_python_sparse | scrounger/utils/general.py | exploit-inters/scrounger | train | 0 |
dd244386849e8f425040fea84b25bf9e3109698d | [
"self.log = logging.getLogger('PololuServo')\nself.number = number\nself.controller_number = controller_number\nself.config = config\nself.serial = serial_port\nself.cmd_header = bytes([170, self.controller_number])",
"cmd = self.cmd_header + bytes([34, self.number])\nif self.config['debug']:\n self.log.debug(... | <|body_start_0|>
self.log = logging.getLogger('PololuServo')
self.number = number
self.controller_number = controller_number
self.config = config
self.serial = serial_port
self.cmd_header = bytes([170, self.controller_number])
<|end_body_0|>
<|body_start_1|>
cmd ... | A servo on the pololu servo controller. | PololuServo | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PololuServo:
"""A servo on the pololu servo controller."""
def __init__(self, controller_number, number, config, serial_port):
"""Initialise Pololu servo."""
<|body_0|>
def stop(self):
"""Disable servo. Send the Go Home command which will disable the servo."""
... | stack_v2_sparse_classes_36k_train_024528 | 7,030 | permissive | [
{
"docstring": "Initialise Pololu servo.",
"name": "__init__",
"signature": "def __init__(self, controller_number, number, config, serial_port)"
},
{
"docstring": "Disable servo. Send the Go Home command which will disable the servo.",
"name": "stop",
"signature": "def stop(self)"
},
... | 5 | null | Implement the Python class `PololuServo` described below.
Class description:
A servo on the pololu servo controller.
Method signatures and docstrings:
- def __init__(self, controller_number, number, config, serial_port): Initialise Pololu servo.
- def stop(self): Disable servo. Send the Go Home command which will dis... | Implement the Python class `PololuServo` described below.
Class description:
A servo on the pololu servo controller.
Method signatures and docstrings:
- def __init__(self, controller_number, number, config, serial_port): Initialise Pololu servo.
- def stop(self): Disable servo. Send the Go Home command which will dis... | 9f90c8b1586363b65340017bfa3af5d56d32c6d9 | <|skeleton|>
class PololuServo:
"""A servo on the pololu servo controller."""
def __init__(self, controller_number, number, config, serial_port):
"""Initialise Pololu servo."""
<|body_0|>
def stop(self):
"""Disable servo. Send the Go Home command which will disable the servo."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PololuServo:
"""A servo on the pololu servo controller."""
def __init__(self, controller_number, number, config, serial_port):
"""Initialise Pololu servo."""
self.log = logging.getLogger('PololuServo')
self.number = number
self.controller_number = controller_number
... | the_stack_v2_python_sparse | mpf/platforms/pololu_maestro.py | missionpinball/mpf | train | 191 |
cacb6ec8145bcd9298c91b9adfea0e97439b6fc1 | [
"assert self.user_id is not None\nassert self.normalized_payload is not None\nusername = self.normalized_payload['username']\nrole = self.normalized_payload['role']\nuser_id = user_services.get_user_id_from_username(username)\nif user_id is None:\n raise self.InvalidInputException('User with given username does ... | <|body_start_0|>
assert self.user_id is not None
assert self.normalized_payload is not None
username = self.normalized_payload['username']
role = self.normalized_payload['role']
user_id = user_services.get_user_id_from_username(username)
if user_id is None:
ra... | Handler for the blog admin page. | BlogAdminRolesHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlogAdminRolesHandler:
"""Handler for the blog admin page."""
def post(self) -> None:
"""Handles POST requests."""
<|body_0|>
def put(self) -> None:
"""Handles PUT requests."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
assert self.user_id is ... | stack_v2_sparse_classes_36k_train_024529 | 8,179 | permissive | [
{
"docstring": "Handles POST requests.",
"name": "post",
"signature": "def post(self) -> None"
},
{
"docstring": "Handles PUT requests.",
"name": "put",
"signature": "def put(self) -> None"
}
] | 2 | null | Implement the Python class `BlogAdminRolesHandler` described below.
Class description:
Handler for the blog admin page.
Method signatures and docstrings:
- def post(self) -> None: Handles POST requests.
- def put(self) -> None: Handles PUT requests. | Implement the Python class `BlogAdminRolesHandler` described below.
Class description:
Handler for the blog admin page.
Method signatures and docstrings:
- def post(self) -> None: Handles POST requests.
- def put(self) -> None: Handles PUT requests.
<|skeleton|>
class BlogAdminRolesHandler:
"""Handler for the bl... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class BlogAdminRolesHandler:
"""Handler for the blog admin page."""
def post(self) -> None:
"""Handles POST requests."""
<|body_0|>
def put(self) -> None:
"""Handles PUT requests."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlogAdminRolesHandler:
"""Handler for the blog admin page."""
def post(self) -> None:
"""Handles POST requests."""
assert self.user_id is not None
assert self.normalized_payload is not None
username = self.normalized_payload['username']
role = self.normalized_paylo... | the_stack_v2_python_sparse | core/controllers/blog_admin.py | oppia/oppia | train | 6,172 |
bb91cbc762751f307b2ddc76f1a358afd5daa74d | [
"parameters = {'image': image, 'flavor': flavor, 'number_machines': number_machines, 'availability_zone': availability_zone, 'key_name': key_name, 'security_groups': security_groups, 'private_network': private_network, 'public_network': public_network, 'userdata': userdata, 'swap': swap, 'block_device': None, 'sche... | <|body_start_0|>
parameters = {'image': image, 'flavor': flavor, 'number_machines': number_machines, 'availability_zone': availability_zone, 'key_name': key_name, 'security_groups': security_groups, 'private_network': private_network, 'public_network': public_network, 'userdata': userdata, 'swap': swap, 'block_... | Create a virtual machine instance: mysqlfabric machine create provider --image name=image-mysql --flavor name=vm-template --meta db=mysql --meta version=5.6 mysqlfabric machine create provider --image name=image-mysql --flavor name=vm-template --security_groups grp_fabric, grp_ham Options that accept a list are defined... | CreateMachine | [
"Apache-2.0",
"LicenseRef-scancode-python-cwi",
"LGPL-2.0-or-later",
"BSD-3-Clause",
"bzip2-1.0.6",
"LicenseRef-scancode-free-unknown",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft",
"Sleepycat",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateMachine:
"""Create a virtual machine instance: mysqlfabric machine create provider --image name=image-mysql --flavor name=vm-template --meta db=mysql --meta version=5.6 mysqlfabric machine create provider --image name=image-mysql --flavor name=vm-template --security_groups grp_fabric, grp_h... | stack_v2_sparse_classes_36k_train_024530 | 19,734 | permissive | [
{
"docstring": "Create a machine. :param provider_id: Provider's Id. :param image: Image's properties (e.g. name=image-mysql). :rtype image: list of key/value pairs :param flavor: Flavor's properties (e.g. name=vm-template). :rtype flavor: list of key/value pairs :param number_machines: Number of machines to be... | 2 | stack_v2_sparse_classes_30k_train_018636 | Implement the Python class `CreateMachine` described below.
Class description:
Create a virtual machine instance: mysqlfabric machine create provider --image name=image-mysql --flavor name=vm-template --meta db=mysql --meta version=5.6 mysqlfabric machine create provider --image name=image-mysql --flavor name=vm-templ... | Implement the Python class `CreateMachine` described below.
Class description:
Create a virtual machine instance: mysqlfabric machine create provider --image name=image-mysql --flavor name=vm-template --meta db=mysql --meta version=5.6 mysqlfabric machine create provider --image name=image-mysql --flavor name=vm-templ... | 1e912fd87282be3b3bed48487e6beb0ecb1de339 | <|skeleton|>
class CreateMachine:
"""Create a virtual machine instance: mysqlfabric machine create provider --image name=image-mysql --flavor name=vm-template --meta db=mysql --meta version=5.6 mysqlfabric machine create provider --image name=image-mysql --flavor name=vm-template --security_groups grp_fabric, grp_h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateMachine:
"""Create a virtual machine instance: mysqlfabric machine create provider --image name=image-mysql --flavor name=vm-template --meta db=mysql --meta version=5.6 mysqlfabric machine create provider --image name=image-mysql --flavor name=vm-template --security_groups grp_fabric, grp_ham Options th... | the_stack_v2_python_sparse | mysql-utilities-1.6.0/mysql/fabric/services/machine.py | scavarda/mysql-dbcompare | train | 2 |
c07261ca00f253a040512a41b02797051250d402 | [
"self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)\nself.statusItem.setTitle_(u'M')\nself.statusItem.setHighlightMode_(TRUE)\nself.statusItem.setEnabled_(TRUE)\nself.quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')\nself.port = N... | <|body_start_0|>
self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
self.statusItem.setTitle_(u'M')
self.statusItem.setHighlightMode_(TRUE)
self.statusItem.setEnabled_(TRUE)
self.quit = NSMenuItem.alloc().initWithTitle_action_keyEqui... | Setup a small user interface that allows the user to shutdown the application and see which port mimic is listening on. | MimicAppDelegate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MimicAppDelegate:
"""Setup a small user interface that allows the user to shutdown the application and see which port mimic is listening on."""
def applicationDidFinishLaunching_(self, aNotification):
"""Create a toolbar and menu for the mac application that can be used to close shut... | stack_v2_sparse_classes_36k_train_024531 | 3,684 | permissive | [
{
"docstring": "Create a toolbar and menu for the mac application that can be used to close shut down the application.",
"name": "applicationDidFinishLaunching_",
"signature": "def applicationDidFinishLaunching_(self, aNotification)"
},
{
"docstring": "Stop twisted's reactor when the application... | 2 | stack_v2_sparse_classes_30k_train_004062 | Implement the Python class `MimicAppDelegate` described below.
Class description:
Setup a small user interface that allows the user to shutdown the application and see which port mimic is listening on.
Method signatures and docstrings:
- def applicationDidFinishLaunching_(self, aNotification): Create a toolbar and me... | Implement the Python class `MimicAppDelegate` described below.
Class description:
Setup a small user interface that allows the user to shutdown the application and see which port mimic is listening on.
Method signatures and docstrings:
- def applicationDidFinishLaunching_(self, aNotification): Create a toolbar and me... | 8e7eeed84ec5ae97863f9330023298845623c639 | <|skeleton|>
class MimicAppDelegate:
"""Setup a small user interface that allows the user to shutdown the application and see which port mimic is listening on."""
def applicationDidFinishLaunching_(self, aNotification):
"""Create a toolbar and menu for the mac application that can be used to close shut... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MimicAppDelegate:
"""Setup a small user interface that allows the user to shutdown the application and see which port mimic is listening on."""
def applicationDidFinishLaunching_(self, aNotification):
"""Create a toolbar and menu for the mac application that can be used to close shut down the app... | the_stack_v2_python_sparse | bundle/start-app.py | ranjithpeddi/mimic | train | 1 |
b9d93247cd4223fc41da7f47e4cf7f1c4c0dd489 | [
"f = open(datapath + '/Data/companylist.csv', 'r')\nfor line in f:\n reg = line.split(',')\n if reg[0] != 'Symbol':\n if reg[0] not in self.cnames:\n self.cnames[reg[0]] = [reg[1], reg[2], reg[3], reg[4].strip()]\n elif reg[4].strip() != 'ASX':\n self.cnames[reg[0]] = [reg[... | <|body_start_0|>
f = open(datapath + '/Data/companylist.csv', 'r')
for line in f:
reg = line.split(',')
if reg[0] != 'Symbol':
if reg[0] not in self.cnames:
self.cnames[reg[0]] = [reg[1], reg[2], reg[3], reg[4].strip()]
elif reg... | Company | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Company:
def __init__(self):
"""Reads the companies from a file and stores it in a dictionary"""
<|body_0|>
def get_company(self, cmp):
"""Returns the data for the company :param cmp: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
f = open... | stack_v2_sparse_classes_36k_train_024532 | 1,156 | no_license | [
{
"docstring": "Reads the companies from a file and stores it in a dictionary",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns the data for the company :param cmp: :return:",
"name": "get_company",
"signature": "def get_company(self, cmp)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004602 | Implement the Python class `Company` described below.
Class description:
Implement the Company class.
Method signatures and docstrings:
- def __init__(self): Reads the companies from a file and stores it in a dictionary
- def get_company(self, cmp): Returns the data for the company :param cmp: :return: | Implement the Python class `Company` described below.
Class description:
Implement the Company class.
Method signatures and docstrings:
- def __init__(self): Reads the companies from a file and stores it in a dictionary
- def get_company(self, cmp): Returns the data for the company :param cmp: :return:
<|skeleton|>
... | 3abf7e00848cbff8be33f051a5fb65bd889f1110 | <|skeleton|>
class Company:
def __init__(self):
"""Reads the companies from a file and stores it in a dictionary"""
<|body_0|>
def get_company(self, cmp):
"""Returns the data for the company :param cmp: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Company:
def __init__(self):
"""Reads the companies from a file and stores it in a dictionary"""
f = open(datapath + '/Data/companylist.csv', 'r')
for line in f:
reg = line.split(',')
if reg[0] != 'Symbol':
if reg[0] not in self.cnames:
... | the_stack_v2_python_sparse | FSociety/Data/Company.py | bejar/FSociety | train | 3 | |
37d5a35373cee58b1d8d313ea149bc412af38762 | [
"super(AsciiCrawler, self).__init__(*args, **kwargs)\nself.__parsedContents = None\nself.setVar('category', 'ascii')",
"f = open(self.var('filePath'), 'r')\ncontents = f.read()\nf.close()\nreturn contents",
"if not self.__parsedContents:\n self.__parsedContents = self._runParser()\nreturn self.__parsedConten... | <|body_start_0|>
super(AsciiCrawler, self).__init__(*args, **kwargs)
self.__parsedContents = None
self.setVar('category', 'ascii')
<|end_body_0|>
<|body_start_1|>
f = open(self.var('filePath'), 'r')
contents = f.read()
f.close()
return contents
<|end_body_1|>
<|... | Abstracted ascii crawler. | AsciiCrawler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsciiCrawler:
"""Abstracted ascii crawler."""
def __init__(self, *args, **kwargs):
"""Create a ascii crawler."""
<|body_0|>
def _runParser(self):
"""For re-implementation: Needs to return the parsed data."""
<|body_1|>
def contents(self):
"""... | stack_v2_sparse_classes_36k_train_024533 | 799 | permissive | [
{
"docstring": "Create a ascii crawler.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "For re-implementation: Needs to return the parsed data.",
"name": "_runParser",
"signature": "def _runParser(self)"
},
{
"docstring": "Return the pa... | 3 | null | Implement the Python class `AsciiCrawler` described below.
Class description:
Abstracted ascii crawler.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a ascii crawler.
- def _runParser(self): For re-implementation: Needs to return the parsed data.
- def contents(self): Return the pars... | Implement the Python class `AsciiCrawler` described below.
Class description:
Abstracted ascii crawler.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a ascii crawler.
- def _runParser(self): For re-implementation: Needs to return the parsed data.
- def contents(self): Return the pars... | 046dbb0c1b4ff20ea5f2e1679f8d89f3089b6aa4 | <|skeleton|>
class AsciiCrawler:
"""Abstracted ascii crawler."""
def __init__(self, *args, **kwargs):
"""Create a ascii crawler."""
<|body_0|>
def _runParser(self):
"""For re-implementation: Needs to return the parsed data."""
<|body_1|>
def contents(self):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsciiCrawler:
"""Abstracted ascii crawler."""
def __init__(self, *args, **kwargs):
"""Create a ascii crawler."""
super(AsciiCrawler, self).__init__(*args, **kwargs)
self.__parsedContents = None
self.setVar('category', 'ascii')
def _runParser(self):
"""For re-i... | the_stack_v2_python_sparse | src/lib/kombi/Crawler/Fs/Ascii/AsciiCrawler.py | kombiHQ/kombi | train | 2 |
ddee675240ce5bebe9cebf29a1384f12f0b802ec | [
"self = object.__new__(cls)\nself.url = url\nself.tags = tags\nself.provider = provider\nreturn self",
"repr_parts = [self.__class__.__name__, '(', repr(self.url), ', ', repr(self.tags)]\nprovider = self.provider\nif provider is not None:\n repr_parts.append(', ')\n repr_parts.append(repr(provider))\nrepr_p... | <|body_start_0|>
self = object.__new__(cls)
self.url = url
self.tags = tags
self.provider = provider
return self
<|end_body_0|>
<|body_start_1|>
repr_parts = [self.__class__.__name__, '(', repr(self.url), ', ', repr(self.tags)]
provider = self.provider
if... | Represents an image. Attributes ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None`, `str` The provider of the image. | ImageDetail | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageDetail:
"""Represents an image. Attributes ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None`, `str` The provider of the image."""
def __new__(cls, url, tags, provider=None):
"""Creates a new image detail. Parame... | stack_v2_sparse_classes_36k_train_024534 | 2,073 | no_license | [
{
"docstring": "Creates a new image detail. Parameters ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None, `str` = `None`, Optional Provider of the image.",
"name": "__new__",
"signature": "def __new__(cls, url, tags, provider=None)"
},... | 4 | stack_v2_sparse_classes_30k_train_014484 | Implement the Python class `ImageDetail` described below.
Class description:
Represents an image. Attributes ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None`, `str` The provider of the image.
Method signatures and docstrings:
- def __new__(cls, url,... | Implement the Python class `ImageDetail` described below.
Class description:
Represents an image. Attributes ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None`, `str` The provider of the image.
Method signatures and docstrings:
- def __new__(cls, url,... | 74f92b598e86606ea3a269311316cddd84a5215f | <|skeleton|>
class ImageDetail:
"""Represents an image. Attributes ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None`, `str` The provider of the image."""
def __new__(cls, url, tags, provider=None):
"""Creates a new image detail. Parame... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageDetail:
"""Represents an image. Attributes ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None`, `str` The provider of the image."""
def __new__(cls, url, tags, provider=None):
"""Creates a new image detail. Parameters --------... | the_stack_v2_python_sparse | koishi/plugins/image_handling_core/image_detail.py | HuyaneMatsu/Koishi | train | 17 |
e8ff0dffb9b020e19adc98e9c51bbec241ea1562 | [
"self.set_header('Cache-Control', 'no-cache, no-store, must-revalidate')\nself.set_header('Pragma', 'no-cache')\nself.set_header('Expires', '0')\nusuario = self.get_secure_cookie('user')\nif usuario:\n self.redirect('/')\nelse:\n self.clear_cookie('user')\n self.render('user/login/view.html')",
"self.set... | <|body_start_0|>
self.set_header('Cache-Control', 'no-cache, no-store, must-revalidate')
self.set_header('Pragma', 'no-cache')
self.set_header('Expires', '0')
usuario = self.get_secure_cookie('user')
if usuario:
self.redirect('/')
else:
self.clear_... | Login | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Login:
def get(self):
"""Renderiza el login"""
<|body_0|>
def post(self):
"""Inicia sesión en la aplicación. Si se inicia sesión con éxito enctonces se guarda el usuario en la cookie caso contrario se vuelve al login."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_024535 | 1,796 | permissive | [
{
"docstring": "Renderiza el login",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Inicia sesión en la aplicación. Si se inicia sesión con éxito enctonces se guarda el usuario en la cookie caso contrario se vuelve al login.",
"name": "post",
"signature": "def post(self)"... | 2 | stack_v2_sparse_classes_30k_train_008389 | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- def get(self): Renderiza el login
- def post(self): Inicia sesión en la aplicación. Si se inicia sesión con éxito enctonces se guarda el usuario en la cookie caso contrario se vuelve a... | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- def get(self): Renderiza el login
- def post(self): Inicia sesión en la aplicación. Si se inicia sesión con éxito enctonces se guarda el usuario en la cookie caso contrario se vuelve a... | da59c7b659348c15af0ed8376fe808622d9aec2c | <|skeleton|>
class Login:
def get(self):
"""Renderiza el login"""
<|body_0|>
def post(self):
"""Inicia sesión en la aplicación. Si se inicia sesión con éxito enctonces se guarda el usuario en la cookie caso contrario se vuelve al login."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Login:
def get(self):
"""Renderiza el login"""
self.set_header('Cache-Control', 'no-cache, no-store, must-revalidate')
self.set_header('Pragma', 'no-cache')
self.set_header('Expires', '0')
usuario = self.get_secure_cookie('user')
if usuario:
self.red... | the_stack_v2_python_sparse | server/user/login/controllers.py | shiross/crm-web | train | 1 | |
0fec9cb4b8d86dfaea25aec8c1361f09dd7e1b5d | [
"super(NeRF, self).__init__()\nself.D = D\nself.W = W\nself.in_channels_xyz = in_channels_xyz\nself.skips = skips\nself.sh = torch.nn.Parameter(torch.rand(9), requires_grad=True)\nfor i in range(D):\n if i == 0:\n layer = nn.Linear(in_channels_xyz, W)\n elif i in skips:\n layer = nn.Linear(W + i... | <|body_start_0|>
super(NeRF, self).__init__()
self.D = D
self.W = W
self.in_channels_xyz = in_channels_xyz
self.skips = skips
self.sh = torch.nn.Parameter(torch.rand(9), requires_grad=True)
for i in range(D):
if i == 0:
layer = nn.Linea... | NeRF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeRF:
def __init__(self, D=8, W=256, in_channels_xyz=63, skips=[4]):
"""This network has NO direction input, only input xyz, output albedo and sigma D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xyz: number of input channels for xyz (... | stack_v2_sparse_classes_36k_train_024536 | 18,983 | no_license | [
{
"docstring": "This network has NO direction input, only input xyz, output albedo and sigma D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xyz: number of input channels for xyz (3+3*10*2=63 by default) skips: add skip connection in the Dth layer",
"name"... | 2 | stack_v2_sparse_classes_30k_train_015507 | Implement the Python class `NeRF` described below.
Class description:
Implement the NeRF class.
Method signatures and docstrings:
- def __init__(self, D=8, W=256, in_channels_xyz=63, skips=[4]): This network has NO direction input, only input xyz, output albedo and sigma D: number of layers for density (sigma) encode... | Implement the Python class `NeRF` described below.
Class description:
Implement the NeRF class.
Method signatures and docstrings:
- def __init__(self, D=8, W=256, in_channels_xyz=63, skips=[4]): This network has NO direction input, only input xyz, output albedo and sigma D: number of layers for density (sigma) encode... | 3b6e9d85e77077d1ad3b669fe88799d6a19e6d99 | <|skeleton|>
class NeRF:
def __init__(self, D=8, W=256, in_channels_xyz=63, skips=[4]):
"""This network has NO direction input, only input xyz, output albedo and sigma D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xyz: number of input channels for xyz (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NeRF:
def __init__(self, D=8, W=256, in_channels_xyz=63, skips=[4]):
"""This network has NO direction input, only input xyz, output albedo and sigma D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xyz: number of input channels for xyz (3+3*10*2=63 by... | the_stack_v2_python_sparse | models/nert.py | jcn16/nert | train | 0 | |
614b796a8ee0386d61aedf11064cca8ec90a05f8 | [
"outfile = values\nif outfile.startswith('~'):\n outfile = os.path.realpath(os.path.expanduser(outfile))\nif not outfile.startswith('/'):\n outfile = os.path.realpath(os.path.join(os.getcwd(), outfile))\nif os.path.exists(outfile) and (not os.access(outfile, os.R_OK)):\n parser.error(f'{option_string} {out... | <|body_start_0|>
outfile = values
if outfile.startswith('~'):
outfile = os.path.realpath(os.path.expanduser(outfile))
if not outfile.startswith('/'):
outfile = os.path.realpath(os.path.join(os.getcwd(), outfile))
if os.path.exists(outfile) and (not os.access(outfi... | File directory action class definition. | FileDirAction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileDirAction:
"""File directory action class definition."""
def check_path(parser, values, option_string=None):
"""Check argument for file path. Args: parser (ArgumentParser): Passed-in argument parser. values (object): Argument values with type depending on argument definition. opt... | stack_v2_sparse_classes_36k_train_024537 | 7,613 | permissive | [
{
"docstring": "Check argument for file path. Args: parser (ArgumentParser): Passed-in argument parser. values (object): Argument values with type depending on argument definition. option_string (str): Optional string for specific argument name. Default: None.",
"name": "check_path",
"signature": "def c... | 2 | stack_v2_sparse_classes_30k_train_008452 | Implement the Python class `FileDirAction` described below.
Class description:
File directory action class definition.
Method signatures and docstrings:
- def check_path(parser, values, option_string=None): Check argument for file path. Args: parser (ArgumentParser): Passed-in argument parser. values (object): Argume... | Implement the Python class `FileDirAction` described below.
Class description:
File directory action class definition.
Method signatures and docstrings:
- def check_path(parser, values, option_string=None): Check argument for file path. Args: parser (ArgumentParser): Passed-in argument parser. values (object): Argume... | 8be1c70c44913a6f67dd424aa0e0330f82e48b06 | <|skeleton|>
class FileDirAction:
"""File directory action class definition."""
def check_path(parser, values, option_string=None):
"""Check argument for file path. Args: parser (ArgumentParser): Passed-in argument parser. values (object): Argument values with type depending on argument definition. opt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileDirAction:
"""File directory action class definition."""
def check_path(parser, values, option_string=None):
"""Check argument for file path. Args: parser (ArgumentParser): Passed-in argument parser. values (object): Argument values with type depending on argument definition. option_string (s... | the_stack_v2_python_sparse | mindinsight/mindinsight/mindconverter/cli.py | ZeroWangZY/DL-VIS | train | 1 |
649143f88d61d04528c416f1c4aa7e2166f94f4b | [
"self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')\nfirst_cat = Category.objects.create(name='first', caffe=self.caffe)\nsecond_cat = Category.objects.create(name='second', caffe=self.caffe)\ngram = Unit.objects.create(name='gram', caffe=self... | <|body_start_0|>
self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')
first_cat = Category.objects.create(name='first', caffe=self.caffe)
second_cat = Category.objects.create(name='second', caffe=self.caffe)
gram = Un... | FullProductForm tests. | FullProductFormTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullProductFormTest:
"""FullProductForm tests."""
def setUp(self):
"""Initialize data for further FullProductForm tests."""
<|body_0|>
def test_full_product(self):
"""Check validation and adding/deleting products."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_024538 | 12,667 | permissive | [
{
"docstring": "Initialize data for further FullProductForm tests.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Check validation and adding/deleting products.",
"name": "test_full_product",
"signature": "def test_full_product(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015097 | Implement the Python class `FullProductFormTest` described below.
Class description:
FullProductForm tests.
Method signatures and docstrings:
- def setUp(self): Initialize data for further FullProductForm tests.
- def test_full_product(self): Check validation and adding/deleting products. | Implement the Python class `FullProductFormTest` described below.
Class description:
FullProductForm tests.
Method signatures and docstrings:
- def setUp(self): Initialize data for further FullProductForm tests.
- def test_full_product(self): Check validation and adding/deleting products.
<|skeleton|>
class FullProd... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class FullProductFormTest:
"""FullProductForm tests."""
def setUp(self):
"""Initialize data for further FullProductForm tests."""
<|body_0|>
def test_full_product(self):
"""Check validation and adding/deleting products."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FullProductFormTest:
"""FullProductForm tests."""
def setUp(self):
"""Initialize data for further FullProductForm tests."""
self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')
first_cat = Category.objects.crea... | the_stack_v2_python_sparse | caffe/reports/test_forms.py | VirrageS/io-kawiarnie | train | 3 |
175e29c76811c01616f96a8ec605a1add71f3523 | [
"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!')"
] | <|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... | Missing associated documentation comment in .proto file. | AgentRegistrationServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgentRegistrationServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Register(self, request, context):
"""Registers specified agent."""
<|body_0|>
def ExternalAgentRegister(self, request, context):
"""Registers external agent."""
... | stack_v2_sparse_classes_36k_train_024539 | 5,247 | permissive | [
{
"docstring": "Registers specified agent.",
"name": "Register",
"signature": "def Register(self, request, context)"
},
{
"docstring": "Registers external agent.",
"name": "ExternalAgentRegister",
"signature": "def ExternalAgentRegister(self, request, context)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000392 | Implement the Python class `AgentRegistrationServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Register(self, request, context): Registers specified agent.
- def ExternalAgentRegister(self, request, context): Registers... | Implement the Python class `AgentRegistrationServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Register(self, request, context): Registers specified agent.
- def ExternalAgentRegister(self, request, context): Registers... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class AgentRegistrationServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Register(self, request, context):
"""Registers specified agent."""
<|body_0|>
def ExternalAgentRegister(self, request, context):
"""Registers external agent."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgentRegistrationServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Register(self, request, context):
"""Registers specified agent."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotI... | the_stack_v2_python_sparse | yandex/cloud/loadtesting/agent/v1/agent_registration_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
f44b0c8b93a32cde2118a066c67f5afc252dcf27 | [
"def recursive(i, j):\n if i > j:\n return 0\n count = Counter(s[i:j + 1])\n for m in range(i, j + 1):\n if count[s[m]] >= k:\n continue\n n = m + 1\n while n <= j and count[s[n]] < k:\n n += 1\n return max(recursive(i, m - 1), recursive(n, j))\n ... | <|body_start_0|>
def recursive(i, j):
if i > j:
return 0
count = Counter(s[i:j + 1])
for m in range(i, j + 1):
if count[s[m]] >= k:
continue
n = m + 1
while n <= j and count[s[n]] < k:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def recursive(i, j):
... | stack_v2_sparse_classes_36k_train_024540 | 1,891 | no_license | [
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "longestSubstring",
"signature": "def longestSubstring(self, s, k)"
},
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "longestSubstring",
"signature": "def longestSubstring(self, s, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005871 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int
<|skeleton|>
class Solution:
... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
def recursive(i, j):
if i > j:
return 0
count = Counter(s[i:j + 1])
for m in range(i, j + 1):
if count[s[m]] >= k:
con... | the_stack_v2_python_sparse | problems/longestSubstring.py | joddiy/leetcode | train | 1 | |
1b3120af08fdc04f485fcbfc532844fc4a570f55 | [
"self.data_conn = data_conn\nself.data_proc = data_proc\nself.load_params(config)",
"with open(config, 'r') as conf:\n try:\n self.params = yaml.safe_load(conf)\n except Exception as e:\n print('Error loading DataWriter')\n print(e)\n raise Exception(\"Couldn't load config file: ... | <|body_start_0|>
self.data_conn = data_conn
self.data_proc = data_proc
self.load_params(config)
<|end_body_0|>
<|body_start_1|>
with open(config, 'r') as conf:
try:
self.params = yaml.safe_load(conf)
except Exception as e:
print('E... | DataWriter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataWriter:
def __init__(self, data_conn, data_proc, config):
"""Initializes the mechanisms for transforming and writing data. Parameters ---------- data_conn : DataConnection A connection to the data store where new data will be written to data_proc : DataProcessor The mechanism for pro... | stack_v2_sparse_classes_36k_train_024541 | 1,849 | permissive | [
{
"docstring": "Initializes the mechanisms for transforming and writing data. Parameters ---------- data_conn : DataConnection A connection to the data store where new data will be written to data_proc : DataProcessor The mechanism for processing the incoming data config : str A path to the data-writing configu... | 3 | stack_v2_sparse_classes_30k_train_002330 | Implement the Python class `DataWriter` described below.
Class description:
Implement the DataWriter class.
Method signatures and docstrings:
- def __init__(self, data_conn, data_proc, config): Initializes the mechanisms for transforming and writing data. Parameters ---------- data_conn : DataConnection A connection ... | Implement the Python class `DataWriter` described below.
Class description:
Implement the DataWriter class.
Method signatures and docstrings:
- def __init__(self, data_conn, data_proc, config): Initializes the mechanisms for transforming and writing data. Parameters ---------- data_conn : DataConnection A connection ... | 05d8ec2bac925a53e1882c645f5e086a540bfe6b | <|skeleton|>
class DataWriter:
def __init__(self, data_conn, data_proc, config):
"""Initializes the mechanisms for transforming and writing data. Parameters ---------- data_conn : DataConnection A connection to the data store where new data will be written to data_proc : DataProcessor The mechanism for pro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataWriter:
def __init__(self, data_conn, data_proc, config):
"""Initializes the mechanisms for transforming and writing data. Parameters ---------- data_conn : DataConnection A connection to the data store where new data will be written to data_proc : DataProcessor The mechanism for processing the in... | the_stack_v2_python_sparse | dictionaries/data_writer.py | mwhittemore2/vocab_manager | train | 0 | |
ad8e6fd8a4d96240bb93409001d36ae896c5fdf1 | [
"item_id = int(self.item_id.data)\nitem = PaymentItem.query.get(item_id)\nif item is None:\n raise ValueError\nif item.event_id != event.id:\n raise ValueError\nreturn item",
"while len(self.item_prices) > 0:\n self.item_prices.pop_entry()\nfor price in item.prices:\n self.item_prices.append_entry(pri... | <|body_start_0|>
item_id = int(self.item_id.data)
item = PaymentItem.query.get(item_id)
if item is None:
raise ValueError
if item.event_id != event.id:
raise ValueError
return item
<|end_body_0|>
<|body_start_1|>
while len(self.item_prices) > 0:
... | Form for editing a single payment item and associated prices | PaymentItemForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaymentItemForm:
"""Form for editing a single payment item and associated prices"""
def get_item(self, event):
""":param event: Event to which the payment item belongs :type event: :py:class:`collectives.models.event.Event` :return: Returns both the price and its parent item from whi... | stack_v2_sparse_classes_36k_train_024542 | 11,297 | no_license | [
{
"docstring": ":param event: Event to which the payment item belongs :type event: :py:class:`collectives.models.event.Event` :return: Returns both the price and its parent item from which this form was created If the ids are inconsistent or do not correspond to valid elements, raise a ValueError :rtype: tuple ... | 3 | stack_v2_sparse_classes_30k_train_002923 | Implement the Python class `PaymentItemForm` described below.
Class description:
Form for editing a single payment item and associated prices
Method signatures and docstrings:
- def get_item(self, event): :param event: Event to which the payment item belongs :type event: :py:class:`collectives.models.event.Event` :re... | Implement the Python class `PaymentItemForm` described below.
Class description:
Form for editing a single payment item and associated prices
Method signatures and docstrings:
- def get_item(self, event): :param event: Event to which the payment item belongs :type event: :py:class:`collectives.models.event.Event` :re... | 1ae05ae9029a28fd0656c06a2092f67a87a93dcd | <|skeleton|>
class PaymentItemForm:
"""Form for editing a single payment item and associated prices"""
def get_item(self, event):
""":param event: Event to which the payment item belongs :type event: :py:class:`collectives.models.event.Event` :return: Returns both the price and its parent item from whi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaymentItemForm:
"""Form for editing a single payment item and associated prices"""
def get_item(self, event):
""":param event: Event to which the payment item belongs :type event: :py:class:`collectives.models.event.Event` :return: Returns both the price and its parent item from which this form ... | the_stack_v2_python_sparse | collectives/forms/payment.py | Club-Alpin-Annecy/collectives | train | 12 |
c5531fb392267ddeeff02183b2cc622e0ffd8e01 | [
"try:\n ectool_output = self._device.CallOutput(['ectool', 'pwmgetfanrpm'] + (['%d' % fan_id] if fan_id is not None else []))\n return [int(rpm[1]) for rpm in self.GET_FAN_SPEED_RE.findall(ectool_output)]\nexcept Exception as e:\n raise self.Error('Unable to get fan speed: %s' % e)",
"try:\n if rpm ==... | <|body_start_0|>
try:
ectool_output = self._device.CallOutput(['ectool', 'pwmgetfanrpm'] + (['%d' % fan_id] if fan_id is not None else []))
return [int(rpm[1]) for rpm in self.GET_FAN_SPEED_RE.findall(ectool_output)]
except Exception as e:
raise self.Error('Unable to ... | System module for thermal control (temperature sensors, fans). Implementation for systems with 'ectool' and able to control thermal with EC. | ECToolFanControl | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ECToolFanControl:
"""System module for thermal control (temperature sensors, fans). Implementation for systems with 'ectool' and able to control thermal with EC."""
def GetFanRPM(self, fan_id=None):
"""Gets the fan RPM. Args: fan_id: The id of the fan. Returns: A list of int indicati... | stack_v2_sparse_classes_36k_train_024543 | 5,738 | permissive | [
{
"docstring": "Gets the fan RPM. Args: fan_id: The id of the fan. Returns: A list of int indicating the RPM of each fan.",
"name": "GetFanRPM",
"signature": "def GetFanRPM(self, fan_id=None)"
},
{
"docstring": "Sets the target fan RPM. Args: rpm: Target fan RPM, or FanControl.AUTO for auto fan ... | 2 | stack_v2_sparse_classes_30k_train_011579 | Implement the Python class `ECToolFanControl` described below.
Class description:
System module for thermal control (temperature sensors, fans). Implementation for systems with 'ectool' and able to control thermal with EC.
Method signatures and docstrings:
- def GetFanRPM(self, fan_id=None): Gets the fan RPM. Args: f... | Implement the Python class `ECToolFanControl` described below.
Class description:
System module for thermal control (temperature sensors, fans). Implementation for systems with 'ectool' and able to control thermal with EC.
Method signatures and docstrings:
- def GetFanRPM(self, fan_id=None): Gets the fan RPM. Args: f... | a1b0fccd68987d8cd9c89710adc3c04b868347ec | <|skeleton|>
class ECToolFanControl:
"""System module for thermal control (temperature sensors, fans). Implementation for systems with 'ectool' and able to control thermal with EC."""
def GetFanRPM(self, fan_id=None):
"""Gets the fan RPM. Args: fan_id: The id of the fan. Returns: A list of int indicati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ECToolFanControl:
"""System module for thermal control (temperature sensors, fans). Implementation for systems with 'ectool' and able to control thermal with EC."""
def GetFanRPM(self, fan_id=None):
"""Gets the fan RPM. Args: fan_id: The id of the fan. Returns: A list of int indicating the RPM of... | the_stack_v2_python_sparse | py/device/fan.py | bridder/factory | train | 0 |
b0250dc05cf6e544e49281a5062e1652b2bb81f7 | [
"self._version = version\nif self._version == 1:\n self._url = f'http://{ip_address}/instantaneousdemand'\nelif self._version == 2:\n self._url = f'http://{ip_address}:8888/zigbee/se/instantaneousdemand'\nself._attr_name = name",
"try:\n response = requests.get(self._url, timeout=5)\nexcept (requests.exc... | <|body_start_0|>
self._version = version
if self._version == 1:
self._url = f'http://{ip_address}/instantaneousdemand'
elif self._version == 2:
self._url = f'http://{ip_address}:8888/zigbee/se/instantaneousdemand'
self._attr_name = name
<|end_body_0|>
<|body_star... | Implementation of the DTE Energy Bridge sensors. | DteEnergyBridgeSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DteEnergyBridgeSensor:
"""Implementation of the DTE Energy Bridge sensors."""
def __init__(self, ip_address, name, version):
"""Initialize the sensor."""
<|body_0|>
def update(self) -> None:
"""Get the energy usage data from the DTE energy bridge."""
<|bo... | stack_v2_sparse_classes_36k_train_024544 | 3,599 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, ip_address, name, version)"
},
{
"docstring": "Get the energy usage data from the DTE energy bridge.",
"name": "update",
"signature": "def update(self) -> None"
}
] | 2 | null | Implement the Python class `DteEnergyBridgeSensor` described below.
Class description:
Implementation of the DTE Energy Bridge sensors.
Method signatures and docstrings:
- def __init__(self, ip_address, name, version): Initialize the sensor.
- def update(self) -> None: Get the energy usage data from the DTE energy br... | Implement the Python class `DteEnergyBridgeSensor` described below.
Class description:
Implementation of the DTE Energy Bridge sensors.
Method signatures and docstrings:
- def __init__(self, ip_address, name, version): Initialize the sensor.
- def update(self) -> None: Get the energy usage data from the DTE energy br... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class DteEnergyBridgeSensor:
"""Implementation of the DTE Energy Bridge sensors."""
def __init__(self, ip_address, name, version):
"""Initialize the sensor."""
<|body_0|>
def update(self) -> None:
"""Get the energy usage data from the DTE energy bridge."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DteEnergyBridgeSensor:
"""Implementation of the DTE Energy Bridge sensors."""
def __init__(self, ip_address, name, version):
"""Initialize the sensor."""
self._version = version
if self._version == 1:
self._url = f'http://{ip_address}/instantaneousdemand'
elif ... | the_stack_v2_python_sparse | homeassistant/components/dte_energy_bridge/sensor.py | home-assistant/core | train | 35,501 |
5529715989d1d82f82ecaae57184868ce8fdf701 | [
"if not is_loading:\n sys.stdout.write(os.linesep)\n print('[screenshot.py] Web page loading is complete')\n browser.GetMainFrame().GetSource(self._visitor)\n cef.PostTask(cef.TID_UI, exit_app, browser)",
"if not frame.IsMain():\n return\nprint('[screenshot.py] ERROR: Failed to load url: {url}'.for... | <|body_start_0|>
if not is_loading:
sys.stdout.write(os.linesep)
print('[screenshot.py] Web page loading is complete')
browser.GetMainFrame().GetSource(self._visitor)
cef.PostTask(cef.TID_UI, exit_app, browser)
<|end_body_0|>
<|body_start_1|>
if not frame... | LoadHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadHandler:
def OnLoadingStateChange(self, browser, is_loading, **_):
"""Called when the loading state has changed."""
<|body_0|>
def OnLoadError(self, browser, frame, error_code, failed_url, **_):
"""Called when the resource load for a navigation fails or is cancel... | stack_v2_sparse_classes_36k_train_024545 | 4,540 | no_license | [
{
"docstring": "Called when the loading state has changed.",
"name": "OnLoadingStateChange",
"signature": "def OnLoadingStateChange(self, browser, is_loading, **_)"
},
{
"docstring": "Called when the resource load for a navigation fails or is canceled.",
"name": "OnLoadError",
"signature... | 2 | stack_v2_sparse_classes_30k_train_018891 | Implement the Python class `LoadHandler` described below.
Class description:
Implement the LoadHandler class.
Method signatures and docstrings:
- def OnLoadingStateChange(self, browser, is_loading, **_): Called when the loading state has changed.
- def OnLoadError(self, browser, frame, error_code, failed_url, **_): C... | Implement the Python class `LoadHandler` described below.
Class description:
Implement the LoadHandler class.
Method signatures and docstrings:
- def OnLoadingStateChange(self, browser, is_loading, **_): Called when the loading state has changed.
- def OnLoadError(self, browser, frame, error_code, failed_url, **_): C... | 2a1b5c62a5fcdaf31bc961ee5a75fb9e640f3e93 | <|skeleton|>
class LoadHandler:
def OnLoadingStateChange(self, browser, is_loading, **_):
"""Called when the loading state has changed."""
<|body_0|>
def OnLoadError(self, browser, frame, error_code, failed_url, **_):
"""Called when the resource load for a navigation fails or is cancel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadHandler:
def OnLoadingStateChange(self, browser, is_loading, **_):
"""Called when the loading state has changed."""
if not is_loading:
sys.stdout.write(os.linesep)
print('[screenshot.py] Web page loading is complete')
browser.GetMainFrame().GetSource(sel... | the_stack_v2_python_sparse | cef_offscreen.py | adoregnu/scrapper | train | 1 | |
586fbcd144d70b81eeb684aa70830ae3724deedc | [
"self.source = source\nself.merge_source = merge_source\nself.keys = keys\nself.merge_tags = tags\nself.before = before\nself.saved_columns = None\nself.merge_map = None\nself.empty_result = [''] * len(tags)",
"if self.saved_columns is None:\n new_columns = [HXLColumn(hxlTag=tag) for tag in self.merge_tags]\n ... | <|body_start_0|>
self.source = source
self.merge_source = merge_source
self.keys = keys
self.merge_tags = tags
self.before = before
self.saved_columns = None
self.merge_map = None
self.empty_result = [''] * len(tags)
<|end_body_0|>
<|body_start_1|>
... | Composable filter class to merge values from two HXL datasets. This is the class supporting the hxlmerge command-line utility. Warning: this filter may store a large amount of data in memory, depending on the merge. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance o... | HXLMergeFilter | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HXLMergeFilter:
"""Composable filter class to merge values from two HXL datasets. This is the class supporting the hxlmerge command-line utility. Warning: this filter may store a large amount of data in memory, depending on the merge. Because this class is a {@link hxl.model.HXLDataProvider}, you... | stack_v2_sparse_classes_36k_train_024546 | 5,439 | permissive | [
{
"docstring": "Constructor. @param source the HXL data source. @param merge_source a second HXL data source to merge into the first. @param keys the shared key hashtags to use for the merge @param tags the tags to include from the second dataset @param before if True, add new columns before existing ones",
... | 5 | stack_v2_sparse_classes_30k_train_009178 | Implement the Python class `HXLMergeFilter` described below.
Class description:
Composable filter class to merge values from two HXL datasets. This is the class supporting the hxlmerge command-line utility. Warning: this filter may store a large amount of data in memory, depending on the merge. Because this class is a... | Implement the Python class `HXLMergeFilter` described below.
Class description:
Composable filter class to merge values from two HXL datasets. This is the class supporting the hxlmerge command-line utility. Warning: this filter may store a large amount of data in memory, depending on the merge. Because this class is a... | b0209e75789501d99a2fb2df8a30cf55a383065a | <|skeleton|>
class HXLMergeFilter:
"""Composable filter class to merge values from two HXL datasets. This is the class supporting the hxlmerge command-line utility. Warning: this filter may store a large amount of data in memory, depending on the merge. Because this class is a {@link hxl.model.HXLDataProvider}, you... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HXLMergeFilter:
"""Composable filter class to merge values from two HXL datasets. This is the class supporting the hxlmerge command-line utility. Warning: this filter may store a large amount of data in memory, depending on the merge. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it a... | the_stack_v2_python_sparse | hxl/filters/merge.py | jayvdb/libhxl-python | train | 0 |
37780a6999508b4b636aecf97af4b766fdd3c22b | [
"self.global_args = config.get('global_args', {})\nself.scenario_data = config.get('scenario')\nself.data_dir = config.get('data_dir')\nif not self.scenario_data:\n raise ScenarioException('No blocks in scenario')\nif not self.data_dir:\n raise ScenarioException('Data directory must be set')",
"self.blocks ... | <|body_start_0|>
self.global_args = config.get('global_args', {})
self.scenario_data = config.get('scenario')
self.data_dir = config.get('data_dir')
if not self.scenario_data:
raise ScenarioException('No blocks in scenario')
if not self.data_dir:
raise Sce... | This represents a scenario, i.e. a sequence of blocks to be run on the data | Scenario | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scenario:
"""This represents a scenario, i.e. a sequence of blocks to be run on the data"""
def __init__(self, config):
"""Initialize (parse YAML scenario from a file)"""
<|body_0|>
def load_blocks(self):
"""Load all blocks into memory, finding and creating class... | stack_v2_sparse_classes_36k_train_024547 | 3,189 | permissive | [
{
"docstring": "Initialize (parse YAML scenario from a file)",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Load all blocks into memory, finding and creating class objects.",
"name": "load_blocks",
"signature": "def load_blocks(self)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_train_002233 | Implement the Python class `Scenario` described below.
Class description:
This represents a scenario, i.e. a sequence of blocks to be run on the data
Method signatures and docstrings:
- def __init__(self, config): Initialize (parse YAML scenario from a file)
- def load_blocks(self): Load all blocks into memory, findi... | Implement the Python class `Scenario` described below.
Class description:
This represents a scenario, i.e. a sequence of blocks to be run on the data
Method signatures and docstrings:
- def __init__(self, config): Initialize (parse YAML scenario from a file)
- def load_blocks(self): Load all blocks into memory, findi... | 73af644ec35c8a1cd0c37cd478c2afc1db717e0b | <|skeleton|>
class Scenario:
"""This represents a scenario, i.e. a sequence of blocks to be run on the data"""
def __init__(self, config):
"""Initialize (parse YAML scenario from a file)"""
<|body_0|>
def load_blocks(self):
"""Load all blocks into memory, finding and creating class... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Scenario:
"""This represents a scenario, i.e. a sequence of blocks to be run on the data"""
def __init__(self, config):
"""Initialize (parse YAML scenario from a file)"""
self.global_args = config.get('global_args', {})
self.scenario_data = config.get('scenario')
self.data... | the_stack_v2_python_sparse | alex/components/nlg/tectotpl/core/run.py | oplatek/alex | train | 0 |
54f88c0e4b171c1d19d72011ea4e774ab71db650 | [
"if values['mode'] == 'master':\n values['puppet_server'] = ''\n values['puppet_port'] = ''\n values['puppet_log'] = ''\n values['puppet_extra_opts'] = ''\n if 'puppetmaster_ports' in values:\n values['puppetmaster_ports'] = re.split('[ ,]+', values['puppetmaster_ports'])\nelse:\n values['p... | <|body_start_0|>
if values['mode'] == 'master':
values['puppet_server'] = ''
values['puppet_port'] = ''
values['puppet_log'] = ''
values['puppet_extra_opts'] = ''
if 'puppetmaster_ports' in values:
values['puppetmaster_ports'] = re.spli... | Puppet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Puppet:
def renderContext(self, values):
"""Validate values"""
<|body_0|>
def renderContextVariable(self, variable, value):
"""Final transformations on the variables"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if values['mode'] == 'master':
... | stack_v2_sparse_classes_36k_train_024548 | 2,044 | no_license | [
{
"docstring": "Validate values",
"name": "renderContext",
"signature": "def renderContext(self, values)"
},
{
"docstring": "Final transformations on the variables",
"name": "renderContextVariable",
"signature": "def renderContextVariable(self, variable, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005291 | Implement the Python class `Puppet` described below.
Class description:
Implement the Puppet class.
Method signatures and docstrings:
- def renderContext(self, values): Validate values
- def renderContextVariable(self, variable, value): Final transformations on the variables | Implement the Python class `Puppet` described below.
Class description:
Implement the Puppet class.
Method signatures and docstrings:
- def renderContext(self, values): Validate values
- def renderContextVariable(self, variable, value): Final transformations on the variables
<|skeleton|>
class Puppet:
def rende... | aacb83e9656b73edd1cac71dfcad4890a9bcc669 | <|skeleton|>
class Puppet:
def renderContext(self, values):
"""Validate values"""
<|body_0|>
def renderContextVariable(self, variable, value):
"""Final transformations on the variables"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Puppet:
def renderContext(self, values):
"""Validate values"""
if values['mode'] == 'master':
values['puppet_server'] = ''
values['puppet_port'] = ''
values['puppet_log'] = ''
values['puppet_extra_opts'] = ''
if 'puppetmaster_ports' i... | the_stack_v2_python_sparse | src/cvmo/core/plugin/puppet.py | cernvm/cernvm-online | train | 1 | |
2b1029ec88bf0e6803cdc9278e3c6d10c04bffc1 | [
"guests_sdfile = str(Path(__file__).resolve().parent.parent.joinpath('tests', 'data', 'ligands_40__first-two-ligs.sdf'))\nhost_pdbfile = str(Path(__file__).resolve().parent.parent.joinpath('tests', 'data', 'hif2a_nowater_min.pdb'))\ntransition_type = 'insertion'\nn_steps = 1001\ntransition_steps = 500\nmax_lambda =... | <|body_start_0|>
guests_sdfile = str(Path(__file__).resolve().parent.parent.joinpath('tests', 'data', 'ligands_40__first-two-ligs.sdf'))
host_pdbfile = str(Path(__file__).resolve().parent.parent.joinpath('tests', 'data', 'hif2a_nowater_min.pdb'))
transition_type = 'insertion'
n_steps = 1... | TestDocking | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDocking:
def test_pose_dock(self):
"""Tests basic functionality of pose_dock"""
<|body_0|>
def test_dock_and_equilibrate(self):
"""Tests basic functionality of dock_and_equilibrate"""
<|body_1|>
def test_rigorous_work(self):
"""Tests basic fu... | stack_v2_sparse_classes_36k_train_024549 | 5,248 | permissive | [
{
"docstring": "Tests basic functionality of pose_dock",
"name": "test_pose_dock",
"signature": "def test_pose_dock(self)"
},
{
"docstring": "Tests basic functionality of dock_and_equilibrate",
"name": "test_dock_and_equilibrate",
"signature": "def test_dock_and_equilibrate(self)"
},
... | 4 | stack_v2_sparse_classes_30k_train_009686 | Implement the Python class `TestDocking` described below.
Class description:
Implement the TestDocking class.
Method signatures and docstrings:
- def test_pose_dock(self): Tests basic functionality of pose_dock
- def test_dock_and_equilibrate(self): Tests basic functionality of dock_and_equilibrate
- def test_rigorou... | Implement the Python class `TestDocking` described below.
Class description:
Implement the TestDocking class.
Method signatures and docstrings:
- def test_pose_dock(self): Tests basic functionality of pose_dock
- def test_dock_and_equilibrate(self): Tests basic functionality of dock_and_equilibrate
- def test_rigorou... | 74efe28bfe4fe72a995a764bf3afe635b01bfc73 | <|skeleton|>
class TestDocking:
def test_pose_dock(self):
"""Tests basic functionality of pose_dock"""
<|body_0|>
def test_dock_and_equilibrate(self):
"""Tests basic functionality of dock_and_equilibrate"""
<|body_1|>
def test_rigorous_work(self):
"""Tests basic fu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDocking:
def test_pose_dock(self):
"""Tests basic functionality of pose_dock"""
guests_sdfile = str(Path(__file__).resolve().parent.parent.joinpath('tests', 'data', 'ligands_40__first-two-ligs.sdf'))
host_pdbfile = str(Path(__file__).resolve().parent.parent.joinpath('tests', 'data'... | the_stack_v2_python_sparse | slow_tests/test_docking.py | jchodera/timemachine | train | 0 | |
bac482190b131501460ef4b85db5547897848935 | [
"super().__init__()\nself.source_embedding = nn.Embedding(num_embeddings=num_embeddings, embedding_dim=embedding_size, padding_idx=0)\nself.birnn = nn.GRU(embedding_size, rnn_hidden_size, bidirectional=True, batch_first=True)",
"x_embedded = self.source_embedding(x_source)\nx_lengths = x_lengths.detach().cpu().nu... | <|body_start_0|>
super().__init__()
self.source_embedding = nn.Embedding(num_embeddings=num_embeddings, embedding_dim=embedding_size, padding_idx=0)
self.birnn = nn.GRU(embedding_size, rnn_hidden_size, bidirectional=True, batch_first=True)
<|end_body_0|>
<|body_start_1|>
x_embedded = se... | NMTEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NMTEncoder:
def __init__(self, num_embeddings, embedding_size, rnn_hidden_size):
"""Args :param num_embeddings: int, size of source vocabulary :param embedding_size: int, size of embedding vectors :param rnn_hidden_size: int, size of the RNN hidden state vectors"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_024550 | 9,631 | permissive | [
{
"docstring": "Args :param num_embeddings: int, size of source vocabulary :param embedding_size: int, size of embedding vectors :param rnn_hidden_size: int, size of the RNN hidden state vectors",
"name": "__init__",
"signature": "def __init__(self, num_embeddings, embedding_size, rnn_hidden_size)"
},... | 2 | stack_v2_sparse_classes_30k_train_005561 | Implement the Python class `NMTEncoder` described below.
Class description:
Implement the NMTEncoder class.
Method signatures and docstrings:
- def __init__(self, num_embeddings, embedding_size, rnn_hidden_size): Args :param num_embeddings: int, size of source vocabulary :param embedding_size: int, size of embedding ... | Implement the Python class `NMTEncoder` described below.
Class description:
Implement the NMTEncoder class.
Method signatures and docstrings:
- def __init__(self, num_embeddings, embedding_size, rnn_hidden_size): Args :param num_embeddings: int, size of source vocabulary :param embedding_size: int, size of embedding ... | c360e81624296c9243fd662dea618042164e0aa7 | <|skeleton|>
class NMTEncoder:
def __init__(self, num_embeddings, embedding_size, rnn_hidden_size):
"""Args :param num_embeddings: int, size of source vocabulary :param embedding_size: int, size of embedding vectors :param rnn_hidden_size: int, size of the RNN hidden state vectors"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NMTEncoder:
def __init__(self, num_embeddings, embedding_size, rnn_hidden_size):
"""Args :param num_embeddings: int, size of source vocabulary :param embedding_size: int, size of embedding vectors :param rnn_hidden_size: int, size of the RNN hidden state vectors"""
super().__init__()
s... | the_stack_v2_python_sparse | Tempermonkey-vue3-tfjs/torch/ml/mnt_model.py | flashlin/Samples | train | 3 | |
1c6315bf1ee497701ab03a0319aa9cf1024b13f0 | [
"url = '/availability2/'\narrival = datetime.now().date().strftime('%Y/%m/%d')\ndeparture = datetime.now() + timedelta(days=2)\ndeparture = departure.date().strftime('%Y/%m/%d')\nresponse = self.client.get(url, {'arrival': arrival, 'departure': departure, 'site_id': self.area.id}, HTTP_HOST='website.domain')\nself.... | <|body_start_0|>
url = '/availability2/'
arrival = datetime.now().date().strftime('%Y/%m/%d')
departure = datetime.now() + timedelta(days=2)
departure = departure.date().strftime('%Y/%m/%d')
response = self.client.get(url, {'arrival': arrival, 'departure': departure, 'site_id': s... | Test availability2 as availability is not used for moorings anymore. | AvailabilityTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AvailabilityTestCase:
"""Test availability2 as availability is not used for moorings anymore."""
def test_not_logged_in(self):
"""Test that the availability view will load whilst not logged in."""
<|body_0|>
def test_logged_in_admin(self):
"""Test that the availa... | stack_v2_sparse_classes_36k_train_024551 | 26,818 | permissive | [
{
"docstring": "Test that the availability view will load whilst not logged in.",
"name": "test_not_logged_in",
"signature": "def test_not_logged_in(self)"
},
{
"docstring": "Test that the availability view will load whilst logged in as admin.",
"name": "test_logged_in_admin",
"signature... | 3 | null | Implement the Python class `AvailabilityTestCase` described below.
Class description:
Test availability2 as availability is not used for moorings anymore.
Method signatures and docstrings:
- def test_not_logged_in(self): Test that the availability view will load whilst not logged in.
- def test_logged_in_admin(self):... | Implement the Python class `AvailabilityTestCase` described below.
Class description:
Test availability2 as availability is not used for moorings anymore.
Method signatures and docstrings:
- def test_not_logged_in(self): Test that the availability view will load whilst not logged in.
- def test_logged_in_admin(self):... | 37d2942efcbdaad072f7a06ac876a40e0f69f702 | <|skeleton|>
class AvailabilityTestCase:
"""Test availability2 as availability is not used for moorings anymore."""
def test_not_logged_in(self):
"""Test that the availability view will load whilst not logged in."""
<|body_0|>
def test_logged_in_admin(self):
"""Test that the availa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AvailabilityTestCase:
"""Test availability2 as availability is not used for moorings anymore."""
def test_not_logged_in(self):
"""Test that the availability view will load whilst not logged in."""
url = '/availability2/'
arrival = datetime.now().date().strftime('%Y/%m/%d')
... | the_stack_v2_python_sparse | mooring/test_views.py | dbca-wa/moorings | train | 0 |
0ae59b6807a7f2391a191fc31b547a271b893f02 | [
"from onegov.gazette.models.notice import GazetteNotice\nnotices = object_session(self).query(GazetteNotice)\nnotices = notices.filter(GazetteNotice._categories.has_key(self.name))\nreturn notices",
"if self.notices().first():\n return True\nreturn False",
"from onegov.gazette.models.notice import GazetteNot... | <|body_start_0|>
from onegov.gazette.models.notice import GazetteNotice
notices = object_session(self).query(GazetteNotice)
notices = notices.filter(GazetteNotice._categories.has_key(self.name))
return notices
<|end_body_0|>
<|body_start_1|>
if self.notices().first():
... | Defines a category for official notices. Although the categories are defined as an adjacency list, we currently use it only as a simple alphabetically ordered key-value list (name-title). | Category | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Category:
"""Defines a category for official notices. Although the categories are defined as an adjacency list, we currently use it only as a simple alphabetically ordered key-value list (name-title)."""
def notices(self):
"""Returns a query to get all notices related to this categor... | stack_v2_sparse_classes_36k_train_024552 | 1,807 | permissive | [
{
"docstring": "Returns a query to get all notices related to this category.",
"name": "notices",
"signature": "def notices(self)"
},
{
"docstring": "True, if the category is used by any notice.",
"name": "in_use",
"signature": "def in_use(self)"
},
{
"docstring": "Changes the ca... | 3 | stack_v2_sparse_classes_30k_train_014903 | Implement the Python class `Category` described below.
Class description:
Defines a category for official notices. Although the categories are defined as an adjacency list, we currently use it only as a simple alphabetically ordered key-value list (name-title).
Method signatures and docstrings:
- def notices(self): R... | Implement the Python class `Category` described below.
Class description:
Defines a category for official notices. Although the categories are defined as an adjacency list, we currently use it only as a simple alphabetically ordered key-value list (name-title).
Method signatures and docstrings:
- def notices(self): R... | c706b38d5b67692b4146cdf14ef24d971a32c6b8 | <|skeleton|>
class Category:
"""Defines a category for official notices. Although the categories are defined as an adjacency list, we currently use it only as a simple alphabetically ordered key-value list (name-title)."""
def notices(self):
"""Returns a query to get all notices related to this categor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Category:
"""Defines a category for official notices. Although the categories are defined as an adjacency list, we currently use it only as a simple alphabetically ordered key-value list (name-title)."""
def notices(self):
"""Returns a query to get all notices related to this category."""
... | the_stack_v2_python_sparse | src/onegov/gazette/models/category.py | OneGov/onegov-cloud | train | 17 |
76bd7f781ea70916468a179f452343b5f5dfd42b | [
"prev = float('-inf')\n\ndef dfs(root):\n nonlocal prev\n if root.left:\n if dfs(root.left) == False:\n return False\n if root.val <= prev:\n return False\n prev = root.val\n if root.right:\n if dfs(root.right) == False:\n return False\n return True\nretu... | <|body_start_0|>
prev = float('-inf')
def dfs(root):
nonlocal prev
if root.left:
if dfs(root.left) == False:
return False
if root.val <= prev:
return False
prev = root.val
if root.right:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidBST(self, root) -> bool:
"""Recursive In-Order Traversal, Time: O(n), Space: O(n)"""
<|body_0|>
def isValidBST(self, root) -> bool:
"""Iterative In-Order Traversal, Time: O(n), Space: O(n)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_024553 | 1,386 | no_license | [
{
"docstring": "Recursive In-Order Traversal, Time: O(n), Space: O(n)",
"name": "isValidBST",
"signature": "def isValidBST(self, root) -> bool"
},
{
"docstring": "Iterative In-Order Traversal, Time: O(n), Space: O(n)",
"name": "isValidBST",
"signature": "def isValidBST(self, root) -> boo... | 2 | stack_v2_sparse_classes_30k_train_003083 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root) -> bool: Recursive In-Order Traversal, Time: O(n), Space: O(n)
- def isValidBST(self, root) -> bool: Iterative In-Order Traversal, Time: O(n), Space: O... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root) -> bool: Recursive In-Order Traversal, Time: O(n), Space: O(n)
- def isValidBST(self, root) -> bool: Iterative In-Order Traversal, Time: O(n), Space: O... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def isValidBST(self, root) -> bool:
"""Recursive In-Order Traversal, Time: O(n), Space: O(n)"""
<|body_0|>
def isValidBST(self, root) -> bool:
"""Iterative In-Order Traversal, Time: O(n), Space: O(n)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isValidBST(self, root) -> bool:
"""Recursive In-Order Traversal, Time: O(n), Space: O(n)"""
prev = float('-inf')
def dfs(root):
nonlocal prev
if root.left:
if dfs(root.left) == False:
return False
if... | the_stack_v2_python_sparse | python/98-Validate Binary Search Tree.py | cwza/leetcode | train | 0 | |
911e89e6d247ffe47e863a23545143ffcba8890b | [
"if options.numbers:\n return esc(n) + '%3d ' % n\nelif options.hex:\n return esc(n) + ' %2x ' % n\nreturn esc(n) + ' '",
"if options.foreground:\n esc = lambda n: fg_escape % n\nelse:\n esc = lambda n: bg_escape % n + fg_escape % (15 if n < 9 else 0)\nreturn [[term16.label(n, esc) + clear for n in r... | <|body_start_0|>
if options.numbers:
return esc(n) + '%3d ' % n
elif options.hex:
return esc(n) + ' %2x ' % n
return esc(n) + ' '
<|end_body_0|>
<|body_start_1|>
if options.foreground:
esc = lambda n: fg_escape % n
else:
esc = lam... | Basic 16 color terminal. | term16 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class term16:
"""Basic 16 color terminal."""
def label(n, esc):
"""color label for 256 color values >>> options.numbers = True >>> term16.label(95, lambda n: '') ' 95 ' >>> options.numbers = False >>> options.hex = True >>> term16.label(95, lambda n: '') ' 5f '"""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_024554 | 20,144 | permissive | [
{
"docstring": "color label for 256 color values >>> options.numbers = True >>> term16.label(95, lambda n: '') ' 95 ' >>> options.numbers = False >>> options.hex = True >>> term16.label(95, lambda n: '') ' 5f '",
"name": "label",
"signature": "def label(n, esc)"
},
{
"docstring": "16 color info ... | 5 | stack_v2_sparse_classes_30k_train_016348 | Implement the Python class `term16` described below.
Class description:
Basic 16 color terminal.
Method signatures and docstrings:
- def label(n, esc): color label for 256 color values >>> options.numbers = True >>> term16.label(95, lambda n: '') ' 95 ' >>> options.numbers = False >>> options.hex = True >>> term16.la... | Implement the Python class `term16` described below.
Class description:
Basic 16 color terminal.
Method signatures and docstrings:
- def label(n, esc): color label for 256 color values >>> options.numbers = True >>> term16.label(95, lambda n: '') ' 95 ' >>> options.numbers = False >>> options.hex = True >>> term16.la... | 03925ab9701d70850e0621bc7857e154551a03a6 | <|skeleton|>
class term16:
"""Basic 16 color terminal."""
def label(n, esc):
"""color label for 256 color values >>> options.numbers = True >>> term16.label(95, lambda n: '') ' 95 ' >>> options.numbers = False >>> options.hex = True >>> term16.label(95, lambda n: '') ' 5f '"""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class term16:
"""Basic 16 color terminal."""
def label(n, esc):
"""color label for 256 color values >>> options.numbers = True >>> term16.label(95, lambda n: '') ' 95 ' >>> options.numbers = False >>> options.hex = True >>> term16.label(95, lambda n: '') ' 5f '"""
if options.numbers:
... | the_stack_v2_python_sparse | dot_bin/executable_colors | benmezger/dotfiles | train | 95 |
4d9c5447d5c09557490f1a6f16236ecb19bf0b34 | [
"self.existing_tags_ids = [1, 2, 3, 4]\nself.content_id = 1\nself.tag_ids = [1, 5, 7]\nself.content = MagicMock(spec=Content, id=self.content_id, owner_id=21, tags=MagicMock(spec=Tag, all=MagicMock(return_value=MagicMock(values_list=MagicMock(return_value=self.existing_tags_ids)))))",
"mock_objects.get.return_val... | <|body_start_0|>
self.existing_tags_ids = [1, 2, 3, 4]
self.content_id = 1
self.tag_ids = [1, 5, 7]
self.content = MagicMock(spec=Content, id=self.content_id, owner_id=21, tags=MagicMock(spec=Tag, all=MagicMock(return_value=MagicMock(values_list=MagicMock(return_value=self.existing_tags_... | Test case for PushFeeds | TestStreamFeedsUtils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStreamFeedsUtils:
"""Test case for PushFeeds"""
def setUp(self):
"""SetUp method for test case"""
<|body_0|>
def test_update_content_tags_at_getsream(self, mock_objects, mock_delay, mock_parent_ids):
"""test case for testing the update_content_tags_at_getsrea... | stack_v2_sparse_classes_36k_train_024555 | 20,391 | no_license | [
{
"docstring": "SetUp method for test case",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test case for testing the update_content_tags_at_getsream",
"name": "test_update_content_tags_at_getsream",
"signature": "def test_update_content_tags_at_getsream(self, mock_ob... | 2 | stack_v2_sparse_classes_30k_train_002856 | Implement the Python class `TestStreamFeedsUtils` described below.
Class description:
Test case for PushFeeds
Method signatures and docstrings:
- def setUp(self): SetUp method for test case
- def test_update_content_tags_at_getsream(self, mock_objects, mock_delay, mock_parent_ids): test case for testing the update_co... | Implement the Python class `TestStreamFeedsUtils` described below.
Class description:
Test case for PushFeeds
Method signatures and docstrings:
- def setUp(self): SetUp method for test case
- def test_update_content_tags_at_getsream(self, mock_objects, mock_delay, mock_parent_ids): test case for testing the update_co... | 248a7b406686c0c98e944319a6eca08485104f5d | <|skeleton|>
class TestStreamFeedsUtils:
"""Test case for PushFeeds"""
def setUp(self):
"""SetUp method for test case"""
<|body_0|>
def test_update_content_tags_at_getsream(self, mock_objects, mock_delay, mock_parent_ids):
"""test case for testing the update_content_tags_at_getsrea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestStreamFeedsUtils:
"""Test case for PushFeeds"""
def setUp(self):
"""SetUp method for test case"""
self.existing_tags_ids = [1, 2, 3, 4]
self.content_id = 1
self.tag_ids = [1, 5, 7]
self.content = MagicMock(spec=Content, id=self.content_id, owner_id=21, tags=Mag... | the_stack_v2_python_sparse | common/feeds/tests.py | skshivammahajan/DRFChat | train | 0 |
8dc18a314224c615306e6e0f8b3b93d9062d961f | [
"client = LdapClient({'ldap_server_vendor': 'OpenLDAP', 'host': 'server_ip', 'connection_type': 'SSL', 'ssl_version': ssl_version})\nssl_version_value = client._get_ssl_version()\nassert ssl_version_value == expected_ssl_version",
"client = LdapClient({'ldap_server_vendor': 'OpenLDAP', 'host': 'server_ip', 'conne... | <|body_start_0|>
client = LdapClient({'ldap_server_vendor': 'OpenLDAP', 'host': 'server_ip', 'connection_type': 'SSL', 'ssl_version': ssl_version})
ssl_version_value = client._get_ssl_version()
assert ssl_version_value == expected_ssl_version
<|end_body_0|>
<|body_start_1|>
client = Lda... | Contains unit tests for general functions that deal with both OpenLDAP and Active Directory servers. | TestLDAPAuthentication | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLDAPAuthentication:
"""Contains unit tests for general functions that deal with both OpenLDAP and Active Directory servers."""
def test_get_ssl_version(self, ssl_version, expected_ssl_version):
"""Given: - An ssl protocol version: 1. TLS 2. TLSv1 3. TLSv1_1 4. TLSv1_2 5. TLS_CLIE... | stack_v2_sparse_classes_36k_train_024556 | 12,670 | permissive | [
{
"docstring": "Given: - An ssl protocol version: 1. TLS 2. TLSv1 3. TLSv1_1 4. TLSv1_2 5. TLS_CLIENT 6. None 7. 'None' When: - Running the '_get_ssl_version()' function. Then: - Verify that the returned ssl version value is as expected: 1. TLS - 2 2. TLSv1 - 3 3. TLSv1_1 - 4 4. TLSv1_2 - 5 5. TLS_CLIENT - 16 6... | 3 | stack_v2_sparse_classes_30k_train_017928 | Implement the Python class `TestLDAPAuthentication` described below.
Class description:
Contains unit tests for general functions that deal with both OpenLDAP and Active Directory servers.
Method signatures and docstrings:
- def test_get_ssl_version(self, ssl_version, expected_ssl_version): Given: - An ssl protocol v... | Implement the Python class `TestLDAPAuthentication` described below.
Class description:
Contains unit tests for general functions that deal with both OpenLDAP and Active Directory servers.
Method signatures and docstrings:
- def test_get_ssl_version(self, ssl_version, expected_ssl_version): Given: - An ssl protocol v... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestLDAPAuthentication:
"""Contains unit tests for general functions that deal with both OpenLDAP and Active Directory servers."""
def test_get_ssl_version(self, ssl_version, expected_ssl_version):
"""Given: - An ssl protocol version: 1. TLS 2. TLSv1 3. TLSv1_1 4. TLSv1_2 5. TLS_CLIE... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLDAPAuthentication:
"""Contains unit tests for general functions that deal with both OpenLDAP and Active Directory servers."""
def test_get_ssl_version(self, ssl_version, expected_ssl_version):
"""Given: - An ssl protocol version: 1. TLS 2. TLSv1 3. TLSv1_1 4. TLSv1_2 5. TLS_CLIENT 6. None 7.... | the_stack_v2_python_sparse | Packs/OpenLDAP/Integrations/OpenLDAP/OpenLDAP_test.py | demisto/content | train | 1,023 |
29d59d5adcb972276b3ac57a845be2127b6ff8a8 | [
"for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n if not matrix[i][j]:\n continue\n matrix[i][j] = float('inf')\n if i > 0:\n matrix[i][j] = min(matrix[i][j], matrix[i - 1][j] + 1)\n if j > 0:\n matrix[i][j] = min(matrix[i][j], matrix[i... | <|body_start_0|>
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if not matrix[i][j]:
continue
matrix[i][j] = float('inf')
if i > 0:
matrix[i][j] = min(matrix[i][j], matrix[i - 1][j] + 1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def updateMatrix(self, matrix):
""":type matrix: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def updateMatrix1(self, A):
""":type mat: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i ... | stack_v2_sparse_classes_36k_train_024557 | 2,824 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: List[List[int]]",
"name": "updateMatrix",
"signature": "def updateMatrix(self, matrix)"
},
{
"docstring": ":type mat: List[List[int]] :rtype: List[List[int]]",
"name": "updateMatrix1",
"signature": "def updateMatrix1(self, A)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def updateMatrix(self, matrix): :type matrix: List[List[int]] :rtype: List[List[int]]
- def updateMatrix1(self, A): :type mat: List[List[int]] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def updateMatrix(self, matrix): :type matrix: List[List[int]] :rtype: List[List[int]]
- def updateMatrix1(self, A): :type mat: List[List[int]] :rtype: List[List[int]]
<|skeleton... | 233d12deca34f51c3bb0406831cc07f3b72b50cf | <|skeleton|>
class Solution:
def updateMatrix(self, matrix):
""":type matrix: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def updateMatrix1(self, A):
""":type mat: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def updateMatrix(self, matrix):
""":type matrix: List[List[int]] :rtype: List[List[int]]"""
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if not matrix[i][j]:
continue
matrix[i][j] = float('inf')
... | the_stack_v2_python_sparse | Python/01 Matrix/main.py | briansu2004/MyLeet | train | 1 | |
3dc529a4dff3b8b7923d29326e2f176172a42e0c | [
"dic = set()\ndummy = node = ListNode(0)\nnode.next = head\nwhile node.next:\n if node.next.val in dic:\n node.next = node.next.next\n else:\n dic.add(node.next.val)\n node = node.next\nreturn dummy.next",
"d = set()\nhh = head\nbf = ''\nwhile head:\n if head.val not in d:\n d... | <|body_start_0|>
dic = set()
dummy = node = ListNode(0)
node.next = head
while node.next:
if node.next.val in dic:
node.next = node.next.next
else:
dic.add(node.next.val)
node = node.next
return dummy.next
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicateNodes1(self, head: ListNode) -> ListNode:
"""思路:每次判断node.next"""
<|body_0|>
def removeDuplicateNodes2(self, head):
"""更快的"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dic = set()
dummy = node = ListNode(0)
... | stack_v2_sparse_classes_36k_train_024558 | 1,493 | no_license | [
{
"docstring": "思路:每次判断node.next",
"name": "removeDuplicateNodes1",
"signature": "def removeDuplicateNodes1(self, head: ListNode) -> ListNode"
},
{
"docstring": "更快的",
"name": "removeDuplicateNodes2",
"signature": "def removeDuplicateNodes2(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicateNodes1(self, head: ListNode) -> ListNode: 思路:每次判断node.next
- def removeDuplicateNodes2(self, head): 更快的 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicateNodes1(self, head: ListNode) -> ListNode: 思路:每次判断node.next
- def removeDuplicateNodes2(self, head): 更快的
<|skeleton|>
class Solution:
def removeDuplicateN... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def removeDuplicateNodes1(self, head: ListNode) -> ListNode:
"""思路:每次判断node.next"""
<|body_0|>
def removeDuplicateNodes2(self, head):
"""更快的"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeDuplicateNodes1(self, head: ListNode) -> ListNode:
"""思路:每次判断node.next"""
dic = set()
dummy = node = ListNode(0)
node.next = head
while node.next:
if node.next.val in dic:
node.next = node.next.next
else:
... | the_stack_v2_python_sparse | LeetCode/链表(Linked list)/面试题 02.01. 移除重复节点.py | yiming1012/MyLeetCode | train | 2 | |
2cd5f89e24ac5dcba3d58280a9d20070f662b808 | [
"z = model.user.User()\nname = 'ram'\nz.set_username(name)\ny = z.get_username()\nself.assertEqual(name, y)",
"a = model.user.User()\npassword = '12345'\na.set_password(password)\nb = a.get_password()\nself.assertEqual(password, b)",
"a = model.user.User()\nname = 'kathmandu'\na.set_username(name)\nb = a.get_us... | <|body_start_0|>
z = model.user.User()
name = 'ram'
z.set_username(name)
y = z.get_username()
self.assertEqual(name, y)
<|end_body_0|>
<|body_start_1|>
a = model.user.User()
password = '12345'
a.set_password(password)
b = a.get_password()
... | TestUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUser:
def test_set_username(self):
"""it tests if set and get is working or not :return: whatever user sets"""
<|body_0|>
def test_set_password(self):
"""it tests if set and get password is working or not :return: whatever user sets password"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_024559 | 1,318 | no_license | [
{
"docstring": "it tests if set and get is working or not :return: whatever user sets",
"name": "test_set_username",
"signature": "def test_set_username(self)"
},
{
"docstring": "it tests if set and get password is working or not :return: whatever user sets password",
"name": "test_set_passw... | 4 | stack_v2_sparse_classes_30k_train_000489 | Implement the Python class `TestUser` described below.
Class description:
Implement the TestUser class.
Method signatures and docstrings:
- def test_set_username(self): it tests if set and get is working or not :return: whatever user sets
- def test_set_password(self): it tests if set and get password is working or n... | Implement the Python class `TestUser` described below.
Class description:
Implement the TestUser class.
Method signatures and docstrings:
- def test_set_username(self): it tests if set and get is working or not :return: whatever user sets
- def test_set_password(self): it tests if set and get password is working or n... | 7aebcaaeff679253026c8c3e5666ffd02fc33399 | <|skeleton|>
class TestUser:
def test_set_username(self):
"""it tests if set and get is working or not :return: whatever user sets"""
<|body_0|>
def test_set_password(self):
"""it tests if set and get password is working or not :return: whatever user sets password"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestUser:
def test_set_username(self):
"""it tests if set and get is working or not :return: whatever user sets"""
z = model.user.User()
name = 'ram'
z.set_username(name)
y = z.get_username()
self.assertEqual(name, y)
def test_set_password(self):
""... | the_stack_v2_python_sparse | PycharmProjects/Assignment/unittesting/test_user.py | manish2000g/manishg | train | 0 | |
0da0fd4ad585d8d23651c6e9766495015eeeb266 | [
"user_details = UserDetails.objects.get(user=user)\nproducts = Product.objects.all()\nserializer = ProductSerializer(products, many=True)\nresponse_data = dict(products=serializer.data, credit=user_details.available_credit)\nreturn Response(response_data, status=status.HTTP_200_OK)",
"user_request_body = request.... | <|body_start_0|>
user_details = UserDetails.objects.get(user=user)
products = Product.objects.all()
serializer = ProductSerializer(products, many=True)
response_data = dict(products=serializer.data, credit=user_details.available_credit)
return Response(response_data, status=statu... | Product Controller View | ProductView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductView:
"""Product Controller View"""
def get(self, request, user):
"""products view for fetching the list of products :param request: http request for the view method allowed: GET http request should be authorised by the jwt token of the user :param user: User object of the req... | stack_v2_sparse_classes_36k_train_024560 | 14,511 | permissive | [
{
"docstring": "products view for fetching the list of products :param request: http request for the view method allowed: GET http request should be authorised by the jwt token of the user :param user: User object of the requesting user :returns Response object with products list and 200 status if no error mess... | 2 | stack_v2_sparse_classes_30k_train_003191 | Implement the Python class `ProductView` described below.
Class description:
Product Controller View
Method signatures and docstrings:
- def get(self, request, user): products view for fetching the list of products :param request: http request for the view method allowed: GET http request should be authorised by the ... | Implement the Python class `ProductView` described below.
Class description:
Product Controller View
Method signatures and docstrings:
- def get(self, request, user): products view for fetching the list of products :param request: http request for the view method allowed: GET http request should be authorised by the ... | 45e98d77b2fef6004dd36c640bd95b25395d0948 | <|skeleton|>
class ProductView:
"""Product Controller View"""
def get(self, request, user):
"""products view for fetching the list of products :param request: http request for the view method allowed: GET http request should be authorised by the jwt token of the user :param user: User object of the req... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductView:
"""Product Controller View"""
def get(self, request, user):
"""products view for fetching the list of products :param request: http request for the view method allowed: GET http request should be authorised by the jwt token of the user :param user: User object of the requesting user ... | the_stack_v2_python_sparse | services/workshop/crapi/shop/views.py | OWASP/crAPI | train | 772 |
4f0474389c00e852aabd5ed8efb28d791cd80fa2 | [
"rows, cols = (len(grid), len(grid[0]))\ndistinct_islands = set()\nfor row in range(rows):\n for col in range(cols):\n if grid[row][col] == 1:\n path = self.compute_path(row, col, grid, rows, cols, 'X')\n distinct_islands.add(path)\nreturn len(distinct_islands)",
"if row < 0 or col... | <|body_start_0|>
rows, cols = (len(grid), len(grid[0]))
distinct_islands = set()
for row in range(rows):
for col in range(cols):
if grid[row][col] == 1:
path = self.compute_path(row, col, grid, rows, cols, 'X')
distinct_islands.... | Islands | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Islands:
def get_distinct_islands(self, grid: List[List[int]]) -> int:
"""Approach: Hash by path signature Time Complexity: O(MN) Space Complexity: O(MN) :param grid: :return:"""
<|body_0|>
def compute_path(self, row: int, col: int, grid: List[List[int]], rows: int, cols: in... | stack_v2_sparse_classes_36k_train_024561 | 1,883 | no_license | [
{
"docstring": "Approach: Hash by path signature Time Complexity: O(MN) Space Complexity: O(MN) :param grid: :return:",
"name": "get_distinct_islands",
"signature": "def get_distinct_islands(self, grid: List[List[int]]) -> int"
},
{
"docstring": "Computes the island shape. :param row: :param col... | 2 | null | Implement the Python class `Islands` described below.
Class description:
Implement the Islands class.
Method signatures and docstrings:
- def get_distinct_islands(self, grid: List[List[int]]) -> int: Approach: Hash by path signature Time Complexity: O(MN) Space Complexity: O(MN) :param grid: :return:
- def compute_pa... | Implement the Python class `Islands` described below.
Class description:
Implement the Islands class.
Method signatures and docstrings:
- def get_distinct_islands(self, grid: List[List[int]]) -> int: Approach: Hash by path signature Time Complexity: O(MN) Space Complexity: O(MN) :param grid: :return:
- def compute_pa... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Islands:
def get_distinct_islands(self, grid: List[List[int]]) -> int:
"""Approach: Hash by path signature Time Complexity: O(MN) Space Complexity: O(MN) :param grid: :return:"""
<|body_0|>
def compute_path(self, row: int, col: int, grid: List[List[int]], rows: int, cols: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Islands:
def get_distinct_islands(self, grid: List[List[int]]) -> int:
"""Approach: Hash by path signature Time Complexity: O(MN) Space Complexity: O(MN) :param grid: :return:"""
rows, cols = (len(grid), len(grid[0]))
distinct_islands = set()
for row in range(rows):
... | the_stack_v2_python_sparse | amazon/dfs_and_bfs/number_of_distinct_islands.py | Shiv2157k/leet_code | train | 1 | |
6dd3357cf85753a24ac6fa5861723c269f808493 | [
"self.genome_a = genome_a\nself.genome_b = genome_b\nself.config = config\nself.env = DurakEnv()\nself.net_a = neat.nn.FeedForwardNetwork.create(self.genome_a, self.config)\nself.net_b = neat.nn.FeedForwardNetwork.create(self.genome_b, self.config)",
"self.env.reset()\nobservation, _, _, info = self.env.step(self... | <|body_start_0|>
self.genome_a = genome_a
self.genome_b = genome_b
self.config = config
self.env = DurakEnv()
self.net_a = neat.nn.FeedForwardNetwork.create(self.genome_a, self.config)
self.net_b = neat.nn.FeedForwardNetwork.create(self.genome_b, self.config)
<|end_body_0... | A worker for multi-threaded evolution. Attributes: genome: The genome to be tested. config: The configuration specifications for NEAT. env: The Durak environment. | Worker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Worker:
"""A worker for multi-threaded evolution. Attributes: genome: The genome to be tested. config: The configuration specifications for NEAT. env: The Durak environment."""
def __init__(self, genome_a, genome_b, config):
"""Inits a worker with a genome and the config."""
... | stack_v2_sparse_classes_36k_train_024562 | 5,074 | no_license | [
{
"docstring": "Inits a worker with a genome and the config.",
"name": "__init__",
"signature": "def __init__(self, genome_a, genome_b, config)"
},
{
"docstring": "Evaluates the fitness of a genome. Returns: A float that represents the fitness of a genome. The higher the number the fitter it is ... | 2 | stack_v2_sparse_classes_30k_train_020571 | Implement the Python class `Worker` described below.
Class description:
A worker for multi-threaded evolution. Attributes: genome: The genome to be tested. config: The configuration specifications for NEAT. env: The Durak environment.
Method signatures and docstrings:
- def __init__(self, genome_a, genome_b, config):... | Implement the Python class `Worker` described below.
Class description:
A worker for multi-threaded evolution. Attributes: genome: The genome to be tested. config: The configuration specifications for NEAT. env: The Durak environment.
Method signatures and docstrings:
- def __init__(self, genome_a, genome_b, config):... | 8d785c6ce9841f60dd2465b739d8def6ed1c9137 | <|skeleton|>
class Worker:
"""A worker for multi-threaded evolution. Attributes: genome: The genome to be tested. config: The configuration specifications for NEAT. env: The Durak environment."""
def __init__(self, genome_a, genome_b, config):
"""Inits a worker with a genome and the config."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Worker:
"""A worker for multi-threaded evolution. Attributes: genome: The genome to be tested. config: The configuration specifications for NEAT. env: The Durak environment."""
def __init__(self, genome_a, genome_b, config):
"""Inits a worker with a genome and the config."""
self.genome_a... | the_stack_v2_python_sparse | src/versus_run.py | Bretley/durakBot | train | 3 |
74cada21c63162ab8915a1fd637e80d2a82fa9ff | [
"super(LogFollowerBuilder, self).__init__(*args, **kwargs)\nself._arguments = None\nreturn",
"if self._product is None:\n self._product = LogFollower(output=self.output_file, connection=self.node.connection, arguments=self.arguments)\nreturn self._product"
] | <|body_start_0|>
super(LogFollowerBuilder, self).__init__(*args, **kwargs)
self._arguments = None
return
<|end_body_0|>
<|body_start_1|>
if self._product is None:
self._product = LogFollower(output=self.output_file, connection=self.node.connection, arguments=self.arguments)
... | A builder of log followers | LogFollowerBuilder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogFollowerBuilder:
"""A builder of log followers"""
def __init__(self, *args, **kwargs):
""":param: - `node`: device to watch - `parameters`: named tuple built from config file - `output`: storageobject to send output to - `name`: a name to add to the output file - `event`: event to... | stack_v2_sparse_classes_36k_train_024563 | 7,765 | permissive | [
{
"docstring": ":param: - `node`: device to watch - `parameters`: named tuple built from config file - `output`: storageobject to send output to - `name`: a name to add to the output file - `event`: event to watch to decide when to stop",
"name": "__init__",
"signature": "def __init__(self, *args, **kwa... | 2 | null | Implement the Python class `LogFollowerBuilder` described below.
Class description:
A builder of log followers
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): :param: - `node`: device to watch - `parameters`: named tuple built from config file - `output`: storageobject to send output to - `na... | Implement the Python class `LogFollowerBuilder` described below.
Class description:
A builder of log followers
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): :param: - `node`: device to watch - `parameters`: named tuple built from config file - `output`: storageobject to send output to - `na... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class LogFollowerBuilder:
"""A builder of log followers"""
def __init__(self, *args, **kwargs):
""":param: - `node`: device to watch - `parameters`: named tuple built from config file - `output`: storageobject to send output to - `name`: a name to add to the output file - `event`: event to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogFollowerBuilder:
"""A builder of log followers"""
def __init__(self, *args, **kwargs):
""":param: - `node`: device to watch - `parameters`: named tuple built from config file - `output`: storageobject to send output to - `name`: a name to add to the output file - `event`: event to watch to dec... | the_stack_v2_python_sparse | apetools/builders/subbuilders/logwatcherbuilders.py | russell-n/oldape | train | 0 |
6c378e5a0f41a3a08895a836d8063ffff4878d0b | [
"employee_env = self.env['hr.employee']\nuser_env = self.env['res.users']\nemployee_obj = employee_env.search([('user_id', '=', self._uid)])\nis_allow = False\nfor rec in self:\n if user_env.has_group('base.group_hr_manager') or employee_obj.id == rec.manager_id.id:\n is_allow = True\n else:\n i... | <|body_start_0|>
employee_env = self.env['hr.employee']
user_env = self.env['res.users']
employee_obj = employee_env.search([('user_id', '=', self._uid)])
is_allow = False
for rec in self:
if user_env.has_group('base.group_hr_manager') or employee_obj.id == rec.manage... | HrAppraisal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HrAppraisal:
def _password_security_salary(self):
"""HR manager and the Manager of the employee can see and edit Salary Information"""
<|body_0|>
def _password_security_interview_result(self):
"""Interview Result - HR manager and the Manager of the employee can see a... | stack_v2_sparse_classes_36k_train_024564 | 2,753 | no_license | [
{
"docstring": "HR manager and the Manager of the employee can see and edit Salary Information",
"name": "_password_security_salary",
"signature": "def _password_security_salary(self)"
},
{
"docstring": "Interview Result - HR manager and the Manager of the employee can see and edit - Employee ca... | 3 | stack_v2_sparse_classes_30k_train_004993 | Implement the Python class `HrAppraisal` described below.
Class description:
Implement the HrAppraisal class.
Method signatures and docstrings:
- def _password_security_salary(self): HR manager and the Manager of the employee can see and edit Salary Information
- def _password_security_interview_result(self): Intervi... | Implement the Python class `HrAppraisal` described below.
Class description:
Implement the HrAppraisal class.
Method signatures and docstrings:
- def _password_security_salary(self): HR manager and the Manager of the employee can see and edit Salary Information
- def _password_security_interview_result(self): Intervi... | 673dd0f2a7c0b69a984342b20f55164a97a00529 | <|skeleton|>
class HrAppraisal:
def _password_security_salary(self):
"""HR manager and the Manager of the employee can see and edit Salary Information"""
<|body_0|>
def _password_security_interview_result(self):
"""Interview Result - HR manager and the Manager of the employee can see a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HrAppraisal:
def _password_security_salary(self):
"""HR manager and the Manager of the employee can see and edit Salary Information"""
employee_env = self.env['hr.employee']
user_env = self.env['res.users']
employee_obj = employee_env.search([('user_id', '=', self._uid)])
... | the_stack_v2_python_sparse | addons/app-trobz-hr/trobz_hr_simple_appraisal_secure/model/hr_appraisal.py | TinPlusIT05/tms | train | 0 | |
52fcf8e790d3847b2dbc1edf27e71578f193b696 | [
"res = []\nwords = sorted(words, key=len)\n\ndef recursive(words):\n longest = words.pop()\n for each in words:\n if each in longest:\n res.append(each)\n if words == []:\n return res\n else:\n return recursive(words)\nreturn list(set(recursive(words)))",
"arr = ' '.joi... | <|body_start_0|>
res = []
words = sorted(words, key=len)
def recursive(words):
longest = words.pop()
for each in words:
if each in longest:
res.append(each)
if words == []:
return res
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def stringMatching(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_0|>
def stringMatching_cool_solution(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_1|>
def stringMatching_brute(self, words):
"... | stack_v2_sparse_classes_36k_train_024565 | 1,529 | no_license | [
{
"docstring": ":type words: List[str] :rtype: List[str]",
"name": "stringMatching",
"signature": "def stringMatching(self, words)"
},
{
"docstring": ":type words: List[str] :rtype: List[str]",
"name": "stringMatching_cool_solution",
"signature": "def stringMatching_cool_solution(self, w... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def stringMatching(self, words): :type words: List[str] :rtype: List[str]
- def stringMatching_cool_solution(self, words): :type words: List[str] :rtype: List[str]
- def stringMa... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def stringMatching(self, words): :type words: List[str] :rtype: List[str]
- def stringMatching_cool_solution(self, words): :type words: List[str] :rtype: List[str]
- def stringMa... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def stringMatching(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_0|>
def stringMatching_cool_solution(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_1|>
def stringMatching_brute(self, words):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def stringMatching(self, words):
""":type words: List[str] :rtype: List[str]"""
res = []
words = sorted(words, key=len)
def recursive(words):
longest = words.pop()
for each in words:
if each in longest:
res.... | the_stack_v2_python_sparse | LeetCode/String/1408_string_matching_in_an_array.py | XyK0907/for_work | train | 0 | |
85907978edce07f7e16b0d945df19aa10656894e | [
"self.pos = Vector2D(cf.X_POS, cf.Y_POS)\nself.dir = Vector2D(0, -1)\nself.vel = 0.0\nself.two_d_pos = Vector2D(0, 0)",
"try:\n one = self.dir.rotate(cf.ROTATION[0]).normalized() * cf.SCALING[0]\n two = self.dir.rotate(cf.ROTATION[1]).normalized() * cf.SCALING[1]\n three = self.dir.rotate(cf.ROTATION[2])... | <|body_start_0|>
self.pos = Vector2D(cf.X_POS, cf.Y_POS)
self.dir = Vector2D(0, -1)
self.vel = 0.0
self.two_d_pos = Vector2D(0, 0)
<|end_body_0|>
<|body_start_1|>
try:
one = self.dir.rotate(cf.ROTATION[0]).normalized() * cf.SCALING[0]
two = self.dir.rotat... | Make an arrow that can be drawn, displayed and rotated. | Arrow | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Arrow:
"""Make an arrow that can be drawn, displayed and rotated."""
def __init__(self):
"""Initializing all attributes 'Arrow' needs."""
<|body_0|>
def draw(self, screen):
"""Draw a polygon that takes the shape of a big arrow. Makes the polygon from seven 'Vecto... | stack_v2_sparse_classes_36k_train_024566 | 3,495 | permissive | [
{
"docstring": "Initializing all attributes 'Arrow' needs.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Draw a polygon that takes the shape of a big arrow. Makes the polygon from seven 'Vector2D' objects that are all based on the 'dir'-attribute of the arrow. Argume... | 3 | stack_v2_sparse_classes_30k_train_019886 | Implement the Python class `Arrow` described below.
Class description:
Make an arrow that can be drawn, displayed and rotated.
Method signatures and docstrings:
- def __init__(self): Initializing all attributes 'Arrow' needs.
- def draw(self, screen): Draw a polygon that takes the shape of a big arrow. Makes the poly... | Implement the Python class `Arrow` described below.
Class description:
Make an arrow that can be drawn, displayed and rotated.
Method signatures and docstrings:
- def __init__(self): Initializing all attributes 'Arrow' needs.
- def draw(self, screen): Draw a polygon that takes the shape of a big arrow. Makes the poly... | d1cc3d9861febd4848821c602141dbcd48b6e0e1 | <|skeleton|>
class Arrow:
"""Make an arrow that can be drawn, displayed and rotated."""
def __init__(self):
"""Initializing all attributes 'Arrow' needs."""
<|body_0|>
def draw(self, screen):
"""Draw a polygon that takes the shape of a big arrow. Makes the polygon from seven 'Vecto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Arrow:
"""Make an arrow that can be drawn, displayed and rotated."""
def __init__(self):
"""Initializing all attributes 'Arrow' needs."""
self.pos = Vector2D(cf.X_POS, cf.Y_POS)
self.dir = Vector2D(0, -1)
self.vel = 0.0
self.two_d_pos = Vector2D(0, 0)
def draw... | the_stack_v2_python_sparse | gps_pygame/arrow.py | engeir/bladeGPS-Game | train | 0 |
ca8e9cee6725b88f4fbbae5c1c920b3ad99fc11a | [
"res = []\npath = []\nlength = len(s)\nself.find_palindrome_2(res, path, s, length)\nreturn res",
"path_length = sum([len(item) for item in path])\nif path_length == length:\n res.append(path)\n return\nfor i in range(1, len(s) + 1):\n current_str = s[:i]\n if not self.is_palindrome(current_str):\n ... | <|body_start_0|>
res = []
path = []
length = len(s)
self.find_palindrome_2(res, path, s, length)
return res
<|end_body_0|>
<|body_start_1|>
path_length = sum([len(item) for item in path])
if path_length == length:
res.append(path)
return
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def partition(self, s):
""":type s: str :rtype: List[List[str]]"""
<|body_0|>
def find_palindrome(self, res, path, s, length):
"""find palindrome partition :param res: a list :param path: a list :param s: a string :param length: length of original string :r... | stack_v2_sparse_classes_36k_train_024567 | 2,959 | no_license | [
{
"docstring": ":type s: str :rtype: List[List[str]]",
"name": "partition",
"signature": "def partition(self, s)"
},
{
"docstring": "find palindrome partition :param res: a list :param path: a list :param s: a string :param length: length of original string :return:",
"name": "find_palindrom... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partition(self, s): :type s: str :rtype: List[List[str]]
- def find_palindrome(self, res, path, s, length): find palindrome partition :param res: a list :param path: a list :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partition(self, s): :type s: str :rtype: List[List[str]]
- def find_palindrome(self, res, path, s, length): find palindrome partition :param res: a list :param path: a list :... | cf4235170db3629b65790fd0855a8a72ac5886f7 | <|skeleton|>
class Solution:
def partition(self, s):
""":type s: str :rtype: List[List[str]]"""
<|body_0|>
def find_palindrome(self, res, path, s, length):
"""find palindrome partition :param res: a list :param path: a list :param s: a string :param length: length of original string :r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def partition(self, s):
""":type s: str :rtype: List[List[str]]"""
res = []
path = []
length = len(s)
self.find_palindrome_2(res, path, s, length)
return res
def find_palindrome(self, res, path, s, length):
"""find palindrome partition :pa... | the_stack_v2_python_sparse | palindrome_partitioning.py | buxizhizhoum/leetcode | train | 1 | |
d71897e78e2f251d39d56c275a3114323bc67efa | [
"self.item_info_keys = ['item_title', 'item_bib', 'item_id', 'item_barcode', 'item_callnumber', 'item_pickup_location']\n'patron_full_name for email'\nself.patron_info_keys = ['patron_full_name', 'patron_last_name', 'patron_email', 'patron_barcode_login_name', 'patron_barcode_login_barcode']\nself.other_info_keys =... | <|body_start_0|>
self.item_info_keys = ['item_title', 'item_bib', 'item_id', 'item_barcode', 'item_callnumber', 'item_pickup_location']
'patron_full_name for email'
self.patron_info_keys = ['patron_full_name', 'patron_last_name', 'patron_email', 'patron_barcode_login_name', 'patron_barcode_login... | Helps to initialize and manage `request.session`. | SessionHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionHelper:
"""Helps to initialize and manage `request.session`."""
def __init__(self):
"""Non-obvious usage... - patron_full_name, for email - patron_las_name, for possible second josiah-api attempt if default shib firstname fails"""
<|body_0|>
def initialize_session... | stack_v2_sparse_classes_36k_train_024568 | 1,500 | permissive | [
{
"docstring": "Non-obvious usage... - patron_full_name, for email - patron_las_name, for possible second josiah-api attempt if default shib firstname fails",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Initializes session. Called by views.time_period()",
"name":... | 2 | stack_v2_sparse_classes_30k_train_006842 | Implement the Python class `SessionHelper` described below.
Class description:
Helps to initialize and manage `request.session`.
Method signatures and docstrings:
- def __init__(self): Non-obvious usage... - patron_full_name, for email - patron_las_name, for possible second josiah-api attempt if default shib firstnam... | Implement the Python class `SessionHelper` described below.
Class description:
Helps to initialize and manage `request.session`.
Method signatures and docstrings:
- def __init__(self): Non-obvious usage... - patron_full_name, for email - patron_las_name, for possible second josiah-api attempt if default shib firstnam... | 0718b3e22485354b45eb27615aba05c56b2b833b | <|skeleton|>
class SessionHelper:
"""Helps to initialize and manage `request.session`."""
def __init__(self):
"""Non-obvious usage... - patron_full_name, for email - patron_las_name, for possible second josiah-api attempt if default shib firstname fails"""
<|body_0|>
def initialize_session... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionHelper:
"""Helps to initialize and manage `request.session`."""
def __init__(self):
"""Non-obvious usage... - patron_full_name, for email - patron_las_name, for possible second josiah-api attempt if default shib firstname fails"""
self.item_info_keys = ['item_title', 'item_bib', 'i... | the_stack_v2_python_sparse | easyrequest_hay_app/lib/session.py | Brown-University-Library/easyrequest_hay_project | train | 0 |
7c2bdc67d4688c02649f3168ef50a64f773c667d | [
"if hasattr(o, '_js_name'):\n self.name = o._js_name\n self.javascript = o._js_code\n return\nsrc = inspect.getsource(o)\nclassname = ''\nif isinstance(o, types.MethodType):\n classname = o.im_class.__name__\n o = o.im_func\nif isinstance(o, types.FunctionType):\n if o.__module__ == '__main__':\n ... | <|body_start_0|>
if hasattr(o, '_js_name'):
self.name = o._js_name
self.javascript = o._js_code
return
src = inspect.getsource(o)
classname = ''
if isinstance(o, types.MethodType):
classname = o.im_class.__name__
o = o.im_func
... | Transcode a Python function or module to javascript code | JS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JS:
"""Transcode a Python function or module to javascript code"""
def __init__(self, o):
"""Transcode a Python function or module In: - ``o`` -- Python function or module to transcode"""
<|body_0|>
def generate_action(self, priority, renderer):
"""Include the tr... | stack_v2_sparse_classes_36k_train_024569 | 17,967 | permissive | [
{
"docstring": "Transcode a Python function or module In: - ``o`` -- Python function or module to transcode",
"name": "__init__",
"signature": "def __init__(self, o)"
},
{
"docstring": "Include the transcoded javascript into ``<head>`` In: - ``priority`` -- *not used* - ``renderer`` -- the curre... | 2 | null | Implement the Python class `JS` described below.
Class description:
Transcode a Python function or module to javascript code
Method signatures and docstrings:
- def __init__(self, o): Transcode a Python function or module In: - ``o`` -- Python function or module to transcode
- def generate_action(self, priority, rend... | Implement the Python class `JS` described below.
Class description:
Transcode a Python function or module to javascript code
Method signatures and docstrings:
- def __init__(self, o): Transcode a Python function or module In: - ``o`` -- Python function or module to transcode
- def generate_action(self, priority, rend... | 9e251f053c4edeb46b59b46d22049b29d1498727 | <|skeleton|>
class JS:
"""Transcode a Python function or module to javascript code"""
def __init__(self, o):
"""Transcode a Python function or module In: - ``o`` -- Python function or module to transcode"""
<|body_0|>
def generate_action(self, priority, renderer):
"""Include the tr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JS:
"""Transcode a Python function or module to javascript code"""
def __init__(self, o):
"""Transcode a Python function or module In: - ``o`` -- Python function or module to transcode"""
if hasattr(o, '_js_name'):
self.name = o._js_name
self.javascript = o._js_cod... | the_stack_v2_python_sparse | cifrado/web/codigo/Python/virtualenv-15.1.0/NAGARE_HOME/Lib/site-packages/nagare-0.5.1-py2.7.egg/nagare/ajax.py | SanchezRuizCarlosEduardo/disor | train | 0 |
30f28f4fe58d9bf2525ffca0c671effbc3b0f3a6 | [
"len_g = len(grid)\nlen_gp = len_g * 4 + 1\ngp = [['1'] * len_gp for _ in range(len_gp)]\nfor i in range(len_g):\n l = list(grid[i])\n for j in range(len_g):\n row = 4 * i + 2\n col = 4 * j + 2\n if l[j] == '\\\\':\n gp[row - 2][col - 2] = '0'\n gp[row - 1][col - 1] ... | <|body_start_0|>
len_g = len(grid)
len_gp = len_g * 4 + 1
gp = [['1'] * len_gp for _ in range(len_gp)]
for i in range(len_g):
l = list(grid[i])
for j in range(len_g):
row = 4 * i + 2
col = 4 * j + 2
if l[j] == '\\':
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def regionsBySlashes(self, grid):
""":type grid: List[str] :rtype: int"""
<|body_0|>
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
len_g = len(grid)
len_gp = ... | stack_v2_sparse_classes_36k_train_024570 | 2,743 | no_license | [
{
"docstring": ":type grid: List[str] :rtype: int",
"name": "regionsBySlashes",
"signature": "def regionsBySlashes(self, grid)"
},
{
"docstring": ":type grid: List[List[str]] :rtype: int",
"name": "numIslands",
"signature": "def numIslands(self, grid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012701 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def regionsBySlashes(self, grid): :type grid: List[str] :rtype: int
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def regionsBySlashes(self, grid): :type grid: List[str] :rtype: int
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int
<|skeleton|>
class Solution:
def r... | 3232620c73175dcf4cfef31a07319e7cc032d224 | <|skeleton|>
class Solution:
def regionsBySlashes(self, grid):
""":type grid: List[str] :rtype: int"""
<|body_0|>
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def regionsBySlashes(self, grid):
""":type grid: List[str] :rtype: int"""
len_g = len(grid)
len_gp = len_g * 4 + 1
gp = [['1'] * len_gp for _ in range(len_gp)]
for i in range(len_g):
l = list(grid[i])
for j in range(len_g):
... | the_stack_v2_python_sparse | C115/0959_regions_cut_by_slashes/solution_1.py | asymmetry/leetcode | train | 0 | |
cdb87aa34052b988b1b4b4a97333c8121809e7fe | [
"cnt = 0\ncur_max = 0\ni = 0\nwhile cur_max < n:\n if i >= len(nums) or cur_max + 1 < nums[i]:\n cur_max += cur_max + 1\n cnt += 1\n else:\n cur_max += nums[i]\n i += 1\nreturn cnt",
"nums = filter(lambda x: x <= n, nums)\ncnt = 0\ncur_max = 0\nfor elt in nums:\n while cur_max... | <|body_start_0|>
cnt = 0
cur_max = 0
i = 0
while cur_max < n:
if i >= len(nums) or cur_max + 1 < nums[i]:
cur_max += cur_max + 1
cnt += 1
else:
cur_max += nums[i]
i += 1
return cnt
<|end_body_... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minPatches(self, nums, n):
"""https://discuss.leetcode.com/topic/35494/solution-explanation Greedy Let cur_max be the current max sum can be formed by [0, i) when iterating at i-th index if cur_max < Ai: we have a void gap at [cur_max + 1, Ai] we need to patch a cur_max in ... | stack_v2_sparse_classes_36k_train_024571 | 2,519 | permissive | [
{
"docstring": "https://discuss.leetcode.com/topic/35494/solution-explanation Greedy Let cur_max be the current max sum can be formed by [0, i) when iterating at i-th index if cur_max < Ai: we have a void gap at [cur_max + 1, Ai] we need to patch a cur_max in the array to maximize the all-cover reach else: cur_... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPatches(self, nums, n): https://discuss.leetcode.com/topic/35494/solution-explanation Greedy Let cur_max be the current max sum can be formed by [0, i) when iterating at i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPatches(self, nums, n): https://discuss.leetcode.com/topic/35494/solution-explanation Greedy Let cur_max be the current max sum can be formed by [0, i) when iterating at i... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def minPatches(self, nums, n):
"""https://discuss.leetcode.com/topic/35494/solution-explanation Greedy Let cur_max be the current max sum can be formed by [0, i) when iterating at i-th index if cur_max < Ai: we have a void gap at [cur_max + 1, Ai] we need to patch a cur_max in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minPatches(self, nums, n):
"""https://discuss.leetcode.com/topic/35494/solution-explanation Greedy Let cur_max be the current max sum can be formed by [0, i) when iterating at i-th index if cur_max < Ai: we have a void gap at [cur_max + 1, Ai] we need to patch a cur_max in the array to m... | the_stack_v2_python_sparse | 330 Patching Array.py | Aminaba123/LeetCode | train | 1 | |
a3999d45dfacb4f98bae684fd73a4d023c248d89 | [
"self.band_edge_energies = band_edge_energies\nself.orbital_character = orbital_character\nself.orbital_character_indices = orbital_character_indices\nself.participation_ratio = participation_ratio",
"band_edge_energies = mod_defaultdict(depth=3)\norbital_character = mod_defaultdict(depth=3)\norbital_character_in... | <|body_start_0|>
self.band_edge_energies = band_edge_energies
self.orbital_character = orbital_character
self.orbital_character_indices = orbital_character_indices
self.participation_ratio = participation_ratio
<|end_body_0|>
<|body_start_1|>
band_edge_energies = mod_defaultdict... | Class with DFT results for supercell systems. | ProcarDefectProperty | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcarDefectProperty:
"""Class with DFT results for supercell systems."""
def __init__(self, band_edge_energies: dict, orbital_character: dict, orbital_character_indices: dict, participation_ratio: dict):
"""Args: band_edge_energies (dict): Averaged band energy over k-space as functi... | stack_v2_sparse_classes_36k_train_024572 | 20,839 | permissive | [
{
"docstring": "Args: band_edge_energies (dict): Averaged band energy over k-space as functions of spin and band_edge. orbital_character (dict): Orbital character at the eigenstate of each spin, band_edge (=\"hob\" or \"lub\"), and energy_position = (=\"top\" or \"bottom\") ex. {Spin.up: {\"hob\": {\"top\": {\"... | 2 | stack_v2_sparse_classes_30k_test_000461 | Implement the Python class `ProcarDefectProperty` described below.
Class description:
Class with DFT results for supercell systems.
Method signatures and docstrings:
- def __init__(self, band_edge_energies: dict, orbital_character: dict, orbital_character_indices: dict, participation_ratio: dict): Args: band_edge_ene... | Implement the Python class `ProcarDefectProperty` described below.
Class description:
Class with DFT results for supercell systems.
Method signatures and docstrings:
- def __init__(self, band_edge_energies: dict, orbital_character: dict, orbital_character_indices: dict, participation_ratio: dict): Args: band_edge_ene... | e909796c429e16982cefe549d16881039bce89e7 | <|skeleton|>
class ProcarDefectProperty:
"""Class with DFT results for supercell systems."""
def __init__(self, band_edge_energies: dict, orbital_character: dict, orbital_character_indices: dict, participation_ratio: dict):
"""Args: band_edge_energies (dict): Averaged band energy over k-space as functi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProcarDefectProperty:
"""Class with DFT results for supercell systems."""
def __init__(self, band_edge_energies: dict, orbital_character: dict, orbital_character_indices: dict, participation_ratio: dict):
"""Args: band_edge_energies (dict): Averaged band energy over k-space as functions of spin a... | the_stack_v2_python_sparse | pydefect/core/supercell_calc_results.py | obaica/pydefect | train | 0 |
450016e1acacda541140e9f73bbff8a8dcd5145a | [
"params = dict(workspace_name='harfangletest_corp')\nform = WorkspaceUpdateForm(params)\nself.assertTrue(form.is_valid())\nself.assertEquals(form.cleaned_data['workspace_name'], 'harfangletest_corp')",
"params = dict(workspace_name='全角テスト株式会社')\nform = WorkspaceUpdateForm(params)\nself.assertTrue(form.is_valid())... | <|body_start_0|>
params = dict(workspace_name='harfangletest_corp')
form = WorkspaceUpdateForm(params)
self.assertTrue(form.is_valid())
self.assertEquals(form.cleaned_data['workspace_name'], 'harfangletest_corp')
<|end_body_0|>
<|body_start_1|>
params = dict(workspace_name='全角テス... | WorkspaceUpdateFormTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkspaceUpdateFormTests:
def test_workspace_update_forms_normal_1(self):
"""顧客情報更新フォーム 正常系 1"""
<|body_0|>
def test_workspace_update_forms_normal_2(self):
"""顧客情報更新フォーム 正常系 2"""
<|body_1|>
def test_workspace_update_forms_normal_3(self):
"""顧客情報更... | stack_v2_sparse_classes_36k_train_024573 | 4,355 | permissive | [
{
"docstring": "顧客情報更新フォーム 正常系 1",
"name": "test_workspace_update_forms_normal_1",
"signature": "def test_workspace_update_forms_normal_1(self)"
},
{
"docstring": "顧客情報更新フォーム 正常系 2",
"name": "test_workspace_update_forms_normal_2",
"signature": "def test_workspace_update_forms_normal_2(se... | 5 | stack_v2_sparse_classes_30k_train_001311 | Implement the Python class `WorkspaceUpdateFormTests` described below.
Class description:
Implement the WorkspaceUpdateFormTests class.
Method signatures and docstrings:
- def test_workspace_update_forms_normal_1(self): 顧客情報更新フォーム 正常系 1
- def test_workspace_update_forms_normal_2(self): 顧客情報更新フォーム 正常系 2
- def test_wor... | Implement the Python class `WorkspaceUpdateFormTests` described below.
Class description:
Implement the WorkspaceUpdateFormTests class.
Method signatures and docstrings:
- def test_workspace_update_forms_normal_1(self): 顧客情報更新フォーム 正常系 1
- def test_workspace_update_forms_normal_2(self): 顧客情報更新フォーム 正常系 2
- def test_wor... | 049058a37b9ee45b58be5f4393a0b3191362043c | <|skeleton|>
class WorkspaceUpdateFormTests:
def test_workspace_update_forms_normal_1(self):
"""顧客情報更新フォーム 正常系 1"""
<|body_0|>
def test_workspace_update_forms_normal_2(self):
"""顧客情報更新フォーム 正常系 2"""
<|body_1|>
def test_workspace_update_forms_normal_3(self):
"""顧客情報更... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkspaceUpdateFormTests:
def test_workspace_update_forms_normal_1(self):
"""顧客情報更新フォーム 正常系 1"""
params = dict(workspace_name='harfangletest_corp')
form = WorkspaceUpdateForm(params)
self.assertTrue(form.is_valid())
self.assertEquals(form.cleaned_data['workspace_name'],... | the_stack_v2_python_sparse | register/tests_forms.py | yashiki-takajin/sfa-next | train | 0 | |
3c1210cdc03bb34e682eec232bc504fc35aff7e5 | [
"filtering = create_facebook_filter(field=FieldsMetadata.campaign_id.name.replace('_', '.'), operator=AgGridFacebookOperator.EQUAL, value=campaign['campaign_id'])\nadset_structures = get_and_map_structures(ad_account_id=f'act_{account_id}', level=level, filtering=filtering)\nvalid_adset_structures = self.check_inte... | <|body_start_0|>
filtering = create_facebook_filter(field=FieldsMetadata.campaign_id.name.replace('_', '.'), operator=AgGridFacebookOperator.EQUAL, value=campaign['campaign_id'])
adset_structures = get_and_map_structures(ad_account_id=f'act_{account_id}', level=level, filtering=filtering)
valid_... | HiddenInterestsStrategy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HiddenInterestsStrategy:
def generate_recommendation(self, level: LevelEnum, business_owner: str, account_id: str, campaign: Dict, recommendations_repository: MongoRepositoryBase) -> None:
"""Generates Hidden Interests Recommendations. Parameters ---------- level: LevelEnum Ad Campaign S... | stack_v2_sparse_classes_36k_train_024574 | 5,271 | no_license | [
{
"docstring": "Generates Hidden Interests Recommendations. Parameters ---------- level: LevelEnum Ad Campaign Structure Level business_owner: str Facebook Business Owner ID account_id: str Ad Account ID campaign: dict Campaign recommendations_repository: MongoRepositoryBase env_dexter_recommendations Mongo Tab... | 2 | null | Implement the Python class `HiddenInterestsStrategy` described below.
Class description:
Implement the HiddenInterestsStrategy class.
Method signatures and docstrings:
- def generate_recommendation(self, level: LevelEnum, business_owner: str, account_id: str, campaign: Dict, recommendations_repository: MongoRepositor... | Implement the Python class `HiddenInterestsStrategy` described below.
Class description:
Implement the HiddenInterestsStrategy class.
Method signatures and docstrings:
- def generate_recommendation(self, level: LevelEnum, business_owner: str, account_id: str, campaign: Dict, recommendations_repository: MongoRepositor... | 17b93889c6945db15ed8b57147def2ae89a07de5 | <|skeleton|>
class HiddenInterestsStrategy:
def generate_recommendation(self, level: LevelEnum, business_owner: str, account_id: str, campaign: Dict, recommendations_repository: MongoRepositoryBase) -> None:
"""Generates Hidden Interests Recommendations. Parameters ---------- level: LevelEnum Ad Campaign S... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HiddenInterestsStrategy:
def generate_recommendation(self, level: LevelEnum, business_owner: str, account_id: str, campaign: Dict, recommendations_repository: MongoRepositoryBase) -> None:
"""Generates Hidden Interests Recommendations. Parameters ---------- level: LevelEnum Ad Campaign Structure Level... | the_stack_v2_python_sparse | FacebookDexter/BackgroundTasks/Strategies/HiddenInterestsStrategy.py | jssellars/aniket_filed | train | 0 | |
6a1ee5fac25d2281238296f5c473178835402b08 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('raykatz_nedg_gaudiosi', 'raykatz_nedg_gaudiosi')\nrepo.dropCollection('averages')\nrepo.createCollection('averages')\nrepo.raykatz_nedg_gaudiosi.zipcode_info.aggregate([{'$group': {'_id': 'null', 'avg_pe... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('raykatz_nedg_gaudiosi', 'raykatz_nedg_gaudiosi')
repo.dropCollection('averages')
repo.createCollection('averages')
repo.raykatz_nedg_gaudi... | averages | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class averages:
def execute(trial=False):
"""Computes averages for the city of Boston"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this script. Each run of th... | stack_v2_sparse_classes_36k_train_024575 | 6,785 | no_license | [
{
"docstring": "Computes averages for the city of Boston",
"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 document describing that invocation e... | 2 | stack_v2_sparse_classes_30k_train_020429 | Implement the Python class `averages` described below.
Class description:
Implement the averages class.
Method signatures and docstrings:
- def execute(trial=False): Computes averages for the city of Boston
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create the provenance document d... | Implement the Python class `averages` described below.
Class description:
Implement the averages class.
Method signatures and docstrings:
- def execute(trial=False): Computes averages for the city of Boston
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create the provenance document d... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class averages:
def execute(trial=False):
"""Computes averages for the city of Boston"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this script. Each run of th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class averages:
def execute(trial=False):
"""Computes averages for the city of Boston"""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('raykatz_nedg_gaudiosi', 'raykatz_nedg_gaudiosi')
repo.dropCollection('... | the_stack_v2_python_sparse | raykatz_nedg_gaudiosi/averages.py | ROODAY/course-2017-fal-proj | train | 3 | |
a09b03ac37f60e776f3b081d59400252b8f20fc4 | [
"novo_no = No(dado, None, None)\nif self.cabeca is None:\n self.cabeca = novo_no\n self.rabo = novo_no\nelse:\n novo_no.anterior = self.rabo\n novo_no.proximo = None\n self.rabo.proximo = novo_no\n self.rabo = novo_no",
"no_atual = self.cabeca\nwhile no_atual is not None:\n if no_atual.dado =... | <|body_start_0|>
novo_no = No(dado, None, None)
if self.cabeca is None:
self.cabeca = novo_no
self.rabo = novo_no
else:
novo_no.anterior = self.rabo
novo_no.proximo = None
self.rabo.proximo = novo_no
self.rabo = novo_no
<|en... | ListaDuplamenteEncadeada | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListaDuplamenteEncadeada:
def acrescentar(self, dado):
"""Acrescenta um novo no a lista."""
<|body_0|>
def remover(self, dado):
"""Remove um no da lista."""
<|body_1|>
def mostrar(self):
"""Mostra todos os dados da lista."""
<|body_2|>
<... | stack_v2_sparse_classes_36k_train_024576 | 3,743 | permissive | [
{
"docstring": "Acrescenta um novo no a lista.",
"name": "acrescentar",
"signature": "def acrescentar(self, dado)"
},
{
"docstring": "Remove um no da lista.",
"name": "remover",
"signature": "def remover(self, dado)"
},
{
"docstring": "Mostra todos os dados da lista.",
"name"... | 3 | stack_v2_sparse_classes_30k_train_011806 | Implement the Python class `ListaDuplamenteEncadeada` described below.
Class description:
Implement the ListaDuplamenteEncadeada class.
Method signatures and docstrings:
- def acrescentar(self, dado): Acrescenta um novo no a lista.
- def remover(self, dado): Remove um no da lista.
- def mostrar(self): Mostra todos os... | Implement the Python class `ListaDuplamenteEncadeada` described below.
Class description:
Implement the ListaDuplamenteEncadeada class.
Method signatures and docstrings:
- def acrescentar(self, dado): Acrescenta um novo no a lista.
- def remover(self, dado): Remove um no da lista.
- def mostrar(self): Mostra todos os... | 8e656f846f2de4783aa59dbed8ff57b9b4b48c09 | <|skeleton|>
class ListaDuplamenteEncadeada:
def acrescentar(self, dado):
"""Acrescenta um novo no a lista."""
<|body_0|>
def remover(self, dado):
"""Remove um no da lista."""
<|body_1|>
def mostrar(self):
"""Mostra todos os dados da lista."""
<|body_2|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListaDuplamenteEncadeada:
def acrescentar(self, dado):
"""Acrescenta um novo no a lista."""
novo_no = No(dado, None, None)
if self.cabeca is None:
self.cabeca = novo_no
self.rabo = novo_no
else:
novo_no.anterior = self.rabo
novo_n... | the_stack_v2_python_sparse | UNP/ref/Python/TADs e Classes/TAD_Listas_Duplamente_Encadeadas.py | ed1rac/AulasEstruturasDados | train | 8 | |
a5df710216898b36bd489aec2be984a72a5188e3 | [
"try:\n verify_token(request.headers)\nexcept Exception as err:\n ns.abort(401, message=err)\noffset = request.args.get('offset', '0')\nlimit = request.args.get('limit', '10')\norder_by = request.args.get('order_by', 'id')\norder = request.args.get('order', 'ASC')\nper_page = request.args.get('per_page', '10'... | <|body_start_0|>
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request.args.get('offset', '0')
limit = request.args.get('limit', '10')
order_by = request.args.get('order_by', 'id')
order = request.a... | DependenciaList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DependenciaList:
def get(self):
"""Listado de dependencias. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""Crear una dependencia"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_36k_train_024577 | 6,772 | no_license | [
{
"docstring": "Listado de dependencias. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Crear una dependencia",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009530 | Implement the Python class `DependenciaList` described below.
Class description:
Implement the DependenciaList class.
Method signatures and docstrings:
- def get(self): Listado de dependencias. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(self): Crear una dependencia | Implement the Python class `DependenciaList` described below.
Class description:
Implement the DependenciaList class.
Method signatures and docstrings:
- def get(self): Listado de dependencias. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(self): Crear una dependencia
<|sk... | e00610fac26ef3ca078fd037c0649b70fa0e9a09 | <|skeleton|>
class DependenciaList:
def get(self):
"""Listado de dependencias. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""Crear una dependencia"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DependenciaList:
def get(self):
"""Listado de dependencias. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request.args.get... | the_stack_v2_python_sparse | DOS/soa/service/genl/endpoints/dependencias.py | Telematica/knight-rider | train | 1 | |
a7118d5c274ce6cd0a564096b9914b2db04b0100 | [
"d = collections.defaultdict(int)\nfor i in intervals:\n d[i.start] += 1\n d[i.end] -= 1\nresult, room = (0, 0)\nfor key in sorted(d):\n val = d[key]\n room += val\n result = max(result, room)\nreturn result",
"intervals = sorted(intervals, key=lambda x: x.start)\nh = []\nheapq.heapify(h)\nfor inte... | <|body_start_0|>
d = collections.defaultdict(int)
for i in intervals:
d[i.start] += 1
d[i.end] -= 1
result, room = (0, 0)
for key in sorted(d):
val = d[key]
room += val
result = max(result, room)
return result
<|end_body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minMeetingRooms(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
<|body_0|>
def minMeetingRooms2(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d = co... | stack_v2_sparse_classes_36k_train_024578 | 1,452 | no_license | [
{
"docstring": ":type intervals: List[Interval] :rtype: int",
"name": "minMeetingRooms",
"signature": "def minMeetingRooms(self, intervals)"
},
{
"docstring": ":type intervals: List[Interval] :rtype: int",
"name": "minMeetingRooms2",
"signature": "def minMeetingRooms2(self, intervals)"
... | 2 | stack_v2_sparse_classes_30k_train_011109 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMeetingRooms(self, intervals): :type intervals: List[Interval] :rtype: int
- def minMeetingRooms2(self, intervals): :type intervals: List[Interval] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMeetingRooms(self, intervals): :type intervals: List[Interval] :rtype: int
- def minMeetingRooms2(self, intervals): :type intervals: List[Interval] :rtype: int
<|skeleton... | 75aef2f6c42aeb51261b9450a24099957a084d51 | <|skeleton|>
class Solution:
def minMeetingRooms(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
<|body_0|>
def minMeetingRooms2(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minMeetingRooms(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
d = collections.defaultdict(int)
for i in intervals:
d[i.start] += 1
d[i.end] -= 1
result, room = (0, 0)
for key in sorted(d):
val = d[k... | the_stack_v2_python_sparse | Python/0253_MeetingRooms2/minMeetingRooms.py | mtmmy/Leetcode | train | 3 | |
892cbc07a1524f47caaf9eddeb1e1485bb79c915 | [
"data = form.cleaned_data\nif validate_token(self.request, data['token'], allow_test=True):\n self.success_url = reverse('questions', kwargs={'course': data['course'].id})\n return super().form_valid(form)\nmessages.warning(self.request, 'Invalid Token. Please try again. Note: Tokens are caSE SensITive')\nret... | <|body_start_0|>
data = form.cleaned_data
if validate_token(self.request, data['token'], allow_test=True):
self.success_url = reverse('questions', kwargs={'course': data['course'].id})
return super().form_valid(form)
messages.warning(self.request, 'Invalid Token. Please t... | This view allows the user to choose which examination to take. Renders a self explanatory form and all fields are required. Redirects to questions view if choices are valid otherwise, returns the form with error message(s) for corrections. If the user account is inactive, they're redirected to the Home Page. | ChooseQuestionView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChooseQuestionView:
"""This view allows the user to choose which examination to take. Renders a self explanatory form and all fields are required. Redirects to questions view if choices are valid otherwise, returns the form with error message(s) for corrections. If the user account is inactive, t... | stack_v2_sparse_classes_36k_train_024579 | 29,759 | no_license | [
{
"docstring": "Validate exam Token and other requirements.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Return the data used in the templates rendering.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004299 | Implement the Python class `ChooseQuestionView` described below.
Class description:
This view allows the user to choose which examination to take. Renders a self explanatory form and all fields are required. Redirects to questions view if choices are valid otherwise, returns the form with error message(s) for correcti... | Implement the Python class `ChooseQuestionView` described below.
Class description:
This view allows the user to choose which examination to take. Renders a self explanatory form and all fields are required. Redirects to questions view if choices are valid otherwise, returns the form with error message(s) for correcti... | 06bc577d01d3dbf6c425e03dcb903977a38e377c | <|skeleton|>
class ChooseQuestionView:
"""This view allows the user to choose which examination to take. Renders a self explanatory form and all fields are required. Redirects to questions view if choices are valid otherwise, returns the form with error message(s) for corrections. If the user account is inactive, t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChooseQuestionView:
"""This view allows the user to choose which examination to take. Renders a self explanatory form and all fields are required. Redirects to questions view if choices are valid otherwise, returns the form with error message(s) for corrections. If the user account is inactive, they're redire... | the_stack_v2_python_sparse | cbt/views.py | Festusali/CBTest | train | 6 |
58aa1d543ce5acfcd856bcc6fc0801e26f8e528f | [
"super(CustomSchedule, self).__init__()\nself.d_model = d_model\nself.d_model = tf.cast(self.d_model, tf.float32)\nself.warmup_steps = warmup_steps",
"arg1 = tf.math.rsqrt(step)\narg2 = step * self.warmup_steps ** (-1.5)\nreturn tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)"
] | <|body_start_0|>
super(CustomSchedule, self).__init__()
self.d_model = d_model
self.d_model = tf.cast(self.d_model, tf.float32)
self.warmup_steps = warmup_steps
<|end_body_0|>
<|body_start_1|>
arg1 = tf.math.rsqrt(step)
arg2 = step * self.warmup_steps ** (-1.5)
r... | CustomSchedule class schedules learning rate | CustomSchedule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSchedule:
"""CustomSchedule class schedules learning rate"""
def __init__(self, d_model, warmup_steps=4000):
"""Initializer"""
<|body_0|>
def __call__(self, step):
"""Instance call"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Cust... | stack_v2_sparse_classes_36k_train_024580 | 4,278 | no_license | [
{
"docstring": "Initializer",
"name": "__init__",
"signature": "def __init__(self, d_model, warmup_steps=4000)"
},
{
"docstring": "Instance call",
"name": "__call__",
"signature": "def __call__(self, step)"
}
] | 2 | null | Implement the Python class `CustomSchedule` described below.
Class description:
CustomSchedule class schedules learning rate
Method signatures and docstrings:
- def __init__(self, d_model, warmup_steps=4000): Initializer
- def __call__(self, step): Instance call | Implement the Python class `CustomSchedule` described below.
Class description:
CustomSchedule class schedules learning rate
Method signatures and docstrings:
- def __init__(self, d_model, warmup_steps=4000): Initializer
- def __call__(self, step): Instance call
<|skeleton|>
class CustomSchedule:
"""CustomSchedu... | 2ddae38cc25d914488451b8c30e1234f1fa55ebe | <|skeleton|>
class CustomSchedule:
"""CustomSchedule class schedules learning rate"""
def __init__(self, d_model, warmup_steps=4000):
"""Initializer"""
<|body_0|>
def __call__(self, step):
"""Instance call"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomSchedule:
"""CustomSchedule class schedules learning rate"""
def __init__(self, d_model, warmup_steps=4000):
"""Initializer"""
super(CustomSchedule, self).__init__()
self.d_model = d_model
self.d_model = tf.cast(self.d_model, tf.float32)
self.warmup_steps = w... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-train.py | KoeusIss/holbertonschool-machine_learning | train | 0 |
6c4c3ee90467100e1106af89081dc4f1c63f7109 | [
"super(VoxelMorphNet, self).__init__()\ndim = len(vol_size)\nself.unet = UNetCore(dim, enc_nf, dec_nf, full_size)\nconv_fn = getattr(nn, 'Conv{0}d'.format(dim))\nself.flow = conv_fn(dec_nf[-1], dim, kernel_size=3, padding=1)\nnd = Normal(0, 1e-05)\nself.flow.weight = nn.Parameter(nd.sample(self.flow.weight.shape))\... | <|body_start_0|>
super(VoxelMorphNet, self).__init__()
dim = len(vol_size)
self.unet = UNetCore(dim, enc_nf, dec_nf, full_size)
conv_fn = getattr(nn, 'Conv{0}d'.format(dim))
self.flow = conv_fn(dec_nf[-1], dim, kernel_size=3, padding=1)
nd = Normal(0, 1e-05)
self.... | VoxelMorphNet. An unsupervised learning-based inference algorithm that uses insights from classical registration methods and makes use of recent developments inconvolutional neural networks (CNNs). VoxelMorph assumes that input images are pre-affined by an external tool. 2018 CVPR implementation of voxelmorph. TODO: ex... | VoxelMorphNet | [
"LicenseRef-scancode-cecill-b-en"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VoxelMorphNet:
"""VoxelMorphNet. An unsupervised learning-based inference algorithm that uses insights from classical registration methods and makes use of recent developments inconvolutional neural networks (CNNs). VoxelMorph assumes that input images are pre-affined by an external tool. 2018 CV... | stack_v2_sparse_classes_36k_train_024581 | 12,977 | permissive | [
{
"docstring": "Init class. Parameters ---------- vol_size: uplet volume size of the atlas. enc_nf: list of int, default [16, 32, 32, 32] the number of features maps for encoding stages. dec_nf: int, default [32, 32, 32, 32, 32, 16, 16] the number of features maps for decoding stages. full_size: bool, default F... | 2 | stack_v2_sparse_classes_30k_train_011187 | Implement the Python class `VoxelMorphNet` described below.
Class description:
VoxelMorphNet. An unsupervised learning-based inference algorithm that uses insights from classical registration methods and makes use of recent developments inconvolutional neural networks (CNNs). VoxelMorph assumes that input images are p... | Implement the Python class `VoxelMorphNet` described below.
Class description:
VoxelMorphNet. An unsupervised learning-based inference algorithm that uses insights from classical registration methods and makes use of recent developments inconvolutional neural networks (CNNs). VoxelMorph assumes that input images are p... | 7a807ed690929563ce36086eaf0998d0e8856aea | <|skeleton|>
class VoxelMorphNet:
"""VoxelMorphNet. An unsupervised learning-based inference algorithm that uses insights from classical registration methods and makes use of recent developments inconvolutional neural networks (CNNs). VoxelMorph assumes that input images are pre-affined by an external tool. 2018 CV... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VoxelMorphNet:
"""VoxelMorphNet. An unsupervised learning-based inference algorithm that uses insights from classical registration methods and makes use of recent developments inconvolutional neural networks (CNNs). VoxelMorph assumes that input images are pre-affined by an external tool. 2018 CVPR implementa... | the_stack_v2_python_sparse | pynet/models/voxelmorphnet.py | Duplums/pynet | train | 0 |
37eb6532ab3d33eaa04cc80491e77a523f1140b9 | [
"if fit_data is None and (a is None or b is None or c is None):\n raise ValueError('Either all the fit parameters or fit_data must be specified.')\nif not (fit_data is None or a is None or b is None or (c is None)):\n raise ValueError('Cannot specify fit parameters when fit_data is specified.')\nself.a = a\ns... | <|body_start_0|>
if fit_data is None and (a is None or b is None or c is None):
raise ValueError('Either all the fit parameters or fit_data must be specified.')
if not (fit_data is None or a is None or b is None or (c is None)):
raise ValueError('Cannot specify fit parameters whe... | Represents the Fundamental Plane (FP) relation between the velocity dispersion, luminosity, and effective radius for elliptical galaxies Luminosity is expressed as apparent magnitude in this form. | FundamentalPlane | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FundamentalPlane:
"""Represents the Fundamental Plane (FP) relation between the velocity dispersion, luminosity, and effective radius for elliptical galaxies Luminosity is expressed as apparent magnitude in this form."""
def __init__(self, a=None, b=None, c=None, intrinsic_scatter=0.0, fit_d... | stack_v2_sparse_classes_36k_train_024582 | 19,262 | permissive | [
{
"docstring": "Parameters ---------- a : float linear slope on the log velocity dispersion, log(vel_disp/(km/s)) b : float linear slope on the V-band apparent magnitude, or m_V/mag c : float intercept, i.e. the log effective radius, or log(R_eff/kpc), when vel_disp = m_V = 0 fit_data : str sample on which a, b... | 3 | stack_v2_sparse_classes_30k_train_017147 | Implement the Python class `FundamentalPlane` described below.
Class description:
Represents the Fundamental Plane (FP) relation between the velocity dispersion, luminosity, and effective radius for elliptical galaxies Luminosity is expressed as apparent magnitude in this form.
Method signatures and docstrings:
- def... | Implement the Python class `FundamentalPlane` described below.
Class description:
Represents the Fundamental Plane (FP) relation between the velocity dispersion, luminosity, and effective radius for elliptical galaxies Luminosity is expressed as apparent magnitude in this form.
Method signatures and docstrings:
- def... | 2a9a1b3eafbafef925bedab4b3137a3505a9b750 | <|skeleton|>
class FundamentalPlane:
"""Represents the Fundamental Plane (FP) relation between the velocity dispersion, luminosity, and effective radius for elliptical galaxies Luminosity is expressed as apparent magnitude in this form."""
def __init__(self, a=None, b=None, c=None, intrinsic_scatter=0.0, fit_d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FundamentalPlane:
"""Represents the Fundamental Plane (FP) relation between the velocity dispersion, luminosity, and effective radius for elliptical galaxies Luminosity is expressed as apparent magnitude in this form."""
def __init__(self, a=None, b=None, c=None, intrinsic_scatter=0.0, fit_data=None):
... | the_stack_v2_python_sparse | baobab/bnn_priors/parameter_models.py | jiwoncpark/baobab | train | 9 |
41334ecdb5f3a7c2bf8aa35df405ac1b2aff2510 | [
"self.spec = spec\nself.typemap = {}\nfor x, y in vars(spec).items():\n try:\n if issubclass(y, Element):\n if hasattr(y, 'xmlname'):\n x = y.xmlname\n self.typemap[x] = y\n except TypeError:\n pass",
"if type(source) == type(u''):\n source = source.enco... | <|body_start_0|>
self.spec = spec
self.typemap = {}
for x, y in vars(spec).items():
try:
if issubclass(y, Element):
if hasattr(y, 'xmlname'):
x = y.xmlname
self.typemap[x] = y
except TypeError... | ObjectParser | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectParser:
def __init__(self, spec):
"""initialize ObjectParser with the Element tags contained in spec which are later used for tagname-to-Object parsing."""
<|body_0|>
def parse(self, source):
"""return xist-like objects parsed from UTF-8 string or dom tree. Fra... | stack_v2_sparse_classes_36k_train_024583 | 2,688 | permissive | [
{
"docstring": "initialize ObjectParser with the Element tags contained in spec which are later used for tagname-to-Object parsing.",
"name": "__init__",
"signature": "def __init__(self, spec)"
},
{
"docstring": "return xist-like objects parsed from UTF-8 string or dom tree. Fragment contains no... | 3 | stack_v2_sparse_classes_30k_train_021344 | Implement the Python class `ObjectParser` described below.
Class description:
Implement the ObjectParser class.
Method signatures and docstrings:
- def __init__(self, spec): initialize ObjectParser with the Element tags contained in spec which are later used for tagname-to-Object parsing.
- def parse(self, source): r... | Implement the Python class `ObjectParser` described below.
Class description:
Implement the ObjectParser class.
Method signatures and docstrings:
- def __init__(self, spec): initialize ObjectParser with the Element tags contained in spec which are later used for tagname-to-Object parsing.
- def parse(self, source): r... | b3f237eedea4aa9a1014ed49487585359027a8e9 | <|skeleton|>
class ObjectParser:
def __init__(self, spec):
"""initialize ObjectParser with the Element tags contained in spec which are later used for tagname-to-Object parsing."""
<|body_0|>
def parse(self, source):
"""return xist-like objects parsed from UTF-8 string or dom tree. Fra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectParser:
def __init__(self, spec):
"""initialize ObjectParser with the Element tags contained in spec which are later used for tagname-to-Object parsing."""
self.spec = spec
self.typemap = {}
for x, y in vars(spec).items():
try:
if issubclass(y,... | the_stack_v2_python_sparse | Products/SilvaDocument/transform/ObjectParser.py | silvacms/Products.SilvaDocument | train | 0 | |
aafcd52dd8d1454874bba62346aa891924fdf8ea | [
"path = os.path.join(self.directory, self.filepath)\nlog_report('INFO', 'path: ' + str(path), self)\npoints = PointDataFileHandler.parse_point_data_file(path, self)\nlog_report('INFO', 'Number points: ' + str(len(points)), self)\nreconstruction_collection = add_collection('Reconstruction Collection')\nself.import_p... | <|body_start_0|>
path = os.path.join(self.directory, self.filepath)
log_report('INFO', 'path: ' + str(path), self)
points = PointDataFileHandler.parse_point_data_file(path, self)
log_report('INFO', 'Number points: ' + str(len(points)), self)
reconstruction_collection = add_collec... | Import point data (e.g. a :code:`PLY` file) as point cloud. | ImportPointDataOperator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportPointDataOperator:
"""Import point data (e.g. a :code:`PLY` file) as point cloud."""
def execute(self, context):
"""Import a file with point data (e.g. :code:`PLY`)."""
<|body_0|>
def invoke(self, context, event):
"""Set the default import options before ru... | stack_v2_sparse_classes_36k_train_024584 | 2,347 | permissive | [
{
"docstring": "Import a file with point data (e.g. :code:`PLY`).",
"name": "execute",
"signature": "def execute(self, context)"
},
{
"docstring": "Set the default import options before running the operator.",
"name": "invoke",
"signature": "def invoke(self, context, event)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_019947 | Implement the Python class `ImportPointDataOperator` described below.
Class description:
Import point data (e.g. a :code:`PLY` file) as point cloud.
Method signatures and docstrings:
- def execute(self, context): Import a file with point data (e.g. :code:`PLY`).
- def invoke(self, context, event): Set the default imp... | Implement the Python class `ImportPointDataOperator` described below.
Class description:
Import point data (e.g. a :code:`PLY` file) as point cloud.
Method signatures and docstrings:
- def execute(self, context): Import a file with point data (e.g. :code:`PLY`).
- def invoke(self, context, event): Set the default imp... | da404ebf8d4412196c2740f0b569cbf9e542952d | <|skeleton|>
class ImportPointDataOperator:
"""Import point data (e.g. a :code:`PLY` file) as point cloud."""
def execute(self, context):
"""Import a file with point data (e.g. :code:`PLY`)."""
<|body_0|>
def invoke(self, context, event):
"""Set the default import options before ru... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImportPointDataOperator:
"""Import point data (e.g. a :code:`PLY` file) as point cloud."""
def execute(self, context):
"""Import a file with point data (e.g. :code:`PLY`)."""
path = os.path.join(self.directory, self.filepath)
log_report('INFO', 'path: ' + str(path), self)
... | the_stack_v2_python_sparse | photogrammetry_importer/operators/point_data_import_op.py | SBCV/Blender-Addon-Photogrammetry-Importer | train | 718 |
931b24d1dcb401a8af1ad26baa060db0f0396a7e | [
"ids_lst = User.load_all_ids_from_db()\nselected_users = list()\nusers_In_Day = random.randint(10, len(ids_lst[0]) - 1)\nfor i in range(users_In_Day):\n idx = random.randint(0, len(ids_lst[0]) - 1)\n selected_users.append(ids_lst[0][idx][0])\nreturn selected_users",
"positions = list()\nx_pos = random.unifo... | <|body_start_0|>
ids_lst = User.load_all_ids_from_db()
selected_users = list()
users_In_Day = random.randint(10, len(ids_lst[0]) - 1)
for i in range(users_In_Day):
idx = random.randint(0, len(ids_lst[0]) - 1)
selected_users.append(ids_lst[0][idx][0])
retur... | UsersDataExtraction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsersDataExtraction:
def random_users():
"""based on the number of the active users in each day, randomly select user ids from user table :return: list of the active user ids"""
<|body_0|>
def random_user_location(cls, step_size=0.5):
"""create locations based on def... | stack_v2_sparse_classes_36k_train_024585 | 2,716 | permissive | [
{
"docstring": "based on the number of the active users in each day, randomly select user ids from user table :return: list of the active user ids",
"name": "random_users",
"signature": "def random_users()"
},
{
"docstring": "create locations based on defined step size and number of steps in the... | 3 | stack_v2_sparse_classes_30k_test_000984 | Implement the Python class `UsersDataExtraction` described below.
Class description:
Implement the UsersDataExtraction class.
Method signatures and docstrings:
- def random_users(): based on the number of the active users in each day, randomly select user ids from user table :return: list of the active user ids
- def... | Implement the Python class `UsersDataExtraction` described below.
Class description:
Implement the UsersDataExtraction class.
Method signatures and docstrings:
- def random_users(): based on the number of the active users in each day, randomly select user ids from user table :return: list of the active user ids
- def... | b667ef6e04ea4e3206760f9dc2035d425b6e26f5 | <|skeleton|>
class UsersDataExtraction:
def random_users():
"""based on the number of the active users in each day, randomly select user ids from user table :return: list of the active user ids"""
<|body_0|>
def random_user_location(cls, step_size=0.5):
"""create locations based on def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsersDataExtraction:
def random_users():
"""based on the number of the active users in each day, randomly select user ids from user table :return: list of the active user ids"""
ids_lst = User.load_all_ids_from_db()
selected_users = list()
users_In_Day = random.randint(10, len(... | the_stack_v2_python_sparse | build/lib/chainedSCT/extraction/location_Extraction.py | MSBeni/SmartContactTracing_Chained | train | 3 | |
debd26906a2455c022d5568877e1f970f3533849 | [
"logger = logging.getLogger()\nlogger.setLevel(logging.INFO)\nlog_dir = os.path.join(MODULE_PATH, 'logs')\nif not os.path.isdir(log_dir):\n os.mkdir(log_dir)\nhandler = DayRotatingTimeHandler(os.path.join(log_dir, 'hqc_log.log'))\naux = '%(asctime)s | %(processName)s | %(levelname)s | %(message)s'\nformatter = l... | <|body_start_0|>
logger = logging.getLogger()
logger.setLevel(logging.INFO)
log_dir = os.path.join(MODULE_PATH, 'logs')
if not os.path.isdir(log_dir):
os.mkdir(log_dir)
handler = DayRotatingTimeHandler(os.path.join(log_dir, 'hqc_log.log'))
aux = '%(asctime)s |... | Plugin managing the application logging. | LogPlugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogPlugin:
"""Plugin managing the application logging."""
def start_logging(self, std=True):
"""Start the log system. Parameters ---------- std : bool, optionnal Should stdout and stderr be redirected to a logger."""
<|body_0|>
def add_handler(self, id, handler=None, log... | stack_v2_sparse_classes_36k_train_024586 | 6,638 | no_license | [
{
"docstring": "Start the log system. Parameters ---------- std : bool, optionnal Should stdout and stderr be redirected to a logger.",
"name": "start_logging",
"signature": "def start_logging(self, std=True)"
},
{
"docstring": "Add a handler to the specified logger. Parameters ---------- id : u... | 6 | stack_v2_sparse_classes_30k_train_016918 | Implement the Python class `LogPlugin` described below.
Class description:
Plugin managing the application logging.
Method signatures and docstrings:
- def start_logging(self, std=True): Start the log system. Parameters ---------- std : bool, optionnal Should stdout and stderr be redirected to a logger.
- def add_han... | Implement the Python class `LogPlugin` described below.
Class description:
Plugin managing the application logging.
Method signatures and docstrings:
- def start_logging(self, std=True): Start the log system. Parameters ---------- std : bool, optionnal Should stdout and stderr be redirected to a logger.
- def add_han... | 6d54091d2c1c436a4dc07727a66be5a536ea8414 | <|skeleton|>
class LogPlugin:
"""Plugin managing the application logging."""
def start_logging(self, std=True):
"""Start the log system. Parameters ---------- std : bool, optionnal Should stdout and stderr be redirected to a logger."""
<|body_0|>
def add_handler(self, id, handler=None, log... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogPlugin:
"""Plugin managing the application logging."""
def start_logging(self, std=True):
"""Start the log system. Parameters ---------- std : bool, optionnal Should stdout and stderr be redirected to a logger."""
logger = logging.getLogger()
logger.setLevel(logging.INFO)
... | the_stack_v2_python_sparse | hqc_meas/utils/log/plugin.py | MatthieuDartiailh/HQCMeas | train | 11 |
875c3acb9b521924c09ab3c2f06815aebaf398ef | [
"hearing_list = response.css('.field-item ul')[1]\nfor item in hearing_list.css('li'):\n item_text = ' '.join(item.css('*::text').extract())\n meeting = Meeting(title='Public Hearing', description='', classification=FORUM, start=self._parse_start(item_text), end=None, all_day=False, time_notes='', location=se... | <|body_start_0|>
hearing_list = response.css('.field-item ul')[1]
for item in hearing_list.css('li'):
item_text = ' '.join(item.css('*::text').extract())
meeting = Meeting(title='Public Hearing', description='', classification=FORUM, start=self._parse_start(item_text), end=None, ... | CookZoningSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CookZoningSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_start(self, text):
"""Parse start datetime as a naive datetime obj... | stack_v2_sparse_classes_36k_train_024587 | 2,526 | permissive | [
{
"docstring": "`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Parse start datetime as a naive datetime object.",
"name": "_parse_st... | 3 | stack_v2_sparse_classes_30k_train_016437 | Implement the Python class `CookZoningSpider` described below.
Class description:
Implement the CookZoningSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.
- def _... | Implement the Python class `CookZoningSpider` described below.
Class description:
Implement the CookZoningSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.
- def _... | 611fce6a2705446e25a2fc33e32090a571eb35d1 | <|skeleton|>
class CookZoningSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_start(self, text):
"""Parse start datetime as a naive datetime obj... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CookZoningSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
hearing_list = response.css('.field-item ul')[1]
for item in hearing_list.css('li'):
item_text ... | the_stack_v2_python_sparse | city_scrapers/spiders/cook_zoning.py | City-Bureau/city-scrapers | train | 308 | |
4b9208117e9582f217238dcde22b44d6a950c131 | [
"self.min_length = min_length\nself.max_length = max_length\nself.seed = seed\nsuper().__init__()",
"track: MidiTrack = mid.tracks[track_index]\nif 'chord_track' in kwargs and kwargs['chord_track'] is not None:\n chord_track_ind = kwargs['chord_track']\n chord_track = mid.tracks[chord_track_ind]\nelse:\n ... | <|body_start_0|>
self.min_length = min_length
self.max_length = max_length
self.seed = seed
super().__init__()
<|end_body_0|>
<|body_start_1|>
track: MidiTrack = mid.tracks[track_index]
if 'chord_track' in kwargs and kwargs['chord_track'] is not None:
chord_t... | RandomSegmenter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomSegmenter:
def __init__(self, seed: Optional[int], min_length: float=1, max_length: float=2):
"""A ``Segmenter`` which is similar to ``TimeSegmenter``, but extracts random length ``NoteSegments`` instead of fixed length ones. Args: seed: The random seed used to determine segment le... | stack_v2_sparse_classes_36k_train_024588 | 3,056 | no_license | [
{
"docstring": "A ``Segmenter`` which is similar to ``TimeSegmenter``, but extracts random length ``NoteSegments`` instead of fixed length ones. Args: seed: The random seed used to determine segment lengths. If None, uses the Numpy default random seed. min_length: The minimum length of each segment (in seconds)... | 2 | stack_v2_sparse_classes_30k_train_005277 | Implement the Python class `RandomSegmenter` described below.
Class description:
Implement the RandomSegmenter class.
Method signatures and docstrings:
- def __init__(self, seed: Optional[int], min_length: float=1, max_length: float=2): A ``Segmenter`` which is similar to ``TimeSegmenter``, but extracts random length... | Implement the Python class `RandomSegmenter` described below.
Class description:
Implement the RandomSegmenter class.
Method signatures and docstrings:
- def __init__(self, seed: Optional[int], min_length: float=1, max_length: float=2): A ``Segmenter`` which is similar to ``TimeSegmenter``, but extracts random length... | f78b35274f49f6ae54ca7bc02691ab5db45eda36 | <|skeleton|>
class RandomSegmenter:
def __init__(self, seed: Optional[int], min_length: float=1, max_length: float=2):
"""A ``Segmenter`` which is similar to ``TimeSegmenter``, but extracts random length ``NoteSegments`` instead of fixed length ones. Args: seed: The random seed used to determine segment le... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomSegmenter:
def __init__(self, seed: Optional[int], min_length: float=1, max_length: float=2):
"""A ``Segmenter`` which is similar to ``TimeSegmenter``, but extracts random length ``NoteSegments`` instead of fixed length ones. Args: seed: The random seed used to determine segment lengths. If None... | the_stack_v2_python_sparse | project/algorithms/core/random_segmenter.py | jamesb456/final-year-project | train | 0 | |
770c254009644d08f7816e0431ee2974a9b1a992 | [
"for c in pipe.components[::-1]:\n return OutputLevelUtils.resolve_component_to_output_level(pipe, c)\nreturn NLP_LEVELS.DOCUMENT",
"if NLP_FEATURES.DOCUMENT in component_to_resolve.spark_input_column_names:\n return NLP_LEVELS.DOCUMENT\nif NLP_FEATURES.SENTENCE in component_to_resolve.spark_input_column_na... | <|body_start_0|>
for c in pipe.components[::-1]:
return OutputLevelUtils.resolve_component_to_output_level(pipe, c)
return NLP_LEVELS.DOCUMENT
<|end_body_0|>
<|body_start_1|>
if NLP_FEATURES.DOCUMENT in component_to_resolve.spark_input_column_names:
return NLP_LEVELS.DOC... | Resolve output level of pipeline and components | OutputLevelUtils | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutputLevelUtils:
"""Resolve output level of pipeline and components"""
def infer_prediction_output_level(pipe) -> NlpLevel:
"""This function checks the LAST component_to_resolve of the NLU pipeline and infers from that the output level via checking the components' info. :param pipe:... | stack_v2_sparse_classes_36k_train_024589 | 5,752 | permissive | [
{
"docstring": "This function checks the LAST component_to_resolve of the NLU pipeline and infers from that the output level via checking the components' info. :param pipe: to infer output level for :return returns inferred output level",
"name": "infer_prediction_output_level",
"signature": "def infer_... | 5 | stack_v2_sparse_classes_30k_test_000651 | Implement the Python class `OutputLevelUtils` described below.
Class description:
Resolve output level of pipeline and components
Method signatures and docstrings:
- def infer_prediction_output_level(pipe) -> NlpLevel: This function checks the LAST component_to_resolve of the NLU pipeline and infers from that the out... | Implement the Python class `OutputLevelUtils` described below.
Class description:
Resolve output level of pipeline and components
Method signatures and docstrings:
- def infer_prediction_output_level(pipe) -> NlpLevel: This function checks the LAST component_to_resolve of the NLU pipeline and infers from that the out... | 614bc2ff94c80a7ebc34a78720ef29a1bf7080e0 | <|skeleton|>
class OutputLevelUtils:
"""Resolve output level of pipeline and components"""
def infer_prediction_output_level(pipe) -> NlpLevel:
"""This function checks the LAST component_to_resolve of the NLU pipeline and infers from that the output level via checking the components' info. :param pipe:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutputLevelUtils:
"""Resolve output level of pipeline and components"""
def infer_prediction_output_level(pipe) -> NlpLevel:
"""This function checks the LAST component_to_resolve of the NLU pipeline and infers from that the output level via checking the components' info. :param pipe: to infer out... | the_stack_v2_python_sparse | nlu/pipe/utils/output_level_resolution_utils.py | ahmedlone127/nlu | train | 0 |
0623dfd86a435ef1695bfa540bec1d19ccbe511e | [
"name = 'askdjkaj1213asd'\neffect_without_modifiers = CardEffect.objects.filter(has_modifier=False).first()\neffect_with_modifiers = CardEffect.objects.filter(has_modifier=True).first()\nself.assertRaises(ProposedCardInfo.DoesNotExist, ProposedCardInfo.objects.get, name=name)\nself.assertIsNotNone(effect_without_mo... | <|body_start_0|>
name = 'askdjkaj1213asd'
effect_without_modifiers = CardEffect.objects.filter(has_modifier=False).first()
effect_with_modifiers = CardEffect.objects.filter(has_modifier=True).first()
self.assertRaises(ProposedCardInfo.DoesNotExist, ProposedCardInfo.objects.get, name=name... | WholeProposedCardDetailsTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WholeProposedCardDetailsTestCase:
def test_get1(self):
"""Scenario: Proposed card is created in database. GET request is performed to view details of this card. Expected result: Response status code OK 200. Card returned in response has proper data."""
<|body_0|>
def test_ge... | stack_v2_sparse_classes_36k_train_024590 | 42,884 | permissive | [
{
"docstring": "Scenario: Proposed card is created in database. GET request is performed to view details of this card. Expected result: Response status code OK 200. Card returned in response has proper data.",
"name": "test_get1",
"signature": "def test_get1(self)"
},
{
"docstring": "Scenario: G... | 3 | stack_v2_sparse_classes_30k_train_004615 | Implement the Python class `WholeProposedCardDetailsTestCase` described below.
Class description:
Implement the WholeProposedCardDetailsTestCase class.
Method signatures and docstrings:
- def test_get1(self): Scenario: Proposed card is created in database. GET request is performed to view details of this card. Expect... | Implement the Python class `WholeProposedCardDetailsTestCase` described below.
Class description:
Implement the WholeProposedCardDetailsTestCase class.
Method signatures and docstrings:
- def test_get1(self): Scenario: Proposed card is created in database. GET request is performed to view details of this card. Expect... | ea812b13de0cd6c47c541cbede2d016a7837b4b8 | <|skeleton|>
class WholeProposedCardDetailsTestCase:
def test_get1(self):
"""Scenario: Proposed card is created in database. GET request is performed to view details of this card. Expected result: Response status code OK 200. Card returned in response has proper data."""
<|body_0|>
def test_ge... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WholeProposedCardDetailsTestCase:
def test_get1(self):
"""Scenario: Proposed card is created in database. GET request is performed to view details of this card. Expected result: Response status code OK 200. Card returned in response has proper data."""
name = 'askdjkaj1213asd'
effect_w... | the_stack_v2_python_sparse | WMIAdventure/backend/WMIAdventure_backend/proposed_content/tests.py | Michal-Czekanski/WMIAdventure-1 | train | 0 | |
f5aa867391c66b9237c4972a6eaea6b4f9bf7696 | [
"endpoint = LookupEndpoint.CUSTOMER_ID.value.format(customerId=customer_id)\nquery_parameters = self._copy_query_parameters()\nquery_parameters['fixture'] = fixture\nreturn self._get(url=self._build_url(endpoint), query_parameters=query_parameters)",
"endpoint = LookupEndpoint.SEARCH.value\nquery_parameters = sel... | <|body_start_0|>
endpoint = LookupEndpoint.CUSTOMER_ID.value.format(customerId=customer_id)
query_parameters = self._copy_query_parameters()
query_parameters['fixture'] = fixture
return self._get(url=self._build_url(endpoint), query_parameters=query_parameters)
<|end_body_0|>
<|body_sta... | LookupClient | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LookupClient:
def get_customer(self, customer_id, fixture=None):
"""GET /central/lookup/customer/{customerId} :param int customer_id: path parameter :param bool fixture: fixture query parameter (If true, will return hardcoded values and not call HQ) :return: Response object :rtype: reque... | stack_v2_sparse_classes_36k_train_024591 | 3,190 | permissive | [
{
"docstring": "GET /central/lookup/customer/{customerId} :param int customer_id: path parameter :param bool fixture: fixture query parameter (If true, will return hardcoded values and not call HQ) :return: Response object :rtype: requests.Response",
"name": "get_customer",
"signature": "def get_custome... | 5 | stack_v2_sparse_classes_30k_train_021437 | Implement the Python class `LookupClient` described below.
Class description:
Implement the LookupClient class.
Method signatures and docstrings:
- def get_customer(self, customer_id, fixture=None): GET /central/lookup/customer/{customerId} :param int customer_id: path parameter :param bool fixture: fixture query par... | Implement the Python class `LookupClient` described below.
Class description:
Implement the LookupClient class.
Method signatures and docstrings:
- def get_customer(self, customer_id, fixture=None): GET /central/lookup/customer/{customerId} :param int customer_id: path parameter :param bool fixture: fixture query par... | 4431af164eb4baf52e26e8842e017cad1609a279 | <|skeleton|>
class LookupClient:
def get_customer(self, customer_id, fixture=None):
"""GET /central/lookup/customer/{customerId} :param int customer_id: path parameter :param bool fixture: fixture query parameter (If true, will return hardcoded values and not call HQ) :return: Response object :rtype: reque... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LookupClient:
def get_customer(self, customer_id, fixture=None):
"""GET /central/lookup/customer/{customerId} :param int customer_id: path parameter :param bool fixture: fixture query parameter (If true, will return hardcoded values and not call HQ) :return: Response object :rtype: requests.Response""... | the_stack_v2_python_sparse | q2_api_client/clients/central/lookup_client.py | jcook00/q2-api-client | train | 0 | |
ba008f71ec629db5107a315f0747981d2faac79c | [
"self.ID = trial_nr\nself.bar_pass_direction_at_TR = bar_pass_direction_at_TR\nself.bar_midpoint_at_TR = bar_midpoint_at_TR\nself.trial_type_at_TR = trial_type_at_TR\nself.session = session\nself.phase_durations = phase_durations\nself.phase_names = phase_names\nsuper().__init__(session, trial_nr, phase_durations, ... | <|body_start_0|>
self.ID = trial_nr
self.bar_pass_direction_at_TR = bar_pass_direction_at_TR
self.bar_midpoint_at_TR = bar_midpoint_at_TR
self.trial_type_at_TR = trial_type_at_TR
self.session = session
self.phase_durations = phase_durations
self.phase_names = phas... | FeatureTrial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureTrial:
def __init__(self, session, trial_nr, phase_durations, phase_names, bar_pass_direction_at_TR, bar_midpoint_at_TR, trial_type_at_TR, num_bars_on_screen=2, timing='seconds', *args, **kwargs):
"""Initializes a FeatureTrial object. Parameters ---------- session : exptools Sessi... | stack_v2_sparse_classes_36k_train_024592 | 20,707 | no_license | [
{
"docstring": "Initializes a FeatureTrial object. Parameters ---------- session : exptools Session object A Session object (needed for metadata) trial_nr: int Trial nr of trial timing : str The \"units\" of the phase durations. Default is 'seconds', where we assume the phase-durations are in seconds. The other... | 5 | stack_v2_sparse_classes_30k_val_000641 | Implement the Python class `FeatureTrial` described below.
Class description:
Implement the FeatureTrial class.
Method signatures and docstrings:
- def __init__(self, session, trial_nr, phase_durations, phase_names, bar_pass_direction_at_TR, bar_midpoint_at_TR, trial_type_at_TR, num_bars_on_screen=2, timing='seconds'... | Implement the Python class `FeatureTrial` described below.
Class description:
Implement the FeatureTrial class.
Method signatures and docstrings:
- def __init__(self, session, trial_nr, phase_durations, phase_names, bar_pass_direction_at_TR, bar_midpoint_at_TR, trial_type_at_TR, num_bars_on_screen=2, timing='seconds'... | 41fd68e93607570c2f71c33cf1d8bce609b229bf | <|skeleton|>
class FeatureTrial:
def __init__(self, session, trial_nr, phase_durations, phase_names, bar_pass_direction_at_TR, bar_midpoint_at_TR, trial_type_at_TR, num_bars_on_screen=2, timing='seconds', *args, **kwargs):
"""Initializes a FeatureTrial object. Parameters ---------- session : exptools Sessi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureTrial:
def __init__(self, session, trial_nr, phase_durations, phase_names, bar_pass_direction_at_TR, bar_midpoint_at_TR, trial_type_at_TR, num_bars_on_screen=2, timing='seconds', *args, **kwargs):
"""Initializes a FeatureTrial object. Parameters ---------- session : exptools Session object A Se... | the_stack_v2_python_sparse | experiment/trial.py | iverissimo/feature_attention_mapping | train | 0 | |
4dc8223b3c0d9b54b669b139449a49bd4c4e5fc5 | [
"Frame.__init__(self, spec.FRAME_HEADER, channel_number)\nself.body_size = body_size\nself.properties = props",
"pieces = self.properties.encode()\npieces.insert(0, struct.pack('>HxxQ', self.properties.INDEX, self.body_size))\nreturn self._marshal(pieces)"
] | <|body_start_0|>
Frame.__init__(self, spec.FRAME_HEADER, channel_number)
self.body_size = body_size
self.properties = props
<|end_body_0|>
<|body_start_1|>
pieces = self.properties.encode()
pieces.insert(0, struct.pack('>HxxQ', self.properties.INDEX, self.body_size))
ret... | Header frame object mapping. AMQP content header frames are mapped on top of this class for creating or accessing their data and attributes. | Header | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Header:
"""Header frame object mapping. AMQP content header frames are mapped on top of this class for creating or accessing their data and attributes."""
def __init__(self, channel_number, body_size, props):
"""Parameters: - channel_number: int - body_size: int - props: spec.BasicPr... | stack_v2_sparse_classes_36k_train_024593 | 12,681 | no_license | [
{
"docstring": "Parameters: - channel_number: int - body_size: int - props: spec.BasicProperties object",
"name": "__init__",
"signature": "def __init__(self, channel_number, body_size, props)"
},
{
"docstring": "Return the AMQP binary encoded value of the frame",
"name": "marshal",
"sig... | 2 | stack_v2_sparse_classes_30k_train_007066 | Implement the Python class `Header` described below.
Class description:
Header frame object mapping. AMQP content header frames are mapped on top of this class for creating or accessing their data and attributes.
Method signatures and docstrings:
- def __init__(self, channel_number, body_size, props): Parameters: - c... | Implement the Python class `Header` described below.
Class description:
Header frame object mapping. AMQP content header frames are mapped on top of this class for creating or accessing their data and attributes.
Method signatures and docstrings:
- def __init__(self, channel_number, body_size, props): Parameters: - c... | a427d8b2790350b524b66ac14534fd836ae10476 | <|skeleton|>
class Header:
"""Header frame object mapping. AMQP content header frames are mapped on top of this class for creating or accessing their data and attributes."""
def __init__(self, channel_number, body_size, props):
"""Parameters: - channel_number: int - body_size: int - props: spec.BasicPr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Header:
"""Header frame object mapping. AMQP content header frames are mapped on top of this class for creating or accessing their data and attributes."""
def __init__(self, channel_number, body_size, props):
"""Parameters: - channel_number: int - body_size: int - props: spec.BasicProperties obje... | the_stack_v2_python_sparse | scripts/autoland/vendor/lib/python/pika/frame.py | lsblakk/tools | train | 1 |
f2e8ca674b5567cdb1f4ff51791ea953a227b17e | [
"if self.station in source_data:\n if 'site_antenna' not in source_data[self.station]:\n raise MissingDataError(f'Station {self.station!r} is not given in SITE/ANTENNA SINEX block.')\n raw_info = source_data[self.station]['site_antenna']\nelif self.station.upper() in source_data:\n if 'site_antenna'... | <|body_start_0|>
if self.station in source_data:
if 'site_antenna' not in source_data[self.station]:
raise MissingDataError(f'Station {self.station!r} is not given in SITE/ANTENNA SINEX block.')
raw_info = source_data[self.station]['site_antenna']
elif self.statio... | AntennaHistorySinex | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AntennaHistorySinex:
def _process_history(self, source_data: Dict) -> Dict[Tuple[datetime, datetime], 'AntennaSinex']:
"""Process antenna site history from SINEX file Args: source_data: Source data with site information. Returns: Dictionary with (date_from, date_to) tuple as key. The val... | stack_v2_sparse_classes_36k_train_024594 | 5,951 | permissive | [
{
"docstring": "Process antenna site history from SINEX file Args: source_data: Source data with site information. Returns: Dictionary with (date_from, date_to) tuple as key. The values are AntennaSinex objects.",
"name": "_process_history",
"signature": "def _process_history(self, source_data: Dict) ->... | 2 | null | Implement the Python class `AntennaHistorySinex` described below.
Class description:
Implement the AntennaHistorySinex class.
Method signatures and docstrings:
- def _process_history(self, source_data: Dict) -> Dict[Tuple[datetime, datetime], 'AntennaSinex']: Process antenna site history from SINEX file Args: source_... | Implement the Python class `AntennaHistorySinex` described below.
Class description:
Implement the AntennaHistorySinex class.
Method signatures and docstrings:
- def _process_history(self, source_data: Dict) -> Dict[Tuple[datetime, datetime], 'AntennaSinex']: Process antenna site history from SINEX file Args: source_... | 31939afee943273b23fa0a5ef193cfecfa68d6c0 | <|skeleton|>
class AntennaHistorySinex:
def _process_history(self, source_data: Dict) -> Dict[Tuple[datetime, datetime], 'AntennaSinex']:
"""Process antenna site history from SINEX file Args: source_data: Source data with site information. Returns: Dictionary with (date_from, date_to) tuple as key. The val... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AntennaHistorySinex:
def _process_history(self, source_data: Dict) -> Dict[Tuple[datetime, datetime], 'AntennaSinex']:
"""Process antenna site history from SINEX file Args: source_data: Source data with site information. Returns: Dictionary with (date_from, date_to) tuple as key. The values are Antenn... | the_stack_v2_python_sparse | midgard/site_info/antenna.py | kartverket/midgard | train | 18 | |
103a6b89ba157fce8cc9c4f9dcbf9ddeb929ca11 | [
"dev = self.selectedDevice(c)\ninstrumentName = (yield dev.query('ID?'))\nreturnValue(instrumentName)",
"dev = self.selectedDevice(c)\nAcquireMode = (yield dev.query('ACQuire:MODe?'))\nreturnValue(AcquireMode)"
] | <|body_start_0|>
dev = self.selectedDevice(c)
instrumentName = (yield dev.query('ID?'))
returnValue(instrumentName)
<|end_body_0|>
<|body_start_1|>
dev = self.selectedDevice(c)
AcquireMode = (yield dev.query('ACQuire:MODe?'))
returnValue(AcquireMode)
<|end_body_1|>
| TBS1052B | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TBS1052B:
def getInstrumentName(self, c):
"""Return the instrument name."""
<|body_0|>
def getAcquireMode(self, c):
"""Returns the instrument acquire mode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dev = self.selectedDevice(c)
instrumen... | stack_v2_sparse_classes_36k_train_024595 | 1,633 | no_license | [
{
"docstring": "Return the instrument name.",
"name": "getInstrumentName",
"signature": "def getInstrumentName(self, c)"
},
{
"docstring": "Returns the instrument acquire mode",
"name": "getAcquireMode",
"signature": "def getAcquireMode(self, c)"
}
] | 2 | null | Implement the Python class `TBS1052B` described below.
Class description:
Implement the TBS1052B class.
Method signatures and docstrings:
- def getInstrumentName(self, c): Return the instrument name.
- def getAcquireMode(self, c): Returns the instrument acquire mode | Implement the Python class `TBS1052B` described below.
Class description:
Implement the TBS1052B class.
Method signatures and docstrings:
- def getInstrumentName(self, c): Return the instrument name.
- def getAcquireMode(self, c): Returns the instrument acquire mode
<|skeleton|>
class TBS1052B:
def getInstrumen... | 6f041503ff9967e7ed52cfb619d9cc21d66b5ad6 | <|skeleton|>
class TBS1052B:
def getInstrumentName(self, c):
"""Return the instrument name."""
<|body_0|>
def getAcquireMode(self, c):
"""Returns the instrument acquire mode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TBS1052B:
def getInstrumentName(self, c):
"""Return the instrument name."""
dev = self.selectedDevice(c)
instrumentName = (yield dev.query('ID?'))
returnValue(instrumentName)
def getAcquireMode(self, c):
"""Returns the instrument acquire mode"""
dev = self.... | the_stack_v2_python_sparse | instruments/gpibdevices/Tektronix_TBS1052B_sampling_scope.py | McDermott-Group/servers | train | 0 | |
08f88e42a369d339d135957e8e4088a820344469 | [
"area = 0\ncol_max = [0] * len(grid[0])\nfor row in grid:\n for i, elem in enumerate(zip(row, col_max)):\n if elem[0] > elem[1]:\n col_max[i] = elem[0]\n row_max = 0\n for col in row:\n if col > 0:\n area += 1\n row_max = max(row_max, col)\n area += row_max... | <|body_start_0|>
area = 0
col_max = [0] * len(grid[0])
for row in grid:
for i, elem in enumerate(zip(row, col_max)):
if elem[0] > elem[1]:
col_max[i] = elem[0]
row_max = 0
for col in row:
if col > 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def projectionArea(self, grid):
"""Note: grid is N * N Top projection: any grid[i][j] > 0 will be projected with area of 1 Side projection: the projected area for each row would the largest element in the row Front projection: the projected area for each column would the larges... | stack_v2_sparse_classes_36k_train_024596 | 1,835 | no_license | [
{
"docstring": "Note: grid is N * N Top projection: any grid[i][j] > 0 will be projected with area of 1 Side projection: the projected area for each row would the largest element in the row Front projection: the projected area for each column would the largest element in the column Time: O(N^2) Space: O(N) :typ... | 2 | stack_v2_sparse_classes_30k_train_003056 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def projectionArea(self, grid): Note: grid is N * N Top projection: any grid[i][j] > 0 will be projected with area of 1 Side projection: the projected area for each row would the... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def projectionArea(self, grid): Note: grid is N * N Top projection: any grid[i][j] > 0 will be projected with area of 1 Side projection: the projected area for each row would the... | 143aa25f92f3827aa379f29c67a9b7ec3757fef9 | <|skeleton|>
class Solution:
def projectionArea(self, grid):
"""Note: grid is N * N Top projection: any grid[i][j] > 0 will be projected with area of 1 Side projection: the projected area for each row would the largest element in the row Front projection: the projected area for each column would the larges... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def projectionArea(self, grid):
"""Note: grid is N * N Top projection: any grid[i][j] > 0 will be projected with area of 1 Side projection: the projected area for each row would the largest element in the row Front projection: the projected area for each column would the largest element in t... | the_stack_v2_python_sparse | py/leetcode_py/887.py | imsure/tech-interview-prep | train | 0 | |
cd2f4524b8b0f1bf5869c7228957671d012236c2 | [
"super().__init__()\nchannels = size // 2\nself.kernel_size = kernel_size\nif causal:\n self.lorder = kernel_size - 1\n padding = 0\nelse:\n self.lorder = 0\n padding = (kernel_size - 1) // 2\nself.conv = torch.nn.Conv1d(channels, channels, kernel_size, stride=1, padding=padding, groups=channels)\nself.... | <|body_start_0|>
super().__init__()
channels = size // 2
self.kernel_size = kernel_size
if causal:
self.lorder = kernel_size - 1
padding = 0
else:
self.lorder = 0
padding = (kernel_size - 1) // 2
self.conv = torch.nn.Conv1d(... | Convolutional Spatial Gating Unit module definition. Args: size: Initial size to determine the number of channels. kernel_size: Size of the convolving kernel. norm_class: Normalization module class. norm_args: Normalization module arguments. dropout_rate: Dropout rate. causal: Whether to use causal convolution (set to ... | ConvolutionalSpatialGatingUnit | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvolutionalSpatialGatingUnit:
"""Convolutional Spatial Gating Unit module definition. Args: size: Initial size to determine the number of channels. kernel_size: Size of the convolving kernel. norm_class: Normalization module class. norm_args: Normalization module arguments. dropout_rate: Dropou... | stack_v2_sparse_classes_36k_train_024597 | 7,416 | permissive | [
{
"docstring": "Construct a ConvolutionalSpatialGatingUnit object.",
"name": "__init__",
"signature": "def __init__(self, size: int, kernel_size: int, norm_class: torch.nn.Module=torch.nn.LayerNorm, norm_args: Dict={}, dropout_rate: float=0.0, causal: bool=False) -> None"
},
{
"docstring": "Comp... | 2 | null | Implement the Python class `ConvolutionalSpatialGatingUnit` described below.
Class description:
Convolutional Spatial Gating Unit module definition. Args: size: Initial size to determine the number of channels. kernel_size: Size of the convolving kernel. norm_class: Normalization module class. norm_args: Normalization... | Implement the Python class `ConvolutionalSpatialGatingUnit` described below.
Class description:
Convolutional Spatial Gating Unit module definition. Args: size: Initial size to determine the number of channels. kernel_size: Size of the convolving kernel. norm_class: Normalization module class. norm_args: Normalization... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class ConvolutionalSpatialGatingUnit:
"""Convolutional Spatial Gating Unit module definition. Args: size: Initial size to determine the number of channels. kernel_size: Size of the convolving kernel. norm_class: Normalization module class. norm_args: Normalization module arguments. dropout_rate: Dropou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvolutionalSpatialGatingUnit:
"""Convolutional Spatial Gating Unit module definition. Args: size: Initial size to determine the number of channels. kernel_size: Size of the convolving kernel. norm_class: Normalization module class. norm_args: Normalization module arguments. dropout_rate: Dropout rate. causa... | the_stack_v2_python_sparse | espnet2/asr_transducer/encoder/modules/convolution.py | espnet/espnet | train | 7,242 |
13044818fbf2a5feb9301e317bea1c768184945d | [
"if key == '$or' and key in self:\n raise KeyError('Невозможно установить ключ $or однозначно, т.к. ключ уже существует. При повторном назначении ключа возможно его переопределение. Для корректной установки второго $or воспользуйтесь методом and_or().')\nsuper(MongoMatchFilter, self).__setitem__(key, value)",
... | <|body_start_0|>
if key == '$or' and key in self:
raise KeyError('Невозможно установить ключ $or однозначно, т.к. ключ уже существует. При повторном назначении ключа возможно его переопределение. Для корректной установки второго $or воспользуйтесь методом and_or().')
super(MongoMatchFilter, ... | Класс, представляющий собой словарь raw-запроса к mongo. Реализует запрет повторной установки ключа $or: Поскольку для запроса используется словарь типа dict, возможно неожидаемое переопределение ключа $or. | MongoMatchFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MongoMatchFilter:
"""Класс, представляющий собой словарь raw-запроса к mongo. Реализует запрет повторной установки ключа $or: Поскольку для запроса используется словарь типа dict, возможно неожидаемое переопределение ключа $or."""
def __setitem__(self, key, value):
"""Устанваливает к... | stack_v2_sparse_classes_36k_train_024598 | 2,434 | no_license | [
{
"docstring": "Устанваливает ключи в словарь запроса mongo. Если устанавливается больше одного ключа $or, вызывается исключение. Для корректного использования нескольких $or-условий одновременно, используйте метод and_or(). :param key: ключ словаря :param value: значение словаря по ключу :return:",
"name":... | 2 | stack_v2_sparse_classes_30k_train_002580 | Implement the Python class `MongoMatchFilter` described below.
Class description:
Класс, представляющий собой словарь raw-запроса к mongo. Реализует запрет повторной установки ключа $or: Поскольку для запроса используется словарь типа dict, возможно неожидаемое переопределение ключа $or.
Method signatures and docstri... | Implement the Python class `MongoMatchFilter` described below.
Class description:
Класс, представляющий собой словарь raw-запроса к mongo. Реализует запрет повторной установки ключа $or: Поскольку для запроса используется словарь типа dict, возможно неожидаемое переопределение ключа $or.
Method signatures and docstri... | 47fa74182db770aa93e2e554b2c9477f324506ec | <|skeleton|>
class MongoMatchFilter:
"""Класс, представляющий собой словарь raw-запроса к mongo. Реализует запрет повторной установки ключа $or: Поскольку для запроса используется словарь типа dict, возможно неожидаемое переопределение ключа $or."""
def __setitem__(self, key, value):
"""Устанваливает к... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MongoMatchFilter:
"""Класс, представляющий собой словарь raw-запроса к mongo. Реализует запрет повторной установки ключа $or: Поскольку для запроса используется словарь типа dict, возможно неожидаемое переопределение ключа $or."""
def __setitem__(self, key, value):
"""Устанваливает ключи в словар... | the_stack_v2_python_sparse | snuff_utils/MongoMatchFilter.py | egorgvo/utils | train | 0 |
2e6cb3cb1dc77b921076bbe9fd13881d26cb0677 | [
"self.filename = filename\nself.fps = fps\nself.frame_fill = frame_fill\nself.fourcc = cv2.VideoWriter_fourcc('I', 'Y', 'U', 'V')",
"self.writer = cv2.VideoWriter(self.filename, self.fourcc, self.fps, size, 1)\nself.video_time = 0.0\nself.start_time = time.time()",
"if not self.writer:\n self.init_writer(img... | <|body_start_0|>
self.filename = filename
self.fps = fps
self.frame_fill = frame_fill
self.fourcc = cv2.VideoWriter_fourcc('I', 'Y', 'U', 'V')
<|end_body_0|>
<|body_start_1|>
self.writer = cv2.VideoWriter(self.filename, self.fourcc, self.fps, size, 1)
self.video_time = 0... | Allows user save video files in different formats. You can initialize it by specifying the file you want to output:: vs = VideoStream("hello.avi") You can also specify a framerate, and if you want to "fill" in missed frames. So if you want to record a real time video you may want to do this:: # note these are default v... | VideoStream | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoStream:
"""Allows user save video files in different formats. You can initialize it by specifying the file you want to output:: vs = VideoStream("hello.avi") You can also specify a framerate, and if you want to "fill" in missed frames. So if you want to record a real time video you may want ... | stack_v2_sparse_classes_36k_train_024599 | 9,045 | permissive | [
{
"docstring": "TODO: details :param filename: :param fps: :param frame_fill:",
"name": "__init__",
"signature": "def __init__(self, filename, fps=25, frame_fill=True)"
},
{
"docstring": "TODO: details :param size: :return:",
"name": "init_writer",
"signature": "def init_writer(self, siz... | 3 | stack_v2_sparse_classes_30k_train_015175 | Implement the Python class `VideoStream` described below.
Class description:
Allows user save video files in different formats. You can initialize it by specifying the file you want to output:: vs = VideoStream("hello.avi") You can also specify a framerate, and if you want to "fill" in missed frames. So if you want to... | Implement the Python class `VideoStream` described below.
Class description:
Allows user save video files in different formats. You can initialize it by specifying the file you want to output:: vs = VideoStream("hello.avi") You can also specify a framerate, and if you want to "fill" in missed frames. So if you want to... | f312569ec983b5f27c75846b34debc04fe7bdf98 | <|skeleton|>
class VideoStream:
"""Allows user save video files in different formats. You can initialize it by specifying the file you want to output:: vs = VideoStream("hello.avi") You can also specify a framerate, and if you want to "fill" in missed frames. So if you want to record a real time video you may want ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VideoStream:
"""Allows user save video files in different formats. You can initialize it by specifying the file you want to output:: vs = VideoStream("hello.avi") You can also specify a framerate, and if you want to "fill" in missed frames. So if you want to record a real time video you may want to do this:: ... | the_stack_v2_python_sparse | PhloxAR/core/stream.py | PhloxAR/PhloxAR | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.