blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8d3767b711a7d7b15486529f21f8ad54453d622a | [
"self.distance = distance\nself.pid_foward = PID(distance, 0.01, 0.0001, 0.01, 500, -500, 0.7, -0.7)\nself.pid_yaw = PID(0, 0.33, 0.0, 0.33, 500, -500, 100, -100)\nself.pid_angle = PID(0.0, 0.01, 0.0, 0.01, 500, -500, 0.3, -0.3)\nself.pid_height = PID(0.0, 0.002, 0.0002, 0.002, 500, -500, 0.3, -0.2)\ncflib.crtp.ini... | <|body_start_0|>
self.distance = distance
self.pid_foward = PID(distance, 0.01, 0.0001, 0.01, 500, -500, 0.7, -0.7)
self.pid_yaw = PID(0, 0.33, 0.0, 0.33, 500, -500, 100, -100)
self.pid_angle = PID(0.0, 0.01, 0.0, 0.01, 500, -500, 0.3, -0.3)
self.pid_height = PID(0.0, 0.002, 0.00... | Aruco_tracker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Aruco_tracker:
def __init__(self, distance):
"""Inicialização dos drivers, parâmetros do controle PID e decolagem do drone."""
<|body_0|>
def search_marker(self):
"""Interrompe o movimento se nao encontrar o marcador por tres frames consecutivos. Após 4 segundos, ini... | stack_v2_sparse_classes_10k_train_003300 | 3,942 | no_license | [
{
"docstring": "Inicialização dos drivers, parâmetros do controle PID e decolagem do drone.",
"name": "__init__",
"signature": "def __init__(self, distance)"
},
{
"docstring": "Interrompe o movimento se nao encontrar o marcador por tres frames consecutivos. Após 4 segundos, inicia movimento de r... | 4 | stack_v2_sparse_classes_30k_train_002368 | Implement the Python class `Aruco_tracker` described below.
Class description:
Implement the Aruco_tracker class.
Method signatures and docstrings:
- def __init__(self, distance): Inicialização dos drivers, parâmetros do controle PID e decolagem do drone.
- def search_marker(self): Interrompe o movimento se nao encon... | Implement the Python class `Aruco_tracker` described below.
Class description:
Implement the Aruco_tracker class.
Method signatures and docstrings:
- def __init__(self, distance): Inicialização dos drivers, parâmetros do controle PID e decolagem do drone.
- def search_marker(self): Interrompe o movimento se nao encon... | 8af0ca6930b326ae7bc0cd7bb9aa2d6aa62bceeb | <|skeleton|>
class Aruco_tracker:
def __init__(self, distance):
"""Inicialização dos drivers, parâmetros do controle PID e decolagem do drone."""
<|body_0|>
def search_marker(self):
"""Interrompe o movimento se nao encontrar o marcador por tres frames consecutivos. Após 4 segundos, ini... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Aruco_tracker:
def __init__(self, distance):
"""Inicialização dos drivers, parâmetros do controle PID e decolagem do drone."""
self.distance = distance
self.pid_foward = PID(distance, 0.01, 0.0001, 0.01, 500, -500, 0.7, -0.7)
self.pid_yaw = PID(0, 0.33, 0.0, 0.33, 500, -500, 10... | the_stack_v2_python_sparse | Código-fonte/Esquadrilha/aruco_tracker_pid.py | EvoSystems-com-br/IniciacaoCientifica2018_ProjetoDrones | train | 0 | |
ccfa549c203e6aaa51d5e12d24543cdf770eefdf | [
"def check_supported_spec(spec):\n if tensor_spec.is_discrete(spec):\n assert len(spec.shape) == 0 or (len(spec.shape) == 1 and spec.shape[0] == 1)\n else:\n assert len(spec.shape) == 1\ntf.nest.map_structure(check_supported_spec, action_spec)\nself._action_spec = action_spec",
"tf.nest.assert... | <|body_start_0|>
def check_supported_spec(spec):
if tensor_spec.is_discrete(spec):
assert len(spec.shape) == 0 or (len(spec.shape) == 1 and spec.shape[0] == 1)
else:
assert len(spec.shape) == 1
tf.nest.map_structure(check_supported_spec, action_spe... | A simple encoder for action. Only supports one action (discrete or continuous). If encode discrete action to one hot representation and use the original continous actions. And output the concat of all of them | SimpleActionEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleActionEncoder:
"""A simple encoder for action. Only supports one action (discrete or continuous). If encode discrete action to one hot representation and use the original continous actions. And output the concat of all of them"""
def __init__(self, action_spec):
"""Create Simpl... | stack_v2_sparse_classes_10k_train_003301 | 2,438 | permissive | [
{
"docstring": "Create SimpleActionEncoder. Args: action_spec (nested BoundedTensorSpec): spec for actions",
"name": "__init__",
"signature": "def __init__(self, action_spec)"
},
{
"docstring": "Generate encoded actions. Args: inputs (nested Tensor): action tensors. Returns: nested Tensor with t... | 2 | stack_v2_sparse_classes_30k_train_000405 | Implement the Python class `SimpleActionEncoder` described below.
Class description:
A simple encoder for action. Only supports one action (discrete or continuous). If encode discrete action to one hot representation and use the original continous actions. And output the concat of all of them
Method signatures and do... | Implement the Python class `SimpleActionEncoder` described below.
Class description:
A simple encoder for action. Only supports one action (discrete or continuous). If encode discrete action to one hot representation and use the original continous actions. And output the concat of all of them
Method signatures and do... | 38a3621337a030f74bb3944d7695e7642e777e10 | <|skeleton|>
class SimpleActionEncoder:
"""A simple encoder for action. Only supports one action (discrete or continuous). If encode discrete action to one hot representation and use the original continous actions. And output the concat of all of them"""
def __init__(self, action_spec):
"""Create Simpl... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SimpleActionEncoder:
"""A simple encoder for action. Only supports one action (discrete or continuous). If encode discrete action to one hot representation and use the original continous actions. And output the concat of all of them"""
def __init__(self, action_spec):
"""Create SimpleActionEncode... | the_stack_v2_python_sparse | alf/utils/action_encoder.py | Haichao-Zhang/alf | train | 1 |
426fc61ad9c6c50eedc5e13990a2950b6aa2fd8a | [
"self.Account: Optional[Account] = None\nself.StartTimeUtc: datetime = datetime.min\nself.EndTimeUtc: datetime = datetime.min\nself.Host: Optional[Host] = None\nself.SessionId: str = ''\nsuper().__init__(src_entity=src_entity, **kwargs)\nif src_event is not None:\n if 'TimeCreatedUtc' in src_event:\n self... | <|body_start_0|>
self.Account: Optional[Account] = None
self.StartTimeUtc: datetime = datetime.min
self.EndTimeUtc: datetime = datetime.min
self.Host: Optional[Host] = None
self.SessionId: str = ''
super().__init__(src_entity=src_entity, **kwargs)
if src_event is ... | HostLogonSession Entity class. Attributes ---------- Account : Account HostLogonSession Account StartTimeUtc : datetime HostLogonSession StartTimeUtc EndTimeUtc : datetime HostLogonSession EndTimeUtc Host : Host HostLogonSession Host SessionId : str HostLogonSession SessionId | HostLogonSession | [
"LicenseRef-scancode-generic-cla",
"LGPL-3.0-only",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"ISC",
"LGPL-2.0-or-later",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"LGPL-2.1-only",
"Unlicense",
"Python-2.0",
"LicenseRef-scancode-python-cwi",
"MIT",
"LGPL-2.1-or-later",
"GPL-2.... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostLogonSession:
"""HostLogonSession Entity class. Attributes ---------- Account : Account HostLogonSession Account StartTimeUtc : datetime HostLogonSession StartTimeUtc EndTimeUtc : datetime HostLogonSession EndTimeUtc Host : Host HostLogonSession Host SessionId : str HostLogonSession SessionId... | stack_v2_sparse_classes_10k_train_003302 | 3,178 | permissive | [
{
"docstring": "Create a new instance of the entity type. Parameters ---------- src_entity : Mapping[str, Any], optional Create entity from existing entity or other mapping object that implements entity properties. (the default is None) src_event : Mapping[str, Any], optional Create entity from event properties... | 2 | stack_v2_sparse_classes_30k_train_000279 | Implement the Python class `HostLogonSession` described below.
Class description:
HostLogonSession Entity class. Attributes ---------- Account : Account HostLogonSession Account StartTimeUtc : datetime HostLogonSession StartTimeUtc EndTimeUtc : datetime HostLogonSession EndTimeUtc Host : Host HostLogonSession Host Ses... | Implement the Python class `HostLogonSession` described below.
Class description:
HostLogonSession Entity class. Attributes ---------- Account : Account HostLogonSession Account StartTimeUtc : datetime HostLogonSession StartTimeUtc EndTimeUtc : datetime HostLogonSession EndTimeUtc Host : Host HostLogonSession Host Ses... | 44b1a390510f9be2772ec62cb95d0fc67dfc234b | <|skeleton|>
class HostLogonSession:
"""HostLogonSession Entity class. Attributes ---------- Account : Account HostLogonSession Account StartTimeUtc : datetime HostLogonSession StartTimeUtc EndTimeUtc : datetime HostLogonSession EndTimeUtc Host : Host HostLogonSession Host SessionId : str HostLogonSession SessionId... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HostLogonSession:
"""HostLogonSession Entity class. Attributes ---------- Account : Account HostLogonSession Account StartTimeUtc : datetime HostLogonSession StartTimeUtc EndTimeUtc : datetime HostLogonSession EndTimeUtc Host : Host HostLogonSession Host SessionId : str HostLogonSession SessionId"""
def ... | the_stack_v2_python_sparse | msticpy/datamodel/entities/host_logon_session.py | RiskIQ/msticpy | train | 1 |
4d5e4ad90895baf7ad4c0b44e8ec0015c92e2192 | [
"self.playerCount = 0\nself.names = []\nscreen = GameSetupScreen()\nConsoleController.__init__(self, screen, commands={'1': self.setPlayerCount, '2': self.setPlayerCount, '3': self.setPlayerCount, '4': self.setPlayerCount, '5': self.setPlayerCount, '6': self.setPlayerCount})",
"self.playerCount = int(event)\nfor ... | <|body_start_0|>
self.playerCount = 0
self.names = []
screen = GameSetupScreen()
ConsoleController.__init__(self, screen, commands={'1': self.setPlayerCount, '2': self.setPlayerCount, '3': self.setPlayerCount, '4': self.setPlayerCount, '5': self.setPlayerCount, '6': self.setPlayerCount})... | Controller for Game Setup | GameSetupController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameSetupController:
"""Controller for Game Setup"""
def __init__(self):
"""Initialize the Game Setup Controller"""
<|body_0|>
def setPlayerCount(self, event):
"""Set the player Count"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.playerCo... | stack_v2_sparse_classes_10k_train_003303 | 1,367 | permissive | [
{
"docstring": "Initialize the Game Setup Controller",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Set the player Count",
"name": "setPlayerCount",
"signature": "def setPlayerCount(self, event)"
}
] | 2 | null | Implement the Python class `GameSetupController` described below.
Class description:
Controller for Game Setup
Method signatures and docstrings:
- def __init__(self): Initialize the Game Setup Controller
- def setPlayerCount(self, event): Set the player Count | Implement the Python class `GameSetupController` described below.
Class description:
Controller for Game Setup
Method signatures and docstrings:
- def __init__(self): Initialize the Game Setup Controller
- def setPlayerCount(self, event): Set the player Count
<|skeleton|>
class GameSetupController:
"""Controller... | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | <|skeleton|>
class GameSetupController:
"""Controller for Game Setup"""
def __init__(self):
"""Initialize the Game Setup Controller"""
<|body_0|>
def setPlayerCount(self, event):
"""Set the player Count"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GameSetupController:
"""Controller for Game Setup"""
def __init__(self):
"""Initialize the Game Setup Controller"""
self.playerCount = 0
self.names = []
screen = GameSetupScreen()
ConsoleController.__init__(self, screen, commands={'1': self.setPlayerCount, '2': sel... | the_stack_v2_python_sparse | data/train/python/4d9ee7bf7dbec4d310606d1b54cadb8a00648191game_setup_controller.py | harshp8l/deep-learning-lang-detection | train | 0 |
d1ac42be54d2e210db652e5663ffe14d7e659fab | [
"super().__init__(name=name, identity=identity, channel_division=channel_division, gain_provider=gain_provider, mode_class=mode_class)\nself.gain_range = Range()\nself.solve_signal = True",
"if branch is None:\n branch = f'correlated.{self.name}'\nsuper().set_options(configuration, branch=branch)\nif isinstanc... | <|body_start_0|>
super().__init__(name=name, identity=identity, channel_division=channel_division, gain_provider=gain_provider, mode_class=mode_class)
self.gain_range = Range()
self.solve_signal = True
<|end_body_0|>
<|body_start_1|>
if branch is None:
branch = f'correlated.... | CorrelatedModality | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CorrelatedModality:
def __init__(self, name=None, identity=None, channel_division=None, gain_provider=None, mode_class=None):
"""Create a correlated modality. A Modality is a collection of channel modes. A channel mode extracts/sets/operates-on gains from a channel group (collection of c... | stack_v2_sparse_classes_10k_train_003304 | 5,391 | permissive | [
{
"docstring": "Create a correlated modality. A Modality is a collection of channel modes. A channel mode extracts/sets/operates-on gains from a channel group (collection of channels). Modes are created by the modality from a channel division which is a collection of channel groups. The type of mode may be expl... | 4 | null | Implement the Python class `CorrelatedModality` described below.
Class description:
Implement the CorrelatedModality class.
Method signatures and docstrings:
- def __init__(self, name=None, identity=None, channel_division=None, gain_provider=None, mode_class=None): Create a correlated modality. A Modality is a collec... | Implement the Python class `CorrelatedModality` described below.
Class description:
Implement the CorrelatedModality class.
Method signatures and docstrings:
- def __init__(self, name=None, identity=None, channel_division=None, gain_provider=None, mode_class=None): Create a correlated modality. A Modality is a collec... | 493700340cd34d5f319af6f3a562a82135bb30dd | <|skeleton|>
class CorrelatedModality:
def __init__(self, name=None, identity=None, channel_division=None, gain_provider=None, mode_class=None):
"""Create a correlated modality. A Modality is a collection of channel modes. A channel mode extracts/sets/operates-on gains from a channel group (collection of c... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CorrelatedModality:
def __init__(self, name=None, identity=None, channel_division=None, gain_provider=None, mode_class=None):
"""Create a correlated modality. A Modality is a collection of channel modes. A channel mode extracts/sets/operates-on gains from a channel group (collection of channels). Mode... | the_stack_v2_python_sparse | sofia_redux/scan/channels/modality/correlated_modality.py | SOFIA-USRA/sofia_redux | train | 12 | |
088ac256a3cf15785085c494bc69912280c63774 | [
"client = mock_client(mocker)\nargs = {'user-profile': {'email': 'testdemisto2@paloaltonetworks.com'}}\nmocker.patch.object(client, 'get_user', return_value=None)\nmocker.patch.object(IAMUserProfile, 'map_object', return_value={})\nmocker.patch.object(client, 'create_user', return_value=USER_APP_DATA)\nuser_profile... | <|body_start_0|>
client = mock_client(mocker)
args = {'user-profile': {'email': 'testdemisto2@paloaltonetworks.com'}}
mocker.patch.object(client, 'get_user', return_value=None)
mocker.patch.object(IAMUserProfile, 'map_object', return_value={})
mocker.patch.object(client, 'create_... | Class to group the create user commands test | TestCreateUserCommand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCreateUserCommand:
"""Class to group the create user commands test"""
def test_create_user_command__success(self, mocker):
"""Given: - An app client object - A user-profile argument that contains an email of a non-existing user in the application When: - Calling function create_u... | stack_v2_sparse_classes_10k_train_003305 | 13,964 | permissive | [
{
"docstring": "Given: - An app client object - A user-profile argument that contains an email of a non-existing user in the application When: - Calling function create_user_command Then: - Ensure a User Profile object with the user data is returned",
"name": "test_create_user_command__success",
"signat... | 2 | null | Implement the Python class `TestCreateUserCommand` described below.
Class description:
Class to group the create user commands test
Method signatures and docstrings:
- def test_create_user_command__success(self, mocker): Given: - An app client object - A user-profile argument that contains an email of a non-existing ... | Implement the Python class `TestCreateUserCommand` described below.
Class description:
Class to group the create user commands test
Method signatures and docstrings:
- def test_create_user_command__success(self, mocker): Given: - An app client object - A user-profile argument that contains an email of a non-existing ... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestCreateUserCommand:
"""Class to group the create user commands test"""
def test_create_user_command__success(self, mocker):
"""Given: - An app client object - A user-profile argument that contains an email of a non-existing user in the application When: - Calling function create_u... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestCreateUserCommand:
"""Class to group the create user commands test"""
def test_create_user_command__success(self, mocker):
"""Given: - An app client object - A user-profile argument that contains an email of a non-existing user in the application When: - Calling function create_user_command T... | the_stack_v2_python_sparse | Packs/PrismaCloud/Integrations/PrismaCloudIAM/PrismaCloudIAM_test.py | demisto/content | train | 1,023 |
79c756691ca4186debb8c1de5da3f520db87cfc7 | [
"blog = get_object_or_404(BlogEntry, slug=kwargs.get('slug', None))\nself.template_name = blog.template.path\nself.entry = blog\nreturn super(BlogDetailView, self).get(request, *args, **kwargs)",
"context = super(BlogDetailView, self).get_context_data(**kwargs)\ntag_lines = [('Create simple, human-like, conversat... | <|body_start_0|>
blog = get_object_or_404(BlogEntry, slug=kwargs.get('slug', None))
self.template_name = blog.template.path
self.entry = blog
return super(BlogDetailView, self).get(request, *args, **kwargs)
<|end_body_0|>
<|body_start_1|>
context = super(BlogDetailView, self).ge... | Our view to set the template path prior to a regular get request. | BlogDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlogDetailView:
"""Our view to set the template path prior to a regular get request."""
def get(self, request, *args, **kwargs):
"""Here we base our render on the selected template/blog entry."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Set the blog en... | stack_v2_sparse_classes_10k_train_003306 | 3,135 | no_license | [
{
"docstring": "Here we base our render on the selected template/blog entry.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Set the blog entry context.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002510 | Implement the Python class `BlogDetailView` described below.
Class description:
Our view to set the template path prior to a regular get request.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Here we base our render on the selected template/blog entry.
- def get_context_data(self, **kwa... | Implement the Python class `BlogDetailView` described below.
Class description:
Our view to set the template path prior to a regular get request.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Here we base our render on the selected template/blog entry.
- def get_context_data(self, **kwa... | 4cd52c07bb64e9d9381a957323d277489a02181a | <|skeleton|>
class BlogDetailView:
"""Our view to set the template path prior to a regular get request."""
def get(self, request, *args, **kwargs):
"""Here we base our render on the selected template/blog entry."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Set the blog en... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BlogDetailView:
"""Our view to set the template path prior to a regular get request."""
def get(self, request, *args, **kwargs):
"""Here we base our render on the selected template/blog entry."""
blog = get_object_or_404(BlogEntry, slug=kwargs.get('slug', None))
self.template_name... | the_stack_v2_python_sparse | cms/blog/views.py | webmaxdev0110/digi-django | train | 0 |
862980c746946faf69f81e043c15a90cc130fa88 | [
"from Akamai_SIEM import fetch_incidents_command\nrequests_mock.get(f'{BASE_URL}/50170?limit=5&from=1575966002', text=SEC_EVENTS_TXT)\ntested_incidents, tested_last_run = fetch_incidents_command(client=client, fetch_time='12 hours', fetch_limit=5, config_ids='50170', last_run={})\nexpected_incidents = load_params_f... | <|body_start_0|>
from Akamai_SIEM import fetch_incidents_command
requests_mock.get(f'{BASE_URL}/50170?limit=5&from=1575966002', text=SEC_EVENTS_TXT)
tested_incidents, tested_last_run = fetch_incidents_command(client=client, fetch_time='12 hours', fetch_limit=5, config_ids='50170', last_run={})
... | TestCommandsFunctions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCommandsFunctions:
def test_fetch_incidents_command_1(self, client, datadir, requests_mock):
"""Test - No last time exsits and event available"""
<|body_0|>
def test_fetch_incidents_command_2(self, client, datadir, requests_mock):
"""Test - Last time exsits and e... | stack_v2_sparse_classes_10k_train_003307 | 7,487 | permissive | [
{
"docstring": "Test - No last time exsits and event available",
"name": "test_fetch_incidents_command_1",
"signature": "def test_fetch_incidents_command_1(self, client, datadir, requests_mock)"
},
{
"docstring": "Test - Last time exsits and events available",
"name": "test_fetch_incidents_c... | 6 | stack_v2_sparse_classes_30k_train_006680 | Implement the Python class `TestCommandsFunctions` described below.
Class description:
Implement the TestCommandsFunctions class.
Method signatures and docstrings:
- def test_fetch_incidents_command_1(self, client, datadir, requests_mock): Test - No last time exsits and event available
- def test_fetch_incidents_comm... | Implement the Python class `TestCommandsFunctions` described below.
Class description:
Implement the TestCommandsFunctions class.
Method signatures and docstrings:
- def test_fetch_incidents_command_1(self, client, datadir, requests_mock): Test - No last time exsits and event available
- def test_fetch_incidents_comm... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestCommandsFunctions:
def test_fetch_incidents_command_1(self, client, datadir, requests_mock):
"""Test - No last time exsits and event available"""
<|body_0|>
def test_fetch_incidents_command_2(self, client, datadir, requests_mock):
"""Test - Last time exsits and e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestCommandsFunctions:
def test_fetch_incidents_command_1(self, client, datadir, requests_mock):
"""Test - No last time exsits and event available"""
from Akamai_SIEM import fetch_incidents_command
requests_mock.get(f'{BASE_URL}/50170?limit=5&from=1575966002', text=SEC_EVENTS_TXT)
... | the_stack_v2_python_sparse | Packs/Akamai_SIEM/Integrations/Akamai_SIEM/Akamai_SIEM_test.py | demisto/content | train | 1,023 | |
1a98cc9ab99016897fb2d2a97ac2904ffffa5978 | [
"filename = 'rented_items.csv'\nfile = open(filename, 'a')\nfile.close()\nwith open('test_items.csv', 'a', newline='') as file:\n writer = csv.writer(file)\n writer.writerow(['LR04', 'Leather Sofa', 25.0])\n writer.writerow(['KT78', 'Kitchen Tablee', 10.0])\n writer.writerow(['BR02', 'Queen Mattress', 1... | <|body_start_0|>
filename = 'rented_items.csv'
file = open(filename, 'a')
file.close()
with open('test_items.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(['LR04', 'Leather Sofa', 25.0])
writer.writerow(['KT78', 'Kitchen Tab... | Tests the inventory functionalities | TestInventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestInventory:
"""Tests the inventory functionalities"""
def setUp(self):
"""Sets up the environment for testing"""
<|body_0|>
def tearDown(self):
"""Tears down all creations for testing"""
<|body_1|>
def test_add_furniture(self):
"""test to ... | stack_v2_sparse_classes_10k_train_003308 | 2,415 | no_license | [
{
"docstring": "Sets up the environment for testing",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tears down all creations for testing",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "test to make sure an entry is added to the file... | 4 | stack_v2_sparse_classes_30k_train_004261 | Implement the Python class `TestInventory` described below.
Class description:
Tests the inventory functionalities
Method signatures and docstrings:
- def setUp(self): Sets up the environment for testing
- def tearDown(self): Tears down all creations for testing
- def test_add_furniture(self): test to make sure an en... | Implement the Python class `TestInventory` described below.
Class description:
Tests the inventory functionalities
Method signatures and docstrings:
- def setUp(self): Sets up the environment for testing
- def tearDown(self): Tears down all creations for testing
- def test_add_furniture(self): test to make sure an en... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestInventory:
"""Tests the inventory functionalities"""
def setUp(self):
"""Sets up the environment for testing"""
<|body_0|>
def tearDown(self):
"""Tears down all creations for testing"""
<|body_1|>
def test_add_furniture(self):
"""test to ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestInventory:
"""Tests the inventory functionalities"""
def setUp(self):
"""Sets up the environment for testing"""
filename = 'rented_items.csv'
file = open(filename, 'a')
file.close()
with open('test_items.csv', 'a', newline='') as file:
writer = csv.... | the_stack_v2_python_sparse | students/humberto_gonzalez/lesson08/test_unit.py | JavaRod/SP_Python220B_2019 | train | 1 |
67347296046b45bd31aeaef3c0ca45b1f6fb8ec3 | [
"self.model = model\nself.beta = beta\nself.S0 = S0\nself.iso = iso",
"odf_matrix = self.model.cache_get('odf_matrix', key=sphere)\nif odf_matrix is None:\n odf_matrix = sfm_design_matrix(sphere, self.model.sphere, self.model.response, mode='odf')\n self.model.cache_set('odf_matrix', key=sphere, value=odf_m... | <|body_start_0|>
self.model = model
self.beta = beta
self.S0 = S0
self.iso = iso
<|end_body_0|>
<|body_start_1|>
odf_matrix = self.model.cache_get('odf_matrix', key=sphere)
if odf_matrix is None:
odf_matrix = sfm_design_matrix(sphere, self.model.sphere, self.... | SparseFascicleFit | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseFascicleFit:
def __init__(self, model, beta, S0, iso):
"""Initalize a SparseFascicleFit class instance Parameters ---------- model : a SparseFascicleModel object. beta : ndarray The parameters of fit to data. S0 : ndarray The mean non-diffusion-weighted signal. iso : IsotropicFit c... | stack_v2_sparse_classes_10k_train_003309 | 20,499 | permissive | [
{
"docstring": "Initalize a SparseFascicleFit class instance Parameters ---------- model : a SparseFascicleModel object. beta : ndarray The parameters of fit to data. S0 : ndarray The mean non-diffusion-weighted signal. iso : IsotropicFit class instance A representation of the isotropic signal, together with pa... | 3 | null | Implement the Python class `SparseFascicleFit` described below.
Class description:
Implement the SparseFascicleFit class.
Method signatures and docstrings:
- def __init__(self, model, beta, S0, iso): Initalize a SparseFascicleFit class instance Parameters ---------- model : a SparseFascicleModel object. beta : ndarra... | Implement the Python class `SparseFascicleFit` described below.
Class description:
Implement the SparseFascicleFit class.
Method signatures and docstrings:
- def __init__(self, model, beta, S0, iso): Initalize a SparseFascicleFit class instance Parameters ---------- model : a SparseFascicleModel object. beta : ndarra... | 3c3acc55de8ba741e673063378e6cbaf10b64c7a | <|skeleton|>
class SparseFascicleFit:
def __init__(self, model, beta, S0, iso):
"""Initalize a SparseFascicleFit class instance Parameters ---------- model : a SparseFascicleModel object. beta : ndarray The parameters of fit to data. S0 : ndarray The mean non-diffusion-weighted signal. iso : IsotropicFit c... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SparseFascicleFit:
def __init__(self, model, beta, S0, iso):
"""Initalize a SparseFascicleFit class instance Parameters ---------- model : a SparseFascicleModel object. beta : ndarray The parameters of fit to data. S0 : ndarray The mean non-diffusion-weighted signal. iso : IsotropicFit class instance ... | the_stack_v2_python_sparse | env/lib/python3.6/site-packages/dipy/reconst/sfm.py | Raniac/NEURO-LEARN | train | 9 | |
20776725c21ee332b17e9e1182e6e93771ca1309 | [
"self.bundle_distr = bundle_distr\nself.bundle_var = RandomVariable(self.bundle_distr, sims)\nself.nb = nb\nself.eval()\nself.n = self.bundle_var.n\nself.x = self.bundle_var.x",
"def pdf_min(cdf, pdf):\n return self.nb * pow(1.0 - cdf, self.nb - 1.0) * pdf\npdf_min_func = frompyfunc(pdf_min, 2, 1)\nself.pdf = ... | <|body_start_0|>
self.bundle_distr = bundle_distr
self.bundle_var = RandomVariable(self.bundle_distr, sims)
self.nb = nb
self.eval()
self.n = self.bundle_var.n
self.x = self.bundle_var.x
<|end_body_0|>
<|body_start_1|>
def pdf_min(cdf, pdf):
return se... | @brief Random variable for a chain of bundles. This variable is constructed using a BundleDistribution. | RandomChainOfBundlesVariable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomChainOfBundlesVariable:
"""@brief Random variable for a chain of bundles. This variable is constructed using a BundleDistribution."""
def __init__(self, bundle_distr, nb, sims):
"""@brief Constructor @param bundle_distr Instance of DanielsSmithDistrib to represent a single bund... | stack_v2_sparse_classes_10k_train_003310 | 12,843 | no_license | [
{
"docstring": "@brief Constructor @param bundle_distr Instance of DanielsSmithDistrib to represent a single bundle with a specified length @param nb number of bundles chained @param sims number of sampling points to use for the bundle and chain-of-bundles variable.",
"name": "__init__",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_005926 | Implement the Python class `RandomChainOfBundlesVariable` described below.
Class description:
@brief Random variable for a chain of bundles. This variable is constructed using a BundleDistribution.
Method signatures and docstrings:
- def __init__(self, bundle_distr, nb, sims): @brief Constructor @param bundle_distr I... | Implement the Python class `RandomChainOfBundlesVariable` described below.
Class description:
@brief Random variable for a chain of bundles. This variable is constructed using a BundleDistribution.
Method signatures and docstrings:
- def __init__(self, bundle_distr, nb, sims): @brief Constructor @param bundle_distr I... | 00de9f0eec52835d839a3c6c1407cac11a496339 | <|skeleton|>
class RandomChainOfBundlesVariable:
"""@brief Random variable for a chain of bundles. This variable is constructed using a BundleDistribution."""
def __init__(self, bundle_distr, nb, sims):
"""@brief Constructor @param bundle_distr Instance of DanielsSmithDistrib to represent a single bund... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomChainOfBundlesVariable:
"""@brief Random variable for a chain of bundles. This variable is constructed using a BundleDistribution."""
def __init__(self, bundle_distr, nb, sims):
"""@brief Constructor @param bundle_distr Instance of DanielsSmithDistrib to represent a single bundle with a spe... | the_stack_v2_python_sparse | bmcs/ytta/chob/chob.py | simvisage/bmcs | train | 1 |
4200782a5602e4020adeebc16dd8d375a5a5bc57 | [
"res = []\nwhile head:\n res.append(head.val)\n head = head.next\nreturn int(''.join((str(e) for e in res)), base=2)",
"num = head.val\nwhile head.next:\n num = num * 2 + head.next.val\n head = head.next\nreturn num",
"num = head.val\nwhile head.next:\n num = num << 1 | head.next.val\n head = ... | <|body_start_0|>
res = []
while head:
res.append(head.val)
head = head.next
return int(''.join((str(e) for e in res)), base=2)
<|end_body_0|>
<|body_start_1|>
num = head.val
while head.next:
num = num * 2 + head.next.val
head = hea... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getDecimalValue(self, head):
""":type head: ListNode :rtype: int"""
<|body_0|>
def getDecimalValue1(self, head):
"""Binary Representation time O(n) space O(1) :type head: ListNode :rtype: int"""
<|body_1|>
def getDecimalValue2(self, head):
... | stack_v2_sparse_classes_10k_train_003311 | 1,080 | no_license | [
{
"docstring": ":type head: ListNode :rtype: int",
"name": "getDecimalValue",
"signature": "def getDecimalValue(self, head)"
},
{
"docstring": "Binary Representation time O(n) space O(1) :type head: ListNode :rtype: int",
"name": "getDecimalValue1",
"signature": "def getDecimalValue1(sel... | 3 | stack_v2_sparse_classes_30k_test_000276 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getDecimalValue(self, head): :type head: ListNode :rtype: int
- def getDecimalValue1(self, head): Binary Representation time O(n) space O(1) :type head: ListNode :rtype: int
... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getDecimalValue(self, head): :type head: ListNode :rtype: int
- def getDecimalValue1(self, head): Binary Representation time O(n) space O(1) :type head: ListNode :rtype: int
... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def getDecimalValue(self, head):
""":type head: ListNode :rtype: int"""
<|body_0|>
def getDecimalValue1(self, head):
"""Binary Representation time O(n) space O(1) :type head: ListNode :rtype: int"""
<|body_1|>
def getDecimalValue2(self, head):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def getDecimalValue(self, head):
""":type head: ListNode :rtype: int"""
res = []
while head:
res.append(head.val)
head = head.next
return int(''.join((str(e) for e in res)), base=2)
def getDecimalValue1(self, head):
"""Binary Repre... | the_stack_v2_python_sparse | LeetCode/LinkedList/1290_convert_binary_number_in_a_linked_list_to_integer.py | XyK0907/for_work | train | 0 | |
3a7660e003988568899bd07222e53a87855df3d4 | [
"super().__init__()\nself.input_conv = nn.Conv1D(in_channels, hidden_channels, 1)\nself.encoder = WaveNet(in_channels=-1, out_channels=-1, kernel_size=kernel_size, layers=layers, stacks=stacks, base_dilation=base_dilation, residual_channels=hidden_channels, aux_channels=-1, gate_channels=hidden_channels * 2, skip_c... | <|body_start_0|>
super().__init__()
self.input_conv = nn.Conv1D(in_channels, hidden_channels, 1)
self.encoder = WaveNet(in_channels=-1, out_channels=-1, kernel_size=kernel_size, layers=layers, stacks=stacks, base_dilation=base_dilation, residual_channels=hidden_channels, aux_channels=-1, gate_ch... | Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`: https://arxiv.org/abs/2006.04558 | PosteriorEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PosteriorEncoder:
"""Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speec... | stack_v2_sparse_classes_10k_train_003312 | 4,766 | permissive | [
{
"docstring": "Initilialize PosteriorEncoder module. Args: in_channels (int): Number of input channels. out_channels (int): Number of output channels. hidden_channels (int): Number of hidden channels. kernel_size (int): Kernel size in WaveNet. layers (int): Number of layers of WaveNet. stacks (int): Number of ... | 2 | null | Implement the Python class `PosteriorEncoder` described below.
Class description:
Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversaria... | Implement the Python class `PosteriorEncoder` described below.
Class description:
Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversaria... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class PosteriorEncoder:
"""Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speec... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PosteriorEncoder:
"""Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`: https://a... | the_stack_v2_python_sparse | paddlespeech/t2s/models/vits/posterior_encoder.py | anniyanvr/DeepSpeech-1 | train | 0 |
bcc7f1832fedfd747b4184641e5ca057f16e70fa | [
"super().__init__(reduction=LossReduction(reduction).value)\nself.to_onehot_y = to_onehot_y\nself.num_classes = num_classes\nself.gamma = gamma\nself.delta = delta\nself.weight: float = weight\nself.asy_focal_loss = AsymmetricFocalLoss(gamma=self.gamma, delta=self.delta)\nself.asy_focal_tversky_loss = AsymmetricFoc... | <|body_start_0|>
super().__init__(reduction=LossReduction(reduction).value)
self.to_onehot_y = to_onehot_y
self.num_classes = num_classes
self.gamma = gamma
self.delta = delta
self.weight: float = weight
self.asy_focal_loss = AsymmetricFocalLoss(gamma=self.gamma, ... | AsymmetricUnifiedFocalLoss is a variant of Focal Loss. Actually, it's only supported for binary image segmentation now Reimplementation of the Asymmetric Unified Focal Tversky Loss described in: - "Unified Focal Loss: Generalising Dice and Cross Entropy-based Losses to Handle Class Imbalanced Medical Image Segmentation... | AsymmetricUnifiedFocalLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsymmetricUnifiedFocalLoss:
"""AsymmetricUnifiedFocalLoss is a variant of Focal Loss. Actually, it's only supported for binary image segmentation now Reimplementation of the Asymmetric Unified Focal Tversky Loss described in: - "Unified Focal Loss: Generalising Dice and Cross Entropy-based Losses... | stack_v2_sparse_classes_10k_train_003313 | 10,224 | permissive | [
{
"docstring": "Args: to_onehot_y : whether to convert `y` into the one-hot format. Defaults to False. num_classes : number of classes, it only supports 2 now. Defaults to 2. delta : weight of the background. Defaults to 0.7. gamma : value of the exponent gamma in the definition of the Focal loss. Defaults to 0... | 2 | stack_v2_sparse_classes_30k_train_004962 | Implement the Python class `AsymmetricUnifiedFocalLoss` described below.
Class description:
AsymmetricUnifiedFocalLoss is a variant of Focal Loss. Actually, it's only supported for binary image segmentation now Reimplementation of the Asymmetric Unified Focal Tversky Loss described in: - "Unified Focal Loss: Generalis... | Implement the Python class `AsymmetricUnifiedFocalLoss` described below.
Class description:
AsymmetricUnifiedFocalLoss is a variant of Focal Loss. Actually, it's only supported for binary image segmentation now Reimplementation of the Asymmetric Unified Focal Tversky Loss described in: - "Unified Focal Loss: Generalis... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class AsymmetricUnifiedFocalLoss:
"""AsymmetricUnifiedFocalLoss is a variant of Focal Loss. Actually, it's only supported for binary image segmentation now Reimplementation of the Asymmetric Unified Focal Tversky Loss described in: - "Unified Focal Loss: Generalising Dice and Cross Entropy-based Losses... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AsymmetricUnifiedFocalLoss:
"""AsymmetricUnifiedFocalLoss is a variant of Focal Loss. Actually, it's only supported for binary image segmentation now Reimplementation of the Asymmetric Unified Focal Tversky Loss described in: - "Unified Focal Loss: Generalising Dice and Cross Entropy-based Losses to Handle Cl... | the_stack_v2_python_sparse | monai/losses/unified_focal_loss.py | Project-MONAI/MONAI | train | 4,805 |
35ebd862f2db95944c1c51cd8d63e4d17570b69e | [
"assert query_batch_cnt.is_contiguous()\nassert key_batch_cnt.is_contiguous()\nassert index_pair_batch.is_contiguous()\nassert index_pair.is_contiguous()\nassert query_features.is_contiguous()\nassert key_features.is_contiguous()\nb = query_batch_cnt.shape[0]\ntotal_query_num, local_size = index_pair.size()\ntotal_... | <|body_start_0|>
assert query_batch_cnt.is_contiguous()
assert key_batch_cnt.is_contiguous()
assert index_pair_batch.is_contiguous()
assert index_pair.is_contiguous()
assert query_features.is_contiguous()
assert key_features.is_contiguous()
b = query_batch_cnt.sha... | Generate the attention weight matrix based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size) | AttentionWeightComputation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentionWeightComputation:
"""Generate the attention weight matrix based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, l... | stack_v2_sparse_classes_10k_train_003314 | 8,019 | no_license | [
{
"docstring": ":param ctx: :param query_batch_cnt: A integer tensor with shape [bs], indicating the query amount for each batch. :param key_batch_cnt: A integer tensor with shape [bs], indicating the key amount of each batch. :param index_pair_batch: A integer tensor with shape [total_query_num], indicating th... | 2 | stack_v2_sparse_classes_30k_train_001136 | Implement the Python class `AttentionWeightComputation` described below.
Class description:
Generate the attention weight matrix based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attenti... | Implement the Python class `AttentionWeightComputation` described below.
Class description:
Generate the attention weight matrix based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attenti... | bbc78ca91e851f0f04459b1a8bbe96ab44bf41bc | <|skeleton|>
class AttentionWeightComputation:
"""Generate the attention weight matrix based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, l... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AttentionWeightComputation:
"""Generate the attention weight matrix based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size)"""... | the_stack_v2_python_sparse | EQNet/eqnet/ops/attention/attention_utils_v2.py | dvlab-research/DeepVision3D | train | 94 |
d9d143c05516988af8c916776de2ac5cf840a97f | [
"self.ecal_train = ecal_train\nself.hcal_train = hcal_train\nself.true_train = true_train\nif lim == -1:\n lim = max(ecal_train) + max(hcal_train)\nself.lim = lim\nself.numberPart = len(self.ecal_train)\nif len(self.hcal_train) != self.numberPart or len(self.true_train) != self.numberPart or len(self.hcal_train)... | <|body_start_0|>
self.ecal_train = ecal_train
self.hcal_train = hcal_train
self.true_train = true_train
if lim == -1:
lim = max(ecal_train) + max(hcal_train)
self.lim = lim
self.numberPart = len(self.ecal_train)
if len(self.hcal_train) != self.numberPa... | Mother Class to calibrate the true energy of a particle thanks to training datas. All claibrations have to inherit from this class. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to train the calibration true_train : array ecal value to train the calibration lim... | Calibration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Calibration:
"""Mother Class to calibrate the true energy of a particle thanks to training datas. All claibrations have to inherit from this class. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to train the calibration true_train : array ... | stack_v2_sparse_classes_10k_train_003315 | 4,045 | no_license | [
{
"docstring": "Constructor of the class Parameters ---------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to train the calibration true_train : array ecal value to train the calibration lim : float if ecal + hcal > lim, the calibrated energy ecalib = math.nan if lim = -... | 4 | stack_v2_sparse_classes_30k_train_006471 | Implement the Python class `Calibration` described below.
Class description:
Mother Class to calibrate the true energy of a particle thanks to training datas. All claibrations have to inherit from this class. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to tr... | Implement the Python class `Calibration` described below.
Class description:
Mother Class to calibrate the true energy of a particle thanks to training datas. All claibrations have to inherit from this class. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to tr... | 53dbbd2e68986602c29008338d6c9cc96edc6d77 | <|skeleton|>
class Calibration:
"""Mother Class to calibrate the true energy of a particle thanks to training datas. All claibrations have to inherit from this class. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to train the calibration true_train : array ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Calibration:
"""Mother Class to calibrate the true energy of a particle thanks to training datas. All claibrations have to inherit from this class. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value to train the calibration true_train : array ecal value to... | the_stack_v2_python_sparse | pfcalibration/Calibration.py | sniang/particle_flow_calibration | train | 3 |
af4427f3e83a54bf497d24818e6a9b052df23ff3 | [
"if ADAPTIVE_AVG_POOL_BUG and module.input0.is_cuda and (self.N == 3):\n warn('Be careful when computing gradients of AdaptiveAvgPool3d. There is a bug using autograd.grad on cuda with AdaptiveAvgPool3d. https://discuss.pytorch.org/t/bug-report-autograd-grad-adaptiveavgpool3d-cuda/124614 BackPACK derivatives are... | <|body_start_0|>
if ADAPTIVE_AVG_POOL_BUG and module.input0.is_cuda and (self.N == 3):
warn('Be careful when computing gradients of AdaptiveAvgPool3d. There is a bug using autograd.grad on cuda with AdaptiveAvgPool3d. https://discuss.pytorch.org/t/bug-report-autograd-grad-adaptiveavgpool3d-cuda/1246... | Implements the derivatives for AdaptiveAvgPool. | AdaptiveAvgPoolNDDerivatives | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdaptiveAvgPoolNDDerivatives:
"""Implements the derivatives for AdaptiveAvgPool."""
def check_parameters(self, module: Union[AdaptiveAvgPool1d, AdaptiveAvgPool2d, AdaptiveAvgPool3d]) -> None:
"""Checks if the parameters are supported. Specifically checks if input shape is multiple of... | stack_v2_sparse_classes_10k_train_003316 | 3,807 | permissive | [
{
"docstring": "Checks if the parameters are supported. Specifically checks if input shape is multiple of output shape. In this case, there are parameters for AvgPoolND that are equivalent. https://stackoverflow.com/questions/53841509/how-does-adaptive-pooling-in-pytorch-work/63603993#63603993 # noqa: B950 Args... | 2 | stack_v2_sparse_classes_30k_train_000596 | Implement the Python class `AdaptiveAvgPoolNDDerivatives` described below.
Class description:
Implements the derivatives for AdaptiveAvgPool.
Method signatures and docstrings:
- def check_parameters(self, module: Union[AdaptiveAvgPool1d, AdaptiveAvgPool2d, AdaptiveAvgPool3d]) -> None: Checks if the parameters are sup... | Implement the Python class `AdaptiveAvgPoolNDDerivatives` described below.
Class description:
Implements the derivatives for AdaptiveAvgPool.
Method signatures and docstrings:
- def check_parameters(self, module: Union[AdaptiveAvgPool1d, AdaptiveAvgPool2d, AdaptiveAvgPool3d]) -> None: Checks if the parameters are sup... | 1ebfb4055be72ed9e0f9d101d78806bd4119645e | <|skeleton|>
class AdaptiveAvgPoolNDDerivatives:
"""Implements the derivatives for AdaptiveAvgPool."""
def check_parameters(self, module: Union[AdaptiveAvgPool1d, AdaptiveAvgPool2d, AdaptiveAvgPool3d]) -> None:
"""Checks if the parameters are supported. Specifically checks if input shape is multiple of... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AdaptiveAvgPoolNDDerivatives:
"""Implements the derivatives for AdaptiveAvgPool."""
def check_parameters(self, module: Union[AdaptiveAvgPool1d, AdaptiveAvgPool2d, AdaptiveAvgPool3d]) -> None:
"""Checks if the parameters are supported. Specifically checks if input shape is multiple of output shape... | the_stack_v2_python_sparse | backpack/core/derivatives/adaptive_avg_pool_nd.py | f-dangel/backpack | train | 505 |
73dc5a7d0ef009b7289a3b07bea55fc9b7055afd | [
"super(Embedding_LS, self).__init__()\nself.num_classes = num_classes\nself.label_smoothing_prob = label_smoothing_prob\nself.use_cuda = use_cuda\nwith self.init_scope():\n self.embed = LinearND(num_classes, embedding_dim, bias=False, dropout=dropout, use_cuda=use_cuda)\n if use_cuda:\n self.embed.to_g... | <|body_start_0|>
super(Embedding_LS, self).__init__()
self.num_classes = num_classes
self.label_smoothing_prob = label_smoothing_prob
self.use_cuda = use_cuda
with self.init_scope():
self.embed = LinearND(num_classes, embedding_dim, bias=False, dropout=dropout, use_cu... | Embedding_LS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedding_LS:
def __init__(self, num_classes, embedding_dim, dropout=0, label_smoothing_prob=0.0, use_cuda=False):
"""Embedding layer with label smoothing. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension... | stack_v2_sparse_classes_10k_train_003317 | 5,435 | no_license | [
{
"docstring": "Embedding layer with label smoothing. 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 label_smoothing_p... | 2 | stack_v2_sparse_classes_30k_train_003932 | Implement the Python class `Embedding_LS` described below.
Class description:
Implement the Embedding_LS class.
Method signatures and docstrings:
- def __init__(self, num_classes, embedding_dim, dropout=0, label_smoothing_prob=0.0, use_cuda=False): Embedding layer with label smoothing. Args: num_classes (int): the nu... | Implement the Python class `Embedding_LS` described below.
Class description:
Implement the Embedding_LS class.
Method signatures and docstrings:
- def __init__(self, num_classes, embedding_dim, dropout=0, label_smoothing_prob=0.0, use_cuda=False): Embedding layer with label smoothing. Args: num_classes (int): the nu... | b6b60a338d65bb369d0034f423feb09db10db8b7 | <|skeleton|>
class Embedding_LS:
def __init__(self, num_classes, embedding_dim, dropout=0, label_smoothing_prob=0.0, use_cuda=False):
"""Embedding layer with label smoothing. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Embedding_LS:
def __init__(self, num_classes, embedding_dim, dropout=0, label_smoothing_prob=0.0, use_cuda=False):
"""Embedding layer with label smoothing. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedd... | the_stack_v2_python_sparse | models/chainer/linear.py | carolinebear/pytorch_end2end_speech_recognition | train | 0 | |
3c0ce2bf58aeabbcb17fa76c2d382917c302a445 | [
"super().__init__(template_fn='joint_calling.html')\nself.title = 'Joint Calling Report'\nself.vcf = data\nself.table_html, self.table_options = self.create_datatable()\nself.create_html('joint_calling.html')",
"datatable = DataTable(self.vcf.df, 'jc')\ndatatable.datatable.datatable_options = {'scrollX': 'true', ... | <|body_start_0|>
super().__init__(template_fn='joint_calling.html')
self.title = 'Joint Calling Report'
self.vcf = data
self.table_html, self.table_options = self.create_datatable()
self.create_html('joint_calling.html')
<|end_body_0|>
<|body_start_1|>
datatable = DataTa... | Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter. | JointCallingModule | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JointCallingModule:
"""Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter."""
def __init__(self, data):
""".. rubric:: constructor :param data: it can be a csv filename created by sequana.freebayes_vcf_filter or a :class:`freebayes_v... | stack_v2_sparse_classes_10k_train_003318 | 2,093 | permissive | [
{
"docstring": ".. rubric:: constructor :param data: it can be a csv filename created by sequana.freebayes_vcf_filter or a :class:`freebayes_vcf_filter.Filtered_freebayes` object.",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Variants detected section.",
"n... | 2 | stack_v2_sparse_classes_30k_train_005897 | Implement the Python class `JointCallingModule` described below.
Class description:
Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter.
Method signatures and docstrings:
- def __init__(self, data): .. rubric:: constructor :param data: it can be a csv filename created... | Implement the Python class `JointCallingModule` described below.
Class description:
Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter.
Method signatures and docstrings:
- def __init__(self, data): .. rubric:: constructor :param data: it can be a csv filename created... | 8717094493d1993debd079f324c540541dece70f | <|skeleton|>
class JointCallingModule:
"""Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter."""
def __init__(self, data):
""".. rubric:: constructor :param data: it can be a csv filename created by sequana.freebayes_vcf_filter or a :class:`freebayes_v... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JointCallingModule:
"""Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter."""
def __init__(self, data):
""".. rubric:: constructor :param data: it can be a csv filename created by sequana.freebayes_vcf_filter or a :class:`freebayes_vcf_filter.Fil... | the_stack_v2_python_sparse | sequana/modules_report/joint_calling.py | sequana/sequana | train | 155 |
62d991f5db107f8844723fe018d8ab00245b4320 | [
"assert d_min > 0\nassert width > 0\nunit_cell = space_group.average_unit_cell(unit_cell)\nself.half_width = width / 2.0\nd_min = uctbx.d_star_sq_as_d(uctbx.d_as_d_star_sq(d_min) + self.half_width)\ngenerator = index_generator(unit_cell, space_group.type(), False, d_min)\nindices = generator.to_array()\nself.d_star... | <|body_start_0|>
assert d_min > 0
assert width > 0
unit_cell = space_group.average_unit_cell(unit_cell)
self.half_width = width / 2.0
d_min = uctbx.d_star_sq_as_d(uctbx.d_as_d_star_sq(d_min) + self.half_width)
generator = index_generator(unit_cell, space_group.type(), Fal... | A class to do powder ring filtering. | PowderRingFilter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PowderRingFilter:
"""A class to do powder ring filtering."""
def __init__(self, unit_cell, space_group, d_min, width):
"""Initialise the filter. :param unit_cell: The unit_cell of the powder rings :param space_group: The space group of the powder rings :param d_min: The maximum resol... | stack_v2_sparse_classes_10k_train_003319 | 3,314 | permissive | [
{
"docstring": "Initialise the filter. :param unit_cell: The unit_cell of the powder rings :param space_group: The space group of the powder rings :param d_min: The maximum resolution to filter to :param width: The resolution width to filter around",
"name": "__init__",
"signature": "def __init__(self, ... | 2 | null | Implement the Python class `PowderRingFilter` described below.
Class description:
A class to do powder ring filtering.
Method signatures and docstrings:
- def __init__(self, unit_cell, space_group, d_min, width): Initialise the filter. :param unit_cell: The unit_cell of the powder rings :param space_group: The space ... | Implement the Python class `PowderRingFilter` described below.
Class description:
A class to do powder ring filtering.
Method signatures and docstrings:
- def __init__(self, unit_cell, space_group, d_min, width): Initialise the filter. :param unit_cell: The unit_cell of the powder rings :param space_group: The space ... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class PowderRingFilter:
"""A class to do powder ring filtering."""
def __init__(self, unit_cell, space_group, d_min, width):
"""Initialise the filter. :param unit_cell: The unit_cell of the powder rings :param space_group: The space group of the powder rings :param d_min: The maximum resol... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PowderRingFilter:
"""A class to do powder ring filtering."""
def __init__(self, unit_cell, space_group, d_min, width):
"""Initialise the filter. :param unit_cell: The unit_cell of the powder rings :param space_group: The space group of the powder rings :param d_min: The maximum resolution to filt... | the_stack_v2_python_sparse | src/dials/algorithms/integration/filtering.py | dials/dials | train | 71 |
05f07a76dddded07a535778a4586a897075b7660 | [
"torch.manual_seed(0)\nmodel = goalDNN(in_dim=20, nb_category=3, nb_measures=1, p_dropout=0.1, hidden_dims=[64, 32])\nrng = np.random.default_rng(seed=0)\nx = torch.tensor(rng.random(size=(10, 20))).float()\n[mmse_hat, dx_hat] = model(x)\nmmse_hat_mean = torch.mean(mmse_hat).detach().numpy()\ndx_hat_mean = torch.me... | <|body_start_0|>
torch.manual_seed(0)
model = goalDNN(in_dim=20, nb_category=3, nb_measures=1, p_dropout=0.1, hidden_dims=[64, 32])
rng = np.random.default_rng(seed=0)
x = torch.tensor(rng.random(size=(10, 20))).float()
[mmse_hat, dx_hat] = model(x)
mmse_hat_mean = torch.... | CBIG_gcVAE_unit_test | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CBIG_gcVAE_unit_test:
def test_goaldnn_init(self):
"""Test initialization of goalDNN"""
<|body_0|>
def test_cvae_init(self):
"""Test initialization of cVAE"""
<|body_1|>
def test_training(self):
"""Test the training of goalDNN, cVAE, gcVAE, XGBoo... | stack_v2_sparse_classes_10k_train_003320 | 3,321 | permissive | [
{
"docstring": "Test initialization of goalDNN",
"name": "test_goaldnn_init",
"signature": "def test_goaldnn_init(self)"
},
{
"docstring": "Test initialization of cVAE",
"name": "test_cvae_init",
"signature": "def test_cvae_init(self)"
},
{
"docstring": "Test the training of goal... | 3 | stack_v2_sparse_classes_30k_train_002746 | Implement the Python class `CBIG_gcVAE_unit_test` described below.
Class description:
Implement the CBIG_gcVAE_unit_test class.
Method signatures and docstrings:
- def test_goaldnn_init(self): Test initialization of goalDNN
- def test_cvae_init(self): Test initialization of cVAE
- def test_training(self): Test the tr... | Implement the Python class `CBIG_gcVAE_unit_test` described below.
Class description:
Implement the CBIG_gcVAE_unit_test class.
Method signatures and docstrings:
- def test_goaldnn_init(self): Test initialization of goalDNN
- def test_cvae_init(self): Test initialization of cVAE
- def test_training(self): Test the tr... | c773720ad340dcb1d566b0b8de68b6acdf2ca505 | <|skeleton|>
class CBIG_gcVAE_unit_test:
def test_goaldnn_init(self):
"""Test initialization of goalDNN"""
<|body_0|>
def test_cvae_init(self):
"""Test initialization of cVAE"""
<|body_1|>
def test_training(self):
"""Test the training of goalDNN, cVAE, gcVAE, XGBoo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CBIG_gcVAE_unit_test:
def test_goaldnn_init(self):
"""Test initialization of goalDNN"""
torch.manual_seed(0)
model = goalDNN(in_dim=20, nb_category=3, nb_measures=1, p_dropout=0.1, hidden_dims=[64, 32])
rng = np.random.default_rng(seed=0)
x = torch.tensor(rng.random(siz... | the_stack_v2_python_sparse | stable_projects/predict_phenotypes/An2022_gcVAE/unit_tests/CBIG_gcVAE_unit_test.py | ThomasYeoLab/CBIG | train | 508 | |
435f48322403ca8e571f3bccfe8cc3a0a1677b7e | [
"super().__init__()\nself.frequency = frequency\nself.quality_factor = quality_factor\nself.sampling_freq = sampling_freq",
"b_notch, a_notch = convert_to_tensor(iirnotch(self.frequency, self.quality_factor, self.sampling_freq), dtype=torch.float)\ny_notched = filtfilt(convert_to_tensor(signal), a_notch, b_notch)... | <|body_start_0|>
super().__init__()
self.frequency = frequency
self.quality_factor = quality_factor
self.sampling_freq = sampling_freq
<|end_body_0|>
<|body_start_1|>
b_notch, a_notch = convert_to_tensor(iirnotch(self.frequency, self.quality_factor, self.sampling_freq), dtype=to... | Remove a frequency from a signal | SignalRemoveFrequency | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignalRemoveFrequency:
"""Remove a frequency from a signal"""
def __init__(self, frequency: float | None=None, quality_factor: float | None=None, sampling_freq: float | None=None) -> None:
"""Args: frequency: frequency to be removed from the signal quality_factor: quality factor for ... | stack_v2_sparse_classes_10k_train_003321 | 16,322 | permissive | [
{
"docstring": "Args: frequency: frequency to be removed from the signal quality_factor: quality factor for notch filter see : https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.iirnotch.html sampling_freq: sampling frequency of the input signal",
"name": "__init__",
"signature": "def __i... | 2 | stack_v2_sparse_classes_30k_train_000756 | Implement the Python class `SignalRemoveFrequency` described below.
Class description:
Remove a frequency from a signal
Method signatures and docstrings:
- def __init__(self, frequency: float | None=None, quality_factor: float | None=None, sampling_freq: float | None=None) -> None: Args: frequency: frequency to be re... | Implement the Python class `SignalRemoveFrequency` described below.
Class description:
Remove a frequency from a signal
Method signatures and docstrings:
- def __init__(self, frequency: float | None=None, quality_factor: float | None=None, sampling_freq: float | None=None) -> None: Args: frequency: frequency to be re... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class SignalRemoveFrequency:
"""Remove a frequency from a signal"""
def __init__(self, frequency: float | None=None, quality_factor: float | None=None, sampling_freq: float | None=None) -> None:
"""Args: frequency: frequency to be removed from the signal quality_factor: quality factor for ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SignalRemoveFrequency:
"""Remove a frequency from a signal"""
def __init__(self, frequency: float | None=None, quality_factor: float | None=None, sampling_freq: float | None=None) -> None:
"""Args: frequency: frequency to be removed from the signal quality_factor: quality factor for notch filter ... | the_stack_v2_python_sparse | monai/transforms/signal/array.py | Project-MONAI/MONAI | train | 4,805 |
903802845f80cf0335662140bae84750609ba452 | [
"flags.AddUsername(parser)\nflags.AddRegion(parser)\nflags.AddCluster(parser, False)\nflags.AddUserPassword(parser, True)",
"client = api_util.AlloyDBClient(self.ReleaseTrack())\nalloydb_client = client.alloydb_client\nalloydb_messages = client.alloydb_messages\nuser_ref = client.resource_parser.Create('alloydb.p... | <|body_start_0|>
flags.AddUsername(parser)
flags.AddRegion(parser)
flags.AddCluster(parser, False)
flags.AddUserPassword(parser, True)
<|end_body_0|>
<|body_start_1|>
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
allo... | Update an AlloyDB user's password within a given cluster and region. | Update | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Update:
"""Update an AlloyDB user's password within a given cluster and region."""
def Args(cls, parser):
"""Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs."""
<|body_0|>
def Run(self, args):
"""Constructs... | stack_v2_sparse_classes_10k_train_003322 | 2,620 | permissive | [
{
"docstring": "Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs.",
"name": "Args",
"signature": "def Args(cls, parser)"
},
{
"docstring": "Constructs and sends request. Args: args: argparse.Namespace, An object that contains the values for... | 2 | null | Implement the Python class `Update` described below.
Class description:
Update an AlloyDB user's password within a given cluster and region.
Method signatures and docstrings:
- def Args(cls, parser): Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs.
- def Run(se... | Implement the Python class `Update` described below.
Class description:
Update an AlloyDB user's password within a given cluster and region.
Method signatures and docstrings:
- def Args(cls, parser): Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs.
- def Run(se... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Update:
"""Update an AlloyDB user's password within a given cluster and region."""
def Args(cls, parser):
"""Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs."""
<|body_0|>
def Run(self, args):
"""Constructs... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Update:
"""Update an AlloyDB user's password within a given cluster and region."""
def Args(cls, parser):
"""Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs."""
flags.AddUsername(parser)
flags.AddRegion(parser)
flags... | the_stack_v2_python_sparse | lib/surface/alloydb/users/set_password.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
bea5c71ff4e8f4b1623fe68e7e5d54419a35d5fa | [
"self.args = arguments or {}\nself.uri = uri\nself.location = location\nsuper().__init__(**kwargs)",
"from git.repo import Repo\nref = self.__determine_git_ref()\ndir_name = '_'.join([self.sanitize_git_path(self.uri), ref])\ncached_dir_path = self.cache_dir / dir_name\nif cached_dir_path.exists():\n return cac... | <|body_start_0|>
self.args = arguments or {}
self.uri = uri
self.location = location
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
from git.repo import Repo
ref = self.__determine_git_ref()
dir_name = '_'.join([self.sanitize_git_path(self.uri), ref])... | Git Path Source. The Git path source can be tasked with cloning a remote repository and pointing to a specific module folder (or the root). | Git | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Git:
"""Git Path Source. The Git path source can be tasked with cloning a remote repository and pointing to a specific module folder (or the root)."""
def __init__(self, *, arguments: Optional[Dict[str, str]]=None, location: str='', uri: str='', **kwargs: Any) -> None:
"""Git Path So... | stack_v2_sparse_classes_10k_train_003323 | 4,143 | permissive | [
{
"docstring": "Git Path Source. Args: arguments: A reference can be passed along via the arguments so that a specific version of the repository is cloned. **commit**, **tag**, **branch** are all valid keys with respective output location: The relative location to the root of the repository where the module res... | 6 | stack_v2_sparse_classes_30k_train_007364 | Implement the Python class `Git` described below.
Class description:
Git Path Source. The Git path source can be tasked with cloning a remote repository and pointing to a specific module folder (or the root).
Method signatures and docstrings:
- def __init__(self, *, arguments: Optional[Dict[str, str]]=None, location:... | Implement the Python class `Git` described below.
Class description:
Git Path Source. The Git path source can be tasked with cloning a remote repository and pointing to a specific module folder (or the root).
Method signatures and docstrings:
- def __init__(self, *, arguments: Optional[Dict[str, str]]=None, location:... | 0763b06aee07d2cf3f037a49ca0cb81a048c5deb | <|skeleton|>
class Git:
"""Git Path Source. The Git path source can be tasked with cloning a remote repository and pointing to a specific module folder (or the root)."""
def __init__(self, *, arguments: Optional[Dict[str, str]]=None, location: str='', uri: str='', **kwargs: Any) -> None:
"""Git Path So... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Git:
"""Git Path Source. The Git path source can be tasked with cloning a remote repository and pointing to a specific module folder (or the root)."""
def __init__(self, *, arguments: Optional[Dict[str, str]]=None, location: str='', uri: str='', **kwargs: Any) -> None:
"""Git Path Source. Args: a... | the_stack_v2_python_sparse | runway/sources/git.py | onicagroup/runway | train | 156 |
aeb7f367b308b038e0e223872475cca9b121c1be | [
"config = configparser.ConfigParser()\nconfig.read(configfile, encoding='utf8')\nself.inception_password = config.get('inception', 'inception_password')\nself.inception_port = config['inception']['inception_port']\nself.inception_user = config['inception']['inception_user']\nself.inception_host = config['inception'... | <|body_start_0|>
config = configparser.ConfigParser()
config.read(configfile, encoding='utf8')
self.inception_password = config.get('inception', 'inception_password')
self.inception_port = config['inception']['inception_port']
self.inception_user = config['inception']['inception_... | inception使用 | InceptionClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InceptionClass:
"""inception使用"""
def __init__(self):
"""初始化函数,获取配置文件内容"""
<|body_0|>
def CheckSql(self, **kwargs):
""":param instance_host: 被执行SQL的实例地址 :param instance_port: 被执行SQL的实例端口 :param dbname: 被执行SQL的数据库名字 :param sql: 被执行的SQL内容 :return: 返回inception检查的结果"... | stack_v2_sparse_classes_10k_train_003324 | 3,658 | no_license | [
{
"docstring": "初始化函数,获取配置文件内容",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":param instance_host: 被执行SQL的实例地址 :param instance_port: 被执行SQL的实例端口 :param dbname: 被执行SQL的数据库名字 :param sql: 被执行的SQL内容 :return: 返回inception检查的结果",
"name": "CheckSql",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_007241 | Implement the Python class `InceptionClass` described below.
Class description:
inception使用
Method signatures and docstrings:
- def __init__(self): 初始化函数,获取配置文件内容
- def CheckSql(self, **kwargs): :param instance_host: 被执行SQL的实例地址 :param instance_port: 被执行SQL的实例端口 :param dbname: 被执行SQL的数据库名字 :param sql: 被执行的SQL内容 :retu... | Implement the Python class `InceptionClass` described below.
Class description:
inception使用
Method signatures and docstrings:
- def __init__(self): 初始化函数,获取配置文件内容
- def CheckSql(self, **kwargs): :param instance_host: 被执行SQL的实例地址 :param instance_port: 被执行SQL的实例端口 :param dbname: 被执行SQL的数据库名字 :param sql: 被执行的SQL内容 :retu... | f23fa1760d80a0c900a6b599c405cf7edef7a654 | <|skeleton|>
class InceptionClass:
"""inception使用"""
def __init__(self):
"""初始化函数,获取配置文件内容"""
<|body_0|>
def CheckSql(self, **kwargs):
""":param instance_host: 被执行SQL的实例地址 :param instance_port: 被执行SQL的实例端口 :param dbname: 被执行SQL的数据库名字 :param sql: 被执行的SQL内容 :return: 返回inception检查的结果"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InceptionClass:
"""inception使用"""
def __init__(self):
"""初始化函数,获取配置文件内容"""
config = configparser.ConfigParser()
config.read(configfile, encoding='utf8')
self.inception_password = config.get('inception', 'inception_password')
self.inception_port = config['inception'... | the_stack_v2_python_sparse | drf_api/app/instance/action.py | Rob-Bao/sqlaudit | train | 0 |
7f0d30328a2587dfa25eb079dba49795fdf3c61e | [
"params = dict()\nif Utils.is_containing_bracket(synapse_order):\n params = cls._associate_order_params_to_values(user_order, synapse_order)\n logger.debug('Parameters for order: %s' % params)\nreturn params",
"logger.debug('[OrderAnalyser._associate_order_params_to_values] user order: %s, order from synaps... | <|body_start_0|>
params = dict()
if Utils.is_containing_bracket(synapse_order):
params = cls._associate_order_params_to_values(user_order, synapse_order)
logger.debug('Parameters for order: %s' % params)
return params
<|end_body_0|>
<|body_start_1|>
logger.debug(... | NeuronParameterLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuronParameterLoader:
def get_parameters(cls, synapse_order, user_order):
"""Class method to get all params coming from a string order. Returns a dict of key/value."""
<|body_0|>
def _associate_order_params_to_values(cls, order, order_to_check):
"""Associate the var... | stack_v2_sparse_classes_10k_train_003325 | 2,737 | permissive | [
{
"docstring": "Class method to get all params coming from a string order. Returns a dict of key/value.",
"name": "get_parameters",
"signature": "def get_parameters(cls, synapse_order, user_order)"
},
{
"docstring": "Associate the variables from the order to the incoming user order :param order_... | 2 | stack_v2_sparse_classes_30k_train_002464 | Implement the Python class `NeuronParameterLoader` described below.
Class description:
Implement the NeuronParameterLoader class.
Method signatures and docstrings:
- def get_parameters(cls, synapse_order, user_order): Class method to get all params coming from a string order. Returns a dict of key/value.
- def _assoc... | Implement the Python class `NeuronParameterLoader` described below.
Class description:
Implement the NeuronParameterLoader class.
Method signatures and docstrings:
- def get_parameters(cls, synapse_order, user_order): Class method to get all params coming from a string order. Returns a dict of key/value.
- def _assoc... | cea86934e3474b4f944b77001f952285fe2f70bf | <|skeleton|>
class NeuronParameterLoader:
def get_parameters(cls, synapse_order, user_order):
"""Class method to get all params coming from a string order. Returns a dict of key/value."""
<|body_0|>
def _associate_order_params_to_values(cls, order, order_to_check):
"""Associate the var... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NeuronParameterLoader:
def get_parameters(cls, synapse_order, user_order):
"""Class method to get all params coming from a string order. Returns a dict of key/value."""
params = dict()
if Utils.is_containing_bracket(synapse_order):
params = cls._associate_order_params_to_va... | the_stack_v2_python_sparse | kalliope/core/NeuronParameterLoader.py | metal3d/kalliope | train | 1 | |
b5f32f84124af5ab1349b23a8d6ccc05ade5e833 | [
"super().__init__()\nself.predict_ntype = predict_ntype\nself.adapt_fcs = nn.ModuleDict({ntype: nn.Linear(in_dim, hidden_dim) for ntype, in_dim in in_dims.items()})\nself.layers = nn.ModuleList([HGTLayer(hidden_dim, hidden_dim, num_heads, ntypes, etypes, dropout, use_norm) for _ in range(num_layers)])\nself.predict... | <|body_start_0|>
super().__init__()
self.predict_ntype = predict_ntype
self.adapt_fcs = nn.ModuleDict({ntype: nn.Linear(in_dim, hidden_dim) for ntype, in_dim in in_dims.items()})
self.layers = nn.ModuleList([HGTLayer(hidden_dim, hidden_dim, num_heads, ntypes, etypes, dropout, use_norm) f... | HGT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HGT:
def __init__(self, in_dims, hidden_dim, out_dim, num_heads, ntypes, etypes, predict_ntype, num_layers, dropout=0.2, use_norm=True):
"""HGT模型 :param in_dims: Dict[str, int] 顶点类型到输入特征维数的映射 :param hidden_dim: int 隐含特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param nty... | stack_v2_sparse_classes_10k_train_003326 | 8,548 | no_license | [
{
"docstring": "HGT模型 :param in_dims: Dict[str, int] 顶点类型到输入特征维数的映射 :param hidden_dim: int 隐含特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param ntypes: List[str] 顶点类型列表 :param etypes: List[(str, str, str)] 规范边类型列表 :param predict_ntype: str 待预测顶点类型 :param num_layers: int 层数 :param dropout: dropo... | 2 | stack_v2_sparse_classes_30k_train_005074 | Implement the Python class `HGT` described below.
Class description:
Implement the HGT class.
Method signatures and docstrings:
- def __init__(self, in_dims, hidden_dim, out_dim, num_heads, ntypes, etypes, predict_ntype, num_layers, dropout=0.2, use_norm=True): HGT模型 :param in_dims: Dict[str, int] 顶点类型到输入特征维数的映射 :par... | Implement the Python class `HGT` described below.
Class description:
Implement the HGT class.
Method signatures and docstrings:
- def __init__(self, in_dims, hidden_dim, out_dim, num_heads, ntypes, etypes, predict_ntype, num_layers, dropout=0.2, use_norm=True): HGT模型 :param in_dims: Dict[str, int] 顶点类型到输入特征维数的映射 :par... | b40071dc9f9fb20f081f4ed4944a7b65de919c18 | <|skeleton|>
class HGT:
def __init__(self, in_dims, hidden_dim, out_dim, num_heads, ntypes, etypes, predict_ntype, num_layers, dropout=0.2, use_norm=True):
"""HGT模型 :param in_dims: Dict[str, int] 顶点类型到输入特征维数的映射 :param hidden_dim: int 隐含特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param nty... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HGT:
def __init__(self, in_dims, hidden_dim, out_dim, num_heads, ntypes, etypes, predict_ntype, num_layers, dropout=0.2, use_norm=True):
"""HGT模型 :param in_dims: Dict[str, int] 顶点类型到输入特征维数的映射 :param hidden_dim: int 隐含特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param ntypes: List[str]... | the_stack_v2_python_sparse | gnn/hgt/model.py | deepdumbo/pytorch-tutorial-1 | train | 0 | |
9950e1b66b76d8c0050628f88eff259315cf3609 | [
"super(WideDeep, self).__init__()\nself.cate_fea_size = len(cate_fea_uniques)\nself.num_fea_size = num_fea_size\nself.n_layers = 3\nself.n_filters = 12\nself.k = emb_size\nself.sparse_emb = nn.ModuleList([nn.Embedding(voc_size, emb_size) for voc_size in cate_fea_uniques])\nself.linear = nn.Linear(self.num_fea_size,... | <|body_start_0|>
super(WideDeep, self).__init__()
self.cate_fea_size = len(cate_fea_uniques)
self.num_fea_size = num_fea_size
self.n_layers = 3
self.n_filters = 12
self.k = emb_size
self.sparse_emb = nn.ModuleList([nn.Embedding(voc_size, emb_size) for voc_size in ... | WideDeep | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WideDeep:
def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], num_classes=1, dropout=[0.2, 0.2]):
""":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: :param hidden_dims: :param num_classes: :param dropout:"""
<|body_... | stack_v2_sparse_classes_10k_train_003327 | 5,176 | permissive | [
{
"docstring": ":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: :param hidden_dims: :param num_classes: :param dropout:",
"name": "__init__",
"signature": "def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], num_classes=1, dropout=[0.2, 0.... | 2 | null | Implement the Python class `WideDeep` described below.
Class description:
Implement the WideDeep class.
Method signatures and docstrings:
- def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], num_classes=1, dropout=[0.2, 0.2]): :param cate_fea_uniques: :param num_fea_size: 数字特征 也就... | Implement the Python class `WideDeep` described below.
Class description:
Implement the WideDeep class.
Method signatures and docstrings:
- def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], num_classes=1, dropout=[0.2, 0.2]): :param cate_fea_uniques: :param num_fea_size: 数字特征 也就... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class WideDeep:
def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], num_classes=1, dropout=[0.2, 0.2]):
""":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: :param hidden_dims: :param num_classes: :param dropout:"""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WideDeep:
def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], num_classes=1, dropout=[0.2, 0.2]):
""":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: :param hidden_dims: :param num_classes: :param dropout:"""
super(WideDeep, self)... | the_stack_v2_python_sparse | PyTorch/dev/others/Widedeep_ID2866_for_PyTorch/WideDeep/model.py | Ascend/ModelZoo-PyTorch | train | 23 | |
92c592b1c1b9a0fbb0d703e41acb399017898dcb | [
"s = login_xadmin\ndetails = Contract_details(s, contractNo=20090900006)\nassert details['data']['baseInfo']['contractNo'] == 20090900006\nassert details['success'] == True",
"s = login_xadmin\ndetails = Contract_details(s, contractNo=200909000)\nassert details['success'] == False\nprint('66666666')\nassert '未搵到該... | <|body_start_0|>
s = login_xadmin
details = Contract_details(s, contractNo=20090900006)
assert details['data']['baseInfo']['contractNo'] == 20090900006
assert details['success'] == True
<|end_body_0|>
<|body_start_1|>
s = login_xadmin
details = Contract_details(s, contra... | 合同详情信息查询 | Test_Contract_details | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_Contract_details:
"""合同详情信息查询"""
def test_Contract_details_34(self, login_xadmin):
"""验证输入有效的合同编号,可对合同详情信息进行查询"""
<|body_0|>
def test_Contract_details_35(self, login_xadmin):
"""验证输入无效的合同编号,查询的合同为空"""
<|body_1|>
def test_Contract_details_36(self... | stack_v2_sparse_classes_10k_train_003328 | 20,573 | no_license | [
{
"docstring": "验证输入有效的合同编号,可对合同详情信息进行查询",
"name": "test_Contract_details_34",
"signature": "def test_Contract_details_34(self, login_xadmin)"
},
{
"docstring": "验证输入无效的合同编号,查询的合同为空",
"name": "test_Contract_details_35",
"signature": "def test_Contract_details_35(self, login_xadmin)"
},... | 3 | stack_v2_sparse_classes_30k_train_007181 | Implement the Python class `Test_Contract_details` described below.
Class description:
合同详情信息查询
Method signatures and docstrings:
- def test_Contract_details_34(self, login_xadmin): 验证输入有效的合同编号,可对合同详情信息进行查询
- def test_Contract_details_35(self, login_xadmin): 验证输入无效的合同编号,查询的合同为空
- def test_Contract_details_36(self, lo... | Implement the Python class `Test_Contract_details` described below.
Class description:
合同详情信息查询
Method signatures and docstrings:
- def test_Contract_details_34(self, login_xadmin): 验证输入有效的合同编号,可对合同详情信息进行查询
- def test_Contract_details_35(self, login_xadmin): 验证输入无效的合同编号,查询的合同为空
- def test_Contract_details_36(self, lo... | 196ebbddaad6ee2acaf6b2b6ba40c856af2a35c3 | <|skeleton|>
class Test_Contract_details:
"""合同详情信息查询"""
def test_Contract_details_34(self, login_xadmin):
"""验证输入有效的合同编号,可对合同详情信息进行查询"""
<|body_0|>
def test_Contract_details_35(self, login_xadmin):
"""验证输入无效的合同编号,查询的合同为空"""
<|body_1|>
def test_Contract_details_36(self... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test_Contract_details:
"""合同详情信息查询"""
def test_Contract_details_34(self, login_xadmin):
"""验证输入有效的合同编号,可对合同详情信息进行查询"""
s = login_xadmin
details = Contract_details(s, contractNo=20090900006)
assert details['data']['baseInfo']['contractNo'] == 20090900006
assert deta... | the_stack_v2_python_sparse | case/VC_project/Annual_contract/test_annual_contract.py | wuyouyaun/django_templte | train | 0 |
75464d33be402e7a31e2b28c92d89bee016dbe37 | [
"self.modified_coeff = modified_coeff\nself.a = a\nself.b = b",
"ans = 0\nfor coeff in self.modified_coeff:\n ans *= x\n ans += coeff\nreturn ans"
] | <|body_start_0|>
self.modified_coeff = modified_coeff
self.a = a
self.b = b
<|end_body_0|>
<|body_start_1|>
ans = 0
for coeff in self.modified_coeff:
ans *= x
ans += coeff
return ans
<|end_body_1|>
| SievePolynomial | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SievePolynomial:
def __init__(self, modified_coeff=(), a=None, b=None):
"""This class denotes the seive polynomial. If ``g(x) = (a*x + b)**2 - N``. `g(x)` can be expanded to ``a*x**2 + 2*a*b*x + b**2 - N``, so the coefficient is stored in the form `[a**2, 2*a*b, b**2 - N]`. This ensures ... | stack_v2_sparse_classes_10k_train_003329 | 18,360 | permissive | [
{
"docstring": "This class denotes the seive polynomial. If ``g(x) = (a*x + b)**2 - N``. `g(x)` can be expanded to ``a*x**2 + 2*a*b*x + b**2 - N``, so the coefficient is stored in the form `[a**2, 2*a*b, b**2 - N]`. This ensures faster `eval` method because we dont have to perform `a**2, 2*a*b, b**2` every time... | 2 | null | Implement the Python class `SievePolynomial` described below.
Class description:
Implement the SievePolynomial class.
Method signatures and docstrings:
- def __init__(self, modified_coeff=(), a=None, b=None): This class denotes the seive polynomial. If ``g(x) = (a*x + b)**2 - N``. `g(x)` can be expanded to ``a*x**2 +... | Implement the Python class `SievePolynomial` described below.
Class description:
Implement the SievePolynomial class.
Method signatures and docstrings:
- def __init__(self, modified_coeff=(), a=None, b=None): This class denotes the seive polynomial. If ``g(x) = (a*x + b)**2 - N``. `g(x)` can be expanded to ``a*x**2 +... | 69f98fb2b0d845e76874067a381dba37b577e8c5 | <|skeleton|>
class SievePolynomial:
def __init__(self, modified_coeff=(), a=None, b=None):
"""This class denotes the seive polynomial. If ``g(x) = (a*x + b)**2 - N``. `g(x)` can be expanded to ``a*x**2 + 2*a*b*x + b**2 - N``, so the coefficient is stored in the form `[a**2, 2*a*b, b**2 - N]`. This ensures ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SievePolynomial:
def __init__(self, modified_coeff=(), a=None, b=None):
"""This class denotes the seive polynomial. If ``g(x) = (a*x + b)**2 - N``. `g(x)` can be expanded to ``a*x**2 + 2*a*b*x + b**2 - N``, so the coefficient is stored in the form `[a**2, 2*a*b, b**2 - N]`. This ensures faster `eval` ... | the_stack_v2_python_sparse | sympy/ntheory/qs.py | sympy/sympy | train | 10,928 | |
4860c833e40934d1965efedb528f15911f820ba4 | [
"self.noise = noise\nif seed != -1:\n numpy.random.seed(seed)",
"if self.noise == 0:\n return\ninputSize = data.size\nflipBits = numpy.random.randint(0, inputSize, self.noise * inputSize)\ndata[flipBits] = numpy.logical_not(data[flipBits])"
] | <|body_start_0|>
self.noise = noise
if seed != -1:
numpy.random.seed(seed)
<|end_body_0|>
<|body_start_1|>
if self.noise == 0:
return
inputSize = data.size
flipBits = numpy.random.randint(0, inputSize, self.noise * inputSize)
data[flipBits] = nump... | This RecordSensor filter adds noise to the input | AddNoise | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddNoise:
"""This RecordSensor filter adds noise to the input"""
def __init__(self, noise=0.0, seed=-1):
"""Construct the filter Parameters: ------------------------------------------------- noise: Amount of noise to add, from 0 to 1.0"""
<|body_0|>
def process(self, enc... | stack_v2_sparse_classes_10k_train_003330 | 1,686 | no_license | [
{
"docstring": "Construct the filter Parameters: ------------------------------------------------- noise: Amount of noise to add, from 0 to 1.0",
"name": "__init__",
"signature": "def __init__(self, noise=0.0, seed=-1)"
},
{
"docstring": "Modify the data in place, adding noise",
"name": "pro... | 2 | null | Implement the Python class `AddNoise` described below.
Class description:
This RecordSensor filter adds noise to the input
Method signatures and docstrings:
- def __init__(self, noise=0.0, seed=-1): Construct the filter Parameters: ------------------------------------------------- noise: Amount of noise to add, from ... | Implement the Python class `AddNoise` described below.
Class description:
This RecordSensor filter adds noise to the input
Method signatures and docstrings:
- def __init__(self, noise=0.0, seed=-1): Construct the filter Parameters: ------------------------------------------------- noise: Amount of noise to add, from ... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class AddNoise:
"""This RecordSensor filter adds noise to the input"""
def __init__(self, noise=0.0, seed=-1):
"""Construct the filter Parameters: ------------------------------------------------- noise: Amount of noise to add, from 0 to 1.0"""
<|body_0|>
def process(self, enc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AddNoise:
"""This RecordSensor filter adds noise to the input"""
def __init__(self, noise=0.0, seed=-1):
"""Construct the filter Parameters: ------------------------------------------------- noise: Amount of noise to add, from 0 to 1.0"""
self.noise = noise
if seed != -1:
... | the_stack_v2_python_sparse | python/numenta_nupic/nupic-master/src/nupic/regions/RecordSensorFilters/AddNoise.py | LiuFang816/SALSTM_py_data | train | 10 |
9255d3e6c8a5225f3c6444051b220bf9674194dd | [
"stock_move_line = self.env['stock.move.line'].search([('reference', '=', self.name)])\nfor line in stock_move_line:\n if line.lot_id:\n stock = self.env['stock.quant'].search([('quantity', '>', 0), ('lot_id', '=', line.lot_id.id)])\n line.lot_id.qty_location = [(5, 0, 0)]\n if len(stock.ids... | <|body_start_0|>
stock_move_line = self.env['stock.move.line'].search([('reference', '=', self.name)])
for line in stock_move_line:
if line.lot_id:
stock = self.env['stock.quant'].search([('quantity', '>', 0), ('lot_id', '=', line.lot_id.id)])
line.lot_id.qty_... | class_name: FlspMrpProductionFilterSn inherit: mrp.production Purpose: To change the stock.production.lot field qty_location when consumed in MO Date: Mar/29th/2021/M Author: Sami Byaruhanga | FlspMrpProductionFilterSn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlspMrpProductionFilterSn:
"""class_name: FlspMrpProductionFilterSn inherit: mrp.production Purpose: To change the stock.production.lot field qty_location when consumed in MO Date: Mar/29th/2021/M Author: Sami Byaruhanga"""
def change_product_qty_in_lot_table(self):
"""Purpose: To ch... | stack_v2_sparse_classes_10k_train_003331 | 7,672 | no_license | [
{
"docstring": "Purpose: To change the location name on the lot Note: Did not call the method in lot coz, we had to filter the lots to those Used only in the manufacturing order. Did this to make the run time quicker",
"name": "change_product_qty_in_lot_table",
"signature": "def change_product_qty_in_lo... | 2 | null | Implement the Python class `FlspMrpProductionFilterSn` described below.
Class description:
class_name: FlspMrpProductionFilterSn inherit: mrp.production Purpose: To change the stock.production.lot field qty_location when consumed in MO Date: Mar/29th/2021/M Author: Sami Byaruhanga
Method signatures and docstrings:
- ... | Implement the Python class `FlspMrpProductionFilterSn` described below.
Class description:
class_name: FlspMrpProductionFilterSn inherit: mrp.production Purpose: To change the stock.production.lot field qty_location when consumed in MO Date: Mar/29th/2021/M Author: Sami Byaruhanga
Method signatures and docstrings:
- ... | 4a82cd5cfd1898c6da860cb68dff3a14e037bbad | <|skeleton|>
class FlspMrpProductionFilterSn:
"""class_name: FlspMrpProductionFilterSn inherit: mrp.production Purpose: To change the stock.production.lot field qty_location when consumed in MO Date: Mar/29th/2021/M Author: Sami Byaruhanga"""
def change_product_qty_in_lot_table(self):
"""Purpose: To ch... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FlspMrpProductionFilterSn:
"""class_name: FlspMrpProductionFilterSn inherit: mrp.production Purpose: To change the stock.production.lot field qty_location when consumed in MO Date: Mar/29th/2021/M Author: Sami Byaruhanga"""
def change_product_qty_in_lot_table(self):
"""Purpose: To change the loca... | the_stack_v2_python_sparse | flsp_mrp_filter_sn/models/filter_sn_method.py | odoo-smg/firstlight | train | 3 |
7f2af0ebde25c221a0a63c207324e765d46e704c | [
"super(SVRenderLayer, self).__init__()\nself.layer = render_layer\nself.camera = camera\nself.keep = keep_output\nself.attr = attr",
"self.layer.renderer.eye = self.camera\nself.layer.renderer.light_direction = -self.camera\nout = self.layer(input)\nif self.keep:\n setattr(input, self.attr, out)\nreturn out"
] | <|body_start_0|>
super(SVRenderLayer, self).__init__()
self.layer = render_layer
self.camera = camera
self.keep = keep_output
self.attr = attr
<|end_body_0|>
<|body_start_1|>
self.layer.renderer.eye = self.camera
self.layer.renderer.light_direction = -self.camera... | A class representing a signle view rendering layer Attributes ---------- layer : RenderLayer a rendering layer camera : Tensor the positions of the camera keep : bool if True keeps the output in an attribute of the input data attr : str the name of the attribute to store the output to Methods ------- forward(input) ret... | SVRenderLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SVRenderLayer:
"""A class representing a signle view rendering layer Attributes ---------- layer : RenderLayer a rendering layer camera : Tensor the positions of the camera keep : bool if True keeps the output in an attribute of the input data attr : str the name of the attribute to store the out... | stack_v2_sparse_classes_10k_train_003332 | 9,441 | permissive | [
{
"docstring": "Parameters ---------- render_layer : RenderLayer a rendering layer camera : Tensor the positions of the camera keep_output : bool (optional) if True keeps the output in an attribute of the input data (default is False) attr : str (optional) the name of the attribute to store the output to (defau... | 2 | stack_v2_sparse_classes_30k_train_006378 | Implement the Python class `SVRenderLayer` described below.
Class description:
A class representing a signle view rendering layer Attributes ---------- layer : RenderLayer a rendering layer camera : Tensor the positions of the camera keep : bool if True keeps the output in an attribute of the input data attr : str the... | Implement the Python class `SVRenderLayer` described below.
Class description:
A class representing a signle view rendering layer Attributes ---------- layer : RenderLayer a rendering layer camera : Tensor the positions of the camera keep : bool if True keeps the output in an attribute of the input data attr : str the... | 2615b66dd4addfd5c03d9d91a24c7da414294308 | <|skeleton|>
class SVRenderLayer:
"""A class representing a signle view rendering layer Attributes ---------- layer : RenderLayer a rendering layer camera : Tensor the positions of the camera keep : bool if True keeps the output in an attribute of the input data attr : str the name of the attribute to store the out... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SVRenderLayer:
"""A class representing a signle view rendering layer Attributes ---------- layer : RenderLayer a rendering layer camera : Tensor the positions of the camera keep : bool if True keeps the output in an attribute of the input data attr : str the name of the attribute to store the output to Method... | the_stack_v2_python_sparse | ACME/layer/RenderLayer.py | mauriziokovacic/ACME | train | 3 |
ab2c0e1dc13e27ad74cd5f4c6d55a490f3960a96 | [
"self.logger = logging.getLogger(VisualAppearanceFeatureTransformer.__name__)\nself.device = get_device()\nself.use_masks = use_masks\nself.input_type = input_type\nself.reduced_size = reduced_size",
"if self.use_masks and all_masks is None:\n raise RuntimeError('No masks are provided but transformer has use_m... | <|body_start_0|>
self.logger = logging.getLogger(VisualAppearanceFeatureTransformer.__name__)
self.device = get_device()
self.use_masks = use_masks
self.input_type = input_type
self.reduced_size = reduced_size
<|end_body_0|>
<|body_start_1|>
if self.use_masks and all_mas... | VisualAppearanceFeatureTransformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisualAppearanceFeatureTransformer:
def __init__(self, input_type='default', reduced_size=64, use_masks=False, **kwargs):
"""Parent class for visual appearance feature transformers. :param input_type: Input type for the auto encoder. If 'default', then an object region is cut out. If 'bl... | stack_v2_sparse_classes_10k_train_003333 | 6,881 | no_license | [
{
"docstring": "Parent class for visual appearance feature transformers. :param input_type: Input type for the auto encoder. If 'default', then an object region is cut out. If 'blacked', then the image is blacked except for the object region. Default: 'default' :param reduced_size: Size to which inputs are scal... | 5 | stack_v2_sparse_classes_30k_train_006831 | Implement the Python class `VisualAppearanceFeatureTransformer` described below.
Class description:
Implement the VisualAppearanceFeatureTransformer class.
Method signatures and docstrings:
- def __init__(self, input_type='default', reduced_size=64, use_masks=False, **kwargs): Parent class for visual appearance featu... | Implement the Python class `VisualAppearanceFeatureTransformer` described below.
Class description:
Implement the VisualAppearanceFeatureTransformer class.
Method signatures and docstrings:
- def __init__(self, input_type='default', reduced_size=64, use_masks=False, **kwargs): Parent class for visual appearance featu... | 259fff9b7576055ba1534375de859f8708f79337 | <|skeleton|>
class VisualAppearanceFeatureTransformer:
def __init__(self, input_type='default', reduced_size=64, use_masks=False, **kwargs):
"""Parent class for visual appearance feature transformers. :param input_type: Input type for the auto encoder. If 'default', then an object region is cut out. If 'bl... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VisualAppearanceFeatureTransformer:
def __init__(self, input_type='default', reduced_size=64, use_masks=False, **kwargs):
"""Parent class for visual appearance feature transformers. :param input_type: Input type for the auto encoder. If 'default', then an object region is cut out. If 'blacked', then t... | the_stack_v2_python_sparse | iorank/featuretransformation/visual_appearance_feature_transformer.py | fweiland8/iorank | train | 3 | |
e3685d5e705d429cc8cddd3d16edb7631f2047bf | [
"serialized = pickle.dumps(obj)\nif cls.COMPRESSION_CUTOFF_LEN and len(serialized) > cls.COMPRESSION_CUTOFF_LEN:\n serialized = cls.ZLIB_COMPRESSED_HEADER + zlib.compress(serialized)\nreturn serialized",
"if obj[:len(cls.ZLIB_COMPRESSED_HEADER)] == cls.ZLIB_COMPRESSED_HEADER:\n obj = zlib.decompress(obj[len... | <|body_start_0|>
serialized = pickle.dumps(obj)
if cls.COMPRESSION_CUTOFF_LEN and len(serialized) > cls.COMPRESSION_CUTOFF_LEN:
serialized = cls.ZLIB_COMPRESSED_HEADER + zlib.compress(serialized)
return serialized
<|end_body_0|>
<|body_start_1|>
if obj[:len(cls.ZLIB_COMPRESS... | PickleSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PickleSerializer:
def _serialize(cls, obj):
"""Common serialization for storing objects in cache. If the object is huge, it will be transparently compressed."""
<|body_0|>
def _deserialize(cls, obj):
"""Common deserialization for fetching objects from cache. `obj` mu... | stack_v2_sparse_classes_10k_train_003334 | 3,420 | no_license | [
{
"docstring": "Common serialization for storing objects in cache. If the object is huge, it will be transparently compressed.",
"name": "_serialize",
"signature": "def _serialize(cls, obj)"
},
{
"docstring": "Common deserialization for fetching objects from cache. `obj` must be not-None. Handle... | 2 | stack_v2_sparse_classes_30k_train_005285 | Implement the Python class `PickleSerializer` described below.
Class description:
Implement the PickleSerializer class.
Method signatures and docstrings:
- def _serialize(cls, obj): Common serialization for storing objects in cache. If the object is huge, it will be transparently compressed.
- def _deserialize(cls, o... | Implement the Python class `PickleSerializer` described below.
Class description:
Implement the PickleSerializer class.
Method signatures and docstrings:
- def _serialize(cls, obj): Common serialization for storing objects in cache. If the object is huge, it will be transparently compressed.
- def _deserialize(cls, o... | dcc66feed986b8970c5e8827107c075e6655b692 | <|skeleton|>
class PickleSerializer:
def _serialize(cls, obj):
"""Common serialization for storing objects in cache. If the object is huge, it will be transparently compressed."""
<|body_0|>
def _deserialize(cls, obj):
"""Common deserialization for fetching objects from cache. `obj` mu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PickleSerializer:
def _serialize(cls, obj):
"""Common serialization for storing objects in cache. If the object is huge, it will be transparently compressed."""
serialized = pickle.dumps(obj)
if cls.COMPRESSION_CUTOFF_LEN and len(serialized) > cls.COMPRESSION_CUTOFF_LEN:
se... | the_stack_v2_python_sparse | pypipes/service/base_client.py | vani-public/pipes | train | 3 | |
397712fb8f2369fc535f77090b6f6264002cb1f0 | [
"result = []\n\ndef preorderDFS(node, result):\n if not node:\n result += ['#']\n return\n result += [str(node.val)]\n preorderDFS(node.left, result)\n preorderDFS(node.right, result)\npreorderDFS(root, result)\nreturn ' '.join(result)",
"serial_tree = data.split(' ')\n\ndef constructTre... | <|body_start_0|>
result = []
def preorderDFS(node, result):
if not node:
result += ['#']
return
result += [str(node.val)]
preorderDFS(node.left, result)
preorderDFS(node.right, result)
preorderDFS(root, result)
... | Codec_II | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec_II:
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|>
<|bo... | stack_v2_sparse_classes_10k_train_003335 | 2,710 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec_II` described below.
Class description:
Implement the Codec_II 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 :... | Implement the Python class `Codec_II` described below.
Class description:
Implement the Codec_II 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 :... | 1461b10b8910fa90a311939c6df9082a8526f9b1 | <|skeleton|>
class Codec_II:
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_10k | data/stack_v2_sparse_classes_30k | class Codec_II:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
result = []
def preorderDFS(node, result):
if not node:
result += ['#']
return
result += [str(node.val)]
p... | the_stack_v2_python_sparse | Hard/297_serialize&DeserializeBinaryTree.py | Yucheng7713/CodingPracticeByYuch | train | 0 | |
b9d3c82cc5afd29e76b63012ce67187dff1ec233 | [
"self.copy_snapshot_tasks = copy_snapshot_tasks\nself.data_lock_constraints = data_lock_constraints\nself.error = error\nself.expiry_time_usecs = expiry_time_usecs\nself.hold_for_legal_purpose = hold_for_legal_purpose\nself.legal_holdings = legal_holdings\nself.run_start_time_usecs = run_start_time_usecs\nself.stat... | <|body_start_0|>
self.copy_snapshot_tasks = copy_snapshot_tasks
self.data_lock_constraints = data_lock_constraints
self.error = error
self.expiry_time_usecs = expiry_time_usecs
self.hold_for_legal_purpose = hold_for_legal_purpose
self.legal_holdings = legal_holdings
... | Implementation of the 'CopyRun' model. Specifies details about the Copy Run for a backup run of a Job Run. A Copy task copies snapshots resulted from a backup run to a snapshot target which could be 'kLocal', 'kArchival', or 'kRemote'. Attributes: copy_snapshot_tasks (list of CopySnapshotTaskStatus): Specifies the stat... | CopyRun | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CopyRun:
"""Implementation of the 'CopyRun' model. Specifies details about the Copy Run for a backup run of a Job Run. A Copy task copies snapshots resulted from a backup run to a snapshot target which could be 'kLocal', 'kArchival', or 'kRemote'. Attributes: copy_snapshot_tasks (list of CopySnap... | stack_v2_sparse_classes_10k_train_003336 | 7,628 | permissive | [
{
"docstring": "Constructor for the CopyRun class",
"name": "__init__",
"signature": "def __init__(self, copy_snapshot_tasks=None, data_lock_constraints=None, error=None, expiry_time_usecs=None, hold_for_legal_purpose=None, legal_holdings=None, run_start_time_usecs=None, stats=None, status=None, target=... | 2 | null | Implement the Python class `CopyRun` described below.
Class description:
Implementation of the 'CopyRun' model. Specifies details about the Copy Run for a backup run of a Job Run. A Copy task copies snapshots resulted from a backup run to a snapshot target which could be 'kLocal', 'kArchival', or 'kRemote'. Attributes... | Implement the Python class `CopyRun` described below.
Class description:
Implementation of the 'CopyRun' model. Specifies details about the Copy Run for a backup run of a Job Run. A Copy task copies snapshots resulted from a backup run to a snapshot target which could be 'kLocal', 'kArchival', or 'kRemote'. Attributes... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CopyRun:
"""Implementation of the 'CopyRun' model. Specifies details about the Copy Run for a backup run of a Job Run. A Copy task copies snapshots resulted from a backup run to a snapshot target which could be 'kLocal', 'kArchival', or 'kRemote'. Attributes: copy_snapshot_tasks (list of CopySnap... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CopyRun:
"""Implementation of the 'CopyRun' model. Specifies details about the Copy Run for a backup run of a Job Run. A Copy task copies snapshots resulted from a backup run to a snapshot target which could be 'kLocal', 'kArchival', or 'kRemote'. Attributes: copy_snapshot_tasks (list of CopySnapshotTaskStatu... | the_stack_v2_python_sparse | cohesity_management_sdk/models/copy_run.py | cohesity/management-sdk-python | train | 24 |
d295f56e7d03aad68ac25921d46879b8b8e5e39d | [
"super(AttentionalDecoder, self).__init__(output_size, hidden_size, embedding_dim, max_length, enc_dim, device, dropout_p, pad_token)\nself._gru = nn.GRU(input_size=self._embedding_dim + self._enc_dim, hidden_size=self._hidden_size)\nself._attention = AdditiveAttention(key_dim=self._enc_dim, value_dim=self._enc_dim... | <|body_start_0|>
super(AttentionalDecoder, self).__init__(output_size, hidden_size, embedding_dim, max_length, enc_dim, device, dropout_p, pad_token)
self._gru = nn.GRU(input_size=self._embedding_dim + self._enc_dim, hidden_size=self._hidden_size)
self._attention = AdditiveAttention(key_dim=self... | AttentionalDecoder | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentionalDecoder:
def __init__(self, hidden_size, output_size, embedding_dim, max_length, enc_dim, device, dropout_p=0.1, pad_token=0):
""":param embedding_dim: dimension of :param hidden_size: :param output_size: :param max_length: :param device: :param dropout_p:"""
<|body_0|... | stack_v2_sparse_classes_10k_train_003337 | 2,837 | permissive | [
{
"docstring": ":param embedding_dim: dimension of :param hidden_size: :param output_size: :param max_length: :param device: :param dropout_p:",
"name": "__init__",
"signature": "def __init__(self, hidden_size, output_size, embedding_dim, max_length, enc_dim, device, dropout_p=0.1, pad_token=0)"
},
... | 2 | stack_v2_sparse_classes_30k_train_006415 | Implement the Python class `AttentionalDecoder` described below.
Class description:
Implement the AttentionalDecoder class.
Method signatures and docstrings:
- def __init__(self, hidden_size, output_size, embedding_dim, max_length, enc_dim, device, dropout_p=0.1, pad_token=0): :param embedding_dim: dimension of :para... | Implement the Python class `AttentionalDecoder` described below.
Class description:
Implement the AttentionalDecoder class.
Method signatures and docstrings:
- def __init__(self, hidden_size, output_size, embedding_dim, max_length, enc_dim, device, dropout_p=0.1, pad_token=0): :param embedding_dim: dimension of :para... | 689b9924d3c88a433f8f350b89c13a878ac7d7c3 | <|skeleton|>
class AttentionalDecoder:
def __init__(self, hidden_size, output_size, embedding_dim, max_length, enc_dim, device, dropout_p=0.1, pad_token=0):
""":param embedding_dim: dimension of :param hidden_size: :param output_size: :param max_length: :param device: :param dropout_p:"""
<|body_0|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AttentionalDecoder:
def __init__(self, hidden_size, output_size, embedding_dim, max_length, enc_dim, device, dropout_p=0.1, pad_token=0):
""":param embedding_dim: dimension of :param hidden_size: :param output_size: :param max_length: :param device: :param dropout_p:"""
super(AttentionalDecode... | the_stack_v2_python_sparse | nntoolbox/sequence/models/decoder.py | nhatsmrt/nn-toolbox | train | 19 | |
0ccbe8cf9e20ca38114ece312ac4aa7d55fb2611 | [
"super().__init__()\nself.embed, self.encoders, self.enc_out, self.conv_subsampling_factor = build_blocks('encoder', idim, input_layer, enc_arch, repeat_block=repeat_block, self_attn_type=self_attn_type, positional_encoding_type=positional_encoding_type, positionwise_layer_type=positionwise_layer_type, positionwise... | <|body_start_0|>
super().__init__()
self.embed, self.encoders, self.enc_out, self.conv_subsampling_factor = build_blocks('encoder', idim, input_layer, enc_arch, repeat_block=repeat_block, self_attn_type=self_attn_type, positional_encoding_type=positional_encoding_type, positionwise_layer_type=positionwi... | Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self-attention type. positional_encoding_type: Positional encoding type. positionwis... | CustomEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomEncoder:
"""Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self-attention type. positional_encoding_ty... | stack_v2_sparse_classes_10k_train_003338 | 4,661 | permissive | [
{
"docstring": "Construct an CustomEncoder object.",
"name": "__init__",
"signature": "def __init__(self, idim: int, enc_arch: List, input_layer: str='linear', repeat_block: int=1, self_attn_type: str='selfattn', positional_encoding_type: str='abs_pos', positionwise_layer_type: str='linear', positionwis... | 2 | stack_v2_sparse_classes_30k_train_000242 | Implement the Python class `CustomEncoder` described below.
Class description:
Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self... | Implement the Python class `CustomEncoder` described below.
Class description:
Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class CustomEncoder:
"""Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self-attention type. positional_encoding_ty... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomEncoder:
"""Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self-attention type. positional_encoding_type: Positiona... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transducer/custom_encoder.py | espnet/espnet | train | 7,242 |
6308c615f1eaf57354b82a4af1a81cc9abd796b1 | [
"self.__function = function\nself.__args = args\nself.__kwargs = kwargs\nself.__status = False\nself.__thread = False\nself.__lock = _thread.allocate_lock()",
"self.__lock.acquire()\nself.__status = True\nif not self.__thread:\n self.__thread = True\n _thread.start_new_thread(self.__run, ())\nself.__lock.re... | <|body_start_0|>
self.__function = function
self.__args = args
self.__kwargs = kwargs
self.__status = False
self.__thread = False
self.__lock = _thread.allocate_lock()
<|end_body_0|>
<|body_start_1|>
self.__lock.acquire()
self.__status = True
if n... | Mille_Timer(function, *args, **kwargs) -> Mille Timer | Mille_Timer | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mille_Timer:
"""Mille_Timer(function, *args, **kwargs) -> Mille Timer"""
def __init__(self, function, *args, **kwargs):
"""Initialize the Mille_Timer object."""
<|body_0|>
def start(self):
"""Start the Mille_Timer object."""
<|body_1|>
def stop(self)... | stack_v2_sparse_classes_10k_train_003339 | 3,709 | permissive | [
{
"docstring": "Initialize the Mille_Timer object.",
"name": "__init__",
"signature": "def __init__(self, function, *args, **kwargs)"
},
{
"docstring": "Start the Mille_Timer object.",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "Stop the Mille_Timer object.... | 4 | stack_v2_sparse_classes_30k_train_002429 | Implement the Python class `Mille_Timer` described below.
Class description:
Mille_Timer(function, *args, **kwargs) -> Mille Timer
Method signatures and docstrings:
- def __init__(self, function, *args, **kwargs): Initialize the Mille_Timer object.
- def start(self): Start the Mille_Timer object.
- def stop(self): St... | Implement the Python class `Mille_Timer` described below.
Class description:
Mille_Timer(function, *args, **kwargs) -> Mille Timer
Method signatures and docstrings:
- def __init__(self, function, *args, **kwargs): Initialize the Mille_Timer object.
- def start(self): Start the Mille_Timer object.
- def stop(self): St... | d097ca0ad6a6aee2180d32dce6a3322621f655fd | <|skeleton|>
class Mille_Timer:
"""Mille_Timer(function, *args, **kwargs) -> Mille Timer"""
def __init__(self, function, *args, **kwargs):
"""Initialize the Mille_Timer object."""
<|body_0|>
def start(self):
"""Start the Mille_Timer object."""
<|body_1|>
def stop(self)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Mille_Timer:
"""Mille_Timer(function, *args, **kwargs) -> Mille Timer"""
def __init__(self, function, *args, **kwargs):
"""Initialize the Mille_Timer object."""
self.__function = function
self.__args = args
self.__kwargs = kwargs
self.__status = False
self.... | the_stack_v2_python_sparse | recipes/Python/502238_Aens_Time/recipe-502238.py | betty29/code-1 | train | 0 |
54f166f08813310ce20a7b5ee504de8323429b3e | [
"team_list = list(Southerner.objects.by_season(season))\nif len(team_list) > 0:\n rank = 1\n previous = team_list[0]\n previous.rank = 1\n for i, entry in enumerate(team_list[1:]):\n if entry.avg_points_per_game != previous.avg_points_per_game:\n rank = i + 2\n entry.rank = ... | <|body_start_0|>
team_list = list(Southerner.objects.by_season(season))
if len(team_list) > 0:
rank = 1
previous = team_list[0]
previous.rank = 1
for i, entry in enumerate(team_list[1:]):
if entry.avg_points_per_game != previous.avg_points_... | View for displaying the Southerners League stats for a particular season | SouthernersSeasonView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SouthernersSeasonView:
"""View for displaying the Southerners League stats for a particular season"""
def get_southerners_list(self, season):
"""Returns a list of Southerners League items for the specified season"""
<|body_0|>
def get_context_data(self, **kwargs):
... | stack_v2_sparse_classes_10k_train_003340 | 7,907 | no_license | [
{
"docstring": "Returns a list of Southerners League items for the specified season",
"name": "get_southerners_list",
"signature": "def get_southerners_list(self, season)"
},
{
"docstring": "Gets the context data for the view. In addition to the 'team_list' item, the following are also added to ... | 2 | null | Implement the Python class `SouthernersSeasonView` described below.
Class description:
View for displaying the Southerners League stats for a particular season
Method signatures and docstrings:
- def get_southerners_list(self, season): Returns a list of Southerners League items for the specified season
- def get_cont... | Implement the Python class `SouthernersSeasonView` described below.
Class description:
View for displaying the Southerners League stats for a particular season
Method signatures and docstrings:
- def get_southerners_list(self, season): Returns a list of Southerners League items for the specified season
- def get_cont... | d85aa4522c4ffa603efa9e8625fc7253fb7550b5 | <|skeleton|>
class SouthernersSeasonView:
"""View for displaying the Southerners League stats for a particular season"""
def get_southerners_list(self, season):
"""Returns a list of Southerners League items for the specified season"""
<|body_0|>
def get_context_data(self, **kwargs):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SouthernersSeasonView:
"""View for displaying the Southerners League stats for a particular season"""
def get_southerners_list(self, season):
"""Returns a list of Southerners League items for the specified season"""
team_list = list(Southerner.objects.by_season(season))
if len(tea... | the_stack_v2_python_sparse | src/teams/views.py | cshc/cshc-web | train | 3 |
b04fd945061f57090941fd0c5021759af2ae09ba | [
"params = init_risky_asset.copy()\nparams.update(kwds)\nRiskyAssetConsumerType.__init__(self, verbose=verbose, quiet=quiet, **params)\nself.solve_one_period = make_one_period_oo_solver(ConsRiskyAssetLabeledSolver)\nself.update_labeled_type()",
"super().update_distributions()\nself.RiskyDstn = DiscreteDistribution... | <|body_start_0|>
params = init_risky_asset.copy()
params.update(kwds)
RiskyAssetConsumerType.__init__(self, verbose=verbose, quiet=quiet, **params)
self.solve_one_period = make_one_period_oo_solver(ConsRiskyAssetLabeledSolver)
self.update_labeled_type()
<|end_body_0|>
<|body_sta... | A labeled RiskyAssetConsumerType. This class is a subclass of RiskyAssetConsumerType, and inherits all of its methods and attributes. Risky asset consumers can only save on a risky asset that pays a stochastic return. | RiskyAssetLabeledType | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RiskyAssetLabeledType:
"""A labeled RiskyAssetConsumerType. This class is a subclass of RiskyAssetConsumerType, and inherits all of its methods and attributes. Risky asset consumers can only save on a risky asset that pays a stochastic return."""
def __init__(self, verbose=1, quiet=False, **... | stack_v2_sparse_classes_10k_train_003341 | 40,507 | permissive | [
{
"docstring": "Initialize a labeled RiskyAssetConsumerType.",
"name": "__init__",
"signature": "def __init__(self, verbose=1, quiet=False, **kwds)"
},
{
"docstring": "Update the labeled distributions including the Risky distribution.",
"name": "update_distributions",
"signature": "def u... | 2 | stack_v2_sparse_classes_30k_train_002702 | Implement the Python class `RiskyAssetLabeledType` described below.
Class description:
A labeled RiskyAssetConsumerType. This class is a subclass of RiskyAssetConsumerType, and inherits all of its methods and attributes. Risky asset consumers can only save on a risky asset that pays a stochastic return.
Method signat... | Implement the Python class `RiskyAssetLabeledType` described below.
Class description:
A labeled RiskyAssetConsumerType. This class is a subclass of RiskyAssetConsumerType, and inherits all of its methods and attributes. Risky asset consumers can only save on a risky asset that pays a stochastic return.
Method signat... | 7ce7138b6d9617a28fd4448936be3d61acad21d8 | <|skeleton|>
class RiskyAssetLabeledType:
"""A labeled RiskyAssetConsumerType. This class is a subclass of RiskyAssetConsumerType, and inherits all of its methods and attributes. Risky asset consumers can only save on a risky asset that pays a stochastic return."""
def __init__(self, verbose=1, quiet=False, **... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RiskyAssetLabeledType:
"""A labeled RiskyAssetConsumerType. This class is a subclass of RiskyAssetConsumerType, and inherits all of its methods and attributes. Risky asset consumers can only save on a risky asset that pays a stochastic return."""
def __init__(self, verbose=1, quiet=False, **kwds):
... | the_stack_v2_python_sparse | HARK/ConsumptionSaving/ConsLabeledModel.py | econ-ark/HARK | train | 315 |
dce997da4d5ad422fae448fdc1234cd00753155b | [
"non_cacheable_elements = ['code']\nviewable = self.get_viewable()\nif viewable is None:\n return 0\nfor node in viewable.content.documentElement.childNodes:\n node_name = node.nodeName\n if node_name in non_cacheable_elements:\n return 0\n if node_name == 'source':\n is_cacheable = extern... | <|body_start_0|>
non_cacheable_elements = ['code']
viewable = self.get_viewable()
if viewable is None:
return 0
for node in viewable.content.documentElement.childNodes:
node_name = node.nodeName
if node_name in non_cacheable_elements:
r... | Document | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Document:
def is_cacheable(self):
"""Return true if this document is cacheable. That means the document contains no dynamic elements like code, datasource or toc."""
<|body_0|>
def PUT(self, REQUEST=None, RESPONSE=None):
"""PUT support"""
<|body_1|>
def ... | stack_v2_sparse_classes_10k_train_003342 | 8,333 | permissive | [
{
"docstring": "Return true if this document is cacheable. That means the document contains no dynamic elements like code, datasource or toc.",
"name": "is_cacheable",
"signature": "def is_cacheable(self)"
},
{
"docstring": "PUT support",
"name": "PUT",
"signature": "def PUT(self, REQUES... | 3 | stack_v2_sparse_classes_30k_train_003248 | Implement the Python class `Document` described below.
Class description:
Implement the Document class.
Method signatures and docstrings:
- def is_cacheable(self): Return true if this document is cacheable. That means the document contains no dynamic elements like code, datasource or toc.
- def PUT(self, REQUEST=None... | Implement the Python class `Document` described below.
Class description:
Implement the Document class.
Method signatures and docstrings:
- def is_cacheable(self): Return true if this document is cacheable. That means the document contains no dynamic elements like code, datasource or toc.
- def PUT(self, REQUEST=None... | b3f237eedea4aa9a1014ed49487585359027a8e9 | <|skeleton|>
class Document:
def is_cacheable(self):
"""Return true if this document is cacheable. That means the document contains no dynamic elements like code, datasource or toc."""
<|body_0|>
def PUT(self, REQUEST=None, RESPONSE=None):
"""PUT support"""
<|body_1|>
def ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Document:
def is_cacheable(self):
"""Return true if this document is cacheable. That means the document contains no dynamic elements like code, datasource or toc."""
non_cacheable_elements = ['code']
viewable = self.get_viewable()
if viewable is None:
return 0
... | the_stack_v2_python_sparse | Products/SilvaDocument/Document.py | silvacms/Products.SilvaDocument | train | 0 | |
b8b44bbc21030299c36498186edf206ff715cb75 | [
"if isinstance(cls, six.class_types):\n init = cls.__init__\n\n def wrapped(*args, **kwargs):\n try:\n warp_self = args[0]\n warp_self.df = None\n init(*args, **kwargs)\n symbol = args[1]\n self._gen_warp_df(warp_self, symbol)\n except Excep... | <|body_start_0|>
if isinstance(cls, six.class_types):
init = cls.__init__
def wrapped(*args, **kwargs):
try:
warp_self = args[0]
warp_self.df = None
init(*args, **kwargs)
symbol = args[1]
... | 做为类装饰器封装替换解析数据统一操作,装饰替换init | AbuDataParseWrap | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbuDataParseWrap:
"""做为类装饰器封装替换解析数据统一操作,装饰替换init"""
def __call__(self, cls):
"""只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程"""
<|body_0|>
def _gen_warp_df(self, warp_self, symbol):
"""封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的symbol str对象 :return:"... | stack_v2_sparse_classes_10k_train_003343 | 14,108 | permissive | [
{
"docstring": "只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程",
"name": "__call__",
"signature": "def __call__(self, cls)"
},
{
"docstring": "封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的symbol str对象 :return:",
"name": "_gen_warp_df",
"signature": "def _gen_warp_df(self, warp_s... | 2 | null | Implement the Python class `AbuDataParseWrap` described below.
Class description:
做为类装饰器封装替换解析数据统一操作,装饰替换init
Method signatures and docstrings:
- def __call__(self, cls): 只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程
- def _gen_warp_df(self, warp_self, symbol): 封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的s... | Implement the Python class `AbuDataParseWrap` described below.
Class description:
做为类装饰器封装替换解析数据统一操作,装饰替换init
Method signatures and docstrings:
- def __call__(self, cls): 只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程
- def _gen_warp_df(self, warp_self, symbol): 封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的s... | 2e5ab17f2d20deb3c68c927f6208ea89db7c639d | <|skeleton|>
class AbuDataParseWrap:
"""做为类装饰器封装替换解析数据统一操作,装饰替换init"""
def __call__(self, cls):
"""只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程"""
<|body_0|>
def _gen_warp_df(self, warp_self, symbol):
"""封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的symbol str对象 :return:"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AbuDataParseWrap:
"""做为类装饰器封装替换解析数据统一操作,装饰替换init"""
def __call__(self, cls):
"""只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程"""
if isinstance(cls, six.class_types):
init = cls.__init__
def wrapped(*args, **kwargs):
try:
warp_self = args[0]
... | the_stack_v2_python_sparse | abupy/MarketBu/ABuDataParser.py | luqin/firefly | train | 1 |
572ee8b72b3ecfe0afde9a250cefabfb32d9bd57 | [
"if not root:\n return 0\ndepth = 0\nstack = [root]\nwhile stack:\n for node in stack:\n if node.right:\n nxLevel.append(node.right)\n if node.left:\n nxLevel.append(node.left)\n depth += 1\nreturn depth",
"if not root:\n return 0\nreturn 1 + max(self.maxDepth(root.... | <|body_start_0|>
if not root:
return 0
depth = 0
stack = [root]
while stack:
for node in stack:
if node.right:
nxLevel.append(node.right)
if node.left:
nxLevel.append(node.left)
de... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
depth = 0
... | stack_v2_sparse_classes_10k_train_003344 | 1,708 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def maxDepth(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def maxDepth(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def maxDepth(self, root... | f8fd6bb130a4d55d83d9bc07caac53c7e0a26afd | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
depth = 0
stack = [root]
while stack:
for node in stack:
if node.right:
nxLevel.append(node.right)
... | the_stack_v2_python_sparse | 104. Maximum Depth of Binary Tree.py | cherryzoe/Leetcode | train | 0 | |
80b94d2e421d638914c955bd28fed9ee5222c3c3 | [
"def back_track(nums: List[int], path: List[int], result: List[List[int]]):\n if not nums:\n result.append(path)\n for idx in range(len(nums)):\n back_track(nums[:idx] + nums[idx + 1:], path + [nums[idx]], result)\nresult = []\nback_track(nums, [], result)\nreturn result",
"def back_track(firs... | <|body_start_0|>
def back_track(nums: List[int], path: List[int], result: List[List[int]]):
if not nums:
result.append(path)
for idx in range(len(nums)):
back_track(nums[:idx] + nums[idx + 1:], path + [nums[idx]], result)
result = []
back_t... | Permutations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Permutations:
def permutee(self, nums: List[int]) -> List[List[int]]:
"""Approach: Back track Time Complexity: Space Complexity: :param nums: :return:"""
<|body_0|>
def permute(self, nums: List[int]) -> List[List[int]]:
"""Approach: Back tracking Time Complexity: O(N... | stack_v2_sparse_classes_10k_train_003345 | 2,384 | no_license | [
{
"docstring": "Approach: Back track Time Complexity: Space Complexity: :param nums: :return:",
"name": "permutee",
"signature": "def permutee(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "Approach: Back tracking Time Complexity: O(N!) Space Complexity: O(N!) :param nums: :return... | 3 | null | Implement the Python class `Permutations` described below.
Class description:
Implement the Permutations class.
Method signatures and docstrings:
- def permutee(self, nums: List[int]) -> List[List[int]]: Approach: Back track Time Complexity: Space Complexity: :param nums: :return:
- def permute(self, nums: List[int])... | Implement the Python class `Permutations` described below.
Class description:
Implement the Permutations class.
Method signatures and docstrings:
- def permutee(self, nums: List[int]) -> List[List[int]]: Approach: Back track Time Complexity: Space Complexity: :param nums: :return:
- def permute(self, nums: List[int])... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Permutations:
def permutee(self, nums: List[int]) -> List[List[int]]:
"""Approach: Back track Time Complexity: Space Complexity: :param nums: :return:"""
<|body_0|>
def permute(self, nums: List[int]) -> List[List[int]]:
"""Approach: Back tracking Time Complexity: O(N... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Permutations:
def permutee(self, nums: List[int]) -> List[List[int]]:
"""Approach: Back track Time Complexity: Space Complexity: :param nums: :return:"""
def back_track(nums: List[int], path: List[int], result: List[List[int]]):
if not nums:
result.append(path)
... | the_stack_v2_python_sparse | revisited/permutations_combinations_subsets/permutations.py | Shiv2157k/leet_code | train | 1 | |
166340735e012a724b1f8ee84a9bac335fac8e0e | [
"self.main_url = url\nself.main_config = configuration\nself._session = requests.Session()\nself._session.verify = False\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nreturn",
"token = str(self.main_config['creds'][tokenId])\nself._session.auth = (token, '')\nurl = str(self.main_url) + api... | <|body_start_0|>
self.main_url = url
self.main_config = configuration
self._session = requests.Session()
self._session.verify = False
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
return
<|end_body_0|>
<|body_start_1|>
token = str(self.main_... | SonarAPIClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SonarAPIClient:
def __init__(self, url, configuration):
"""Constructor :param url: to generate http-connection to"""
<|body_0|>
def make_apicall(self, method, apistring, tokenId):
"""Call Rest API of SONAR for report. :param method: :param apistring: :return: respons... | stack_v2_sparse_classes_10k_train_003346 | 3,812 | no_license | [
{
"docstring": "Constructor :param url: to generate http-connection to",
"name": "__init__",
"signature": "def __init__(self, url, configuration)"
},
{
"docstring": "Call Rest API of SONAR for report. :param method: :param apistring: :return: response as JSON Object",
"name": "make_apicall",... | 5 | stack_v2_sparse_classes_30k_train_005458 | Implement the Python class `SonarAPIClient` described below.
Class description:
Implement the SonarAPIClient class.
Method signatures and docstrings:
- def __init__(self, url, configuration): Constructor :param url: to generate http-connection to
- def make_apicall(self, method, apistring, tokenId): Call Rest API of ... | Implement the Python class `SonarAPIClient` described below.
Class description:
Implement the SonarAPIClient class.
Method signatures and docstrings:
- def __init__(self, url, configuration): Constructor :param url: to generate http-connection to
- def make_apicall(self, method, apistring, tokenId): Call Rest API of ... | c734ab9f467f6d882406b9ac8a94c475d4a00465 | <|skeleton|>
class SonarAPIClient:
def __init__(self, url, configuration):
"""Constructor :param url: to generate http-connection to"""
<|body_0|>
def make_apicall(self, method, apistring, tokenId):
"""Call Rest API of SONAR for report. :param method: :param apistring: :return: respons... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SonarAPIClient:
def __init__(self, url, configuration):
"""Constructor :param url: to generate http-connection to"""
self.main_url = url
self.main_config = configuration
self._session = requests.Session()
self._session.verify = False
urllib3.disable_warnings(url... | the_stack_v2_python_sparse | metric/Sonarqube/SonarAPIClient.py | mmiedaner/security | train | 2 | |
aa79383fe10ee11b82703955dd65ffbec4682003 | [
"self.iceContext = iceContext\nself.mets = Mets(iceContext, 'ICE-METS', Mets.Helper.METS_NLA_PROFILE)\nself.__includeExts = includeExts",
"fs = self.iceContext.FileSystem(basePath)\ncreationDate = strftime('%Y-%m-%dT%H:%M:%S', gmtime())\nself.mets.setCreateDate(creationDate)\nself.mets.setLastModDate(creationDate... | <|body_start_0|>
self.iceContext = iceContext
self.mets = Mets(iceContext, 'ICE-METS', Mets.Helper.METS_NLA_PROFILE)
self.__includeExts = includeExts
<|end_body_0|>
<|body_start_1|>
fs = self.iceContext.FileSystem(basePath)
creationDate = strftime('%Y-%m-%dT%H:%M:%S', gmtime())
... | Base class for MetsCreator | MetsCreator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetsCreator:
"""Base class for MetsCreator"""
def __init__(self, iceContext, includeExts):
"""Constructor for MetsCreator @param iceContext: Current ice context @type iceContext: IceContext @param includeExts: list of extension to be included @type includeExts: list"""
<|body... | stack_v2_sparse_classes_10k_train_003347 | 19,400 | no_license | [
{
"docstring": "Constructor for MetsCreator @param iceContext: Current ice context @type iceContext: IceContext @param includeExts: list of extension to be included @type includeExts: list",
"name": "__init__",
"signature": "def __init__(self, iceContext, includeExts)"
},
{
"docstring": "to crea... | 2 | null | Implement the Python class `MetsCreator` described below.
Class description:
Base class for MetsCreator
Method signatures and docstrings:
- def __init__(self, iceContext, includeExts): Constructor for MetsCreator @param iceContext: Current ice context @type iceContext: IceContext @param includeExts: list of extension... | Implement the Python class `MetsCreator` described below.
Class description:
Base class for MetsCreator
Method signatures and docstrings:
- def __init__(self, iceContext, includeExts): Constructor for MetsCreator @param iceContext: Current ice context @type iceContext: IceContext @param includeExts: list of extension... | c1d6b5a1bea3df4dde10cb582fb0da361dd747bc | <|skeleton|>
class MetsCreator:
"""Base class for MetsCreator"""
def __init__(self, iceContext, includeExts):
"""Constructor for MetsCreator @param iceContext: Current ice context @type iceContext: IceContext @param includeExts: list of extension to be included @type includeExts: list"""
<|body... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MetsCreator:
"""Base class for MetsCreator"""
def __init__(self, iceContext, includeExts):
"""Constructor for MetsCreator @param iceContext: Current ice context @type iceContext: IceContext @param includeExts: list of extension to be included @type includeExts: list"""
self.iceContext = i... | the_stack_v2_python_sparse | apps/ice/plugins/service/plugin_odp_ppt_service.py | ptsefton/integrated-content-environment | train | 0 |
55693c6abbc419b4a4a54b7d080faeb784c72345 | [
"if not heights:\n return 0\nn = len(heights)\nlessFromLeft = [0] * n\nlessFromRight = [0] * n\nlessFromLeft[0] = -1\nlessFromRight[n - 1] = n\nfor i in range(1, n):\n p = i - 1\n '\\n for example in order to left[i]; if height[i - 1] < height[i] then \\n left[i] = i - 1; other wise w... | <|body_start_0|>
if not heights:
return 0
n = len(heights)
lessFromLeft = [0] * n
lessFromRight = [0] * n
lessFromLeft[0] = -1
lessFromRight[n - 1] = n
for i in range(1, n):
p = i - 1
'\n for example in order to left[... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights):
"""For any bar i the maximum rectangle is of width r - l - 1 where r - is the last coordinate of the bar to the right with height h[r] >= h[i] and l - is the last coordinate of the bar to the left which height h[l] >= h[i] So if for any ... | stack_v2_sparse_classes_10k_train_003348 | 5,351 | no_license | [
{
"docstring": "For any bar i the maximum rectangle is of width r - l - 1 where r - is the last coordinate of the bar to the right with height h[r] >= h[i] and l - is the last coordinate of the bar to the left which height h[l] >= h[i] So if for any i coordinate we know his utmost higher (or of the same height)... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): For any bar i the maximum rectangle is of width r - l - 1 where r - is the last coordinate of the bar to the right with height h[r] >= h[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): For any bar i the maximum rectangle is of width r - l - 1 where r - is the last coordinate of the bar to the right with height h[r] >= h[... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights):
"""For any bar i the maximum rectangle is of width r - l - 1 where r - is the last coordinate of the bar to the right with height h[r] >= h[i] and l - is the last coordinate of the bar to the left which height h[l] >= h[i] So if for any ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def largestRectangleArea(self, heights):
"""For any bar i the maximum rectangle is of width r - l - 1 where r - is the last coordinate of the bar to the right with height h[r] >= h[i] and l - is the last coordinate of the bar to the left which height h[l] >= h[i] So if for any i coordinate w... | the_stack_v2_python_sparse | L/LargestRectangleinHistogram.py | bssrdf/pyleet | train | 2 | |
dfe5f02b50716f99ace689d257d999318f32bf80 | [
"def dfs(nums, k, val):\n \"\"\"\n Check if there is a subset with sum equal to val\n k: the number of elements to check. Current subset should be [0..k-1]\n Reduce this problem into two sub-problems:\n 1. Do search val in [0..k-2]\n 2. Do search val-nums[k-... | <|body_start_0|>
def dfs(nums, k, val):
"""
Check if there is a subset with sum equal to val
k: the number of elements to check. Current subset should be [0..k-1]
Reduce this problem into two sub-problems:
1. Do search v... | @ eBay dp Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Note: Each of the array element will not exceed 100. The array size will not exceed 200. Example 1: Input: [1, 5, 11, 5] Output: true Explana... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""@ eBay dp Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Note: Each of the array element will not exceed 100. The array size will not exceed 200. Example 1: Input... | stack_v2_sparse_classes_10k_train_003349 | 3,413 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canPartition_recursive",
"signature": "def canPartition_recursive(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canPartition_dp",
"signature": "def canPartition_dp(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005965 | Implement the Python class `Solution` described below.
Class description:
@ eBay dp Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Note: Each of the array element will not exceed 100. The array siz... | Implement the Python class `Solution` described below.
Class description:
@ eBay dp Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Note: Each of the array element will not exceed 100. The array siz... | cbe6a7e7f05eccb4f9c5fce8651c0d87e5168516 | <|skeleton|>
class Solution:
"""@ eBay dp Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Note: Each of the array element will not exceed 100. The array size will not exceed 200. Example 1: Input... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""@ eBay dp Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Note: Each of the array element will not exceed 100. The array size will not exceed 200. Example 1: Input: [1, 5, 11, ... | the_stack_v2_python_sparse | src/dp/leetcode416_PartitionEqualSubsetSum.py | apepkuss/Cracking-Leetcode-in-Python | train | 2 |
568bc8b7c327a414e176f397298fca068106f5cb | [
"if root != None:\n if root.left != None or root.right != None:\n root.left, root.right = (root.right, root.left)\n self.invertTree(root.left)\n self.invertTree(root.right)\nreturn root",
"if p != None and q != None:\n if p.val != q.val:\n return False\n if self.isSameTree(p.l... | <|body_start_0|>
if root != None:
if root.left != None or root.right != None:
root.left, root.right = (root.right, root.left)
self.invertTree(root.left)
self.invertTree(root.right)
return root
<|end_body_0|>
<|body_start_1|>
if p != No... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
def isSymmetric(self, root):
""":type root: TreeNode :rtype... | stack_v2_sparse_classes_10k_train_003350 | 1,353 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "invertTree",
"signature": "def invertTree(self, root)"
},
{
"docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q)"
},
{
"docstring": ":type r... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root): :type root: TreeNode :rtype: TreeNode
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
- def isSymmetric(self, root): :t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root): :type root: TreeNode :rtype: TreeNode
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
- def isSymmetric(self, root): :t... | 7a1c3aba65f338f6e11afd2864dabd2b26142b6c | <|skeleton|>
class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
def isSymmetric(self, root):
""":type root: TreeNode :rtype... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
if root != None:
if root.left != None or root.right != None:
root.left, root.right = (root.right, root.left)
self.invertTree(root.left)
self.invertTree(... | the_stack_v2_python_sparse | exercise/leetcode/python_src/by2017_Sep/Leet101.py | SS4G/AlgorithmTraining | train | 2 | |
77bddbc3ebbf3c71dba50cf099459bad3a0b1691 | [
"n = len(nums)\nself.tree = [0] * (2 * n)\nfor i in range(n, 2 * n, 1):\n self.tree[i] = nums[i - n]\nfor i in range(n - 1, 0, -1):\n self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]\nself.nums = nums\nself.n = n\nreturn",
"n = self.n\nself.nums[index] = val\nindex += n\nself.tree[index] = val\nindex ... | <|body_start_0|>
n = len(nums)
self.tree = [0] * (2 * n)
for i in range(n, 2 * n, 1):
self.tree[i] = nums[i - n]
for i in range(n - 1, 0, -1):
self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]
self.nums = nums
self.n = n
return
<|end_b... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, index, val):
""":type index: int :type val: int :rtype: None"""
<|body_1|>
def sumRange(self, left, right):
""":type left: int :type right: int :rtype: in... | stack_v2_sparse_classes_10k_train_003351 | 2,072 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type index: int :type val: int :rtype: None",
"name": "update",
"signature": "def update(self, index, val)"
},
{
"docstring": ":type left: int :type right: int ... | 3 | stack_v2_sparse_classes_30k_train_000077 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, index, val): :type index: int :type val: int :rtype: None
- def sumRange(self, left, right): :type left: int :t... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, index, val): :type index: int :type val: int :rtype: None
- def sumRange(self, left, right): :type left: int :t... | ad1eabfa27dda65b743d7d93524f1ec8f1e0ebfc | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, index, val):
""":type index: int :type val: int :rtype: None"""
<|body_1|>
def sumRange(self, left, right):
""":type left: int :type right: int :rtype: in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
n = len(nums)
self.tree = [0] * (2 * n)
for i in range(n, 2 * n, 1):
self.tree[i] = nums[i - n]
for i in range(n - 1, 0, -1):
self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]
... | the_stack_v2_python_sparse | code/leetcode-307.py | kiyoxi2020/leetcode | train | 3 | |
69ec0e59d8dcbe48569a36647d1bf781e9181daf | [
"model = self._meta.verbose_name.title()\ntitle = self.title or str(_('Empty title'))\nreturn f'{model:s}: {title:s}'",
"if self.__class__.objects.filter(master__draft_course_run__translations__pk=self.pk, language_code=self.language_code).exclude(title=self.title).exists():\n self.master.direct_course.extende... | <|body_start_0|>
model = self._meta.verbose_name.title()
title = self.title or str(_('Empty title'))
return f'{model:s}: {title:s}'
<|end_body_0|>
<|body_start_1|>
if self.__class__.objects.filter(master__draft_course_run__translations__pk=self.pk, language_code=self.language_code).excl... | CourseRun Translation model. Django parler model linked to the CourseRun to internationalize the fields. | CourseRunTranslation | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseRunTranslation:
"""CourseRun Translation model. Django parler model linked to the CourseRun to internationalize the fields."""
def __str__(self):
"""Human representation of a course run translation."""
<|body_0|>
def save(self, *args, **kwargs):
"""Mark rel... | stack_v2_sparse_classes_10k_train_003352 | 42,905 | permissive | [
{
"docstring": "Human representation of a course run translation.",
"name": "__str__",
"signature": "def __str__(self)"
},
{
"docstring": "Mark related course page dirty if the title has changed compared to the public version.",
"name": "save",
"signature": "def save(self, *args, **kwarg... | 2 | stack_v2_sparse_classes_30k_train_000318 | Implement the Python class `CourseRunTranslation` described below.
Class description:
CourseRun Translation model. Django parler model linked to the CourseRun to internationalize the fields.
Method signatures and docstrings:
- def __str__(self): Human representation of a course run translation.
- def save(self, *args... | Implement the Python class `CourseRunTranslation` described below.
Class description:
CourseRun Translation model. Django parler model linked to the CourseRun to internationalize the fields.
Method signatures and docstrings:
- def __str__(self): Human representation of a course run translation.
- def save(self, *args... | f2d46fc46b271eb3b4d565039a29c15ba15f027c | <|skeleton|>
class CourseRunTranslation:
"""CourseRun Translation model. Django parler model linked to the CourseRun to internationalize the fields."""
def __str__(self):
"""Human representation of a course run translation."""
<|body_0|>
def save(self, *args, **kwargs):
"""Mark rel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CourseRunTranslation:
"""CourseRun Translation model. Django parler model linked to the CourseRun to internationalize the fields."""
def __str__(self):
"""Human representation of a course run translation."""
model = self._meta.verbose_name.title()
title = self.title or str(_('Empt... | the_stack_v2_python_sparse | src/richie/apps/courses/models/course.py | openfun/richie | train | 238 |
c0691d01912cda3d8372186aef59c9af810ce174 | [
"self.packages: str = cli_args.packages\nself.host: str = cli_args.host\nself.env: EnvType = EnvType[cli_args.env]\nself.group: str = cli_args.group\nself.name: str = cli_args.name",
"parser.add_argument('--packages', '-p', nargs='+', required=True, help='Generate schema from provided packages')\nparser.add_argum... | <|body_start_0|>
self.packages: str = cli_args.packages
self.host: str = cli_args.host
self.env: EnvType = EnvType[cli_args.env]
self.group: str = cli_args.group
self.name: str = cli_args.name
<|end_body_0|>
<|body_start_1|>
parser.add_argument('--packages', '-p', nargs=... | Command to write packages schema to specified data source | SchemaCommand | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaCommand:
"""Command to write packages schema to specified data source"""
def __init__(self, cli_args):
"""Init schema command from parsed CLI args."""
<|body_0|>
def add_arguments(cls, parser):
"""Add arguments to parser."""
<|body_1|>
def exec... | stack_v2_sparse_classes_10k_train_003353 | 3,525 | permissive | [
{
"docstring": "Init schema command from parsed CLI args.",
"name": "__init__",
"signature": "def __init__(self, cli_args)"
},
{
"docstring": "Add arguments to parser.",
"name": "add_arguments",
"signature": "def add_arguments(cls, parser)"
},
{
"docstring": "Generate declaration... | 3 | stack_v2_sparse_classes_30k_train_000457 | Implement the Python class `SchemaCommand` described below.
Class description:
Command to write packages schema to specified data source
Method signatures and docstrings:
- def __init__(self, cli_args): Init schema command from parsed CLI args.
- def add_arguments(cls, parser): Add arguments to parser.
- def execute(... | Implement the Python class `SchemaCommand` described below.
Class description:
Command to write packages schema to specified data source
Method signatures and docstrings:
- def __init__(self, cli_args): Init schema command from parsed CLI args.
- def add_arguments(cls, parser): Add arguments to parser.
- def execute(... | 40113ddfb68e62d98b880b3c7427db5cc9fbd8cd | <|skeleton|>
class SchemaCommand:
"""Command to write packages schema to specified data source"""
def __init__(self, cli_args):
"""Init schema command from parsed CLI args."""
<|body_0|>
def add_arguments(cls, parser):
"""Add arguments to parser."""
<|body_1|>
def exec... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SchemaCommand:
"""Command to write packages schema to specified data source"""
def __init__(self, cli_args):
"""Init schema command from parsed CLI args."""
self.packages: str = cli_args.packages
self.host: str = cli_args.host
self.env: EnvType = EnvType[cli_args.env]
... | the_stack_v2_python_sparse | py/datacentric/commands/schema.py | datacentricorg/datacentric-py | train | 1 |
39685c1099f7c955dc954dd226f6e3ac9bded848 | [
"self.buildings = [3, 5, 4, 4, 3, 1, 3, 2]\nself.direction = 'EAST'\nself.output = [1, 3, 6, 7]\nreturn (self.buildings, self.direction, self.output)",
"buildings, direction, proper_out = self.setUp()\noutput = sunsetViews(buildings, direction)\nself.assertEqual(output, proper_out)"
] | <|body_start_0|>
self.buildings = [3, 5, 4, 4, 3, 1, 3, 2]
self.direction = 'EAST'
self.output = [1, 3, 6, 7]
return (self.buildings, self.direction, self.output)
<|end_body_0|>
<|body_start_1|>
buildings, direction, proper_out = self.setUp()
output = sunsetViews(buildin... | Class with unittests for SunsetViews.py | test_SunsetViews | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_SunsetViews:
"""Class with unittests for SunsetViews.py"""
def setUp(self):
"""SetUp array for tests."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_003354 | 925 | no_license | [
{
"docstring": "SetUp array for tests.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if returned output is as expected.",
"name": "test_ExpectedOutput",
"signature": "def test_ExpectedOutput(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004600 | Implement the Python class `test_SunsetViews` described below.
Class description:
Class with unittests for SunsetViews.py
Method signatures and docstrings:
- def setUp(self): SetUp array for tests.
- def test_ExpectedOutput(self): Checks if returned output is as expected. | Implement the Python class `test_SunsetViews` described below.
Class description:
Class with unittests for SunsetViews.py
Method signatures and docstrings:
- def setUp(self): SetUp array for tests.
- def test_ExpectedOutput(self): Checks if returned output is as expected.
<|skeleton|>
class test_SunsetViews:
"""... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_SunsetViews:
"""Class with unittests for SunsetViews.py"""
def setUp(self):
"""SetUp array for tests."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class test_SunsetViews:
"""Class with unittests for SunsetViews.py"""
def setUp(self):
"""SetUp array for tests."""
self.buildings = [3, 5, 4, 4, 3, 1, 3, 2]
self.direction = 'EAST'
self.output = [1, 3, 6, 7]
return (self.buildings, self.direction, self.output)
def ... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Medium/SunsetViews/test_SunsetViews.py | JakubKazimierski/PythonPortfolio | train | 9 |
28aa59c69a49f80feb0d7819bf8da704def57da3 | [
"self.actions = actions\nself.player_id = player_id\nself.goal_states = goal_states",
"play_cost = []\ndraft_cost = []\nplay_set = []\ndraft_set = []\ntry:\n for action in self.actions:\n if (action['play_card'], action['coords']) in play_set:\n continue\n play_set.append((action['play... | <|body_start_0|>
self.actions = actions
self.player_id = player_id
self.goal_states = goal_states
<|end_body_0|>
<|body_start_1|>
play_cost = []
draft_cost = []
play_set = []
draft_set = []
try:
for action in self.actions:
if (... | Class for local search algorithms | SearchProblem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchProblem:
"""Class for local search algorithms"""
def __init__(self, player_id, goal_states, actions):
"""game_state: the current board in list of list format goal_state: Object BoardList"""
<|body_0|>
def GreedyAlgorithm(self, heuristic='simple'):
"""Greedy... | stack_v2_sparse_classes_10k_train_003355 | 1,748 | no_license | [
{
"docstring": "game_state: the current board in list of list format goal_state: Object BoardList",
"name": "__init__",
"signature": "def __init__(self, player_id, goal_states, actions)"
},
{
"docstring": "Greedy heuristic search (local constraint)",
"name": "GreedyAlgorithm",
"signature... | 2 | stack_v2_sparse_classes_30k_train_005010 | Implement the Python class `SearchProblem` described below.
Class description:
Class for local search algorithms
Method signatures and docstrings:
- def __init__(self, player_id, goal_states, actions): game_state: the current board in list of list format goal_state: Object BoardList
- def GreedyAlgorithm(self, heuris... | Implement the Python class `SearchProblem` described below.
Class description:
Class for local search algorithms
Method signatures and docstrings:
- def __init__(self, player_id, goal_states, actions): game_state: the current board in list of list format goal_state: Object BoardList
- def GreedyAlgorithm(self, heuris... | 1ac842505adcf5abf37ef0cd1bbd24b8ce87984f | <|skeleton|>
class SearchProblem:
"""Class for local search algorithms"""
def __init__(self, player_id, goal_states, actions):
"""game_state: the current board in list of list format goal_state: Object BoardList"""
<|body_0|>
def GreedyAlgorithm(self, heuristic='simple'):
"""Greedy... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SearchProblem:
"""Class for local search algorithms"""
def __init__(self, player_id, goal_states, actions):
"""game_state: the current board in list of list format goal_state: Object BoardList"""
self.actions = actions
self.player_id = player_id
self.goal_states = goal_sta... | the_stack_v2_python_sparse | agents/group13/hs_utils/search_problem.py | hmooy/Sequence-COMP90054 | train | 0 |
c32648503f99a51d2d61b172c5e290c30cfee946 | [
"if self.dbconn.version < 90300:\n return\nfor trig in self.fetch():\n trig.enabled = self.enable_modes[trig.enabled]\n self[trig.key()] = trig",
"for key in intriggers:\n if not key.startswith('event trigger '):\n raise KeyError('Unrecognized object type: %s' % key)\n trg = key[14:]\n in... | <|body_start_0|>
if self.dbconn.version < 90300:
return
for trig in self.fetch():
trig.enabled = self.enable_modes[trig.enabled]
self[trig.key()] = trig
<|end_body_0|>
<|body_start_1|>
for key in intriggers:
if not key.startswith('event trigger ')... | The collection of event triggers in a database | EventTriggerDict | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventTriggerDict:
"""The collection of event triggers in a database"""
def _from_catalog(self):
"""Initialize the dictionary of triggers by querying the catalogs"""
<|body_0|>
def from_map(self, intriggers, newdb):
"""Initalize the dictionary of triggers by conve... | stack_v2_sparse_classes_10k_train_003356 | 3,974 | permissive | [
{
"docstring": "Initialize the dictionary of triggers by querying the catalogs",
"name": "_from_catalog",
"signature": "def _from_catalog(self)"
},
{
"docstring": "Initalize the dictionary of triggers by converting the input map :param intriggers: YAML map defining the event triggers :param newd... | 3 | stack_v2_sparse_classes_30k_train_005207 | Implement the Python class `EventTriggerDict` described below.
Class description:
The collection of event triggers in a database
Method signatures and docstrings:
- def _from_catalog(self): Initialize the dictionary of triggers by querying the catalogs
- def from_map(self, intriggers, newdb): Initalize the dictionary... | Implement the Python class `EventTriggerDict` described below.
Class description:
The collection of event triggers in a database
Method signatures and docstrings:
- def _from_catalog(self): Initialize the dictionary of triggers by querying the catalogs
- def from_map(self, intriggers, newdb): Initalize the dictionary... | 0133f3bc522890e0564d27de6791824acb4d2773 | <|skeleton|>
class EventTriggerDict:
"""The collection of event triggers in a database"""
def _from_catalog(self):
"""Initialize the dictionary of triggers by querying the catalogs"""
<|body_0|>
def from_map(self, intriggers, newdb):
"""Initalize the dictionary of triggers by conve... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EventTriggerDict:
"""The collection of event triggers in a database"""
def _from_catalog(self):
"""Initialize the dictionary of triggers by querying the catalogs"""
if self.dbconn.version < 90300:
return
for trig in self.fetch():
trig.enabled = self.enable_... | the_stack_v2_python_sparse | pyrseas/dbobject/eventtrig.py | vayerx/Pyrseas | train | 1 |
b1bf98d5a2673a7878b261bdf63093cff0a8f234 | [
"cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')\nservice = check_obj(ClusterObject, {'cluster': cluster, 'id': service_id}, 'SERVICE_NOT_FOUND')\nres = cm.api.get_import(cluster, service)\nreturn Response(res)",
"cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')\nservice = check_obj(Clu... | <|body_start_0|>
cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')
service = check_obj(ClusterObject, {'cluster': cluster, 'id': service_id}, 'SERVICE_NOT_FOUND')
res = cm.api.get_import(cluster, service)
return Response(res)
<|end_body_0|>
<|body_start_1|>
cluster =... | ClusterServiceImport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterServiceImport:
def get(self, request, cluster_id, service_id):
"""List all imports avaliable for specified service in cluster"""
<|body_0|>
def post(self, request, cluster_id, service_id):
"""Update bind for service in cluster"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_10k_train_003357 | 32,530 | permissive | [
{
"docstring": "List all imports avaliable for specified service in cluster",
"name": "get",
"signature": "def get(self, request, cluster_id, service_id)"
},
{
"docstring": "Update bind for service in cluster",
"name": "post",
"signature": "def post(self, request, cluster_id, service_id)... | 2 | stack_v2_sparse_classes_30k_train_001740 | Implement the Python class `ClusterServiceImport` described below.
Class description:
Implement the ClusterServiceImport class.
Method signatures and docstrings:
- def get(self, request, cluster_id, service_id): List all imports avaliable for specified service in cluster
- def post(self, request, cluster_id, service_... | Implement the Python class `ClusterServiceImport` described below.
Class description:
Implement the ClusterServiceImport class.
Method signatures and docstrings:
- def get(self, request, cluster_id, service_id): List all imports avaliable for specified service in cluster
- def post(self, request, cluster_id, service_... | e1c67e3041437ad9e17dccc6c95c5ac02184eddb | <|skeleton|>
class ClusterServiceImport:
def get(self, request, cluster_id, service_id):
"""List all imports avaliable for specified service in cluster"""
<|body_0|>
def post(self, request, cluster_id, service_id):
"""Update bind for service in cluster"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClusterServiceImport:
def get(self, request, cluster_id, service_id):
"""List all imports avaliable for specified service in cluster"""
cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')
service = check_obj(ClusterObject, {'cluster': cluster, 'id': service_id}, 'SERVICE_NOT_... | the_stack_v2_python_sparse | api/cluster_views.py | amleshkov/adcm | train | 0 | |
0b44003e4c51d27d22ac0735f4b9317cc343cb96 | [
"x = kwargs.get('x', self.problem.data_x)\ny = kwargs.get('y', self.problem.data_y)\ne = kwargs.get('e', self.problem.data_e)\nif len(x) != len(y) or len(x) != len(e):\n raise CostFuncError(f'The length of the x, y and e are not the same, len(x)={len(x)}, len(y)={len(y)} and len(e)={len(e)}')\nresult = (y - self... | <|body_start_0|>
x = kwargs.get('x', self.problem.data_x)
y = kwargs.get('y', self.problem.data_y)
e = kwargs.get('e', self.problem.data_e)
if len(x) != len(y) or len(x) != len(e):
raise CostFuncError(f'The length of the x, y and e are not the same, len(x)={len(x)}, len(y)={l... | This defines the weighted non-linear least squares cost function where, given a set of :math:`n` data points :math:`(x_i,y_i)`, associated errors :math:`e_i`, and a model function :math:`f(x,p)`, we find the optimal parameters in the root least-squares sense by solving: .. math:: \\min_p \\sum_{i=1}^n \\left(\\frac{y_i... | WeightedNLLSCostFunc | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightedNLLSCostFunc:
"""This defines the weighted non-linear least squares cost function where, given a set of :math:`n` data points :math:`(x_i,y_i)`, associated errors :math:`e_i`, and a model function :math:`f(x,p)`, we find the optimal parameters in the root least-squares sense by solving: .... | stack_v2_sparse_classes_10k_train_003358 | 3,159 | permissive | [
{
"docstring": "Calculate the residuals, :math:`\\\\frac{y_i - f(x_i, p)}{e_i}` :param params: The parameters, :math:`p`, to calculate residuals for :type params: list :return: The residuals for the data points at the given parameters :rtype: numpy array",
"name": "eval_r",
"signature": "def eval_r(self... | 3 | stack_v2_sparse_classes_30k_train_004999 | Implement the Python class `WeightedNLLSCostFunc` described below.
Class description:
This defines the weighted non-linear least squares cost function where, given a set of :math:`n` data points :math:`(x_i,y_i)`, associated errors :math:`e_i`, and a model function :math:`f(x,p)`, we find the optimal parameters in the... | Implement the Python class `WeightedNLLSCostFunc` described below.
Class description:
This defines the weighted non-linear least squares cost function where, given a set of :math:`n` data points :math:`(x_i,y_i)`, associated errors :math:`e_i`, and a model function :math:`f(x,p)`, we find the optimal parameters in the... | 5ee7e66d963ebe9296c0a62c24b9616f6c65537e | <|skeleton|>
class WeightedNLLSCostFunc:
"""This defines the weighted non-linear least squares cost function where, given a set of :math:`n` data points :math:`(x_i,y_i)`, associated errors :math:`e_i`, and a model function :math:`f(x,p)`, we find the optimal parameters in the root least-squares sense by solving: .... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WeightedNLLSCostFunc:
"""This defines the weighted non-linear least squares cost function where, given a set of :math:`n` data points :math:`(x_i,y_i)`, associated errors :math:`e_i`, and a model function :math:`f(x,p)`, we find the optimal parameters in the root least-squares sense by solving: .. math:: \\mi... | the_stack_v2_python_sparse | fitbenchmarking/cost_func/weighted_nlls_cost_func.py | fitbenchmarking/fitbenchmarking | train | 15 |
f4d621441d5f26ee0b92113d34a61302aa84f900 | [
"start = ListNode(-1)\nstart.next = head\np = start\nwhile p.next:\n if p.next.val == val:\n p.next = p.next.next\n else:\n p = p.next\nreturn start.next",
"if head is None:\n return None\nhead.next = self._removeElements(head.next, val)\nreturn head.next if head.val == val else head"
] | <|body_start_0|>
start = ListNode(-1)
start.next = head
p = start
while p.next:
if p.next.val == val:
p.next = p.next.next
else:
p = p.next
return start.next
<|end_body_0|>
<|body_start_1|>
if head is None:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElements(self, head, val):
""":type head: ListNode :type val: int :rtype: ListNode"""
<|body_0|>
def _removeElements(self, head, val):
""":type head: ListNode :type val: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_10k_train_003359 | 1,540 | no_license | [
{
"docstring": ":type head: ListNode :type val: int :rtype: ListNode",
"name": "removeElements",
"signature": "def removeElements(self, head, val)"
},
{
"docstring": ":type head: ListNode :type val: int :rtype: ListNode",
"name": "_removeElements",
"signature": "def _removeElements(self,... | 2 | stack_v2_sparse_classes_30k_train_000533 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElements(self, head, val): :type head: ListNode :type val: int :rtype: ListNode
- def _removeElements(self, head, val): :type head: ListNode :type val: int :rtype: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElements(self, head, val): :type head: ListNode :type val: int :rtype: ListNode
- def _removeElements(self, head, val): :type head: ListNode :type val: int :rtype: List... | 1d1ffe25d8b49832acc1791261c959ce436a6362 | <|skeleton|>
class Solution:
def removeElements(self, head, val):
""":type head: ListNode :type val: int :rtype: ListNode"""
<|body_0|>
def _removeElements(self, head, val):
""":type head: ListNode :type val: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def removeElements(self, head, val):
""":type head: ListNode :type val: int :rtype: ListNode"""
start = ListNode(-1)
start.next = head
p = start
while p.next:
if p.next.val == val:
p.next = p.next.next
else:
... | the_stack_v2_python_sparse | 03-单链表/3-虚拟头结点/01-203.py | qiaozhi827/leetcode-1 | train | 0 | |
c83a126fcf82805e353bec8a36aaa4ac53092571 | [
"if graph is None:\n self._qubit_number = 0\n return\nnode_number = len(graph.nodes)\nedge_number = len(graph.edges)\nif node_number < 2 ** 8:\n data_type = numpy.uint8\nelif node_number < 2 ** 16:\n data_type = numpy.uint16\nelse:\n data_type = numpy.uint32\nself._from_arr = numpy.zeros((edge_number... | <|body_start_0|>
if graph is None:
self._qubit_number = 0
return
node_number = len(graph.nodes)
edge_number = len(graph.edges)
if node_number < 2 ** 8:
data_type = numpy.uint8
elif node_number < 2 ** 16:
data_type = numpy.uint16
... | CompressedMultiDiGraph | [
"BSD-3-Clause",
"CECILL-B",
"MIT",
"LicenseRef-scancode-cecill-b-en"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompressedMultiDiGraph:
def __init__(self, graph: nx.MultiDiGraph=None) -> None:
"""Initialise the :py:class:`~.CompressedMultiDiGraph` instance. Instances of :py:class:`~.CompressedMultiDiGraph` are just storing a :py:class:`networkx.MultiDiGraph` in a more memory efficient format. :par... | stack_v2_sparse_classes_10k_train_003360 | 21,657 | permissive | [
{
"docstring": "Initialise the :py:class:`~.CompressedMultiDiGraph` instance. Instances of :py:class:`~.CompressedMultiDiGraph` are just storing a :py:class:`networkx.MultiDiGraph` in a more memory efficient format. :param graph: The graph to compress.",
"name": "__init__",
"signature": "def __init__(se... | 3 | stack_v2_sparse_classes_30k_train_003838 | Implement the Python class `CompressedMultiDiGraph` described below.
Class description:
Implement the CompressedMultiDiGraph class.
Method signatures and docstrings:
- def __init__(self, graph: nx.MultiDiGraph=None) -> None: Initialise the :py:class:`~.CompressedMultiDiGraph` instance. Instances of :py:class:`~.Compr... | Implement the Python class `CompressedMultiDiGraph` described below.
Class description:
Implement the CompressedMultiDiGraph class.
Method signatures and docstrings:
- def __init__(self, graph: nx.MultiDiGraph=None) -> None: Initialise the :py:class:`~.CompressedMultiDiGraph` instance. Instances of :py:class:`~.Compr... | 1e99bd7d3a143a327c3bb92595ea88ec12dbdb89 | <|skeleton|>
class CompressedMultiDiGraph:
def __init__(self, graph: nx.MultiDiGraph=None) -> None:
"""Initialise the :py:class:`~.CompressedMultiDiGraph` instance. Instances of :py:class:`~.CompressedMultiDiGraph` are just storing a :py:class:`networkx.MultiDiGraph` in a more memory efficient format. :par... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CompressedMultiDiGraph:
def __init__(self, graph: nx.MultiDiGraph=None) -> None:
"""Initialise the :py:class:`~.CompressedMultiDiGraph` instance. Instances of :py:class:`~.CompressedMultiDiGraph` are just storing a :py:class:`networkx.MultiDiGraph` in a more memory efficient format. :param graph: The ... | the_stack_v2_python_sparse | qtoolkit/data_structures/quantum_circuit/quantum_circuit.py | nelimee/qtoolkit | train | 4 | |
86606bc769437f84b37de8eb1be2a52e0111826a | [
"dct = self._base_map(no_owner)\nif '.' in self.parser:\n sch, pars = self.parser.split('.')\n if sch == self.schema:\n dct['parser'] = pars\nreturn dct",
"clauses = []\nclauses.append('PARSER = %s' % self.parser)\nreturn ['CREATE TEXT SEARCH CONFIGURATION %s (\\n %s)' % (self.qualname(), ',\\n ... | <|body_start_0|>
dct = self._base_map(no_owner)
if '.' in self.parser:
sch, pars = self.parser.split('.')
if sch == self.schema:
dct['parser'] = pars
return dct
<|end_body_0|>
<|body_start_1|>
clauses = []
clauses.append('PARSER = %s' % se... | A text search configuration definition | TSConfiguration | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TSConfiguration:
"""A text search configuration definition"""
def to_map(self, no_owner):
"""Convert a text search configuration to a YAML-suitable format :return: dictionary"""
<|body_0|>
def create(self):
"""Return SQL statements to CREATE the configuration :re... | stack_v2_sparse_classes_10k_train_003361 | 15,925 | permissive | [
{
"docstring": "Convert a text search configuration to a YAML-suitable format :return: dictionary",
"name": "to_map",
"signature": "def to_map(self, no_owner)"
},
{
"docstring": "Return SQL statements to CREATE the configuration :return: SQL statements",
"name": "create",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_000513 | Implement the Python class `TSConfiguration` described below.
Class description:
A text search configuration definition
Method signatures and docstrings:
- def to_map(self, no_owner): Convert a text search configuration to a YAML-suitable format :return: dictionary
- def create(self): Return SQL statements to CREATE ... | Implement the Python class `TSConfiguration` described below.
Class description:
A text search configuration definition
Method signatures and docstrings:
- def to_map(self, no_owner): Convert a text search configuration to a YAML-suitable format :return: dictionary
- def create(self): Return SQL statements to CREATE ... | 0133f3bc522890e0564d27de6791824acb4d2773 | <|skeleton|>
class TSConfiguration:
"""A text search configuration definition"""
def to_map(self, no_owner):
"""Convert a text search configuration to a YAML-suitable format :return: dictionary"""
<|body_0|>
def create(self):
"""Return SQL statements to CREATE the configuration :re... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TSConfiguration:
"""A text search configuration definition"""
def to_map(self, no_owner):
"""Convert a text search configuration to a YAML-suitable format :return: dictionary"""
dct = self._base_map(no_owner)
if '.' in self.parser:
sch, pars = self.parser.split('.')
... | the_stack_v2_python_sparse | pyrseas/dbobject/textsearch.py | vayerx/Pyrseas | train | 1 |
b24c4af73643e56fcb07c11f7ce0db6f79d5dc60 | [
"payloads = ['\\r\\nSet-Cookie: {}={}', '\\nSet-Cookie: {}={}', '\\rSet-Cookie: {}={}', 'čĊSet-Cookie: {}={}']\nself._random = utility.generate_random(string.ascii_lowercase)\nself._payloads = [payload.format(self._random, self._random) for payload in payloads]",
"if not response.cookies:\n return False\nif se... | <|body_start_0|>
payloads = ['\r\nSet-Cookie: {}={}', '\nSet-Cookie: {}={}', '\rSet-Cookie: {}={}', 'čĊSet-Cookie: {}={}']
self._random = utility.generate_random(string.ascii_lowercase)
self._payloads = [payload.format(self._random, self._random) for payload in payloads]
<|end_body_0|>
<|body_s... | Checks for Header Injection in the response's header. The payload sets a cookie of 'ava=avascan' using CRLF character variations, such as removing each CR/LF character and encoding as UTF-8. | HeaderInjectionCheck | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeaderInjectionCheck:
"""Checks for Header Injection in the response's header. The payload sets a cookie of 'ava=avascan' using CRLF character variations, such as removing each CR/LF character and encoding as UTF-8."""
def __init__(self):
"""Define static payloads"""
<|body_0... | stack_v2_sparse_classes_10k_train_003362 | 1,534 | permissive | [
{
"docstring": "Define static payloads",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Checks for Header Injections by looking for the 'Set-Cookie' payload in the response's headers. :param response: response object from server :param payload: payload value :return: tr... | 2 | stack_v2_sparse_classes_30k_train_006542 | Implement the Python class `HeaderInjectionCheck` described below.
Class description:
Checks for Header Injection in the response's header. The payload sets a cookie of 'ava=avascan' using CRLF character variations, such as removing each CR/LF character and encoding as UTF-8.
Method signatures and docstrings:
- def _... | Implement the Python class `HeaderInjectionCheck` described below.
Class description:
Checks for Header Injection in the response's header. The payload sets a cookie of 'ava=avascan' using CRLF character variations, such as removing each CR/LF character and encoding as UTF-8.
Method signatures and docstrings:
- def _... | 962f551710c6369d04851cc09ea579ce16fcc4db | <|skeleton|>
class HeaderInjectionCheck:
"""Checks for Header Injection in the response's header. The payload sets a cookie of 'ava=avascan' using CRLF character variations, such as removing each CR/LF character and encoding as UTF-8."""
def __init__(self):
"""Define static payloads"""
<|body_0... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HeaderInjectionCheck:
"""Checks for Header Injection in the response's header. The payload sets a cookie of 'ava=avascan' using CRLF character variations, such as removing each CR/LF character and encoding as UTF-8."""
def __init__(self):
"""Define static payloads"""
payloads = ['\r\nSet-... | the_stack_v2_python_sparse | ava/actives/header_injection.py | indeedsecurity/ava | train | 10 |
013c9018ed5c308ede628fd084f5bb063abb065f | [
"LOG.info('Initializing - Version:{}'.format(__version__))\nself.m_pyhouse_obj = p_pyhouse_obj\nself.m_config = Config(p_pyhouse_obj)\nself.m_utility = Utility(p_pyhouse_obj)\np_pyhouse_obj.House = HouseInformation()\nself.m_location_api = location.Api(p_pyhouse_obj)\nself.m_floor_api = floors.Api(p_pyhouse_obj)\ns... | <|body_start_0|>
LOG.info('Initializing - Version:{}'.format(__version__))
self.m_pyhouse_obj = p_pyhouse_obj
self.m_config = Config(p_pyhouse_obj)
self.m_utility = Utility(p_pyhouse_obj)
p_pyhouse_obj.House = HouseInformation()
self.m_location_api = location.Api(p_pyhous... | API | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class API:
def __init__(self, p_pyhouse_obj):
"""**NoReactor** This is part of Core PyHouse - House is the reason we are running! Note that the reactor is not yet running."""
<|body_0|>
def LoadConfig(self):
"""The house is always present but the components of the house ar... | stack_v2_sparse_classes_10k_train_003363 | 14,568 | no_license | [
{
"docstring": "**NoReactor** This is part of Core PyHouse - House is the reason we are running! Note that the reactor is not yet running.",
"name": "__init__",
"signature": "def __init__(self, p_pyhouse_obj)"
},
{
"docstring": "The house is always present but the components of the house are plu... | 5 | stack_v2_sparse_classes_30k_train_003726 | Implement the Python class `API` described below.
Class description:
Implement the API class.
Method signatures and docstrings:
- def __init__(self, p_pyhouse_obj): **NoReactor** This is part of Core PyHouse - House is the reason we are running! Note that the reactor is not yet running.
- def LoadConfig(self): The ho... | Implement the Python class `API` described below.
Class description:
Implement the API class.
Method signatures and docstrings:
- def __init__(self, p_pyhouse_obj): **NoReactor** This is part of Core PyHouse - House is the reason we are running! Note that the reactor is not yet running.
- def LoadConfig(self): The ho... | 8ccbbd1494b7b33ff5099d321cda634fbb254ceb | <|skeleton|>
class API:
def __init__(self, p_pyhouse_obj):
"""**NoReactor** This is part of Core PyHouse - House is the reason we are running! Note that the reactor is not yet running."""
<|body_0|>
def LoadConfig(self):
"""The house is always present but the components of the house ar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class API:
def __init__(self, p_pyhouse_obj):
"""**NoReactor** This is part of Core PyHouse - House is the reason we are running! Note that the reactor is not yet running."""
LOG.info('Initializing - Version:{}'.format(__version__))
self.m_pyhouse_obj = p_pyhouse_obj
self.m_config = ... | the_stack_v2_python_sparse | Project/src/Modules/House/house.py | bopopescu/PyHouse | train | 0 | |
efe07249cb12578db74937b05e27f5beaada33a8 | [
"self._mutation_rate = mutation_rate\nself._mutation_rand = random.Random()\nself._switch_rand = random.Random()\nself._pos_rand = random.Random()",
"mutated_org = organism.copy()\ngene_choices = mutated_org.genome.alphabet.letters\nmutation_chance = self._mutation_rand.random()\nif mutation_chance <= self._mutat... | <|body_start_0|>
self._mutation_rate = mutation_rate
self._mutation_rand = random.Random()
self._switch_rand = random.Random()
self._pos_rand = random.Random()
<|end_body_0|>
<|body_start_1|>
mutated_org = organism.copy()
gene_choices = mutated_org.genome.alphabet.letter... | Perform a conversion mutation, but only at a single point in the genome. This does not randomize the genome as much as ConversionMutation, since only one change is allowed per genome at the specified mutation rate. | SinglePositionMutation | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SinglePositionMutation:
"""Perform a conversion mutation, but only at a single point in the genome. This does not randomize the genome as much as ConversionMutation, since only one change is allowed per genome at the specified mutation rate."""
def __init__(self, mutation_rate=0.001):
... | stack_v2_sparse_classes_10k_train_003364 | 3,166 | permissive | [
{
"docstring": "Initialize a mutator. Arguments: o mutation_rate - The chance of a mutation happening once in the genome.",
"name": "__init__",
"signature": "def __init__(self, mutation_rate=0.001)"
},
{
"docstring": "Mutate the organisms genome.",
"name": "mutate",
"signature": "def mut... | 2 | stack_v2_sparse_classes_30k_test_000327 | Implement the Python class `SinglePositionMutation` described below.
Class description:
Perform a conversion mutation, but only at a single point in the genome. This does not randomize the genome as much as ConversionMutation, since only one change is allowed per genome at the specified mutation rate.
Method signatur... | Implement the Python class `SinglePositionMutation` described below.
Class description:
Perform a conversion mutation, but only at a single point in the genome. This does not randomize the genome as much as ConversionMutation, since only one change is allowed per genome at the specified mutation rate.
Method signatur... | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | <|skeleton|>
class SinglePositionMutation:
"""Perform a conversion mutation, but only at a single point in the genome. This does not randomize the genome as much as ConversionMutation, since only one change is allowed per genome at the specified mutation rate."""
def __init__(self, mutation_rate=0.001):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SinglePositionMutation:
"""Perform a conversion mutation, but only at a single point in the genome. This does not randomize the genome as much as ConversionMutation, since only one change is allowed per genome at the specified mutation rate."""
def __init__(self, mutation_rate=0.001):
"""Initiali... | the_stack_v2_python_sparse | bin/last_wrapper/Bio/GA/Mutation/Simple.py | LyonsLab/coge | train | 41 |
b22b9964a2f842567ae74166802036d1ffd01a79 | [
"assert isinstance(output_space, ContainerSpace), 'ERROR: `output_space` must be a ContainerSpace (Dict or Tuple)!'\nsuper(Merger, self).__init__(scope=scope, **kwargs)\nself.output_space = output_space\nassert isinstance(output_space, ContainerSpace), 'ERROR: `output_space` of Merger Component must be a ContainerS... | <|body_start_0|>
assert isinstance(output_space, ContainerSpace), 'ERROR: `output_space` must be a ContainerSpace (Dict or Tuple)!'
super(Merger, self).__init__(scope=scope, **kwargs)
self.output_space = output_space
assert isinstance(output_space, ContainerSpace), 'ERROR: `output_space`... | Merges incoming items into one FlattenedDataOp. | Merger | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Merger:
"""Merges incoming items into one FlattenedDataOp."""
def __init__(self, output_space, scope='merger', **kwargs):
"""Args: output_space (Space): The output Space to merge to from the single components. Must be a ContainerSpace."""
<|body_0|>
def _graph_fn_merge(s... | stack_v2_sparse_classes_10k_train_003365 | 2,587 | permissive | [
{
"docstring": "Args: output_space (Space): The output Space to merge to from the single components. Must be a ContainerSpace.",
"name": "__init__",
"signature": "def __init__(self, output_space, scope='merger', **kwargs)"
},
{
"docstring": "Merges the inputs into a single FlattenedDataOp. Args:... | 2 | stack_v2_sparse_classes_30k_train_004638 | Implement the Python class `Merger` described below.
Class description:
Merges incoming items into one FlattenedDataOp.
Method signatures and docstrings:
- def __init__(self, output_space, scope='merger', **kwargs): Args: output_space (Space): The output Space to merge to from the single components. Must be a Contain... | Implement the Python class `Merger` described below.
Class description:
Merges incoming items into one FlattenedDataOp.
Method signatures and docstrings:
- def __init__(self, output_space, scope='merger', **kwargs): Args: output_space (Space): The output Space to merge to from the single components. Must be a Contain... | ff7d4768579c0e30aa6ceb932cd16f1e51940010 | <|skeleton|>
class Merger:
"""Merges incoming items into one FlattenedDataOp."""
def __init__(self, output_space, scope='merger', **kwargs):
"""Args: output_space (Space): The output Space to merge to from the single components. Must be a ContainerSpace."""
<|body_0|>
def _graph_fn_merge(s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Merger:
"""Merges incoming items into one FlattenedDataOp."""
def __init__(self, output_space, scope='merger', **kwargs):
"""Args: output_space (Space): The output Space to merge to from the single components. Must be a ContainerSpace."""
assert isinstance(output_space, ContainerSpace), '... | the_stack_v2_python_sparse | yarl/components/common/merger.py | pascalwhoop/YARL | train | 0 |
a33d9ebca4a7476b41a3c0ab88702e913a5d60ba | [
"self.mode = mode\nself.allowed_urls = allowed_urls\nself.allowed_files = allowed_files",
"if dictionary is None:\n return None\nmode = dictionary.get('mode')\nallowed_urls = None\nif dictionary.get('allowedUrls') != None:\n allowed_urls = list()\n for structure in dictionary.get('allowedUrls'):\n ... | <|body_start_0|>
self.mode = mode
self.allowed_urls = allowed_urls
self.allowed_files = allowed_files
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
mode = dictionary.get('mode')
allowed_urls = None
if dictionary.get('allowedUrls')... | Implementation of the 'updateNetworkSecurityMalwareSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'enabled' to enable malware prevention, otherwise 'disabled' allowed_urls (list of AllowedUrlModel): The urls that should be permitted by the malware detection engine. If omitted... | UpdateNetworkSecurityMalwareSettingsModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateNetworkSecurityMalwareSettingsModel:
"""Implementation of the 'updateNetworkSecurityMalwareSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'enabled' to enable malware prevention, otherwise 'disabled' allowed_urls (list of AllowedUrlModel): The urls... | stack_v2_sparse_classes_10k_train_003366 | 3,077 | permissive | [
{
"docstring": "Constructor for the UpdateNetworkSecurityMalwareSettingsModel class",
"name": "__init__",
"signature": "def __init__(self, mode=None, allowed_urls=None, allowed_files=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A di... | 2 | null | Implement the Python class `UpdateNetworkSecurityMalwareSettingsModel` described below.
Class description:
Implementation of the 'updateNetworkSecurityMalwareSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'enabled' to enable malware prevention, otherwise 'disabled' allowed_u... | Implement the Python class `UpdateNetworkSecurityMalwareSettingsModel` described below.
Class description:
Implementation of the 'updateNetworkSecurityMalwareSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'enabled' to enable malware prevention, otherwise 'disabled' allowed_u... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class UpdateNetworkSecurityMalwareSettingsModel:
"""Implementation of the 'updateNetworkSecurityMalwareSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'enabled' to enable malware prevention, otherwise 'disabled' allowed_urls (list of AllowedUrlModel): The urls... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpdateNetworkSecurityMalwareSettingsModel:
"""Implementation of the 'updateNetworkSecurityMalwareSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'enabled' to enable malware prevention, otherwise 'disabled' allowed_urls (list of AllowedUrlModel): The urls that should ... | the_stack_v2_python_sparse | meraki_sdk/models/update_network_security_malware_settings_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
e82d1080472569ba433d54900246adfcc73093c3 | [
"self.ensure_one()\nif self.country_id.code != 'CL':\n return super()._format_document_number(document_number)\nif not document_number:\n return False\nreturn document_number.zfill(6)",
"self.ensure_one()\nif self.country_id.code == 'CL' and self.code in ['39', '41', '110', '111', '112', '34']:\n return ... | <|body_start_0|>
self.ensure_one()
if self.country_id.code != 'CL':
return super()._format_document_number(document_number)
if not document_number:
return False
return document_number.zfill(6)
<|end_body_0|>
<|body_start_1|>
self.ensure_one()
if s... | L10nLatamDocumentType | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class L10nLatamDocumentType:
def _format_document_number(self, document_number):
"""Make validation of Import Dispatch Number * making validations on the document_number. If it is wrong it should raise an exception * format the document_number against a pattern and return it"""
<|body_... | stack_v2_sparse_classes_10k_train_003367 | 1,398 | permissive | [
{
"docstring": "Make validation of Import Dispatch Number * making validations on the document_number. If it is wrong it should raise an exception * format the document_number against a pattern and return it",
"name": "_format_document_number",
"signature": "def _format_document_number(self, document_nu... | 2 | null | Implement the Python class `L10nLatamDocumentType` described below.
Class description:
Implement the L10nLatamDocumentType class.
Method signatures and docstrings:
- def _format_document_number(self, document_number): Make validation of Import Dispatch Number * making validations on the document_number. If it is wron... | Implement the Python class `L10nLatamDocumentType` described below.
Class description:
Implement the L10nLatamDocumentType class.
Method signatures and docstrings:
- def _format_document_number(self, document_number): Make validation of Import Dispatch Number * making validations on the document_number. If it is wron... | 310497a9872db7844b521e6dab5f7a9f61d365a4 | <|skeleton|>
class L10nLatamDocumentType:
def _format_document_number(self, document_number):
"""Make validation of Import Dispatch Number * making validations on the document_number. If it is wrong it should raise an exception * format the document_number against a pattern and return it"""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class L10nLatamDocumentType:
def _format_document_number(self, document_number):
"""Make validation of Import Dispatch Number * making validations on the document_number. If it is wrong it should raise an exception * format the document_number against a pattern and return it"""
self.ensure_one()
... | the_stack_v2_python_sparse | addons/l10n_cl/models/l10n_latam_document_type.py | SHIVJITH/Odoo_Machine_Test | train | 0 | |
b5e7cdc5752a78168aa4cc3cad4b9861cd7ce4e5 | [
"self.__case_folder = CaseFolder()\nself.__tokenizer = Tokenizer()\nstopword_remover_factory = StopwordRemoverFactory()\nself.__stopword_remover = stopword_remover_factory.create()\nstemmer_factory = StemmerFactory()\nself.__stemmer = stemmer_factory.create()\nself.__tf_unigram = TfUnigram()\nself.__tf_bigram = TfB... | <|body_start_0|>
self.__case_folder = CaseFolder()
self.__tokenizer = Tokenizer()
stopword_remover_factory = StopwordRemoverFactory()
self.__stopword_remover = stopword_remover_factory.create()
stemmer_factory = StemmerFactory()
self.__stemmer = stemmer_factory.create()
... | Bertugas Melakukan Pemrosesan Teks (Text Proeprocessing) | Preprocesser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preprocesser:
"""Bertugas Melakukan Pemrosesan Teks (Text Proeprocessing)"""
def __init__(self):
"""Konstruktor"""
<|body_0|>
def __del__(self):
"""Destructor"""
<|body_1|>
def __get_features(self, tokens: list):
"""Mendapatkan Fitur Ruang-Ve... | stack_v2_sparse_classes_10k_train_003368 | 2,073 | no_license | [
{
"docstring": "Konstruktor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Destructor",
"name": "__del__",
"signature": "def __del__(self)"
},
{
"docstring": "Mendapatkan Fitur Ruang-Vektor Kombinasi Unigram dan Bigram",
"name": "__get_features",
... | 5 | stack_v2_sparse_classes_30k_train_005389 | Implement the Python class `Preprocesser` described below.
Class description:
Bertugas Melakukan Pemrosesan Teks (Text Proeprocessing)
Method signatures and docstrings:
- def __init__(self): Konstruktor
- def __del__(self): Destructor
- def __get_features(self, tokens: list): Mendapatkan Fitur Ruang-Vektor Kombinasi ... | Implement the Python class `Preprocesser` described below.
Class description:
Bertugas Melakukan Pemrosesan Teks (Text Proeprocessing)
Method signatures and docstrings:
- def __init__(self): Konstruktor
- def __del__(self): Destructor
- def __get_features(self, tokens: list): Mendapatkan Fitur Ruang-Vektor Kombinasi ... | 9742c193251303334ef805c8c94eb075afad777f | <|skeleton|>
class Preprocesser:
"""Bertugas Melakukan Pemrosesan Teks (Text Proeprocessing)"""
def __init__(self):
"""Konstruktor"""
<|body_0|>
def __del__(self):
"""Destructor"""
<|body_1|>
def __get_features(self, tokens: list):
"""Mendapatkan Fitur Ruang-Ve... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Preprocesser:
"""Bertugas Melakukan Pemrosesan Teks (Text Proeprocessing)"""
def __init__(self):
"""Konstruktor"""
self.__case_folder = CaseFolder()
self.__tokenizer = Tokenizer()
stopword_remover_factory = StopwordRemoverFactory()
self.__stopword_remover = stopwor... | the_stack_v2_python_sparse | ujian_app/penilaian/pemrosesan_teks/preprocesser.py | anh4rs/Aplikasi-Penilaian-Otomatis-Esai-BI | train | 0 |
af9c5d93d664488664c15ee68ef6574f2126d5ca | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Parameter()",
"from .value_type import ValueType\nfrom .value_type import ValueType\nfields: Dict[str, Callable[[Any], None]] = {'name': lambda n: setattr(self, 'name', n.get_str_value()), '@odata.type': lambda n: setattr(self, 'odata_... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Parameter()
<|end_body_0|>
<|body_start_1|>
from .value_type import ValueType
from .value_type import ValueType
fields: Dict[str, Callable[[Any], None]] = {'name': lambda n: seta... | Parameter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parameter:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Parameter:
"""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: Parame... | stack_v2_sparse_classes_10k_train_003369 | 3,021 | 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: Parameter",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(par... | 3 | null | Implement the Python class `Parameter` described below.
Class description:
Implement the Parameter class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Parameter: Creates a new instance of the appropriate class based on discriminator value Args: parse... | Implement the Python class `Parameter` described below.
Class description:
Implement the Parameter class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Parameter: Creates a new instance of the appropriate class based on discriminator value Args: parse... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Parameter:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Parameter:
"""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: Parame... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Parameter:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Parameter:
"""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: Parameter"""
... | the_stack_v2_python_sparse | msgraph/generated/models/identity_governance/parameter.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
2db7ed8951cad880e828dbb04b7ad6d53582d307 | [
"super(DQNBase, self).__init__()\nencoder_kwargs, lstm_kwargs, head_kwargs = get_kwargs(kwargs)\nself._encoder = Encoder(obs_dim, embedding_dim, **encoder_kwargs)\nif lstm_kwargs['lstm_type'] != 'none':\n lstm_kwargs['input_size'] = embedding_dim\n lstm_kwargs['hidden_size'] = embedding_dim\n self._lstm = ... | <|body_start_0|>
super(DQNBase, self).__init__()
encoder_kwargs, lstm_kwargs, head_kwargs = get_kwargs(kwargs)
self._encoder = Encoder(obs_dim, embedding_dim, **encoder_kwargs)
if lstm_kwargs['lstm_type'] != 'none':
lstm_kwargs['input_size'] = embedding_dim
lstm_k... | Overview: Base class for DQN based models. Interface: __init__, forward, fast_timestep_forward | DQNBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DQNBase:
"""Overview: Base class for DQN based models. Interface: __init__, forward, fast_timestep_forward"""
def __init__(self, obs_dim: Union[int, tuple], action_dim: tuple, embedding_dim: int=64, **kwargs) -> None:
"""Overview: Init the DQNBase according to arguments, including en... | stack_v2_sparse_classes_10k_train_003370 | 9,851 | permissive | [
{
"docstring": "Overview: Init the DQNBase according to arguments, including encoder, lstm(if needed) and head. Arguments: - obs_dim (:obj:`Union[int, tuple]`): a tuple of observation dim - action_dim (:obj:`int`): the num of action dim, \\\\ note that it can be a tuple containing more than one element - embedd... | 3 | stack_v2_sparse_classes_30k_train_003336 | Implement the Python class `DQNBase` described below.
Class description:
Overview: Base class for DQN based models. Interface: __init__, forward, fast_timestep_forward
Method signatures and docstrings:
- def __init__(self, obs_dim: Union[int, tuple], action_dim: tuple, embedding_dim: int=64, **kwargs) -> None: Overvi... | Implement the Python class `DQNBase` described below.
Class description:
Overview: Base class for DQN based models. Interface: __init__, forward, fast_timestep_forward
Method signatures and docstrings:
- def __init__(self, obs_dim: Union[int, tuple], action_dim: tuple, embedding_dim: int=64, **kwargs) -> None: Overvi... | 09d507c412235a2f0cf9c0b3485ec9ed15fb6421 | <|skeleton|>
class DQNBase:
"""Overview: Base class for DQN based models. Interface: __init__, forward, fast_timestep_forward"""
def __init__(self, obs_dim: Union[int, tuple], action_dim: tuple, embedding_dim: int=64, **kwargs) -> None:
"""Overview: Init the DQNBase according to arguments, including en... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DQNBase:
"""Overview: Base class for DQN based models. Interface: __init__, forward, fast_timestep_forward"""
def __init__(self, obs_dim: Union[int, tuple], action_dim: tuple, embedding_dim: int=64, **kwargs) -> None:
"""Overview: Init the DQNBase according to arguments, including encoder, lstm(i... | the_stack_v2_python_sparse | ctools/model/dqn/dqn_network.py | LFhase/DI-star | train | 1 |
f011f099de166710225d93a1e7b85e36fa4c0ca7 | [
"if ShowProductsAndCustomers.mongo is None:\n return 'connection not found'\nwith ShowProductsAndCustomers.mongo:\n norton_db = ShowProductsAndCustomers.mongo.connection.NortonDB\n products_list = []\n try:\n products = norton_db['products']\n products_collection = products.find()\n ... | <|body_start_0|>
if ShowProductsAndCustomers.mongo is None:
return 'connection not found'
with ShowProductsAndCustomers.mongo:
norton_db = ShowProductsAndCustomers.mongo.connection.NortonDB
products_list = []
try:
products = norton_db['prod... | show products class | ShowProductsAndCustomers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShowProductsAndCustomers:
"""show products class"""
def see_products_for_rent():
"""return a list of all products"""
<|body_0|>
def see_all_different_products():
"""Returns a Python dictionary of products listed as available with the following fields: product_id,... | stack_v2_sparse_classes_10k_train_003371 | 9,178 | no_license | [
{
"docstring": "return a list of all products",
"name": "see_products_for_rent",
"signature": "def see_products_for_rent()"
},
{
"docstring": "Returns a Python dictionary of products listed as available with the following fields: product_id, description, product_type, quantity_available",
"n... | 3 | null | Implement the Python class `ShowProductsAndCustomers` described below.
Class description:
show products class
Method signatures and docstrings:
- def see_products_for_rent(): return a list of all products
- def see_all_different_products(): Returns a Python dictionary of products listed as available with the followin... | Implement the Python class `ShowProductsAndCustomers` described below.
Class description:
show products class
Method signatures and docstrings:
- def see_products_for_rent(): return a list of all products
- def see_all_different_products(): Returns a Python dictionary of products listed as available with the followin... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class ShowProductsAndCustomers:
"""show products class"""
def see_products_for_rent():
"""return a list of all products"""
<|body_0|>
def see_all_different_products():
"""Returns a Python dictionary of products listed as available with the following fields: product_id,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ShowProductsAndCustomers:
"""show products class"""
def see_products_for_rent():
"""return a list of all products"""
if ShowProductsAndCustomers.mongo is None:
return 'connection not found'
with ShowProductsAndCustomers.mongo:
norton_db = ShowProductsAndCus... | the_stack_v2_python_sparse | students/michael_mcdonald/lesson5/database.py | JavaRod/SP_Python220B_2019 | train | 1 |
8f0708deafcad02261115190644b4b073e5ed17c | [
"cnt = collections.Counter(words)\nheap = [(-freq, word) for word, freq in cnt.items()]\nheapq.heapify(heap)\nreturn [heapq.heappop(heap)[1] for _ in range(k)]",
"import collections\ncnt = collections.Counter(words)\nkeys = list(cnt.keys())\nkeys.sort(key=lambda w: (-cnt[w], w))\nreturn keys[:k]"
] | <|body_start_0|>
cnt = collections.Counter(words)
heap = [(-freq, word) for word, freq in cnt.items()]
heapq.heapify(heap)
return [heapq.heappop(heap)[1] for _ in range(k)]
<|end_body_0|>
<|body_start_1|>
import collections
cnt = collections.Counter(words)
keys =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def topKFrequent(self, words, k):
""":type words: List[str] :type k: int :rtype: List[str]"""
<|body_0|>
def topKFrequentSort(self, words, k):
""":type words: List[str] :type k: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_10k_train_003372 | 920 | no_license | [
{
"docstring": ":type words: List[str] :type k: int :rtype: List[str]",
"name": "topKFrequent",
"signature": "def topKFrequent(self, words, k)"
},
{
"docstring": ":type words: List[str] :type k: int :rtype: List[str]",
"name": "topKFrequentSort",
"signature": "def topKFrequentSort(self, ... | 2 | stack_v2_sparse_classes_30k_train_005282 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, words, k): :type words: List[str] :type k: int :rtype: List[str]
- def topKFrequentSort(self, words, k): :type words: List[str] :type k: int :rtype: List[s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, words, k): :type words: List[str] :type k: int :rtype: List[str]
- def topKFrequentSort(self, words, k): :type words: List[str] :type k: int :rtype: List[s... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def topKFrequent(self, words, k):
""":type words: List[str] :type k: int :rtype: List[str]"""
<|body_0|>
def topKFrequentSort(self, words, k):
""":type words: List[str] :type k: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def topKFrequent(self, words, k):
""":type words: List[str] :type k: int :rtype: List[str]"""
cnt = collections.Counter(words)
heap = [(-freq, word) for word, freq in cnt.items()]
heapq.heapify(heap)
return [heapq.heappop(heap)[1] for _ in range(k)]
def t... | the_stack_v2_python_sparse | words/top_k_frequent_words.py | hwc1824/LeetCodeSolution | train | 0 | |
48165ed8ac03ed27d2a6ca76be28f6ab6314d1a7 | [
"citations.sort(reverse=True)\ni = 0\nwhile i < len(citations) and i + 1 <= citations[i]:\n i += 1\nreturn i",
"n = len(citations)\ncounter = defaultdict(int)\nacc = 0\nfor citation in citations:\n counter[citation] += 1\n if citation <= 0:\n acc += 1\ni = 1\nwhile i <= n:\n if n - acc < i:\n ... | <|body_start_0|>
citations.sort(reverse=True)
i = 0
while i < len(citations) and i + 1 <= citations[i]:
i += 1
return i
<|end_body_0|>
<|body_start_1|>
n = len(citations)
counter = defaultdict(int)
acc = 0
for citation in citations:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hIndexnlgn(self, citations):
"""O(nlgn) solution. :type citations: List[int] :rtype: int"""
<|body_0|>
def hIndex(self, citations):
"""O(n) solution. Most certainly you need to check the relationship: left: i right: num of var that is >= i. if left <= r... | stack_v2_sparse_classes_10k_train_003373 | 2,929 | no_license | [
{
"docstring": "O(nlgn) solution. :type citations: List[int] :rtype: int",
"name": "hIndexnlgn",
"signature": "def hIndexnlgn(self, citations)"
},
{
"docstring": "O(n) solution. Most certainly you need to check the relationship: left: i right: num of var that is >= i. if left <= right, i is a po... | 2 | stack_v2_sparse_classes_30k_train_001247 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hIndexnlgn(self, citations): O(nlgn) solution. :type citations: List[int] :rtype: int
- def hIndex(self, citations): O(n) solution. Most certainly you need to check the relat... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hIndexnlgn(self, citations): O(nlgn) solution. :type citations: List[int] :rtype: int
- def hIndex(self, citations): O(n) solution. Most certainly you need to check the relat... | 33c623f226981942780751554f0593f2c71cf458 | <|skeleton|>
class Solution:
def hIndexnlgn(self, citations):
"""O(nlgn) solution. :type citations: List[int] :rtype: int"""
<|body_0|>
def hIndex(self, citations):
"""O(n) solution. Most certainly you need to check the relationship: left: i right: num of var that is >= i. if left <= r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def hIndexnlgn(self, citations):
"""O(nlgn) solution. :type citations: List[int] :rtype: int"""
citations.sort(reverse=True)
i = 0
while i < len(citations) and i + 1 <= citations[i]:
i += 1
return i
def hIndex(self, citations):
"""O(n)... | the_stack_v2_python_sparse | arr/leetcode_H_Index.py | monkeylyf/interviewjam | train | 59 | |
0528402cc2c7e48fa740de49ee4e7ac618ef613c | [
"self.conn = Connection(password=get_environment_variable('VEN_ADWORDS_PASSWORD'), developer_token=get_environment_variable('VEN_ADWORDS_TOKEN'), account_id=account_id)\nself.awq = AWQ(self.conn)\nself.gmoney = GMoney(min_money=min_money, max_money=max_money)\nself.ops = Operations(self.gmoney)\nself.mutations = Mu... | <|body_start_0|>
self.conn = Connection(password=get_environment_variable('VEN_ADWORDS_PASSWORD'), developer_token=get_environment_variable('VEN_ADWORDS_TOKEN'), account_id=account_id)
self.awq = AWQ(self.conn)
self.gmoney = GMoney(min_money=min_money, max_money=max_money)
self.ops = Ope... | KeywordOperationsBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeywordOperationsBase:
def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000):
"""Pass in min and max (in Euros, NOT micros) based bid if you want to override the GMoney defaults store: storage that acts like an... | stack_v2_sparse_classes_10k_train_003374 | 3,450 | permissive | [
{
"docstring": "Pass in min and max (in Euros, NOT micros) based bid if you want to override the GMoney defaults store: storage that acts like an HDF5 store",
"name": "__init__",
"signature": "def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.D... | 4 | stack_v2_sparse_classes_30k_train_004614 | Implement the Python class `KeywordOperationsBase` described below.
Class description:
Implement the KeywordOperationsBase class.
Method signatures and docstrings:
- def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000): Pass in min and max... | Implement the Python class `KeywordOperationsBase` described below.
Class description:
Implement the KeywordOperationsBase class.
Method signatures and docstrings:
- def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000): Pass in min and max... | 72dbdf41b0250708ad525030128cc7c3948b3f41 | <|skeleton|>
class KeywordOperationsBase:
def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000):
"""Pass in min and max (in Euros, NOT micros) based bid if you want to override the GMoney defaults store: storage that acts like an... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KeywordOperationsBase:
def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000):
"""Pass in min and max (in Euros, NOT micros) based bid if you want to override the GMoney defaults store: storage that acts like an HDF5 store"""... | the_stack_v2_python_sparse | ut/aw/keyword_operations_base.py | thorwhalen/ut | train | 6 | |
e0d5131221bbcf0b806cce2dfb3dae8b44cdc75e | [
"val = 0\nfor i in range(len(A)):\n for j in reversed(range(i + 1 + val, len(A))):\n if A[i] <= A[j]:\n val = max(val, j - i)\n break\nreturn val",
"from collections import defaultdict\ndp = defaultdict(int)\ndp[0] = 0\nval = 0\nfor i in range(1, len(A)):\n for j in range(i):\n ... | <|body_start_0|>
val = 0
for i in range(len(A)):
for j in reversed(range(i + 1 + val, len(A))):
if A[i] <= A[j]:
val = max(val, j - i)
break
return val
<|end_body_0|>
<|body_start_1|>
from collections import defaultdict... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxWidthRamp1(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def maxWidthRamp(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
val = 0
for i in range(len(A)):
fo... | stack_v2_sparse_classes_10k_train_003375 | 868 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int",
"name": "maxWidthRamp1",
"signature": "def maxWidthRamp1(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: int",
"name": "maxWidthRamp",
"signature": "def maxWidthRamp(self, A)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006083 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxWidthRamp1(self, A): :type A: List[int] :rtype: int
- def maxWidthRamp(self, A): :type A: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxWidthRamp1(self, A): :type A: List[int] :rtype: int
- def maxWidthRamp(self, A): :type A: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxWidthRamp1(self, ... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class Solution:
def maxWidthRamp1(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def maxWidthRamp(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxWidthRamp1(self, A):
""":type A: List[int] :rtype: int"""
val = 0
for i in range(len(A)):
for j in reversed(range(i + 1 + val, len(A))):
if A[i] <= A[j]:
val = max(val, j - i)
break
return val
... | the_stack_v2_python_sparse | maximum-width-ramp/solution.py | uxlsl/leetcode_practice | train | 0 | |
fc909699fb192232c2293ff871d2971a1d836bf3 | [
"res.append(partial)\nn = len(nums)\nif start >= n:\n return\nlast = float('inf')\nfor i in range(start, n):\n if nums[i] == last:\n continue\n last = nums[i]\n self._subsetsWithDup(nums, i + 1, partial + [nums[i]], res)",
"res = []\npartial = []\nself._subsetsWithDup(sorted(nums), 0, partial, ... | <|body_start_0|>
res.append(partial)
n = len(nums)
if start >= n:
return
last = float('inf')
for i in range(start, n):
if nums[i] == last:
continue
last = nums[i]
self._subsetsWithDup(nums, i + 1, partial + [nums[i]]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _subsetsWithDup(self, nums, start, partial, res):
""":type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]] :rtype: void"""
<|body_0|>
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]""... | stack_v2_sparse_classes_10k_train_003376 | 1,454 | no_license | [
{
"docstring": ":type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]] :rtype: void",
"name": "_subsetsWithDup",
"signature": "def _subsetsWithDup(self, nums, start, partial, res)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_001401 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _subsetsWithDup(self, nums, start, partial, res): :type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]] :rtype: void
- def subsetsWithDup... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _subsetsWithDup(self, nums, start, partial, res): :type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]] :rtype: void
- def subsetsWithDup... | cd3900a7d91d1d94d308bc7a65533b8262781ee9 | <|skeleton|>
class Solution:
def _subsetsWithDup(self, nums, start, partial, res):
""":type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]] :rtype: void"""
<|body_0|>
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def _subsetsWithDup(self, nums, start, partial, res):
""":type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]] :rtype: void"""
res.append(partial)
n = len(nums)
if start >= n:
return
last = float('inf')
... | the_stack_v2_python_sparse | lc0090_SubsetsII/lc0090.py | cgi0911/LeetCodePractice | train | 0 | |
44d160bd335180af752386c8ffa6662bacf81c5c | [
"self._dbg = debug\nself._log = get_logger(self.__class__.__name__, self._dbg)\nself._log.debug('midi_file=%s, channel=%s', midi_file, channel)\nself._log.debug('dst=%s', dst)\nself._log.debug('note_origin=%s', note_origin)\nself._log.debug('no_note_offset_flag=%s', no_note_offset_flag)\nself._log.debug('wav_mode=%... | <|body_start_0|>
self._dbg = debug
self._log = get_logger(self.__class__.__name__, self._dbg)
self._log.debug('midi_file=%s, channel=%s', midi_file, channel)
self._log.debug('dst=%s', dst)
self._log.debug('note_origin=%s', note_origin)
self._log.debug('no_note_offset_flag... | MidiApp | MidiApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MidiApp:
"""MidiApp"""
def __init__(self, midi_file, dst=(), channel=[], note_origin=-1, no_note_offset_flag=False, wav_mode=0, debug=False) -> None:
"""Constructor Parameters ---------- midi_file: str dst: str channel: list of int note_origin: int no_note_offset_flag: bool wav_mode:... | stack_v2_sparse_classes_10k_train_003377 | 25,197 | no_license | [
{
"docstring": "Constructor Parameters ---------- midi_file: str dst: str channel: list of int note_origin: int no_note_offset_flag: bool wav_mode: int",
"name": "__init__",
"signature": "def __init__(self, midi_file, dst=(), channel=[], note_origin=-1, no_note_offset_flag=False, wav_mode=0, debug=False... | 2 | stack_v2_sparse_classes_30k_train_003127 | Implement the Python class `MidiApp` described below.
Class description:
MidiApp
Method signatures and docstrings:
- def __init__(self, midi_file, dst=(), channel=[], note_origin=-1, no_note_offset_flag=False, wav_mode=0, debug=False) -> None: Constructor Parameters ---------- midi_file: str dst: str channel: list of... | Implement the Python class `MidiApp` described below.
Class description:
MidiApp
Method signatures and docstrings:
- def __init__(self, midi_file, dst=(), channel=[], note_origin=-1, no_note_offset_flag=False, wav_mode=0, debug=False) -> None: Constructor Parameters ---------- midi_file: str dst: str channel: list of... | b8264118d19c7f6c6be9b11f18c890c598eb1295 | <|skeleton|>
class MidiApp:
"""MidiApp"""
def __init__(self, midi_file, dst=(), channel=[], note_origin=-1, no_note_offset_flag=False, wav_mode=0, debug=False) -> None:
"""Constructor Parameters ---------- midi_file: str dst: str channel: list of int note_origin: int no_note_offset_flag: bool wav_mode:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MidiApp:
"""MidiApp"""
def __init__(self, midi_file, dst=(), channel=[], note_origin=-1, no_note_offset_flag=False, wav_mode=0, debug=False) -> None:
"""Constructor Parameters ---------- midi_file: str dst: str channel: list of int note_origin: int no_note_offset_flag: bool wav_mode: int"""
... | the_stack_v2_python_sparse | musicbox/__main__.py | ytani01/MusicBox | train | 1 |
9184cb39bebd2bbbad3ad44212c6f27a74219ede | [
"fields = cls.IMPORT_FIELDS\nfor name, field in fields.items():\n base_field = None\n for f in cls._meta.fields:\n if f.name == name:\n base_field = f\n break\n if base_field:\n if 'label' not in field:\n field['label'] = base_field.verbose_name\n if 'h... | <|body_start_0|>
fields = cls.IMPORT_FIELDS
for name, field in fields.items():
base_field = None
for f in cls._meta.fields:
if f.name == name:
base_field = f
break
if base_field:
if 'label' not in... | Model mixin class which provides support for 'data import' functionality. Models which implement this mixin should provide information on the fields available for import | DataImportMixin | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataImportMixin:
"""Model mixin class which provides support for 'data import' functionality. Models which implement this mixin should provide information on the fields available for import"""
def get_import_fields(cls):
"""Return all available import fields. Where information on a p... | stack_v2_sparse_classes_10k_train_003378 | 29,718 | permissive | [
{
"docstring": "Return all available import fields. Where information on a particular field is not explicitly provided, introspect the base model to (attempt to) find that information.",
"name": "get_import_fields",
"signature": "def get_import_fields(cls)"
},
{
"docstring": "Return all *require... | 2 | null | Implement the Python class `DataImportMixin` described below.
Class description:
Model mixin class which provides support for 'data import' functionality. Models which implement this mixin should provide information on the fields available for import
Method signatures and docstrings:
- def get_import_fields(cls): Ret... | Implement the Python class `DataImportMixin` described below.
Class description:
Model mixin class which provides support for 'data import' functionality. Models which implement this mixin should provide information on the fields available for import
Method signatures and docstrings:
- def get_import_fields(cls): Ret... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class DataImportMixin:
"""Model mixin class which provides support for 'data import' functionality. Models which implement this mixin should provide information on the fields available for import"""
def get_import_fields(cls):
"""Return all available import fields. Where information on a p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DataImportMixin:
"""Model mixin class which provides support for 'data import' functionality. Models which implement this mixin should provide information on the fields available for import"""
def get_import_fields(cls):
"""Return all available import fields. Where information on a particular fie... | the_stack_v2_python_sparse | InvenTree/InvenTree/models.py | inventree/InvenTree | train | 3,077 |
bd4e9bd5fa99ae3f31eeb99e60615c067f8daf18 | [
"def dt_conv(dt):\n return pd.datetime.strptime(dt, self._dt_fmt)\ndf = pd.read_csv(agt_file, sep=self._sep, converters={0: dt_conv}, names=['timestamp'] + list(self._columns), nrows=nr_lines)\ndf.set_index('timestamp', inplace=True)\nself._current_line += nr_lines\nreturn df",
"line = agt_file.readline().rstr... | <|body_start_0|>
def dt_conv(dt):
return pd.datetime.strptime(dt, self._dt_fmt)
df = pd.read_csv(agt_file, sep=self._sep, converters={0: dt_conv}, names=['timestamp'] + list(self._columns), nrows=nr_lines)
df.set_index('timestamp', inplace=True)
self._current_line += nr_lines... | Parser for agt files that contain sensor data, i.e., timestamps, temerature, and pressure. These files also contain meta-inforamtion that is ignored. | AgtPandasParser | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgtPandasParser:
"""Parser for agt files that contain sensor data, i.e., timestamps, temerature, and pressure. These files also contain meta-inforamtion that is ignored."""
def _read_data(self, agt_file, nr_lines):
"""read data using pandas methods"""
<|body_0|>
def _par... | stack_v2_sparse_classes_10k_train_003379 | 6,235 | permissive | [
{
"docstring": "read data using pandas methods",
"name": "_read_data",
"signature": "def _read_data(self, agt_file, nr_lines)"
},
{
"docstring": "parse footer, i.e., file content after data.",
"name": "_parse_footer",
"signature": "def _parse_footer(self, agt_file)"
}
] | 2 | null | Implement the Python class `AgtPandasParser` described below.
Class description:
Parser for agt files that contain sensor data, i.e., timestamps, temerature, and pressure. These files also contain meta-inforamtion that is ignored.
Method signatures and docstrings:
- def _read_data(self, agt_file, nr_lines): read data... | Implement the Python class `AgtPandasParser` described below.
Class description:
Parser for agt files that contain sensor data, i.e., timestamps, temerature, and pressure. These files also contain meta-inforamtion that is ignored.
Method signatures and docstrings:
- def _read_data(self, agt_file, nr_lines): read data... | e748466a2af9f3388a8b0ed091aa061dbfc752d6 | <|skeleton|>
class AgtPandasParser:
"""Parser for agt files that contain sensor data, i.e., timestamps, temerature, and pressure. These files also contain meta-inforamtion that is ignored."""
def _read_data(self, agt_file, nr_lines):
"""read data using pandas methods"""
<|body_0|>
def _par... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AgtPandasParser:
"""Parser for agt files that contain sensor data, i.e., timestamps, temerature, and pressure. These files also contain meta-inforamtion that is ignored."""
def _read_data(self, agt_file, nr_lines):
"""read data using pandas methods"""
def dt_conv(dt):
return p... | the_stack_v2_python_sparse | Python/DataFormats/agt_parser.py | gjbex/training-material | train | 130 |
c7fd2822d044a839a815846260a5bdbe9be1eabd | [
"self.dim = dim\nself.parts = parts\nself.surface = pygame.Surface(dim)\nself.width, self.height = dim\nself.parts = self._initialize_parts(parts)\nself.radius = self.height // 2\nself.center = pygame.Vector2(self.width // 4, self.height // 2)\nself.timeseries_x = self.width // 2\nself.timeseries = [0.0] * 512\nsel... | <|body_start_0|>
self.dim = dim
self.parts = parts
self.surface = pygame.Surface(dim)
self.width, self.height = dim
self.parts = self._initialize_parts(parts)
self.radius = self.height // 2
self.center = pygame.Vector2(self.width // 4, self.height // 2)
se... | Fourier Animation, left side showing some oscillating vector, right side timelines of x,y,radius,phi | Fourier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fourier:
"""Fourier Animation, left side showing some oscillating vector, right side timelines of x,y,radius,phi"""
def __init__(self, dim: tuple, parts=1):
""":param surface: surface to draw on :param center: center of calculations in (x, y) :param amplitude: maximum amplitude of si... | stack_v2_sparse_classes_10k_train_003380 | 5,878 | no_license | [
{
"docstring": ":param surface: surface to draw on :param center: center of calculations in (x, y) :param amplitude: maximum amplitude of single part :param pats: number of parts to generate",
"name": "__init__",
"signature": "def __init__(self, dim: tuple, parts=1)"
},
{
"docstring": "initializ... | 3 | stack_v2_sparse_classes_30k_train_005220 | Implement the Python class `Fourier` described below.
Class description:
Fourier Animation, left side showing some oscillating vector, right side timelines of x,y,radius,phi
Method signatures and docstrings:
- def __init__(self, dim: tuple, parts=1): :param surface: surface to draw on :param center: center of calcula... | Implement the Python class `Fourier` described below.
Class description:
Fourier Animation, left side showing some oscillating vector, right side timelines of x,y,radius,phi
Method signatures and docstrings:
- def __init__(self, dim: tuple, parts=1): :param surface: surface to draw on :param center: center of calcula... | 1fd421195a2888c0588a49f5a043a1110eedcdbf | <|skeleton|>
class Fourier:
"""Fourier Animation, left side showing some oscillating vector, right side timelines of x,y,radius,phi"""
def __init__(self, dim: tuple, parts=1):
""":param surface: surface to draw on :param center: center of calculations in (x, y) :param amplitude: maximum amplitude of si... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Fourier:
"""Fourier Animation, left side showing some oscillating vector, right side timelines of x,y,radius,phi"""
def __init__(self, dim: tuple, parts=1):
""":param surface: surface to draw on :param center: center of calculations in (x, y) :param amplitude: maximum amplitude of single part :pa... | the_stack_v2_python_sparse | effects/Fourier.py | gunny26/pygame | train | 5 |
769a44c9d325a1bbc356c9db97a6e338a4e2bcd5 | [
"if not s or not wordDict:\n return []\nn = len(s)\nf = [[] for i in range(n)]\nfor i in range(n - 1, -1, -1):\n for j in range(i + 1, n + 1):\n if s[i:j] in wordDict:\n if j == n or len(f[j]) > 0:\n f[i].append(j)\nprint(f)\nreturn self.dfs(0, s, f, '', [])",
"if p == len(s... | <|body_start_0|>
if not s or not wordDict:
return []
n = len(s)
f = [[] for i in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n + 1):
if s[i:j] in wordDict:
if j == n or len(f[j]) > 0:
f... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
"""利用f[i]记录以i为起点的每个片段的终点j,并且片段要在在字典中, 然后从0开始搜索,每次给当前片段加上空格,然后以当前片段的末尾作为 下一次搜索的头部,避免不必要的搜索 深度优先搜索的思想不是体现在字符搜索上,而是单词搜索上 所以要先找出以各个位置字符为开始的单词通过记录最后的位置,来加块之后的搜索"""
<|body_0|>
def dfs(self, p, s, f, now, res):
"""深度优先搜索,当前单词搜索完之后... | stack_v2_sparse_classes_10k_train_003381 | 2,910 | no_license | [
{
"docstring": "利用f[i]记录以i为起点的每个片段的终点j,并且片段要在在字典中, 然后从0开始搜索,每次给当前片段加上空格,然后以当前片段的末尾作为 下一次搜索的头部,避免不必要的搜索 深度优先搜索的思想不是体现在字符搜索上,而是单词搜索上 所以要先找出以各个位置字符为开始的单词通过记录最后的位置,来加块之后的搜索",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
},
{
"docstring": "深度优先搜索,当前单词搜索完之后,从结束为止下一个字符开始搜索",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): 利用f[i]记录以i为起点的每个片段的终点j,并且片段要在在字典中, 然后从0开始搜索,每次给当前片段加上空格,然后以当前片段的末尾作为 下一次搜索的头部,避免不必要的搜索 深度优先搜索的思想不是体现在字符搜索上,而是单词搜索上 所以要先找出以各个位置字符为开始的单词通过记录最后的位置,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): 利用f[i]记录以i为起点的每个片段的终点j,并且片段要在在字典中, 然后从0开始搜索,每次给当前片段加上空格,然后以当前片段的末尾作为 下一次搜索的头部,避免不必要的搜索 深度优先搜索的思想不是体现在字符搜索上,而是单词搜索上 所以要先找出以各个位置字符为开始的单词通过记录最后的位置,... | 95dddb78bccd169d9d219a473627361fe739ab5e | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
"""利用f[i]记录以i为起点的每个片段的终点j,并且片段要在在字典中, 然后从0开始搜索,每次给当前片段加上空格,然后以当前片段的末尾作为 下一次搜索的头部,避免不必要的搜索 深度优先搜索的思想不是体现在字符搜索上,而是单词搜索上 所以要先找出以各个位置字符为开始的单词通过记录最后的位置,来加块之后的搜索"""
<|body_0|>
def dfs(self, p, s, f, now, res):
"""深度优先搜索,当前单词搜索完之后... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak(self, s, wordDict):
"""利用f[i]记录以i为起点的每个片段的终点j,并且片段要在在字典中, 然后从0开始搜索,每次给当前片段加上空格,然后以当前片段的末尾作为 下一次搜索的头部,避免不必要的搜索 深度优先搜索的思想不是体现在字符搜索上,而是单词搜索上 所以要先找出以各个位置字符为开始的单词通过记录最后的位置,来加块之后的搜索"""
if not s or not wordDict:
return []
n = len(s)
f = [[] for i in... | the_stack_v2_python_sparse | BFS&DFS/wordBreak2.py | Philex5/codingPractice | train | 0 | |
d33f5928e4414fbed5d4a09ae32baa2c6f413c19 | [
"super().__init__()\nassert attention_size % n_heads == 0\nself.hidden_size = hidden_size\nself.n_heads = n_heads\nself.head_size = attention_size // n_heads\nself.attention_size = attention_size\nself.hidden_to_query = nn.Linear(hidden_size, attention_size)\nself.hidden_to_key = nn.Linear(hidden_size, attention_si... | <|body_start_0|>
super().__init__()
assert attention_size % n_heads == 0
self.hidden_size = hidden_size
self.n_heads = n_heads
self.head_size = attention_size // n_heads
self.attention_size = attention_size
self.hidden_to_query = nn.Linear(hidden_size, attention_s... | Multihead self-attention | MultiHeadAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
"""Multihead self-attention"""
def __init__(self, hidden_size: int, attention_size: int, n_heads: int, dropout: float, device: str):
"""Constructor Args: hidden_size (int): hidden size of the input. attention_size (int): attention size n_heads (int): number of hea... | stack_v2_sparse_classes_10k_train_003382 | 14,969 | permissive | [
{
"docstring": "Constructor Args: hidden_size (int): hidden size of the input. attention_size (int): attention size n_heads (int): number of heads (attention heads) dropout (double): dropout rate device (string): cuda or cpu",
"name": "__init__",
"signature": "def __init__(self, hidden_size: int, attent... | 2 | stack_v2_sparse_classes_30k_train_000569 | Implement the Python class `MultiHeadAttention` described below.
Class description:
Multihead self-attention
Method signatures and docstrings:
- def __init__(self, hidden_size: int, attention_size: int, n_heads: int, dropout: float, device: str): Constructor Args: hidden_size (int): hidden size of the input. attentio... | Implement the Python class `MultiHeadAttention` described below.
Class description:
Multihead self-attention
Method signatures and docstrings:
- def __init__(self, hidden_size: int, attention_size: int, n_heads: int, dropout: float, device: str): Constructor Args: hidden_size (int): hidden size of the input. attentio... | 5b4a61b5dd0bc259ffe68223877949ef4ebfa5e3 | <|skeleton|>
class MultiHeadAttention:
"""Multihead self-attention"""
def __init__(self, hidden_size: int, attention_size: int, n_heads: int, dropout: float, device: str):
"""Constructor Args: hidden_size (int): hidden size of the input. attention_size (int): attention size n_heads (int): number of hea... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiHeadAttention:
"""Multihead self-attention"""
def __init__(self, hidden_size: int, attention_size: int, n_heads: int, dropout: float, device: str):
"""Constructor Args: hidden_size (int): hidden size of the input. attention_size (int): attention size n_heads (int): number of heads (attention... | the_stack_v2_python_sparse | src/models/anomalia/layers.py | maurony/ts-vrae | train | 1 |
aa7b62aca0826b4cb65751144e446510b3c1b4c4 | [
"if not root:\n return 0\nreturn 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))",
"if not root:\n return 0\nreturn max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1"
] | <|body_start_0|>
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
<|end_body_0|>
<|body_start_1|>
if not root:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Feb 28, 2022 12:02"""
<|body_0|>
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Mar 20, 2023 23:27"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
re... | stack_v2_sparse_classes_10k_train_003383 | 1,582 | no_license | [
{
"docstring": "Feb 28, 2022 12:02",
"name": "maxDepth",
"signature": "def maxDepth(self, root: Optional[TreeNode]) -> int"
},
{
"docstring": "Mar 20, 2023 23:27",
"name": "maxDepth",
"signature": "def maxDepth(self, root: Optional[TreeNode]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root: Optional[TreeNode]) -> int: Feb 28, 2022 12:02
- def maxDepth(self, root: Optional[TreeNode]) -> int: Mar 20, 2023 23:27 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root: Optional[TreeNode]) -> int: Feb 28, 2022 12:02
- def maxDepth(self, root: Optional[TreeNode]) -> int: Mar 20, 2023 23:27
<|skeleton|>
class Solution:
... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Feb 28, 2022 12:02"""
<|body_0|>
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Mar 20, 2023 23:27"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Feb 28, 2022 12:02"""
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Mar 20, 2023 23:27"""
... | the_stack_v2_python_sparse | leetcode/solved/104_Maximum_Depth_of_Binary_Tree/solution.py | sungminoh/algorithms | train | 0 | |
1c09e2ced8ed33aaf69f92e353bcdee1631818af | [
"self.pack_id = pack_id\nself._last_rn_file_path = rn_file_path\nself._update_type = update_type\nself._update_rn_obj = UpdateRN(pack_path=f'{PACKS_DIR}/{pack_id}', update_type=update_type.value, modified_files_in_pack=set(), added_files=set(), pack=pack_id, is_force=True)\nself._bc_file = self._last_rn_file_path.w... | <|body_start_0|>
self.pack_id = pack_id
self._last_rn_file_path = rn_file_path
self._update_type = update_type
self._update_rn_obj = UpdateRN(pack_path=f'{PACKS_DIR}/{pack_id}', update_type=update_type.value, modified_files_in_pack=set(), added_files=set(), pack=pack_id, is_force=True)
... | PackAutoBumper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackAutoBumper:
def __init__(self, pack_id: str, rn_file_path: Path, update_type: UpdateType):
"""Autobump pack version. Args: pack_id: Pack id to its release notes. rn_file_path: last release notes path. update_type: the update type that was in the pr."""
<|body_0|>
def set... | stack_v2_sparse_classes_10k_train_003384 | 11,815 | permissive | [
{
"docstring": "Autobump pack version. Args: pack_id: Pack id to its release notes. rn_file_path: last release notes path. update_type: the update type that was in the pr.",
"name": "__init__",
"signature": "def __init__(self, pack_id: str, rn_file_path: Path, update_type: UpdateType)"
},
{
"doc... | 3 | null | Implement the Python class `PackAutoBumper` described below.
Class description:
Implement the PackAutoBumper class.
Method signatures and docstrings:
- def __init__(self, pack_id: str, rn_file_path: Path, update_type: UpdateType): Autobump pack version. Args: pack_id: Pack id to its release notes. rn_file_path: last ... | Implement the Python class `PackAutoBumper` described below.
Class description:
Implement the PackAutoBumper class.
Method signatures and docstrings:
- def __init__(self, pack_id: str, rn_file_path: Path, update_type: UpdateType): Autobump pack version. Args: pack_id: Pack id to its release notes. rn_file_path: last ... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class PackAutoBumper:
def __init__(self, pack_id: str, rn_file_path: Path, update_type: UpdateType):
"""Autobump pack version. Args: pack_id: Pack id to its release notes. rn_file_path: last release notes path. update_type: the update type that was in the pr."""
<|body_0|>
def set... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PackAutoBumper:
def __init__(self, pack_id: str, rn_file_path: Path, update_type: UpdateType):
"""Autobump pack version. Args: pack_id: Pack id to its release notes. rn_file_path: last release notes path. update_type: the update type that was in the pr."""
self.pack_id = pack_id
self._... | the_stack_v2_python_sparse | Utils/github_workflow_scripts/autobump_release_notes/autobump_rn.py | demisto/content | train | 1,023 | |
7f9be951db40216dbef352b4d1c8c1487bfcec29 | [
"self.threshold = threshold\nself.sampling_method = sampling_method\nself.func_of_freq = func_of_freq\nself.elements = {}",
"if key in self.elements:\n raise ValueError('Only works for aggregated data: repeated key %s' % key)\nscore = self.sampling_method.sampling_score(self.func_of_freq(freq))\nif score < sel... | <|body_start_0|>
self.threshold = threshold
self.sampling_method = sampling_method
self.func_of_freq = func_of_freq
self.elements = {}
<|end_body_0|>
<|body_start_1|>
if key in self.elements:
raise ValueError('Only works for aggregated data: repeated key %s' % key)
... | Implementation of a threshold sampling sketch (without privacy guarantees). Threshold sampling works by computing a random score for each key, and keeping the keys with score below a given threshold (a parameter). The keys that are kept are the sample. The score is determined by the underlying sampling method, e.g., PP... | ThresholdSample | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThresholdSample:
"""Implementation of a threshold sampling sketch (without privacy guarantees). Threshold sampling works by computing a random score for each key, and keeping the keys with score below a given threshold (a parameter). The keys that are kept are the sample. The score is determined ... | stack_v2_sparse_classes_10k_train_003385 | 32,453 | permissive | [
{
"docstring": "Initializes an empty sample. Args: threshold: The sampling threshold sampling_method: A class that provides functions to compute the score and inclusion probability according to the underlying sampling method (e.g., PPSWOR, which is the default value) func_of_freq: The function applied to the fr... | 3 | null | Implement the Python class `ThresholdSample` described below.
Class description:
Implementation of a threshold sampling sketch (without privacy guarantees). Threshold sampling works by computing a random score for each key, and keeping the keys with score below a given threshold (a parameter). The keys that are kept a... | Implement the Python class `ThresholdSample` described below.
Class description:
Implementation of a threshold sampling sketch (without privacy guarantees). Threshold sampling works by computing a random score for each key, and keeping the keys with score below a given threshold (a parameter). The keys that are kept a... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ThresholdSample:
"""Implementation of a threshold sampling sketch (without privacy guarantees). Threshold sampling works by computing a random score for each key, and keeping the keys with score below a given threshold (a parameter). The keys that are kept are the sample. The score is determined ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ThresholdSample:
"""Implementation of a threshold sampling sketch (without privacy guarantees). Threshold sampling works by computing a random score for each key, and keeping the keys with score below a given threshold (a parameter). The keys that are kept are the sample. The score is determined by the underl... | the_stack_v2_python_sparse | private_sampling/private_sampling.py | Jimmy-INL/google-research | train | 1 |
66b0d04f9ff8ff6a25a73968d0081278f7593e60 | [
"context = super(AIUpdateView, self).get_context_data(**kwargs)\ncontext['import_form'] = ImportAIForm\nreturn context",
"initial = super(AIUpdateView, self).get_initial()\ninitial = get_ai(self.request.session.get('token', False), self.kwargs['aiid'])\ninitial['default_chat_responses'] = settings.TOKENFIELD_DELI... | <|body_start_0|>
context = super(AIUpdateView, self).get_context_data(**kwargs)
context['import_form'] = ImportAIForm
return context
<|end_body_0|>
<|body_start_1|>
initial = super(AIUpdateView, self).get_initial()
initial = get_ai(self.request.session.get('token', False), self.... | Manage AI settings | AIUpdateView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AIUpdateView:
"""Manage AI settings"""
def get_context_data(self, **kwargs):
"""Update context adding import form"""
<|body_0|>
def get_initial(self):
"""Returns the initial data to use for forms on this view."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_10k_train_003386 | 39,842 | permissive | [
{
"docstring": "Update context adding import form",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Returns the initial data to use for forms on this view.",
"name": "get_initial",
"signature": "def get_initial(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001426 | Implement the Python class `AIUpdateView` described below.
Class description:
Manage AI settings
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Update context adding import form
- def get_initial(self): Returns the initial data to use for forms on this view. | Implement the Python class `AIUpdateView` described below.
Class description:
Manage AI settings
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Update context adding import form
- def get_initial(self): Returns the initial data to use for forms on this view.
<|skeleton|>
class AIUpdateView... | d632d00f9a22a7a826bba4896a7102b2ac8690ff | <|skeleton|>
class AIUpdateView:
"""Manage AI settings"""
def get_context_data(self, **kwargs):
"""Update context adding import form"""
<|body_0|>
def get_initial(self):
"""Returns the initial data to use for forms on this view."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AIUpdateView:
"""Manage AI settings"""
def get_context_data(self, **kwargs):
"""Update context adding import form"""
context = super(AIUpdateView, self).get_context_data(**kwargs)
context['import_form'] = ImportAIForm
return context
def get_initial(self):
"""R... | the_stack_v2_python_sparse | src/studio/views.py | hutomadotAI/web-console | train | 6 |
d04995e55c2d6125504097bc090dfbdf42994686 | [
"super().__init__()\nself.confidence = 1.0 - smoothing\nself.smoothing = smoothing\nself.cls = num_classes\nself.dim = dim",
"assert 0 <= self.smoothing < 1\npred = pred.log_softmax(dim=self.dim)\nwith torch.no_grad():\n true_dist = torch.zeros_like(pred)\n true_dist.fill_(self.smoothing / (self.cls - 1))\n... | <|body_start_0|>
super().__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
self.cls = num_classes
self.dim = dim
<|end_body_0|>
<|body_start_1|>
assert 0 <= self.smoothing < 1
pred = pred.log_softmax(dim=self.dim)
with torch.no_grad(... | Cross Entropy with Label Smoothing. Attributes: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across which to apply loss. Defaults to -1. | LabelSmoothingLoss | [
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelSmoothingLoss:
"""Cross Entropy with Label Smoothing. Attributes: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across which to apply loss. Defaults to -1."""
... | stack_v2_sparse_classes_10k_train_003387 | 3,691 | permissive | [
{
"docstring": "Initializer for LabelSmoothingLoss. Args: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across which to apply loss. Defaults to -1.",
"name": "__init__",
"sig... | 2 | null | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Cross Entropy with Label Smoothing. Attributes: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across whic... | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Cross Entropy with Label Smoothing. Attributes: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across whic... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class LabelSmoothingLoss:
"""Cross Entropy with Label Smoothing. Attributes: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across which to apply loss. Defaults to -1."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LabelSmoothingLoss:
"""Cross Entropy with Label Smoothing. Attributes: num_classes (int): Number of target classes. smoothing (float, optional): Smoothing fraction constant, in the range (0.0, 1.0). Defaults to 0.1. dim (int, optional): Dimension across which to apply loss. Defaults to -1."""
def __init_... | the_stack_v2_python_sparse | PyTorch/dev/cv/image_classification/Keyword-MLP_ID2441_for_PyTorch/utils/loss.py | Ascend/ModelZoo-PyTorch | train | 23 |
e8fa410fe9d934984a89bf9da5c28131e762efbc | [
"length = 0\nfather = None\ncur = head\nwhile cur:\n length += 1\n father = cur\n cur = cur.next\nreturn (length, father)",
"length, tail = self.get_length(head)\nif length == 0 or length == 1 or k == 0:\n return head\nnum = length - k % length\nif num == length:\n return head\nnum -= 1\nif num == ... | <|body_start_0|>
length = 0
father = None
cur = head
while cur:
length += 1
father = cur
cur = cur.next
return (length, father)
<|end_body_0|>
<|body_start_1|>
length, tail = self.get_length(head)
if length == 0 or length == 1 ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_length(self, head):
""":type head: ListNode :rtype: int"""
<|body_0|>
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = 0
father =... | stack_v2_sparse_classes_10k_train_003388 | 1,268 | no_license | [
{
"docstring": ":type head: ListNode :rtype: int",
"name": "get_length",
"signature": "def get_length(self, head)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "rotateRight",
"signature": "def rotateRight(self, head, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003476 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_length(self, head): :type head: ListNode :rtype: int
- def rotateRight(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 get_length(self, head): :type head: ListNode :rtype: int
- def rotateRight(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
<|skeleton|>
class Solution:
... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def get_length(self, head):
""":type head: ListNode :rtype: int"""
<|body_0|>
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def get_length(self, head):
""":type head: ListNode :rtype: int"""
length = 0
father = None
cur = head
while cur:
length += 1
father = cur
cur = cur.next
return (length, father)
def rotateRight(self, head, k):
... | the_stack_v2_python_sparse | python/leetcode/61_Rotate_List.py | bobcaoge/my-code | train | 0 | |
c39e966d4c0185173a64833e16112d7ecc15c8ee | [
"self.dp = [0]\nself.len = len(nums)\nfor val in nums:\n self.dp.append(val + self.dp[-1])",
"if i < 0:\n i = 0\nif j >= self.len:\n j = self.len - 1\nreturn self.dp[j + 1] - self.dp[i]"
] | <|body_start_0|>
self.dp = [0]
self.len = len(nums)
for val in nums:
self.dp.append(val + self.dp[-1])
<|end_body_0|>
<|body_start_1|>
if i < 0:
i = 0
if j >= self.len:
j = self.len - 1
return self.dp[j + 1] - self.dp[i]
<|end_body_1|>... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dp = [0]
self.len = len(nums)
for val ... | stack_v2_sparse_classes_10k_train_003389 | 535 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000187 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | e2837f3d6c23f012148a2d1f9d0ef6d34d4e6912 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.dp = [0]
self.len = len(nums)
for val in nums:
self.dp.append(val + self.dp[-1])
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
if i < 0:
i =... | the_stack_v2_python_sparse | Dp/range-sum-query-immutable.py | wttttt-wang/leetcode_withTopics | train | 0 | |
9ecd0f30fa882e48d8ccf2fa684ec5047c70c450 | [
"super(GilbertElliott, self).__init__(PacketLoss.__name__)\nif prhk is None:\n p = float(GilbertElliott.__DEFAULT_P)\n r = float(GilbertElliott.__DEFAULT_R)\n b = float(1.0 - GilbertElliott.__DEFAULT_H)\n g = float(1.0 - GilbertElliott.__DEFAULT_K)\nelse:\n for param in range(4):\n check_argum... | <|body_start_0|>
super(GilbertElliott, self).__init__(PacketLoss.__name__)
if prhk is None:
p = float(GilbertElliott.__DEFAULT_P)
r = float(GilbertElliott.__DEFAULT_R)
b = float(1.0 - GilbertElliott.__DEFAULT_H)
g = float(1.0 - GilbertElliott.__DEFAULT_K)
... | This class implements the Gilbert-Elliott packet loss model. | GilbertElliott | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GilbertElliott:
"""This class implements the Gilbert-Elliott packet loss model."""
def __init__(self, prhk=None):
"""*Parameters*: - **prhk** (`tuple`): a `tuple` that contains four model parameters: :math:`0\\leqslant p,r,h,k\\leqslant 1`, respectively (each of type `float`). The pa... | stack_v2_sparse_classes_10k_train_003390 | 6,499 | permissive | [
{
"docstring": "*Parameters*: - **prhk** (`tuple`): a `tuple` that contains four model parameters: :math:`0\\\\leqslant p,r,h,k\\\\leqslant 1`, respectively (each of type `float`). The parameters default to the following values: * :math:`p=0.00001333`, * :math:`r=0.00601795`, * :math:`h=0.55494900`, * :math:`k=... | 2 | stack_v2_sparse_classes_30k_train_003353 | Implement the Python class `GilbertElliott` described below.
Class description:
This class implements the Gilbert-Elliott packet loss model.
Method signatures and docstrings:
- def __init__(self, prhk=None): *Parameters*: - **prhk** (`tuple`): a `tuple` that contains four model parameters: :math:`0\\leqslant p,r,h,k\... | Implement the Python class `GilbertElliott` described below.
Class description:
This class implements the Gilbert-Elliott packet loss model.
Method signatures and docstrings:
- def __init__(self, prhk=None): *Parameters*: - **prhk** (`tuple`): a `tuple` that contains four model parameters: :math:`0\\leqslant p,r,h,k\... | ed93d1e3067c569dd4194658b0d02da6b0ab4bed | <|skeleton|>
class GilbertElliott:
"""This class implements the Gilbert-Elliott packet loss model."""
def __init__(self, prhk=None):
"""*Parameters*: - **prhk** (`tuple`): a `tuple` that contains four model parameters: :math:`0\\leqslant p,r,h,k\\leqslant 1`, respectively (each of type `float`). The pa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GilbertElliott:
"""This class implements the Gilbert-Elliott packet loss model."""
def __init__(self, prhk=None):
"""*Parameters*: - **prhk** (`tuple`): a `tuple` that contains four model parameters: :math:`0\\leqslant p,r,h,k\\leqslant 1`, respectively (each of type `float`). The parameters defa... | the_stack_v2_python_sparse | sim2net/packet_loss/gilbert_elliott.py | mkalewski/sim2net | train | 14 |
a8825179e1a07d5aa485bd6c8eba0f3b8f4488b4 | [
"rospy.loginfo('Moving %s to handover position.' % limb)\nif limb == 'left':\n handover_position_joints = {'left_w0': 0.47016511148687934, 'left_w1': -0.42798063982003043, 'left_w2': 0.18676216092504913, 'left_e0': -1.1616069516262295, 'left_e1': 1.889097340280887, 'left_s0': 0.1499466220157992, 'left_s1': -0.91... | <|body_start_0|>
rospy.loginfo('Moving %s to handover position.' % limb)
if limb == 'left':
handover_position_joints = {'left_w0': 0.47016511148687934, 'left_w1': -0.42798063982003043, 'left_w2': 0.18676216092504913, 'left_e0': -1.1616069516262295, 'left_e1': 1.889097340280887, 'left_s0': 0.... | OfferingObjectServer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfferingObjectServer:
def move_to_handover(self, baxter_arm, limb):
"""Moves specified limb to the handover position. :param baxter_arm: arm to move :param limb: which arm, 'right' or 'left :return:"""
<|body_0|>
def callback(self, request=None):
"""Call back for han... | stack_v2_sparse_classes_10k_train_003391 | 3,257 | permissive | [
{
"docstring": "Moves specified limb to the handover position. :param baxter_arm: arm to move :param limb: which arm, 'right' or 'left :return:",
"name": "move_to_handover",
"signature": "def move_to_handover(self, baxter_arm, limb)"
},
{
"docstring": "Call back for handover service. :param requ... | 2 | stack_v2_sparse_classes_30k_train_007351 | Implement the Python class `OfferingObjectServer` described below.
Class description:
Implement the OfferingObjectServer class.
Method signatures and docstrings:
- def move_to_handover(self, baxter_arm, limb): Moves specified limb to the handover position. :param baxter_arm: arm to move :param limb: which arm, 'right... | Implement the Python class `OfferingObjectServer` described below.
Class description:
Implement the OfferingObjectServer class.
Method signatures and docstrings:
- def move_to_handover(self, baxter_arm, limb): Moves specified limb to the handover position. :param baxter_arm: arm to move :param limb: which arm, 'right... | 1f9d05b7232cb9e76eff975e5ef1c8bf3fb5cde6 | <|skeleton|>
class OfferingObjectServer:
def move_to_handover(self, baxter_arm, limb):
"""Moves specified limb to the handover position. :param baxter_arm: arm to move :param limb: which arm, 'right' or 'left :return:"""
<|body_0|>
def callback(self, request=None):
"""Call back for han... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OfferingObjectServer:
def move_to_handover(self, baxter_arm, limb):
"""Moves specified limb to the handover position. :param baxter_arm: arm to move :param limb: which arm, 'right' or 'left :return:"""
rospy.loginfo('Moving %s to handover position.' % limb)
if limb == 'left':
... | the_stack_v2_python_sparse | grasping/src/offering_object_server.py | Hankfirst/de_niro | train | 1 | |
4bf7aebc5baaa5224d030607aa79889a5b515035 | [
"directory_path = Path(directory_path)\noutput_path = Path(output_path)\narchive_path = output_path / f'{directory_path.stem}.zip'\nwith zipfile.ZipFile(archive_path, 'w') as zip_file:\n for path in directory_path.rglob('*'):\n zip_file.write(filename=path, arcname=path.relative_to(directory_path))\nretur... | <|body_start_0|>
directory_path = Path(directory_path)
output_path = Path(output_path)
archive_path = output_path / f'{directory_path.stem}.zip'
with zipfile.ZipFile(archive_path, 'w') as zip_file:
for path in directory_path.rglob('*'):
zip_file.write(filename... | A static class for managing zip archives. | _ZipArchiver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ZipArchiver:
"""A static class for managing zip archives."""
def create_archive(cls, directory_path: str, output_path: str) -> str:
"""Create an archive of all the contents in the given directory and save it to an archive file named as the directory in the provided output path. :par... | stack_v2_sparse_classes_10k_train_003392 | 7,567 | permissive | [
{
"docstring": "Create an archive of all the contents in the given directory and save it to an archive file named as the directory in the provided output path. :param directory_path: The directory with the files to archive. :param output_path: The output path to store the created archive file. :return: The crea... | 2 | stack_v2_sparse_classes_30k_train_000312 | Implement the Python class `_ZipArchiver` described below.
Class description:
A static class for managing zip archives.
Method signatures and docstrings:
- def create_archive(cls, directory_path: str, output_path: str) -> str: Create an archive of all the contents in the given directory and save it to an archive file... | Implement the Python class `_ZipArchiver` described below.
Class description:
A static class for managing zip archives.
Method signatures and docstrings:
- def create_archive(cls, directory_path: str, output_path: str) -> str: Create an archive of all the contents in the given directory and save it to an archive file... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class _ZipArchiver:
"""A static class for managing zip archives."""
def create_archive(cls, directory_path: str, output_path: str) -> str:
"""Create an archive of all the contents in the given directory and save it to an archive file named as the directory in the provided output path. :par... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _ZipArchiver:
"""A static class for managing zip archives."""
def create_archive(cls, directory_path: str, output_path: str) -> str:
"""Create an archive of all the contents in the given directory and save it to an archive file named as the directory in the provided output path. :param directory_... | the_stack_v2_python_sparse | mlrun/package/utils/_archiver.py | mlrun/mlrun | train | 1,093 |
10ccbd8041655ad4bbbcac7d6dfe62cfc2bfa94f | [
"it = iter(test_inputs.split('\\n')) if test_inputs else None\n\ndef uinput():\n return next(it) if it else sys.stdin.readline().rstrip()\n[self.p, self.k] = map(int, uinput().split())\nself.M = 10 ** 9 + 7",
"result = 0\nbp = Binominals(mod=self.p)\nmm = 1\nfor m in range(1, self.p):\n mm = bp.mul(mm, self... | <|body_start_0|>
it = iter(test_inputs.split('\n')) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
[self.p, self.k] = map(int, uinput().split())
self.M = 10 ** 9 + 7
<|end_body_0|>
<|body_start_1|>
result = 0
... | Modular representation | Modular | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Modular:
"""Modular representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
<|body_0|>
def calculate(self):
"""Main calcualtion function of the class"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
it = iter(test_inputs... | stack_v2_sparse_classes_10k_train_003393 | 3,558 | permissive | [
{
"docstring": "Default constructor",
"name": "__init__",
"signature": "def __init__(self, test_inputs=None)"
},
{
"docstring": "Main calcualtion function of the class",
"name": "calculate",
"signature": "def calculate(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006234 | Implement the Python class `Modular` described below.
Class description:
Modular representation
Method signatures and docstrings:
- def __init__(self, test_inputs=None): Default constructor
- def calculate(self): Main calcualtion function of the class | Implement the Python class `Modular` described below.
Class description:
Modular representation
Method signatures and docstrings:
- def __init__(self, test_inputs=None): Default constructor
- def calculate(self): Main calcualtion function of the class
<|skeleton|>
class Modular:
"""Modular representation"""
... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class Modular:
"""Modular representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
<|body_0|>
def calculate(self):
"""Main calcualtion function of the class"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Modular:
"""Modular representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
it = iter(test_inputs.split('\n')) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
[self.p, self.k] = map(int,... | the_stack_v2_python_sparse | codeforces/604D_modular.py | snsokolov/contests | train | 1 |
a99f82655c676f4e8b30b2b00a3c005ded995c4f | [
"try:\n sets = oai_provider_set_api.get_all()\n serializer = serializers.OaiProviderSetSerializer(sets, many=True, context={'request': request})\n return Response(serializer.data, status=status.HTTP_200_OK)\nexcept Exception as exception:\n content = OaiPmhMessage.get_message_labelled(str(exception))\n ... | <|body_start_0|>
try:
sets = oai_provider_set_api.get_all()
serializer = serializers.OaiProviderSetSerializer(sets, many=True, context={'request': request})
return Response(serializer.data, status=status.HTTP_200_OK)
except Exception as exception:
content ... | Sets List | SetsList | [
"BSD-3-Clause",
"Apache-2.0",
"MIT",
"NIST-Software"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetsList:
"""Sets List"""
def get(self, request):
"""Get all OaiProviderSet Args: request: HTTP request Returns: - code: 200 content: List of OaiProviderSet - code: 500 content: Internal server error"""
<|body_0|>
def post(self, request):
"""Create a OaiProviderS... | stack_v2_sparse_classes_10k_train_003394 | 7,772 | permissive | [
{
"docstring": "Get all OaiProviderSet Args: request: HTTP request Returns: - code: 200 content: List of OaiProviderSet - code: 500 content: Internal server error",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Create a OaiProviderSet Parameters: { \"set_spec\": \"value... | 2 | stack_v2_sparse_classes_30k_train_005371 | Implement the Python class `SetsList` described below.
Class description:
Sets List
Method signatures and docstrings:
- def get(self, request): Get all OaiProviderSet Args: request: HTTP request Returns: - code: 200 content: List of OaiProviderSet - code: 500 content: Internal server error
- def post(self, request): ... | Implement the Python class `SetsList` described below.
Class description:
Sets List
Method signatures and docstrings:
- def get(self, request): Get all OaiProviderSet Args: request: HTTP request Returns: - code: 200 content: List of OaiProviderSet - code: 500 content: Internal server error
- def post(self, request): ... | 1d2380d99c00c96a7c5ebdf8513b8ad5e8926d9f | <|skeleton|>
class SetsList:
"""Sets List"""
def get(self, request):
"""Get all OaiProviderSet Args: request: HTTP request Returns: - code: 200 content: List of OaiProviderSet - code: 500 content: Internal server error"""
<|body_0|>
def post(self, request):
"""Create a OaiProviderS... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SetsList:
"""Sets List"""
def get(self, request):
"""Get all OaiProviderSet Args: request: HTTP request Returns: - code: 200 content: List of OaiProviderSet - code: 500 content: Internal server error"""
try:
sets = oai_provider_set_api.get_all()
serializer = serial... | the_stack_v2_python_sparse | core_oaipmh_provider_app/rest/oai_provider_set/views.py | usnistgov/core_oaipmh_provider_app | train | 0 |
655e61a395ab91d28f7be26099d56e71decb9594 | [
"pre = p = j = head\nfor t in range(n - 1):\n p = p.next\nwhile p.next:\n pre = j\n j = j.next\n p = p.next\nif pre == j:\n if pre == p:\n return None\n else:\n head = pre.next\n return head\nelse:\n pre.next = j.next\n return head",
"p = j = head\nfor _ in range(n):\n... | <|body_start_0|>
pre = p = j = head
for t in range(n - 1):
p = p.next
while p.next:
pre = j
j = j.next
p = p.next
if pre == j:
if pre == p:
return None
else:
head = pre.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd2(self, head, n):
"""an improved logic"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pre = p = j = head
... | stack_v2_sparse_classes_10k_train_003395 | 1,033 | no_license | [
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(self, head, n)"
},
{
"docstring": "an improved logic",
"name": "removeNthFromEnd2",
"signature": "def removeNthFromEnd2(self, head, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000466 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd2(self, head, n): an improved logic | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd2(self, head, n): an improved logic
<|skeleton|>
class Solution:
... | 9c5f6621988ce3b15394e7a5d5b949f87e0d6265 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd2(self, head, n):
"""an improved logic"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
pre = p = j = head
for t in range(n - 1):
p = p.next
while p.next:
pre = j
j = j.next
p = p.next
if pre == j:
... | the_stack_v2_python_sparse | leetcode/2016/19_removeNthFromEnd.py | YulongWu/AlgoExercise_CPP | train | 1 | |
618b529d4ad878940a03c6cdc5dbcfce6cfb014e | [
"self.zamg = ZamgDevice(session=async_get_clientsession(hass))\nself.zamg.set_default_station(entry.data[CONF_STATION_ID])\nsuper().__init__(hass, LOGGER, name=DOMAIN, update_interval=MIN_TIME_BETWEEN_UPDATES)",
"try:\n if self.api_fields:\n self.zamg.set_parameters(self.api_fields)\n self.zamg.reque... | <|body_start_0|>
self.zamg = ZamgDevice(session=async_get_clientsession(hass))
self.zamg.set_default_station(entry.data[CONF_STATION_ID])
super().__init__(hass, LOGGER, name=DOMAIN, update_interval=MIN_TIME_BETWEEN_UPDATES)
<|end_body_0|>
<|body_start_1|>
try:
if self.api_fi... | Class to manage fetching ZAMG weather data. | ZamgDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZamgDataUpdateCoordinator:
"""Class to manage fetching ZAMG weather data."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry) -> None:
"""Initialize global ZAMG data updater."""
<|body_0|>
async def _async_update_data(self) -> ZamgDevice:
"""Fetch d... | stack_v2_sparse_classes_10k_train_003396 | 1,868 | permissive | [
{
"docstring": "Initialize global ZAMG data updater.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry) -> None"
},
{
"docstring": "Fetch data from ZAMG api.",
"name": "_async_update_data",
"signature": "async def _async_update_data(self) -... | 2 | null | Implement the Python class `ZamgDataUpdateCoordinator` described below.
Class description:
Class to manage fetching ZAMG weather data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry) -> None: Initialize global ZAMG data updater.
- async def _async_update_data(self) -... | Implement the Python class `ZamgDataUpdateCoordinator` described below.
Class description:
Class to manage fetching ZAMG weather data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry) -> None: Initialize global ZAMG data updater.
- async def _async_update_data(self) -... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ZamgDataUpdateCoordinator:
"""Class to manage fetching ZAMG weather data."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry) -> None:
"""Initialize global ZAMG data updater."""
<|body_0|>
async def _async_update_data(self) -> ZamgDevice:
"""Fetch d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ZamgDataUpdateCoordinator:
"""Class to manage fetching ZAMG weather data."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry) -> None:
"""Initialize global ZAMG data updater."""
self.zamg = ZamgDevice(session=async_get_clientsession(hass))
self.zamg.set_default_stati... | the_stack_v2_python_sparse | homeassistant/components/zamg/coordinator.py | home-assistant/core | train | 35,501 |
83f7383fd83041bf61bd3e0006237db867408471 | [
"super(TDNN, self).__init__()\nself.context_size = context_size\nself.stride = stride\nself.input_dim = input_dim\nself.output_dim = output_dim\nself.dilation = dilation\nself.dropout_p = dropout_p\nself.batch_norm = batch_norm\nself.kernel = nn.Linear(input_dim * context_size, output_dim)\nself.nonlinearity = nn.R... | <|body_start_0|>
super(TDNN, self).__init__()
self.context_size = context_size
self.stride = stride
self.input_dim = input_dim
self.output_dim = output_dim
self.dilation = dilation
self.dropout_p = dropout_p
self.batch_norm = batch_norm
self.kernel... | TDNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TDNN:
def __init__(self, input_dim=3, output_dim=3, context_size=3, dilation=1, stride=1, batch_norm=True, dropout_p=0.0):
"""TDNN as defined by https://www.danielpovey.com/files/2015_interspeech_multisplice.pdf Affine transformation not applied globally to all frames but smaller windows... | stack_v2_sparse_classes_10k_train_003397 | 4,369 | no_license | [
{
"docstring": "TDNN as defined by https://www.danielpovey.com/files/2015_interspeech_multisplice.pdf Affine transformation not applied globally to all frames but smaller windows with local context batch_norm: True to include batch normalisation after the non linearity Context size and dilation determine the fr... | 2 | stack_v2_sparse_classes_30k_train_003554 | Implement the Python class `TDNN` described below.
Class description:
Implement the TDNN class.
Method signatures and docstrings:
- def __init__(self, input_dim=3, output_dim=3, context_size=3, dilation=1, stride=1, batch_norm=True, dropout_p=0.0): TDNN as defined by https://www.danielpovey.com/files/2015_interspeech... | Implement the Python class `TDNN` described below.
Class description:
Implement the TDNN class.
Method signatures and docstrings:
- def __init__(self, input_dim=3, output_dim=3, context_size=3, dilation=1, stride=1, batch_norm=True, dropout_p=0.0): TDNN as defined by https://www.danielpovey.com/files/2015_interspeech... | d04244ed07401567c493171d3e4b7b37d107a68d | <|skeleton|>
class TDNN:
def __init__(self, input_dim=3, output_dim=3, context_size=3, dilation=1, stride=1, batch_norm=True, dropout_p=0.0):
"""TDNN as defined by https://www.danielpovey.com/files/2015_interspeech_multisplice.pdf Affine transformation not applied globally to all frames but smaller windows... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TDNN:
def __init__(self, input_dim=3, output_dim=3, context_size=3, dilation=1, stride=1, batch_norm=True, dropout_p=0.0):
"""TDNN as defined by https://www.danielpovey.com/files/2015_interspeech_multisplice.pdf Affine transformation not applied globally to all frames but smaller windows with local co... | the_stack_v2_python_sparse | 2-x-vector/tdnn.py | zcx-1997/My_speaker_recognition | train | 1 | |
b47f32ffeef53ff13b2856ed4ed02651d05282e6 | [
"self._payment_date = payment_dates\nself._payment_step = payment_steps\nself._reset_date = reset_dates\nself._reset_step = reset_steps\nself._steps = reset_steps[len(reset_steps) - 1]\nself._the_tree = {}",
"bond = ZCBond(self._payment_date, self._payment_step)\nbond.get_price(hw_tree)\nfor i in reversed(range(s... | <|body_start_0|>
self._payment_date = payment_dates
self._payment_step = payment_steps
self._reset_date = reset_dates
self._reset_step = reset_steps
self._steps = reset_steps[len(reset_steps) - 1]
self._the_tree = {}
<|end_body_0|>
<|body_start_1|>
bond = ZCBond(... | Representation of a simple derivative product such as Caplet or Floor | SimpleDerivative | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleDerivative:
"""Representation of a simple derivative product such as Caplet or Floor"""
def __init__(self, payment_dates, payment_steps, reset_dates, reset_steps):
"""Initialize a SimpleDerivative object Parameters ---------- payment_dates : array_like of shape (1, ) with datet... | stack_v2_sparse_classes_10k_train_003398 | 11,731 | no_license | [
{
"docstring": "Initialize a SimpleDerivative object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment dates payment_steps : array_like of shape (1, ) with integer payment steps that corresponds to the tree exercise_dates : array_like of shape (1, ) with datetime exercise dat... | 2 | stack_v2_sparse_classes_30k_train_005758 | Implement the Python class `SimpleDerivative` described below.
Class description:
Representation of a simple derivative product such as Caplet or Floor
Method signatures and docstrings:
- def __init__(self, payment_dates, payment_steps, reset_dates, reset_steps): Initialize a SimpleDerivative object Parameters ------... | Implement the Python class `SimpleDerivative` described below.
Class description:
Representation of a simple derivative product such as Caplet or Floor
Method signatures and docstrings:
- def __init__(self, payment_dates, payment_steps, reset_dates, reset_steps): Initialize a SimpleDerivative object Parameters ------... | 9f710a8de56fb9b4456c6f98be91f4b22ef5ede5 | <|skeleton|>
class SimpleDerivative:
"""Representation of a simple derivative product such as Caplet or Floor"""
def __init__(self, payment_dates, payment_steps, reset_dates, reset_steps):
"""Initialize a SimpleDerivative object Parameters ---------- payment_dates : array_like of shape (1, ) with datet... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SimpleDerivative:
"""Representation of a simple derivative product such as Caplet or Floor"""
def __init__(self, payment_dates, payment_steps, reset_dates, reset_steps):
"""Initialize a SimpleDerivative object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment d... | the_stack_v2_python_sparse | Hull-White Model/simple_derivatives.py | jesusmramirez/Term-Structure-Models | train | 1 |
0e57fd3b6d5613145c0b1d11b7b9b2aa8bf0ece6 | [
"name = name.strip()\nassert name\nself.name = name\nactionInstances = []\nfor action in actions:\n if isinstance(action, (MenuAction, _MenuSeparator)):\n actionInstances.append(action)\n elif isclass(action) and (action is _MenuSeparator or issubclass(action, MenuAction)):\n actionInstances.app... | <|body_start_0|>
name = name.strip()
assert name
self.name = name
actionInstances = []
for action in actions:
if isinstance(action, (MenuAction, _MenuSeparator)):
actionInstances.append(action)
elif isclass(action) and (action is _MenuSepar... | Container class for a menu definition. | MenuBuilder | [
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuBuilder:
"""Container class for a menu definition."""
def __init__(self, name, actions):
"""Parameters ---------- name : str actions : List[Union[MenuAction, Type[MenuAction]]]"""
<|body_0|>
def Build(self, context, contextCallback=None, parent=None):
"""Buil... | stack_v2_sparse_classes_10k_train_003399 | 14,708 | permissive | [
{
"docstring": "Parameters ---------- name : str actions : List[Union[MenuAction, Type[MenuAction]]]",
"name": "__init__",
"signature": "def __init__(self, name, actions)"
},
{
"docstring": "Build and return a new `QMenu` instance using the current list of actions and the given context, and pare... | 2 | stack_v2_sparse_classes_30k_train_006080 | Implement the Python class `MenuBuilder` described below.
Class description:
Container class for a menu definition.
Method signatures and docstrings:
- def __init__(self, name, actions): Parameters ---------- name : str actions : List[Union[MenuAction, Type[MenuAction]]]
- def Build(self, context, contextCallback=Non... | Implement the Python class `MenuBuilder` described below.
Class description:
Container class for a menu definition.
Method signatures and docstrings:
- def __init__(self, name, actions): Parameters ---------- name : str actions : List[Union[MenuAction, Type[MenuAction]]]
- def Build(self, context, contextCallback=Non... | 58dad9ee9dd754c0b22fa986724aace9b3e8b5b9 | <|skeleton|>
class MenuBuilder:
"""Container class for a menu definition."""
def __init__(self, name, actions):
"""Parameters ---------- name : str actions : List[Union[MenuAction, Type[MenuAction]]]"""
<|body_0|>
def Build(self, context, contextCallback=None, parent=None):
"""Buil... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MenuBuilder:
"""Container class for a menu definition."""
def __init__(self, name, actions):
"""Parameters ---------- name : str actions : List[Union[MenuAction, Type[MenuAction]]]"""
name = name.strip()
assert name
self.name = name
actionInstances = []
for... | the_stack_v2_python_sparse | pxr/usdQt/qtUtils.py | LumaPictures/usd-qt | train | 151 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.