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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
89fe99a859fee7360d765c69b88a731fb8c24996 | [
"self.screen_width = 1200\nself.screen_height = 800\nself.bg_color = (230, 230, 230)\nself.ship_speed_factor = 1.5\nself.ship_limit = 3\nself.bullet_speed_factor = 3\nself.bullet_width = 0.3\nself.bullet_height = 15\nself.bullet_color = (60, 60, 60)\nself.bullets_allowed = 3\nself.alien_speed_factor = 1\nself.fleet... | <|body_start_0|>
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_speed_factor = 1.5
self.ship_limit = 3
self.bullet_speed_factor = 3
self.bullet_width = 0.3
self.bullet_height = 15
self.bullet_color = (60... | Класс для хранения всех настроек игры Alien Invasion | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""Класс для хранения всех настроек игры Alien Invasion"""
def __init__(self):
"""Инициализирует статические настройки игры."""
<|body_0|>
def initialize_dynamic_settings(self):
"""Инициализирует настройки,изменяющиеся в ходе игры"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_020700 | 1,378 | no_license | [
{
"docstring": "Инициализирует статические настройки игры.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Инициализирует настройки,изменяющиеся в ходе игры",
"name": "initialize_dynamic_settings",
"signature": "def initialize_dynamic_settings(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_001117 | Implement the Python class `Settings` described below.
Class description:
Класс для хранения всех настроек игры Alien Invasion
Method signatures and docstrings:
- def __init__(self): Инициализирует статические настройки игры.
- def initialize_dynamic_settings(self): Инициализирует настройки,изменяющиеся в ходе игры
-... | Implement the Python class `Settings` described below.
Class description:
Класс для хранения всех настроек игры Alien Invasion
Method signatures and docstrings:
- def __init__(self): Инициализирует статические настройки игры.
- def initialize_dynamic_settings(self): Инициализирует настройки,изменяющиеся в ходе игры
-... | 8913ae55f4db5dcb4c53f5010ec0dfe2bc34f88b | <|skeleton|>
class Settings:
"""Класс для хранения всех настроек игры Alien Invasion"""
def __init__(self):
"""Инициализирует статические настройки игры."""
<|body_0|>
def initialize_dynamic_settings(self):
"""Инициализирует настройки,изменяющиеся в ходе игры"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Settings:
"""Класс для хранения всех настроек игры Alien Invasion"""
def __init__(self):
"""Инициализирует статические настройки игры."""
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_speed_factor = 1.5
self.shi... | the_stack_v2_python_sparse | alien_invasion/settings.py | kirilldotsenko/Web | train | 0 |
179059de3a08256bcbca884f8cb24c47066e7ea0 | [
"from GoogleDrive import drives_list_command\nwith open('test_data/drives_list_response.json', encoding='utf-8') as data:\n mock_response = json.load(data)\nmocker_http_request.return_value = mock_response\nargs = {'use_domain_admin_access': True}\nresult = drives_list_command(gsuite_client, args)\nassert 'Googl... | <|body_start_0|>
from GoogleDrive import drives_list_command
with open('test_data/drives_list_response.json', encoding='utf-8') as data:
mock_response = json.load(data)
mocker_http_request.return_value = mock_response
args = {'use_domain_admin_access': True}
result = ... | TestDriveMethods | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDriveMethods:
def test_drives_list_command_success(self, mocker_http_request, gsuite_client):
"""Scenario: For google-drive-drives-list command successful run. Given: - Command args. When: - Calling google-drive-drives-list command with the parameters provided. Then: - Ensure command... | stack_v2_sparse_classes_36k_train_020701 | 33,071 | permissive | [
{
"docstring": "Scenario: For google-drive-drives-list command successful run. Given: - Command args. When: - Calling google-drive-drives-list command with the parameters provided. Then: - Ensure command's raw_response, outputs should be as expected.",
"name": "test_drives_list_command_success",
"signat... | 4 | stack_v2_sparse_classes_30k_train_004684 | Implement the Python class `TestDriveMethods` described below.
Class description:
Implement the TestDriveMethods class.
Method signatures and docstrings:
- def test_drives_list_command_success(self, mocker_http_request, gsuite_client): Scenario: For google-drive-drives-list command successful run. Given: - Command ar... | Implement the Python class `TestDriveMethods` described below.
Class description:
Implement the TestDriveMethods class.
Method signatures and docstrings:
- def test_drives_list_command_success(self, mocker_http_request, gsuite_client): Scenario: For google-drive-drives-list command successful run. Given: - Command ar... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestDriveMethods:
def test_drives_list_command_success(self, mocker_http_request, gsuite_client):
"""Scenario: For google-drive-drives-list command successful run. Given: - Command args. When: - Calling google-drive-drives-list command with the parameters provided. Then: - Ensure command... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDriveMethods:
def test_drives_list_command_success(self, mocker_http_request, gsuite_client):
"""Scenario: For google-drive-drives-list command successful run. Given: - Command args. When: - Calling google-drive-drives-list command with the parameters provided. Then: - Ensure command's raw_respons... | the_stack_v2_python_sparse | Packs/GoogleDrive/Integrations/GoogleDrive/GoogleDrive_test.py | demisto/content | train | 1,023 | |
0d60b7b8526aa669ba65b13104a262556c82576a | [
"if not image_key:\n image_key = 'image/encoded'\nif not format_key:\n format_key = 'image/format'\nsuper(Image, self).__init__([image_key, format_key])\nself._image_key = image_key\nself._format_key = format_key\nself._shape = shape\nself._channels = channels\nself._dtype = dtype\nself._repeated = repeated",... | <|body_start_0|>
if not image_key:
image_key = 'image/encoded'
if not format_key:
format_key = 'image/format'
super(Image, self).__init__([image_key, format_key])
self._image_key = image_key
self._format_key = format_key
self._shape = shape
... | An ItemHandler that decodes a parsed Tensor as an image. | Image | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Image:
"""An ItemHandler that decodes a parsed Tensor as an image."""
def __init__(self, image_key=None, format_key=None, shape=None, channels=3, dtype=dtypes.uint8, repeated=False):
"""Initializes the image. Args: image_key: the name of the TF-Example feature in which the encoded im... | stack_v2_sparse_classes_36k_train_020702 | 15,383 | permissive | [
{
"docstring": "Initializes the image. Args: image_key: the name of the TF-Example feature in which the encoded image is stored. format_key: the name of the TF-Example feature in which the image format is stored. shape: the output shape of the image as 1-D `Tensor` [height, width, channels]. If provided, the im... | 3 | stack_v2_sparse_classes_30k_train_000469 | Implement the Python class `Image` described below.
Class description:
An ItemHandler that decodes a parsed Tensor as an image.
Method signatures and docstrings:
- def __init__(self, image_key=None, format_key=None, shape=None, channels=3, dtype=dtypes.uint8, repeated=False): Initializes the image. Args: image_key: t... | Implement the Python class `Image` described below.
Class description:
An ItemHandler that decodes a parsed Tensor as an image.
Method signatures and docstrings:
- def __init__(self, image_key=None, format_key=None, shape=None, channels=3, dtype=dtypes.uint8, repeated=False): Initializes the image. Args: image_key: t... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class Image:
"""An ItemHandler that decodes a parsed Tensor as an image."""
def __init__(self, image_key=None, format_key=None, shape=None, channels=3, dtype=dtypes.uint8, repeated=False):
"""Initializes the image. Args: image_key: the name of the TF-Example feature in which the encoded im... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Image:
"""An ItemHandler that decodes a parsed Tensor as an image."""
def __init__(self, image_key=None, format_key=None, shape=None, channels=3, dtype=dtypes.uint8, repeated=False):
"""Initializes the image. Args: image_key: the name of the TF-Example feature in which the encoded image is stored... | the_stack_v2_python_sparse | Tensorflow_OpenCV_Nightly/source/tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py | ryfeus/lambda-packs | train | 1,283 |
e3743d83791812cae07ec440cc63ecef9cdd72c6 | [
"if not head or k == 0:\n return head\np = q = head\nlength = 1\nwhile q.next:\n length += 1\n q = q.next\nq.next = p\nn = length - k % length\nwhile n - 1:\n p = p.next\n n -= 1\nhead = p.next\np.next = None\nreturn head",
"if not head or k == 0:\n return head\np = q = head\nn = 1\nt = k\nflag ... | <|body_start_0|>
if not head or k == 0:
return head
p = q = head
length = 1
while q.next:
length += 1
q = q.next
q.next = p
n = length - k % length
while n - 1:
p = p.next
n -= 1
head = p.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def rotateRight1(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n... | stack_v2_sparse_classes_36k_train_020703 | 1,660 | no_license | [
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "rotateRight",
"signature": "def rotateRight(self, head, k)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "rotateRight1",
"signature": "def rotateRight1(self, head, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def rotateRight1(self, head, k): :type head: ListNode :type k: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def rotateRight1(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
<|skelet... | f1d780b7e8b91b4df704651514018143c6931f9d | <|skeleton|>
class Solution:
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def rotateRight1(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
if not head or k == 0:
return head
p = q = head
length = 1
while q.next:
length += 1
q = q.next
q.next = p
n = length -... | the_stack_v2_python_sparse | ProgramForLeetCode/LeetCode/61-rotateRight.py | DQDH/Algorithm_Code | train | 0 | |
1b585b2aceb3f79ffa82ffe93720519d8c079ba2 | [
"Simulator.__init__(self, state_set, action_set, modules)\nassert 'auctions' in modules.keys()\nassert 'clicks' in modules.keys()\nassert 'rpc' in modules.keys()\nassert 'cpc' in modules.keys()",
"assert a in self.action_set\nN_A = self.modules['auctions'].sample()\nN_c = self.modules['clicks'].sample(n=N_A, bid=... | <|body_start_0|>
Simulator.__init__(self, state_set, action_set, modules)
assert 'auctions' in modules.keys()
assert 'clicks' in modules.keys()
assert 'rpc' in modules.keys()
assert 'cpc' in modules.keys()
<|end_body_0|>
<|body_start_1|>
assert a in self.action_set
... | Basic auction simulator with auctions, clicks, revenue per click and cost per click modules. :ivar list state_set: List of possible states. :ivar list action_set: List of valid actions. :ivar dict modules: Dictionary of modules used to model stochastic variables in the simulator. :ivar int s_ix: State index. :ivar dict... | SimulatorConstRPC | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulatorConstRPC:
"""Basic auction simulator with auctions, clicks, revenue per click and cost per click modules. :ivar list state_set: List of possible states. :ivar list action_set: List of valid actions. :ivar dict modules: Dictionary of modules used to model stochastic variables in the simul... | stack_v2_sparse_classes_36k_train_020704 | 40,659 | permissive | [
{
"docstring": ":param list state_set: List of possible states. :param list action_set: List of valid actions. :param dict modules: Dictionary of modules used to model stochastic variables in the simulator.",
"name": "__init__",
"signature": "def __init__(self, state_set, action_set, modules)"
},
{
... | 2 | null | Implement the Python class `SimulatorConstRPC` described below.
Class description:
Basic auction simulator with auctions, clicks, revenue per click and cost per click modules. :ivar list state_set: List of possible states. :ivar list action_set: List of valid actions. :ivar dict modules: Dictionary of modules used to ... | Implement the Python class `SimulatorConstRPC` described below.
Class description:
Basic auction simulator with auctions, clicks, revenue per click and cost per click modules. :ivar list state_set: List of possible states. :ivar list action_set: List of valid actions. :ivar dict modules: Dictionary of modules used to ... | ade886e9dcbde9fcea218a19f0130cc09f81e55e | <|skeleton|>
class SimulatorConstRPC:
"""Basic auction simulator with auctions, clicks, revenue per click and cost per click modules. :ivar list state_set: List of possible states. :ivar list action_set: List of valid actions. :ivar dict modules: Dictionary of modules used to model stochastic variables in the simul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimulatorConstRPC:
"""Basic auction simulator with auctions, clicks, revenue per click and cost per click modules. :ivar list state_set: List of possible states. :ivar list action_set: List of valid actions. :ivar dict modules: Dictionary of modules used to model stochastic variables in the simulator. :ivar i... | the_stack_v2_python_sparse | ssa_sim_v2/simulator/simulator.py | donghun2018/adclick-simulator-v2 | train | 0 |
112d1f530a36304b0cef209e0c516f7be15b7911 | [
"ra = self._NewRunAttributes()\nwith self.assertRaises(AssertionError):\n ra.HasBoardParallel(self.BATTR, self.BOARD, self.TARGET)\nra.RegisterBoardAttrs(self.BOARD, self.TARGET)\nself.assertFalse(ra.HasBoardParallel(self.BATTR, self.BOARD, self.TARGET))\nra.SetBoardParallel(self.BATTR, 'TheValue', self.BOARD, s... | <|body_start_0|>
ra = self._NewRunAttributes()
with self.assertRaises(AssertionError):
ra.HasBoardParallel(self.BATTR, self.BOARD, self.TARGET)
ra.RegisterBoardAttrs(self.BOARD, self.TARGET)
self.assertFalse(ra.HasBoardParallel(self.BATTR, self.BOARD, self.TARGET))
ra... | Test the RunAttributes class. | RunAttributesTest | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunAttributesTest:
"""Test the RunAttributes class."""
def testRegisterBoardTarget(self):
"""Test behavior of attributes before and after registering board target."""
<|body_0|>
def testSetGet(self):
"""Test simple set/get of regular and parallel run attributes."... | stack_v2_sparse_classes_36k_train_020705 | 24,848 | permissive | [
{
"docstring": "Test behavior of attributes before and after registering board target.",
"name": "testRegisterBoardTarget",
"signature": "def testRegisterBoardTarget(self)"
},
{
"docstring": "Test simple set/get of regular and parallel run attributes.",
"name": "testSetGet",
"signature":... | 4 | null | Implement the Python class `RunAttributesTest` described below.
Class description:
Test the RunAttributes class.
Method signatures and docstrings:
- def testRegisterBoardTarget(self): Test behavior of attributes before and after registering board target.
- def testSetGet(self): Test simple set/get of regular and para... | Implement the Python class `RunAttributesTest` described below.
Class description:
Test the RunAttributes class.
Method signatures and docstrings:
- def testRegisterBoardTarget(self): Test behavior of attributes before and after registering board target.
- def testSetGet(self): Test simple set/get of regular and para... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class RunAttributesTest:
"""Test the RunAttributes class."""
def testRegisterBoardTarget(self):
"""Test behavior of attributes before and after registering board target."""
<|body_0|>
def testSetGet(self):
"""Test simple set/get of regular and parallel run attributes."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunAttributesTest:
"""Test the RunAttributes class."""
def testRegisterBoardTarget(self):
"""Test behavior of attributes before and after registering board target."""
ra = self._NewRunAttributes()
with self.assertRaises(AssertionError):
ra.HasBoardParallel(self.BATTR, ... | the_stack_v2_python_sparse | third_party/chromite/cbuildbot/cbuildbot_run_unittest.py | metux/chromium-suckless | train | 5 |
c427da84ab06c5444ba7a11ffcf50fe6081643b2 | [
"if verbosity:\n (print >> self.stdout, 'Project settings:')\n (print >> self.stdout, 'Configuration definition file placed at %r\\n' % AVAILABLE_SETTINGS.path)\n for setting in AVAILABLE_SETTINGS:\n indent = ' ' * 4\n if is_settings_container(setting):\n (print >> self.stdout, '%s... | <|body_start_0|>
if verbosity:
(print >> self.stdout, 'Project settings:')
(print >> self.stdout, 'Configuration definition file placed at %r\n' % AVAILABLE_SETTINGS.path)
for setting in AVAILABLE_SETTINGS:
indent = ' ' * 4
if is_settings_conta... | Command | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
def check_setman(self, verbosity):
"""Check setman configuration."""
<|body_0|>
def handle_noargs(self, **options):
"""Do all necessary things."""
<|body_1|>
def store_default_values(self, verbosity):
"""Store default values to Settings ... | stack_v2_sparse_classes_36k_train_020706 | 2,852 | permissive | [
{
"docstring": "Check setman configuration.",
"name": "check_setman",
"signature": "def check_setman(self, verbosity)"
},
{
"docstring": "Do all necessary things.",
"name": "handle_noargs",
"signature": "def handle_noargs(self, **options)"
},
{
"docstring": "Store default values ... | 3 | stack_v2_sparse_classes_30k_train_020705 | Implement the Python class `Command` described below.
Class description:
Implement the Command class.
Method signatures and docstrings:
- def check_setman(self, verbosity): Check setman configuration.
- def handle_noargs(self, **options): Do all necessary things.
- def store_default_values(self, verbosity): Store def... | Implement the Python class `Command` described below.
Class description:
Implement the Command class.
Method signatures and docstrings:
- def check_setman(self, verbosity): Check setman configuration.
- def handle_noargs(self, **options): Do all necessary things.
- def store_default_values(self, verbosity): Store def... | 08fc786b0d7ad0216129c62e4907d6aa79643739 | <|skeleton|>
class Command:
def check_setman(self, verbosity):
"""Check setman configuration."""
<|body_0|>
def handle_noargs(self, **options):
"""Do all necessary things."""
<|body_1|>
def store_default_values(self, verbosity):
"""Store default values to Settings ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
def check_setman(self, verbosity):
"""Check setman configuration."""
if verbosity:
(print >> self.stdout, 'Project settings:')
(print >> self.stdout, 'Configuration definition file placed at %r\n' % AVAILABLE_SETTINGS.path)
for setting in AVAILABLE_... | the_stack_v2_python_sparse | setman/frameworks/django_setman/management/commands/setman_cmd.py | playpauseandstop/setman | train | 2 | |
e585d28fa113ea1a7a40b63a4fabc6107d5bdb4a | [
"super().__init__(list_of_modules_to_winnow, reshape, in_place, verbose)\nmodel.apply(has_hooks)\ndebug_level = logger.getEffectiveLevel()\nlogger.debug('Current log level: %s', debug_level)\nself._using_cuda = next(model.parameters()).is_cuda\nif self._in_place is False:\n self._model = copy.deepcopy(model)\n ... | <|body_start_0|>
super().__init__(list_of_modules_to_winnow, reshape, in_place, verbose)
model.apply(has_hooks)
debug_level = logger.getEffectiveLevel()
logger.debug('Current log level: %s', debug_level)
self._using_cuda = next(model.parameters()).is_cuda
if self._in_plac... | The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed. | MaskPropagationWinnower | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskPropagationWinnower:
"""The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed."""
def __init__(self, model: torch.nn.Module, input_shape: Tuple, list_of_modules_to_winnow: List[Tuple[torch... | stack_v2_sparse_classes_36k_train_020707 | 10,997 | permissive | [
{
"docstring": "MaskPropagationWinnower object initialization. :param model: The model to be winnowed. :param input_shape: The input shape of the model. :param list_of_modules_to_winnow: A list of Tuples with each Tuple containing a module and a list of channels to be winnowed for that module. :param reshape: I... | 5 | null | Implement the Python class `MaskPropagationWinnower` described below.
Class description:
The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed.
Method signatures and docstrings:
- def __init__(self, model: torch.nn.Mod... | Implement the Python class `MaskPropagationWinnower` described below.
Class description:
The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed.
Method signatures and docstrings:
- def __init__(self, model: torch.nn.Mod... | 5a406e657082b6a4f6e4bf48f0e46e085cb1e351 | <|skeleton|>
class MaskPropagationWinnower:
"""The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed."""
def __init__(self, model: torch.nn.Module, input_shape: Tuple, list_of_modules_to_winnow: List[Tuple[torch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaskPropagationWinnower:
"""The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed."""
def __init__(self, model: torch.nn.Module, input_shape: Tuple, list_of_modules_to_winnow: List[Tuple[torch.nn.Module, L... | the_stack_v2_python_sparse | TrainingExtensions/torch/src/python/aimet_torch/winnow/mask_propagation_winnower.py | quic/aimet | train | 1,676 |
2514ba3982c9fb20a5a2034be2f3e7b83ccd3bfa | [
"try:\n if None in read_basic_tiff_header(image_file):\n return False\nexcept Exception:\n return False\nreturn True",
"width, height, depth, header, order = read_basic_tiff_header(image_file)\nheader_bytes = FormatTIFF.open_file(image_file, 'rb').read(header)\nreturn (width, height, depth // 8, orde... | <|body_start_0|>
try:
if None in read_basic_tiff_header(image_file):
return False
except Exception:
return False
return True
<|end_body_0|>
<|body_start_1|>
width, height, depth, header, order = read_basic_tiff_header(image_file)
header_by... | An image reading class for TIFF format images i.e. those from Dectris and Rayonix, which start with a standard TIFF header (which is what is handled here) and have their own custom header following, which must be handled by the inheriting subclasses. | FormatTIFF | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormatTIFF:
"""An image reading class for TIFF format images i.e. those from Dectris and Rayonix, which start with a standard TIFF header (which is what is handled here) and have their own custom header following, which must be handled by the inheriting subclasses."""
def understand(image_fi... | stack_v2_sparse_classes_36k_train_020708 | 2,341 | permissive | [
{
"docstring": "Check to see if this looks like an TIFF format image, i.e. we can make sense of it.",
"name": "understand",
"signature": "def understand(image_file)"
},
{
"docstring": "Pun to get to the image header etc.",
"name": "get_tiff_header",
"signature": "def get_tiff_header(imag... | 4 | stack_v2_sparse_classes_30k_val_000018 | Implement the Python class `FormatTIFF` described below.
Class description:
An image reading class for TIFF format images i.e. those from Dectris and Rayonix, which start with a standard TIFF header (which is what is handled here) and have their own custom header following, which must be handled by the inheriting subc... | Implement the Python class `FormatTIFF` described below.
Class description:
An image reading class for TIFF format images i.e. those from Dectris and Rayonix, which start with a standard TIFF header (which is what is handled here) and have their own custom header following, which must be handled by the inheriting subc... | 2fc8ffadbf67d0611e2d7affcf50d0f23abfc16f | <|skeleton|>
class FormatTIFF:
"""An image reading class for TIFF format images i.e. those from Dectris and Rayonix, which start with a standard TIFF header (which is what is handled here) and have their own custom header following, which must be handled by the inheriting subclasses."""
def understand(image_fi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FormatTIFF:
"""An image reading class for TIFF format images i.e. those from Dectris and Rayonix, which start with a standard TIFF header (which is what is handled here) and have their own custom header following, which must be handled by the inheriting subclasses."""
def understand(image_file):
... | the_stack_v2_python_sparse | src/dxtbx/format/FormatTIFF.py | cctbx/dxtbx | train | 2 |
6fdff4d920703855abcf53c70e3cf97a7fef6857 | [
"int_limit = pow(2, 31)\nint_limit_rem = int_limit % 10\nint_limit //= 10\nsl = len(str)\ni = 0\nsign = 1\nn = 0\nwhile i < sl and str[i] == ' ':\n i += 1\nif i == sl:\n return 0\nif str[i] == '-':\n sign = -1\n i += 1\nelif str[i] == '+':\n i += 1\nwhile i < sl and str[i] >= '0' and (str[i] <= '9'):... | <|body_start_0|>
int_limit = pow(2, 31)
int_limit_rem = int_limit % 10
int_limit //= 10
sl = len(str)
i = 0
sign = 1
n = 0
while i < sl and str[i] == ' ':
i += 1
if i == sl:
return 0
if str[i] == '-':
sig... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myAtoi(self, str):
""":type str: str :rtype: int"""
<|body_0|>
def myAtoi(self, str):
""":type str: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
int_limit = pow(2, 31)
int_limit_rem = int_limit % 10
i... | stack_v2_sparse_classes_36k_train_020709 | 1,638 | no_license | [
{
"docstring": ":type str: str :rtype: int",
"name": "myAtoi",
"signature": "def myAtoi(self, str)"
},
{
"docstring": ":type str: str :rtype: int",
"name": "myAtoi",
"signature": "def myAtoi(self, str)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, str): :type str: str :rtype: int
- def myAtoi(self, str): :type str: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, str): :type str: str :rtype: int
- def myAtoi(self, str): :type str: str :rtype: int
<|skeleton|>
class Solution:
def myAtoi(self, str):
""":type s... | c27f19fac14b4acef8c631ad5569e1a5c29e9e1f | <|skeleton|>
class Solution:
def myAtoi(self, str):
""":type str: str :rtype: int"""
<|body_0|>
def myAtoi(self, str):
""":type str: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def myAtoi(self, str):
""":type str: str :rtype: int"""
int_limit = pow(2, 31)
int_limit_rem = int_limit % 10
int_limit //= 10
sl = len(str)
i = 0
sign = 1
n = 0
while i < sl and str[i] == ' ':
i += 1
if i ==... | the_stack_v2_python_sparse | leetcode/p0008 - String to Integer (atoi).py | liseyko/CtCI | train | 0 | |
c8f1f9494cb7d8da30568f4cc73f5946c9d9f3db | [
"self.cap = capacity\nself.key_pq = PQ()\nself.val_map = {}\nself.counter = itertools.count()",
"ts = next(self.counter)\nif not self.key_pq.contains(key):\n return -1\nself.key_pq.touch(key, ts)\nreturn self.val_map.get(key)",
"ts = next(self.counter)\nif self.cap == 0:\n return\nif self.key_pq.size() ==... | <|body_start_0|>
self.cap = capacity
self.key_pq = PQ()
self.val_map = {}
self.counter = itertools.count()
<|end_body_0|>
<|body_start_1|>
ts = next(self.counter)
if not self.key_pq.contains(key):
return -1
self.key_pq.touch(key, ts)
return se... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_020710 | 2,058 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_004758 | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 2722c0deafcd094ce64140a9a837b4027d29ed6f | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.cap = capacity
self.key_pq = PQ()
self.val_map = {}
self.counter = itertools.count()
def get(self, key):
""":type key: int :rtype: int"""
ts = next(self.counter)
if not s... | the_stack_v2_python_sparse | 460_LFU_cache_vh/pq.py | chao-shi/lclc | train | 0 | |
3e302c40d74c84c8ae76aa4974f0cf15bed072d7 | [
"super().__init__(**kwargs)\nself.lp_dynamic = lp_dynamic\nself.discriminator = discriminator\nif pd_maxdata is None:\n self.pd_maxdata = self.discriminator.pd_maxdata\nelse:\n self.pd_maxdata = pd_maxdata\nif ed_maxdata is None:\n self.ed_maxdata = self.discriminator.ed_maxdata\nelse:\n self.ed_maxdata... | <|body_start_0|>
super().__init__(**kwargs)
self.lp_dynamic = lp_dynamic
self.discriminator = discriminator
if pd_maxdata is None:
self.pd_maxdata = self.discriminator.pd_maxdata
else:
self.pd_maxdata = pd_maxdata
if ed_maxdata is None:
... | Calculates the gradient penalty for a given discriminator. This class takes a BaseDiscriminator instance and runs all necessary steps to calculate the gradient penalty for non-exponential (re-)scaled inputs. The penalty is only calculated on data inputs, not on labels! This class uses the tf.keras.Model interface. | GradientPenalty | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientPenalty:
"""Calculates the gradient penalty for a given discriminator. This class takes a BaseDiscriminator instance and runs all necessary steps to calculate the gradient penalty for non-exponential (re-)scaled inputs. The penalty is only calculated on data inputs, not on labels! This cl... | stack_v2_sparse_classes_36k_train_020711 | 6,122 | permissive | [
{
"docstring": "Construct the GradientPenalty for a given discriminator. Notice: The penalty is only calculated on data inputs, not on labels! Parameters ---------- discriminator : src.models.gan.BaseDiscriminator A BaseDiscriminator instance for which the gradient penatly should be calculated. pd_maxdata : lis... | 3 | null | Implement the Python class `GradientPenalty` described below.
Class description:
Calculates the gradient penalty for a given discriminator. This class takes a BaseDiscriminator instance and runs all necessary steps to calculate the gradient penalty for non-exponential (re-)scaled inputs. The penalty is only calculated... | Implement the Python class `GradientPenalty` described below.
Class description:
Calculates the gradient penalty for a given discriminator. This class takes a BaseDiscriminator instance and runs all necessary steps to calculate the gradient penalty for non-exponential (re-)scaled inputs. The penalty is only calculated... | 7f0086d2cdec23b49958c5afc0e6d12a08598465 | <|skeleton|>
class GradientPenalty:
"""Calculates the gradient penalty for a given discriminator. This class takes a BaseDiscriminator instance and runs all necessary steps to calculate the gradient penalty for non-exponential (re-)scaled inputs. The penalty is only calculated on data inputs, not on labels! This cl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradientPenalty:
"""Calculates the gradient penalty for a given discriminator. This class takes a BaseDiscriminator instance and runs all necessary steps to calculate the gradient penalty for non-exponential (re-)scaled inputs. The penalty is only calculated on data inputs, not on labels! This class uses the ... | the_stack_v2_python_sparse | src/models/gan/loss/gradient_penalty.py | image357/conex-generator | train | 0 |
f21ce1b1fe39a45da099b8010a4491799495e58f | [
"super().__init__()\nself.cost_class = cost_class\nself.cost_mask = cost_mask\nself.cost_dice = cost_dice\nassert cost_class != 0 or cost_mask != 0 or cost_dice != 0, 'all costs cant be 0'",
"bs, num_queries = outputs['pred_logits'].shape[:2]\nindices = []\nfor b in range(bs):\n out_prob = F.softmax(outputs['p... | <|body_start_0|>
super().__init__()
self.cost_class = cost_class
self.cost_mask = cost_mask
self.cost_dice = cost_dice
assert cost_class != 0 or cost_mask != 0 or cost_dice != 0, 'all costs cant be 0'
<|end_body_0|>
<|body_start_1|>
bs, num_queries = outputs['pred_logits... | This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, while the others are un-matched (... | HungarianMatcher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HungarianMatcher:
"""This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best pr... | stack_v2_sparse_classes_36k_train_020712 | 18,965 | permissive | [
{
"docstring": "Creates the matcher Params: cost_class: This is the relative weight of the classification error in the matching cost cost_mask: This is the relative weight of the focal loss of the binary mask in the matching cost cost_dice: This is the relative weight of the dice loss of the binary mask in the ... | 2 | null | Implement the Python class `HungarianMatcher` described below.
Class description:
This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case,... | Implement the Python class `HungarianMatcher` described below.
Class description:
This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case,... | 2c8c35a8949fef74599f5ec557d340a14415f20d | <|skeleton|>
class HungarianMatcher:
"""This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HungarianMatcher:
"""This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, wh... | the_stack_v2_python_sparse | paddleseg/models/losses/maskformer_loss.py | PaddlePaddle/PaddleSeg | train | 8,531 |
ee48606eaea3b7d522ad62fa25e218c9830d544f | [
"new_article = Article()\nnew_article.title = request.data['title']\nnew_article.synopsis = request.data['synopsis']\nnew_article.link = request.data['link']\nnew_article.reference = request.data['reference']\nnew_article.coder = Coder.objects.get(user=request.auth.user)\nnew_article.save()\nserializer = ArticleSer... | <|body_start_0|>
new_article = Article()
new_article.title = request.data['title']
new_article.synopsis = request.data['synopsis']
new_article.link = request.data['link']
new_article.reference = request.data['reference']
new_article.coder = Coder.objects.get(user=request.... | Articles for codeArchive | Articles | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Articles:
"""Articles for codeArchive"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized Article instance"""
<|body_0|>
def destroy(self, request, pk=None):
"""Handle DELETE requests for a single article Returns: Response... | stack_v2_sparse_classes_36k_train_020713 | 3,493 | no_license | [
{
"docstring": "Handle POST operations Returns: Response -- JSON serialized Article instance",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "Handle DELETE requests for a single article Returns: Response -- 200, 404, or 500 status code",
"name": "destroy",
... | 5 | stack_v2_sparse_classes_30k_train_010746 | Implement the Python class `Articles` described below.
Class description:
Articles for codeArchive
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized Article instance
- def destroy(self, request, pk=None): Handle DELETE requests for a single arti... | Implement the Python class `Articles` described below.
Class description:
Articles for codeArchive
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized Article instance
- def destroy(self, request, pk=None): Handle DELETE requests for a single arti... | 2bd984d13baaa9e12bba63a3bf39c2ff93619e59 | <|skeleton|>
class Articles:
"""Articles for codeArchive"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized Article instance"""
<|body_0|>
def destroy(self, request, pk=None):
"""Handle DELETE requests for a single article Returns: Response... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Articles:
"""Articles for codeArchive"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized Article instance"""
new_article = Article()
new_article.title = request.data['title']
new_article.synopsis = request.data['synopsis']
... | the_stack_v2_python_sparse | codearchiveAPIapp/views/article_view.py | shanemiller89/codeArchive_API | train | 0 |
67fd831f1197a211997631f61c2245784e5b6891 | [
"self.initial = initial\nif goal is not None:\n self.goal = goal\nelse:\n self.goal = sorted(self.initial[0], reverse=True)\nassert len(initial) == 3\nself.pegs = [i for i in range(0, len(initial))]\nself.sentinel = self.initial[0][0] + 1\nfor peg in self.initial:\n peg.insert(0, self.sentinel)\nself.goal.... | <|body_start_0|>
self.initial = initial
if goal is not None:
self.goal = goal
else:
self.goal = sorted(self.initial[0], reverse=True)
assert len(initial) == 3
self.pegs = [i for i in range(0, len(initial))]
self.sentinel = self.initial[0][0] + 1
... | This is where the problem is defined. Initial state, goal state and other information that can be got from the problem | Problem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Problem:
"""This is where the problem is defined. Initial state, goal state and other information that can be got from the problem"""
def __init__(self, initial, goal=None):
"""This is the constructor for the Problem class. It specifies the initial state, and possibly a goal state, i... | stack_v2_sparse_classes_36k_train_020714 | 21,082 | no_license | [
{
"docstring": "This is the constructor for the Problem class. It specifies the initial state, and possibly a goal state, if there is a unique goal. You can add other arguments if the need arises",
"name": "__init__",
"signature": "def __init__(self, initial, goal=None)"
},
{
"docstring": "Retur... | 4 | stack_v2_sparse_classes_30k_train_021500 | Implement the Python class `Problem` described below.
Class description:
This is where the problem is defined. Initial state, goal state and other information that can be got from the problem
Method signatures and docstrings:
- def __init__(self, initial, goal=None): This is the constructor for the Problem class. It ... | Implement the Python class `Problem` described below.
Class description:
This is where the problem is defined. Initial state, goal state and other information that can be got from the problem
Method signatures and docstrings:
- def __init__(self, initial, goal=None): This is the constructor for the Problem class. It ... | a283d50eff1d0e7c158479ddc8e17932d518104a | <|skeleton|>
class Problem:
"""This is where the problem is defined. Initial state, goal state and other information that can be got from the problem"""
def __init__(self, initial, goal=None):
"""This is the constructor for the Problem class. It specifies the initial state, and possibly a goal state, i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Problem:
"""This is where the problem is defined. Initial state, goal state and other information that can be got from the problem"""
def __init__(self, initial, goal=None):
"""This is the constructor for the Problem class. It specifies the initial state, and possibly a goal state, if there is a ... | the_stack_v2_python_sparse | 4511W-Intro_To_Artificial_Intelligence/Course_Project_Towers_of_Hanoi/hanoi.py | marvintv/apollo-academia-umn | train | 0 |
cddb41a9ce7c3c418e15b9d610dd649c1cd961e7 | [
"fr = FamilyRelationship.query.get(kf_id)\nif fr is None:\n abort(404, 'could not find {} `{}`'.format('family_relationship', kf_id))\nreturn FamilyRelationshipSchema().jsonify(fr)",
"fr = FamilyRelationship.query.get(kf_id)\nif fr is None:\n abort(404, 'could not find {} `{}`'.format('family_relationship',... | <|body_start_0|>
fr = FamilyRelationship.query.get(kf_id)
if fr is None:
abort(404, 'could not find {} `{}`'.format('family_relationship', kf_id))
return FamilyRelationshipSchema().jsonify(fr)
<|end_body_0|>
<|body_start_1|>
fr = FamilyRelationship.query.get(kf_id)
i... | FamilyRelationship REST API | FamilyRelationshipAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FamilyRelationshipAPI:
"""FamilyRelationship REST API"""
def get(self, kf_id):
"""Get a family_relationship by id --- template: path: get_by_id.yml properties: resource: FamilyRelationship"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing family_relatio... | stack_v2_sparse_classes_36k_train_020715 | 5,385 | permissive | [
{
"docstring": "Get a family_relationship by id --- template: path: get_by_id.yml properties: resource: FamilyRelationship",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing family_relationship. Allows partial update of resource --- template: path: update_... | 3 | null | Implement the Python class `FamilyRelationshipAPI` described below.
Class description:
FamilyRelationship REST API
Method signatures and docstrings:
- def get(self, kf_id): Get a family_relationship by id --- template: path: get_by_id.yml properties: resource: FamilyRelationship
- def patch(self, kf_id): Update an ex... | Implement the Python class `FamilyRelationshipAPI` described below.
Class description:
FamilyRelationship REST API
Method signatures and docstrings:
- def get(self, kf_id): Get a family_relationship by id --- template: path: get_by_id.yml properties: resource: FamilyRelationship
- def patch(self, kf_id): Update an ex... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class FamilyRelationshipAPI:
"""FamilyRelationship REST API"""
def get(self, kf_id):
"""Get a family_relationship by id --- template: path: get_by_id.yml properties: resource: FamilyRelationship"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing family_relatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FamilyRelationshipAPI:
"""FamilyRelationship REST API"""
def get(self, kf_id):
"""Get a family_relationship by id --- template: path: get_by_id.yml properties: resource: FamilyRelationship"""
fr = FamilyRelationship.query.get(kf_id)
if fr is None:
abort(404, 'could not... | the_stack_v2_python_sparse | dataservice/api/family_relationship/resources.py | kids-first/kf-api-dataservice | train | 9 |
c915c9e18424e0e560deec2401cc3dda57f65b85 | [
"super(TDProxy, self).__init__(mf, proxy, x, mf_constructor, frozen=frozen, **kwargs)\nself.e = {}\nself.xy = {}",
"if k is None:\n k = numpy.arange(len(self._scf.kpts))\nif isinstance(k, int):\n k = [k]\nfor kk in k:\n self.e[kk], self.xy[kk] = self.__kernel__(k=kk)\nreturn (self.e, self.xy)"
] | <|body_start_0|>
super(TDProxy, self).__init__(mf, proxy, x, mf_constructor, frozen=frozen, **kwargs)
self.e = {}
self.xy = {}
<|end_body_0|>
<|body_start_1|>
if k is None:
k = numpy.arange(len(self._scf.kpts))
if isinstance(k, int):
k = [k]
for k... | TDProxy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TDProxy:
def __init__(self, mf, proxy, x, mf_constructor, frozen=None, **kwargs):
"""Performs TD calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf: the base model with a time-reversal invariant k-point grid; proxy: a pyscf proxy with TD response function, on... | stack_v2_sparse_classes_36k_train_020716 | 7,401 | permissive | [
{
"docstring": "Performs TD calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf: the base model with a time-reversal invariant k-point grid; proxy: a pyscf proxy with TD response function, one of 'hf', 'dft'; x (Iterable): the original k-grid dimensions (numbers of k-points per each ... | 2 | null | Implement the Python class `TDProxy` described below.
Class description:
Implement the TDProxy class.
Method signatures and docstrings:
- def __init__(self, mf, proxy, x, mf_constructor, frozen=None, **kwargs): Performs TD calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf: the base model... | Implement the Python class `TDProxy` described below.
Class description:
Implement the TDProxy class.
Method signatures and docstrings:
- def __init__(self, mf, proxy, x, mf_constructor, frozen=None, **kwargs): Performs TD calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf: the base model... | dd179a802f0a35e72d8522503172f16977c8d974 | <|skeleton|>
class TDProxy:
def __init__(self, mf, proxy, x, mf_constructor, frozen=None, **kwargs):
"""Performs TD calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf: the base model with a time-reversal invariant k-point grid; proxy: a pyscf proxy with TD response function, on... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TDProxy:
def __init__(self, mf, proxy, x, mf_constructor, frozen=None, **kwargs):
"""Performs TD calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf: the base model with a time-reversal invariant k-point grid; proxy: a pyscf proxy with TD response function, one of 'hf', 'df... | the_stack_v2_python_sparse | pyscf/pbc/tdscf/kproxy.py | sunqm/pyscf | train | 80 | |
e7262655819394e3f313bdf5f6601c2d8632a94f | [
"super().__init__()\nif filename is not None:\n self.readFile(filename)",
"types = {'flashPortionHistoryID': np.int64, 'flashPortionID': str, 'flashID': str, 'nullTime': str, 'time': str, 'lat': np.float, 'lon': np.float, 'alt': np.float, 'type': str, 'amp': np.float}\npdArgs = {'skiprows': 1, 'chunksize': 100... | <|body_start_0|>
super().__init__()
if filename is not None:
self.readFile(filename)
<|end_body_0|>
<|body_start_1|>
types = {'flashPortionHistoryID': np.int64, 'flashPortionID': str, 'flashID': str, 'nullTime': str, 'time': str, 'lat': np.float, 'lon': np.float, 'alt': np.float, 't... | Class to handle Earth Networks Total Lightning Network data. Many of the following are not attributes of the class, but are columns in the underlying Dataframe. But, you can access them as you would an attribute.... Attributes ----------- _data : Dataframe The underlying data. A "real" attribute of the class. flashID :... | ENTLN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ENTLN:
"""Class to handle Earth Networks Total Lightning Network data. Many of the following are not attributes of the class, but are columns in the underlying Dataframe. But, you can access them as you would an attribute.... Attributes ----------- _data : Dataframe The underlying data. A "real" ... | stack_v2_sparse_classes_36k_train_020717 | 7,079 | no_license | [
{
"docstring": "If you don't provide a file name, you'll have to call :meth:`readFile` yourself to actually do anything useful. Parameters ---------- filename : str The file name to be read in.",
"name": "__init__",
"signature": "def __init__(self, filename=None)"
},
{
"docstring": "Given a file... | 2 | stack_v2_sparse_classes_30k_train_016937 | Implement the Python class `ENTLN` described below.
Class description:
Class to handle Earth Networks Total Lightning Network data. Many of the following are not attributes of the class, but are columns in the underlying Dataframe. But, you can access them as you would an attribute.... Attributes ----------- _data : D... | Implement the Python class `ENTLN` described below.
Class description:
Class to handle Earth Networks Total Lightning Network data. Many of the following are not attributes of the class, but are columns in the underlying Dataframe. But, you can access them as you would an attribute.... Attributes ----------- _data : D... | 67f98b5d96ad26407efe98d4303a7d0b084bf06b | <|skeleton|>
class ENTLN:
"""Class to handle Earth Networks Total Lightning Network data. Many of the following are not attributes of the class, but are columns in the underlying Dataframe. But, you can access them as you would an attribute.... Attributes ----------- _data : Dataframe The underlying data. A "real" ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ENTLN:
"""Class to handle Earth Networks Total Lightning Network data. Many of the following are not attributes of the class, but are columns in the underlying Dataframe. But, you can access them as you would an attribute.... Attributes ----------- _data : Dataframe The underlying data. A "real" attribute of ... | the_stack_v2_python_sparse | pyltg/core/entln.py | safelysparky/pyltg | train | 0 |
081699249fde3244c0fdfff328bba4b73cd4a53f | [
"if n == 1:\n return True\ndic = {}\nkey = n\nwhile True:\n key = list(map(int, str(key)))\n tmp = [i ** 2 for i in key]\n key = sum(tmp)\n if key == 1:\n return True\n elif key not in dic:\n dic[key] = 1\n else:\n return False",
"dic = {}\nwhile n:\n if n == 1:\n ... | <|body_start_0|>
if n == 1:
return True
dic = {}
key = n
while True:
key = list(map(int, str(key)))
tmp = [i ** 2 for i in key]
key = sum(tmp)
if key == 1:
return True
elif key not in dic:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isHappy(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isHappy_1(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
def isHappy_2(self, n):
""":type n: int :rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_020718 | 2,193 | no_license | [
{
"docstring": ":type n: int :rtype: bool",
"name": "isHappy",
"signature": "def isHappy(self, n)"
},
{
"docstring": ":type n: int :rtype: bool",
"name": "isHappy_1",
"signature": "def isHappy_1(self, n)"
},
{
"docstring": ":type n: int :rtype: bool",
"name": "isHappy_2",
... | 3 | stack_v2_sparse_classes_30k_train_017036 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isHappy(self, n): :type n: int :rtype: bool
- def isHappy_1(self, n): :type n: int :rtype: bool
- def isHappy_2(self, n): :type n: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isHappy(self, n): :type n: int :rtype: bool
- def isHappy_1(self, n): :type n: int :rtype: bool
- def isHappy_2(self, n): :type n: int :rtype: bool
<|skeleton|>
class Soluti... | 3d9e0ad2f6ed92ec969556f75d97c51ea4854719 | <|skeleton|>
class Solution:
def isHappy(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isHappy_1(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
def isHappy_2(self, n):
""":type n: int :rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isHappy(self, n):
""":type n: int :rtype: bool"""
if n == 1:
return True
dic = {}
key = n
while True:
key = list(map(int, str(key)))
tmp = [i ** 2 for i in key]
key = sum(tmp)
if key == 1:
... | the_stack_v2_python_sparse | Solutions/0202_isHappy.py | YoupengLi/leetcode-sorting | train | 3 | |
6f0c8f967ae0e47aef583cf226137afced79c3f7 | [
"if app is not None:\n self._api_key = app.config.get('SENDCLOUD_API_KEY', '')\n self._api_user = app.config.get('SENDCLOUD_API_USER', '')",
"api_url = 'http://api.sendcloud.net/apiv2/userinfo/get'\nparams = {'apiUser': self._api_user, 'apiKey': self._api_key}\nreturn requests.get(api_url, params=params).js... | <|body_start_0|>
if app is not None:
self._api_key = app.config.get('SENDCLOUD_API_KEY', '')
self._api_user = app.config.get('SENDCLOUD_API_USER', '')
<|end_body_0|>
<|body_start_1|>
api_url = 'http://api.sendcloud.net/apiv2/userinfo/get'
params = {'apiUser': self._api_u... | SendCloud 邮件发送平台 以下方法采用 API v2 (区别:请求地址,参数命名规则) link: http://sendcloud.sohu.com/doc/email_v2/ 仅列出常用接口,实际使用中定制 | SendCloudClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendCloudClient:
"""SendCloud 邮件发送平台 以下方法采用 API v2 (区别:请求地址,参数命名规则) link: http://sendcloud.sohu.com/doc/email_v2/ 仅列出常用接口,实际使用中定制"""
def __init__(self, app=None):
"""初始化应用"""
<|body_0|>
def userinfo_get(self):
"""用户信息 查询"""
<|body_1|>
def mail_send(s... | stack_v2_sparse_classes_36k_train_020719 | 3,339 | permissive | [
{
"docstring": "初始化应用",
"name": "__init__",
"signature": "def __init__(self, app=None)"
},
{
"docstring": "用户信息 查询",
"name": "userinfo_get",
"signature": "def userinfo_get(self)"
},
{
"docstring": "普通发送",
"name": "mail_send",
"signature": "def mail_send(self, mail_from, m... | 6 | null | Implement the Python class `SendCloudClient` described below.
Class description:
SendCloud 邮件发送平台 以下方法采用 API v2 (区别:请求地址,参数命名规则) link: http://sendcloud.sohu.com/doc/email_v2/ 仅列出常用接口,实际使用中定制
Method signatures and docstrings:
- def __init__(self, app=None): 初始化应用
- def userinfo_get(self): 用户信息 查询
- def mail_send(self,... | Implement the Python class `SendCloudClient` described below.
Class description:
SendCloud 邮件发送平台 以下方法采用 API v2 (区别:请求地址,参数命名规则) link: http://sendcloud.sohu.com/doc/email_v2/ 仅列出常用接口,实际使用中定制
Method signatures and docstrings:
- def __init__(self, app=None): 初始化应用
- def userinfo_get(self): 用户信息 查询
- def mail_send(self,... | 25729aa7a8a5b38906e60b370609b15e8911ecdd | <|skeleton|>
class SendCloudClient:
"""SendCloud 邮件发送平台 以下方法采用 API v2 (区别:请求地址,参数命名规则) link: http://sendcloud.sohu.com/doc/email_v2/ 仅列出常用接口,实际使用中定制"""
def __init__(self, app=None):
"""初始化应用"""
<|body_0|>
def userinfo_get(self):
"""用户信息 查询"""
<|body_1|>
def mail_send(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SendCloudClient:
"""SendCloud 邮件发送平台 以下方法采用 API v2 (区别:请求地址,参数命名规则) link: http://sendcloud.sohu.com/doc/email_v2/ 仅列出常用接口,实际使用中定制"""
def __init__(self, app=None):
"""初始化应用"""
if app is not None:
self._api_key = app.config.get('SENDCLOUD_API_KEY', '')
self._api_user... | the_stack_v2_python_sparse | app_common/libs/sendcloud.py | zhanghe06/bearing_project | train | 2 |
eaa39548038ed6ad63e5bc200e14a7a772488aea | [
"self.feed = Feed.objects.create(xml_url='http://localhost:%s/test/feed' % PORT)\nself.group = Group.objects.create(name='Test Group')\nself.feed.group = self.group\nself.feed.save()\nself.user = get_user_model().objects.create_user('john', 'john@montypython.com', 'password')\nself.user.is_staff = True\nself.user.s... | <|body_start_0|>
self.feed = Feed.objects.create(xml_url='http://localhost:%s/test/feed' % PORT)
self.group = Group.objects.create(name='Test Group')
self.feed.group = self.group
self.feed.save()
self.user = get_user_model().objects.create_user('john', 'john@montypython.com', 'pa... | Test UpdateItem view | UpdateItemTest | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateItemTest:
"""Test UpdateItem view"""
def setUp(self):
"""Create data and login"""
<|body_0|>
def test_delete_item(self):
"""Delete item"""
<|body_1|>
def test_update_text(self):
"""Update text field"""
<|body_2|>
def test_u... | stack_v2_sparse_classes_36k_train_020720 | 8,323 | permissive | [
{
"docstring": "Create data and login",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Delete item",
"name": "test_delete_item",
"signature": "def test_delete_item(self)"
},
{
"docstring": "Update text field",
"name": "test_update_text",
"signature": "... | 5 | stack_v2_sparse_classes_30k_train_015143 | Implement the Python class `UpdateItemTest` described below.
Class description:
Test UpdateItem view
Method signatures and docstrings:
- def setUp(self): Create data and login
- def test_delete_item(self): Delete item
- def test_update_text(self): Update text field
- def test_update_boolean(self): Update boolean fiel... | Implement the Python class `UpdateItemTest` described below.
Class description:
Test UpdateItem view
Method signatures and docstrings:
- def setUp(self): Create data and login
- def test_delete_item(self): Delete item
- def test_update_text(self): Update text field
- def test_update_boolean(self): Update boolean fiel... | f713bebcb7dcf5edb8d9b02d7d5055796bb39a82 | <|skeleton|>
class UpdateItemTest:
"""Test UpdateItem view"""
def setUp(self):
"""Create data and login"""
<|body_0|>
def test_delete_item(self):
"""Delete item"""
<|body_1|>
def test_update_text(self):
"""Update text field"""
<|body_2|>
def test_u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateItemTest:
"""Test UpdateItem view"""
def setUp(self):
"""Create data and login"""
self.feed = Feed.objects.create(xml_url='http://localhost:%s/test/feed' % PORT)
self.group = Group.objects.create(name='Test Group')
self.feed.group = self.group
self.feed.save(... | the_stack_v2_python_sparse | feedreader/test_views.py | ahernp/django-feedreader | train | 80 |
1e6f8e6fcb1ebc92cfb21fa658aafd2eedd5c2c6 | [
"Questionnaire.__init__(self, df)\nself.names = ['CAS', 'OCS']\nself.labels = ['The coronavirus anxiety scale', 'Obsession with COVID scale']\nself.values = {'CAS': {}, 'OCS': {}}\nself.new_df = pd.DataFrame(0, index=self.df.index, columns=self.names)",
"corona_df = pd.DataFrame(index=self.df.index, columns=self.... | <|body_start_0|>
Questionnaire.__init__(self, df)
self.names = ['CAS', 'OCS']
self.labels = ['The coronavirus anxiety scale', 'Obsession with COVID scale']
self.values = {'CAS': {}, 'OCS': {}}
self.new_df = pd.DataFrame(0, index=self.df.index, columns=self.names)
<|end_body_0|>
... | A class used to represent the Corona Enxiety Questionnaire Attributes ---------- df : DataFrame A Pandas data frame with the specific columns for the questionnaire Methods ------- grade() Calculates the grading of the questionnaire | CoronaEnxiety | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoronaEnxiety:
"""A class used to represent the Corona Enxiety Questionnaire Attributes ---------- df : DataFrame A Pandas data frame with the specific columns for the questionnaire Methods ------- grade() Calculates the grading of the questionnaire"""
def __init__(self, df):
"""Init... | stack_v2_sparse_classes_36k_train_020721 | 1,813 | no_license | [
{
"docstring": "Init the following arguments: names = the new columns' names (after grading) labels = labels for each column to be written in the SPSS output file values = explanation for the values in each SPSS column - empty for this questionaire new_df = new DataFrame with the graded values Parameters ------... | 2 | stack_v2_sparse_classes_30k_train_021161 | Implement the Python class `CoronaEnxiety` described below.
Class description:
A class used to represent the Corona Enxiety Questionnaire Attributes ---------- df : DataFrame A Pandas data frame with the specific columns for the questionnaire Methods ------- grade() Calculates the grading of the questionnaire
Method ... | Implement the Python class `CoronaEnxiety` described below.
Class description:
A class used to represent the Corona Enxiety Questionnaire Attributes ---------- df : DataFrame A Pandas data frame with the specific columns for the questionnaire Methods ------- grade() Calculates the grading of the questionnaire
Method ... | 26b8a2847d7202b61e67e2cd0074278a46a9f8f3 | <|skeleton|>
class CoronaEnxiety:
"""A class used to represent the Corona Enxiety Questionnaire Attributes ---------- df : DataFrame A Pandas data frame with the specific columns for the questionnaire Methods ------- grade() Calculates the grading of the questionnaire"""
def __init__(self, df):
"""Init... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CoronaEnxiety:
"""A class used to represent the Corona Enxiety Questionnaire Attributes ---------- df : DataFrame A Pandas data frame with the specific columns for the questionnaire Methods ------- grade() Calculates the grading of the questionnaire"""
def __init__(self, df):
"""Init the followin... | the_stack_v2_python_sparse | Questionnaires/CoronaEnxiety.py | TechnionENIC/ENIC_scoring_program | train | 0 |
85a384044dc73fa4202517f680d806dd78db5f80 | [
"cmd = 'python3 poll_http_endpoint.py --endpoint={endpoint} --max_retries={retries} --retry_interval={retry_interval} --timeout={timeout}'.format(endpoint=endpoint, retries=retries, retry_interval=retry_interval, timeout=timeout)\nif expected_response:\n cmd += ' --expected_response=%s' % expected_response\nif e... | <|body_start_0|>
cmd = 'python3 poll_http_endpoint.py --endpoint={endpoint} --max_retries={retries} --retry_interval={retry_interval} --timeout={timeout}'.format(endpoint=endpoint, retries=retries, retry_interval=retry_interval, timeout=timeout)
if expected_response:
cmd += ' --expected_resp... | Polls http endpoint. | HttpPoller | [
"Classpath-exception-2.0",
"BSD-3-Clause",
"AGPL-3.0-only",
"MIT",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpPoller:
"""Polls http endpoint."""
def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response):
"""Builds command for polling script."""
<|body_0|>
def Run(self, vm, endpoint, headers=(), retries=0, retry_in... | stack_v2_sparse_classes_36k_train_020722 | 3,784 | permissive | [
{
"docstring": "Builds command for polling script.",
"name": "_BuildCommand",
"signature": "def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response)"
},
{
"docstring": "Polls HTTP endpoint. Args: vm: VirtualMachine object. endpoint: ... | 2 | stack_v2_sparse_classes_30k_train_009866 | Implement the Python class `HttpPoller` described below.
Class description:
Polls http endpoint.
Method signatures and docstrings:
- def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response): Builds command for polling script.
- def Run(self, vm, endpoint,... | Implement the Python class `HttpPoller` described below.
Class description:
Polls http endpoint.
Method signatures and docstrings:
- def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response): Builds command for polling script.
- def Run(self, vm, endpoint,... | d0699f32998898757b036704fba39e5471641f01 | <|skeleton|>
class HttpPoller:
"""Polls http endpoint."""
def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response):
"""Builds command for polling script."""
<|body_0|>
def Run(self, vm, endpoint, headers=(), retries=0, retry_in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpPoller:
"""Polls http endpoint."""
def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response):
"""Builds command for polling script."""
cmd = 'python3 poll_http_endpoint.py --endpoint={endpoint} --max_retries={retries} --ret... | the_stack_v2_python_sparse | perfkitbenchmarker/linux_packages/http_poller.py | GoogleCloudPlatform/PerfKitBenchmarker | train | 1,923 |
e55444e692aa513bb160f8ef4edc66ac950c9a42 | [
"self.dimensionality = len(search_space)\nself.search_space = search_space\nself.numOfGeneratedPoints = 0\nself.returned_points = []\nself.hypercube_coordinates = []\nfor dimension in search_space:\n dim_indexes = [float(x) for x in range(len(dimension))]\n self.hypercube_coordinates.append(dim_indexes)\nself... | <|body_start_0|>
self.dimensionality = len(search_space)
self.search_space = search_space
self.numOfGeneratedPoints = 0
self.returned_points = []
self.hypercube_coordinates = []
for dimension in search_space:
dim_indexes = [float(x) for x in range(len(dimensio... | SobolSequence | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SobolSequence:
def __init__(self, selection_algorithm_config, search_space):
"""Creates SobolSequence instance that stores information about number of generated points :param selection_algorithm_config: Dict with configuration of selection algorithm. :param search_space: list of dimensio... | stack_v2_sparse_classes_36k_train_020723 | 4,166 | permissive | [
{
"docstring": "Creates SobolSequence instance that stores information about number of generated points :param selection_algorithm_config: Dict with configuration of selection algorithm. :param search_space: list of dimensions that describes a",
"name": "__init__",
"signature": "def __init__(self, selec... | 3 | stack_v2_sparse_classes_30k_train_006049 | Implement the Python class `SobolSequence` described below.
Class description:
Implement the SobolSequence class.
Method signatures and docstrings:
- def __init__(self, selection_algorithm_config, search_space): Creates SobolSequence instance that stores information about number of generated points :param selection_a... | Implement the Python class `SobolSequence` described below.
Class description:
Implement the SobolSequence class.
Method signatures and docstrings:
- def __init__(self, selection_algorithm_config, search_space): Creates SobolSequence instance that stores information about number of generated points :param selection_a... | 2b99e0a069ce866cb1d436a8ab18cc8dea206b15 | <|skeleton|>
class SobolSequence:
def __init__(self, selection_algorithm_config, search_space):
"""Creates SobolSequence instance that stores information about number of generated points :param selection_algorithm_config: Dict with configuration of selection algorithm. :param search_space: list of dimensio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SobolSequence:
def __init__(self, selection_algorithm_config, search_space):
"""Creates SobolSequence instance that stores information about number of generated points :param selection_algorithm_config: Dict with configuration of selection algorithm. :param search_space: list of dimensions that descri... | the_stack_v2_python_sparse | main-node/selection/sobol.py | Valavanca/benchmark | train | 0 | |
5962836e5ddea635a6f5b954b5822a854517b4a7 | [
"if self.params:\n for k in configkeys:\n if k not in self.params or self.params[k] is None:\n self.params[k] = config.__getattribute__(k)\nelse:\n self.params = {k: config.__getattribute__(k) for k in configkeys}",
"release = self.params['release'] if self.params and 'release' in self.par... | <|body_start_0|>
if self.params:
for k in configkeys:
if k not in self.params or self.params[k] is None:
self.params[k] = config.__getattribute__(k)
else:
self.params = {k: config.__getattribute__(k) for k in configkeys}
<|end_body_0|>
<|body_... | Marvins Interaction class, subclassed from Brain This is the main class to make calls to the Marvin API. Instantaiate the Interaction object with a URL to make the call. GET requests can be made without passing parameters. POST requests require parameters to be passed. A successful call results in a HTTP status code of... | Interaction | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interaction:
"""Marvins Interaction class, subclassed from Brain This is the main class to make calls to the Marvin API. Instantaiate the Interaction object with a URL to make the call. GET requests can be made without passing parameters. POST requests require parameters to be passed. A successfu... | stack_v2_sparse_classes_36k_train_020724 | 4,734 | permissive | [
{
"docstring": "Load the local configuration into a parameters dictionary to be sent with the request",
"name": "_loadConfigParams",
"signature": "def _loadConfigParams(self)"
},
{
"docstring": "Set the authorization",
"name": "setAuth",
"signature": "def setAuth(self, authtype=None)"
... | 2 | null | Implement the Python class `Interaction` described below.
Class description:
Marvins Interaction class, subclassed from Brain This is the main class to make calls to the Marvin API. Instantaiate the Interaction object with a URL to make the call. GET requests can be made without passing parameters. POST requests requi... | Implement the Python class `Interaction` described below.
Class description:
Marvins Interaction class, subclassed from Brain This is the main class to make calls to the Marvin API. Instantaiate the Interaction object with a URL to make the call. GET requests can be made without passing parameters. POST requests requi... | db4c536a65fb2f16fee05a4f34996a7fd35f0527 | <|skeleton|>
class Interaction:
"""Marvins Interaction class, subclassed from Brain This is the main class to make calls to the Marvin API. Instantaiate the Interaction object with a URL to make the call. GET requests can be made without passing parameters. POST requests require parameters to be passed. A successfu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Interaction:
"""Marvins Interaction class, subclassed from Brain This is the main class to make calls to the Marvin API. Instantaiate the Interaction object with a URL to make the call. GET requests can be made without passing parameters. POST requests require parameters to be passed. A successful call result... | the_stack_v2_python_sparse | python/marvin/api/api.py | sdss/marvin | train | 56 |
3e4e4a6e4292c2b9b9273c02670d58e775c63732 | [
"argument_group.add_argument('--profilers', dest='profilers', type=str, action='store', default='', metavar='PROFILERS_LIST', help='List of profilers to use by the tool. This is a comma separated list where each entry is the name of a profiler. Use \"--profilers list\" to list the available profilers.')\nargument_g... | <|body_start_0|>
argument_group.add_argument('--profilers', dest='profilers', type=str, action='store', default='', metavar='PROFILERS_LIST', help='List of profilers to use by the tool. This is a comma separated list where each entry is the name of a profiler. Use "--profilers list" to list the available profil... | Profiling CLI arguments helper. | ProfilingArgumentsHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfilingArgumentsHelper:
"""Profiling CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper sup... | stack_v2_sparse_classes_36k_train_020725 | 4,561 | permissive | [
{
"docstring": "Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group.",
"name": "AddArgum... | 2 | stack_v2_sparse_classes_30k_train_007412 | Implement the Python class `ProfilingArgumentsHelper` described below.
Class description:
Profiling CLI arguments helper.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and ... | Implement the Python class `ProfilingArgumentsHelper` described below.
Class description:
Profiling CLI arguments helper.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and ... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class ProfilingArgumentsHelper:
"""Profiling CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper sup... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfilingArgumentsHelper:
"""Profiling CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: ... | the_stack_v2_python_sparse | plaso/cli/helpers/profiling.py | log2timeline/plaso | train | 1,506 |
9096a9e4077128699fa2b5b20522cf6c82e7eb01 | [
"super(MobileNetV2Backbone, self).__init__()\nself.features = nn.ModuleList(list(self.features)[:18])\nif load_path is not None:\n self.load_state_dict(torch.load(load_path), strict=False)",
"outs = []\nfor i, feature in enumerate(self.features):\n x = feature(x)\n if i in [3, 6, 13, 17]:\n outs.a... | <|body_start_0|>
super(MobileNetV2Backbone, self).__init__()
self.features = nn.ModuleList(list(self.features)[:18])
if load_path is not None:
self.load_state_dict(torch.load(load_path), strict=False)
<|end_body_0|>
<|body_start_1|>
outs = []
for i, feature in enumer... | Backbone of mobilenet v2. | MobileNetV2Backbone | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MobileNetV2Backbone:
"""Backbone of mobilenet v2."""
def __init__(self, load_path=None):
"""Construct MobileNetV3Tiny class. :param load_path: path for saved model"""
<|body_0|>
def forward(self, x):
"""Do an inference on MobileNetV2. :param x: input tensor :retu... | stack_v2_sparse_classes_36k_train_020726 | 1,320 | permissive | [
{
"docstring": "Construct MobileNetV3Tiny class. :param load_path: path for saved model",
"name": "__init__",
"signature": "def __init__(self, load_path=None)"
},
{
"docstring": "Do an inference on MobileNetV2. :param x: input tensor :return: output tensor",
"name": "forward",
"signature... | 2 | null | Implement the Python class `MobileNetV2Backbone` described below.
Class description:
Backbone of mobilenet v2.
Method signatures and docstrings:
- def __init__(self, load_path=None): Construct MobileNetV3Tiny class. :param load_path: path for saved model
- def forward(self, x): Do an inference on MobileNetV2. :param ... | Implement the Python class `MobileNetV2Backbone` described below.
Class description:
Backbone of mobilenet v2.
Method signatures and docstrings:
- def __init__(self, load_path=None): Construct MobileNetV3Tiny class. :param load_path: path for saved model
- def forward(self, x): Do an inference on MobileNetV2. :param ... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class MobileNetV2Backbone:
"""Backbone of mobilenet v2."""
def __init__(self, load_path=None):
"""Construct MobileNetV3Tiny class. :param load_path: path for saved model"""
<|body_0|>
def forward(self, x):
"""Do an inference on MobileNetV2. :param x: input tensor :retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MobileNetV2Backbone:
"""Backbone of mobilenet v2."""
def __init__(self, load_path=None):
"""Construct MobileNetV3Tiny class. :param load_path: path for saved model"""
super(MobileNetV2Backbone, self).__init__()
self.features = nn.ModuleList(list(self.features)[:18])
if loa... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/search_space/networks/pytorch/customs/adelaide_nn/mobilenetv2_backbone.py | Huawei-Ascend/modelzoo | train | 1 |
636e530650acaa3430770923a928903410360048 | [
"if n > 45 or n < 1:\n return []\nres = []\nself.helper(res, [], 1, k, n)\nreturn res",
"if k == 0 and n == 0:\n total_res.append(part_res)\nif k < 0:\n return\nif k > 0:\n if n <= 0:\n return\n for i in range(start_ind, 10):\n self.helper(total_res, part_res + [i], i + 1, k - 1, n - ... | <|body_start_0|>
if n > 45 or n < 1:
return []
res = []
self.helper(res, [], 1, k, n)
return res
<|end_body_0|>
<|body_start_1|>
if k == 0 and n == 0:
total_res.append(part_res)
if k < 0:
return
if k > 0:
if n <= 0:... | Solution description | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Solution description"""
def func(self, k, n):
"""Solution function description"""
<|body_0|>
def helper(self, total_res, part_res, start_ind, k, n):
"""Solution Helper desciption"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n ... | stack_v2_sparse_classes_36k_train_020727 | 855 | permissive | [
{
"docstring": "Solution function description",
"name": "func",
"signature": "def func(self, k, n)"
},
{
"docstring": "Solution Helper desciption",
"name": "helper",
"signature": "def helper(self, total_res, part_res, start_ind, k, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Solution description
Method signatures and docstrings:
- def func(self, k, n): Solution function description
- def helper(self, total_res, part_res, start_ind, k, n): Solution Helper desciption | Implement the Python class `Solution` described below.
Class description:
Solution description
Method signatures and docstrings:
- def func(self, k, n): Solution function description
- def helper(self, total_res, part_res, start_ind, k, n): Solution Helper desciption
<|skeleton|>
class Solution:
"""Solution desc... | 869ee24c50c08403b170e8f7868699185e9dfdd1 | <|skeleton|>
class Solution:
"""Solution description"""
def func(self, k, n):
"""Solution function description"""
<|body_0|>
def helper(self, total_res, part_res, start_ind, k, n):
"""Solution Helper desciption"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Solution description"""
def func(self, k, n):
"""Solution function description"""
if n > 45 or n < 1:
return []
res = []
self.helper(res, [], 1, k, n)
return res
def helper(self, total_res, part_res, start_ind, k, n):
"""Soluti... | the_stack_v2_python_sparse | 216.Combination.Sum.3/1.py | cerebrumaize/leetcode | train | 0 |
9ea014162748b92664743cf57ecc1f484e34447a | [
"self.Wh = np.random.normal(size=(h + i, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"xMax = np.max(x, axis=-1, keepdims=True)\ne_x = np.exp(x - xMax)\nreturn e_x / e_x.sum(axis=-1, keepdims=True)",
"hidden_con = np.concatenate((h_prev.T, x_t.T), axis=0... | <|body_start_0|>
self.Wh = np.random.normal(size=(h + i, h))
self.Wy = np.random.normal(size=(h, o))
self.bh = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
xMax = np.max(x, axis=-1, keepdims=True)
e_x = np.exp(x - xMax)
return e_x /... | RNNCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNCell:
def __init__(self, i, h, o):
"""class condtructor :param i: dim of the data :param h: dim of hidden state :param o: dim of outputs Note: create public attributes Wh, Wy, bh, by Note: Wh and bh: for the concatenated Hidden state and input Wy and by: for the output Note: Weights: ... | stack_v2_sparse_classes_36k_train_020728 | 1,817 | no_license | [
{
"docstring": "class condtructor :param i: dim of the data :param h: dim of hidden state :param o: dim of outputs Note: create public attributes Wh, Wy, bh, by Note: Wh and bh: for the concatenated Hidden state and input Wy and by: for the output Note: Weights: initialized using fandom normal distribution in l... | 3 | stack_v2_sparse_classes_30k_train_020152 | Implement the Python class `RNNCell` described below.
Class description:
Implement the RNNCell class.
Method signatures and docstrings:
- def __init__(self, i, h, o): class condtructor :param i: dim of the data :param h: dim of hidden state :param o: dim of outputs Note: create public attributes Wh, Wy, bh, by Note: ... | Implement the Python class `RNNCell` described below.
Class description:
Implement the RNNCell class.
Method signatures and docstrings:
- def __init__(self, i, h, o): class condtructor :param i: dim of the data :param h: dim of hidden state :param o: dim of outputs Note: create public attributes Wh, Wy, bh, by Note: ... | 4ac942126918c7acaa9ef88d18efe299b2f726fe | <|skeleton|>
class RNNCell:
def __init__(self, i, h, o):
"""class condtructor :param i: dim of the data :param h: dim of hidden state :param o: dim of outputs Note: create public attributes Wh, Wy, bh, by Note: Wh and bh: for the concatenated Hidden state and input Wy and by: for the output Note: Weights: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNCell:
def __init__(self, i, h, o):
"""class condtructor :param i: dim of the data :param h: dim of hidden state :param o: dim of outputs Note: create public attributes Wh, Wy, bh, by Note: Wh and bh: for the concatenated Hidden state and input Wy and by: for the output Note: Weights: initialized us... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/0-rnn_cell.py | DracoMindz/holbertonschool-machine_learning | train | 2 | |
2998d58e1a5f110965aba3124aa8df76b8f73e24 | [
"manager = TeamChannelManager(context)\npayload = {'teamChannelUrl': channel_url, 'privateChannel': private_channel, 'privateChannelGroupOwner': private_channel_group_owner}\nreturn_type = TeamChannel(context)\nqry = ServiceOperationQuery(manager, 'AddTeamChannel', None, payload, None, return_type)\nqry.static = Tr... | <|body_start_0|>
manager = TeamChannelManager(context)
payload = {'teamChannelUrl': channel_url, 'privateChannel': private_channel, 'privateChannelGroupOwner': private_channel_group_owner}
return_type = TeamChannel(context)
qry = ServiceOperationQuery(manager, 'AddTeamChannel', None, pay... | This class is a placeholder for all TeamChannel related methods. | TeamChannelManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamChannelManager:
"""This class is a placeholder for all TeamChannel related methods."""
def add_team_channel(context, channel_url, private_channel=False, private_channel_group_owner=None):
"""Create Team Channel based folder with specific prodID. :param office365.sharepoint.client... | stack_v2_sparse_classes_36k_train_020729 | 3,071 | permissive | [
{
"docstring": "Create Team Channel based folder with specific prodID. :param office365.sharepoint.client_context.ClientContext context: SharePoint client context :param str channel_url: Team channel URL to be stored in the folder metadata. :param bool private_channel: :param str private_channel_group_owner:",
... | 4 | stack_v2_sparse_classes_30k_train_009250 | Implement the Python class `TeamChannelManager` described below.
Class description:
This class is a placeholder for all TeamChannel related methods.
Method signatures and docstrings:
- def add_team_channel(context, channel_url, private_channel=False, private_channel_group_owner=None): Create Team Channel based folder... | Implement the Python class `TeamChannelManager` described below.
Class description:
This class is a placeholder for all TeamChannel related methods.
Method signatures and docstrings:
- def add_team_channel(context, channel_url, private_channel=False, private_channel_group_owner=None): Create Team Channel based folder... | cbd245d1af8d69e013c469cfc2a9851f51c91417 | <|skeleton|>
class TeamChannelManager:
"""This class is a placeholder for all TeamChannel related methods."""
def add_team_channel(context, channel_url, private_channel=False, private_channel_group_owner=None):
"""Create Team Channel based folder with specific prodID. :param office365.sharepoint.client... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamChannelManager:
"""This class is a placeholder for all TeamChannel related methods."""
def add_team_channel(context, channel_url, private_channel=False, private_channel_group_owner=None):
"""Create Team Channel based folder with specific prodID. :param office365.sharepoint.client_context.Clie... | the_stack_v2_python_sparse | office365/sharepoint/teams/channel_manager.py | vgrem/Office365-REST-Python-Client | train | 1,006 |
7cc296ad15e082c0c1620cdcf92e8ae3f2d4c54c | [
"if self.onOffset(date):\n return date\nelse:\n return date + QuarterBegin(month=self.month)",
"if self.onOffset(date):\n return date\nelse:\n return date - QuarterBegin(month=self.month)"
] | <|body_start_0|>
if self.onOffset(date):
return date
else:
return date + QuarterBegin(month=self.month)
<|end_body_0|>
<|body_start_1|>
if self.onOffset(date):
return date
else:
return date - QuarterBegin(month=self.month)
<|end_body_1|>
| QuarterBegin | [
"BSD-3-Clause",
"CC-BY-4.0",
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuarterBegin:
def rollforward(self, date):
"""Roll date forward to nearest start of quarter"""
<|body_0|>
def rollback(self, date):
"""Roll date backward to nearest start of quarter"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.onOffset(da... | stack_v2_sparse_classes_36k_train_020730 | 47,274 | permissive | [
{
"docstring": "Roll date forward to nearest start of quarter",
"name": "rollforward",
"signature": "def rollforward(self, date)"
},
{
"docstring": "Roll date backward to nearest start of quarter",
"name": "rollback",
"signature": "def rollback(self, date)"
}
] | 2 | null | Implement the Python class `QuarterBegin` described below.
Class description:
Implement the QuarterBegin class.
Method signatures and docstrings:
- def rollforward(self, date): Roll date forward to nearest start of quarter
- def rollback(self, date): Roll date backward to nearest start of quarter | Implement the Python class `QuarterBegin` described below.
Class description:
Implement the QuarterBegin class.
Method signatures and docstrings:
- def rollforward(self, date): Roll date forward to nearest start of quarter
- def rollback(self, date): Roll date backward to nearest start of quarter
<|skeleton|>
class ... | dd09bddc62d701721565bbed3731e9586ea306d0 | <|skeleton|>
class QuarterBegin:
def rollforward(self, date):
"""Roll date forward to nearest start of quarter"""
<|body_0|>
def rollback(self, date):
"""Roll date backward to nearest start of quarter"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuarterBegin:
def rollforward(self, date):
"""Roll date forward to nearest start of quarter"""
if self.onOffset(date):
return date
else:
return date + QuarterBegin(month=self.month)
def rollback(self, date):
"""Roll date backward to nearest start of... | the_stack_v2_python_sparse | xarray/coding/cftime_offsets.py | pydata/xarray | train | 2,916 | |
38bfc52e6698c9c75d1b1983ec42941b83fd994b | [
"T1_Pos = np.array([0, 0, 0], dtype=float)\nT1_Vel = np.array([10, 0, 40], dtype=float)\nT1_Acc = np.array([0, 0, -9.81], dtype=float)\nT1_Mass = 1\nT1_Charge = 0\nAcc_dt1 = np.array([0, 0, 0], dtype=float)\nAcc_dt2 = np.array([0, 0, 0], dtype=float)\nT1_DeltaT = 0.1\nT1_Time = 10\nE_plate_index = 0\nKE = 0\nTestin... | <|body_start_0|>
T1_Pos = np.array([0, 0, 0], dtype=float)
T1_Vel = np.array([10, 0, 40], dtype=float)
T1_Acc = np.array([0, 0, -9.81], dtype=float)
T1_Mass = 1
T1_Charge = 0
Acc_dt1 = np.array([0, 0, 0], dtype=float)
Acc_dt2 = np.array([0, 0, 0], dtype=float)
... | Kin_Teststates | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Kin_Teststates:
def Teststate_1():
"""Tregetory of a ball"""
<|body_0|>
def Teststate_2():
"""particle oscilating about origin"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
T1_Pos = np.array([0, 0, 0], dtype=float)
T1_Vel = np.array([10, 0... | stack_v2_sparse_classes_36k_train_020731 | 3,252 | no_license | [
{
"docstring": "Tregetory of a ball",
"name": "Teststate_1",
"signature": "def Teststate_1()"
},
{
"docstring": "particle oscilating about origin",
"name": "Teststate_2",
"signature": "def Teststate_2()"
}
] | 2 | stack_v2_sparse_classes_30k_train_003106 | Implement the Python class `Kin_Teststates` described below.
Class description:
Implement the Kin_Teststates class.
Method signatures and docstrings:
- def Teststate_1(): Tregetory of a ball
- def Teststate_2(): particle oscilating about origin | Implement the Python class `Kin_Teststates` described below.
Class description:
Implement the Kin_Teststates class.
Method signatures and docstrings:
- def Teststate_1(): Tregetory of a ball
- def Teststate_2(): particle oscilating about origin
<|skeleton|>
class Kin_Teststates:
def Teststate_1():
"""Tr... | 1818ee9efb761f035907b19aff4663e355d7eb5a | <|skeleton|>
class Kin_Teststates:
def Teststate_1():
"""Tregetory of a ball"""
<|body_0|>
def Teststate_2():
"""particle oscilating about origin"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Kin_Teststates:
def Teststate_1():
"""Tregetory of a ball"""
T1_Pos = np.array([0, 0, 0], dtype=float)
T1_Vel = np.array([10, 0, 40], dtype=float)
T1_Acc = np.array([0, 0, -9.81], dtype=float)
T1_Mass = 1
T1_Charge = 0
Acc_dt1 = np.array([0, 0, 0], dtype... | the_stack_v2_python_sparse | Synchrotron accelerator simulation/Test_states.py | Griffi22/Coding-portfolio | train | 1 | |
75285bf4d5b41ed6d57429844e3df05950046de9 | [
"saved = []\nfor pos1, i in enumerate(arr):\n for pos in range(pos1, len(arr)):\n if arr[pos] > i:\n saved.append(pos)\n break\n if len(saved) < pos1 + 1:\n saved.append(-1)\nreturn saved",
"stack = [(0, arr[0])]\nsolution = [-1] * len(arr)\nfor pos, i in enumerate(arr):\... | <|body_start_0|>
saved = []
for pos1, i in enumerate(arr):
for pos in range(pos1, len(arr)):
if arr[pos] > i:
saved.append(pos)
break
if len(saved) < pos1 + 1:
saved.append(-1)
return saved
<|end_body... | FindNextLargest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FindNextLargest:
def solution1(self, arr):
"""Native solution, Time complexity: O(n^2) Space complexity: O(n)"""
<|body_0|>
def solution2(self, arr):
"""Stack method Time complexity: O(n) Space complexity: O(n)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_020732 | 1,519 | permissive | [
{
"docstring": "Native solution, Time complexity: O(n^2) Space complexity: O(n)",
"name": "solution1",
"signature": "def solution1(self, arr)"
},
{
"docstring": "Stack method Time complexity: O(n) Space complexity: O(n)",
"name": "solution2",
"signature": "def solution2(self, arr)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002693 | Implement the Python class `FindNextLargest` described below.
Class description:
Implement the FindNextLargest class.
Method signatures and docstrings:
- def solution1(self, arr): Native solution, Time complexity: O(n^2) Space complexity: O(n)
- def solution2(self, arr): Stack method Time complexity: O(n) Space compl... | Implement the Python class `FindNextLargest` described below.
Class description:
Implement the FindNextLargest class.
Method signatures and docstrings:
- def solution1(self, arr): Native solution, Time complexity: O(n^2) Space complexity: O(n)
- def solution2(self, arr): Stack method Time complexity: O(n) Space compl... | 0e3492447add6af49b185679da83552ff46e76f8 | <|skeleton|>
class FindNextLargest:
def solution1(self, arr):
"""Native solution, Time complexity: O(n^2) Space complexity: O(n)"""
<|body_0|>
def solution2(self, arr):
"""Stack method Time complexity: O(n) Space complexity: O(n)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FindNextLargest:
def solution1(self, arr):
"""Native solution, Time complexity: O(n^2) Space complexity: O(n)"""
saved = []
for pos1, i in enumerate(arr):
for pos in range(pos1, len(arr)):
if arr[pos] > i:
saved.append(pos)
... | the_stack_v2_python_sparse | algorithms/Daily_Interview/find_next_largest.py | clemencegoh/Python_Algorithms | train | 0 | |
e99767f55543e52e08fd8d4754afad45eb5be1fc | [
"if self._token is None:\n self._token = get_token()\nelif time.time() - self._token['time_fetched'] > self._token['expires_in']:\n self._token = get_token()\nreturn self._token",
"if self._api_token is None:\n self._api_token = get_management_token()\nelif time.time() - self._api_token['time_fetched'] >... | <|body_start_0|>
if self._token is None:
self._token = get_token()
elif time.time() - self._token['time_fetched'] > self._token['expires_in']:
self._token = get_token()
return self._token
<|end_body_0|>
<|body_start_1|>
if self._api_token is None:
sel... | Subclass of the Task type, exists to allow sharing of access tokens between workers. Arguments: Task {Task} -- Celery task class | AuthorizedTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthorizedTask:
"""Subclass of the Task type, exists to allow sharing of access tokens between workers. Arguments: Task {Task} -- Celery task class"""
def token(self):
"""Defines the google access token for the class. Returns: dict -- Access response dictionary with key, ttl, time.""... | stack_v2_sparse_classes_36k_train_020733 | 2,565 | permissive | [
{
"docstring": "Defines the google access token for the class. Returns: dict -- Access response dictionary with key, ttl, time.",
"name": "token",
"signature": "def token(self)"
},
{
"docstring": "Defines the google access token for the class. Returns: dict -- Access response dictionary with key... | 2 | stack_v2_sparse_classes_30k_train_007390 | Implement the Python class `AuthorizedTask` described below.
Class description:
Subclass of the Task type, exists to allow sharing of access tokens between workers. Arguments: Task {Task} -- Celery task class
Method signatures and docstrings:
- def token(self): Defines the google access token for the class. Returns: ... | Implement the Python class `AuthorizedTask` described below.
Class description:
Subclass of the Task type, exists to allow sharing of access tokens between workers. Arguments: Task {Task} -- Celery task class
Method signatures and docstrings:
- def token(self): Defines the google access token for the class. Returns: ... | f6fcadb06a300c905f88de8879198d6485e6fc6a | <|skeleton|>
class AuthorizedTask:
"""Subclass of the Task type, exists to allow sharing of access tokens between workers. Arguments: Task {Task} -- Celery task class"""
def token(self):
"""Defines the google access token for the class. Returns: dict -- Access response dictionary with key, ttl, time.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthorizedTask:
"""Subclass of the Task type, exists to allow sharing of access tokens between workers. Arguments: Task {Task} -- Celery task class"""
def token(self):
"""Defines the google access token for the class. Returns: dict -- Access response dictionary with key, ttl, time."""
if ... | the_stack_v2_python_sparse | framework/tasks/authorized_task.py | CIMAC-CIDC/cidc-taskmanager | train | 0 |
3c8dedd5289adae2c3ce648ce02d1f0c59c059ab | [
"a = st.multiselect('Plot Multiple Tickers', parent.everyone_names())\ntarget = st.selectbox('Target Variable', parent.get_feature_list())\ng_cb1 = st.button('Plot')\nif g_cb1:\n return self.plot_multi(a, parent, target)\nelse:\n st.stop()",
"source = pd.DataFrame()\nfor name in names:\n temp = parent.fe... | <|body_start_0|>
a = st.multiselect('Plot Multiple Tickers', parent.everyone_names())
target = st.selectbox('Target Variable', parent.get_feature_list())
g_cb1 = st.button('Plot')
if g_cb1:
return self.plot_multi(a, parent, target)
else:
st.stop()
<|end_bo... | Class to plot graphs | Graph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Graph:
"""Class to plot graphs"""
def plot_multiple_tickers(self, parent):
"""Function to plot multiple columns into single graph using altair lib Args: parent (object): Parent class's object"""
<|body_0|>
def plot_multi(self, names, parent, target):
"""sub funct... | stack_v2_sparse_classes_36k_train_020734 | 1,749 | permissive | [
{
"docstring": "Function to plot multiple columns into single graph using altair lib Args: parent (object): Parent class's object",
"name": "plot_multiple_tickers",
"signature": "def plot_multiple_tickers(self, parent)"
},
{
"docstring": "sub function of plot_multiple_tickers function; It Fetche... | 2 | stack_v2_sparse_classes_30k_train_004672 | Implement the Python class `Graph` described below.
Class description:
Class to plot graphs
Method signatures and docstrings:
- def plot_multiple_tickers(self, parent): Function to plot multiple columns into single graph using altair lib Args: parent (object): Parent class's object
- def plot_multi(self, names, paren... | Implement the Python class `Graph` described below.
Class description:
Class to plot graphs
Method signatures and docstrings:
- def plot_multiple_tickers(self, parent): Function to plot multiple columns into single graph using altair lib Args: parent (object): Parent class's object
- def plot_multi(self, names, paren... | 2586e0d28ee9e2db17bc0947ada0f4cb6a3eeac6 | <|skeleton|>
class Graph:
"""Class to plot graphs"""
def plot_multiple_tickers(self, parent):
"""Function to plot multiple columns into single graph using altair lib Args: parent (object): Parent class's object"""
<|body_0|>
def plot_multi(self, names, parent, target):
"""sub funct... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Graph:
"""Class to plot graphs"""
def plot_multiple_tickers(self, parent):
"""Function to plot multiple columns into single graph using altair lib Args: parent (object): Parent class's object"""
a = st.multiselect('Plot Multiple Tickers', parent.everyone_names())
target = st.selec... | the_stack_v2_python_sparse | src/eda/graphs.py | adityavyasbme/GetSetHedge | train | 0 |
d6e1d00460b784c7d11f08e9ad9c00f33132d7b5 | [
"length = 0\nnode = head\nwhile node is not None:\n node = node.next\n length += 1\nreturn length",
"found_node = head\nfor i in range(1, index + 1):\n found_node = found_node.next\nreturn found_node",
"length = self.calc_len(head)\nif length == 0 or k % length == 0:\n return head\nsteps_count = k %... | <|body_start_0|>
length = 0
node = head
while node is not None:
node = node.next
length += 1
return length
<|end_body_0|>
<|body_start_1|>
found_node = head
for i in range(1, index + 1):
found_node = found_node.next
return foun... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calc_len(self, head):
""":type head: ListNode :rtype: int"""
<|body_0|>
def find_node(self, head, index):
""":type head: ListNode :type index: int :rtype: ListNode"""
<|body_1|>
def rotateRight(self, head, k):
""":type head: ListNod... | stack_v2_sparse_classes_36k_train_020735 | 1,520 | no_license | [
{
"docstring": ":type head: ListNode :rtype: int",
"name": "calc_len",
"signature": "def calc_len(self, head)"
},
{
"docstring": ":type head: ListNode :type index: int :rtype: ListNode",
"name": "find_node",
"signature": "def find_node(self, head, index)"
},
{
"docstring": ":type... | 3 | stack_v2_sparse_classes_30k_train_004253 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calc_len(self, head): :type head: ListNode :rtype: int
- def find_node(self, head, index): :type head: ListNode :type index: int :rtype: ListNode
- def rotateRight(self, head... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calc_len(self, head): :type head: ListNode :rtype: int
- def find_node(self, head, index): :type head: ListNode :type index: int :rtype: ListNode
- def rotateRight(self, head... | c5a165d14c56f7ce29b923933d2bda4576eab8a2 | <|skeleton|>
class Solution:
def calc_len(self, head):
""":type head: ListNode :rtype: int"""
<|body_0|>
def find_node(self, head, index):
""":type head: ListNode :type index: int :rtype: ListNode"""
<|body_1|>
def rotateRight(self, head, k):
""":type head: ListNod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def calc_len(self, head):
""":type head: ListNode :rtype: int"""
length = 0
node = head
while node is not None:
node = node.next
length += 1
return length
def find_node(self, head, index):
""":type head: ListNode :type inde... | the_stack_v2_python_sparse | LeetCode/Linked Lists/Rotate_List_61.py | unterumarmung/practice | train | 3 | |
3fac809dfa1f4a9498152f480bc428127e0bc571 | [
"if not locale:\n locale = dt.get_locale()\nfmt = self._FORMATTERS_REGEX.sub(lambda m: self._strftime(dt, m, locale), fmt)\nfmt = re.sub('%(a|A|b|B|p)', lambda m: self._localize_directive(dt, m.group(1), locale), fmt)\nif hasattr(dt, '_datetime'):\n trans = dt._datetime.strftime(fmt)\nelif hasattr(dt, '_time'... | <|body_start_0|>
if not locale:
locale = dt.get_locale()
fmt = self._FORMATTERS_REGEX.sub(lambda m: self._strftime(dt, m, locale), fmt)
fmt = re.sub('%(a|A|b|B|p)', lambda m: self._localize_directive(dt, m.group(1), locale), fmt)
if hasattr(dt, '_datetime'):
trans... | ClassicFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassicFormatter:
def format(self, dt, fmt, locale=None):
"""Formats a Pendulum instance with a given format and locale. :param dt: The instance to format :type dt: pendulum.Pendulum or pendulum.Date :param fmt: The format to use :type fmt: str :param locale: The locale to use :type loca... | stack_v2_sparse_classes_36k_train_020736 | 3,284 | permissive | [
{
"docstring": "Formats a Pendulum instance with a given format and locale. :param dt: The instance to format :type dt: pendulum.Pendulum or pendulum.Date :param fmt: The format to use :type fmt: str :param locale: The locale to use :type locale: str or None :rtype: str",
"name": "format",
"signature": ... | 3 | null | Implement the Python class `ClassicFormatter` described below.
Class description:
Implement the ClassicFormatter class.
Method signatures and docstrings:
- def format(self, dt, fmt, locale=None): Formats a Pendulum instance with a given format and locale. :param dt: The instance to format :type dt: pendulum.Pendulum ... | Implement the Python class `ClassicFormatter` described below.
Class description:
Implement the ClassicFormatter class.
Method signatures and docstrings:
- def format(self, dt, fmt, locale=None): Formats a Pendulum instance with a given format and locale. :param dt: The instance to format :type dt: pendulum.Pendulum ... | d59c99dcdcd280d7eec36a693dd80f8c8c831ea2 | <|skeleton|>
class ClassicFormatter:
def format(self, dt, fmt, locale=None):
"""Formats a Pendulum instance with a given format and locale. :param dt: The instance to format :type dt: pendulum.Pendulum or pendulum.Date :param fmt: The format to use :type fmt: str :param locale: The locale to use :type loca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassicFormatter:
def format(self, dt, fmt, locale=None):
"""Formats a Pendulum instance with a given format and locale. :param dt: The instance to format :type dt: pendulum.Pendulum or pendulum.Date :param fmt: The format to use :type fmt: str :param locale: The locale to use :type locale: str or Non... | the_stack_v2_python_sparse | modules/dbnd/src/dbnd/_vendor/pendulum/formatting/classic_formatter.py | databand-ai/dbnd | train | 257 | |
ac0750b1c7448fd5ce6331b1f079934c4f2ae277 | [
"credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Could not validate credentials', headers={'WWW-Authenticate': 'Bearer'})\ntry:\n payload = decode(token, self.SECRET_KEY, algorithms=[self.ALGORITHM])\n username: str = payload.get('sub')\n if username is None:\n ... | <|body_start_0|>
credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Could not validate credentials', headers={'WWW-Authenticate': 'Bearer'})
try:
payload = decode(token, self.SECRET_KEY, algorithms=[self.ALGORITHM])
username: str = payload.get... | This class defines functions that are necessary for the authentication processes of the bot trainer | Authentication | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Authentication:
"""This class defines functions that are necessary for the authentication processes of the bot trainer"""
async def get_current_user(self, request: Request, token: str=Depends(Utility.oauth2_scheme)):
"""Validates the user credentials and facilitates the login process... | stack_v2_sparse_classes_36k_train_020737 | 4,056 | permissive | [
{
"docstring": "Validates the user credentials and facilitates the login process",
"name": "get_current_user",
"signature": "async def get_current_user(self, request: Request, token: str=Depends(Utility.oauth2_scheme))"
},
{
"docstring": "Creates access tokens (JSON Web Tokens) for secure login"... | 5 | stack_v2_sparse_classes_30k_train_007186 | Implement the Python class `Authentication` described below.
Class description:
This class defines functions that are necessary for the authentication processes of the bot trainer
Method signatures and docstrings:
- async def get_current_user(self, request: Request, token: str=Depends(Utility.oauth2_scheme)): Validat... | Implement the Python class `Authentication` described below.
Class description:
This class defines functions that are necessary for the authentication processes of the bot trainer
Method signatures and docstrings:
- async def get_current_user(self, request: Request, token: str=Depends(Utility.oauth2_scheme)): Validat... | 3927d2ba5aab37aa20182b4f21f7a83f7c537b8d | <|skeleton|>
class Authentication:
"""This class defines functions that are necessary for the authentication processes of the bot trainer"""
async def get_current_user(self, request: Request, token: str=Depends(Utility.oauth2_scheme)):
"""Validates the user credentials and facilitates the login process... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Authentication:
"""This class defines functions that are necessary for the authentication processes of the bot trainer"""
async def get_current_user(self, request: Request, token: str=Depends(Utility.oauth2_scheme)):
"""Validates the user credentials and facilitates the login process"""
c... | the_stack_v2_python_sparse | bot_trainer/api/auth.py | ml-ds-data/chiron | train | 1 |
346e07328cb618bb3859b879d0bedaeec374fc7a | [
"self.dir = s_dir\nself.update_time = update_time\nif not os.path.exists('./{}'.format(self.dir)):\n os.makedirs('./{}'.format(self.dir))",
"series_id = str(series_id)\nseries_ids = []\nfor _, _, filenames in os.walk('./{}'.format(self.dir)):\n series_ids.extend(filenames)\nreturn series_id in series_ids",
... | <|body_start_0|>
self.dir = s_dir
self.update_time = update_time
if not os.path.exists('./{}'.format(self.dir)):
os.makedirs('./{}'.format(self.dir))
<|end_body_0|>
<|body_start_1|>
series_id = str(series_id)
series_ids = []
for _, _, filenames in os.walk('./... | Framework for logging information about podcasts Each log file will have a name corresponding to the series_id of the podcast and there will only be one line in the file indicating its last update time. | LogPod | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogPod:
"""Framework for logging information about podcasts Each log file will have a name corresponding to the series_id of the podcast and there will only be one line in the file indicating its last update time."""
def __init__(self, s_dir, update_time=15 * constants.MINUTE):
"""Co... | stack_v2_sparse_classes_36k_train_020738 | 2,505 | permissive | [
{
"docstring": "Constructor: s_dir: location to store logs update_time: second-based time indicator that allows one to determine if a RSS feed request is necessary",
"name": "__init__",
"signature": "def __init__(self, s_dir, update_time=15 * constants.MINUTE)"
},
{
"docstring": "Boolean indicat... | 5 | null | Implement the Python class `LogPod` described below.
Class description:
Framework for logging information about podcasts Each log file will have a name corresponding to the series_id of the podcast and there will only be one line in the file indicating its last update time.
Method signatures and docstrings:
- def __i... | Implement the Python class `LogPod` described below.
Class description:
Framework for logging information about podcasts Each log file will have a name corresponding to the series_id of the podcast and there will only be one line in the file indicating its last update time.
Method signatures and docstrings:
- def __i... | 061d0f9cccf278363ffaeb27fc655743b1052ae5 | <|skeleton|>
class LogPod:
"""Framework for logging information about podcasts Each log file will have a name corresponding to the series_id of the podcast and there will only be one line in the file indicating its last update time."""
def __init__(self, s_dir, update_time=15 * constants.MINUTE):
"""Co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogPod:
"""Framework for logging information about podcasts Each log file will have a name corresponding to the series_id of the podcast and there will only be one line in the file indicating its last update time."""
def __init__(self, s_dir, update_time=15 * constants.MINUTE):
"""Constructor: s_... | the_stack_v2_python_sparse | podcatch/utpodcatch/ils/logpod.py | cuappdev/archives | train | 0 |
1fecae1e4c988d4c0cd8619e2847646a15fd224f | [
"stack = []\nfor i in s:\n if i in '(':\n stack.append(')')\n elif i in '[':\n stack.append(']')\n elif i in '{':\n stack.append('}')\n elif not stack or i != stack.pop():\n return False\nreturn not bool(stack)",
"stack = ['?']\nbrackets = {'(': ')', '{': '}', '[': ']', '?'... | <|body_start_0|>
stack = []
for i in s:
if i in '(':
stack.append(')')
elif i in '[':
stack.append(']')
elif i in '{':
stack.append('}')
elif not stack or i != stack.pop():
return False
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValid(self, s: str) -> bool:
"""栈"""
<|body_0|>
def isValidDict(self, s: str) -> bool:
"""栈 + 哈希表"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
stack = []
for i in s:
if i in '(':
stack.append(')... | stack_v2_sparse_classes_36k_train_020739 | 1,450 | no_license | [
{
"docstring": "栈",
"name": "isValid",
"signature": "def isValid(self, s: str) -> bool"
},
{
"docstring": "栈 + 哈希表",
"name": "isValidDict",
"signature": "def isValidDict(self, s: str) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_006431 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid(self, s: str) -> bool: 栈
- def isValidDict(self, s: str) -> bool: 栈 + 哈希表 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid(self, s: str) -> bool: 栈
- def isValidDict(self, s: str) -> bool: 栈 + 哈希表
<|skeleton|>
class Solution:
def isValid(self, s: str) -> bool:
"""栈"""
... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def isValid(self, s: str) -> bool:
"""栈"""
<|body_0|>
def isValidDict(self, s: str) -> bool:
"""栈 + 哈希表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isValid(self, s: str) -> bool:
"""栈"""
stack = []
for i in s:
if i in '(':
stack.append(')')
elif i in '[':
stack.append(']')
elif i in '{':
stack.append('}')
elif not stack or... | the_stack_v2_python_sparse | 20.有效的括号/solution.py | QtTao/daily_leetcode | train | 0 | |
596414087501bbbf78c8c5b7a198a82ffe5727c9 | [
"self.require_collection()\nrequest = http.Request('POST', self.get_url(), self.wrap_object({}))\nreturn (request, parsers.parse_json)",
"self.require_collection()\nrequest = http.Request('DELETE', self.get_url())\nreturn (request, parsers.parse_empty)"
] | <|body_start_0|>
self.require_collection()
request = http.Request('POST', self.get_url(), self.wrap_object({}))
return (request, parsers.parse_json)
<|end_body_0|>
<|body_start_1|>
self.require_collection()
request = http.Request('DELETE', self.get_url())
return (request... | Likes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Likes:
def create(self):
"""Set a like on this media by the currently authenticated user."""
<|body_0|>
def delete(self):
"""Remove a like on this media by the currently authenticated user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.requir... | stack_v2_sparse_classes_36k_train_020740 | 832 | permissive | [
{
"docstring": "Set a like on this media by the currently authenticated user.",
"name": "create",
"signature": "def create(self)"
},
{
"docstring": "Remove a like on this media by the currently authenticated user.",
"name": "delete",
"signature": "def delete(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018718 | Implement the Python class `Likes` described below.
Class description:
Implement the Likes class.
Method signatures and docstrings:
- def create(self): Set a like on this media by the currently authenticated user.
- def delete(self): Remove a like on this media by the currently authenticated user. | Implement the Python class `Likes` described below.
Class description:
Implement the Likes class.
Method signatures and docstrings:
- def create(self): Set a like on this media by the currently authenticated user.
- def delete(self): Remove a like on this media by the currently authenticated user.
<|skeleton|>
class... | 25caa745a104c8dc209584fa359294c65dbf88bb | <|skeleton|>
class Likes:
def create(self):
"""Set a like on this media by the currently authenticated user."""
<|body_0|>
def delete(self):
"""Remove a like on this media by the currently authenticated user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Likes:
def create(self):
"""Set a like on this media by the currently authenticated user."""
self.require_collection()
request = http.Request('POST', self.get_url(), self.wrap_object({}))
return (request, parsers.parse_json)
def delete(self):
"""Remove a like on th... | the_stack_v2_python_sparse | libsaas/services/instagram/likes.py | piplcom/libsaas | train | 1 | |
0d31caa16c0ca84ee743c74163072377f0aaa348 | [
"enum_values = self._assert_enum_valid(enum)\nif isinstance(enum, EnumMeta):\n self._enum_class = enum\n self._str2enum = dict(zip(enum_values, enum))\nelse:\n self._enum_class = None\n self._str2enum = {v: v for v in enum_values}\nsuper().__init__(type='string', default=default, enum=enum_values, descr... | <|body_start_0|>
enum_values = self._assert_enum_valid(enum)
if isinstance(enum, EnumMeta):
self._enum_class = enum
self._str2enum = dict(zip(enum_values, enum))
else:
self._enum_class = None
self._str2enum = {v: v for v in enum_values}
sup... | Enum parameter parse the value according to its enum values. | EnumInput | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnumInput:
"""Enum parameter parse the value according to its enum values."""
def __init__(self, *, enum: Union[EnumMeta, Sequence[str]]=None, default=None, description=None, **kwargs):
"""Initialize an enum parameter, the options of an enum parameter are the enum values. :param enum... | stack_v2_sparse_classes_36k_train_020741 | 48,366 | permissive | [
{
"docstring": "Initialize an enum parameter, the options of an enum parameter are the enum values. :param enum: Enum values. :type Union[EnumMeta, Sequence[str]] :param description: Description of the param. :type description: str :param optional: If the param is optional. :type optional: bool :raises ~azure.a... | 4 | stack_v2_sparse_classes_30k_train_016148 | Implement the Python class `EnumInput` described below.
Class description:
Enum parameter parse the value according to its enum values.
Method signatures and docstrings:
- def __init__(self, *, enum: Union[EnumMeta, Sequence[str]]=None, default=None, description=None, **kwargs): Initialize an enum parameter, the opti... | Implement the Python class `EnumInput` described below.
Class description:
Enum parameter parse the value according to its enum values.
Method signatures and docstrings:
- def __init__(self, *, enum: Union[EnumMeta, Sequence[str]]=None, default=None, description=None, **kwargs): Initialize an enum parameter, the opti... | 1c66defa502b754abcc9e5afa444ca03c609342f | <|skeleton|>
class EnumInput:
"""Enum parameter parse the value according to its enum values."""
def __init__(self, *, enum: Union[EnumMeta, Sequence[str]]=None, default=None, description=None, **kwargs):
"""Initialize an enum parameter, the options of an enum parameter are the enum values. :param enum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnumInput:
"""Enum parameter parse the value according to its enum values."""
def __init__(self, *, enum: Union[EnumMeta, Sequence[str]]=None, default=None, description=None, **kwargs):
"""Initialize an enum parameter, the options of an enum parameter are the enum values. :param enum: Enum values... | the_stack_v2_python_sparse | sdk/ml/azure-ai-ml/azure/ai/ml/entities/_inputs_outputs.py | gaoyp830/azure-sdk-for-python | train | 0 |
b2e672df28e20bae58e436d87c4e8fa4647d551f | [
"super(mp_conv_residual, self).__init__()\nself.conv1 = torch.nn.Sequential(torch.nn.Conv2d(nin, nmed, 1), SyncBatchNorm(nmed), torch.nn.ReLU(inplace=True))\nself.mp_conv = mp_conv_v2(nmed, nmed, netype, extension=extension)\nself.conv2 = torch.nn.Sequential(torch.nn.Conv2d(nmed, nin, 1), SyncBatchNorm(nin), torch.... | <|body_start_0|>
super(mp_conv_residual, self).__init__()
self.conv1 = torch.nn.Sequential(torch.nn.Conv2d(nin, nmed, 1), SyncBatchNorm(nmed), torch.nn.ReLU(inplace=True))
self.mp_conv = mp_conv_v2(nmed, nmed, netype, extension=extension)
self.conv2 = torch.nn.Sequential(torch.nn.Conv2d(... | mp_conv_residual | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mp_conv_residual:
def __init__(self, nin, nmed, netype, extension=mp_conv_type.ORIG_WITH_DIFF, with_residual=True, with_hop=False):
"""Residual block for graph conv network. :param nin: number of input units :param nmed: number of units in the graph conv layer :param netype: number of ed... | stack_v2_sparse_classes_36k_train_020742 | 1,915 | permissive | [
{
"docstring": "Residual block for graph conv network. :param nin: number of input units :param nmed: number of units in the graph conv layer :param netype: number of edge types :param extension: organization type of edge features :param with_residual: use residual link or not",
"name": "__init__",
"sig... | 2 | stack_v2_sparse_classes_30k_train_015656 | Implement the Python class `mp_conv_residual` described below.
Class description:
Implement the mp_conv_residual class.
Method signatures and docstrings:
- def __init__(self, nin, nmed, netype, extension=mp_conv_type.ORIG_WITH_DIFF, with_residual=True, with_hop=False): Residual block for graph conv network. :param ni... | Implement the Python class `mp_conv_residual` described below.
Class description:
Implement the mp_conv_residual class.
Method signatures and docstrings:
- def __init__(self, nin, nmed, netype, extension=mp_conv_type.ORIG_WITH_DIFF, with_residual=True, with_hop=False): Residual block for graph conv network. :param ni... | d7d480aa63d1e69cb94128610ec72938cc7873e8 | <|skeleton|>
class mp_conv_residual:
def __init__(self, nin, nmed, netype, extension=mp_conv_type.ORIG_WITH_DIFF, with_residual=True, with_hop=False):
"""Residual block for graph conv network. :param nin: number of input units :param nmed: number of units in the graph conv layer :param netype: number of ed... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class mp_conv_residual:
def __init__(self, nin, nmed, netype, extension=mp_conv_type.ORIG_WITH_DIFF, with_residual=True, with_hop=False):
"""Residual block for graph conv network. :param nin: number of input units :param nmed: number of units in the graph conv layer :param netype: number of edge types :para... | the_stack_v2_python_sparse | lib/mpnn/mp_nn_residual.py | richardodliu/Factor-Graph-Neural-Network | train | 0 | |
3f3f6b9f7ab67b729d50d1d582af0be1282b608c | [
"vals = []\n\ndef to_str(node):\n if node:\n vals.append(str(node.val))\n to_str(node.left)\n to_str(node.right)\n else:\n vals.append('#')\nto_str(root)\nreturn ','.join(vals)",
"vals = iter(data.split(','))\n\ndef to_node():\n c = vals.next()\n if c == '#':\n retur... | <|body_start_0|>
vals = []
def to_str(node):
if node:
vals.append(str(node.val))
to_str(node.left)
to_str(node.right)
else:
vals.append('#')
to_str(root)
return ','.join(vals)
<|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_020743 | 1,706 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_003158 | 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:... | f2bf9b13508cd01c8f383789569e55a438f77202 | <|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"""
vals = []
def to_str(node):
if node:
vals.append(str(node.val))
to_str(node.left)
to_str(node.right)
else... | the_stack_v2_python_sparse | version1/449_Serialize_And_Deserialize_BST.py | moontree/leetcode | train | 1 | |
d6e88c9cb2688261c61a4b8e3cbb353216084560 | [
"if not matrix:\n return False\nm = len(matrix)\nn = len(matrix[0])\nfor i in range(m):\n if target <= matrix[i][n - 1]:\n for j in range(n):\n if target == matrix[i][j]:\n return True\n break\nreturn False",
"if not matrix:\n return False\nm = len(matrix)\nn = len... | <|body_start_0|>
if not matrix:
return False
m = len(matrix)
n = len(matrix[0])
for i in range(m):
if target <= matrix[i][n - 1]:
for j in range(n):
if target == matrix[i][j]:
return True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix2(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_020744 | 1,371 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix2",
"signature": "def search... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix2(self, matrix, target): :type matrix: List[List[int]] :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix2(self, matrix, target): :type matrix: List[List[int]] :typ... | 8d83f6f1f4123c61a2be7c369ffa964f382f6bda | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix2(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if not matrix:
return False
m = len(matrix)
n = len(matrix[0])
for i in range(m):
if target <= matrix[i][n - 1]:
... | the_stack_v2_python_sparse | leetcode/74_search_2d_matrix.py | shoumu/HuntingJobPractice | train | 0 | |
e90b2254f9ee8e74ca89ad06df9057b8cef89e9b | [
"self.temperature = None\nself.humidity = None\nself.pressure = None\nself.is_hat_attached = is_hat_attached",
"sense = SenseHat()\ntemp_from_h = sense.get_temperature_from_humidity()\ntemp_from_p = sense.get_temperature_from_pressure()\nt_total = (temp_from_h + temp_from_p) / 2\nif self.is_hat_attached:\n t_c... | <|body_start_0|>
self.temperature = None
self.humidity = None
self.pressure = None
self.is_hat_attached = is_hat_attached
<|end_body_0|>
<|body_start_1|>
sense = SenseHat()
temp_from_h = sense.get_temperature_from_humidity()
temp_from_p = sense.get_temperature_fr... | Get the latest data and update. | SenseHatData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SenseHatData:
"""Get the latest data and update."""
def __init__(self, is_hat_attached):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Get the latest data from Sense HAT."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.t... | stack_v2_sparse_classes_36k_train_020745 | 4,245 | permissive | [
{
"docstring": "Initialize the data object.",
"name": "__init__",
"signature": "def __init__(self, is_hat_attached)"
},
{
"docstring": "Get the latest data from Sense HAT.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | null | Implement the Python class `SenseHatData` described below.
Class description:
Get the latest data and update.
Method signatures and docstrings:
- def __init__(self, is_hat_attached): Initialize the data object.
- def update(self): Get the latest data from Sense HAT. | Implement the Python class `SenseHatData` described below.
Class description:
Get the latest data and update.
Method signatures and docstrings:
- def __init__(self, is_hat_attached): Initialize the data object.
- def update(self): Get the latest data from Sense HAT.
<|skeleton|>
class SenseHatData:
"""Get the la... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class SenseHatData:
"""Get the latest data and update."""
def __init__(self, is_hat_attached):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Get the latest data from Sense HAT."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SenseHatData:
"""Get the latest data and update."""
def __init__(self, is_hat_attached):
"""Initialize the data object."""
self.temperature = None
self.humidity = None
self.pressure = None
self.is_hat_attached = is_hat_attached
def update(self):
"""Get... | the_stack_v2_python_sparse | homeassistant/components/sensehat/sensor.py | BenWoodford/home-assistant | train | 11 |
dbdd9f777e41dd16832c075db145f1d1e32cd076 | [
"m, n = (len(dungeon), len(dungeon[0]))\ndp = [[1] * n for i in range(m)]\ndp[m - 1][n - 1] = max(1, 1 - dungeon[m - 1][n - 1])\nfor i in range(m - 2, -1, -1):\n dp[i][n - 1] = max(1, dp[i + 1][n - 1] - dungeon[i][n - 1])\nfor j in range(n - 1, -1, -1):\n dp[m - 1][j] = max(1, dp[m - 1][j + 1] - dungeon[m - 1... | <|body_start_0|>
m, n = (len(dungeon), len(dungeon[0]))
dp = [[1] * n for i in range(m)]
dp[m - 1][n - 1] = max(1, 1 - dungeon[m - 1][n - 1])
for i in range(m - 2, -1, -1):
dp[i][n - 1] = max(1, dp[i + 1][n - 1] - dungeon[i][n - 1])
for j in range(n - 1, -1, -1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculateMinimumHP1(self, dungeon):
"""dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]), max(1, dp[i][j+1] - dungeon[i][j]))"""
<|body_0|>
def calculateMinimumHP1(self, dun... | stack_v2_sparse_classes_36k_train_020746 | 2,996 | no_license | [
{
"docstring": "dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]), max(1, dp[i][j+1] - dungeon[i][j]))",
"name": "calculateMinimumHP1",
"signature": "def calculateMinimumHP1(self, dungeon)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_017694 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP1(self, dungeon): dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]),... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP1(self, dungeon): dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]),... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def calculateMinimumHP1(self, dungeon):
"""dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]), max(1, dp[i][j+1] - dungeon[i][j]))"""
<|body_0|>
def calculateMinimumHP1(self, dun... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def calculateMinimumHP1(self, dungeon):
"""dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]), max(1, dp[i][j+1] - dungeon[i][j]))"""
m, n = (len(dungeon), len(dungeon[0]))
dp = [[1] * n fo... | the_stack_v2_python_sparse | Leetcode 0174. Dungeon Game.py | Chaoran-sjsu/leetcode | train | 0 | |
73dc5a7d0ef009b7289a3b07bea55fc9b7055afd | [
"super(Embedding, self).__init__()\nself.dropout = dropout\nwith self.init_scope():\n self.embed = L.EmbedID(num_classes, embedding_dim, ignore_label=ignore_index)\n if use_cuda:\n self.embed.to_gpu()",
"y = self.embed(y)\nif self.dropout > 0:\n y = F.dropout(y, ratio=self.dropout)\nreturn y"
] | <|body_start_0|>
super(Embedding, self).__init__()
self.dropout = dropout
with self.init_scope():
self.embed = L.EmbedID(num_classes, embedding_dim, ignore_label=ignore_index)
if use_cuda:
self.embed.to_gpu()
<|end_body_0|>
<|body_start_1|>
y = se... | Embedding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedding:
def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1, use_cuda=False):
"""Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target space... | stack_v2_sparse_classes_36k_train_020747 | 5,435 | no_license | [
{
"docstring": "Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target spaces dropout (float, optional): the probability to drop nodes of the embedding ignore_index (int, optional): use_cuda... | 2 | stack_v2_sparse_classes_30k_train_010580 | Implement the Python class `Embedding` described below.
Class description:
Implement the Embedding class.
Method signatures and docstrings:
- def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1, use_cuda=False): Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (incl... | Implement the Python class `Embedding` described below.
Class description:
Implement the Embedding class.
Method signatures and docstrings:
- def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1, use_cuda=False): Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (incl... | b6b60a338d65bb369d0034f423feb09db10db8b7 | <|skeleton|>
class Embedding:
def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1, use_cuda=False):
"""Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target space... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Embedding:
def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1, use_cuda=False):
"""Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target spaces dropout (flo... | the_stack_v2_python_sparse | models/chainer/linear.py | carolinebear/pytorch_end2end_speech_recognition | train | 0 | |
e594c41df6e11503b3028f042c413f0f3323d31f | [
"super().__init__(name=monitor.name, mjpeg_url=monitor.mjpeg_image_url, still_image_url=monitor.still_image_url, verify_ssl=verify_ssl)\nself._attr_is_recording = False\nself._attr_available = False\nself._monitor = monitor",
"_LOGGER.debug('Updating camera state for monitor %i', self._monitor.id)\nself._attr_is_... | <|body_start_0|>
super().__init__(name=monitor.name, mjpeg_url=monitor.mjpeg_image_url, still_image_url=monitor.still_image_url, verify_ssl=verify_ssl)
self._attr_is_recording = False
self._attr_available = False
self._monitor = monitor
<|end_body_0|>
<|body_start_1|>
_LOGGER.de... | Representation of a ZoneMinder Monitor Stream. | ZoneMinderCamera | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZoneMinderCamera:
"""Representation of a ZoneMinder Monitor Stream."""
def __init__(self, monitor: Monitor, verify_ssl: bool) -> None:
"""Initialize as a subclass of MjpegCamera."""
<|body_0|>
def update(self) -> None:
"""Update our recording state from the ZM AP... | stack_v2_sparse_classes_36k_train_020748 | 2,101 | permissive | [
{
"docstring": "Initialize as a subclass of MjpegCamera.",
"name": "__init__",
"signature": "def __init__(self, monitor: Monitor, verify_ssl: bool) -> None"
},
{
"docstring": "Update our recording state from the ZM API.",
"name": "update",
"signature": "def update(self) -> None"
}
] | 2 | null | Implement the Python class `ZoneMinderCamera` described below.
Class description:
Representation of a ZoneMinder Monitor Stream.
Method signatures and docstrings:
- def __init__(self, monitor: Monitor, verify_ssl: bool) -> None: Initialize as a subclass of MjpegCamera.
- def update(self) -> None: Update our recording... | Implement the Python class `ZoneMinderCamera` described below.
Class description:
Representation of a ZoneMinder Monitor Stream.
Method signatures and docstrings:
- def __init__(self, monitor: Monitor, verify_ssl: bool) -> None: Initialize as a subclass of MjpegCamera.
- def update(self) -> None: Update our recording... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ZoneMinderCamera:
"""Representation of a ZoneMinder Monitor Stream."""
def __init__(self, monitor: Monitor, verify_ssl: bool) -> None:
"""Initialize as a subclass of MjpegCamera."""
<|body_0|>
def update(self) -> None:
"""Update our recording state from the ZM AP... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZoneMinderCamera:
"""Representation of a ZoneMinder Monitor Stream."""
def __init__(self, monitor: Monitor, verify_ssl: bool) -> None:
"""Initialize as a subclass of MjpegCamera."""
super().__init__(name=monitor.name, mjpeg_url=monitor.mjpeg_image_url, still_image_url=monitor.still_image_... | the_stack_v2_python_sparse | homeassistant/components/zoneminder/camera.py | home-assistant/core | train | 35,501 |
c437bbe67f6f16fbdd5c60e1b69794f80ee3bc0f | [
"terms = re.findall('[^+ ,;]+', search_term)\nkeys = ['first_name', 'last_name', 'network_id', 'email_address', 'id']\nwhere_clause = Expression(1, OP.EQ, 1)\nfor user_term in terms:\n user_term = str(user_term)\n where_clause_part = Expression(1, OP.EQ, 0)\n for k in keys:\n if k == 'id':\n ... | <|body_start_0|>
terms = re.findall('[^+ ,;]+', search_term)
keys = ['first_name', 'last_name', 'network_id', 'email_address', 'id']
where_clause = Expression(1, OP.EQ, 1)
for user_term in terms:
user_term = str(user_term)
where_clause_part = Expression(1, OP.EQ, ... | Retrieves detailed info for a given user. | UserSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSearch:
"""Retrieves detailed info for a given user."""
def search_for_user(search_term, option):
"""Return a dictionary containing information about a given user."""
<|body_0|>
def GET(search_term=None, option=None, **kwargs):
"""Return the requested user in... | stack_v2_sparse_classes_36k_train_020749 | 2,523 | no_license | [
{
"docstring": "Return a dictionary containing information about a given user.",
"name": "search_for_user",
"signature": "def search_for_user(search_term, option)"
},
{
"docstring": "Return the requested user information for a given set of search criteria.",
"name": "GET",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_021610 | Implement the Python class `UserSearch` described below.
Class description:
Retrieves detailed info for a given user.
Method signatures and docstrings:
- def search_for_user(search_term, option): Return a dictionary containing information about a given user.
- def GET(search_term=None, option=None, **kwargs): Return ... | Implement the Python class `UserSearch` described below.
Class description:
Retrieves detailed info for a given user.
Method signatures and docstrings:
- def search_for_user(search_term, option): Return a dictionary containing information about a given user.
- def GET(search_term=None, option=None, **kwargs): Return ... | dd9dbc8ea508e5412b9b9803805a1cb12f8cfc2e | <|skeleton|>
class UserSearch:
"""Retrieves detailed info for a given user."""
def search_for_user(search_term, option):
"""Return a dictionary containing information about a given user."""
<|body_0|>
def GET(search_term=None, option=None, **kwargs):
"""Return the requested user in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserSearch:
"""Retrieves detailed info for a given user."""
def search_for_user(search_term, option):
"""Return a dictionary containing information about a given user."""
terms = re.findall('[^+ ,;]+', search_term)
keys = ['first_name', 'last_name', 'network_id', 'email_address', ... | the_stack_v2_python_sparse | metadata/rest/user_queries/user_search.py | markborkum/pacifica-metadata | train | 0 |
d147be66a46875d93ef743b65b1917f1fec7292a | [
"try:\n movieseries = {'movieseries': []}\n url = 'https://imdb-api.com/en/API/SearchAll/{}/{}'.format(env('API_KEY_MOVIE'), data['search'])\n response = requests.get(url).json()\n if 'Maximum' in response['errorMessage'].split():\n raise exceptions.Throttled(status.HTTP_429_TOO_MANY_REQUESTS)\n ... | <|body_start_0|>
try:
movieseries = {'movieseries': []}
url = 'https://imdb-api.com/en/API/SearchAll/{}/{}'.format(env('API_KEY_MOVIE'), data['search'])
response = requests.get(url).json()
if 'Maximum' in response['errorMessage'].split():
raise exc... | Utilities for the service of movies and series. | UtilsMoviesAndSeries | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilsMoviesAndSeries:
"""Utilities for the service of movies and series."""
def search_all(self, data):
"""Search by all items."""
<|body_0|>
def search_date(self, data):
"""Search by date."""
<|body_1|>
def search_uuid(self, data):
"""Search... | stack_v2_sparse_classes_36k_train_020750 | 11,622 | no_license | [
{
"docstring": "Search by all items.",
"name": "search_all",
"signature": "def search_all(self, data)"
},
{
"docstring": "Search by date.",
"name": "search_date",
"signature": "def search_date(self, data)"
},
{
"docstring": "Search by uuid.",
"name": "search_uuid",
"signa... | 4 | stack_v2_sparse_classes_30k_train_015384 | Implement the Python class `UtilsMoviesAndSeries` described below.
Class description:
Utilities for the service of movies and series.
Method signatures and docstrings:
- def search_all(self, data): Search by all items.
- def search_date(self, data): Search by date.
- def search_uuid(self, data): Search by uuid.
- def... | Implement the Python class `UtilsMoviesAndSeries` described below.
Class description:
Utilities for the service of movies and series.
Method signatures and docstrings:
- def search_all(self, data): Search by all items.
- def search_date(self, data): Search by date.
- def search_uuid(self, data): Search by uuid.
- def... | cd8767b5eeaef3a09d77c936781b4126fd8591de | <|skeleton|>
class UtilsMoviesAndSeries:
"""Utilities for the service of movies and series."""
def search_all(self, data):
"""Search by all items."""
<|body_0|>
def search_date(self, data):
"""Search by date."""
<|body_1|>
def search_uuid(self, data):
"""Search... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UtilsMoviesAndSeries:
"""Utilities for the service of movies and series."""
def search_all(self, data):
"""Search by all items."""
try:
movieseries = {'movieseries': []}
url = 'https://imdb-api.com/en/API/SearchAll/{}/{}'.format(env('API_KEY_MOVIE'), data['search']... | the_stack_v2_python_sparse | api/services/utils.py | ignite7/backproject | train | 0 |
a9ae0e0c8eb41f9d3c9e44a34eac7d804717ea82 | [
"if not isinstance(operation, BucketOperator):\n raise ArgumentError('Operation is not a BucketOperator')\nif operation == BucketOperators.REPLACE and (not id_generator):\n raise ArgumentError('Replace cannot use default ID generator.')\nself.id_generator = id_generator or (lambda x: str(uuid.uuid4()))\nself.... | <|body_start_0|>
if not isinstance(operation, BucketOperator):
raise ArgumentError('Operation is not a BucketOperator')
if operation == BucketOperators.REPLACE and (not id_generator):
raise ArgumentError('Replace cannot use default ID generator.')
self.id_generator = id_g... | AnalyticsIngester | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalyticsIngester:
def __init__(self, id_generator=None, data_converter=lambda x: x, operation=BucketOperators.UPSERT):
"""Initialise ingester. :param DataConverter data_converter: Single parameter Callable which takes a JSON input and returns a transformed JSON output. :param IdGenerato... | stack_v2_sparse_classes_36k_train_020751 | 3,924 | permissive | [
{
"docstring": "Initialise ingester. :param DataConverter data_converter: Single parameter Callable which takes a JSON input and returns a transformed JSON output. :param IdGenerator id_generator: Callable that takes a JSON input and returns an ID string :param BucketOperator operation: Callable that takes a bu... | 2 | stack_v2_sparse_classes_30k_test_000901 | Implement the Python class `AnalyticsIngester` described below.
Class description:
Implement the AnalyticsIngester class.
Method signatures and docstrings:
- def __init__(self, id_generator=None, data_converter=lambda x: x, operation=BucketOperators.UPSERT): Initialise ingester. :param DataConverter data_converter: S... | Implement the Python class `AnalyticsIngester` described below.
Class description:
Implement the AnalyticsIngester class.
Method signatures and docstrings:
- def __init__(self, id_generator=None, data_converter=lambda x: x, operation=BucketOperators.UPSERT): Initialise ingester. :param DataConverter data_converter: S... | 98bdd44604675f7ad844b39f72e754dec6445cbb | <|skeleton|>
class AnalyticsIngester:
def __init__(self, id_generator=None, data_converter=lambda x: x, operation=BucketOperators.UPSERT):
"""Initialise ingester. :param DataConverter data_converter: Single parameter Callable which takes a JSON input and returns a transformed JSON output. :param IdGenerato... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnalyticsIngester:
def __init__(self, id_generator=None, data_converter=lambda x: x, operation=BucketOperators.UPSERT):
"""Initialise ingester. :param DataConverter data_converter: Single parameter Callable which takes a JSON input and returns a transformed JSON output. :param IdGenerator id_generator... | the_stack_v2_python_sparse | couchbase_core/analytics_ingester.py | pauldx/couchbase-python-client | train | 1 | |
631de2942d6f0b78ea75799a7cdf87ae27958f39 | [
"super().__init__()\nif not isinstance(volumes, Volumes):\n raise ValueError(\"'volumes' have to be an instance of the 'Volumes' class.\")\nself._volumes = volumes\nself._sample_mode = sample_mode",
"world2local = self._volumes.get_world_to_local_coords_transform().get_matrix()\ndirections_transform_matrix = e... | <|body_start_0|>
super().__init__()
if not isinstance(volumes, Volumes):
raise ValueError("'volumes' have to be an instance of the 'Volumes' class.")
self._volumes = volumes
self._sample_mode = sample_mode
<|end_body_0|>
<|body_start_1|>
world2local = self._volumes.g... | A module to sample a batch of volumes `Volumes` at 3D points sampled along projection rays. | VolumeSampler | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolumeSampler:
"""A module to sample a batch of volumes `Volumes` at 3D points sampled along projection rays."""
def __init__(self, volumes: Volumes, sample_mode: str='bilinear') -> None:
"""Args: volumes: An instance of the `Volumes` class representing a batch of volumes that are be... | stack_v2_sparse_classes_36k_train_020752 | 17,111 | permissive | [
{
"docstring": "Args: volumes: An instance of the `Volumes` class representing a batch of volumes that are being rendered. sample_mode: Defines the algorithm used to sample the volumetric voxel grid. Can be either \"bilinear\" or \"nearest\".",
"name": "__init__",
"signature": "def __init__(self, volume... | 3 | stack_v2_sparse_classes_30k_train_010204 | Implement the Python class `VolumeSampler` described below.
Class description:
A module to sample a batch of volumes `Volumes` at 3D points sampled along projection rays.
Method signatures and docstrings:
- def __init__(self, volumes: Volumes, sample_mode: str='bilinear') -> None: Args: volumes: An instance of the `V... | Implement the Python class `VolumeSampler` described below.
Class description:
A module to sample a batch of volumes `Volumes` at 3D points sampled along projection rays.
Method signatures and docstrings:
- def __init__(self, volumes: Volumes, sample_mode: str='bilinear') -> None: Args: volumes: An instance of the `V... | a3d99cab6bf5eb69be8d5eb48895da6edd859565 | <|skeleton|>
class VolumeSampler:
"""A module to sample a batch of volumes `Volumes` at 3D points sampled along projection rays."""
def __init__(self, volumes: Volumes, sample_mode: str='bilinear') -> None:
"""Args: volumes: An instance of the `Volumes` class representing a batch of volumes that are be... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VolumeSampler:
"""A module to sample a batch of volumes `Volumes` at 3D points sampled along projection rays."""
def __init__(self, volumes: Volumes, sample_mode: str='bilinear') -> None:
"""Args: volumes: An instance of the `Volumes` class representing a batch of volumes that are being rendered.... | the_stack_v2_python_sparse | pytorch3d/renderer/implicit/renderer.py | facebookresearch/pytorch3d | train | 7,964 |
a3819f2d1715953547d3ae484bbaccc7e9de515d | [
"self.__local = local\nself.__client_connection = client_connection\nself.__host = host\nself.__port = port\nStoppableThread.__init__(self, 'Debug connection thread')",
"import traceback\nlink = SocketWrapper(self.__client_connection)\nbanner = 'connected to %s:%d' % (self.__host, self.__port)\nbanner += '\\nStac... | <|body_start_0|>
self.__local = local
self.__client_connection = client_connection
self.__host = host
self.__port = port
StoppableThread.__init__(self, 'Debug connection thread')
<|end_body_0|>
<|body_start_1|>
import traceback
link = SocketWrapper(self.__client_... | Handles a single incoming connection on the server, connecting it to the interactive Python shell. This is run as a thread. | DebugConnection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DebugConnection:
"""Handles a single incoming connection on the server, connecting it to the interactive Python shell. This is run as a thread."""
def __init__(self, local, client_connection, host, port):
"""Initializes the connection. @param local: The dict of local variables to pop... | stack_v2_sparse_classes_36k_train_020753 | 9,376 | permissive | [
{
"docstring": "Initializes the connection. @param local: The dict of local variables to populate into the envinroment the interactive shell is run in. @param client_connection: The network connection @param host: the client's IP address @param port: the client's port @type local: dict @type client_connection: ... | 3 | null | Implement the Python class `DebugConnection` described below.
Class description:
Handles a single incoming connection on the server, connecting it to the interactive Python shell. This is run as a thread.
Method signatures and docstrings:
- def __init__(self, local, client_connection, host, port): Initializes the con... | Implement the Python class `DebugConnection` described below.
Class description:
Handles a single incoming connection on the server, connecting it to the interactive Python shell. This is run as a thread.
Method signatures and docstrings:
- def __init__(self, local, client_connection, host, port): Initializes the con... | 5099a498edc47ab841965b483c2c32af49eb7dae | <|skeleton|>
class DebugConnection:
"""Handles a single incoming connection on the server, connecting it to the interactive Python shell. This is run as a thread."""
def __init__(self, local, client_connection, host, port):
"""Initializes the connection. @param local: The dict of local variables to pop... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DebugConnection:
"""Handles a single incoming connection on the server, connecting it to the interactive Python shell. This is run as a thread."""
def __init__(self, local, client_connection, host, port):
"""Initializes the connection. @param local: The dict of local variables to populate into th... | the_stack_v2_python_sparse | scalyr_agent/remote_shell.py | scalyr/scalyr-agent-2 | train | 75 |
7528b1593ce9e0cfa2125032de2a17eaa3044b9a | [
"size = len(flowerbed)\nif sum(flowerbed) + n > size // 2 + size % 2:\n return False\nif len(flowerbed) == 1:\n return True\nplant = 0\nfor i in range(size):\n if flowerbed[i] == 1:\n continue\n if i != 0:\n if flowerbed[i - 1] == 1:\n continue\n if i != size - 1:\n if... | <|body_start_0|>
size = len(flowerbed)
if sum(flowerbed) + n > size // 2 + size % 2:
return False
if len(flowerbed) == 1:
return True
plant = 0
for i in range(size):
if flowerbed[i] == 1:
continue
if i != 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canPlaceFlowers(self, flowerbed, n):
""":type flowerbed: List[int] :type n: int :rtype: bool"""
<|body_0|>
def canPlaceFlowers_work(self, flowerbed, n):
""":type flowerbed: List[int] :type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_020754 | 2,599 | no_license | [
{
"docstring": ":type flowerbed: List[int] :type n: int :rtype: bool",
"name": "canPlaceFlowers",
"signature": "def canPlaceFlowers(self, flowerbed, n)"
},
{
"docstring": ":type flowerbed: List[int] :type n: int :rtype: bool",
"name": "canPlaceFlowers_work",
"signature": "def canPlaceFlo... | 2 | stack_v2_sparse_classes_30k_train_021450 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPlaceFlowers(self, flowerbed, n): :type flowerbed: List[int] :type n: int :rtype: bool
- def canPlaceFlowers_work(self, flowerbed, n): :type flowerbed: List[int] :type n: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPlaceFlowers(self, flowerbed, n): :type flowerbed: List[int] :type n: int :rtype: bool
- def canPlaceFlowers_work(self, flowerbed, n): :type flowerbed: List[int] :type n: ... | 3f0ffd519404165fd1a735441b212c801fd1ad1e | <|skeleton|>
class Solution:
def canPlaceFlowers(self, flowerbed, n):
""":type flowerbed: List[int] :type n: int :rtype: bool"""
<|body_0|>
def canPlaceFlowers_work(self, flowerbed, n):
""":type flowerbed: List[int] :type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canPlaceFlowers(self, flowerbed, n):
""":type flowerbed: List[int] :type n: int :rtype: bool"""
size = len(flowerbed)
if sum(flowerbed) + n > size // 2 + size % 2:
return False
if len(flowerbed) == 1:
return True
plant = 0
f... | the_stack_v2_python_sparse | Problems/0600_0699/0605_Can_Place_Flowers/Project_Python3/Can_Place_Flowers.py | NobuyukiInoue/LeetCode | train | 0 | |
d70e21a668bd7e302c4128fdecb9ef05edd1a818 | [
"if params is not None:\n for param_str in params:\n if not hasattr(self, param_str):\n setattr(self, param_str, self._make_param_function(param_str))\nsuper().__init__(derivatives, params=params)",
"def param_function(ext: Union[SqrtGGNExact, SqrtGGNMC], module: Module, g_inp: Tuple[Tensor],... | <|body_start_0|>
if params is not None:
for param_str in params:
if not hasattr(self, param_str):
setattr(self, param_str, self._make_param_function(param_str))
super().__init__(derivatives, params=params)
<|end_body_0|>
<|body_start_1|>
def param... | Base module extension for ``SqrtGGN{Exact, MC}``. | SqrtGGNBaseModule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SqrtGGNBaseModule:
"""Base module extension for ``SqrtGGN{Exact, MC}``."""
def __init__(self, derivatives: BaseDerivatives, params: List[str]=None):
"""Store parameter names and derivatives. Sets up methods that extract the GGN/Fisher matrix square root for the passed parameters, unl... | stack_v2_sparse_classes_36k_train_020755 | 2,674 | permissive | [
{
"docstring": "Store parameter names and derivatives. Sets up methods that extract the GGN/Fisher matrix square root for the passed parameters, unless these methods are overwritten by a child class. Args: derivatives: derivatives object. params: List of parameter names. Defaults to None.",
"name": "__init_... | 2 | stack_v2_sparse_classes_30k_train_004404 | Implement the Python class `SqrtGGNBaseModule` described below.
Class description:
Base module extension for ``SqrtGGN{Exact, MC}``.
Method signatures and docstrings:
- def __init__(self, derivatives: BaseDerivatives, params: List[str]=None): Store parameter names and derivatives. Sets up methods that extract the GGN... | Implement the Python class `SqrtGGNBaseModule` described below.
Class description:
Base module extension for ``SqrtGGN{Exact, MC}``.
Method signatures and docstrings:
- def __init__(self, derivatives: BaseDerivatives, params: List[str]=None): Store parameter names and derivatives. Sets up methods that extract the GGN... | 1ebfb4055be72ed9e0f9d101d78806bd4119645e | <|skeleton|>
class SqrtGGNBaseModule:
"""Base module extension for ``SqrtGGN{Exact, MC}``."""
def __init__(self, derivatives: BaseDerivatives, params: List[str]=None):
"""Store parameter names and derivatives. Sets up methods that extract the GGN/Fisher matrix square root for the passed parameters, unl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SqrtGGNBaseModule:
"""Base module extension for ``SqrtGGN{Exact, MC}``."""
def __init__(self, derivatives: BaseDerivatives, params: List[str]=None):
"""Store parameter names and derivatives. Sets up methods that extract the GGN/Fisher matrix square root for the passed parameters, unless these met... | the_stack_v2_python_sparse | backpack/extensions/secondorder/sqrt_ggn/base.py | f-dangel/backpack | train | 505 |
723b23f13f8aa2429f14fbe6f7c0b953a52979c4 | [
"self.terrain = Terrain.random(size)\nself.path_finder = AStar(start, end, self.terrain.grid)\nwidgets = [Button((-5, size[1] - 1), (5, 1), text='start'), Button((-5, size[1] - 3), (5, 1), text='pause'), Button((-5, size[1] - 5), (5, 1), text='restart')]\nsuper().__init__(widgets, **kwargs)",
"self.terrain.show(s... | <|body_start_0|>
self.terrain = Terrain.random(size)
self.path_finder = AStar(start, end, self.terrain.grid)
widgets = [Button((-5, size[1] - 1), (5, 1), text='start'), Button((-5, size[1] - 3), (5, 1), text='pause'), Button((-5, size[1] - 5), (5, 1), text='restart')]
super().__init__(wi... | PathFinderManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PathFinderManager:
def __init__(self, size=(10, 10), start=(0, 0), end=(9, 9), **kwargs):
"""Create a new path finder using size, start, end and optional arguments."""
<|body_0|>
def show(self):
"""Show the terrain, the widgets and the path_finder."""
<|body_... | stack_v2_sparse_classes_36k_train_020756 | 2,573 | no_license | [
{
"docstring": "Create a new path finder using size, start, end and optional arguments.",
"name": "__init__",
"signature": "def __init__(self, size=(10, 10), start=(0, 0), end=(9, 9), **kwargs)"
},
{
"docstring": "Show the terrain, the widgets and the path_finder.",
"name": "show",
"sign... | 2 | null | Implement the Python class `PathFinderManager` described below.
Class description:
Implement the PathFinderManager class.
Method signatures and docstrings:
- def __init__(self, size=(10, 10), start=(0, 0), end=(9, 9), **kwargs): Create a new path finder using size, start, end and optional arguments.
- def show(self):... | Implement the Python class `PathFinderManager` described below.
Class description:
Implement the PathFinderManager class.
Method signatures and docstrings:
- def __init__(self, size=(10, 10), start=(0, 0), end=(9, 9), **kwargs): Create a new path finder using size, start, end and optional arguments.
- def show(self):... | ebfcaaf4a028eddb36bbc99184eb3f7a86eb24ed | <|skeleton|>
class PathFinderManager:
def __init__(self, size=(10, 10), start=(0, 0), end=(9, 9), **kwargs):
"""Create a new path finder using size, start, end and optional arguments."""
<|body_0|>
def show(self):
"""Show the terrain, the widgets and the path_finder."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PathFinderManager:
def __init__(self, size=(10, 10), start=(0, 0), end=(9, 9), **kwargs):
"""Create a new path finder using size, start, end and optional arguments."""
self.terrain = Terrain.random(size)
self.path_finder = AStar(start, end, self.terrain.grid)
widgets = [Button(... | the_stack_v2_python_sparse | Game Structure/geometry/version5/path finding2.py | MarcPartensky/Python-Games | train | 2 | |
ac8f1088a3937cca7f7feb9fd92e28771525e2c8 | [
"super(ResetServerStateTests, cls).setUpClass()\nkey_resp = cls.keypairs_client.create_keypair(rand_name('key'))\nassert key_resp.status_code is 200\ncls.key = key_resp.entity\ncls.resources.add(cls.key.name, cls.keypairs_client.delete_keypair)\ncls.server = cls.server_behaviors.create_active_server(key_name=cls.ke... | <|body_start_0|>
super(ResetServerStateTests, cls).setUpClass()
key_resp = cls.keypairs_client.create_keypair(rand_name('key'))
assert key_resp.status_code is 200
cls.key = key_resp.entity
cls.resources.add(cls.key.name, cls.keypairs_client.delete_keypair)
cls.server = cl... | ResetServerStateTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetServerStateTests:
def setUpClass(cls):
"""Perform actions that setup the necessary resources for testing. The following resources are created during the setup: - Create a server in active state."""
<|body_0|>
def test_set_server_state(self):
"""Verify that the s... | stack_v2_sparse_classes_36k_train_020757 | 2,988 | permissive | [
{
"docstring": "Perform actions that setup the necessary resources for testing. The following resources are created during the setup: - Create a server in active state.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Verify that the state of a server can be set manu... | 2 | stack_v2_sparse_classes_30k_train_017587 | Implement the Python class `ResetServerStateTests` described below.
Class description:
Implement the ResetServerStateTests class.
Method signatures and docstrings:
- def setUpClass(cls): Perform actions that setup the necessary resources for testing. The following resources are created during the setup: - Create a se... | Implement the Python class `ResetServerStateTests` described below.
Class description:
Implement the ResetServerStateTests class.
Method signatures and docstrings:
- def setUpClass(cls): Perform actions that setup the necessary resources for testing. The following resources are created during the setup: - Create a se... | 30f0e64672676c3f90b4a582fe90fac6621475b3 | <|skeleton|>
class ResetServerStateTests:
def setUpClass(cls):
"""Perform actions that setup the necessary resources for testing. The following resources are created during the setup: - Create a server in active state."""
<|body_0|>
def test_set_server_state(self):
"""Verify that the s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResetServerStateTests:
def setUpClass(cls):
"""Perform actions that setup the necessary resources for testing. The following resources are created during the setup: - Create a server in active state."""
super(ResetServerStateTests, cls).setUpClass()
key_resp = cls.keypairs_client.creat... | the_stack_v2_python_sparse | cloudroast/compute/instance_actions/admin_api/test_reset_server_state.py | RULCSoft/cloudroast | train | 1 | |
14dc63c63658e70281ef8ac5579a198485fb2209 | [
"nn.Module.__init__(self)\nassert_kernel_size(kernel_size)\nchannel = 3\ncoordinates = 2\ninputs = kernel_size ** 2 * channel + coordinates\nhidden = (kernel_size + 1) ** 2 * channel + coordinates\noutput = 1\nself.inputs = nn.Linear(inputs, hidden)\nself.hidden = nn.Linear(hidden, output)",
"x = f.relu(self.inpu... | <|body_start_0|>
nn.Module.__init__(self)
assert_kernel_size(kernel_size)
channel = 3
coordinates = 2
inputs = kernel_size ** 2 * channel + coordinates
hidden = (kernel_size + 1) ** 2 * channel + coordinates
output = 1
self.inputs = nn.Linear(inputs, hidde... | TODO document | _SegmentationNN | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _SegmentationNN:
"""TODO document"""
def __init__(self, kernel_size: int):
"""TODO document"""
<|body_0|>
def forward(self, x):
"""TODO document"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nn.Module.__init__(self)
assert_kernel_size(... | stack_v2_sparse_classes_36k_train_020758 | 3,455 | permissive | [
{
"docstring": "TODO document",
"name": "__init__",
"signature": "def __init__(self, kernel_size: int)"
},
{
"docstring": "TODO document",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001049 | Implement the Python class `_SegmentationNN` described below.
Class description:
TODO document
Method signatures and docstrings:
- def __init__(self, kernel_size: int): TODO document
- def forward(self, x): TODO document | Implement the Python class `_SegmentationNN` described below.
Class description:
TODO document
Method signatures and docstrings:
- def __init__(self, kernel_size: int): TODO document
- def forward(self, x): TODO document
<|skeleton|>
class _SegmentationNN:
"""TODO document"""
def __init__(self, kernel_size:... | 87aeb556e871d9b95dee440e9f6476ce478baa56 | <|skeleton|>
class _SegmentationNN:
"""TODO document"""
def __init__(self, kernel_size: int):
"""TODO document"""
<|body_0|>
def forward(self, x):
"""TODO document"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _SegmentationNN:
"""TODO document"""
def __init__(self, kernel_size: int):
"""TODO document"""
nn.Module.__init__(self)
assert_kernel_size(kernel_size)
channel = 3
coordinates = 2
inputs = kernel_size ** 2 * channel + coordinates
hidden = (kernel_si... | the_stack_v2_python_sparse | dbvpra/segmentation/nn_segmentation.py | rawbby/SS20-DBV-Pra | train | 0 |
5118c5cba9c49099d6805b947fe501b01c735e13 | [
"with Database() as db:\n data = db.get_all('SELECT * FROM tbl_building_hazardous_material WHERE id_building=%s;', (id_building,))\nreturn {'data': data}",
"with Database() as db:\n db.execute('INSERT INTO tbl_building_hazardous_material(\\n\\t\\t\\t\\t\\t\\t\\tid_building, id_hazardous_material, quantity, ... | <|body_start_0|>
with Database() as db:
data = db.get_all('SELECT * FROM tbl_building_hazardous_material WHERE id_building=%s;', (id_building,))
return {'data': data}
<|end_body_0|>
<|body_start_1|>
with Database() as db:
db.execute('INSERT INTO tbl_building_hazardous_ma... | BuildingHazardousMaterial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildingHazardousMaterial:
def get(self, id_building):
"""Return all hazardous material for one building :param id_building: UUID"""
<|body_0|>
def assign(self, body):
"""Assign new hazardous material to building :param body: { id_building: UUID, id_hazardous_materia... | stack_v2_sparse_classes_36k_train_020759 | 2,661 | no_license | [
{
"docstring": "Return all hazardous material for one building :param id_building: UUID",
"name": "get",
"signature": "def get(self, id_building)"
},
{
"docstring": "Assign new hazardous material to building :param body: { id_building: UUID, id_hazardous_material: UUID, quantity: INTEGER, contai... | 3 | null | Implement the Python class `BuildingHazardousMaterial` described below.
Class description:
Implement the BuildingHazardousMaterial class.
Method signatures and docstrings:
- def get(self, id_building): Return all hazardous material for one building :param id_building: UUID
- def assign(self, body): Assign new hazardo... | Implement the Python class `BuildingHazardousMaterial` described below.
Class description:
Implement the BuildingHazardousMaterial class.
Method signatures and docstrings:
- def get(self, id_building): Return all hazardous material for one building :param id_building: UUID
- def assign(self, body): Assign new hazardo... | 43bd57c466a5cd3b133ddc437cb4a6b9f007d267 | <|skeleton|>
class BuildingHazardousMaterial:
def get(self, id_building):
"""Return all hazardous material for one building :param id_building: UUID"""
<|body_0|>
def assign(self, body):
"""Assign new hazardous material to building :param body: { id_building: UUID, id_hazardous_materia... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuildingHazardousMaterial:
def get(self, id_building):
"""Return all hazardous material for one building :param id_building: UUID"""
with Database() as db:
data = db.get_all('SELECT * FROM tbl_building_hazardous_material WHERE id_building=%s;', (id_building,))
return {'data... | the_stack_v2_python_sparse | resturls/buildinghazardousmaterial.py | CAUCA-9-1-1/survip-api | train | 1 | |
38015f58e2eabf83c5b2039dff28913ecd1e4fe3 | [
"self.matrix = matrix\nself.zero = zero\nif vector is None:\n if vtype.lower() == 'rd':\n self.new = zeros(matrix.shape[0], dtype=dtype)\n self.new[:] = random.rand(matrix.shape[0])\n else:\n self.new = ones(matrix.shape[0], dtype=dtype)\n self.new[:] = self.new[:] / norm(self.new)\nel... | <|body_start_0|>
self.matrix = matrix
self.zero = zero
if vector is None:
if vtype.lower() == 'rd':
self.new = zeros(matrix.shape[0], dtype=dtype)
self.new[:] = random.rand(matrix.shape[0])
else:
self.new = ones(matrix.shape... | The Lanczos algorithm to deal with csr-formed sparse Hermitian matrices. Attributes: matrix: csr_matrix The csr-formed sparse Hermitian matrix. zero: float The precision used to cut off the Lanczos iterations. new,old: 1D ndarray The new and old vectors updated in the Lanczos iterations. a,b: 1D list of floats The coef... | Lanczos | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lanczos:
"""The Lanczos algorithm to deal with csr-formed sparse Hermitian matrices. Attributes: matrix: csr_matrix The csr-formed sparse Hermitian matrix. zero: float The precision used to cut off the Lanczos iterations. new,old: 1D ndarray The new and old vectors updated in the Lanczos iteratio... | stack_v2_sparse_classes_36k_train_020760 | 4,686 | no_license | [
{
"docstring": "Constructor. Parameters: matrix: csr_matrix The csr-formed sparse Hermitian matrix. vector: 1D ndarray,optional The initial vector to begin with the Lanczos iterations. It must be normalized already. vtype: string,optional A flag to tell what type of initial vectors to use when the parameter vec... | 4 | stack_v2_sparse_classes_30k_train_015587 | Implement the Python class `Lanczos` described below.
Class description:
The Lanczos algorithm to deal with csr-formed sparse Hermitian matrices. Attributes: matrix: csr_matrix The csr-formed sparse Hermitian matrix. zero: float The precision used to cut off the Lanczos iterations. new,old: 1D ndarray The new and old ... | Implement the Python class `Lanczos` described below.
Class description:
The Lanczos algorithm to deal with csr-formed sparse Hermitian matrices. Attributes: matrix: csr_matrix The csr-formed sparse Hermitian matrix. zero: float The precision used to cut off the Lanczos iterations. new,old: 1D ndarray The new and old ... | c985d0e5c70b08ef396dd591180c493b60b268ee | <|skeleton|>
class Lanczos:
"""The Lanczos algorithm to deal with csr-formed sparse Hermitian matrices. Attributes: matrix: csr_matrix The csr-formed sparse Hermitian matrix. zero: float The precision used to cut off the Lanczos iterations. new,old: 1D ndarray The new and old vectors updated in the Lanczos iteratio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lanczos:
"""The Lanczos algorithm to deal with csr-formed sparse Hermitian matrices. Attributes: matrix: csr_matrix The csr-formed sparse Hermitian matrix. zero: float The precision used to cut off the Lanczos iterations. new,old: 1D ndarray The new and old vectors updated in the Lanczos iterations. a,b: 1D l... | the_stack_v2_python_sparse | Core/BasicAlgorithm/LanczosPy.py | Farewell1989/Hamiltonian-Generator | train | 0 |
238be816d3c228b5fa1d0d7ebd03f9b20cb48d1d | [
"super(ResidualRecurrentEncoder, self).__init__()\nself.batch_first = batch_first\nself.rnn_layers = nn.ModuleList()\nself.rnn_layers.append(nn.LSTM(hidden_size, hidden_size, num_layers=1, bias=True, batch_first=batch_first, bidirectional=True))\nself.rnn_layers.append(nn.LSTM(2 * hidden_size, hidden_size, num_laye... | <|body_start_0|>
super(ResidualRecurrentEncoder, self).__init__()
self.batch_first = batch_first
self.rnn_layers = nn.ModuleList()
self.rnn_layers.append(nn.LSTM(hidden_size, hidden_size, num_layers=1, bias=True, batch_first=batch_first, bidirectional=True))
self.rnn_layers.appen... | Encoder with Embedding, LSTM layers, residual connections and optional dropout. The first LSTM layer is bidirectional and uses variable sequence length API, the remaining (num_layers-1) layers are unidirectional. Residual connections are enabled after third LSTM layer, dropout is applied on inputs to LSTM layers. | ResidualRecurrentEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualRecurrentEncoder:
"""Encoder with Embedding, LSTM layers, residual connections and optional dropout. The first LSTM layer is bidirectional and uses variable sequence length API, the remaining (num_layers-1) layers are unidirectional. Residual connections are enabled after third LSTM layer... | stack_v2_sparse_classes_36k_train_020761 | 4,798 | permissive | [
{
"docstring": "Constructor for the ResidualRecurrentEncoder. :param vocab_size: size of vocabulary :param hidden_size: hidden size for LSTM layers :param num_layers: number of LSTM layers, 1st layer is bidirectional :param dropout: probability of dropout (on input to LSTM layers) :param batch_first: if True th... | 2 | null | Implement the Python class `ResidualRecurrentEncoder` described below.
Class description:
Encoder with Embedding, LSTM layers, residual connections and optional dropout. The first LSTM layer is bidirectional and uses variable sequence length API, the remaining (num_layers-1) layers are unidirectional. Residual connect... | Implement the Python class `ResidualRecurrentEncoder` described below.
Class description:
Encoder with Embedding, LSTM layers, residual connections and optional dropout. The first LSTM layer is bidirectional and uses variable sequence length API, the remaining (num_layers-1) layers are unidirectional. Residual connect... | a5388a45f71a949639b35cc5b990bd130d2d8164 | <|skeleton|>
class ResidualRecurrentEncoder:
"""Encoder with Embedding, LSTM layers, residual connections and optional dropout. The first LSTM layer is bidirectional and uses variable sequence length API, the remaining (num_layers-1) layers are unidirectional. Residual connections are enabled after third LSTM layer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResidualRecurrentEncoder:
"""Encoder with Embedding, LSTM layers, residual connections and optional dropout. The first LSTM layer is bidirectional and uses variable sequence length API, the remaining (num_layers-1) layers are unidirectional. Residual connections are enabled after third LSTM layer, dropout is ... | the_stack_v2_python_sparse | PyTorch/Translation/GNMT/seq2seq/models/encoder.py | NVIDIA/DeepLearningExamples | train | 11,838 |
1f374bfc3ccd730f8b2e124827667f8d7fb376de | [
"result = []\nfor i in range(1, 5):\n result.append(i)\nreturn result",
"result = []\na = []\nfor i in range(1, 5):\n a.append(random.randint(1, 10))\nresult.append(a)\nreturn result"
] | <|body_start_0|>
result = []
for i in range(1, 5):
result.append(i)
return result
<|end_body_0|>
<|body_start_1|>
result = []
a = []
for i in range(1, 5):
a.append(random.randint(1, 10))
result.append(a)
return result
<|end_body_1|... | LineChartJSONView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineChartJSONView:
def get_labels(self):
"""Return 7 labels."""
<|body_0|>
def get_data(self):
"""Return 3 datasets to plot."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
for i in range(1, 5):
result.append(i)
... | stack_v2_sparse_classes_36k_train_020762 | 6,554 | no_license | [
{
"docstring": "Return 7 labels.",
"name": "get_labels",
"signature": "def get_labels(self)"
},
{
"docstring": "Return 3 datasets to plot.",
"name": "get_data",
"signature": "def get_data(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002173 | Implement the Python class `LineChartJSONView` described below.
Class description:
Implement the LineChartJSONView class.
Method signatures and docstrings:
- def get_labels(self): Return 7 labels.
- def get_data(self): Return 3 datasets to plot. | Implement the Python class `LineChartJSONView` described below.
Class description:
Implement the LineChartJSONView class.
Method signatures and docstrings:
- def get_labels(self): Return 7 labels.
- def get_data(self): Return 3 datasets to plot.
<|skeleton|>
class LineChartJSONView:
def get_labels(self):
... | f23b3a955a131fd0b4927321401cb5194f2fc574 | <|skeleton|>
class LineChartJSONView:
def get_labels(self):
"""Return 7 labels."""
<|body_0|>
def get_data(self):
"""Return 3 datasets to plot."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LineChartJSONView:
def get_labels(self):
"""Return 7 labels."""
result = []
for i in range(1, 5):
result.append(i)
return result
def get_data(self):
"""Return 3 datasets to plot."""
result = []
a = []
for i in range(1, 5):
... | the_stack_v2_python_sparse | si8device/views.py | AleksZ13ru/mysite | train | 0 | |
676799d9425226a6ee96f26e1e79657b45387b06 | [
"if domain != 'test':\n domain = None\nself._client = Salesforce(username=username, password=password, security_token=token, domain=domain)\nself._base_url = 'https://{}/services/data/v{}/sobjects'.format(self._client.sf_instance, self._client.sf_version)",
"if validators.email(username) is not True:\n rais... | <|body_start_0|>
if domain != 'test':
domain = None
self._client = Salesforce(username=username, password=password, security_token=token, domain=domain)
self._base_url = 'https://{}/services/data/v{}/sobjects'.format(self._client.sf_instance, self._client.sf_version)
<|end_body_0|>
... | SalesforceClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SalesforceClient:
def __init__(self, username, password, token, domain):
"""Initializes a Salesforce client :param username: Username used to connect :type username: :class:`string` :param password: Password used to connect :type password: :class:`passwd` :param token: Token used to conn... | stack_v2_sparse_classes_36k_train_020763 | 2,987 | permissive | [
{
"docstring": "Initializes a Salesforce client :param username: Username used to connect :type username: :class:`string` :param password: Password used to connect :type password: :class:`passwd` :param token: Token used to connect :type token: :class:`passwd` :param domain: The domain to use :type domain: :cla... | 3 | stack_v2_sparse_classes_30k_train_013758 | Implement the Python class `SalesforceClient` described below.
Class description:
Implement the SalesforceClient class.
Method signatures and docstrings:
- def __init__(self, username, password, token, domain): Initializes a Salesforce client :param username: Username used to connect :type username: :class:`string` :... | Implement the Python class `SalesforceClient` described below.
Class description:
Implement the SalesforceClient class.
Method signatures and docstrings:
- def __init__(self, username, password, token, domain): Initializes a Salesforce client :param username: Username used to connect :type username: :class:`string` :... | 43864a39c0beb343a49446b752abbca103790319 | <|skeleton|>
class SalesforceClient:
def __init__(self, username, password, token, domain):
"""Initializes a Salesforce client :param username: Username used to connect :type username: :class:`string` :param password: Password used to connect :type password: :class:`passwd` :param token: Token used to conn... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SalesforceClient:
def __init__(self, username, password, token, domain):
"""Initializes a Salesforce client :param username: Username used to connect :type username: :class:`string` :param password: Password used to connect :type password: :class:`passwd` :param token: Token used to connect :type toke... | the_stack_v2_python_sparse | src/keydra/clients/salesforce.py | kissmyuzi/keydra | train | 0 | |
a104faab3dc4c77cc2f06ab7039f4b7f4f9cd836 | [
"if len(args) is 3:\n return args\nkey, value = args\nif '__' in key:\n key, op = key.split('__')\n return (key, cls.tr_python[op], value)\nreturn (key, ope.eq, value)",
"if '__' in key:\n key, op = key.split('__')\n if op != 'in' or len(value) > 1:\n return key + cls.tr_sql[op] % (value,)\n... | <|body_start_0|>
if len(args) is 3:
return args
key, value = args
if '__' in key:
key, op = key.split('__')
return (key, cls.tr_python[op], value)
return (key, ope.eq, value)
<|end_body_0|>
<|body_start_1|>
if '__' in key:
key, op ... | Filter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Filter:
def translate_py(cls, *args):
"""translate (key_s, value) filter to (key_s, op, value) filter where op is python operator :param args: (tuple) (key_s, value) or (key_s, op, value) :return: (tuple) (key_s, op, value)"""
<|body_0|>
def translate_sql(cls, key, value):
... | stack_v2_sparse_classes_36k_train_020764 | 5,832 | no_license | [
{
"docstring": "translate (key_s, value) filter to (key_s, op, value) filter where op is python operator :param args: (tuple) (key_s, value) or (key_s, op, value) :return: (tuple) (key_s, op, value)",
"name": "translate_py",
"signature": "def translate_py(cls, *args)"
},
{
"docstring": "translat... | 2 | stack_v2_sparse_classes_30k_train_003018 | Implement the Python class `Filter` described below.
Class description:
Implement the Filter class.
Method signatures and docstrings:
- def translate_py(cls, *args): translate (key_s, value) filter to (key_s, op, value) filter where op is python operator :param args: (tuple) (key_s, value) or (key_s, op, value) :retu... | Implement the Python class `Filter` described below.
Class description:
Implement the Filter class.
Method signatures and docstrings:
- def translate_py(cls, *args): translate (key_s, value) filter to (key_s, op, value) filter where op is python operator :param args: (tuple) (key_s, value) or (key_s, op, value) :retu... | 4d82c3fea63a1055c42f553cb57252c5d665826b | <|skeleton|>
class Filter:
def translate_py(cls, *args):
"""translate (key_s, value) filter to (key_s, op, value) filter where op is python operator :param args: (tuple) (key_s, value) or (key_s, op, value) :return: (tuple) (key_s, op, value)"""
<|body_0|>
def translate_sql(cls, key, value):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Filter:
def translate_py(cls, *args):
"""translate (key_s, value) filter to (key_s, op, value) filter where op is python operator :param args: (tuple) (key_s, value) or (key_s, op, value) :return: (tuple) (key_s, op, value)"""
if len(args) is 3:
return args
key, value = arg... | the_stack_v2_python_sparse | table_player.py | francois-vincent/Utilities | train | 0 | |
dae1b4088ca26ece70dbd91d20a5d5f63fec1c5a | [
"Platform.__init__(self, pos=route[0][:], size=size)\nself._route = route\nself._flying_type = flying_type\nif flying_type == MovingPlatform.LINE:\n self._forward = True\nself._next_point = 1\nself._vector = (Vector2(route[1]) - Vector2(route[0])).normal()",
"vector = self._vector * MovingPlatform.SPEED\nself.... | <|body_start_0|>
Platform.__init__(self, pos=route[0][:], size=size)
self._route = route
self._flying_type = flying_type
if flying_type == MovingPlatform.LINE:
self._forward = True
self._next_point = 1
self._vector = (Vector2(route[1]) - Vector2(route[0])).nor... | The moving platform class. An instance of this class represents a moving platform of a level. Attributes: _route: The rout of this moving platform. _flying_type: The flying type of the moving platform. _forward: This optional flag, used for the LINE type, determines if the moving platform moves forward or backward in t... | MovingPlatform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingPlatform:
"""The moving platform class. An instance of this class represents a moving platform of a level. Attributes: _route: The rout of this moving platform. _flying_type: The flying type of the moving platform. _forward: This optional flag, used for the LINE type, determines if the movi... | stack_v2_sparse_classes_36k_train_020765 | 4,212 | no_license | [
{
"docstring": "Generates a new instance of this class. Generates a new instance of this class and sets the field information. Args: size: The size of the moving platform. route: The route the moving platform. flying_type: The flying type of the moving platform.",
"name": "__init__",
"signature": "def _... | 2 | stack_v2_sparse_classes_30k_train_007297 | Implement the Python class `MovingPlatform` described below.
Class description:
The moving platform class. An instance of this class represents a moving platform of a level. Attributes: _route: The rout of this moving platform. _flying_type: The flying type of the moving platform. _forward: This optional flag, used fo... | Implement the Python class `MovingPlatform` described below.
Class description:
The moving platform class. An instance of this class represents a moving platform of a level. Attributes: _route: The rout of this moving platform. _flying_type: The flying type of the moving platform. _forward: This optional flag, used fo... | 0308785a51bf61d9a4fec2d8370540df502b8178 | <|skeleton|>
class MovingPlatform:
"""The moving platform class. An instance of this class represents a moving platform of a level. Attributes: _route: The rout of this moving platform. _flying_type: The flying type of the moving platform. _forward: This optional flag, used for the LINE type, determines if the movi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingPlatform:
"""The moving platform class. An instance of this class represents a moving platform of a level. Attributes: _route: The rout of this moving platform. _flying_type: The flying type of the moving platform. _forward: This optional flag, used for the LINE type, determines if the moving platform m... | the_stack_v2_python_sparse | game_objects/platform.py | donhilion/JumpAndRun | train | 0 |
de1b565ab92f8b99e1e726f62cb4d87d2a621710 | [
"storage = get_storage()\nrole = storage.read_role(role_id)\nreturn jsonify(RoleSchema().dump(role))",
"storage = get_storage()\nstorage.delete_role(role_id)\nreturn ('', 204)"
] | <|body_start_0|>
storage = get_storage()
role = storage.read_role(role_id)
return jsonify(RoleSchema().dump(role))
<|end_body_0|>
<|body_start_1|>
storage = get_storage()
storage.delete_role(role_id)
return ('', 204)
<|end_body_1|>
| RoleView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleView:
def get(self, role_id):
"""--- summary: Get information about a Role. parameters: - role_id tags: - Roles responses: 200: description: Role created successfully. content: application/json: schema: $ref: '#/components/schemas/RoleSchema' 401: $ref: '#/components/responses/401-Un... | stack_v2_sparse_classes_36k_train_020766 | 5,492 | permissive | [
{
"docstring": "--- summary: Get information about a Role. parameters: - role_id tags: - Roles responses: 200: description: Role created successfully. content: application/json: schema: $ref: '#/components/schemas/RoleSchema' 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref: '#/components/response... | 2 | stack_v2_sparse_classes_30k_train_011425 | Implement the Python class `RoleView` described below.
Class description:
Implement the RoleView class.
Method signatures and docstrings:
- def get(self, role_id): --- summary: Get information about a Role. parameters: - role_id tags: - Roles responses: 200: description: Role created successfully. content: applicatio... | Implement the Python class `RoleView` described below.
Class description:
Implement the RoleView class.
Method signatures and docstrings:
- def get(self, role_id): --- summary: Get information about a Role. parameters: - role_id tags: - Roles responses: 200: description: Role created successfully. content: applicatio... | 280800c73eb7cfd49029462b352887e78f1ff91b | <|skeleton|>
class RoleView:
def get(self, role_id):
"""--- summary: Get information about a Role. parameters: - role_id tags: - Roles responses: 200: description: Role created successfully. content: application/json: schema: $ref: '#/components/schemas/RoleSchema' 401: $ref: '#/components/responses/401-Un... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoleView:
def get(self, role_id):
"""--- summary: Get information about a Role. parameters: - role_id tags: - Roles responses: 200: description: Role created successfully. content: application/json: schema: $ref: '#/components/schemas/RoleSchema' 401: $ref: '#/components/responses/401-Unauthorized' 40... | the_stack_v2_python_sparse | sfa_api/roles.py | SolarArbiter/solarforecastarbiter-api | train | 9 | |
f4b85a2b804bf599cd40a6296d10c3a0f9ff454c | [
"self.hadoop_distribution = hadoop_distribution\nself.hadoop_version = hadoop_version\nself.kerberos_principal = kerberos_principal\nself.namenode = namenode\nself.port = port",
"if dictionary is None:\n return None\nhadoop_distribution = dictionary.get('hadoopDistribution')\nhadoop_version = dictionary.get('h... | <|body_start_0|>
self.hadoop_distribution = hadoop_distribution
self.hadoop_version = hadoop_version
self.kerberos_principal = kerberos_principal
self.namenode = namenode
self.port = port
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
... | Implementation of the 'HdfsConnectParams' model. Specifies an Object containing information about a registered Hdfs source. Attributes: hadoop_distribution (HadoopDistributionEnum): Specifies the Hadoop Distribution. Hadoop distribution. 'CDH' indicates Hadoop distribution type Cloudera. 'HDP' indicates Hadoop distribu... | HdfsConnectParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HdfsConnectParams:
"""Implementation of the 'HdfsConnectParams' model. Specifies an Object containing information about a registered Hdfs source. Attributes: hadoop_distribution (HadoopDistributionEnum): Specifies the Hadoop Distribution. Hadoop distribution. 'CDH' indicates Hadoop distribution t... | stack_v2_sparse_classes_36k_train_020767 | 2,629 | permissive | [
{
"docstring": "Constructor for the HdfsConnectParams class",
"name": "__init__",
"signature": "def __init__(self, hadoop_distribution=None, hadoop_version=None, kerberos_principal=None, namenode=None, port=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dicti... | 2 | null | Implement the Python class `HdfsConnectParams` described below.
Class description:
Implementation of the 'HdfsConnectParams' model. Specifies an Object containing information about a registered Hdfs source. Attributes: hadoop_distribution (HadoopDistributionEnum): Specifies the Hadoop Distribution. Hadoop distribution... | Implement the Python class `HdfsConnectParams` described below.
Class description:
Implementation of the 'HdfsConnectParams' model. Specifies an Object containing information about a registered Hdfs source. Attributes: hadoop_distribution (HadoopDistributionEnum): Specifies the Hadoop Distribution. Hadoop distribution... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class HdfsConnectParams:
"""Implementation of the 'HdfsConnectParams' model. Specifies an Object containing information about a registered Hdfs source. Attributes: hadoop_distribution (HadoopDistributionEnum): Specifies the Hadoop Distribution. Hadoop distribution. 'CDH' indicates Hadoop distribution t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HdfsConnectParams:
"""Implementation of the 'HdfsConnectParams' model. Specifies an Object containing information about a registered Hdfs source. Attributes: hadoop_distribution (HadoopDistributionEnum): Specifies the Hadoop Distribution. Hadoop distribution. 'CDH' indicates Hadoop distribution type Cloudera.... | the_stack_v2_python_sparse | cohesity_management_sdk/models/hdfs_connect_params.py | cohesity/management-sdk-python | train | 24 |
c42e22d354f136eaafabbe923ecb85aa7873b8ff | [
"self.num = len(x)\nself.x_train = x\nself.labels = labels\nself.epoch_completed = 0\nself.index_in_epoch = 0",
"if self.epoch_completed == 0 and self.index_in_epoch == 0:\n perm = np.arange(self.num)\n np.random.shuffle(perm)\n self.x_train = self.x_train[perm]\n self.labels = self.labels[perm]\nif s... | <|body_start_0|>
self.num = len(x)
self.x_train = x
self.labels = labels
self.epoch_completed = 0
self.index_in_epoch = 0
<|end_body_0|>
<|body_start_1|>
if self.epoch_completed == 0 and self.index_in_epoch == 0:
perm = np.arange(self.num)
np.rand... | Define the DataSet, which defines the data_ori batch for train or eval. | DataSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSet:
"""Define the DataSet, which defines the data_ori batch for train or eval."""
def __init__(self, x, labels):
"""Initialization."""
<|body_0|>
def next_batch(self):
"""Get next batch with defined batch size."""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_020768 | 16,496 | no_license | [
{
"docstring": "Initialization.",
"name": "__init__",
"signature": "def __init__(self, x, labels)"
},
{
"docstring": "Get next batch with defined batch size.",
"name": "next_batch",
"signature": "def next_batch(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003280 | Implement the Python class `DataSet` described below.
Class description:
Define the DataSet, which defines the data_ori batch for train or eval.
Method signatures and docstrings:
- def __init__(self, x, labels): Initialization.
- def next_batch(self): Get next batch with defined batch size. | Implement the Python class `DataSet` described below.
Class description:
Define the DataSet, which defines the data_ori batch for train or eval.
Method signatures and docstrings:
- def __init__(self, x, labels): Initialization.
- def next_batch(self): Get next batch with defined batch size.
<|skeleton|>
class DataSe... | 038bb8a67df7c0417ef8f342c6c5f2e41edbb696 | <|skeleton|>
class DataSet:
"""Define the DataSet, which defines the data_ori batch for train or eval."""
def __init__(self, x, labels):
"""Initialization."""
<|body_0|>
def next_batch(self):
"""Get next batch with defined batch size."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataSet:
"""Define the DataSet, which defines the data_ori batch for train or eval."""
def __init__(self, x, labels):
"""Initialization."""
self.num = len(x)
self.x_train = x
self.labels = labels
self.epoch_completed = 0
self.index_in_epoch = 0
def nex... | the_stack_v2_python_sparse | recommendation/FFMTrain/FFMTrain.py | Origami-OG/MyPrivate | train | 0 |
2fa59c0b732eb404a7d2f4189d510c9b5a21325b | [
"if value is None or value == CommonPuddleLiquid.INVALID:\n return PuddleLiquid.INVALID\nif isinstance(value, PuddleLiquid):\n return value\nmapping = dict()\nif hasattr(PuddleLiquid, 'WATER'):\n mapping[CommonPuddleLiquid.WATER] = PuddleLiquid.WATER\nif hasattr(PuddleLiquid, 'Dark Matter'):\n mapping[C... | <|body_start_0|>
if value is None or value == CommonPuddleLiquid.INVALID:
return PuddleLiquid.INVALID
if isinstance(value, PuddleLiquid):
return value
mapping = dict()
if hasattr(PuddleLiquid, 'WATER'):
mapping[CommonPuddleLiquid.WATER] = PuddleLiquid.... | Various types of liquids a puddle may have. | CommonPuddleLiquid | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonPuddleLiquid:
"""Various types of liquids a puddle may have."""
def convert_to_vanilla(value: 'CommonPuddleLiquid') -> Union[PuddleLiquid, None]:
"""convert_to_vanilla(value) Convert a value into the vanilla PuddleLiquid enum. :param value: An instance of a CommonPuddleLiquid :... | stack_v2_sparse_classes_36k_train_020769 | 3,607 | permissive | [
{
"docstring": "convert_to_vanilla(value) Convert a value into the vanilla PuddleLiquid enum. :param value: An instance of a CommonPuddleLiquid :type value: CommonPuddleLiquid :return: The specified value translated to a PuddleLiquid or INVALID if the value could not be translated. :rtype: Union[PuddleLiquid, N... | 2 | stack_v2_sparse_classes_30k_train_005182 | Implement the Python class `CommonPuddleLiquid` described below.
Class description:
Various types of liquids a puddle may have.
Method signatures and docstrings:
- def convert_to_vanilla(value: 'CommonPuddleLiquid') -> Union[PuddleLiquid, None]: convert_to_vanilla(value) Convert a value into the vanilla PuddleLiquid ... | Implement the Python class `CommonPuddleLiquid` described below.
Class description:
Various types of liquids a puddle may have.
Method signatures and docstrings:
- def convert_to_vanilla(value: 'CommonPuddleLiquid') -> Union[PuddleLiquid, None]: convert_to_vanilla(value) Convert a value into the vanilla PuddleLiquid ... | 58e7beb30b9c818b294d35abd2436a0192cd3e82 | <|skeleton|>
class CommonPuddleLiquid:
"""Various types of liquids a puddle may have."""
def convert_to_vanilla(value: 'CommonPuddleLiquid') -> Union[PuddleLiquid, None]:
"""convert_to_vanilla(value) Convert a value into the vanilla PuddleLiquid enum. :param value: An instance of a CommonPuddleLiquid :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommonPuddleLiquid:
"""Various types of liquids a puddle may have."""
def convert_to_vanilla(value: 'CommonPuddleLiquid') -> Union[PuddleLiquid, None]:
"""convert_to_vanilla(value) Convert a value into the vanilla PuddleLiquid enum. :param value: An instance of a CommonPuddleLiquid :type value: C... | the_stack_v2_python_sparse | Scripts/sims4communitylib/enums/common_puddle_liquid.py | ColonolNutty/Sims4CommunityLibrary | train | 183 |
3f3fedc0d4facd3f6b20650ffed04ee9a33d24d8 | [
"data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.add_dataStage03QuantificationOtherData(data.data)\ndata.clear_data()",
"data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.update_dataStage03QuantificationOtherData(data.data)\ndata.clear_data()"
] | <|body_start_0|>
data = base_importData()
data.read_csv(filename)
data.format_data()
self.add_dataStage03QuantificationOtherData(data.data)
data.clear_data()
<|end_body_0|>
<|body_start_1|>
data = base_importData()
data.read_csv(filename)
data.format_data... | stage03_quantification_otherData_io | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stage03_quantification_otherData_io:
def import_dataStage03QuantificationOtherData_add(self, filename):
"""table adds"""
<|body_0|>
def import_dataStage03QuantificationOtherData_update(self, filename):
"""table adds"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_020770 | 982 | permissive | [
{
"docstring": "table adds",
"name": "import_dataStage03QuantificationOtherData_add",
"signature": "def import_dataStage03QuantificationOtherData_add(self, filename)"
},
{
"docstring": "table adds",
"name": "import_dataStage03QuantificationOtherData_update",
"signature": "def import_data... | 2 | stack_v2_sparse_classes_30k_train_005562 | Implement the Python class `stage03_quantification_otherData_io` described below.
Class description:
Implement the stage03_quantification_otherData_io class.
Method signatures and docstrings:
- def import_dataStage03QuantificationOtherData_add(self, filename): table adds
- def import_dataStage03QuantificationOtherDat... | Implement the Python class `stage03_quantification_otherData_io` described below.
Class description:
Implement the stage03_quantification_otherData_io class.
Method signatures and docstrings:
- def import_dataStage03QuantificationOtherData_add(self, filename): table adds
- def import_dataStage03QuantificationOtherDat... | 0eeed0191f952ea0226ab8bbc234a30638fb2f9f | <|skeleton|>
class stage03_quantification_otherData_io:
def import_dataStage03QuantificationOtherData_add(self, filename):
"""table adds"""
<|body_0|>
def import_dataStage03QuantificationOtherData_update(self, filename):
"""table adds"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class stage03_quantification_otherData_io:
def import_dataStage03QuantificationOtherData_add(self, filename):
"""table adds"""
data = base_importData()
data.read_csv(filename)
data.format_data()
self.add_dataStage03QuantificationOtherData(data.data)
data.clear_data()
... | the_stack_v2_python_sparse | SBaaS_thermodynamics/stage03_quantification_otherData_io.py | dmccloskey/SBaaS_thermodynamics | train | 0 | |
948477a8e4014073373895e877247c300ed3f03c | [
"super(ConvolutionalBoxPredictor, self).__init__(num_classes, box_code_size)\nself._num_predictions_list = num_predictions_list\nself._conv_hyperparams_fn = conv_hyperparams_fn\nself._kernel_size = kernel_size\nself._use_depthwise = use_depthwise",
"box_encoding_predictions_list = []\nclass_score_predictions_list... | <|body_start_0|>
super(ConvolutionalBoxPredictor, self).__init__(num_classes, box_code_size)
self._num_predictions_list = num_predictions_list
self._conv_hyperparams_fn = conv_hyperparams_fn
self._kernel_size = kernel_size
self._use_depthwise = use_depthwise
<|end_body_0|>
<|bod... | Convolutional box predictor. Note that this subclass of BoxPredictor predicts **ONE** set of box location encodings shared by **ALL** object classes as opposed to making predictions separately for **EACH** object class. | ConvolutionalBoxPredictor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvolutionalBoxPredictor:
"""Convolutional box predictor. Note that this subclass of BoxPredictor predicts **ONE** set of box location encodings shared by **ALL** object classes as opposed to making predictions separately for **EACH** object class."""
def __init__(self, num_classes, num_pre... | stack_v2_sparse_classes_36k_train_020771 | 12,500 | no_license | [
{
"docstring": "Constructor. Args: num_classes: int scalar, num of classes. num_predictions_list: a list of ints, num of anchor boxes per feature map cell. conv_hyperparams_fn: a callable that, when called, creates a dict holding arguments to `slim.arg_scope`. kernel_size: int scalar or int 2-tuple, kernel size... | 2 | stack_v2_sparse_classes_30k_val_000962 | Implement the Python class `ConvolutionalBoxPredictor` described below.
Class description:
Convolutional box predictor. Note that this subclass of BoxPredictor predicts **ONE** set of box location encodings shared by **ALL** object classes as opposed to making predictions separately for **EACH** object class.
Method ... | Implement the Python class `ConvolutionalBoxPredictor` described below.
Class description:
Convolutional box predictor. Note that this subclass of BoxPredictor predicts **ONE** set of box location encodings shared by **ALL** object classes as opposed to making predictions separately for **EACH** object class.
Method ... | 5a53e02c690632bcf140d1b17327959609aab395 | <|skeleton|>
class ConvolutionalBoxPredictor:
"""Convolutional box predictor. Note that this subclass of BoxPredictor predicts **ONE** set of box location encodings shared by **ALL** object classes as opposed to making predictions separately for **EACH** object class."""
def __init__(self, num_classes, num_pre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvolutionalBoxPredictor:
"""Convolutional box predictor. Note that this subclass of BoxPredictor predicts **ONE** set of box location encodings shared by **ALL** object classes as opposed to making predictions separately for **EACH** object class."""
def __init__(self, num_classes, num_predictions_list... | the_stack_v2_python_sparse | core/box_predictors.py | chao-ji/tf-detection | train | 2 |
9c3335af703594a0e0255ebc42f3be313636e3af | [
"super(TrDecoderBlock, self).__init__()\nself.self_attn = nn.MultiheadAttention(n_features, n_attn_heads)\nself.ln1 = nn.LayerNorm(n_features)\nself.dropout1 = nn.Dropout(dropout_prob)\nself.cross_attn = nn.MultiheadAttention(n_features, n_attn_heads)\nself.ln2 = nn.LayerNorm(n_features)\nself.dropout2 = nn.Dropout... | <|body_start_0|>
super(TrDecoderBlock, self).__init__()
self.self_attn = nn.MultiheadAttention(n_features, n_attn_heads)
self.ln1 = nn.LayerNorm(n_features)
self.dropout1 = nn.Dropout(dropout_prob)
self.cross_attn = nn.MultiheadAttention(n_features, n_attn_heads)
self.ln2... | TrDecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrDecoderBlock:
def __init__(self, n_features, n_attn_heads=10, n_hidden=64, dropout_prob=0.1):
""":param n_features: Number of input and output features. :param n_attn_heads: Number of attention heads in the Multi-Head Attention. :param n_hidden: Number of hidden units in the Feedforwar... | stack_v2_sparse_classes_36k_train_020772 | 7,645 | no_license | [
{
"docstring": ":param n_features: Number of input and output features. :param n_attn_heads: Number of attention heads in the Multi-Head Attention. :param n_hidden: Number of hidden units in the Feedforward (MLP) block. :param dropout_prob: Dropout rate after the first layer of the MLP and in three places on th... | 2 | null | Implement the Python class `TrDecoderBlock` described below.
Class description:
Implement the TrDecoderBlock class.
Method signatures and docstrings:
- def __init__(self, n_features, n_attn_heads=10, n_hidden=64, dropout_prob=0.1): :param n_features: Number of input and output features. :param n_attn_heads: Number of... | Implement the Python class `TrDecoderBlock` described below.
Class description:
Implement the TrDecoderBlock class.
Method signatures and docstrings:
- def __init__(self, n_features, n_attn_heads=10, n_hidden=64, dropout_prob=0.1): :param n_features: Number of input and output features. :param n_attn_heads: Number of... | 21d3013f0422f5df3f709f26258c2f4f45f2d8bd | <|skeleton|>
class TrDecoderBlock:
def __init__(self, n_features, n_attn_heads=10, n_hidden=64, dropout_prob=0.1):
""":param n_features: Number of input and output features. :param n_attn_heads: Number of attention heads in the Multi-Head Attention. :param n_hidden: Number of hidden units in the Feedforwar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrDecoderBlock:
def __init__(self, n_features, n_attn_heads=10, n_hidden=64, dropout_prob=0.1):
""":param n_features: Number of input and output features. :param n_attn_heads: Number of attention heads in the Multi-Head Attention. :param n_hidden: Number of hidden units in the Feedforward (MLP) block.... | the_stack_v2_python_sparse | legacy_code/modules/generative_lsdvae/blocks.py | AndrewSukhobok95/discrete_latents_for_text_to_image_gen | train | 0 | |
4739562cfbe313b29f1971bf8f71f791f5258dbd | [
"path = self.request.get('path', None)\nif path is None:\n return []\nclassModule = findAPIDocumentationRoot(self.context)['Code']\nremoveSecurityProxy(classModule).setup()\nfound = [p for p in classRegistry if path in p]\nresults = []\nfor p in found:\n klass = traverse(classModule, p.replace('.', '/'))\n ... | <|body_start_0|>
path = self.request.get('path', None)
if path is None:
return []
classModule = findAPIDocumentationRoot(self.context)['Code']
removeSecurityProxy(classModule).setup()
found = [p for p in classRegistry if path in p]
results = []
for p i... | Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation. | Menu | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Menu:
"""Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation."""
def findClasses(self):
"""Find the classes that match a partial path. Examples:: Setup the view. >>> from zope.app.... | stack_v2_sparse_classes_36k_train_020773 | 4,537 | permissive | [
{
"docstring": "Find the classes that match a partial path. Examples:: Setup the view. >>> from zope.app.apidoc.codemodule.browser.menu import Menu >>> from zope.publisher.browser import TestRequest >>> menu = Menu() (In the following line flake8 sees a NameError, but the test passes.) >>> menu.context = apidoc... | 2 | stack_v2_sparse_classes_30k_train_012354 | Implement the Python class `Menu` described below.
Class description:
Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation.
Method signatures and docstrings:
- def findClasses(self): Find the classes that match a pa... | Implement the Python class `Menu` described below.
Class description:
Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation.
Method signatures and docstrings:
- def findClasses(self): Find the classes that match a pa... | ea7814831c279422b982c553866ceac6b442de68 | <|skeleton|>
class Menu:
"""Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation."""
def findClasses(self):
"""Find the classes that match a partial path. Examples:: Setup the view. >>> from zope.app.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Menu:
"""Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation."""
def findClasses(self):
"""Find the classes that match a partial path. Examples:: Setup the view. >>> from zope.app.apidoc.codemo... | the_stack_v2_python_sparse | src/zope/app/apidoc/codemodule/browser/menu.py | zopefoundation/zope.app.apidoc | train | 0 |
4a3ab11f6ef5670d0e547aa55cc4e14253c82da7 | [
"if not intervals:\n return [newInterval]\nelif not newInterval:\n return intervals\nif newInterval[0] <= intervals[0][0]:\n intervals.insert(0, newInterval)\nelif newInterval[0] >= intervals[-1][0]:\n intervals.append(newInterval)\nans = []\nfor interval in intervals:\n if newInterval[0] < interval[... | <|body_start_0|>
if not intervals:
return [newInterval]
elif not newInterval:
return intervals
if newInterval[0] <= intervals[0][0]:
intervals.insert(0, newInterval)
elif newInterval[0] >= intervals[-1][0]:
intervals.append(newInterval)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def insert__(self, intervals, newInterval):
""":type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]]"""
<|body_0|>
def insert(self, intervals, newInterval):
""":type intervals: List[List[int]] :type newInterval: List[int] :rt... | stack_v2_sparse_classes_36k_train_020774 | 2,188 | no_license | [
{
"docstring": ":type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]]",
"name": "insert__",
"signature": "def insert__(self, intervals, newInterval)"
},
{
"docstring": ":type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]]",
"na... | 2 | stack_v2_sparse_classes_30k_train_017677 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insert__(self, intervals, newInterval): :type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]]
- def insert(self, intervals, newInterval): :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insert__(self, intervals, newInterval): :type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]]
- def insert(self, intervals, newInterval): :typ... | b5c25f976866eefec33b96c638a4c5e127319e74 | <|skeleton|>
class Solution:
def insert__(self, intervals, newInterval):
""":type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]]"""
<|body_0|>
def insert(self, intervals, newInterval):
""":type intervals: List[List[int]] :type newInterval: List[int] :rt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def insert__(self, intervals, newInterval):
""":type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]]"""
if not intervals:
return [newInterval]
elif not newInterval:
return intervals
if newInterval[0] <= intervals... | the_stack_v2_python_sparse | Python/057_Insert Interval.py | Eddie02582/Leetcode | train | 1 | |
556b4c969e149baab351b7afb7be9b04abe8c66e | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ChatMessageMention()",
"from .chat_message_mentioned_identity_set import ChatMessageMentionedIdentitySet\nfrom .chat_message_mentioned_identity_set import ChatMessageMentionedIdentitySet\nfields: Dict[str, Callable[[Any], None]] = {'id... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ChatMessageMention()
<|end_body_0|>
<|body_start_1|>
from .chat_message_mentioned_identity_set import ChatMessageMentionedIdentitySet
from .chat_message_mentioned_identity_set import Cha... | ChatMessageMention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChatMessageMention:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ChatMessageMention:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_36k_train_020775 | 3,443 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ChatMessageMention",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_train_001523 | Implement the Python class `ChatMessageMention` described below.
Class description:
Implement the ChatMessageMention class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ChatMessageMention: Creates a new instance of the appropriate class based on disc... | Implement the Python class `ChatMessageMention` described below.
Class description:
Implement the ChatMessageMention class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ChatMessageMention: Creates a new instance of the appropriate class based on disc... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ChatMessageMention:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ChatMessageMention:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChatMessageMention:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ChatMessageMention:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Ch... | the_stack_v2_python_sparse | msgraph/generated/models/chat_message_mention.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
0cec5c6ceb1df809854e5dd36576a5b0c1e6acc7 | [
"super(COMACriticNetwork, self).__init__()\nself.action_shape = action_shape\nself.act = nn.ReLU()\nself.mlp = nn.Sequential(MLP(input_size, hidden_size, hidden_size, 2, activation=self.act), nn.Linear(hidden_size, action_shape))",
"x = self._preprocess_data(data)\nq = self.mlp(x)\nreturn {'q_value': q}",
"t_si... | <|body_start_0|>
super(COMACriticNetwork, self).__init__()
self.action_shape = action_shape
self.act = nn.ReLU()
self.mlp = nn.Sequential(MLP(input_size, hidden_size, hidden_size, 2, activation=self.act), nn.Linear(hidden_size, action_shape))
<|end_body_0|>
<|body_start_1|>
x = ... | Overview: Centralized critic network in COMA Interface: __init__, forward | COMACriticNetwork | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class COMACriticNetwork:
"""Overview: Centralized critic network in COMA Interface: __init__, forward"""
def __init__(self, input_size: int, action_shape: int, hidden_size: int=128):
"""Overview: initialize COMA critic network Arguments: - input_size (:obj:`int`): the size of input global ... | stack_v2_sparse_classes_36k_train_020776 | 7,790 | permissive | [
{
"docstring": "Overview: initialize COMA critic network Arguments: - input_size (:obj:`int`): the size of input global observation - action_shape (:obj:`int`): the dimension of action shape - hidden_size_list (:obj:`list`): the list of hidden size, default to 128",
"name": "__init__",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_013358 | Implement the Python class `COMACriticNetwork` described below.
Class description:
Overview: Centralized critic network in COMA Interface: __init__, forward
Method signatures and docstrings:
- def __init__(self, input_size: int, action_shape: int, hidden_size: int=128): Overview: initialize COMA critic network Argume... | Implement the Python class `COMACriticNetwork` described below.
Class description:
Overview: Centralized critic network in COMA Interface: __init__, forward
Method signatures and docstrings:
- def __init__(self, input_size: int, action_shape: int, hidden_size: int=128): Overview: initialize COMA critic network Argume... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class COMACriticNetwork:
"""Overview: Centralized critic network in COMA Interface: __init__, forward"""
def __init__(self, input_size: int, action_shape: int, hidden_size: int=128):
"""Overview: initialize COMA critic network Arguments: - input_size (:obj:`int`): the size of input global ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class COMACriticNetwork:
"""Overview: Centralized critic network in COMA Interface: __init__, forward"""
def __init__(self, input_size: int, action_shape: int, hidden_size: int=128):
"""Overview: initialize COMA critic network Arguments: - input_size (:obj:`int`): the size of input global observation -... | the_stack_v2_python_sparse | ding/model/template/coma.py | shengxuesun/DI-engine | train | 1 |
dbcf6a6159316c123dc8d5560b61313ece1ade42 | [
"idx = 1\nrecord = []\nres = []\nself.dfs(n, k, idx, record, res)\nreturn res",
"for i in range(idx, n + 1):\n record.append(i)\n if len(record) == k:\n copy_record = record.copy()\n res.append(copy_record)\n else:\n idx += 1\n self.dfs(n, k, idx, record, res)\n record.pop(... | <|body_start_0|>
idx = 1
record = []
res = []
self.dfs(n, k, idx, record, res)
return res
<|end_body_0|>
<|body_start_1|>
for i in range(idx, n + 1):
record.append(i)
if len(record) == k:
copy_record = record.copy()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combine(self, n, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
<|body_0|>
def dfs(self, n, k, idx=1, record=[], res=[]):
""":type k: int :type n: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_020777 | 753 | no_license | [
{
"docstring": ":type n: int :type k: int :rtype: List[List[int]]",
"name": "combine",
"signature": "def combine(self, n, k)"
},
{
"docstring": ":type k: int :type n: int :rtype: List[List[int]]",
"name": "dfs",
"signature": "def dfs(self, n, k, idx=1, record=[], res=[])"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combine(self, n, k): :type n: int :type k: int :rtype: List[List[int]]
- def dfs(self, n, k, idx=1, record=[], res=[]): :type k: int :type n: int :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combine(self, n, k): :type n: int :type k: int :rtype: List[List[int]]
- def dfs(self, n, k, idx=1, record=[], res=[]): :type k: int :type n: int :rtype: List[List[int]]
<|s... | 9bd2d706f014ce84356ba38fc7801da0285a91d3 | <|skeleton|>
class Solution:
def combine(self, n, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
<|body_0|>
def dfs(self, n, k, idx=1, record=[], res=[]):
""":type k: int :type n: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combine(self, n, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
idx = 1
record = []
res = []
self.dfs(n, k, idx, record, res)
return res
def dfs(self, n, k, idx=1, record=[], res=[]):
""":type k: int :type n: int :rtype: L... | the_stack_v2_python_sparse | leetcode/combine-77.py | pittcat/Algorithm_Practice | train | 0 | |
f21f96b886b9d3e88b5208f2e85d54038f77a5aa | [
"for filename in glob.glob(USERVAR_GLOB):\n if filename in EXCLUDES:\n continue\n try:\n with open(filename, 'r') as f:\n data = yaml.load(f.read())\n if isinstance(data, dict):\n yield data\n except Exception:\n pass",
"for ex in EXCLUDES_CONTAIN... | <|body_start_0|>
for filename in glob.glob(USERVAR_GLOB):
if filename in EXCLUDES:
continue
try:
with open(filename, 'r') as f:
data = yaml.load(f.read())
if isinstance(data, dict):
yield data... | ActionModule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionModule:
def iter_uservar_files(self):
"""Iterate over all user variable files."""
<|body_0|>
def filter_contains(self, key):
"""Filter keys containing exludes. :param key: Name of the key :type key: str :returns: True for keep, false otherwise :rtype: bool"""
... | stack_v2_sparse_classes_36k_train_020778 | 3,175 | permissive | [
{
"docstring": "Iterate over all user variable files.",
"name": "iter_uservar_files",
"signature": "def iter_uservar_files(self)"
},
{
"docstring": "Filter keys containing exludes. :param key: Name of the key :type key: str :returns: True for keep, false otherwise :rtype: bool",
"name": "fil... | 6 | stack_v2_sparse_classes_30k_train_001121 | Implement the Python class `ActionModule` described below.
Class description:
Implement the ActionModule class.
Method signatures and docstrings:
- def iter_uservar_files(self): Iterate over all user variable files.
- def filter_contains(self, key): Filter keys containing exludes. :param key: Name of the key :type ke... | Implement the Python class `ActionModule` described below.
Class description:
Implement the ActionModule class.
Method signatures and docstrings:
- def iter_uservar_files(self): Iterate over all user variable files.
- def filter_contains(self, key): Filter keys containing exludes. :param key: Name of the key :type ke... | aaab76706c8268d3ff3e87c275baee9dd4714314 | <|skeleton|>
class ActionModule:
def iter_uservar_files(self):
"""Iterate over all user variable files."""
<|body_0|>
def filter_contains(self, key):
"""Filter keys containing exludes. :param key: Name of the key :type key: str :returns: True for keep, false otherwise :rtype: bool"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionModule:
def iter_uservar_files(self):
"""Iterate over all user variable files."""
for filename in glob.glob(USERVAR_GLOB):
if filename in EXCLUDES:
continue
try:
with open(filename, 'r') as f:
data = yaml.load(f.... | the_stack_v2_python_sparse | collection/action_plugins/uservars_snitch.py | rcbops/FleetDeploymentReporting | train | 1 | |
8f02b1a1282199fd012756dfbc111afa1a50d0cb | [
"number = self.validate_number(number)\nif number == 1:\n bottom = 0\n top = self.per_page - self.delta\nelse:\n bottom = (number - 1) * self.per_page - self.delta\n top = bottom + self.per_page\nif top + self.orphans >= self.count:\n top = self.count\nreturn Page(self.object_list[bottom:top], number... | <|body_start_0|>
number = self.validate_number(number)
if number == 1:
bottom = 0
top = self.per_page - self.delta
else:
bottom = (number - 1) * self.per_page - self.delta
top = bottom + self.per_page
if top + self.orphans >= self.count:
... | DeltaFirstPagePaginator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeltaFirstPagePaginator:
def page(self, number):
"""Returns first page with `per_page` - `delta` entries."""
<|body_0|>
def num_pages(self):
"""Return the total number of pages. Add delta elements to the count to get all pages."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_020779 | 1,054 | no_license | [
{
"docstring": "Returns first page with `per_page` - `delta` entries.",
"name": "page",
"signature": "def page(self, number)"
},
{
"docstring": "Return the total number of pages. Add delta elements to the count to get all pages.",
"name": "num_pages",
"signature": "def num_pages(self)"
... | 2 | stack_v2_sparse_classes_30k_test_000450 | Implement the Python class `DeltaFirstPagePaginator` described below.
Class description:
Implement the DeltaFirstPagePaginator class.
Method signatures and docstrings:
- def page(self, number): Returns first page with `per_page` - `delta` entries.
- def num_pages(self): Return the total number of pages. Add delta ele... | Implement the Python class `DeltaFirstPagePaginator` described below.
Class description:
Implement the DeltaFirstPagePaginator class.
Method signatures and docstrings:
- def page(self, number): Returns first page with `per_page` - `delta` entries.
- def num_pages(self): Return the total number of pages. Add delta ele... | e1a019c8fdf5c9ff6a384a45b56bffef128b78c1 | <|skeleton|>
class DeltaFirstPagePaginator:
def page(self, number):
"""Returns first page with `per_page` - `delta` entries."""
<|body_0|>
def num_pages(self):
"""Return the total number of pages. Add delta elements to the count to get all pages."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeltaFirstPagePaginator:
def page(self, number):
"""Returns first page with `per_page` - `delta` entries."""
number = self.validate_number(number)
if number == 1:
bottom = 0
top = self.per_page - self.delta
else:
bottom = (number - 1) * self.... | the_stack_v2_python_sparse | apps/ideas/paginators.py | liqd/a4-advocate-europe | train | 8 | |
43c6fb8d8f3b0b77a28381237cff91cae42ef6b8 | [
"self.img_u = dataset_loader\nif mode == 'GAP_CAM':\n self.model = Sequential(applications.VGG16(weights='imagenet', include_top=False).layers)\n self.model.add(Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='CAM'))\n self.model.add(GlobalAveragePooling2D(name='GAP'))\n self.model.... | <|body_start_0|>
self.img_u = dataset_loader
if mode == 'GAP_CAM':
self.model = Sequential(applications.VGG16(weights='imagenet', include_top=False).layers)
self.model.add(Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='CAM'))
self.model.add(Glob... | VGG16 fine tuned. | VGG16FineTuned | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGG16FineTuned:
"""VGG16 fine tuned."""
def __init__(self, dataset_loader: DatasetLoader, mode: str):
"""Create and compile the custom VGG16 model. :param dataset_loader: The data set loader with the model will train."""
<|body_0|>
def train(self, nb_epochs, weights_in=N... | stack_v2_sparse_classes_36k_train_020780 | 2,317 | no_license | [
{
"docstring": "Create and compile the custom VGG16 model. :param dataset_loader: The data set loader with the model will train.",
"name": "__init__",
"signature": "def __init__(self, dataset_loader: DatasetLoader, mode: str)"
},
{
"docstring": "Trains the custom VGG16 model. :param weights_in: ... | 2 | stack_v2_sparse_classes_30k_train_020783 | Implement the Python class `VGG16FineTuned` described below.
Class description:
VGG16 fine tuned.
Method signatures and docstrings:
- def __init__(self, dataset_loader: DatasetLoader, mode: str): Create and compile the custom VGG16 model. :param dataset_loader: The data set loader with the model will train.
- def tra... | Implement the Python class `VGG16FineTuned` described below.
Class description:
VGG16 fine tuned.
Method signatures and docstrings:
- def __init__(self, dataset_loader: DatasetLoader, mode: str): Create and compile the custom VGG16 model. :param dataset_loader: The data set loader with the model will train.
- def tra... | 59b979521c66ad7509295c3cbb2696e3b38ebbd9 | <|skeleton|>
class VGG16FineTuned:
"""VGG16 fine tuned."""
def __init__(self, dataset_loader: DatasetLoader, mode: str):
"""Create and compile the custom VGG16 model. :param dataset_loader: The data set loader with the model will train."""
<|body_0|>
def train(self, nb_epochs, weights_in=N... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VGG16FineTuned:
"""VGG16 fine tuned."""
def __init__(self, dataset_loader: DatasetLoader, mode: str):
"""Create and compile the custom VGG16 model. :param dataset_loader: The data set loader with the model will train."""
self.img_u = dataset_loader
if mode == 'GAP_CAM':
... | the_stack_v2_python_sparse | keras/VGG16_ft.py | ioannisNoukakis/Bachelor-2017 | train | 0 |
e125e655a8febcb816ca069eaaa3bbd2076ae4e7 | [
"super(Conv1dStatic, self).__init__()\nself.in_channels = in_channels\nself.out_channels = out_channels\nself.conv = nn.Conv1d(4 * in_channels, 4 * out_channels, kernel_size, stride, padding, dilation, 4 * groups, bias)",
"batch_size = x.shape[0]\nx = x.view(batch_size, 4 * self.in_channels, -1)\nx = self.conv(x)... | <|body_start_0|>
super(Conv1dStatic, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.conv = nn.Conv1d(4 * in_channels, 4 * out_channels, kernel_size, stride, padding, dilation, 4 * groups, bias)
<|end_body_0|>
<|body_start_1|>
batch_size = x... | 1D convolution with an independent kernel for each instrument | Conv1dStatic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv1dStatic:
"""1D convolution with an independent kernel for each instrument"""
def __init__(self, _, __, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False):
"""Arguments: in_channels {int} -- Number of channels of the input out_channels ... | stack_v2_sparse_classes_36k_train_020781 | 37,269 | no_license | [
{
"docstring": "Arguments: in_channels {int} -- Number of channels of the input out_channels {int} -- Number of channels of the output kernel_size {int} -- Kernel size of the convolution Keyword Arguments: stride {int} -- Stride of the convolution (default: {1}) padding {int} -- Padding of the convolution (defa... | 2 | stack_v2_sparse_classes_30k_train_010865 | Implement the Python class `Conv1dStatic` described below.
Class description:
1D convolution with an independent kernel for each instrument
Method signatures and docstrings:
- def __init__(self, _, __, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False): Arguments: in_channe... | Implement the Python class `Conv1dStatic` described below.
Class description:
1D convolution with an independent kernel for each instrument
Method signatures and docstrings:
- def __init__(self, _, __, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False): Arguments: in_channe... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Conv1dStatic:
"""1D convolution with an independent kernel for each instrument"""
def __init__(self, _, __, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False):
"""Arguments: in_channels {int} -- Number of channels of the input out_channels ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conv1dStatic:
"""1D convolution with an independent kernel for each instrument"""
def __init__(self, _, __, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False):
"""Arguments: in_channels {int} -- Number of channels of the input out_channels {int} -- Numb... | the_stack_v2_python_sparse | generated/test_pfnet_research_meta_tasnet.py | jansel/pytorch-jit-paritybench | train | 35 |
d9a2e576989f86a5732667a6833a9d8421b0b44f | [
"cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), 'plugins'))\ncommands = []\nfor filename in os.listdir(cmd_folder):\n if filename.endswith('.py') and (not filename.startswith('__')):\n commands.append(filename[:-3])\ncommands.sort()\nreturn commands",
"try:\n mod = __import__('{... | <|body_start_0|>
cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), 'plugins'))
commands = []
for filename in os.listdir(cmd_folder):
if filename.endswith('.py') and (not filename.startswith('__')):
commands.append(filename[:-3])
commands.sor... | The Home Assistant Command-line. | HomeAssistantCli | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HomeAssistantCli:
"""The Home Assistant Command-line."""
def list_commands(self, ctx: Context) -> List[str]:
"""List all command available as plugin."""
<|body_0|>
def get_command(self, ctx: Context, cmd_name: str) -> Optional[Union[Group, Command]]:
"""Import th... | stack_v2_sparse_classes_36k_train_020782 | 6,604 | permissive | [
{
"docstring": "List all command available as plugin.",
"name": "list_commands",
"signature": "def list_commands(self, ctx: Context) -> List[str]"
},
{
"docstring": "Import the commands of the plugins.",
"name": "get_command",
"signature": "def get_command(self, ctx: Context, cmd_name: s... | 2 | stack_v2_sparse_classes_30k_train_000846 | Implement the Python class `HomeAssistantCli` described below.
Class description:
The Home Assistant Command-line.
Method signatures and docstrings:
- def list_commands(self, ctx: Context) -> List[str]: List all command available as plugin.
- def get_command(self, ctx: Context, cmd_name: str) -> Optional[Union[Group,... | Implement the Python class `HomeAssistantCli` described below.
Class description:
The Home Assistant Command-line.
Method signatures and docstrings:
- def list_commands(self, ctx: Context) -> List[str]: List all command available as plugin.
- def get_command(self, ctx: Context, cmd_name: str) -> Optional[Union[Group,... | e9ab228a6fbc50aabe2251cbefbecaabc48efc0b | <|skeleton|>
class HomeAssistantCli:
"""The Home Assistant Command-line."""
def list_commands(self, ctx: Context) -> List[str]:
"""List all command available as plugin."""
<|body_0|>
def get_command(self, ctx: Context, cmd_name: str) -> Optional[Union[Group, Command]]:
"""Import th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HomeAssistantCli:
"""The Home Assistant Command-line."""
def list_commands(self, ctx: Context) -> List[str]:
"""List all command available as plugin."""
cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), 'plugins'))
commands = []
for filename in os.listdi... | the_stack_v2_python_sparse | homeassistant_cli/cli.py | home-assistant-ecosystem/home-assistant-cli | train | 171 |
e5165bc6d8806030e8083bd2f0f19926188b4369 | [
"self.letters = []\nself.nums = []\nidx = 0\nwhile idx < len(compressedString):\n if compressedString[idx].isalpha():\n self.letters.append(compressedString[idx])\n idx += 1\n else:\n tmp = ''\n while idx < len(compressedString) and compressedString[idx].isdigit():\n tmp... | <|body_start_0|>
self.letters = []
self.nums = []
idx = 0
while idx < len(compressedString):
if compressedString[idx].isalpha():
self.letters.append(compressedString[idx])
idx += 1
else:
tmp = ''
whil... | StringIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_36k_train_020783 | 1,632 | no_license | [
{
"docstring": ":type compressedString: str",
"name": "__init__",
"signature": "def __init__(self, compressedString)"
},
{
"docstring": ":rtype: str",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",
"signature": "def hasN... | 3 | stack_v2_sparse_classes_30k_train_000933 | Implement the Python class `StringIterator` described below.
Class description:
Implement the StringIterator class.
Method signatures and docstrings:
- def __init__(self, compressedString): :type compressedString: str
- def next(self): :rtype: str
- def hasNext(self): :rtype: bool | Implement the Python class `StringIterator` described below.
Class description:
Implement the StringIterator class.
Method signatures and docstrings:
- def __init__(self, compressedString): :type compressedString: str
- def next(self): :rtype: str
- def hasNext(self): :rtype: bool
<|skeleton|>
class StringIterator:
... | ee79d3437cf47b26a4bca0ec798dc54d7b623453 | <|skeleton|>
class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
self.letters = []
self.nums = []
idx = 0
while idx < len(compressedString):
if compressedString[idx].isalpha():
self.letters.append(compressedString[idx])... | the_stack_v2_python_sparse | Algorithm/Python/604. Design Compressed String Iterator.py | WuLC/LeetCode | train | 29 | |
8e51b0b6bfae44443262781e402c34f42b9914d2 | [
"template = db.Template.find_one(template_name=template_name)\nif not template:\n return self.make_response('No such template found', HTTP.NOT_FOUND)\nreturn self.make_response({'template': template})",
"self.reqparse.add_argument('template', type=str, required=True)\nargs = self.reqparse.parse_args()\ntemplat... | <|body_start_0|>
template = db.Template.find_one(template_name=template_name)
if not template:
return self.make_response('No such template found', HTTP.NOT_FOUND)
return self.make_response({'template': template})
<|end_body_0|>
<|body_start_1|>
self.reqparse.add_argument('te... | TemplateGet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateGet:
def get(self, template_name):
"""Get a specific template"""
<|body_0|>
def put(self, template_name):
"""Update a template"""
<|body_1|>
def delete(self, template_name):
"""Delete a template"""
<|body_2|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_020784 | 4,164 | permissive | [
{
"docstring": "Get a specific template",
"name": "get",
"signature": "def get(self, template_name)"
},
{
"docstring": "Update a template",
"name": "put",
"signature": "def put(self, template_name)"
},
{
"docstring": "Delete a template",
"name": "delete",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_010520 | Implement the Python class `TemplateGet` described below.
Class description:
Implement the TemplateGet class.
Method signatures and docstrings:
- def get(self, template_name): Get a specific template
- def put(self, template_name): Update a template
- def delete(self, template_name): Delete a template | Implement the Python class `TemplateGet` described below.
Class description:
Implement the TemplateGet class.
Method signatures and docstrings:
- def get(self, template_name): Get a specific template
- def put(self, template_name): Update a template
- def delete(self, template_name): Delete a template
<|skeleton|>
c... | 29a26c705381fdba3538b4efedb25b9e09b387ed | <|skeleton|>
class TemplateGet:
def get(self, template_name):
"""Get a specific template"""
<|body_0|>
def put(self, template_name):
"""Update a template"""
<|body_1|>
def delete(self, template_name):
"""Delete a template"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemplateGet:
def get(self, template_name):
"""Get a specific template"""
template = db.Template.find_one(template_name=template_name)
if not template:
return self.make_response('No such template found', HTTP.NOT_FOUND)
return self.make_response({'template': template... | the_stack_v2_python_sparse | backend/cloud_inquisitor/plugins/views/templates.py | RiotGames/cloud-inquisitor | train | 468 | |
1045cff0cce963fa728dd835717731fa7d764b9d | [
"new_list = []\nfor i in matrix:\n for j in i:\n new_list.append(j)\nprint(new_list)\nnew_list.sort()\nreturn new_list[k - 1]",
"n = len(matrix)\n\ndef check(mid):\n i, j = (n - 1, 0)\n num = 0\n while j < n and i >= 0:\n if matrix[i][j] <= mid:\n num += i + 1\n j +... | <|body_start_0|>
new_list = []
for i in matrix:
for j in i:
new_list.append(j)
print(new_list)
new_list.sort()
return new_list[k - 1]
<|end_body_0|>
<|body_start_1|>
n = len(matrix)
def check(mid):
i, j = (n - 1, 0)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""将二维矩阵变成一维矩阵之后,从小到大排序好 取第k-1即可。 :param matrix: :param k: :return:"""
<|body_0|>
def kthSmallest2(self, matrix: List[List[int]], k: int) -> int:
"""二分法 完全利用有序矩阵的两个特性 :param matrix: :param k: :r... | stack_v2_sparse_classes_36k_train_020785 | 2,021 | no_license | [
{
"docstring": "将二维矩阵变成一维矩阵之后,从小到大排序好 取第k-1即可。 :param matrix: :param k: :return:",
"name": "kthSmallest",
"signature": "def kthSmallest(self, matrix: List[List[int]], k: int) -> int"
},
{
"docstring": "二分法 完全利用有序矩阵的两个特性 :param matrix: :param k: :return:",
"name": "kthSmallest2",
"signatu... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, matrix: List[List[int]], k: int) -> int: 将二维矩阵变成一维矩阵之后,从小到大排序好 取第k-1即可。 :param matrix: :param k: :return:
- def kthSmallest2(self, matrix: List[List[int]], ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, matrix: List[List[int]], k: int) -> int: 将二维矩阵变成一维矩阵之后,从小到大排序好 取第k-1即可。 :param matrix: :param k: :return:
- def kthSmallest2(self, matrix: List[List[int]], ... | 578cacff5851c5c2522981693c34e3c318002d30 | <|skeleton|>
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""将二维矩阵变成一维矩阵之后,从小到大排序好 取第k-1即可。 :param matrix: :param k: :return:"""
<|body_0|>
def kthSmallest2(self, matrix: List[List[int]], k: int) -> int:
"""二分法 完全利用有序矩阵的两个特性 :param matrix: :param k: :r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""将二维矩阵变成一维矩阵之后,从小到大排序好 取第k-1即可。 :param matrix: :param k: :return:"""
new_list = []
for i in matrix:
for j in i:
new_list.append(j)
print(new_list)
new_list.sort()
... | the_stack_v2_python_sparse | 有序矩阵中第K小的元素.py | cjrzs/MyLeetCode | train | 8 | |
852d86266232703c304e5b8618d514285eb59aad | [
"assert scope_type in VALID_FILTER_SCOPES, 'Invalid scope type.'\nself.sample_id_set = set(sample_ids)\nself.scope_type = scope_type",
"if self.scope_type == FILTER_SCOPE__ALL:\n intersection = samples_passing_for_variant & self.sample_id_set\n return intersection == self.sample_id_set\nelif self.scope_type... | <|body_start_0|>
assert scope_type in VALID_FILTER_SCOPES, 'Invalid scope type.'
self.sample_id_set = set(sample_ids)
self.scope_type = scope_type
<|end_body_0|>
<|body_start_1|>
if self.scope_type == FILTER_SCOPE__ALL:
intersection = samples_passing_for_variant & self.sampl... | Represents the scope that a filter should be applied over. | FilterScope | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterScope:
"""Represents the scope that a filter should be applied over."""
def __init__(self, scope_type, sample_ids):
"""Args: sample_ids: Set of sample ids. scope_type: A scope in VALID_FILTER_SCOPES."""
<|body_0|>
def do_passing_samples_satisfy_scope(self, samples_... | stack_v2_sparse_classes_36k_train_020786 | 2,031 | permissive | [
{
"docstring": "Args: sample_ids: Set of sample ids. scope_type: A scope in VALID_FILTER_SCOPES.",
"name": "__init__",
"signature": "def __init__(self, scope_type, sample_ids)"
},
{
"docstring": "Returns a Boolean indicating whether the samples satisfy the scope.",
"name": "do_passing_sample... | 3 | stack_v2_sparse_classes_30k_train_008689 | Implement the Python class `FilterScope` described below.
Class description:
Represents the scope that a filter should be applied over.
Method signatures and docstrings:
- def __init__(self, scope_type, sample_ids): Args: sample_ids: Set of sample ids. scope_type: A scope in VALID_FILTER_SCOPES.
- def do_passing_samp... | Implement the Python class `FilterScope` described below.
Class description:
Represents the scope that a filter should be applied over.
Method signatures and docstrings:
- def __init__(self, scope_type, sample_ids): Args: sample_ids: Set of sample ids. scope_type: A scope in VALID_FILTER_SCOPES.
- def do_passing_samp... | 898936072a716a799462c113286056690a7723d1 | <|skeleton|>
class FilterScope:
"""Represents the scope that a filter should be applied over."""
def __init__(self, scope_type, sample_ids):
"""Args: sample_ids: Set of sample ids. scope_type: A scope in VALID_FILTER_SCOPES."""
<|body_0|>
def do_passing_samples_satisfy_scope(self, samples_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilterScope:
"""Represents the scope that a filter should be applied over."""
def __init__(self, scope_type, sample_ids):
"""Args: sample_ids: Set of sample ids. scope_type: A scope in VALID_FILTER_SCOPES."""
assert scope_type in VALID_FILTER_SCOPES, 'Invalid scope type.'
self.sam... | the_stack_v2_python_sparse | genome_designer/variants/filter_scope.py | RubensZimbres/millstone | train | 1 |
0749002de17f03cf3b1a6a207c0bd0c87cbcdbb9 | [
"raw_config = self.config.to_json()\nraw_config.type = self.config.type\nmap_dict = LossMappingDict()\nself.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_dict.params_mapping_dict).backend_mapping(raw_config)\nself._cls = ClassFactory.get_cls(ClassType.LOSS, self.map_config.type)",
"params = se... | <|body_start_0|>
raw_config = self.config.to_json()
raw_config.type = self.config.type
map_dict = LossMappingDict()
self.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_dict.params_mapping_dict).backend_mapping(raw_config)
self._cls = ClassFactory.get_cls(ClassT... | Register and call loss class. | Loss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Loss:
"""Register and call loss class."""
def __init__(self):
"""Initialize."""
<|body_0|>
def __call__(self):
"""Call loss cls."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
raw_config = self.config.to_json()
raw_config.type = self.co... | stack_v2_sparse_classes_36k_train_020787 | 2,539 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Call loss cls.",
"name": "__call__",
"signature": "def __call__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012228 | Implement the Python class `Loss` described below.
Class description:
Register and call loss class.
Method signatures and docstrings:
- def __init__(self): Initialize.
- def __call__(self): Call loss cls. | Implement the Python class `Loss` described below.
Class description:
Register and call loss class.
Method signatures and docstrings:
- def __init__(self): Initialize.
- def __call__(self): Call loss cls.
<|skeleton|>
class Loss:
"""Register and call loss class."""
def __init__(self):
"""Initialize.... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class Loss:
"""Register and call loss class."""
def __init__(self):
"""Initialize."""
<|body_0|>
def __call__(self):
"""Call loss cls."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Loss:
"""Register and call loss class."""
def __init__(self):
"""Initialize."""
raw_config = self.config.to_json()
raw_config.type = self.config.type
map_dict = LossMappingDict()
self.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_dict.params_map... | the_stack_v2_python_sparse | zeus/modules/loss/loss.py | huawei-noah/xingtian | train | 308 |
d41a3f1992344249a401e655c00163eb2f73ec28 | [
"super().__init__(name=name)\nself._num_layers = num_layers\nself._msg_hidden_size_factor = msg_hidden_size_factor\nself._layer_norm = layer_norm",
"input_node_dim = graph.nodes.shape[-1]\nmsg_hidden_size = input_node_dim * self._msg_hidden_size_factor\nfor _ in range(self._num_layers):\n graph = MLPMessagePas... | <|body_start_0|>
super().__init__(name=name)
self._num_layers = num_layers
self._msg_hidden_size_factor = msg_hidden_size_factor
self._layer_norm = layer_norm
<|end_body_0|>
<|body_start_1|>
input_node_dim = graph.nodes.shape[-1]
msg_hidden_size = input_node_dim * self._... | A simple graph net module, a stack of message passing layers. | SimpleGraphNet | [
"Apache-2.0",
"CC-BY-SA-4.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleGraphNet:
"""A simple graph net module, a stack of message passing layers."""
def __init__(self, num_layers: int, msg_hidden_size_factor: int=2, layer_norm: bool=False, name: Optional[str]=None):
"""Constructor. Args: num_layers: number of message passing layers in the network.... | stack_v2_sparse_classes_36k_train_020788 | 10,075 | permissive | [
{
"docstring": "Constructor. Args: num_layers: number of message passing layers in the network. msg_hidden_size_factor: size of message module hidden sizes as a factor of the input node feature dimensionality. layer_norm: whether to apply layer norm on node updates. name: name of this module.",
"name": "__i... | 2 | null | Implement the Python class `SimpleGraphNet` described below.
Class description:
A simple graph net module, a stack of message passing layers.
Method signatures and docstrings:
- def __init__(self, num_layers: int, msg_hidden_size_factor: int=2, layer_norm: bool=False, name: Optional[str]=None): Constructor. Args: num... | Implement the Python class `SimpleGraphNet` described below.
Class description:
A simple graph net module, a stack of message passing layers.
Method signatures and docstrings:
- def __init__(self, num_layers: int, msg_hidden_size_factor: int=2, layer_norm: bool=False, name: Optional[str]=None): Constructor. Args: num... | a6ef8053380d6aa19aaae14b93f013ae9762d057 | <|skeleton|>
class SimpleGraphNet:
"""A simple graph net module, a stack of message passing layers."""
def __init__(self, num_layers: int, msg_hidden_size_factor: int=2, layer_norm: bool=False, name: Optional[str]=None):
"""Constructor. Args: num_layers: number of message passing layers in the network.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleGraphNet:
"""A simple graph net module, a stack of message passing layers."""
def __init__(self, num_layers: int, msg_hidden_size_factor: int=2, layer_norm: bool=False, name: Optional[str]=None):
"""Constructor. Args: num_layers: number of message passing layers in the network. msg_hidden_s... | the_stack_v2_python_sparse | wikigraphs/wikigraphs/model/graph_net.py | sethuramanio/deepmind-research | train | 1 |
3e0abac0d9d72f48592728dd3052f3024fb71925 | [
"self.dim = pos_samples.shape[1]\nif self.dim + 1 != pos_samples.shape[0]:\n raise ValueError('Wrong number of samples')\nself.vertices = pos_samples\nself.facets = []\nself.create_facets()",
"for sample_id in range(self.vertices.shape[0]):\n facet_points = np.delete(self.vertices, sample_id, axis=0)\n s... | <|body_start_0|>
self.dim = pos_samples.shape[1]
if self.dim + 1 != pos_samples.shape[0]:
raise ValueError('Wrong number of samples')
self.vertices = pos_samples
self.facets = []
self.create_facets()
<|end_body_0|>
<|body_start_1|>
for sample_id in range(self... | Implement the convex polytope | PosRegion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PosRegion:
"""Implement the convex polytope"""
def __init__(self, pos_samples):
"""Params: pos_samples (np.array): dim+1 positive samples to create the (dim)-polytope."""
<|body_0|>
def create_facets(self):
"""Create the facets of the polytope"""
<|body_1... | stack_v2_sparse_classes_36k_train_020789 | 4,260 | permissive | [
{
"docstring": "Params: pos_samples (np.array): dim+1 positive samples to create the (dim)-polytope.",
"name": "__init__",
"signature": "def __init__(self, pos_samples)"
},
{
"docstring": "Create the facets of the polytope",
"name": "create_facets",
"signature": "def create_facets(self)"... | 5 | stack_v2_sparse_classes_30k_train_013226 | Implement the Python class `PosRegion` described below.
Class description:
Implement the convex polytope
Method signatures and docstrings:
- def __init__(self, pos_samples): Params: pos_samples (np.array): dim+1 positive samples to create the (dim)-polytope.
- def create_facets(self): Create the facets of the polytop... | Implement the Python class `PosRegion` described below.
Class description:
Implement the convex polytope
Method signatures and docstrings:
- def __init__(self, pos_samples): Params: pos_samples (np.array): dim+1 positive samples to create the (dim)-polytope.
- def create_facets(self): Create the facets of the polytop... | b37b4ba33e035ff2c005e3faa194c25702b7e5f1 | <|skeleton|>
class PosRegion:
"""Implement the convex polytope"""
def __init__(self, pos_samples):
"""Params: pos_samples (np.array): dim+1 positive samples to create the (dim)-polytope."""
<|body_0|>
def create_facets(self):
"""Create the facets of the polytope"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PosRegion:
"""Implement the convex polytope"""
def __init__(self, pos_samples):
"""Params: pos_samples (np.array): dim+1 positive samples to create the (dim)-polytope."""
self.dim = pos_samples.shape[1]
if self.dim + 1 != pos_samples.shape[0]:
raise ValueError('Wrong n... | the_stack_v2_python_sparse | neural_aide/threesetsmetric/posregion.py | AlexandreSev/neural_aide | train | 0 |
e8edd7b4d3823d07b33564a52458fb11ae66d0a4 | [
"self.cnn_network_dir = cnn_network_dir\nself.batch_size = batch_size\nself.config = config\nsuper(TrainCNN, self).__init__(str_description, [])",
"for label, data in obj_data.getIterator():\n data_labels = obj_data.info(label)['Labels']\n ann.train(image_data=data, image_labels=data_labels, model_dir=self.... | <|body_start_0|>
self.cnn_network_dir = cnn_network_dir
self.batch_size = batch_size
self.config = config
super(TrainCNN, self).__init__(str_description, [])
<|end_body_0|>
<|body_start_1|>
for label, data in obj_data.getIterator():
data_labels = obj_data.info(label)... | Train a CNN | TrainCNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainCNN:
"""Train a CNN"""
def __init__(self, str_description, cnn_network_dir, batch_size, config=None):
"""Initialize TrainCNN item @param str_description: String describing item @param cnn_network_dir: Strining containing the directiory where the CNN is stored @param batch_size: ... | stack_v2_sparse_classes_36k_train_020790 | 2,909 | permissive | [
{
"docstring": "Initialize TrainCNN item @param str_description: String describing item @param cnn_network_dir: Strining containing the directiory where the CNN is stored @param batch_size: Batch size to use when training data @param config: Dictinoary of extra options to use with the tensorflow session",
"... | 2 | stack_v2_sparse_classes_30k_train_010029 | Implement the Python class `TrainCNN` described below.
Class description:
Train a CNN
Method signatures and docstrings:
- def __init__(self, str_description, cnn_network_dir, batch_size, config=None): Initialize TrainCNN item @param str_description: String describing item @param cnn_network_dir: Strining containing t... | Implement the Python class `TrainCNN` described below.
Class description:
Train a CNN
Method signatures and docstrings:
- def __init__(self, str_description, cnn_network_dir, batch_size, config=None): Initialize TrainCNN item @param str_description: String describing item @param cnn_network_dir: Strining containing t... | 4d22e3ef90ef842d6b390074a8b5deedc7658a2b | <|skeleton|>
class TrainCNN:
"""Train a CNN"""
def __init__(self, str_description, cnn_network_dir, batch_size, config=None):
"""Initialize TrainCNN item @param str_description: String describing item @param cnn_network_dir: Strining containing the directiory where the CNN is stored @param batch_size: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainCNN:
"""Train a CNN"""
def __init__(self, str_description, cnn_network_dir, batch_size, config=None):
"""Initialize TrainCNN item @param str_description: String describing item @param cnn_network_dir: Strining containing the directiory where the CNN is stored @param batch_size: Batch size to... | the_stack_v2_python_sparse | pyinsar/processing/discovery/train_cnn.py | MITeaps/pyinsar | train | 11 |
c261b13b90109cef02e3919f26e5edfddd9e51c7 | [
"super().__init__(dataset, categorical_indices=categorical_indices, feature_names=feature_names)\nif self.is_structured:\n self.discretised_dtype = []\n for feature in self.dataset_dtype.names:\n if feature in self.numerical_indices:\n self.discretised_dtype.append((feature, np.int8))\n ... | <|body_start_0|>
super().__init__(dataset, categorical_indices=categorical_indices, feature_names=feature_names)
if self.is_structured:
self.discretised_dtype = []
for feature in self.dataset_dtype.names:
if feature in self.numerical_indices:
s... | Discretises selected numerical features of the ``dataset`` into quartiles. .. versionadded:: 0.0.2 This class discretises numerical columns (features) of the ``dataset`` by mapping their values onto quartile ids to which they belong. The quartile boundaries are computed based of the ``dataset`` used to initialise this ... | QuartileDiscretiser | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuartileDiscretiser:
"""Discretises selected numerical features of the ``dataset`` into quartiles. .. versionadded:: 0.0.2 This class discretises numerical columns (features) of the ``dataset`` by mapping their values onto quartile ids to which they belong. The quartile boundaries are computed ba... | stack_v2_sparse_classes_36k_train_020791 | 24,052 | permissive | [
{
"docstring": "Constructs a ``QuartileDiscretiser`` object.",
"name": "__init__",
"signature": "def __init__(self, dataset: np.ndarray, categorical_indices: Optional[List[Index]]=None, feature_names: Optional[List[str]]=None) -> None"
},
{
"docstring": "Discretises numerical features of the ``d... | 2 | stack_v2_sparse_classes_30k_train_006687 | Implement the Python class `QuartileDiscretiser` described below.
Class description:
Discretises selected numerical features of the ``dataset`` into quartiles. .. versionadded:: 0.0.2 This class discretises numerical columns (features) of the ``dataset`` by mapping their values onto quartile ids to which they belong. ... | Implement the Python class `QuartileDiscretiser` described below.
Class description:
Discretises selected numerical features of the ``dataset`` into quartiles. .. versionadded:: 0.0.2 This class discretises numerical columns (features) of the ``dataset`` by mapping their values onto quartile ids to which they belong. ... | f6ce0853d328a6eab8d2506cc1122c1a79a4eccc | <|skeleton|>
class QuartileDiscretiser:
"""Discretises selected numerical features of the ``dataset`` into quartiles. .. versionadded:: 0.0.2 This class discretises numerical columns (features) of the ``dataset`` by mapping their values onto quartile ids to which they belong. The quartile boundaries are computed ba... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuartileDiscretiser:
"""Discretises selected numerical features of the ``dataset`` into quartiles. .. versionadded:: 0.0.2 This class discretises numerical columns (features) of the ``dataset`` by mapping their values onto quartile ids to which they belong. The quartile boundaries are computed based of the ``... | the_stack_v2_python_sparse | fatf/utils/data/discretisation.py | fat-forensics/fat-forensics | train | 65 |
1217aaa1ee5f0fcf9310cbff24737a55422afd55 | [
"width = ele.size['width']\nheight = ele.size['height']\nreturn (width, height)",
"x = ele.location['x']\ny = ele.location['y']\nreturn (x, y)",
"loc = self.get_element_location(element)\nsize = self.get_element_size(element)\nx_left = loc[0]\ny_up = loc[1]\nx_center = loc[0] + size[0] // 2\ny_center = loc[1] +... | <|body_start_0|>
width = ele.size['width']
height = ele.size['height']
return (width, height)
<|end_body_0|>
<|body_start_1|>
x = ele.location['x']
y = ele.location['y']
return (x, y)
<|end_body_1|>
<|body_start_2|>
loc = self.get_element_location(element)
... | 获取 元素 大小及坐标 | ElementBounds | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElementBounds:
"""获取 元素 大小及坐标"""
def get_element_size(self, ele):
"""获取元素 width & height"""
<|body_0|>
def get_element_location(self, ele):
"""获取元素坐标"""
<|body_1|>
def get_element_bounds(self, element):
"""获取元素 左上角/中心点/右下角的坐标值"""
<|bo... | stack_v2_sparse_classes_36k_train_020792 | 997 | no_license | [
{
"docstring": "获取元素 width & height",
"name": "get_element_size",
"signature": "def get_element_size(self, ele)"
},
{
"docstring": "获取元素坐标",
"name": "get_element_location",
"signature": "def get_element_location(self, ele)"
},
{
"docstring": "获取元素 左上角/中心点/右下角的坐标值",
"name": "g... | 3 | null | Implement the Python class `ElementBounds` described below.
Class description:
获取 元素 大小及坐标
Method signatures and docstrings:
- def get_element_size(self, ele): 获取元素 width & height
- def get_element_location(self, ele): 获取元素坐标
- def get_element_bounds(self, element): 获取元素 左上角/中心点/右下角的坐标值 | Implement the Python class `ElementBounds` described below.
Class description:
获取 元素 大小及坐标
Method signatures and docstrings:
- def get_element_size(self, ele): 获取元素 width & height
- def get_element_location(self, ele): 获取元素坐标
- def get_element_bounds(self, element): 获取元素 左上角/中心点/右下角的坐标值
<|skeleton|>
class ElementBou... | 908bef52867e3944b76898cfcc018fa403202815 | <|skeleton|>
class ElementBounds:
"""获取 元素 大小及坐标"""
def get_element_size(self, ele):
"""获取元素 width & height"""
<|body_0|>
def get_element_location(self, ele):
"""获取元素坐标"""
<|body_1|>
def get_element_bounds(self, element):
"""获取元素 左上角/中心点/右下角的坐标值"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElementBounds:
"""获取 元素 大小及坐标"""
def get_element_size(self, ele):
"""获取元素 width & height"""
width = ele.size['width']
height = ele.size['height']
return (width, height)
def get_element_location(self, ele):
"""获取元素坐标"""
x = ele.location['x']
y =... | the_stack_v2_python_sparse | testfarm/test_program/utils/get_element_bounds.py | sj542484/test | train | 0 |
c066d0c4307f1ec545ed968b579ac064fbb87ecd | [
"if not root:\n return []\nres_lst = []\nlevel_lst = []\nqueue = [root, '#']\nwhile queue:\n node = queue.pop(0)\n if node == '#':\n res_lst.append(level_lst)\n level_lst = []\n if not queue:\n break\n queue.append('#')\n else:\n level_lst.append(node.val)\n... | <|body_start_0|>
if not root:
return []
res_lst = []
level_lst = []
queue = [root, '#']
while queue:
node = queue.pop(0)
if node == '#':
res_lst.append(level_lst)
level_lst = []
if not queue:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrder(self, root):
"""More concise implement by thinking in level by level. :type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_020793 | 1,472 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrder",
"signature": "def levelOrder(self, root)"
},
{
"docstring": "More concise implement by thinking in level by level. :type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrder",
"signature": "def l... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrder(self, root): More concise implement by thinking in level by level. :type root: TreeNode ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrder(self, root): More concise implement by thinking in level by level. :type root: TreeNode ... | 052bd7915257679877dbe55b60ed1abb7528eaa2 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrder(self, root):
"""More concise implement by thinking in level by level. :type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
if not root:
return []
res_lst = []
level_lst = []
queue = [root, '#']
while queue:
node = queue.pop(0)
if node == '#':
r... | the_stack_v2_python_sparse | python_solution/BreadthFirstSearch/102_BinaryTreeLevelOrderTraversal.py | Dimen61/leetcode | train | 4 | |
6689a2841eeb96c150f81b748a445eb97d3fc93a | [
"sof = self._get_sof(rake)\nmu_rw, sigma_rw, rw_max, p_i = self.get_rupture_width(magnitude, dip, sof, lsd)\nmu_ra, sigma_ra = self.get_rupture_area(magnitude, sof, rw_max, sigma_rw)\nF_rw_max_norm = norm.cdf(log(rw_max), loc=mu_rw, scale=sigma_rw)\nncdf_epsilon = norm.cdf(epsilon)\ntarget = ncdf_epsilon / F_rw_max... | <|body_start_0|>
sof = self._get_sof(rake)
mu_rw, sigma_rw, rw_max, p_i = self.get_rupture_width(magnitude, dip, sof, lsd)
mu_ra, sigma_ra = self.get_rupture_area(magnitude, sof, rw_max, sigma_rw)
F_rw_max_norm = norm.cdf(log(rw_max), loc=mu_rw, scale=sigma_rw)
ncdf_epsilon = nor... | Implements Stafford (2014) scaling relation model | Stafford2014 | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stafford2014:
"""Implements Stafford (2014) scaling relation model"""
def get_rupture_dimensions(self, magnitude, dip, rake, lsd, epsilon=0.0):
"""Gets the rupture dimension from for the given magnitude"""
<|body_0|>
def _get_sof(self, rake):
"""Returns the Style... | stack_v2_sparse_classes_36k_train_020794 | 23,900 | permissive | [
{
"docstring": "Gets the rupture dimension from for the given magnitude",
"name": "get_rupture_dimensions",
"signature": "def get_rupture_dimensions(self, magnitude, dip, rake, lsd, epsilon=0.0)"
},
{
"docstring": "Returns the Style of faulting from the Rake",
"name": "_get_sof",
"signat... | 5 | null | Implement the Python class `Stafford2014` described below.
Class description:
Implements Stafford (2014) scaling relation model
Method signatures and docstrings:
- def get_rupture_dimensions(self, magnitude, dip, rake, lsd, epsilon=0.0): Gets the rupture dimension from for the given magnitude
- def _get_sof(self, rak... | Implement the Python class `Stafford2014` described below.
Class description:
Implements Stafford (2014) scaling relation model
Method signatures and docstrings:
- def get_rupture_dimensions(self, magnitude, dip, rake, lsd, epsilon=0.0): Gets the rupture dimension from for the given magnitude
- def _get_sof(self, rak... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class Stafford2014:
"""Implements Stafford (2014) scaling relation model"""
def get_rupture_dimensions(self, magnitude, dip, rake, lsd, epsilon=0.0):
"""Gets the rupture dimension from for the given magnitude"""
<|body_0|>
def _get_sof(self, rake):
"""Returns the Style... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stafford2014:
"""Implements Stafford (2014) scaling relation model"""
def get_rupture_dimensions(self, magnitude, dip, rake, lsd, epsilon=0.0):
"""Gets the rupture dimension from for the given magnitude"""
sof = self._get_sof(rake)
mu_rw, sigma_rw, rw_max, p_i = self.get_rupture_w... | the_stack_v2_python_sparse | synthetic_rupture_generator.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
4c598df0b0989bdf2e546d04e5be15b20a622175 | [
"serialized = []\n\ndef preorder(node):\n if not node:\n return\n serialized.append(str(node.val))\n for child in node.children:\n preorder(child)\n serialized.append('#')\npreorder(root)\nreturn ' '.join(serialized)",
"tokens = deque(data.split())\nif len(tokens) == 0:\n return None\... | <|body_start_0|>
serialized = []
def preorder(node):
if not node:
return
serialized.append(str(node.val))
for child in node.children:
preorder(child)
serialized.append('#')
preorder(root)
return ' '.join(ser... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_020795 | 1,306 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | fd4cf122cfd4920f3bd8dce40ba7487a170a1b57 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
serialized = []
def preorder(node):
if not node:
return
serialized.append(str(node.val))
for child in node.childre... | the_stack_v2_python_sparse | 0428_Serialize_and_Deserialize_N-ary_Tree.py | coldmanck/leetcode-python | train | 6 | |
aae8e91d5707b7c830fa13f71f44f3d131aa4b29 | [
"QtGui.QMainWindow.__init__(self)\nself.resize(800, 600)\nself.centralwidget = QtGui.QWidget(self)\nself.mainLayout = QtGui.QHBoxLayout(self.centralwidget)\nself.mainLayout.setSpacing(0)\nself.mainLayout.setMargin(1)\nself.frame = QtGui.QFrame(self.centralwidget)\nself.gridLayout = QtGui.QVBoxLayout(self.frame)\nse... | <|body_start_0|>
QtGui.QMainWindow.__init__(self)
self.resize(800, 600)
self.centralwidget = QtGui.QWidget(self)
self.mainLayout = QtGui.QHBoxLayout(self.centralwidget)
self.mainLayout.setSpacing(0)
self.mainLayout.setMargin(1)
self.frame = QtGui.QFrame(self.centr... | Browser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Browser:
def __init__(self, default_url='http://google.com'):
"""Initialize the browser GUI and connect the events"""
<|body_0|>
def browse(self):
"""Make a web browse on a specific url and show the page on the Webview widget."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_020796 | 33,580 | no_license | [
{
"docstring": "Initialize the browser GUI and connect the events",
"name": "__init__",
"signature": "def __init__(self, default_url='http://google.com')"
},
{
"docstring": "Make a web browse on a specific url and show the page on the Webview widget.",
"name": "browse",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_011962 | Implement the Python class `Browser` described below.
Class description:
Implement the Browser class.
Method signatures and docstrings:
- def __init__(self, default_url='http://google.com'): Initialize the browser GUI and connect the events
- def browse(self): Make a web browse on a specific url and show the page on ... | Implement the Python class `Browser` described below.
Class description:
Implement the Browser class.
Method signatures and docstrings:
- def __init__(self, default_url='http://google.com'): Initialize the browser GUI and connect the events
- def browse(self): Make a web browse on a specific url and show the page on ... | 211c963dbac615920051be3a57991853e2081ac0 | <|skeleton|>
class Browser:
def __init__(self, default_url='http://google.com'):
"""Initialize the browser GUI and connect the events"""
<|body_0|>
def browse(self):
"""Make a web browse on a specific url and show the page on the Webview widget."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Browser:
def __init__(self, default_url='http://google.com'):
"""Initialize the browser GUI and connect the events"""
QtGui.QMainWindow.__init__(self)
self.resize(800, 600)
self.centralwidget = QtGui.QWidget(self)
self.mainLayout = QtGui.QHBoxLayout(self.centralwidget)
... | the_stack_v2_python_sparse | pyFAI-src/integrate_widget.py | SulzmannFr/pyFAI | train | 0 | |
0c70a6ae6b72489e68ca3b12f63c1510a603e752 | [
"self.k = k\nself.nums = nums\nheapq.heapify(self.nums)",
"heapq.heappush(self.nums, val)\nwhile len(self.nums) > self.k:\n heapq.heappop(self.nums)\nreturn self.nums[0]"
] | <|body_start_0|>
self.k = k
self.nums = nums
heapq.heapify(self.nums)
<|end_body_0|>
<|body_start_1|>
heapq.heappush(self.nums, val)
while len(self.nums) > self.k:
heapq.heappop(self.nums)
return self.nums[0]
<|end_body_1|>
| KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.nums = nums
heapq.heapify(... | stack_v2_sparse_classes_36k_train_020797 | 1,050 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005951 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 139a2808c551bcf77c8ebba8d387f6ea13c1507c | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.nums = nums
heapq.heapify(self.nums)
def add(self, val):
""":type val: int :rtype: int"""
heapq.heappush(self.nums, val)
while len(self.nums) > self.k:... | the_stack_v2_python_sparse | Kth Largest Element in a Stream.py | arekatlabhanuja/Leetcode-Problems | train | 0 | |
b162d351fe49b470251429de8e7cbf3af69be79a | [
"self.db_uri = kwargs.get('db_uri')\nif self.db_uri is None:\n raise ValueError('db_uri is required in the handler.')\nreturn True",
"kv_data['Time'] = {'$date': iso8601_to_ms(kv_data['Time'])}\nret = requests.post(self.db_uri, data=json.dumps(kv_data))\nif ret.ok:\n ret_value = ret.json()\n if ret_value... | <|body_start_0|>
self.db_uri = kwargs.get('db_uri')
if self.db_uri is None:
raise ValueError('db_uri is required in the handler.')
return True
<|end_body_0|>
<|body_start_1|>
kv_data['Time'] = {'$date': iso8601_to_ms(kv_data['Time'])}
ret = requests.post(self.db_uri,... | you can use the following code to submit data into the default mongodb. from connector_mongodb import connector_mongodb class handler(connector_mongodb): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_uri="your_mongodb_rest_api") p.submit(kv_data) | db_connector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class db_connector:
"""you can use the following code to submit data into the default mongodb. from connector_mongodb import connector_mongodb class handler(connector_mongodb): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_uri="your_mongodb_rest_api") p.submit(kv_data)"""
d... | stack_v2_sparse_classes_36k_train_020798 | 1,998 | permissive | [
{
"docstring": "db_uri must be passed.",
"name": "db_init",
"signature": "def db_init(self, **kwargs)"
},
{
"docstring": "- submit json data into the MongoDB via REST API. - assuming that all keys are exist in the json data. because it assumes that proc_tp_uplink() has been called already. - ass... | 2 | stack_v2_sparse_classes_30k_train_004960 | Implement the Python class `db_connector` described below.
Class description:
you can use the following code to submit data into the default mongodb. from connector_mongodb import connector_mongodb class handler(connector_mongodb): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_uri="your_mongodb... | Implement the Python class `db_connector` described below.
Class description:
you can use the following code to submit data into the default mongodb. from connector_mongodb import connector_mongodb class handler(connector_mongodb): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_uri="your_mongodb... | f473be5bc88a2dab0b1dbe6734ec70b71fd8b48b | <|skeleton|>
class db_connector:
"""you can use the following code to submit data into the default mongodb. from connector_mongodb import connector_mongodb class handler(connector_mongodb): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_uri="your_mongodb_rest_api") p.submit(kv_data)"""
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class db_connector:
"""you can use the following code to submit data into the default mongodb. from connector_mongodb import connector_mongodb class handler(connector_mongodb): pass p = handler(logger=self.logger, debug_level=self.debug_level, db_uri="your_mongodb_rest_api") p.submit(kv_data)"""
def db_init(se... | the_stack_v2_python_sparse | db_connectors/db_connector_mongodb.py | just-kuna/lorawan-ssas | train | 0 |
7ac4ea2b8485e84af4708d866087314f05c9665e | [
"if not isinstance(data, np.ndarray) or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\nd, n = data.shape\nself.mean = np.mean(data, axis=1, keepdims=True)\nxi = data - self.mean\nself.cov = np.matm... | <|body_start_0|>
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
raise ValueError('data must contain multiple data points')
d, n = data.shape
self.mean = np.mean(data, axis=1, ke... | Class Multinormal | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""Class Multinormal"""
def __init__(self, data):
"""Funtion that represents a Multivariate Normal distribution"""
<|body_0|>
def pdf(self, x):
"""Funtion that clculates the PDF of a Multivariate Normal distribution"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_020799 | 1,322 | no_license | [
{
"docstring": "Funtion that represents a Multivariate Normal distribution",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Funtion that clculates the PDF of a Multivariate Normal distribution",
"name": "pdf",
"signature": "def pdf(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016993 | Implement the Python class `MultiNormal` described below.
Class description:
Class Multinormal
Method signatures and docstrings:
- def __init__(self, data): Funtion that represents a Multivariate Normal distribution
- def pdf(self, x): Funtion that clculates the PDF of a Multivariate Normal distribution | Implement the Python class `MultiNormal` described below.
Class description:
Class Multinormal
Method signatures and docstrings:
- def __init__(self, data): Funtion that represents a Multivariate Normal distribution
- def pdf(self, x): Funtion that clculates the PDF of a Multivariate Normal distribution
<|skeleton|>... | 9dbf8221d4eb22dbc2487cb55e84a801a38aa5c8 | <|skeleton|>
class MultiNormal:
"""Class Multinormal"""
def __init__(self, data):
"""Funtion that represents a Multivariate Normal distribution"""
<|body_0|>
def pdf(self, x):
"""Funtion that clculates the PDF of a Multivariate Normal distribution"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiNormal:
"""Class Multinormal"""
def __init__(self, data):
"""Funtion that represents a Multivariate Normal distribution"""
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | yasmineholb/holbertonschool-machine_learning | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.