blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d14db89feb972db40fbd185e4d9afebbd4bd9ec5 | [
"self.object_prefix = object_prefix\nself.region = region\nself.s3_bucket = s3_bucket",
"if dictionary is None:\n return None\nobject_prefix = dictionary.get('objectPrefix')\nregion = cohesity_management_sdk.models.entity_proto.EntityProto.from_dictionary(dictionary.get('region')) if dictionary.get('region') e... | <|body_start_0|>
self.object_prefix = object_prefix
self.region = region
self.s3_bucket = s3_bucket
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
object_prefix = dictionary.get('objectPrefix')
region = cohesity_management_sdk.models.entit... | Implementation of the 'RestoreS3Params_NewLocationParams' model. Message specifying new location details, should be set only when is_original_location is false. Attributes: object_prefix (string): Object prefix for the recovered objects. E.g. "/", "/a/b". region (EntityProto): Target Region in which recovery should hap... | RestoreS3Params_NewLocationParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreS3Params_NewLocationParams:
"""Implementation of the 'RestoreS3Params_NewLocationParams' model. Message specifying new location details, should be set only when is_original_location is false. Attributes: object_prefix (string): Object prefix for the recovered objects. E.g. "/", "/a/b". reg... | stack_v2_sparse_classes_75kplus_train_072600 | 2,258 | permissive | [
{
"docstring": "Constructor for the RestoreS3Params_NewLocationParams class",
"name": "__init__",
"signature": "def __init__(self, object_prefix=None, region=None, s3_bucket=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary ... | 2 | stack_v2_sparse_classes_30k_train_024530 | Implement the Python class `RestoreS3Params_NewLocationParams` described below.
Class description:
Implementation of the 'RestoreS3Params_NewLocationParams' model. Message specifying new location details, should be set only when is_original_location is false. Attributes: object_prefix (string): Object prefix for the r... | Implement the Python class `RestoreS3Params_NewLocationParams` described below.
Class description:
Implementation of the 'RestoreS3Params_NewLocationParams' model. Message specifying new location details, should be set only when is_original_location is false. Attributes: object_prefix (string): Object prefix for the r... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreS3Params_NewLocationParams:
"""Implementation of the 'RestoreS3Params_NewLocationParams' model. Message specifying new location details, should be set only when is_original_location is false. Attributes: object_prefix (string): Object prefix for the recovered objects. E.g. "/", "/a/b". reg... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RestoreS3Params_NewLocationParams:
"""Implementation of the 'RestoreS3Params_NewLocationParams' model. Message specifying new location details, should be set only when is_original_location is false. Attributes: object_prefix (string): Object prefix for the recovered objects. E.g. "/", "/a/b". region (EntityPr... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_s3_params_new_location_params.py | cohesity/management-sdk-python | train | 24 |
1b9c18f88049a5be7560688fe91c910f69e1c27d | [
"def fset(self, data):\n if self._finalized:\n raise NodeTreeError('Tree was already finalized')\n if self._udict['closed']:\n raise NodeTreeError('Self-closing elements cannot have an endtag')\n if not isinstance(data, str):\n raise NodeTreeError('Endtag data must be a string')\n s... | <|body_start_0|>
def fset(self, data):
if self._finalized:
raise NodeTreeError('Tree was already finalized')
if self._udict['closed']:
raise NodeTreeError('Self-closing elements cannot have an endtag')
if not isinstance(data, str):
... | Template node This is kind of a proto node. During rendering each template node is turned into a user visible `Node` object, which implements the user interface. `TemplateNode` objects provide a tree building interface instead. :IVariables: `_udict` : ``dict`` The dict containing node information `_finalized` : ``bool`... | TemplateNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateNode:
"""Template node This is kind of a proto node. During rendering each template node is turned into a user visible `Node` object, which implements the user interface. `TemplateNode` objects provide a tree building interface instead. :IVariables: `_udict` : ``dict`` The dict containing... | stack_v2_sparse_classes_75kplus_train_072601 | 31,259 | permissive | [
{
"docstring": "End tag of the node :Type: ``str``",
"name": "endtag",
"signature": "def endtag()"
},
{
"docstring": "Initialization :Parameters: `tagname` : ``str`` The name of the accompanying tag `attr` : iterable The attribute list (``((name, value), ...)``) `special` : ``dict`` Special node... | 5 | stack_v2_sparse_classes_30k_train_028143 | Implement the Python class `TemplateNode` described below.
Class description:
Template node This is kind of a proto node. During rendering each template node is turned into a user visible `Node` object, which implements the user interface. `TemplateNode` objects provide a tree building interface instead. :IVariables: ... | Implement the Python class `TemplateNode` described below.
Class description:
Template node This is kind of a proto node. During rendering each template node is turned into a user visible `Node` object, which implements the user interface. `TemplateNode` objects provide a tree building interface instead. :IVariables: ... | 65a93080281f9ce5c0379e9dbb111f14965a8613 | <|skeleton|>
class TemplateNode:
"""Template node This is kind of a proto node. During rendering each template node is turned into a user visible `Node` object, which implements the user interface. `TemplateNode` objects provide a tree building interface instead. :IVariables: `_udict` : ``dict`` The dict containing... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TemplateNode:
"""Template node This is kind of a proto node. During rendering each template node is turned into a user visible `Node` object, which implements the user interface. `TemplateNode` objects provide a tree building interface instead. :IVariables: `_udict` : ``dict`` The dict containing node informa... | the_stack_v2_python_sparse | tdi/nodetree.py | ndparker/tdi | train | 4 |
95ba850c1ae8c44ab6c5ae20b12c4982d5019e66 | [
"opt = cls()\nopt._answer = answer\nrdata_len = int(opt._answer._rdlength)\nwhile rdata_len:\n if data.peek(2):\n option_code = struct.unpack('!H', data.read(2))[0]\n option_length = struct.unpack('!H', data.read(2))[0]\n setattr(opt, str(option_code), data.read(option_length))\n rdat... | <|body_start_0|>
opt = cls()
opt._answer = answer
rdata_len = int(opt._answer._rdlength)
while rdata_len:
if data.peek(2):
option_code = struct.unpack('!H', data.read(2))[0]
option_length = struct.unpack('!H', data.read(2))[0]
s... | Pseudo RR type for EDNS. | Opt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Opt:
"""Pseudo RR type for EDNS."""
def unpack(cls, answer, data: 'ByteStream'):
"""Unpacks OPT RR from bytes."""
<|body_0|>
def pack(self):
"""Packs pseudo-RR to bytes."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
opt = cls()
opt._an... | stack_v2_sparse_classes_75kplus_train_072602 | 1,049 | no_license | [
{
"docstring": "Unpacks OPT RR from bytes.",
"name": "unpack",
"signature": "def unpack(cls, answer, data: 'ByteStream')"
},
{
"docstring": "Packs pseudo-RR to bytes.",
"name": "pack",
"signature": "def pack(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046392 | Implement the Python class `Opt` described below.
Class description:
Pseudo RR type for EDNS.
Method signatures and docstrings:
- def unpack(cls, answer, data: 'ByteStream'): Unpacks OPT RR from bytes.
- def pack(self): Packs pseudo-RR to bytes. | Implement the Python class `Opt` described below.
Class description:
Pseudo RR type for EDNS.
Method signatures and docstrings:
- def unpack(cls, answer, data: 'ByteStream'): Unpacks OPT RR from bytes.
- def pack(self): Packs pseudo-RR to bytes.
<|skeleton|>
class Opt:
"""Pseudo RR type for EDNS."""
def unp... | 90c4e8fe80ba1212c4794db489c4950dd23fc48b | <|skeleton|>
class Opt:
"""Pseudo RR type for EDNS."""
def unpack(cls, answer, data: 'ByteStream'):
"""Unpacks OPT RR from bytes."""
<|body_0|>
def pack(self):
"""Packs pseudo-RR to bytes."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Opt:
"""Pseudo RR type for EDNS."""
def unpack(cls, answer, data: 'ByteStream'):
"""Unpacks OPT RR from bytes."""
opt = cls()
opt._answer = answer
rdata_len = int(opt._answer._rdlength)
while rdata_len:
if data.peek(2):
option_code = str... | the_stack_v2_python_sparse | pathfinder/common/middleware/edns/opt.py | Yurzs/pathfinder | train | 0 |
a830c187212527b6c0c182e90688ab101817ae5a | [
"Decoration.__init__(self, x, y)\nself.text = str(text)\nself.font = font\nself.adjust = adjust\nself.color = saneColor(color)",
"if self.color is not None:\n GL.glColor3fv(self.color)\ndrawText2D(self.text, self.x, self.y, self.font, self.adjust)"
] | <|body_start_0|>
Decoration.__init__(self, x, y)
self.text = str(text)
self.font = font
self.adjust = adjust
self.color = saneColor(color)
<|end_body_0|>
<|body_start_1|>
if self.color is not None:
GL.glColor3fv(self.color)
drawText2D(self.text, self.... | A viewport decoration showing a text. | Text | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Text:
"""A viewport decoration showing a text."""
def __init__(self, text, x, y, font='9x15', adjust='left', color=None):
"""Create a text actor"""
<|body_0|>
def drawGL(self, mode='wireframe', color=None):
"""Draw the text."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_072603 | 9,597 | no_license | [
{
"docstring": "Create a text actor",
"name": "__init__",
"signature": "def __init__(self, text, x, y, font='9x15', adjust='left', color=None)"
},
{
"docstring": "Draw the text.",
"name": "drawGL",
"signature": "def drawGL(self, mode='wireframe', color=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022650 | Implement the Python class `Text` described below.
Class description:
A viewport decoration showing a text.
Method signatures and docstrings:
- def __init__(self, text, x, y, font='9x15', adjust='left', color=None): Create a text actor
- def drawGL(self, mode='wireframe', color=None): Draw the text. | Implement the Python class `Text` described below.
Class description:
A viewport decoration showing a text.
Method signatures and docstrings:
- def __init__(self, text, x, y, font='9x15', adjust='left', color=None): Create a text actor
- def drawGL(self, mode='wireframe', color=None): Draw the text.
<|skeleton|>
cla... | f5404809095711334bbb938d9d119a69ad8fc260 | <|skeleton|>
class Text:
"""A viewport decoration showing a text."""
def __init__(self, text, x, y, font='9x15', adjust='left', color=None):
"""Create a text actor"""
<|body_0|>
def drawGL(self, mode='wireframe', color=None):
"""Draw the text."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Text:
"""A viewport decoration showing a text."""
def __init__(self, text, x, y, font='9x15', adjust='left', color=None):
"""Create a text actor"""
Decoration.__init__(self, x, y)
self.text = str(text)
self.font = font
self.adjust = adjust
self.color = sane... | the_stack_v2_python_sparse | tags/release-0.7.1/pyformex/gui/decors.py | BackupTheBerlios/pyformex-svn | train | 0 |
e734cbb0613eeff75b5f63a90e7c3f07a7a9d9d0 | [
"super(ListWebhookManifest, cls).setUpClass()\nwebhook1_response = cls.autoscale_client.create_webhook(cls.group.id, cls.policy['id'], 'webhook1').entity\ncls.webhook1 = cls.autoscale_behaviors.get_webhooks_properties(webhook1_response)\nwebhook2_response = cls.autoscale_client.create_webhook(cls.group.id, cls.poli... | <|body_start_0|>
super(ListWebhookManifest, cls).setUpClass()
webhook1_response = cls.autoscale_client.create_webhook(cls.group.id, cls.policy['id'], 'webhook1').entity
cls.webhook1 = cls.autoscale_behaviors.get_webhooks_properties(webhook1_response)
webhook2_response = cls.autoscale_cli... | Verify that the webhook manifest is provided when using /groups/[group_id]?webhooks=True Note: Should "webhooks" be case sensitive (currently it is) Note: Should "True" be case sensitive (currently it is not) (Assume that pagination of policies is the same) What is the pagination behavior? Test - add a second policy wi... | ListWebhookManifest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListWebhookManifest:
"""Verify that the webhook manifest is provided when using /groups/[group_id]?webhooks=True Note: Should "webhooks" be case sensitive (currently it is) Note: Should "True" be case sensitive (currently it is not) (Assume that pagination of policies is the same) What is the pag... | stack_v2_sparse_classes_75kplus_train_072604 | 4,167 | permissive | [
{
"docstring": "Creates a scaling group with a policy and 3 webhooks on the policy.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Verify the manifest call for response code 200, headers and data.",
"name": "test_manifest_webhooks",
"signature": "def test_m... | 3 | stack_v2_sparse_classes_30k_val_001159 | Implement the Python class `ListWebhookManifest` described below.
Class description:
Verify that the webhook manifest is provided when using /groups/[group_id]?webhooks=True Note: Should "webhooks" be case sensitive (currently it is) Note: Should "True" be case sensitive (currently it is not) (Assume that pagination o... | Implement the Python class `ListWebhookManifest` described below.
Class description:
Verify that the webhook manifest is provided when using /groups/[group_id]?webhooks=True Note: Should "webhooks" be case sensitive (currently it is) Note: Should "True" be case sensitive (currently it is not) (Assume that pagination o... | 7199cdd67255fe116dbcbedea660c13453671134 | <|skeleton|>
class ListWebhookManifest:
"""Verify that the webhook manifest is provided when using /groups/[group_id]?webhooks=True Note: Should "webhooks" be case sensitive (currently it is) Note: Should "True" be case sensitive (currently it is not) (Assume that pagination of policies is the same) What is the pag... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListWebhookManifest:
"""Verify that the webhook manifest is provided when using /groups/[group_id]?webhooks=True Note: Should "webhooks" be case sensitive (currently it is) Note: Should "True" be case sensitive (currently it is not) (Assume that pagination of policies is the same) What is the pagination behav... | the_stack_v2_python_sparse | autoscale_cloudroast/test_repo/autoscale/functional/scaling_group/test_scaling_group_manifest.py | rackerlabs/otter | train | 20 |
f8cdbab6e58b719575e090da2a9ff4c490d312a1 | [
"OrderItemForm.populate(self, location)\nif not self.is_submitted():\n if self.user_name.data is None:\n self.user_name.data = request.args.get('user_name')\n if self.user_name.data is None:\n self.user_name.data = session.get('anon_name', None)",
"rv = OrderForm.validate(self)\nif not rv:\n ... | <|body_start_0|>
OrderItemForm.populate(self, location)
if not self.is_submitted():
if self.user_name.data is None:
self.user_name.data = request.args.get('user_name')
if self.user_name.data is None:
self.user_name.data = session.get('anon_name', N... | Class which defines the form for a new Item in an Order For Users who aren't logged in | AnonOrderItemForm | [
"MIT",
"AGPL-3.0-or-later",
"AGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnonOrderItemForm:
"""Class which defines the form for a new Item in an Order For Users who aren't logged in"""
def populate(self, location: Location) -> None:
"""Fill in all the dish options from the location and the name of the anon user"""
<|body_0|>
def validate(self... | stack_v2_sparse_classes_75kplus_train_072605 | 3,544 | permissive | [
{
"docstring": "Fill in all the dish options from the location and the name of the anon user",
"name": "populate",
"signature": "def populate(self, location: Location) -> None"
},
{
"docstring": "Check if the provided anon_name is not already taken",
"name": "validate",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_050165 | Implement the Python class `AnonOrderItemForm` described below.
Class description:
Class which defines the form for a new Item in an Order For Users who aren't logged in
Method signatures and docstrings:
- def populate(self, location: Location) -> None: Fill in all the dish options from the location and the name of t... | Implement the Python class `AnonOrderItemForm` described below.
Class description:
Class which defines the form for a new Item in an Order For Users who aren't logged in
Method signatures and docstrings:
- def populate(self, location: Location) -> None: Fill in all the dish options from the location and the name of t... | 73671bd8f13b0c40dd0accd6ba27683b3bde442a | <|skeleton|>
class AnonOrderItemForm:
"""Class which defines the form for a new Item in an Order For Users who aren't logged in"""
def populate(self, location: Location) -> None:
"""Fill in all the dish options from the location and the name of the anon user"""
<|body_0|>
def validate(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnonOrderItemForm:
"""Class which defines the form for a new Item in an Order For Users who aren't logged in"""
def populate(self, location: Location) -> None:
"""Fill in all the dish options from the location and the name of the anon user"""
OrderItemForm.populate(self, location)
... | the_stack_v2_python_sparse | app/forms.py | fbegyn/Haldis | train | 0 |
c55358a55a80c02947fe6ece890005b7a1b1008d | [
"self.spooler = spool\nself.scope = scope\nself.hdf5File = hdf5File\nself.evts = self.hdf5File.createTable(hdf5File.root, 'Events', SpoolEvent)",
"if eventName == 'StartAq':\n eventDescr = '%d' % self.spooler.imNum\nev = self.evts.row\nev['EventName'] = eventName\nev['EventDescr'] = eventDescr\nev['Time'] = sp... | <|body_start_0|>
self.spooler = spool
self.scope = scope
self.hdf5File = hdf5File
self.evts = self.hdf5File.createTable(hdf5File.root, 'Events', SpoolEvent)
<|end_body_0|>
<|body_start_1|>
if eventName == 'StartAq':
eventDescr = '%d' % self.spooler.imNum
ev =... | Event logging backend for hdf/pytables data storage Parameters ---------- spool : instance of HDFSpooler.Spooler The spooler to ascociate this logger with scope : PYME.Acquire.microscope.microscope instance The current microscope object hdf5File : pytables hdf file The open HDF5 file to write to | EventLogger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventLogger:
"""Event logging backend for hdf/pytables data storage Parameters ---------- spool : instance of HDFSpooler.Spooler The spooler to ascociate this logger with scope : PYME.Acquire.microscope.microscope instance The current microscope object hdf5File : pytables hdf file The open HDF5 f... | stack_v2_sparse_classes_75kplus_train_072606 | 4,294 | no_license | [
{
"docstring": "Create a new Events table.",
"name": "__init__",
"signature": "def __init__(self, spool, scope, hdf5File)"
},
{
"docstring": "Log an event. Parameters ---------- eventName : string short event name - < 32 chars and should be shared by events of the same type. eventDescr : string ... | 2 | stack_v2_sparse_classes_30k_train_003864 | Implement the Python class `EventLogger` described below.
Class description:
Event logging backend for hdf/pytables data storage Parameters ---------- spool : instance of HDFSpooler.Spooler The spooler to ascociate this logger with scope : PYME.Acquire.microscope.microscope instance The current microscope object hdf5F... | Implement the Python class `EventLogger` described below.
Class description:
Event logging backend for hdf/pytables data storage Parameters ---------- spool : instance of HDFSpooler.Spooler The spooler to ascociate this logger with scope : PYME.Acquire.microscope.microscope instance The current microscope object hdf5F... | 6596167034c727ad7dad0a741dd59e0e48f6852a | <|skeleton|>
class EventLogger:
"""Event logging backend for hdf/pytables data storage Parameters ---------- spool : instance of HDFSpooler.Spooler The spooler to ascociate this logger with scope : PYME.Acquire.microscope.microscope instance The current microscope object hdf5File : pytables hdf file The open HDF5 f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventLogger:
"""Event logging backend for hdf/pytables data storage Parameters ---------- spool : instance of HDFSpooler.Spooler The spooler to ascociate this logger with scope : PYME.Acquire.microscope.microscope instance The current microscope object hdf5File : pytables hdf file The open HDF5 file to write ... | the_stack_v2_python_sparse | PYME/Acquire/HDFSpooler.py | WilliamRo/CLipPYME | train | 3 |
b0312d816b315254d4680768c25567a5212d3d8d | [
"self._stops = sorted(stops)\nif len(stops) < 2:\n raise ValueError('At least 2 stops required.')\nif self._stops[0][0] != 0.0:\n raise ValueError('First stop must be 0.')\nif self._stops[-1][0] != 1.0:\n raise ValueError('Last stop must be 1.')",
"position = clamp(position, 0.0, 1.0)\nfor (stop1, color1... | <|body_start_0|>
self._stops = sorted(stops)
if len(stops) < 2:
raise ValueError('At least 2 stops required.')
if self._stops[0][0] != 0.0:
raise ValueError('First stop must be 0.')
if self._stops[-1][0] != 1.0:
raise ValueError('Last stop must be 1.')... | Defines a color gradient. | Gradient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gradient:
"""Defines a color gradient."""
def __init__(self, *stops: tuple[float, Color]) -> None:
"""Create a color gradient that blends colors to form a spectrum. A gradient is defined by a sequence of "stops" consisting of a float and a color. The stop indicate the color at that p... | stack_v2_sparse_classes_75kplus_train_072607 | 20,476 | permissive | [
{
"docstring": "Create a color gradient that blends colors to form a spectrum. A gradient is defined by a sequence of \"stops\" consisting of a float and a color. The stop indicate the color at that point on a spectrum between 0 and 1. Args: stops: A colors stop. Raises: ValueError: If any stops are missing (mu... | 2 | null | Implement the Python class `Gradient` described below.
Class description:
Defines a color gradient.
Method signatures and docstrings:
- def __init__(self, *stops: tuple[float, Color]) -> None: Create a color gradient that blends colors to form a spectrum. A gradient is defined by a sequence of "stops" consisting of a... | Implement the Python class `Gradient` described below.
Class description:
Defines a color gradient.
Method signatures and docstrings:
- def __init__(self, *stops: tuple[float, Color]) -> None: Create a color gradient that blends colors to form a spectrum. A gradient is defined by a sequence of "stops" consisting of a... | b74ac1e47fdd16133ca567390c99ea19de278c5a | <|skeleton|>
class Gradient:
"""Defines a color gradient."""
def __init__(self, *stops: tuple[float, Color]) -> None:
"""Create a color gradient that blends colors to form a spectrum. A gradient is defined by a sequence of "stops" consisting of a float and a color. The stop indicate the color at that p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Gradient:
"""Defines a color gradient."""
def __init__(self, *stops: tuple[float, Color]) -> None:
"""Create a color gradient that blends colors to form a spectrum. A gradient is defined by a sequence of "stops" consisting of a float and a color. The stop indicate the color at that point on a spe... | the_stack_v2_python_sparse | src/textual/color.py | Textualize/textual | train | 14,818 |
e4d01b0e01d0c69f5a144e96a45c09824890e48d | [
"if not envelopes:\n return 0\nenvelopes = sorted(envelopes, key=lambda x: (x[0], -x[1]))\nenvelopes_height = [x[1] for x in envelopes]\nreturn self.LIS(envelopes_height)",
"def binary_search(l, r, nums, target):\n while r - l > 1:\n m = l + (r - l) // 2\n if nums[m] >= target:\n r ... | <|body_start_0|>
if not envelopes:
return 0
envelopes = sorted(envelopes, key=lambda x: (x[0], -x[1]))
envelopes_height = [x[1] for x in envelopes]
return self.LIS(envelopes_height)
<|end_body_0|>
<|body_start_1|>
def binary_search(l, r, nums, target):
wh... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_0|>
def LIS(self, nums):
"""Longest increasing sequences"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not envelopes:
return 0
... | stack_v2_sparse_classes_75kplus_train_072608 | 2,063 | no_license | [
{
"docstring": ":type envelopes: List[List[int]] :rtype: int",
"name": "maxEnvelopes",
"signature": "def maxEnvelopes(self, envelopes)"
},
{
"docstring": "Longest increasing sequences",
"name": "LIS",
"signature": "def LIS(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051773 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int
- def LIS(self, nums): Longest increasing sequences | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int
- def LIS(self, nums): Longest increasing sequences
<|skeleton|>
class Solution:
def maxEnve... | 4de7d3ea9aaa2e0cb2d934816036ced2357205ac | <|skeleton|>
class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_0|>
def LIS(self, nums):
"""Longest increasing sequences"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
if not envelopes:
return 0
envelopes = sorted(envelopes, key=lambda x: (x[0], -x[1]))
envelopes_height = [x[1] for x in envelopes]
return self.LIS(envelopes_heigh... | the_stack_v2_python_sparse | 354_russian_doll_envelopes.py | nshung2010/leet_code | train | 0 | |
04d04b854da21363c3a3362c13cb4a9fda559886 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Vulnerability()",
"from ..entity import Entity\nfrom .article import Article\nfrom .cvss_summary import CvssSummary\nfrom .formatted_content import FormattedContent\nfrom .hyperlink import Hyperlink\nfrom .vulnerability_component impor... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Vulnerability()
<|end_body_0|>
<|body_start_1|>
from ..entity import Entity
from .article import Article
from .cvss_summary import CvssSummary
from .formatted_content imp... | Vulnerability | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vulnerability:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Vulnerability:
"""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... | stack_v2_sparse_classes_75kplus_train_072609 | 7,963 | 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: Vulnerability",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | stack_v2_sparse_classes_30k_val_002010 | Implement the Python class `Vulnerability` described below.
Class description:
Implement the Vulnerability class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Vulnerability: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `Vulnerability` described below.
Class description:
Implement the Vulnerability class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Vulnerability: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Vulnerability:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Vulnerability:
"""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... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Vulnerability:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Vulnerability:
"""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: Vulnerabilit... | the_stack_v2_python_sparse | msgraph/generated/models/security/vulnerability.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
1ad5ed08108a68b0c690c9c59f9c19defc818c4f | [
"def convert(root):\n to_convert = []\n if root == None:\n to_convert.append('None')\n else:\n to_convert.append(str(root.val))\n to_convert.extend(convert(root.left))\n to_convert.extend(convert(root.right))\n return to_convert\nreturn ' '.join(convert(root))",
"def conver... | <|body_start_0|>
def convert(root):
to_convert = []
if root == None:
to_convert.append('None')
else:
to_convert.append(str(root.val))
to_convert.extend(convert(root.left))
to_convert.extend(convert(root.right))
... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_072610 | 1,372 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_022018 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 93936aeeef64487285db360b5884e844e0662b8e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def convert(root):
to_convert = []
if root == None:
to_convert.append('None')
else:
to_convert.append(str(root.val))
... | the_stack_v2_python_sparse | amazon/python/serialize_deserialize_binary_tree_297.py | Xiaoyu-Xing/algorithms | train | 0 | |
bb0c5155111e0c6ad0be0dcc95af68e9fde7e24b | [
"response = self.client.get(reverse('education:states'))\nself.assertEqual(response.status_code, 200)\nself.assertEqual(response.context.get('states').count(), 0)\nself.assertContains(response, 'No Data Available')\nself.assertNotContains(response, 'Number of Public High Schools')",
"create_states()\nresponse = s... | <|body_start_0|>
response = self.client.get(reverse('education:states'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context.get('states').count(), 0)
self.assertContains(response, 'No Data Available')
self.assertNotContains(response, 'Number of Public H... | EducationStatesViewTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EducationStatesViewTest:
def test_no_data(self):
"""Make sure the page renders and gives an error message if no data is available."""
<|body_0|>
def test_with_data(self):
"""Make sure page renders when state database is filled."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_75kplus_train_072611 | 9,266 | no_license | [
{
"docstring": "Make sure the page renders and gives an error message if no data is available.",
"name": "test_no_data",
"signature": "def test_no_data(self)"
},
{
"docstring": "Make sure page renders when state database is filled.",
"name": "test_with_data",
"signature": "def test_with_... | 2 | stack_v2_sparse_classes_30k_train_006637 | Implement the Python class `EducationStatesViewTest` described below.
Class description:
Implement the EducationStatesViewTest class.
Method signatures and docstrings:
- def test_no_data(self): Make sure the page renders and gives an error message if no data is available.
- def test_with_data(self): Make sure page re... | Implement the Python class `EducationStatesViewTest` described below.
Class description:
Implement the EducationStatesViewTest class.
Method signatures and docstrings:
- def test_no_data(self): Make sure the page renders and gives an error message if no data is available.
- def test_with_data(self): Make sure page re... | 2a8e2dc4e9b3cb92d4d437b37e61940a9486b81f | <|skeleton|>
class EducationStatesViewTest:
def test_no_data(self):
"""Make sure the page renders and gives an error message if no data is available."""
<|body_0|>
def test_with_data(self):
"""Make sure page renders when state database is filled."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EducationStatesViewTest:
def test_no_data(self):
"""Make sure the page renders and gives an error message if no data is available."""
response = self.client.get(reverse('education:states'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context.get('state... | the_stack_v2_python_sparse | education/tests.py | smeds1/mysite | train | 1 | |
ca3b9831c3756ecfbbe3bc4a133b3204d4377c7d | [
"self._num_threads = num_threads\nself._count = 0\nself._cond = threading.Condition()",
"with self._cond:\n self._count += 1\n self._cond.notifyAll()\n while self._count < self._num_threads:\n self._cond.wait()"
] | <|body_start_0|>
self._num_threads = num_threads
self._count = 0
self._cond = threading.Condition()
<|end_body_0|>
<|body_start_1|>
with self._cond:
self._count += 1
self._cond.notifyAll()
while self._count < self._num_threads:
self._c... | Defines a simple barrier class to synchronize on a particular event. | Barrier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Barrier:
"""Defines a simple barrier class to synchronize on a particular event."""
def __init__(self, num_threads):
"""Constructor. Args: num_threads: int - how many threads will be syncronizing on this barrier"""
<|body_0|>
def wait(self):
"""Waits on the barri... | stack_v2_sparse_classes_75kplus_train_072612 | 3,873 | permissive | [
{
"docstring": "Constructor. Args: num_threads: int - how many threads will be syncronizing on this barrier",
"name": "__init__",
"signature": "def __init__(self, num_threads)"
},
{
"docstring": "Waits on the barrier until all threads have called this method.",
"name": "wait",
"signature... | 2 | stack_v2_sparse_classes_30k_test_002617 | Implement the Python class `Barrier` described below.
Class description:
Defines a simple barrier class to synchronize on a particular event.
Method signatures and docstrings:
- def __init__(self, num_threads): Constructor. Args: num_threads: int - how many threads will be syncronizing on this barrier
- def wait(self... | Implement the Python class `Barrier` described below.
Class description:
Defines a simple barrier class to synchronize on a particular event.
Method signatures and docstrings:
- def __init__(self, num_threads): Constructor. Args: num_threads: int - how many threads will be syncronizing on this barrier
- def wait(self... | 97c50eaa62c039d8f4b9efa3e80c4d80e6f40c4c | <|skeleton|>
class Barrier:
"""Defines a simple barrier class to synchronize on a particular event."""
def __init__(self, num_threads):
"""Constructor. Args: num_threads: int - how many threads will be syncronizing on this barrier"""
<|body_0|>
def wait(self):
"""Waits on the barri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Barrier:
"""Defines a simple barrier class to synchronize on a particular event."""
def __init__(self, num_threads):
"""Constructor. Args: num_threads: int - how many threads will be syncronizing on this barrier"""
self._num_threads = num_threads
self._count = 0
self._cond... | the_stack_v2_python_sparse | acme/utils/counting_test.py | RaoulDrake/acme | train | 0 |
351ab2297381688a4177253566b4ff1c76897526 | [
"cost_s = sorted(costs)\nans = 0\nfor i in range(len(cost_s)):\n if coins >= cost_s[i]:\n coins -= cost_s[i]\n ans += 1\nreturn ans",
"def select_sort(l):\n \"\"\"\n\n :param l: 需要排序的列\n :return: 有序列\n \"\"\"\n for i in range(len(l) - 1):\n min_index ... | <|body_start_0|>
cost_s = sorted(costs)
ans = 0
for i in range(len(cost_s)):
if coins >= cost_s[i]:
coins -= cost_s[i]
ans += 1
return ans
<|end_body_0|>
<|body_start_1|>
def select_sort(l):
"""
:param ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxIceCream(self, costs: List[int], coins: int) -> int:
"""不能重复购买 先排序costs 优先从便宜的购买 :param costs: 雪糕价格表 :param coins: 手头的现金 :return: 能买到的最多雪糕数"""
<|body_0|>
def maxIceCream(self, costs: List[int], coins: int) -> int:
"""二分排序 :param costs: :param coins: ... | stack_v2_sparse_classes_75kplus_train_072613 | 2,488 | no_license | [
{
"docstring": "不能重复购买 先排序costs 优先从便宜的购买 :param costs: 雪糕价格表 :param coins: 手头的现金 :return: 能买到的最多雪糕数",
"name": "maxIceCream",
"signature": "def maxIceCream(self, costs: List[int], coins: int) -> int"
},
{
"docstring": "二分排序 :param costs: :param coins: :return:",
"name": "maxIceCream",
"si... | 2 | stack_v2_sparse_classes_30k_train_005596 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxIceCream(self, costs: List[int], coins: int) -> int: 不能重复购买 先排序costs 优先从便宜的购买 :param costs: 雪糕价格表 :param coins: 手头的现金 :return: 能买到的最多雪糕数
- def maxIceCream(self, costs: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxIceCream(self, costs: List[int], coins: int) -> int: 不能重复购买 先排序costs 优先从便宜的购买 :param costs: 雪糕价格表 :param coins: 手头的现金 :return: 能买到的最多雪糕数
- def maxIceCream(self, costs: Lis... | b1680014ce3f55ba952a1e64241c0cbb783cc436 | <|skeleton|>
class Solution:
def maxIceCream(self, costs: List[int], coins: int) -> int:
"""不能重复购买 先排序costs 优先从便宜的购买 :param costs: 雪糕价格表 :param coins: 手头的现金 :return: 能买到的最多雪糕数"""
<|body_0|>
def maxIceCream(self, costs: List[int], coins: int) -> int:
"""二分排序 :param costs: :param coins: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxIceCream(self, costs: List[int], coins: int) -> int:
"""不能重复购买 先排序costs 优先从便宜的购买 :param costs: 雪糕价格表 :param coins: 手头的现金 :return: 能买到的最多雪糕数"""
cost_s = sorted(costs)
ans = 0
for i in range(len(cost_s)):
if coins >= cost_s[i]:
coins -... | the_stack_v2_python_sparse | a_1833.py | sun510001/leetcode_jianzhi_offer_2 | train | 0 | |
83581516b9cb82d0425968ce240f31fc5d5fe9e5 | [
"super(DVCNNClassifier, self).__init__(json_model_path=model_file)\nif not ops.isfile(model_file):\n raise ValueError('{:s} is not a valid file'.format(model_file))\nself.__model_file = model_file\nself.__weights_file = weights_file\nself.__dvcnn_architecture = cnn_util.read_json_model(json_model_path=model_file... | <|body_start_0|>
super(DVCNNClassifier, self).__init__(json_model_path=model_file)
if not ops.isfile(model_file):
raise ValueError('{:s} is not a valid file'.format(model_file))
self.__model_file = model_file
self.__weights_file = weights_file
self.__dvcnn_architectur... | DVCNNClassifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DVCNNClassifier:
def __init__(self, model_file, weights_file):
"""Initialize the dvcnn model :param model_file: the dvcnn architecture definition file path :param weights_file: the weights file path"""
<|body_0|>
def predict(self, top_view_image_list, front_view_image_list):... | stack_v2_sparse_classes_75kplus_train_072614 | 2,798 | permissive | [
{
"docstring": "Initialize the dvcnn model :param model_file: the dvcnn architecture definition file path :param weights_file: the weights file path",
"name": "__init__",
"signature": "def __init__(self, model_file, weights_file)"
},
{
"docstring": "Use the top view and front view image pair to ... | 2 | null | Implement the Python class `DVCNNClassifier` described below.
Class description:
Implement the DVCNNClassifier class.
Method signatures and docstrings:
- def __init__(self, model_file, weights_file): Initialize the dvcnn model :param model_file: the dvcnn architecture definition file path :param weights_file: the wei... | Implement the Python class `DVCNNClassifier` described below.
Class description:
Implement the DVCNNClassifier class.
Method signatures and docstrings:
- def __init__(self, model_file, weights_file): Initialize the dvcnn model :param model_file: the dvcnn architecture definition file path :param weights_file: the wei... | b66a1a856ba69b0a0a82c7b53dd192e4906a375b | <|skeleton|>
class DVCNNClassifier:
def __init__(self, model_file, weights_file):
"""Initialize the dvcnn model :param model_file: the dvcnn architecture definition file path :param weights_file: the weights file path"""
<|body_0|>
def predict(self, top_view_image_list, front_view_image_list):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DVCNNClassifier:
def __init__(self, model_file, weights_file):
"""Initialize the dvcnn model :param model_file: the dvcnn architecture definition file path :param weights_file: the weights file path"""
super(DVCNNClassifier, self).__init__(json_model_path=model_file)
if not ops.isfile(... | the_stack_v2_python_sparse | Global_Optimization/dvcnn_classifier.py | robin1987z/DVCNN_Lane_Detection | train | 0 | |
2b8e4f3f5ba8f48ff6b455ce0b938743621d2e47 | [
"self.pos_init = pos_init\nself.pos_fin = pos_fin\nself.obs_fixe = obs_fixe\nself.taille = taille\nself.frontier = []\nhq.heappush(self.frontier, (0, self.pos_init))\nself.cost_so_far = {}\nself.cost_so_far[self.pos_init] = 0\nself.ferme = set()",
"while cible not in self.ferme:\n _, pos = hq.heappop(self.fron... | <|body_start_0|>
self.pos_init = pos_init
self.pos_fin = pos_fin
self.obs_fixe = obs_fixe
self.taille = taille
self.frontier = []
hq.heappush(self.frontier, (0, self.pos_init))
self.cost_so_far = {}
self.cost_so_far[self.pos_init] = 0
self.ferme = ... | Algorithme A* pour le calcul de la distance réelle dans les algorithmes coopératifs avancés. L'implémentation de A* est décomposée en deux parties. L'initialisation des variables est faite dans __init__. La fonction distance calcule la distance réelle entre pos_init et la cible en faisant tourner l'algorithme jusqu'à c... | algo_A | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class algo_A:
"""Algorithme A* pour le calcul de la distance réelle dans les algorithmes coopératifs avancés. L'implémentation de A* est décomposée en deux parties. L'initialisation des variables est faite dans __init__. La fonction distance calcule la distance réelle entre pos_init et la cible en fais... | stack_v2_sparse_classes_75kplus_train_072615 | 2,380 | no_license | [
{
"docstring": "pos_init : position de la fiole cible (on fait le chemin inverse). pos_fin : position initiale du joueur. obs_fixe : ensemble des obstacles fixes. taille : duplet contenant le nombre de lignes et de colonnes du monde.",
"name": "__init__",
"signature": "def __init__(self, pos_init, pos_f... | 2 | stack_v2_sparse_classes_30k_train_043456 | Implement the Python class `algo_A` described below.
Class description:
Algorithme A* pour le calcul de la distance réelle dans les algorithmes coopératifs avancés. L'implémentation de A* est décomposée en deux parties. L'initialisation des variables est faite dans __init__. La fonction distance calcule la distance ré... | Implement the Python class `algo_A` described below.
Class description:
Algorithme A* pour le calcul de la distance réelle dans les algorithmes coopératifs avancés. L'implémentation de A* est décomposée en deux parties. L'initialisation des variables est faite dans __init__. La fonction distance calcule la distance ré... | ee6c6863f1b584bc9e84bf5aa98bffa57eed5455 | <|skeleton|>
class algo_A:
"""Algorithme A* pour le calcul de la distance réelle dans les algorithmes coopératifs avancés. L'implémentation de A* est décomposée en deux parties. L'initialisation des variables est faite dans __init__. La fonction distance calcule la distance réelle entre pos_init et la cible en fais... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class algo_A:
"""Algorithme A* pour le calcul de la distance réelle dans les algorithmes coopératifs avancés. L'implémentation de A* est décomposée en deux parties. L'initialisation des variables est faite dans __init__. La fonction distance calcule la distance réelle entre pos_init et la cible en faisant tourner l... | the_stack_v2_python_sparse | TP5-7/teaching-iaro-master/pySpriteWorld-forStudents/code/algo_A.py | arianacarnielli/3I025 | train | 0 |
7f21dcf95b011292844fa197982adee16c80fead | [
"super().__init__(in_channels=in_channels, squeeze_ratio=squeeze_ratio, conv=conv, activation=activation, gate_activation=gate_activation)\nself.conv_squeeze2 = Conv(conv, in_channels=in_channels, out_channels=1, kernel_size=1, padding=0)\nself.gate2 = Activation(gate_activation)",
"x_ce = x.mean((2, 3), keepdim=... | <|body_start_0|>
super().__init__(in_channels=in_channels, squeeze_ratio=squeeze_ratio, conv=conv, activation=activation, gate_activation=gate_activation)
self.conv_squeeze2 = Conv(conv, in_channels=in_channels, out_channels=1, kernel_size=1, padding=0)
self.gate2 = Activation(gate_activation)
<... | SCSqueezeAndExcite | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SCSqueezeAndExcite:
def __init__(self, in_channels: int, squeeze_ratio: float=0.25, conv: str='conv', activation: str='relu', gate_activation: str='sigmoid', **kwargs) -> None:
"""Spatial and Channel Squeeze & Excitation. https://arxiv.org/abs/1803.02579 Parameters ---------- in_channels... | stack_v2_sparse_classes_75kplus_train_072616 | 11,576 | permissive | [
{
"docstring": "Spatial and Channel Squeeze & Excitation. https://arxiv.org/abs/1803.02579 Parameters ---------- in_channels : int Number of input channels. squeeze_ratio : float, default=0.25 Ratio of squeeze. conv : str, default=\"conv\" Convolution layer type. activation : str, default=\"relu\" Activation la... | 2 | stack_v2_sparse_classes_30k_train_012055 | Implement the Python class `SCSqueezeAndExcite` described below.
Class description:
Implement the SCSqueezeAndExcite class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, squeeze_ratio: float=0.25, conv: str='conv', activation: str='relu', gate_activation: str='sigmoid', **kwargs) -> None: S... | Implement the Python class `SCSqueezeAndExcite` described below.
Class description:
Implement the SCSqueezeAndExcite class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, squeeze_ratio: float=0.25, conv: str='conv', activation: str='relu', gate_activation: str='sigmoid', **kwargs) -> None: S... | 7f79405012eb934b419bbdba8de23f35e840ca85 | <|skeleton|>
class SCSqueezeAndExcite:
def __init__(self, in_channels: int, squeeze_ratio: float=0.25, conv: str='conv', activation: str='relu', gate_activation: str='sigmoid', **kwargs) -> None:
"""Spatial and Channel Squeeze & Excitation. https://arxiv.org/abs/1803.02579 Parameters ---------- in_channels... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SCSqueezeAndExcite:
def __init__(self, in_channels: int, squeeze_ratio: float=0.25, conv: str='conv', activation: str='relu', gate_activation: str='sigmoid', **kwargs) -> None:
"""Spatial and Channel Squeeze & Excitation. https://arxiv.org/abs/1803.02579 Parameters ---------- in_channels : int Number ... | the_stack_v2_python_sparse | cellseg_models_pytorch/modules/attention_modules.py | okunator/cellseg_models.pytorch | train | 43 | |
2b5ae912190d192c9800f906ef4ce1e338138b5b | [
"if value is self.field.missing_value:\n return []\nconverter = self._getConverter(self.field.value_type)\nkey_converter = self._getConverter(self.field.key_type)\nreturn [(key_converter.toWidgetValue(k), converter.toWidgetValue(v)) for k, v in value.items()]",
"if not len(value):\n return self.field.missin... | <|body_start_0|>
if value is self.field.missing_value:
return []
converter = self._getConverter(self.field.value_type)
key_converter = self._getConverter(self.field.key_type)
return [(key_converter.toWidgetValue(k), converter.toWidgetValue(v)) for k, v in value.items()]
<|end... | Data converter for IMultiWidget. | DictMultiConverter | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DictMultiConverter:
"""Data converter for IMultiWidget."""
def toWidgetValue(self, value):
"""Just dispatch it."""
<|body_0|>
def toFieldValue(self, value):
"""Just dispatch it."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if value is self.fi... | stack_v2_sparse_classes_75kplus_train_072617 | 15,934 | permissive | [
{
"docstring": "Just dispatch it.",
"name": "toWidgetValue",
"signature": "def toWidgetValue(self, value)"
},
{
"docstring": "Just dispatch it.",
"name": "toFieldValue",
"signature": "def toFieldValue(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016880 | Implement the Python class `DictMultiConverter` described below.
Class description:
Data converter for IMultiWidget.
Method signatures and docstrings:
- def toWidgetValue(self, value): Just dispatch it.
- def toFieldValue(self, value): Just dispatch it. | Implement the Python class `DictMultiConverter` described below.
Class description:
Data converter for IMultiWidget.
Method signatures and docstrings:
- def toWidgetValue(self, value): Just dispatch it.
- def toFieldValue(self, value): Just dispatch it.
<|skeleton|>
class DictMultiConverter:
"""Data converter fo... | aa47e9b109ad2d7de600fc1d4ea7359d8144f356 | <|skeleton|>
class DictMultiConverter:
"""Data converter for IMultiWidget."""
def toWidgetValue(self, value):
"""Just dispatch it."""
<|body_0|>
def toFieldValue(self, value):
"""Just dispatch it."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DictMultiConverter:
"""Data converter for IMultiWidget."""
def toWidgetValue(self, value):
"""Just dispatch it."""
if value is self.field.missing_value:
return []
converter = self._getConverter(self.field.value_type)
key_converter = self._getConverter(self.fiel... | the_stack_v2_python_sparse | src/z3c/form/converter.py | zopefoundation/z3c.form | train | 6 |
b3d9d6bb732fbd618729c295e66853ae4906c245 | [
"self._data = data\nself._period = min(period, len(data))\nself._window = window\nself._symbol = symbol",
"window_values = []\naveraged_data = []\nfor i in range(self._period):\n window_values.append(self._data[i])\n if len(window_values) == self._window:\n averaged_data.append(np.mean(window_values)... | <|body_start_0|>
self._data = data
self._period = min(period, len(data))
self._window = window
self._symbol = symbol
<|end_body_0|>
<|body_start_1|>
window_values = []
averaged_data = []
for i in range(self._period):
window_values.append(self._data[i]... | DaysProcessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DaysProcessor:
def __init__(self, data, period, window=5, symbol=''):
"""Constructor. Args: data: a dictionary of values for each week in reverse order (ie. latest first) period: an `int` indicating the number of days used in total. window: an `int` indicating the number of days to avera... | stack_v2_sparse_classes_75kplus_train_072618 | 4,541 | no_license | [
{
"docstring": "Constructor. Args: data: a dictionary of values for each week in reverse order (ie. latest first) period: an `int` indicating the number of days used in total. window: an `int` indicating the number of days to average over. symbol: only used by the polynomial model function",
"name": "__init... | 3 | stack_v2_sparse_classes_30k_test_000315 | Implement the Python class `DaysProcessor` described below.
Class description:
Implement the DaysProcessor class.
Method signatures and docstrings:
- def __init__(self, data, period, window=5, symbol=''): Constructor. Args: data: a dictionary of values for each week in reverse order (ie. latest first) period: an `int... | Implement the Python class `DaysProcessor` described below.
Class description:
Implement the DaysProcessor class.
Method signatures and docstrings:
- def __init__(self, data, period, window=5, symbol=''): Constructor. Args: data: a dictionary of values for each week in reverse order (ie. latest first) period: an `int... | 7385c1c485cf94eeebd7aa9186d1cd7802bd50a4 | <|skeleton|>
class DaysProcessor:
def __init__(self, data, period, window=5, symbol=''):
"""Constructor. Args: data: a dictionary of values for each week in reverse order (ie. latest first) period: an `int` indicating the number of days used in total. window: an `int` indicating the number of days to avera... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DaysProcessor:
def __init__(self, data, period, window=5, symbol=''):
"""Constructor. Args: data: a dictionary of values for each week in reverse order (ie. latest first) period: an `int` indicating the number of days used in total. window: an `int` indicating the number of days to average over. symbo... | the_stack_v2_python_sparse | days_processor.py | xavigonzalvo/stock-trigger | train | 4 | |
2a1f8d2713a1a4870626bfe5c8642f7b8365f945 | [
"self.config_entry = config_entry\nself.current_config: dict = dict(config_entry.data)\nself.sensor_type: SensorType = self.current_config.get(CONF_SENSOR_TYPE) or SensorType.VIRTUAL_POWER\nself.source_entity_id: str | None = self.current_config.get(CONF_ENTITY_ID)\nself.source_entity: SourceEntity | None = None",
... | <|body_start_0|>
self.config_entry = config_entry
self.current_config: dict = dict(config_entry.data)
self.sensor_type: SensorType = self.current_config.get(CONF_SENSOR_TYPE) or SensorType.VIRTUAL_POWER
self.source_entity_id: str | None = self.current_config.get(CONF_ENTITY_ID)
s... | Handle an option flow for PowerCalc. | OptionsFlowHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionsFlowHandler:
"""Handle an option flow for PowerCalc."""
def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize options flow."""
<|body_0|>
async def async_step_init(self, user_input: dict[str, Any] | None=None) -> FlowResult:
"""Handle option... | stack_v2_sparse_classes_75kplus_train_072619 | 27,685 | no_license | [
{
"docstring": "Initialize options flow.",
"name": "__init__",
"signature": "def __init__(self, config_entry: ConfigEntry) -> None"
},
{
"docstring": "Handle options flow.",
"name": "async_step_init",
"signature": "async def async_step_init(self, user_input: dict[str, Any] | None=None) -... | 4 | stack_v2_sparse_classes_30k_train_025919 | Implement the Python class `OptionsFlowHandler` described below.
Class description:
Handle an option flow for PowerCalc.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry) -> None: Initialize options flow.
- async def async_step_init(self, user_input: dict[str, Any] | None=None) -> Flow... | Implement the Python class `OptionsFlowHandler` described below.
Class description:
Handle an option flow for PowerCalc.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry) -> None: Initialize options flow.
- async def async_step_init(self, user_input: dict[str, Any] | None=None) -> Flow... | b157b2ca9e38eb670bdfa735f824f48c81103707 | <|skeleton|>
class OptionsFlowHandler:
"""Handle an option flow for PowerCalc."""
def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize options flow."""
<|body_0|>
async def async_step_init(self, user_input: dict[str, Any] | None=None) -> FlowResult:
"""Handle option... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OptionsFlowHandler:
"""Handle an option flow for PowerCalc."""
def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize options flow."""
self.config_entry = config_entry
self.current_config: dict = dict(config_entry.data)
self.sensor_type: SensorType = self.cur... | the_stack_v2_python_sparse | custom_components/powercalc/config_flow.py | atxbyea/HA-Config | train | 8 |
05b655479137133b8a1209060873ac77b67ac0a2 | [
"def get_query():\n if np.random.rand() < prob:\n query_idx = np.random.randint(0, len(queries))\n query = queries[query_idx]\n else:\n query_idx = len(queries)\n query = np.random.choice([foo_token, bar_token, baz_token], size=3, replace=False)\n query = query.tolist()\n ... | <|body_start_0|>
def get_query():
if np.random.rand() < prob:
query_idx = np.random.randint(0, len(queries))
query = queries[query_idx]
else:
query_idx = len(queries)
query = np.random.choice([foo_token, bar_token, baz_token... | Utility that: - accepts user-specified queries and actions for those queries (that should be rewarded). - this requires specifying the vocab of tokens, and specifying the queries / actions for queries in terms of those vocab tokens - augments representations (i.e. builds out numpy.ndarray for DQN, torch.Tensor for SPG)... | RepresentationBuilder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepresentationBuilder:
"""Utility that: - accepts user-specified queries and actions for those queries (that should be rewarded). - this requires specifying the vocab of tokens, and specifying the queries / actions for queries in terms of those vocab tokens - augments representations (i.e. builds... | stack_v2_sparse_classes_75kplus_train_072620 | 14,400 | no_license | [
{
"docstring": "Args: queries (list of lists of ints): queries actions_per_query (list of list of ints): actions for corresponding queries to be rewarded K (int): size of state / query representation prob (float): probability with which to sample from queries (vs. random query)",
"name": "build_dqn",
"s... | 2 | stack_v2_sparse_classes_30k_train_008450 | Implement the Python class `RepresentationBuilder` described below.
Class description:
Utility that: - accepts user-specified queries and actions for those queries (that should be rewarded). - this requires specifying the vocab of tokens, and specifying the queries / actions for queries in terms of those vocab tokens ... | Implement the Python class `RepresentationBuilder` described below.
Class description:
Utility that: - accepts user-specified queries and actions for those queries (that should be rewarded). - this requires specifying the vocab of tokens, and specifying the queries / actions for queries in terms of those vocab tokens ... | 0d325b8cf5baed45edd4cbfcbe3c8366566b534a | <|skeleton|>
class RepresentationBuilder:
"""Utility that: - accepts user-specified queries and actions for those queries (that should be rewarded). - this requires specifying the vocab of tokens, and specifying the queries / actions for queries in terms of those vocab tokens - augments representations (i.e. builds... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RepresentationBuilder:
"""Utility that: - accepts user-specified queries and actions for those queries (that should be rewarded). - this requires specifying the vocab of tokens, and specifying the queries / actions for queries in terms of those vocab tokens - augments representations (i.e. builds out numpy.nd... | the_stack_v2_python_sparse | src/spg_agent/repr.py | jerwelborn/rlautoindex | train | 0 |
100e6d9a0609147cdc94f186222bf9bb6d58c69d | [
"self.Name = None\nself.Pid = None\nself.Username = None\nself.Cmdline = None",
"info('ProcessManager::Terminate Name:' + self.Name + ' PID:' + str(self.Pid))\ntry:\n process = Process(self.Pid)\n process.terminate()\nexcept Exception as ex:\n error('ProcessInfo::Terminate failed Name:' + self.Name + ' P... | <|body_start_0|>
self.Name = None
self.Pid = None
self.Username = None
self.Cmdline = None
<|end_body_0|>
<|body_start_1|>
info('ProcessManager::Terminate Name:' + self.Name + ' PID:' + str(self.Pid))
try:
process = Process(self.Pid)
process.termi... | Class for getting process info and killing processes | ProcessInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessInfo:
"""Class for getting process info and killing processes"""
def __init__(self):
"""Initialize process information"""
<|body_0|>
def Terminate(self):
"""Terminate the process"""
<|body_1|>
def IsRunning(pid):
"""Return True if proc... | stack_v2_sparse_classes_75kplus_train_072621 | 8,931 | permissive | [
{
"docstring": "Initialize process information",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Terminate the process",
"name": "Terminate",
"signature": "def Terminate(self)"
},
{
"docstring": "Return True if process with specified pid is running",
... | 3 | stack_v2_sparse_classes_30k_train_002857 | Implement the Python class `ProcessInfo` described below.
Class description:
Class for getting process info and killing processes
Method signatures and docstrings:
- def __init__(self): Initialize process information
- def Terminate(self): Terminate the process
- def IsRunning(pid): Return True if process with specif... | Implement the Python class `ProcessInfo` described below.
Class description:
Class for getting process info and killing processes
Method signatures and docstrings:
- def __init__(self): Initialize process information
- def Terminate(self): Terminate the process
- def IsRunning(pid): Return True if process with specif... | 4fa4360d0c05dbbb65bd53cca0ca1014fcd45071 | <|skeleton|>
class ProcessInfo:
"""Class for getting process info and killing processes"""
def __init__(self):
"""Initialize process information"""
<|body_0|>
def Terminate(self):
"""Terminate the process"""
<|body_1|>
def IsRunning(pid):
"""Return True if proc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProcessInfo:
"""Class for getting process info and killing processes"""
def __init__(self):
"""Initialize process information"""
self.Name = None
self.Pid = None
self.Username = None
self.Cmdline = None
def Terminate(self):
"""Terminate the process"""
... | the_stack_v2_python_sparse | myDevices/system/services.py | myDevicesIoT/Cayenne-Agent | train | 21 |
3accda0b5b82073651a328298b202670814179ec | [
"self.robot = robot\nself.relative_phase = relative_phase\nself.v = v\nself.a = a\nself.R = R\nself.amp_offset = amp_offset\nself.phase_offset = phase_offset\nself.phase_biases = self.generate_biases(relative_phase)",
"phase_biases = np.zeros((self.robot.n_oscillators, self.robot.n_oscillators))\nfor i in range(s... | <|body_start_0|>
self.robot = robot
self.relative_phase = relative_phase
self.v = v
self.a = a
self.R = R
self.amp_offset = amp_offset
self.phase_offset = phase_offset
self.phase_biases = self.generate_biases(relative_phase)
<|end_body_0|>
<|body_start_1|... | Gait | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gait:
def __init__(self, robot, relative_phase, v, a, R, amp_offset, phase_offset):
"""Class containing default components of a gait. Formulation similar to Crespi2008 :param robot: Robot object :param relative_phase: phase difference between base joints :param v: frequency of each CPG -... | stack_v2_sparse_classes_75kplus_train_072622 | 9,855 | no_license | [
{
"docstring": "Class containing default components of a gait. Formulation similar to Crespi2008 :param robot: Robot object :param relative_phase: phase difference between base joints :param v: frequency of each CPG - fixed and same right now :param R: amplitude of CPG - fixed and same right now :param a: posit... | 2 | stack_v2_sparse_classes_30k_train_009828 | Implement the Python class `Gait` described below.
Class description:
Implement the Gait class.
Method signatures and docstrings:
- def __init__(self, robot, relative_phase, v, a, R, amp_offset, phase_offset): Class containing default components of a gait. Formulation similar to Crespi2008 :param robot: Robot object ... | Implement the Python class `Gait` described below.
Class description:
Implement the Gait class.
Method signatures and docstrings:
- def __init__(self, robot, relative_phase, v, a, R, amp_offset, phase_offset): Class containing default components of a gait. Formulation similar to Crespi2008 :param robot: Robot object ... | 463c5555a1b3c28c0d73bd05521e9758eef15e0e | <|skeleton|>
class Gait:
def __init__(self, robot, relative_phase, v, a, R, amp_offset, phase_offset):
"""Class containing default components of a gait. Formulation similar to Crespi2008 :param robot: Robot object :param relative_phase: phase difference between base joints :param v: frequency of each CPG -... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Gait:
def __init__(self, robot, relative_phase, v, a, R, amp_offset, phase_offset):
"""Class containing default components of a gait. Formulation similar to Crespi2008 :param robot: Robot object :param relative_phase: phase difference between base joints :param v: frequency of each CPG - fixed and sam... | the_stack_v2_python_sparse | gym-daisy-custom/gym_daisy_custom/control/gaits.py | contactrika/bo-svae-dc | train | 6 | |
ed41bfc5515008d62eee2b4e11ec55f39c8710c4 | [
"query = request.GET.get('q')\nsort = request.GET.get('sort', 'name')\nasearch = Platform.objects.filter(id=kwargs['id']).first()\nform = PlatformForm(instance=asearch)\nlist_platform = None\nif query:\n list_platform = Platform.objects.filter(Q(name_platform__icontains=query))\nelse:\n list_platform = Platfo... | <|body_start_0|>
query = request.GET.get('q')
sort = request.GET.get('sort', 'name')
asearch = Platform.objects.filter(id=kwargs['id']).first()
form = PlatformForm(instance=asearch)
list_platform = None
if query:
list_platform = Platform.objects.filter(Q(name_... | Clase para editar las plataformas | PlatformEditView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlatformEditView:
"""Clase para editar las plataformas"""
def get(self, request, *args, **kwargs):
"""Método get"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Método post"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
query = reque... | stack_v2_sparse_classes_75kplus_train_072623 | 22,221 | no_license | [
{
"docstring": "Método get",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Método post",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033924 | Implement the Python class `PlatformEditView` described below.
Class description:
Clase para editar las plataformas
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Método get
- def post(self, request, *args, **kwargs): Método post | Implement the Python class `PlatformEditView` described below.
Class description:
Clase para editar las plataformas
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Método get
- def post(self, request, *args, **kwargs): Método post
<|skeleton|>
class PlatformEditView:
"""Clase para ed... | e28e2d968372609ad396c42fb572a00c2410a117 | <|skeleton|>
class PlatformEditView:
"""Clase para editar las plataformas"""
def get(self, request, *args, **kwargs):
"""Método get"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Método post"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlatformEditView:
"""Clase para editar las plataformas"""
def get(self, request, *args, **kwargs):
"""Método get"""
query = request.GET.get('q')
sort = request.GET.get('sort', 'name')
asearch = Platform.objects.filter(id=kwargs['id']).first()
form = PlatformForm(in... | the_stack_v2_python_sparse | list/views.py | damaos/server_list2 | train | 0 |
2ddecd9114f9d28791355050c36172b4f42fbdf5 | [
"self.index = person.get('Index')\nself.bounding_box = person.get('BoundingBox')\nface = person.get('Face')\nself.face = RekognitionFace(face) if face is not None else None\nself.timestamp = timestamp",
"rendering = self.face.to_dict() if self.face is not None else {}\nif self.index is not None:\n rendering['i... | <|body_start_0|>
self.index = person.get('Index')
self.bounding_box = person.get('BoundingBox')
face = person.get('Face')
self.face = RekognitionFace(face) if face is not None else None
self.timestamp = timestamp
<|end_body_0|>
<|body_start_1|>
rendering = self.face.to_d... | Encapsulates an Amazon Rekognition person. | RekognitionPerson | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RekognitionPerson:
"""Encapsulates an Amazon Rekognition person."""
def __init__(self, person, timestamp=None):
"""Initializes the person object. :param person: Person data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the person was detecte... | stack_v2_sparse_classes_75kplus_train_072624 | 11,689 | permissive | [
{
"docstring": "Initializes the person object. :param person: Person data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the person was detected, if the person was detected in a video.",
"name": "__init__",
"signature": "def __init__(self, person, timestamp=None... | 2 | stack_v2_sparse_classes_30k_train_011015 | Implement the Python class `RekognitionPerson` described below.
Class description:
Encapsulates an Amazon Rekognition person.
Method signatures and docstrings:
- def __init__(self, person, timestamp=None): Initializes the person object. :param person: Person data, in the format returned by Amazon Rekognition function... | Implement the Python class `RekognitionPerson` described below.
Class description:
Encapsulates an Amazon Rekognition person.
Method signatures and docstrings:
- def __init__(self, person, timestamp=None): Initializes the person object. :param person: Person data, in the format returned by Amazon Rekognition function... | dec41fb589043ac9d8667aac36fb88a53c3abe50 | <|skeleton|>
class RekognitionPerson:
"""Encapsulates an Amazon Rekognition person."""
def __init__(self, person, timestamp=None):
"""Initializes the person object. :param person: Person data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the person was detecte... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RekognitionPerson:
"""Encapsulates an Amazon Rekognition person."""
def __init__(self, person, timestamp=None):
"""Initializes the person object. :param person: Person data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the person was detected, if the per... | the_stack_v2_python_sparse | python/example_code/rekognition/rekognition_objects.py | awsdocs/aws-doc-sdk-examples | train | 8,240 |
728b7213957771505cc3874ff5b7088e68502e86 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SharedWithChannelTeamInfo()",
"from .conversation_member import ConversationMember\nfrom .team_info import TeamInfo\nfrom .conversation_member import ConversationMember\nfrom .team_info import TeamInfo\nfields: Dict[str, Callable[[Any]... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SharedWithChannelTeamInfo()
<|end_body_0|>
<|body_start_1|>
from .conversation_member import ConversationMember
from .team_info import TeamInfo
from .conversation_member import C... | SharedWithChannelTeamInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SharedWithChannelTeamInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedWithChannelTeamInfo:
"""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 c... | stack_v2_sparse_classes_75kplus_train_072625 | 2,593 | 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: SharedWithChannelTeamInfo",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrim... | 3 | stack_v2_sparse_classes_30k_train_048790 | Implement the Python class `SharedWithChannelTeamInfo` described below.
Class description:
Implement the SharedWithChannelTeamInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedWithChannelTeamInfo: Creates a new instance of the appropriat... | Implement the Python class `SharedWithChannelTeamInfo` described below.
Class description:
Implement the SharedWithChannelTeamInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedWithChannelTeamInfo: Creates a new instance of the appropriat... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SharedWithChannelTeamInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedWithChannelTeamInfo:
"""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 c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SharedWithChannelTeamInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedWithChannelTeamInfo:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | the_stack_v2_python_sparse | msgraph/generated/models/shared_with_channel_team_info.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
268c21986fe539544344a86cb088d0a84dd94964 | [
"if self.dataset is None or dset not in self.dataset:\n if dset not in container._dataset_spec or not container._dataset_spec[dset].get('truncate', False):\n self.log.debug(f\"Not truncating dataset '{dset}' in {container}.\")\n return None\n given_params = container._dataset_spec[dset].get('tru... | <|body_start_0|>
if self.dataset is None or dset not in self.dataset:
if dset not in container._dataset_spec or not container._dataset_spec[dset].get('truncate', False):
self.log.debug(f"Not truncating dataset '{dset}' in {container}.")
return None
given_p... | Precision truncate data prior to saving with bitshuffle compression. If no configuration is provided, will look for preset values for the input container. Any properties defined in the config will override the presets. If available, each specified dataset will be truncated relative to a (specified) weight dataset with ... | Truncate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Truncate:
"""Precision truncate data prior to saving with bitshuffle compression. If no configuration is provided, will look for preset values for the input container. Any properties defined in the config will override the presets. If available, each specified dataset will be truncated relative t... | stack_v2_sparse_classes_75kplus_train_072626 | 38,215 | permissive | [
{
"docstring": "Load truncation parameters for a dataset from config or container defaults. Parameters ---------- container Container class. dset : str Dataset name Returns ------- Dict or None Returns `None` if the dataset shouldn't get truncated.",
"name": "_get_params",
"signature": "def _get_params(... | 2 | null | Implement the Python class `Truncate` described below.
Class description:
Precision truncate data prior to saving with bitshuffle compression. If no configuration is provided, will look for preset values for the input container. Any properties defined in the config will override the presets. If available, each specifi... | Implement the Python class `Truncate` described below.
Class description:
Precision truncate data prior to saving with bitshuffle compression. If no configuration is provided, will look for preset values for the input container. Any properties defined in the config will override the presets. If available, each specifi... | 544e485c03c125d260eb22ef467ae4d2e4dfed09 | <|skeleton|>
class Truncate:
"""Precision truncate data prior to saving with bitshuffle compression. If no configuration is provided, will look for preset values for the input container. Any properties defined in the config will override the presets. If available, each specified dataset will be truncated relative t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Truncate:
"""Precision truncate data prior to saving with bitshuffle compression. If no configuration is provided, will look for preset values for the input container. Any properties defined in the config will override the presets. If available, each specified dataset will be truncated relative to a (specifie... | the_stack_v2_python_sparse | draco/core/io.py | radiocosmology/draco | train | 8 |
16d2159a79e1bf886a49d7db52e067aa0a2b22f3 | [
"self._caffe = kwargs.pop('caffe')\nself._creator = kwargs.pop('creator')\nkwargs.setdefault('label_suffix', '')\nsuper(ReportForm, self).__init__(*args, **kwargs)",
"report = super(ReportForm, self).save(commit=False)\nreport.caffe = self._caffe\nreport.creator = self._creator\nif commit:\n report.save()\nret... | <|body_start_0|>
self._caffe = kwargs.pop('caffe')
self._creator = kwargs.pop('creator')
kwargs.setdefault('label_suffix', '')
super(ReportForm, self).__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
report = super(ReportForm, self).save(commit=False)
report.caf... | Responsible for setting up a Report. | ReportForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportForm:
"""Responsible for setting up a Report."""
def __init__(self, *args, **kwargs):
"""Initialize all ReportForm's fields."""
<|body_0|>
def save(self, commit=True):
"""Override of save method, to add Caffe relation."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_072627 | 5,569 | permissive | [
{
"docstring": "Initialize all ReportForm's fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Override of save method, to add Caffe relation.",
"name": "save",
"signature": "def save(self, commit=True)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025969 | Implement the Python class `ReportForm` described below.
Class description:
Responsible for setting up a Report.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all ReportForm's fields.
- def save(self, commit=True): Override of save method, to add Caffe relation. | Implement the Python class `ReportForm` described below.
Class description:
Responsible for setting up a Report.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all ReportForm's fields.
- def save(self, commit=True): Override of save method, to add Caffe relation.
<|skeleton|>
cla... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class ReportForm:
"""Responsible for setting up a Report."""
def __init__(self, *args, **kwargs):
"""Initialize all ReportForm's fields."""
<|body_0|>
def save(self, commit=True):
"""Override of save method, to add Caffe relation."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReportForm:
"""Responsible for setting up a Report."""
def __init__(self, *args, **kwargs):
"""Initialize all ReportForm's fields."""
self._caffe = kwargs.pop('caffe')
self._creator = kwargs.pop('creator')
kwargs.setdefault('label_suffix', '')
super(ReportForm, sel... | the_stack_v2_python_sparse | caffe/reports/forms.py | VirrageS/io-kawiarnie | train | 3 |
22c313a5f853f0f19d63ee88652aafb6f36a06da | [
"if self.action == 'create':\n permission_classes = [permissions.IsTokenInstructor | permissions.IsTokenAdmin]\nelse:\n permission_classes = [permissions.IsTokenResourceRouteObjectRelatedVideo & permissions.IsTokenInstructor | permissions.IsTokenResourceRouteObjectRelatedVideo & permissions.IsTokenAdmin]\nret... | <|body_start_0|>
if self.action == 'create':
permission_classes = [permissions.IsTokenInstructor | permissions.IsTokenAdmin]
else:
permission_classes = [permissions.IsTokenResourceRouteObjectRelatedVideo & permissions.IsTokenInstructor | permissions.IsTokenResourceRouteObjectRela... | Viewset for the API of the Thumbnail object. | ThumbnailViewSet | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThumbnailViewSet:
"""Viewset for the API of the Thumbnail object."""
def get_permissions(self):
"""Instantiate and return the list of permissions that this view requires."""
<|body_0|>
def get_queryset(self):
"""Restrict list access to thumbnail related to the vi... | stack_v2_sparse_classes_75kplus_train_072628 | 32,875 | permissive | [
{
"docstring": "Instantiate and return the list of permissions that this view requires.",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Restrict list access to thumbnail related to the video in the JWT token.",
"name": "get_queryset",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_017133 | Implement the Python class `ThumbnailViewSet` described below.
Class description:
Viewset for the API of the Thumbnail object.
Method signatures and docstrings:
- def get_permissions(self): Instantiate and return the list of permissions that this view requires.
- def get_queryset(self): Restrict list access to thumbn... | Implement the Python class `ThumbnailViewSet` described below.
Class description:
Viewset for the API of the Thumbnail object.
Method signatures and docstrings:
- def get_permissions(self): Instantiate and return the list of permissions that this view requires.
- def get_queryset(self): Restrict list access to thumbn... | c26c9a7a4a690b21fbb1254be816a4d2cffbe1e2 | <|skeleton|>
class ThumbnailViewSet:
"""Viewset for the API of the Thumbnail object."""
def get_permissions(self):
"""Instantiate and return the list of permissions that this view requires."""
<|body_0|>
def get_queryset(self):
"""Restrict list access to thumbnail related to the vi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThumbnailViewSet:
"""Viewset for the API of the Thumbnail object."""
def get_permissions(self):
"""Instantiate and return the list of permissions that this view requires."""
if self.action == 'create':
permission_classes = [permissions.IsTokenInstructor | permissions.IsTokenAd... | the_stack_v2_python_sparse | src/backend/marsha/core/api.py | NamFra/marsha | train | 0 |
c045c01f855321240ac01a0ec8a6421caf0a0035 | [
"super(DecodingLayer, self).__init__()\nself.basic = BasicBlock(features_in, features_in)\nself.deconv = None\nself.conv_fc = None\nif last:\n self.conv_fc = nn.Conv3d(features_in, 1, kernel_size=1)\n self.softmax = Softmax3d()\nelse:\n self.deconv = nn.ConvTranspose3d(features_in, features_in // 2, kernel... | <|body_start_0|>
super(DecodingLayer, self).__init__()
self.basic = BasicBlock(features_in, features_in)
self.deconv = None
self.conv_fc = None
if last:
self.conv_fc = nn.Conv3d(features_in, 1, kernel_size=1)
self.softmax = Softmax3d()
else:
... | Definition of decoding layer in FusionNet architecture. | DecodingLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecodingLayer:
"""Definition of decoding layer in FusionNet architecture."""
def __init__(self, features_in: int, last: bool=False):
"""Initialisation. Args: features_in: Number of input feature channels. last: Whether this is the last decoding layer."""
<|body_0|>
def f... | stack_v2_sparse_classes_75kplus_train_072629 | 8,294 | permissive | [
{
"docstring": "Initialisation. Args: features_in: Number of input feature channels. last: Whether this is the last decoding layer.",
"name": "__init__",
"signature": "def __init__(self, features_in: int, last: bool=False)"
},
{
"docstring": "Forward pass through layer.",
"name": "forward",
... | 2 | stack_v2_sparse_classes_30k_train_029135 | Implement the Python class `DecodingLayer` described below.
Class description:
Definition of decoding layer in FusionNet architecture.
Method signatures and docstrings:
- def __init__(self, features_in: int, last: bool=False): Initialisation. Args: features_in: Number of input feature channels. last: Whether this is ... | Implement the Python class `DecodingLayer` described below.
Class description:
Definition of decoding layer in FusionNet architecture.
Method signatures and docstrings:
- def __init__(self, features_in: int, last: bool=False): Initialisation. Args: features_in: Number of input feature channels. last: Whether this is ... | fc0db7ca69d4149c736b8d0923272f14fb5693fe | <|skeleton|>
class DecodingLayer:
"""Definition of decoding layer in FusionNet architecture."""
def __init__(self, features_in: int, last: bool=False):
"""Initialisation. Args: features_in: Number of input feature channels. last: Whether this is the last decoding layer."""
<|body_0|>
def f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecodingLayer:
"""Definition of decoding layer in FusionNet architecture."""
def __init__(self, features_in: int, last: bool=False):
"""Initialisation. Args: features_in: Number of input feature channels. last: Whether this is the last decoding layer."""
super(DecodingLayer, self).__init_... | the_stack_v2_python_sparse | models/fusionnet.py | charleshouston/unet-pytorch | train | 2 |
c0b0a2b391039d470fb51a4e0e4641b965bd2175 | [
"objects = super(_Bgpq3QuerySync, self).query(*objects)\nif not self.path:\n msg = \"couldn't determine bgpq3 executable path\"\n self.log.error(msg=msg)\n raise RuntimeError(msg)\ntry:\n policy = self.opts['policy']\nexcept KeyError:\n policy = None\nall_cmds = self._construct_cmds(objects=objects, ... | <|body_start_0|>
objects = super(_Bgpq3QuerySync, self).query(*objects)
if not self.path:
msg = "couldn't determine bgpq3 executable path"
self.log.error(msg=msg)
raise RuntimeError(msg)
try:
policy = self.opts['policy']
except KeyError:
... | Performs queries using bgpq3. | _Bgpq3QuerySync | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Bgpq3QuerySync:
"""Performs queries using bgpq3."""
def query(self, *objects):
"""Execute a query."""
<|body_0|>
def _construct_cmds(self, objects, policy):
"""Construct bgpq3 command sets for query."""
<|body_1|>
def _run_cmds(self, all_cmds):
... | stack_v2_sparse_classes_75kplus_train_072630 | 4,202 | permissive | [
{
"docstring": "Execute a query.",
"name": "query",
"signature": "def query(self, *objects)"
},
{
"docstring": "Construct bgpq3 command sets for query.",
"name": "_construct_cmds",
"signature": "def _construct_cmds(self, objects, policy)"
},
{
"docstring": "Spawn bgpq3 subprocess... | 5 | stack_v2_sparse_classes_30k_train_008083 | Implement the Python class `_Bgpq3QuerySync` described below.
Class description:
Performs queries using bgpq3.
Method signatures and docstrings:
- def query(self, *objects): Execute a query.
- def _construct_cmds(self, objects, policy): Construct bgpq3 command sets for query.
- def _run_cmds(self, all_cmds): Spawn bg... | Implement the Python class `_Bgpq3QuerySync` described below.
Class description:
Performs queries using bgpq3.
Method signatures and docstrings:
- def query(self, *objects): Execute a query.
- def _construct_cmds(self, objects, policy): Construct bgpq3 command sets for query.
- def _run_cmds(self, all_cmds): Spawn bg... | aa4c5ec9882220fa42d9f7021ae049a3031016ea | <|skeleton|>
class _Bgpq3QuerySync:
"""Performs queries using bgpq3."""
def query(self, *objects):
"""Execute a query."""
<|body_0|>
def _construct_cmds(self, objects, policy):
"""Construct bgpq3 command sets for query."""
<|body_1|>
def _run_cmds(self, all_cmds):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Bgpq3QuerySync:
"""Performs queries using bgpq3."""
def query(self, *objects):
"""Execute a query."""
objects = super(_Bgpq3QuerySync, self).query(*objects)
if not self.path:
msg = "couldn't determine bgpq3 executable path"
self.log.error(msg=msg)
... | the_stack_v2_python_sparse | rptk/query/bgpq3/_sync.py | wolcomm/rptk | train | 16 |
d23879fbb4919967e4d9b07a7b7b2fdcd1cbabe0 | [
"local_path = tempfile.mkdtemp()\nmodel.model.save_pretrained(local_path)\nmodel.tokenizer.save_pretrained(local_path)\ndm.fs.copy_dir(local_path, path, force=True, progress=True, leave_progress=False)\nlogger.info(f'Model saved to {path}')\nif clean_up:\n mapper = dm.fs.get_mapper(local_path)\n mapper.fs.del... | <|body_start_0|>
local_path = tempfile.mkdtemp()
model.model.save_pretrained(local_path)
model.tokenizer.save_pretrained(local_path)
dm.fs.copy_dir(local_path, path, force=True, progress=True, leave_progress=False)
logger.info(f'Model saved to {path}')
if clean_up:
... | HFExperiment | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HFExperiment:
def save(cls, model: HFExperiment, path: str, clean_up: bool=False):
"""Save a hugging face model to a specific path Args: model: model to save path: path to the folder root where to save the model clean_up: whether to clean up the local path after saving"""
<|body_... | stack_v2_sparse_classes_75kplus_train_072631 | 16,347 | permissive | [
{
"docstring": "Save a hugging face model to a specific path Args: model: model to save path: path to the folder root where to save the model clean_up: whether to clean up the local path after saving",
"name": "save",
"signature": "def save(cls, model: HFExperiment, path: str, clean_up: bool=False)"
}... | 2 | stack_v2_sparse_classes_30k_train_001567 | Implement the Python class `HFExperiment` described below.
Class description:
Implement the HFExperiment class.
Method signatures and docstrings:
- def save(cls, model: HFExperiment, path: str, clean_up: bool=False): Save a hugging face model to a specific path Args: model: model to save path: path to the folder root... | Implement the Python class `HFExperiment` described below.
Class description:
Implement the HFExperiment class.
Method signatures and docstrings:
- def save(cls, model: HFExperiment, path: str, clean_up: bool=False): Save a hugging face model to a specific path Args: model: model to save path: path to the folder root... | 4390f9fce25fa2da94338227f7c8f33a23e25b2a | <|skeleton|>
class HFExperiment:
def save(cls, model: HFExperiment, path: str, clean_up: bool=False):
"""Save a hugging face model to a specific path Args: model: model to save path: path to the folder root where to save the model clean_up: whether to clean up the local path after saving"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HFExperiment:
def save(cls, model: HFExperiment, path: str, clean_up: bool=False):
"""Save a hugging face model to a specific path Args: model: model to save path: path to the folder root where to save the model clean_up: whether to clean up the local path after saving"""
local_path = tempfile... | the_stack_v2_python_sparse | molfeat/trans/pretrained/hf_transformers.py | datamol-io/molfeat | train | 111 | |
cf626943f9d1dfe2a3ab12003a4564fea14ad99c | [
"if not root:\n return ''\ndq = deque([root])\nres = [root.val]\nres.append(None)\nwhile dq:\n node = dq.pop()\n for child in node.children:\n res.append(child.val)\n dq.appendleft(child)\n res.append(None)\nreturn ' '.join(map(str, res))",
"if not data:\n return None\ndata = data.spl... | <|body_start_0|>
if not root:
return ''
dq = deque([root])
res = [root.val]
res.append(None)
while dq:
node = dq.pop()
for child in node.children:
res.append(child.val)
dq.appendleft(child)
res.append... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_072632 | 1,439 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_train_015919 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | 63120dbaabd7c3c19633ebe952bcee4cf826b0e0 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
if not root:
return ''
dq = deque([root])
res = [root.val]
res.append(None)
while dq:
node = dq.pop()
for c... | the_stack_v2_python_sparse | 428. Serialize and Deserialize N-ary Tree _ tree.py | CaizhiXu/LeetCode-Python-Solutions | train | 0 | |
5d9b10994e1c8a53e55e6d0357f14a3e76b0a343 | [
"motif_info = Motif.objects.get(pk=kwargs['motif_pk'])\nmotifinfo_serializer = self.serializer_class(motif_info)\ncontent = {'motifInfo': motifinfo_serializer.data}\nreturn Response(content, status=status.HTTP_200_OK)",
"motif_info = Motif.objects.get(pk=kwargs['motif_pk'])\nif self.request.user.is_authenticated:... | <|body_start_0|>
motif_info = Motif.objects.get(pk=kwargs['motif_pk'])
motifinfo_serializer = self.serializer_class(motif_info)
content = {'motifInfo': motifinfo_serializer.data}
return Response(content, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
motif_info = Mot... | 모티프 세부페이지 조회 | MotifDetailRetrieveUpdateDestroyView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MotifDetailRetrieveUpdateDestroyView:
"""모티프 세부페이지 조회"""
def get(self, request, *args, **kwargs):
"""모티프 세부 정보와 연결된 작품 정보"""
<|body_0|>
def put(self, request, *args, **kwargs):
"""모티프 제목 수정"""
<|body_1|>
def delete(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_072633 | 6,610 | no_license | [
{
"docstring": "모티프 세부 정보와 연결된 작품 정보",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "모티프 제목 수정",
"name": "put",
"signature": "def put(self, request, *args, **kwargs)"
},
{
"docstring": "모티프 삭제",
"name": "delete",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_018322 | Implement the Python class `MotifDetailRetrieveUpdateDestroyView` described below.
Class description:
모티프 세부페이지 조회
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 모티프 세부 정보와 연결된 작품 정보
- def put(self, request, *args, **kwargs): 모티프 제목 수정
- def delete(self, request, *args, **kwargs): 모티프 삭제 | Implement the Python class `MotifDetailRetrieveUpdateDestroyView` described below.
Class description:
모티프 세부페이지 조회
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 모티프 세부 정보와 연결된 작품 정보
- def put(self, request, *args, **kwargs): 모티프 제목 수정
- def delete(self, request, *args, **kwargs): 모티프 삭제... | 4031afe1b5d45865a61f4ff4136a8314258a917a | <|skeleton|>
class MotifDetailRetrieveUpdateDestroyView:
"""모티프 세부페이지 조회"""
def get(self, request, *args, **kwargs):
"""모티프 세부 정보와 연결된 작품 정보"""
<|body_0|>
def put(self, request, *args, **kwargs):
"""모티프 제목 수정"""
<|body_1|>
def delete(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MotifDetailRetrieveUpdateDestroyView:
"""모티프 세부페이지 조회"""
def get(self, request, *args, **kwargs):
"""모티프 세부 정보와 연결된 작품 정보"""
motif_info = Motif.objects.get(pk=kwargs['motif_pk'])
motifinfo_serializer = self.serializer_class(motif_info)
content = {'motifInfo': motifinfo_ser... | the_stack_v2_python_sparse | django_app/motif/apis/motifs.py | Monaegi/Julia-WordyGallery | train | 1 |
66b0d04f9ff8ff6a25a73968d0081278f7593e60 | [
"if not self.initial:\n intent = get_intent(self.request.session.get('token', False), self.kwargs['aiid'], self.kwargs['intent_name'])\n intent['webhook'] = '' if intent['webhook'] is None else intent['webhook']['endpoint']\n intent['responses'] = settings.TOKENFIELD_DELIMITER.join(intent['responses'])\n ... | <|body_start_0|>
if not self.initial:
intent = get_intent(self.request.session.get('token', False), self.kwargs['aiid'], self.kwargs['intent_name'])
intent['webhook'] = '' if intent['webhook'] is None else intent['webhook']['endpoint']
intent['responses'] = settings.TOKENFIEL... | Single Intent view | IntentsUpdateView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntentsUpdateView:
"""Single Intent view"""
def get_initial(self, **kwargs):
"""Get and prepare Intent data"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Provide intent name for the template"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_072634 | 39,842 | permissive | [
{
"docstring": "Get and prepare Intent data",
"name": "get_initial",
"signature": "def get_initial(self, **kwargs)"
},
{
"docstring": "Provide intent name for the template",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013357 | Implement the Python class `IntentsUpdateView` described below.
Class description:
Single Intent view
Method signatures and docstrings:
- def get_initial(self, **kwargs): Get and prepare Intent data
- def get_context_data(self, **kwargs): Provide intent name for the template | Implement the Python class `IntentsUpdateView` described below.
Class description:
Single Intent view
Method signatures and docstrings:
- def get_initial(self, **kwargs): Get and prepare Intent data
- def get_context_data(self, **kwargs): Provide intent name for the template
<|skeleton|>
class IntentsUpdateView:
... | d632d00f9a22a7a826bba4896a7102b2ac8690ff | <|skeleton|>
class IntentsUpdateView:
"""Single Intent view"""
def get_initial(self, **kwargs):
"""Get and prepare Intent data"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Provide intent name for the template"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IntentsUpdateView:
"""Single Intent view"""
def get_initial(self, **kwargs):
"""Get and prepare Intent data"""
if not self.initial:
intent = get_intent(self.request.session.get('token', False), self.kwargs['aiid'], self.kwargs['intent_name'])
intent['webhook'] = ''... | the_stack_v2_python_sparse | src/studio/views.py | hutomadotAI/web-console | train | 6 |
11ffc652f007e0182aa10995303ce88299e7e5ac | [
"if 'reduction' in kwargs:\n raise ValueError('Reduction is not supported in TopKLoss.This will always return the mean!')\nsuper().__init__(reduction='none', **kwargs)\nif topk < 0 or topk > 1:\n raise ValueError('topk needs to be in the range [0, 1].')\nself.topk = topk\nself.loss_weight = loss_weight",
"l... | <|body_start_0|>
if 'reduction' in kwargs:
raise ValueError('Reduction is not supported in TopKLoss.This will always return the mean!')
super().__init__(reduction='none', **kwargs)
if topk < 0 or topk > 1:
raise ValueError('topk needs to be in the range [0, 1].')
... | TopKLoss | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopKLoss:
def __init__(self, topk: float, loss_weight: float=1.0, **kwargs):
"""Uses topk percent of values to compute CE loss (expects pre softmax logits!) Args: topk: percentage of all entries to use for loss computation loss_weight: scalar to balance multiple losses"""
<|body_... | stack_v2_sparse_classes_75kplus_train_072635 | 8,471 | permissive | [
{
"docstring": "Uses topk percent of values to compute CE loss (expects pre softmax logits!) Args: topk: percentage of all entries to use for loss computation loss_weight: scalar to balance multiple losses",
"name": "__init__",
"signature": "def __init__(self, topk: float, loss_weight: float=1.0, **kwar... | 2 | stack_v2_sparse_classes_30k_test_002754 | Implement the Python class `TopKLoss` described below.
Class description:
Implement the TopKLoss class.
Method signatures and docstrings:
- def __init__(self, topk: float, loss_weight: float=1.0, **kwargs): Uses topk percent of values to compute CE loss (expects pre softmax logits!) Args: topk: percentage of all entr... | Implement the Python class `TopKLoss` described below.
Class description:
Implement the TopKLoss class.
Method signatures and docstrings:
- def __init__(self, topk: float, loss_weight: float=1.0, **kwargs): Uses topk percent of values to compute CE loss (expects pre softmax logits!) Args: topk: percentage of all entr... | 4f41faa7536dcef8fca7b647dcdca25360e5b58a | <|skeleton|>
class TopKLoss:
def __init__(self, topk: float, loss_weight: float=1.0, **kwargs):
"""Uses topk percent of values to compute CE loss (expects pre softmax logits!) Args: topk: percentage of all entries to use for loss computation loss_weight: scalar to balance multiple losses"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TopKLoss:
def __init__(self, topk: float, loss_weight: float=1.0, **kwargs):
"""Uses topk percent of values to compute CE loss (expects pre softmax logits!) Args: topk: percentage of all entries to use for loss computation loss_weight: scalar to balance multiple losses"""
if 'reduction' in kwa... | the_stack_v2_python_sparse | nndet/losses/segmentation.py | dboun/nnDetection | train | 1 | |
6e0404fadfc79d244ffe772282a1a8ab7802364d | [
"self.app = app\nself.connection = app.connection_or_acquire()\nif isinstance(self.connection, FallbackContext):\n self.connection = self.connection.fallback()\nsuper().__init__()",
"while True:\n try:\n workers = self.app.control.ping(timeout=self.workers_ping_timeout_seconds)\n logging.info(... | <|body_start_0|>
self.app = app
self.connection = app.connection_or_acquire()
if isinstance(self.connection, FallbackContext):
self.connection = self.connection.fallback()
super().__init__()
<|end_body_0|>
<|body_start_1|>
while True:
try:
... | A thread for collecting information on queues and workers. Based on, the now archived, https://github.com/zerok/celery-prometheus-exporter. | Collector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Collector:
"""A thread for collecting information on queues and workers. Based on, the now archived, https://github.com/zerok/celery-prometheus-exporter."""
def __init__(self, app: Celery):
"""Create the collector thread."""
<|body_0|>
def run(self):
"""Run the c... | stack_v2_sparse_classes_75kplus_train_072636 | 12,496 | permissive | [
{
"docstring": "Create the collector thread.",
"name": "__init__",
"signature": "def __init__(self, app: Celery)"
},
{
"docstring": "Run the collector thread.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012415 | Implement the Python class `Collector` described below.
Class description:
A thread for collecting information on queues and workers. Based on, the now archived, https://github.com/zerok/celery-prometheus-exporter.
Method signatures and docstrings:
- def __init__(self, app: Celery): Create the collector thread.
- def... | Implement the Python class `Collector` described below.
Class description:
A thread for collecting information on queues and workers. Based on, the now archived, https://github.com/zerok/celery-prometheus-exporter.
Method signatures and docstrings:
- def __init__(self, app: Celery): Create the collector thread.
- def... | 47c6377ccbfe8576b35854053d726537e533e78c | <|skeleton|>
class Collector:
"""A thread for collecting information on queues and workers. Based on, the now archived, https://github.com/zerok/celery-prometheus-exporter."""
def __init__(self, app: Celery):
"""Create the collector thread."""
<|body_0|>
def run(self):
"""Run the c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Collector:
"""A thread for collecting information on queues and workers. Based on, the now archived, https://github.com/zerok/celery-prometheus-exporter."""
def __init__(self, app: Celery):
"""Create the collector thread."""
self.app = app
self.connection = app.connection_or_acqui... | the_stack_v2_python_sparse | overseer/overseer.py | gxf1986/hub | train | 0 |
b257eaf075fa10862c3f9f0895e7aacf0c961b7e | [
"def get_all_seq(pre: str, text: str) -> List[str]:\n if not text:\n return [pre]\n r = []\n c = text[0]\n r.extend(get_all_seq(pre + c, text[1:]))\n r.extend(get_all_seq(pre, text[1:]))\n return r\ns1 = set(get_all_seq('', text1))\ns2 = set(get_all_seq('', text2))\nlcs = ''\nn = 0\nfor x i... | <|body_start_0|>
def get_all_seq(pre: str, text: str) -> List[str]:
if not text:
return [pre]
r = []
c = text[0]
r.extend(get_all_seq(pre + c, text[1:]))
r.extend(get_all_seq(pre, text[1:]))
return r
s1 = set(get_all... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonSubsequence_v1(self, text1: str, text2: str) -> int:
"""Brute force. Complexity is O(n * 2^n)."""
<|body_0|>
def longestCommonSubsequence_v2(self, text1: str, text2: str) -> int:
"""Use recursion. Slow."""
<|body_1|>
def longes... | stack_v2_sparse_classes_75kplus_train_072637 | 5,357 | no_license | [
{
"docstring": "Brute force. Complexity is O(n * 2^n).",
"name": "longestCommonSubsequence_v1",
"signature": "def longestCommonSubsequence_v1(self, text1: str, text2: str) -> int"
},
{
"docstring": "Use recursion. Slow.",
"name": "longestCommonSubsequence_v2",
"signature": "def longestCo... | 4 | stack_v2_sparse_classes_30k_train_032748 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonSubsequence_v1(self, text1: str, text2: str) -> int: Brute force. Complexity is O(n * 2^n).
- def longestCommonSubsequence_v2(self, text1: str, text2: str) -> in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonSubsequence_v1(self, text1: str, text2: str) -> int: Brute force. Complexity is O(n * 2^n).
- def longestCommonSubsequence_v2(self, text1: str, text2: str) -> in... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def longestCommonSubsequence_v1(self, text1: str, text2: str) -> int:
"""Brute force. Complexity is O(n * 2^n)."""
<|body_0|>
def longestCommonSubsequence_v2(self, text1: str, text2: str) -> int:
"""Use recursion. Slow."""
<|body_1|>
def longes... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestCommonSubsequence_v1(self, text1: str, text2: str) -> int:
"""Brute force. Complexity is O(n * 2^n)."""
def get_all_seq(pre: str, text: str) -> List[str]:
if not text:
return [pre]
r = []
c = text[0]
r.extend(... | the_stack_v2_python_sparse | python3/dynamic_programming/longest_common_subsequence.py | victorchu/algorithms | train | 0 | |
0396eb41e33c45ad322772ef51a25690542c82c7 | [
"if value is not None:\n value.encode('ascii')\nreturn value",
"if isinstance(value, unicode):\n value = value.encode('ascii')\nreturn value"
] | <|body_start_0|>
if value is not None:
value.encode('ascii')
return value
<|end_body_0|>
<|body_start_1|>
if isinstance(value, unicode):
value = value.encode('ascii')
return value
<|end_body_1|>
| A database string type that only allows ASCII characters. This is a data type check since all strings in the database could be unicode. | ASCII | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ASCII:
"""A database string type that only allows ASCII characters. This is a data type check since all strings in the database could be unicode."""
def process_bind_param(self, value, dialect):
"""Run encode on a unicode string to make sure the string only contains ASCII characterse... | stack_v2_sparse_classes_75kplus_train_072638 | 4,635 | permissive | [
{
"docstring": "Run encode on a unicode string to make sure the string only contains ASCII characterset characters. To avoid another conversion pass, the original unicode value is passed to the underlying db.",
"name": "process_bind_param",
"signature": "def process_bind_param(self, value, dialect)"
}... | 2 | null | Implement the Python class `ASCII` described below.
Class description:
A database string type that only allows ASCII characters. This is a data type check since all strings in the database could be unicode.
Method signatures and docstrings:
- def process_bind_param(self, value, dialect): Run encode on a unicode strin... | Implement the Python class `ASCII` described below.
Class description:
A database string type that only allows ASCII characters. This is a data type check since all strings in the database could be unicode.
Method signatures and docstrings:
- def process_bind_param(self, value, dialect): Run encode on a unicode strin... | 4ef792b01c40b333fcbb16319f2c5ff16a30b2d9 | <|skeleton|>
class ASCII:
"""A database string type that only allows ASCII characters. This is a data type check since all strings in the database could be unicode."""
def process_bind_param(self, value, dialect):
"""Run encode on a unicode string to make sure the string only contains ASCII characterse... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ASCII:
"""A database string type that only allows ASCII characters. This is a data type check since all strings in the database could be unicode."""
def process_bind_param(self, value, dialect):
"""Run encode on a unicode string to make sure the string only contains ASCII characterset characters.... | the_stack_v2_python_sparse | pybald/db/ext.py | mikepk/pybald | train | 7 |
f1d4e8df97ee488fad685e64d09333e478b11b23 | [
"if not Settings.Notification.Telegram.token:\n raise InvalidApiSettingsException('You need an API token to use the Telegram API')\nself._token = Settings.Notification.Telegram.token\nself.api_url = 'https://api.telegram.org/bot{0:s}'.format(self._token)\nbot_profile = self.get_me()\nif not bot_profile.ok:\n ... | <|body_start_0|>
if not Settings.Notification.Telegram.token:
raise InvalidApiSettingsException('You need an API token to use the Telegram API')
self._token = Settings.Notification.Telegram.token
self.api_url = 'https://api.telegram.org/bot{0:s}'.format(self._token)
bot_profi... | Class to notify the user via telegram bot. The telegram API documentation can be found here: https://core.telegram.org/bots/api | Telegram | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Telegram:
"""Class to notify the user via telegram bot. The telegram API documentation can be found here: https://core.telegram.org/bots/api"""
def __init__(self) -> None:
"""Initializing function"""
<|body_0|>
def get_me(self) -> APIResponse:
"""getMe implementa... | stack_v2_sparse_classes_75kplus_train_072639 | 3,913 | permissive | [
{
"docstring": "Initializing function",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "getMe implementation https://core.telegram.org/bots/api#getme :return:",
"name": "get_me",
"signature": "def get_me(self) -> APIResponse"
},
{
"docstring": "ge... | 5 | stack_v2_sparse_classes_30k_test_001464 | Implement the Python class `Telegram` described below.
Class description:
Class to notify the user via telegram bot. The telegram API documentation can be found here: https://core.telegram.org/bots/api
Method signatures and docstrings:
- def __init__(self) -> None: Initializing function
- def get_me(self) -> APIRespo... | Implement the Python class `Telegram` described below.
Class description:
Class to notify the user via telegram bot. The telegram API documentation can be found here: https://core.telegram.org/bots/api
Method signatures and docstrings:
- def __init__(self) -> None: Initializing function
- def get_me(self) -> APIRespo... | 57afb861a8e59b988fa56a6d69680ba27cfed5f4 | <|skeleton|>
class Telegram:
"""Class to notify the user via telegram bot. The telegram API documentation can be found here: https://core.telegram.org/bots/api"""
def __init__(self) -> None:
"""Initializing function"""
<|body_0|>
def get_me(self) -> APIResponse:
"""getMe implementa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Telegram:
"""Class to notify the user via telegram bot. The telegram API documentation can be found here: https://core.telegram.org/bots/api"""
def __init__(self) -> None:
"""Initializing function"""
if not Settings.Notification.Telegram.token:
raise InvalidApiSettingsExceptio... | the_stack_v2_python_sparse | kuon/watcher/notifications/telegram.py | DaRealFreak/Kuon | train | 2 |
242ee2d28aa2259df3224b2c7da236e73708325b | [
"board = Board.objects.filter(user=request.user)\nserializer = self.serializer_class(board, many=True)\nreturn Response(serializer.data)",
"serializer = self.serializer_class(data=request.data)\nif serializer.is_valid():\n serializer.save(user=request.user)\n serializer.save()\n return Response(serialize... | <|body_start_0|>
board = Board.objects.filter(user=request.user)
serializer = self.serializer_class(board, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
seri... | BoardViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BoardViewSet:
def get(self, request):
"""Retrieves all the boards of the user"""
<|body_0|>
def post(self, request):
"""Add new board"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
board = Board.objects.filter(user=request.user)
serializer ... | stack_v2_sparse_classes_75kplus_train_072640 | 11,986 | no_license | [
{
"docstring": "Retrieves all the boards of the user",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Add new board",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053004 | Implement the Python class `BoardViewSet` described below.
Class description:
Implement the BoardViewSet class.
Method signatures and docstrings:
- def get(self, request): Retrieves all the boards of the user
- def post(self, request): Add new board | Implement the Python class `BoardViewSet` described below.
Class description:
Implement the BoardViewSet class.
Method signatures and docstrings:
- def get(self, request): Retrieves all the boards of the user
- def post(self, request): Add new board
<|skeleton|>
class BoardViewSet:
def get(self, request):
... | 5f108eb86f7552b505e4eedd3c6004e340c0280f | <|skeleton|>
class BoardViewSet:
def get(self, request):
"""Retrieves all the boards of the user"""
<|body_0|>
def post(self, request):
"""Add new board"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BoardViewSet:
def get(self, request):
"""Retrieves all the boards of the user"""
board = Board.objects.filter(user=request.user)
serializer = self.serializer_class(board, many=True)
return Response(serializer.data)
def post(self, request):
"""Add new board"""
... | the_stack_v2_python_sparse | trello_drf/trello_drf_app/views.py | erykestabillo/trelloAngular | train | 0 | |
f6c61c25f3ec4f454aca2419073cca7b423cc080 | [
"super(Decoder, self).__init__()\nself.embedding1 = tf.keras.layers.Embedding(vocab_size, embedding_dim)\nself.attention1 = BahdanauAttention(units)\nself.attention2 = BahdanauAttention(units)\nself.gru1 = tf.keras.layers.GRU(units, return_sequences=True, return_state=True, activation=tf.keras.activations.tanh, rec... | <|body_start_0|>
super(Decoder, self).__init__()
self.embedding1 = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.attention1 = BahdanauAttention(units)
self.attention2 = BahdanauAttention(units)
self.gru1 = tf.keras.layers.GRU(units, return_sequences=True, return_state... | 解码器 | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""解码器"""
def __init__(self, vocab_size, embedding_dim, units):
"""vocab_size:字符数 embedding_dim:字符编码特征数 units:隐藏层神经元数量"""
<|body_0|>
def call(self, input_data, gru_state1=None, gru_state2=None):
"""input_data:单步预测数据(None,1) gru_state1:上一步的状态(None,units) ... | stack_v2_sparse_classes_75kplus_train_072641 | 26,365 | no_license | [
{
"docstring": "vocab_size:字符数 embedding_dim:字符编码特征数 units:隐藏层神经元数量",
"name": "__init__",
"signature": "def __init__(self, vocab_size, embedding_dim, units)"
},
{
"docstring": "input_data:单步预测数据(None,1) gru_state1:上一步的状态(None,units) gru_state2:上一步的状态(None,units)",
"name": "call",
"signat... | 2 | stack_v2_sparse_classes_30k_train_004073 | Implement the Python class `Decoder` described below.
Class description:
解码器
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, units): vocab_size:字符数 embedding_dim:字符编码特征数 units:隐藏层神经元数量
- def call(self, input_data, gru_state1=None, gru_state2=None): input_data:单步预测数据(None,1) gru_state... | Implement the Python class `Decoder` described below.
Class description:
解码器
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, units): vocab_size:字符数 embedding_dim:字符编码特征数 units:隐藏层神经元数量
- def call(self, input_data, gru_state1=None, gru_state2=None): input_data:单步预测数据(None,1) gru_state... | c74c69556c1898d711f86422d469afe38829ebba | <|skeleton|>
class Decoder:
"""解码器"""
def __init__(self, vocab_size, embedding_dim, units):
"""vocab_size:字符数 embedding_dim:字符编码特征数 units:隐藏层神经元数量"""
<|body_0|>
def call(self, input_data, gru_state1=None, gru_state2=None):
"""input_data:单步预测数据(None,1) gru_state1:上一步的状态(None,units) ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decoder:
"""解码器"""
def __init__(self, vocab_size, embedding_dim, units):
"""vocab_size:字符数 embedding_dim:字符编码特征数 units:隐藏层神经元数量"""
super(Decoder, self).__init__()
self.embedding1 = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.attention1 = BahdanauAttention(uni... | the_stack_v2_python_sparse | RNN/robot.py | zhangliangjing/AI | train | 0 |
21a0be8d01b5e1660c2383f5990e69378432cd38 | [
"if self.all_day:\n return settings.WORKING_HOURS_PER_DAY\nelse:\n return datetime.combine(date.min, self.end_time) - datetime.combine(date.min, self.start_time)",
"timesheet_days_sum = 0\nfor tse in tses:\n date = tse.date\n if tse.all_day:\n timesheet_days_sum += 1\n else:\n timeshe... | <|body_start_0|>
if self.all_day:
return settings.WORKING_HOURS_PER_DAY
else:
return datetime.combine(date.min, self.end_time) - datetime.combine(date.min, self.start_time)
<|end_body_0|>
<|body_start_1|>
timesheet_days_sum = 0
for tse in tses:
date =... | Represents a single time sheet entry (either full day or hourly) | TimeSheetEntry | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeSheetEntry:
"""Represents a single time sheet entry (either full day or hourly)"""
def duration(self):
"""duration is is based off the global WORKING_HOURS_PER_DAY value (if all day event) or the actual hours if hourly entry"""
<|body_0|>
def working_days(tses) -> fl... | stack_v2_sparse_classes_75kplus_train_072642 | 1,754 | permissive | [
{
"docstring": "duration is is based off the global WORKING_HOURS_PER_DAY value (if all day event) or the actual hours if hourly entry",
"name": "duration",
"signature": "def duration(self)"
},
{
"docstring": "Get the working days recorded on timesheet for project for the specified time sheet en... | 2 | stack_v2_sparse_classes_30k_train_022789 | Implement the Python class `TimeSheetEntry` described below.
Class description:
Represents a single time sheet entry (either full day or hourly)
Method signatures and docstrings:
- def duration(self): duration is is based off the global WORKING_HOURS_PER_DAY value (if all day event) or the actual hours if hourly entr... | Implement the Python class `TimeSheetEntry` described below.
Class description:
Represents a single time sheet entry (either full day or hourly)
Method signatures and docstrings:
- def duration(self): duration is is based off the global WORKING_HOURS_PER_DAY value (if all day event) or the actual hours if hourly entr... | fdff8b8ddc202c53edda2a509a50c4e83013474d | <|skeleton|>
class TimeSheetEntry:
"""Represents a single time sheet entry (either full day or hourly)"""
def duration(self):
"""duration is is based off the global WORKING_HOURS_PER_DAY value (if all day event) or the actual hours if hourly entry"""
<|body_0|>
def working_days(tses) -> fl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimeSheetEntry:
"""Represents a single time sheet entry (either full day or hourly)"""
def duration(self):
"""duration is is based off the global WORKING_HOURS_PER_DAY value (if all day event) or the actual hours if hourly entry"""
if self.all_day:
return settings.WORKING_HOUR... | the_stack_v2_python_sparse | timetracking/models.py | RSE-Sheffield/RSEAdmin | train | 22 |
19d91727a7fa137a7572af4119ff6063048a20d0 | [
"self._nodes = list()\nfor node in nodes:\n if node.db.storage_type != 'T':\n log.warning(f'Ignoring non-transport node \"{node.name}\" in Transport Group \"{self.group.name}\"')\n else:\n self._nodes.append(node)\nif not len(self._nodes):\n raise ValueError(f'no usable nodes ({len(nodes)} un... | <|body_start_0|>
self._nodes = list()
for node in nodes:
if node.db.storage_type != 'T':
log.warning(f'Ignoring non-transport node "{node.name}" in Transport Group "{self.group.name}"')
else:
self._nodes.append(node)
if not len(self._nodes)... | Transport Group I/O. This implements (the formerly special-cased) transport disk logic. A Transport StorageGroup is used to transfer data onto transiting storage. Features of a Transport StorageGroup: - it may have any number of nodes. All node must have node.db.storage_type == 'T', but no restrictions are put on the i... | TransportGroupIO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransportGroupIO:
"""Transport Group I/O. This implements (the formerly special-cased) transport disk logic. A Transport StorageGroup is used to transfer data onto transiting storage. Features of a Transport StorageGroup: - it may have any number of nodes. All node must have node.db.storage_type ... | stack_v2_sparse_classes_75kplus_train_072643 | 5,479 | permissive | [
{
"docstring": "Check that nodes in group are transit nodes. Parameters ---------- nodes : list of UpdateableNodes local active nodes in this group Returns ------- nodes : list of UpdateableNodes subset of `nodes` which are Transport nodes. Raises ------ ValueError none of the supplied `nodes` were Transport no... | 3 | stack_v2_sparse_classes_30k_train_034100 | Implement the Python class `TransportGroupIO` described below.
Class description:
Transport Group I/O. This implements (the formerly special-cased) transport disk logic. A Transport StorageGroup is used to transfer data onto transiting storage. Features of a Transport StorageGroup: - it may have any number of nodes. A... | Implement the Python class `TransportGroupIO` described below.
Class description:
Transport Group I/O. This implements (the formerly special-cased) transport disk logic. A Transport StorageGroup is used to transfer data onto transiting storage. Features of a Transport StorageGroup: - it may have any number of nodes. A... | 7067844d144ab5e2bba6d63b5f627c25edf73618 | <|skeleton|>
class TransportGroupIO:
"""Transport Group I/O. This implements (the formerly special-cased) transport disk logic. A Transport StorageGroup is used to transfer data onto transiting storage. Features of a Transport StorageGroup: - it may have any number of nodes. All node must have node.db.storage_type ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransportGroupIO:
"""Transport Group I/O. This implements (the formerly special-cased) transport disk logic. A Transport StorageGroup is used to transfer data onto transiting storage. Features of a Transport StorageGroup: - it may have any number of nodes. All node must have node.db.storage_type == 'T', but n... | the_stack_v2_python_sparse | alpenhorn/io/transport.py | radiocosmology/alpenhorn | train | 3 |
c18d24e960ec4aab1974d6d14db3b08e5e0eb2fc | [
"self.sc = sc\nself.gradient = gradient\nif not f_diff:\n f_diff = np.ones(self.sc.shape[0]) * 0.05\nif isinstance(self.sc, list):\n if not isinstance(gradient, list):\n self.gradient = [self.gradient, self.gradient]\n self.hopf = [HopfModel(self.sc[ii], *args, f_diff=f_diff, hmap=self.gradient[ii],... | <|body_start_0|>
self.sc = sc
self.gradient = gradient
if not f_diff:
f_diff = np.ones(self.sc.shape[0]) * 0.05
if isinstance(self.sc, list):
if not isinstance(gradient, list):
self.gradient = [self.gradient, self.gradient]
self.hopf = ... | Wrapper class for Hopf model. | Hopf | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hopf:
"""Wrapper class for Hopf model."""
def __init__(self, sc, f_diff=None, gradient=None, *args, **kwargs):
"""Parameters ---------- sc : ndarray Structural connectivity matrix gradient : ndarray, optional Heterogeneity map to scale local model parameters. If None, the model param... | stack_v2_sparse_classes_75kplus_train_072644 | 3,717 | no_license | [
{
"docstring": "Parameters ---------- sc : ndarray Structural connectivity matrix gradient : ndarray, optional Heterogeneity map to scale local model parameters. If None, the model parameters are homogeneous (None by default) Notes ----- The optional arguments and keyword arguments pass to the Model class. If t... | 5 | stack_v2_sparse_classes_30k_train_039169 | Implement the Python class `Hopf` described below.
Class description:
Wrapper class for Hopf model.
Method signatures and docstrings:
- def __init__(self, sc, f_diff=None, gradient=None, *args, **kwargs): Parameters ---------- sc : ndarray Structural connectivity matrix gradient : ndarray, optional Heterogeneity map ... | Implement the Python class `Hopf` described below.
Class description:
Wrapper class for Hopf model.
Method signatures and docstrings:
- def __init__(self, sc, f_diff=None, gradient=None, *args, **kwargs): Parameters ---------- sc : ndarray Structural connectivity matrix gradient : ndarray, optional Heterogeneity map ... | 7aa2d0296673cf4a3df96fb01cc34712671b109c | <|skeleton|>
class Hopf:
"""Wrapper class for Hopf model."""
def __init__(self, sc, f_diff=None, gradient=None, *args, **kwargs):
"""Parameters ---------- sc : ndarray Structural connectivity matrix gradient : ndarray, optional Heterogeneity map to scale local model parameters. If None, the model param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Hopf:
"""Wrapper class for Hopf model."""
def __init__(self, sc, f_diff=None, gradient=None, *args, **kwargs):
"""Parameters ---------- sc : ndarray Structural connectivity matrix gradient : ndarray, optional Heterogeneity map to scale local model parameters. If None, the model parameters are hom... | the_stack_v2_python_sparse | lib/models/hopf/model_wrapper.py | murat-demirtas/pylib | train | 2 |
e20542066f1cec20b140415aafafbec126141511 | [
"os.environ['FUNC_DIR'] = ('/'.join(Path(file_path).parts[:-1]) if len(Path(file_path).parts) > 1 else '.') + '/'\nos.environ['FILE_PATH'] = file_path\nfailed = cls.launch_cmd(config.tiramisu.compile_tiramisu_cmd, file_path)\nif failed:\n print(f'Error occured while compiling {file_path}')\n with open(file_pa... | <|body_start_0|>
os.environ['FUNC_DIR'] = ('/'.join(Path(file_path).parts[:-1]) if len(Path(file_path).parts) > 1 else '.') + '/'
os.environ['FILE_PATH'] = file_path
failed = cls.launch_cmd(config.tiramisu.compile_tiramisu_cmd, file_path)
if failed:
print(f'Error occured whil... | CPP_File | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CPP_File:
def compile_and_run_tiramisu_code(cls, config, file_path, log_message='No message'):
"""Compiles and runs a C++ file. Args: config (RLAutoSchedulerConfig): The experiment config. file_path (str): The path to the C++ file to compile. log_message (str, optional): _description_. D... | stack_v2_sparse_classes_75kplus_train_072645 | 6,597 | permissive | [
{
"docstring": "Compiles and runs a C++ file. Args: config (RLAutoSchedulerConfig): The experiment config. file_path (str): The path to the C++ file to compile. log_message (str, optional): _description_. Defaults to \"No message\". Returns: bool: Whether or not the compilation and running was successful.",
... | 4 | stack_v2_sparse_classes_30k_train_006416 | Implement the Python class `CPP_File` described below.
Class description:
Implement the CPP_File class.
Method signatures and docstrings:
- def compile_and_run_tiramisu_code(cls, config, file_path, log_message='No message'): Compiles and runs a C++ file. Args: config (RLAutoSchedulerConfig): The experiment config. fi... | Implement the Python class `CPP_File` described below.
Class description:
Implement the CPP_File class.
Method signatures and docstrings:
- def compile_and_run_tiramisu_code(cls, config, file_path, log_message='No message'): Compiles and runs a C++ file. Args: config (RLAutoSchedulerConfig): The experiment config. fi... | f13e480f0ddb142cec371b7d7431a41d8ca885ec | <|skeleton|>
class CPP_File:
def compile_and_run_tiramisu_code(cls, config, file_path, log_message='No message'):
"""Compiles and runs a C++ file. Args: config (RLAutoSchedulerConfig): The experiment config. file_path (str): The path to the C++ file to compile. log_message (str, optional): _description_. D... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CPP_File:
def compile_and_run_tiramisu_code(cls, config, file_path, log_message='No message'):
"""Compiles and runs a C++ file. Args: config (RLAutoSchedulerConfig): The experiment config. file_path (str): The path to the C++ file to compile. log_message (str, optional): _description_. Defaults to "No... | the_stack_v2_python_sparse | utils/rl_autoscheduler/tiramisu_programs/cpp_file.py | Tiramisu-Compiler/tiramisu | train | 906 | |
13292938663e801400a354e8be0e660934078959 | [
"if toEncrypt.strip() == '':\n return ''\nkey = '12345678901234567890123456789012'.encode()\nBS = AES.block_size\npad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)\nx = pad(toEncrypt)\nx = x.encode()\ncipher = AES.new(key, AES.MODE_ECB)\nencrypted = cipher.encrypt(x)\nresult = base64.b64encode(encry... | <|body_start_0|>
if toEncrypt.strip() == '':
return ''
key = '12345678901234567890123456789012'.encode()
BS = AES.block_size
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
x = pad(toEncrypt)
x = x.encode()
cipher = AES.new(key, AES.MODE... | SecretHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecretHelper:
def AESEncrypt(toEncrypt):
"""256位AES加密 Args: toEncrypt (string): 待加密文本 Returns: returnValue(string): 加密后文本"""
<|body_0|>
def AESDecrypt(toDecrypt):
"""256位AES解密 Args: toDecrypt (string): 待解密文本 Returns: returnValue(string): 解密后的文本"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_072646 | 1,765 | no_license | [
{
"docstring": "256位AES加密 Args: toEncrypt (string): 待加密文本 Returns: returnValue(string): 加密后文本",
"name": "AESEncrypt",
"signature": "def AESEncrypt(toEncrypt)"
},
{
"docstring": "256位AES解密 Args: toDecrypt (string): 待解密文本 Returns: returnValue(string): 解密后的文本",
"name": "AESDecrypt",
"signat... | 2 | null | Implement the Python class `SecretHelper` described below.
Class description:
Implement the SecretHelper class.
Method signatures and docstrings:
- def AESEncrypt(toEncrypt): 256位AES加密 Args: toEncrypt (string): 待加密文本 Returns: returnValue(string): 加密后文本
- def AESDecrypt(toDecrypt): 256位AES解密 Args: toDecrypt (string): ... | Implement the Python class `SecretHelper` described below.
Class description:
Implement the SecretHelper class.
Method signatures and docstrings:
- def AESEncrypt(toEncrypt): 256位AES加密 Args: toEncrypt (string): 待加密文本 Returns: returnValue(string): 加密后文本
- def AESDecrypt(toDecrypt): 256位AES解密 Args: toDecrypt (string): ... | 24689b359ee225c8678b33766e51a045fa5d50c9 | <|skeleton|>
class SecretHelper:
def AESEncrypt(toEncrypt):
"""256位AES加密 Args: toEncrypt (string): 待加密文本 Returns: returnValue(string): 加密后文本"""
<|body_0|>
def AESDecrypt(toDecrypt):
"""256位AES解密 Args: toDecrypt (string): 待解密文本 Returns: returnValue(string): 解密后的文本"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SecretHelper:
def AESEncrypt(toEncrypt):
"""256位AES加密 Args: toEncrypt (string): 待加密文本 Returns: returnValue(string): 加密后文本"""
if toEncrypt.strip() == '':
return ''
key = '12345678901234567890123456789012'.encode()
BS = AES.block_size
pad = lambda s: s + (BS -... | the_stack_v2_python_sparse | apps/utilities/publiclibrary/SecretHelper.py | seesky/hpwf | train | 32 | |
f463be88b853bbd18d79428e0b26cc2b489eba14 | [
"self.k = k\nself.arr = nums\nself.arr.sort()\nwhile len(self.arr) > self.k:\n self.arr.pop(0)",
"self.arr.append(val)\nself.arr.sort()\nif len(self.arr) > self.k:\n self.arr.pop(0)\nreturn self.arr[0]"
] | <|body_start_0|>
self.k = k
self.arr = nums
self.arr.sort()
while len(self.arr) > self.k:
self.arr.pop(0)
<|end_body_0|>
<|body_start_1|>
self.arr.append(val)
self.arr.sort()
if len(self.arr) > self.k:
self.arr.pop(0)
return self.a... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.arr = nums
self.arr.sort()... | stack_v2_sparse_classes_75kplus_train_072647 | 630 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051936 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 920b65db80031fad45d495431eda8d3fb4ef06e5 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.arr = nums
self.arr.sort()
while len(self.arr) > self.k:
self.arr.pop(0)
def add(self, val):
""":type val: int :rtype: int"""
self.arr.appe... | the_stack_v2_python_sparse | easy/ex703.py | ziyuan-shen/leetcode_algorithm_python_solution | train | 2 | |
324e1a42a6225dc1aea167ed2f1587d406ffaf2e | [
"try:\n cls.engine = create_engine(f'mysql+pymysql://{CfgReader.DATABASE_USER}:{CfgReader.DATABASE_PASSWORD}@{CfgReader.DATABASE_HOST_URL}/{CfgReader.DATABASE_NAME}')\n cls.session_maker = sessionmaker(bind=cls.engine, expire_on_commit=False)\n cls.is_connected = True\nexcept Exception as ex:\n cls.is_c... | <|body_start_0|>
try:
cls.engine = create_engine(f'mysql+pymysql://{CfgReader.DATABASE_USER}:{CfgReader.DATABASE_PASSWORD}@{CfgReader.DATABASE_HOST_URL}/{CfgReader.DATABASE_NAME}')
cls.session_maker = sessionmaker(bind=cls.engine, expire_on_commit=False)
cls.is_connected = Tr... | Database | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Database:
def create_connection(cls):
"""create database connection and session_maker and base. If any problem happens in database connection set is_connected variable to False"""
<|body_0|>
def create_session(cls) -> sqlalchemy.orm.session.Session:
"""create a new d... | stack_v2_sparse_classes_75kplus_train_072648 | 1,758 | no_license | [
{
"docstring": "create database connection and session_maker and base. If any problem happens in database connection set is_connected variable to False",
"name": "create_connection",
"signature": "def create_connection(cls)"
},
{
"docstring": "create a new database session :return: return a new ... | 2 | stack_v2_sparse_classes_30k_train_046627 | Implement the Python class `Database` described below.
Class description:
Implement the Database class.
Method signatures and docstrings:
- def create_connection(cls): create database connection and session_maker and base. If any problem happens in database connection set is_connected variable to False
- def create_s... | Implement the Python class `Database` described below.
Class description:
Implement the Database class.
Method signatures and docstrings:
- def create_connection(cls): create database connection and session_maker and base. If any problem happens in database connection set is_connected variable to False
- def create_s... | ad06da559c673157ea1d20730eb1ea8320a87dd0 | <|skeleton|>
class Database:
def create_connection(cls):
"""create database connection and session_maker and base. If any problem happens in database connection set is_connected variable to False"""
<|body_0|>
def create_session(cls) -> sqlalchemy.orm.session.Session:
"""create a new d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Database:
def create_connection(cls):
"""create database connection and session_maker and base. If any problem happens in database connection set is_connected variable to False"""
try:
cls.engine = create_engine(f'mysql+pymysql://{CfgReader.DATABASE_USER}:{CfgReader.DATABASE_PASSWO... | the_stack_v2_python_sparse | stacking_layers_machine/src/libs/database/database.py | hugobranco/koerber | train | 0 | |
3452e571594f7b69ab6b13cd39f4d0b8da463814 | [
"@lru_cache(None)\ndef dp(i):\n if i == len(s):\n return 1\n if s[i] == '0':\n return 0\n ans = dp(i + 1)\n if i + 1 < len(s) and int(s[i:i + 2]) < 27:\n ans += dp(i + 2)\n return ans\nreturn dp(0)",
"valid_two = {str(x) for x in range(10, 27)}\n\n@cache\ndef dp(s: str) -> int:... | <|body_start_0|>
@lru_cache(None)
def dp(i):
if i == len(s):
return 1
if s[i] == '0':
return 0
ans = dp(i + 1)
if i + 1 < len(s) and int(s[i:i + 2]) < 27:
ans += dp(i + 2)
return ans
retur... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numDecodings(self, s: str) -> int:
"""2021/8/18 269 / 269 test cases passed. Status: Accepted Runtime: 36 ms Memory Usage: 14.6 MB :param s: :return:"""
<|body_0|>
def numDecodings2(self, s: str) -> int:
"""2022-10-01 Runtime: 37 ms, faster than 87.73% ... | stack_v2_sparse_classes_75kplus_train_072649 | 2,017 | permissive | [
{
"docstring": "2021/8/18 269 / 269 test cases passed. Status: Accepted Runtime: 36 ms Memory Usage: 14.6 MB :param s: :return:",
"name": "numDecodings",
"signature": "def numDecodings(self, s: str) -> int"
},
{
"docstring": "2022-10-01 Runtime: 37 ms, faster than 87.73% Memory Usage: 14.5 MB, l... | 2 | stack_v2_sparse_classes_30k_train_032534 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDecodings(self, s: str) -> int: 2021/8/18 269 / 269 test cases passed. Status: Accepted Runtime: 36 ms Memory Usage: 14.6 MB :param s: :return:
- def numDecodings2(self, s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDecodings(self, s: str) -> int: 2021/8/18 269 / 269 test cases passed. Status: Accepted Runtime: 36 ms Memory Usage: 14.6 MB :param s: :return:
- def numDecodings2(self, s... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def numDecodings(self, s: str) -> int:
"""2021/8/18 269 / 269 test cases passed. Status: Accepted Runtime: 36 ms Memory Usage: 14.6 MB :param s: :return:"""
<|body_0|>
def numDecodings2(self, s: str) -> int:
"""2022-10-01 Runtime: 37 ms, faster than 87.73% ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numDecodings(self, s: str) -> int:
"""2021/8/18 269 / 269 test cases passed. Status: Accepted Runtime: 36 ms Memory Usage: 14.6 MB :param s: :return:"""
@lru_cache(None)
def dp(i):
if i == len(s):
return 1
if s[i] == '0':
... | the_stack_v2_python_sparse | src/91-DecodeWays.py | Jiezhi/myleetcode | train | 1 | |
152c5455d024c2b2844df6b01b9907e06adfcd4b | [
"curr1, curr2 = (head1, head2)\nexit1, exit2 = (False, False)\nwhile curr1 != curr2:\n if curr1 is not None:\n curr1 = curr1.next\n elif not exit1:\n exit1 = True\n curr1 = head2\n else:\n return\n if curr2 is not None:\n curr2 = curr2.next\n elif not exit2:\n ... | <|body_start_0|>
curr1, curr2 = (head1, head2)
exit1, exit2 = (False, False)
while curr1 != curr2:
if curr1 is not None:
curr1 = curr1.next
elif not exit1:
exit1 = True
curr1 = head2
else:
return
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_intersection_node(self, head1, head2):
"""Returns a node where list 1 connects with list 2 if there's one, returns None otherwise. Time complexity: O(n + m). Space complexity: O(1), where n, m are lengths of linked lists."""
<|body_0|>
def get_intersection_... | stack_v2_sparse_classes_75kplus_train_072650 | 2,029 | no_license | [
{
"docstring": "Returns a node where list 1 connects with list 2 if there's one, returns None otherwise. Time complexity: O(n + m). Space complexity: O(1), where n, m are lengths of linked lists.",
"name": "get_intersection_node",
"signature": "def get_intersection_node(self, head1, head2)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_011955 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_intersection_node(self, head1, head2): Returns a node where list 1 connects with list 2 if there's one, returns None otherwise. Time complexity: O(n + m). Space complexit... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_intersection_node(self, head1, head2): Returns a node where list 1 connects with list 2 if there's one, returns None otherwise. Time complexity: O(n + m). Space complexit... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def get_intersection_node(self, head1, head2):
"""Returns a node where list 1 connects with list 2 if there's one, returns None otherwise. Time complexity: O(n + m). Space complexity: O(1), where n, m are lengths of linked lists."""
<|body_0|>
def get_intersection_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def get_intersection_node(self, head1, head2):
"""Returns a node where list 1 connects with list 2 if there's one, returns None otherwise. Time complexity: O(n + m). Space complexity: O(1), where n, m are lengths of linked lists."""
curr1, curr2 = (head1, head2)
exit1, exit2 ... | the_stack_v2_python_sparse | Linked_Lists/intersection_linked_lists.py | vladn90/Algorithms | train | 0 | |
caea4fe7c3a377758ef7c71f4b045506de29a190 | [
"super(LabelsCheckbox, self).__init__(parent)\nself.check_box_widgets = []\nself.last_state = []\nself.initialize_widget(labels)",
"group = QGroupBox('Labels shown')\nmain_layout = QVBoxLayout()\nlayout = QVBoxLayout()\nfor label in labels:\n box = QCheckBox(label)\n box.setChecked(True)\n layout.addWidg... | <|body_start_0|>
super(LabelsCheckbox, self).__init__(parent)
self.check_box_widgets = []
self.last_state = []
self.initialize_widget(labels)
<|end_body_0|>
<|body_start_1|>
group = QGroupBox('Labels shown')
main_layout = QVBoxLayout()
layout = QVBoxLayout()
... | Check that handles a group of check boxes that decides which labels will be shown. When a checkbox state is changed, a signal is emitted with the active labels at that moment. | LabelsCheckbox | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelsCheckbox:
"""Check that handles a group of check boxes that decides which labels will be shown. When a checkbox state is changed, a signal is emitted with the active labels at that moment."""
def __init__(self, labels, parent=None):
"""Constructor Args: labels: List with the la... | stack_v2_sparse_classes_75kplus_train_072651 | 2,192 | no_license | [
{
"docstring": "Constructor Args: labels: List with the labels names. The position of each label should match with the label id in the mask.",
"name": "__init__",
"signature": "def __init__(self, labels, parent=None)"
},
{
"docstring": "Initialize the widget configuration Args: labels: List with... | 3 | stack_v2_sparse_classes_30k_train_019441 | Implement the Python class `LabelsCheckbox` described below.
Class description:
Check that handles a group of check boxes that decides which labels will be shown. When a checkbox state is changed, a signal is emitted with the active labels at that moment.
Method signatures and docstrings:
- def __init__(self, labels,... | Implement the Python class `LabelsCheckbox` described below.
Class description:
Check that handles a group of check boxes that decides which labels will be shown. When a checkbox state is changed, a signal is emitted with the active labels at that moment.
Method signatures and docstrings:
- def __init__(self, labels,... | 4761f346cb4ff29724f70519da252f1d627a59ff | <|skeleton|>
class LabelsCheckbox:
"""Check that handles a group of check boxes that decides which labels will be shown. When a checkbox state is changed, a signal is emitted with the active labels at that moment."""
def __init__(self, labels, parent=None):
"""Constructor Args: labels: List with the la... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LabelsCheckbox:
"""Check that handles a group of check boxes that decides which labels will be shown. When a checkbox state is changed, a signal is emitted with the active labels at that moment."""
def __init__(self, labels, parent=None):
"""Constructor Args: labels: List with the labels names. T... | the_stack_v2_python_sparse | Adeyemi_Abdulnafiu__Khawaja_Arsalan__Rodriguez_Joaquin_SSI_Project_CODE/scene-segmentation-project/labels_checkbox/labels_checkbox.py | RespectKnowledge/COVID_19-Segmentation_Models | train | 3 |
848f62c95358f83f4a826860fb7bc1f0fa2995e1 | [
"context = aq_inner(self.context)\nksscore = self.getCommandSet('core')\nutility = zapi.getUtility(ICountriesStates)\nif not search and (not country):\n country = context.getCountry()\nif country and country != '--':\n results = TitledVocabulary.fromTitles(utility.states(country=country))\nelse:\n results ... | <|body_start_0|>
context = aq_inner(self.context)
ksscore = self.getCommandSet('core')
utility = zapi.getUtility(ICountriesStates)
if not search and (not country):
country = context.getCountry()
if country and country != '--':
results = TitledVocabulary.fr... | KSSModifySelector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KSSModifySelector:
def kssModifyState(self, country=None, search=0):
"""This method is used to update the province drop down when adding a person or organization and also from the advanced search template that's why it has some ugly logic. Perhaps should be divided in two methods, one th... | stack_v2_sparse_classes_75kplus_train_072652 | 5,306 | no_license | [
{
"docstring": "This method is used to update the province drop down when adding a person or organization and also from the advanced search template that's why it has some ugly logic. Perhaps should be divided in two methods, one that gets called from the ct, and another one that gets called from the search tem... | 2 | stack_v2_sparse_classes_30k_train_042964 | Implement the Python class `KSSModifySelector` described below.
Class description:
Implement the KSSModifySelector class.
Method signatures and docstrings:
- def kssModifyState(self, country=None, search=0): This method is used to update the province drop down when adding a person or organization and also from the ad... | Implement the Python class `KSSModifySelector` described below.
Class description:
Implement the KSSModifySelector class.
Method signatures and docstrings:
- def kssModifyState(self, country=None, search=0): This method is used to update the province drop down when adding a person or organization and also from the ad... | 65e9035903d11f3da53faf22f66ee6080abf3ea1 | <|skeleton|>
class KSSModifySelector:
def kssModifyState(self, country=None, search=0):
"""This method is used to update the province drop down when adding a person or organization and also from the advanced search template that's why it has some ugly logic. Perhaps should be divided in two methods, one th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KSSModifySelector:
def kssModifyState(self, country=None, search=0):
"""This method is used to update the province drop down when adding a person or organization and also from the advanced search template that's why it has some ugly logic. Perhaps should be divided in two methods, one that gets called... | the_stack_v2_python_sparse | collective/contacts/browser/ksscommands.py | collective/collective.contacts | train | 0 | |
76f6f75c328f3ee7352ec46b4284f21feff38594 | [
"self.contents = contents\nself.left_child = left_child\nself.right_child = right_child\nself.parent = parent\nself.balance_factor = 0",
"if self.left_child:\n for yieldval in self.left_child.in_order():\n yield yieldval\nyield self.contents\nif self.right_child:\n for yieldval in self.right_child.in... | <|body_start_0|>
self.contents = contents
self.left_child = left_child
self.right_child = right_child
self.parent = parent
self.balance_factor = 0
<|end_body_0|>
<|body_start_1|>
if self.left_child:
for yieldval in self.left_child.in_order():
... | Class representation of bst node. Methods: in_order(): In Order method for Node class. Return the values in order from smallest to largest. pre_order(): Pre_order method for Node class. Return a generator that will return the values in the tree using pre-order traversal, one at a time. post_order(): Post_order method f... | Node | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
"""Class representation of bst node. Methods: in_order(): In Order method for Node class. Return the values in order from smallest to largest. pre_order(): Pre_order method for Node class. Return a generator that will return the values in the tree using pre-order traversal, one at a time. p... | stack_v2_sparse_classes_75kplus_train_072653 | 15,031 | permissive | [
{
"docstring": "Instantiate linked list node.",
"name": "__init__",
"signature": "def __init__(self, contents, left_child=None, right_child=None, parent=None)"
},
{
"docstring": "In order method for Node object.",
"name": "in_order",
"signature": "def in_order(self)"
},
{
"docstr... | 4 | null | Implement the Python class `Node` described below.
Class description:
Class representation of bst node. Methods: in_order(): In Order method for Node class. Return the values in order from smallest to largest. pre_order(): Pre_order method for Node class. Return a generator that will return the values in the tree usin... | Implement the Python class `Node` described below.
Class description:
Class representation of bst node. Methods: in_order(): In Order method for Node class. Return the values in order from smallest to largest. pre_order(): Pre_order method for Node class. Return a generator that will return the values in the tree usin... | 8ffcb60b54f999c286631061e669e9158a038d2e | <|skeleton|>
class Node:
"""Class representation of bst node. Methods: in_order(): In Order method for Node class. Return the values in order from smallest to largest. pre_order(): Pre_order method for Node class. Return a generator that will return the values in the tree using pre-order traversal, one at a time. p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Node:
"""Class representation of bst node. Methods: in_order(): In Order method for Node class. Return the values in order from smallest to largest. pre_order(): Pre_order method for Node class. Return a generator that will return the values in the tree using pre-order traversal, one at a time. post_order(): ... | the_stack_v2_python_sparse | src/bst.py | JSchatzman/data_structures | train | 0 |
1ff9e23224657f47a46d9c937cc14f53cf30ac26 | [
"res = 0\nfor i in range(len(heights)):\n mh = heights[i]\n res = max(res, heights[i])\n for j in range(i + 1, len(heights)):\n mh = min(mh, heights[j])\n res = max(res, mh * (j - i + 1))\nreturn res",
"def dfs(l, r):\n if l > r:\n return 0\n if l == r:\n return heights[... | <|body_start_0|>
res = 0
for i in range(len(heights)):
mh = heights[i]
res = max(res, heights[i])
for j in range(i + 1, len(heights)):
mh = min(mh, heights[j])
res = max(res, mh * (j - i + 1))
return res
<|end_body_0|>
<|body_s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largest_rectangle_in_histogram(self, heights: List[int]) -> int:
"""Bruteforce T: O(N2) S: O(1)"""
<|body_0|>
def largest_rectangle_in_histogram(self, heights: List[int]) -> int:
"""Divide and conquer T: O(NlogN) average case, O(N2) worst case (sorted) ... | stack_v2_sparse_classes_75kplus_train_072654 | 2,351 | no_license | [
{
"docstring": "Bruteforce T: O(N2) S: O(1)",
"name": "largest_rectangle_in_histogram",
"signature": "def largest_rectangle_in_histogram(self, heights: List[int]) -> int"
},
{
"docstring": "Divide and conquer T: O(NlogN) average case, O(N2) worst case (sorted) S: O(N) stack space",
"name": "... | 3 | stack_v2_sparse_classes_30k_train_005286 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largest_rectangle_in_histogram(self, heights: List[int]) -> int: Bruteforce T: O(N2) S: O(1)
- def largest_rectangle_in_histogram(self, heights: List[int]) -> int: Divide and... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largest_rectangle_in_histogram(self, heights: List[int]) -> int: Bruteforce T: O(N2) S: O(1)
- def largest_rectangle_in_histogram(self, heights: List[int]) -> int: Divide and... | 9882fdc58a24d852ebf9ee85bc10883454bd76a7 | <|skeleton|>
class Solution:
def largest_rectangle_in_histogram(self, heights: List[int]) -> int:
"""Bruteforce T: O(N2) S: O(1)"""
<|body_0|>
def largest_rectangle_in_histogram(self, heights: List[int]) -> int:
"""Divide and conquer T: O(NlogN) average case, O(N2) worst case (sorted) ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def largest_rectangle_in_histogram(self, heights: List[int]) -> int:
"""Bruteforce T: O(N2) S: O(1)"""
res = 0
for i in range(len(heights)):
mh = heights[i]
res = max(res, heights[i])
for j in range(i + 1, len(heights)):
mh ... | the_stack_v2_python_sparse | python/dp/optimization/largest_rectangle_in_histogram.py | pondycrane/algorithms | train | 0 | |
a982cbd211dae5a7d528a9748bebafcaeaa9e6a1 | [
"self.debug = debug\nself.rs_pin = rs_pin\nself.en_pin = en_pin\nself.pins = pins\nGPIO.setmode(GPIO.BCM)\nif not self.debug:\n GPIO.setwarnings(False)\nGPIO.setup(self.en_pin, GPIO.OUT)\nGPIO.setup(self.rs_pin, GPIO.OUT)\nfor pin in self.pins:\n GPIO.setup(pin, GPIO.OUT)\nHD44780.__init__(self, debug=self.de... | <|body_start_0|>
self.debug = debug
self.rs_pin = rs_pin
self.en_pin = en_pin
self.pins = pins
GPIO.setmode(GPIO.BCM)
if not self.debug:
GPIO.setwarnings(False)
GPIO.setup(self.en_pin, GPIO.OUT)
GPIO.setup(self.rs_pin, GPIO.OUT)
for pin... | Driver for using HD44780 displays connected to Raspberry Pi GPIO. Presumes the R/W line is tied to ground. Also, doesn't yet control backlight. | Screen | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Screen:
"""Driver for using HD44780 displays connected to Raspberry Pi GPIO. Presumes the R/W line is tied to ground. Also, doesn't yet control backlight."""
def __init__(self, pins=[], rs_pin=None, en_pin=None, debug=False, **kwargs):
"""Initializes the GPIO-driven HD44780 display A... | stack_v2_sparse_classes_75kplus_train_072655 | 3,397 | permissive | [
{
"docstring": "Initializes the GPIO-driven HD44780 display All GPIOs passed as arguments will be used with BCM mapping. Kwargs: * ``pins``: list of GPIO pins for driving display data bits in format [DB4, DB5, DB6, DB7] * ``en_pin``: EN pin GPIO number. Please, make sure it's pulled down to GND (10K is OK). Oth... | 3 | stack_v2_sparse_classes_30k_train_039874 | Implement the Python class `Screen` described below.
Class description:
Driver for using HD44780 displays connected to Raspberry Pi GPIO. Presumes the R/W line is tied to ground. Also, doesn't yet control backlight.
Method signatures and docstrings:
- def __init__(self, pins=[], rs_pin=None, en_pin=None, debug=False,... | Implement the Python class `Screen` described below.
Class description:
Driver for using HD44780 displays connected to Raspberry Pi GPIO. Presumes the R/W line is tied to ground. Also, doesn't yet control backlight.
Method signatures and docstrings:
- def __init__(self, pins=[], rs_pin=None, en_pin=None, debug=False,... | 47f24116ebe3d9f7336431c20bde880d2e86793e | <|skeleton|>
class Screen:
"""Driver for using HD44780 displays connected to Raspberry Pi GPIO. Presumes the R/W line is tied to ground. Also, doesn't yet control backlight."""
def __init__(self, pins=[], rs_pin=None, en_pin=None, debug=False, **kwargs):
"""Initializes the GPIO-driven HD44780 display A... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Screen:
"""Driver for using HD44780 displays connected to Raspberry Pi GPIO. Presumes the R/W line is tied to ground. Also, doesn't yet control backlight."""
def __init__(self, pins=[], rs_pin=None, en_pin=None, debug=False, **kwargs):
"""Initializes the GPIO-driven HD44780 display All GPIOs pass... | the_stack_v2_python_sparse | output/drivers/pi_gpio.py | samkaufman01/pyLCI | train | 1 |
367c6b7691400f21c9726c2d449c3be198ba40a4 | [
"params = request.body\njsonParams = json.loads(params)\nuser = User_Info.objects.filter(email__exact=jsonParams.get('email'))\nif user.exists():\n return JsonResponse({'status': False, 'err': '邮箱已经被注册'}, status=401)\nuser = User_Info.objects.filter(nickname__exact=jsonParams.get('nickname'))\nif user.exists():\... | <|body_start_0|>
params = request.body
jsonParams = json.loads(params)
user = User_Info.objects.filter(email__exact=jsonParams.get('email'))
if user.exists():
return JsonResponse({'status': False, 'err': '邮箱已经被注册'}, status=401)
user = User_Info.objects.filter(nickname... | RegisterView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterView:
def post(self, request):
"""注册账户"""
<|body_0|>
def randomID(self):
"""生成随机不重复的id :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
params = request.body
jsonParams = json.loads(params)
user = User_Info.objects.fi... | stack_v2_sparse_classes_75kplus_train_072656 | 2,017 | no_license | [
{
"docstring": "注册账户",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "生成随机不重复的id :return:",
"name": "randomID",
"signature": "def randomID(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020658 | Implement the Python class `RegisterView` described below.
Class description:
Implement the RegisterView class.
Method signatures and docstrings:
- def post(self, request): 注册账户
- def randomID(self): 生成随机不重复的id :return: | Implement the Python class `RegisterView` described below.
Class description:
Implement the RegisterView class.
Method signatures and docstrings:
- def post(self, request): 注册账户
- def randomID(self): 生成随机不重复的id :return:
<|skeleton|>
class RegisterView:
def post(self, request):
"""注册账户"""
<|body_... | 526dea540048fc92260bce611c520c50af744e0b | <|skeleton|>
class RegisterView:
def post(self, request):
"""注册账户"""
<|body_0|>
def randomID(self):
"""生成随机不重复的id :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegisterView:
def post(self, request):
"""注册账户"""
params = request.body
jsonParams = json.loads(params)
user = User_Info.objects.filter(email__exact=jsonParams.get('email'))
if user.exists():
return JsonResponse({'status': False, 'err': '邮箱已经被注册'}, status=40... | the_stack_v2_python_sparse | apps/account/views/bashInfo/register.py | DICKQI/ALGYunXS | train | 0 | |
2c5e330b2645a65a1cbc88f56936ce3988a5a872 | [
"try:\n foi = FeaturesofInterest.filter_by_id(foi_id)\nexcept Exception as e:\n logging.warning(e)\n result = {'message': 'error'}\n response = jsonify(result)\n response.status_code = 400\n return response\nif foi:\n response = jsonify(foi)\n response.status_code = 200\n return response\... | <|body_start_0|>
try:
foi = FeaturesofInterest.filter_by_id(foi_id)
except Exception as e:
logging.warning(e)
result = {'message': 'error'}
response = jsonify(result)
response.status_code = 400
return response
if foi:
... | FoI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FoI:
def get(self, foi_id):
"""query data streams #TODO pagination"""
<|body_0|>
def patch(self, foi_id):
"""update existing feature fo interest"""
<|body_1|>
def delete(self, foi_id):
"""delete foi"""
<|body_2|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_072657 | 5,633 | no_license | [
{
"docstring": "query data streams #TODO pagination",
"name": "get",
"signature": "def get(self, foi_id)"
},
{
"docstring": "update existing feature fo interest",
"name": "patch",
"signature": "def patch(self, foi_id)"
},
{
"docstring": "delete foi",
"name": "delete",
"si... | 3 | stack_v2_sparse_classes_30k_train_011851 | Implement the Python class `FoI` described below.
Class description:
Implement the FoI class.
Method signatures and docstrings:
- def get(self, foi_id): query data streams #TODO pagination
- def patch(self, foi_id): update existing feature fo interest
- def delete(self, foi_id): delete foi | Implement the Python class `FoI` described below.
Class description:
Implement the FoI class.
Method signatures and docstrings:
- def get(self, foi_id): query data streams #TODO pagination
- def patch(self, foi_id): update existing feature fo interest
- def delete(self, foi_id): delete foi
<|skeleton|>
class FoI:
... | 711ae2c664b3c2b3dfa3c42a2f5fb1def1fbb6fa | <|skeleton|>
class FoI:
def get(self, foi_id):
"""query data streams #TODO pagination"""
<|body_0|>
def patch(self, foi_id):
"""update existing feature fo interest"""
<|body_1|>
def delete(self, foi_id):
"""delete foi"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FoI:
def get(self, foi_id):
"""query data streams #TODO pagination"""
try:
foi = FeaturesofInterest.filter_by_id(foi_id)
except Exception as e:
logging.warning(e)
result = {'message': 'error'}
response = jsonify(result)
respon... | the_stack_v2_python_sparse | platform_out/app/resources/foi.py | sheenacodes/fvh_sta_datastreams | train | 0 | |
0573b19f17116eff719b69c76d7a9742b2951fa9 | [
"ret = []\nfor ii in text.splitlines():\n ret += [textwrap.fill(ii, width, initial_indent=indent, subsequent_indent=indent)]\nreturn '\\n\\n'.join(ret)",
"indent_len = len(get_indent(1))\nret = []\nfor ii in text.splitlines():\n indent = 0\n for jj in range(len(ii)):\n if not ii[jj].isspace():\n ... | <|body_start_0|>
ret = []
for ii in text.splitlines():
ret += [textwrap.fill(ii, width, initial_indent=indent, subsequent_indent=indent)]
return '\n\n'.join(ret)
<|end_body_0|>
<|body_start_1|>
indent_len = len(get_indent(1))
ret = []
for ii in text.splitline... | Help formatter with necessary changes. | CustomHelpFormatter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomHelpFormatter:
"""Help formatter with necessary changes."""
def _fill_text(self, text, width, indent):
"""Method override."""
<|body_0|>
def _split_lines(self, text, width):
"""Method override."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_072658 | 1,098 | permissive | [
{
"docstring": "Method override.",
"name": "_fill_text",
"signature": "def _fill_text(self, text, width, indent)"
},
{
"docstring": "Method override.",
"name": "_split_lines",
"signature": "def _split_lines(self, text, width)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015717 | Implement the Python class `CustomHelpFormatter` described below.
Class description:
Help formatter with necessary changes.
Method signatures and docstrings:
- def _fill_text(self, text, width, indent): Method override.
- def _split_lines(self, text, width): Method override. | Implement the Python class `CustomHelpFormatter` described below.
Class description:
Help formatter with necessary changes.
Method signatures and docstrings:
- def _fill_text(self, text, width, indent): Method override.
- def _split_lines(self, text, width): Method override.
<|skeleton|>
class CustomHelpFormatter:
... | d71b3952e71779d36d07d9f84d50d254fe10c7e4 | <|skeleton|>
class CustomHelpFormatter:
"""Help formatter with necessary changes."""
def _fill_text(self, text, width, indent):
"""Method override."""
<|body_0|>
def _split_lines(self, text, width):
"""Method override."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomHelpFormatter:
"""Help formatter with necessary changes."""
def _fill_text(self, text, width, indent):
"""Method override."""
ret = []
for ii in text.splitlines():
ret += [textwrap.fill(ii, width, initial_indent=indent, subsequent_indent=indent)]
return '... | the_stack_v2_python_sparse | dnload/custom_help_formatter.py | faemiyah/dnload | train | 73 |
1bd78361973ef25c40bbe8f1be88320cb1a44af8 | [
"result = self.init_parameter()\nanswer_id = self.get_argument('answer_id')\nanswer = self.answer_model.get(answer_id).get('_source')\nanswers = []\nfor emotion_value, emotion in self.answer_model.emotion_dict.items():\n for answer_ in answer.get('answers', []):\n if emotion_value == answer_.get('emotion'... | <|body_start_0|>
result = self.init_parameter()
answer_id = self.get_argument('answer_id')
answer = self.answer_model.get(answer_id).get('_source')
answers = []
for emotion_value, emotion in self.answer_model.emotion_dict.items():
for answer_ in answer.get('answers', ... | AnswerInfoDetailHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnswerInfoDetailHandler:
def get(self, *args, **kwargs):
"""获取答案详细信息 :param args: :param kwargs: :return:"""
<|body_0|>
def put(self):
"""修改答案数据 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = self.init_parameter()
answer_i... | stack_v2_sparse_classes_75kplus_train_072659 | 2,681 | no_license | [
{
"docstring": "获取答案详细信息 :param args: :param kwargs: :return:",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "修改答案数据 :return:",
"name": "put",
"signature": "def put(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034735 | Implement the Python class `AnswerInfoDetailHandler` described below.
Class description:
Implement the AnswerInfoDetailHandler class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): 获取答案详细信息 :param args: :param kwargs: :return:
- def put(self): 修改答案数据 :return: | Implement the Python class `AnswerInfoDetailHandler` described below.
Class description:
Implement the AnswerInfoDetailHandler class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): 获取答案详细信息 :param args: :param kwargs: :return:
- def put(self): 修改答案数据 :return:
<|skeleton|>
class AnswerInfoDetailH... | 9781b183cf168832b3c962d420e7f0a63287c4db | <|skeleton|>
class AnswerInfoDetailHandler:
def get(self, *args, **kwargs):
"""获取答案详细信息 :param args: :param kwargs: :return:"""
<|body_0|>
def put(self):
"""修改答案数据 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnswerInfoDetailHandler:
def get(self, *args, **kwargs):
"""获取答案详细信息 :param args: :param kwargs: :return:"""
result = self.init_parameter()
answer_id = self.get_argument('answer_id')
answer = self.answer_model.get(answer_id).get('_source')
answers = []
for emoti... | the_stack_v2_python_sparse | chat_bot/handlers/bot_manage/answer_info.py | jiaojianglong/MyBot | train | 0 | |
715b9e9f7b9e7c4376e4c6143ea9ee9b8c0064ff | [
"data = self.get_request_data()\nrules = [(v.not_empty, 'phone')]\nerr = v.validate(data, rules)\nif err:\n return self.send_error_response(err)\nphone = data['phone']\ncode = '%04d' % random.randint(1000, 9999)\nself.send_sms(phone, code)\ntry:\n self.db.verify.find_one_and_update(dict(type='email', data=pho... | <|body_start_0|>
data = self.get_request_data()
rules = [(v.not_empty, 'phone')]
err = v.validate(data, rules)
if err:
return self.send_error_response(err)
phone = data['phone']
code = '%04d' % random.randint(1000, 9999)
self.send_sms(phone, code)
... | SendUserPhoneCodeHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendUserPhoneCodeHandler:
def post(self):
"""用户注册时,发送手机验证码"""
<|body_0|>
def send_sms(self, phone, code):
"""发送手机验证码"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = self.get_request_data()
rules = [(v.not_empty, 'phone')]
err ... | stack_v2_sparse_classes_75kplus_train_072660 | 17,328 | no_license | [
{
"docstring": "用户注册时,发送手机验证码",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "发送手机验证码",
"name": "send_sms",
"signature": "def send_sms(self, phone, code)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002925 | Implement the Python class `SendUserPhoneCodeHandler` described below.
Class description:
Implement the SendUserPhoneCodeHandler class.
Method signatures and docstrings:
- def post(self): 用户注册时,发送手机验证码
- def send_sms(self, phone, code): 发送手机验证码 | Implement the Python class `SendUserPhoneCodeHandler` described below.
Class description:
Implement the SendUserPhoneCodeHandler class.
Method signatures and docstrings:
- def post(self): 用户注册时,发送手机验证码
- def send_sms(self, phone, code): 发送手机验证码
<|skeleton|>
class SendUserPhoneCodeHandler:
def post(self):
... | bcb03a2623fc71ef01000a96e524333513b6d138 | <|skeleton|>
class SendUserPhoneCodeHandler:
def post(self):
"""用户注册时,发送手机验证码"""
<|body_0|>
def send_sms(self, phone, code):
"""发送手机验证码"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SendUserPhoneCodeHandler:
def post(self):
"""用户注册时,发送手机验证码"""
data = self.get_request_data()
rules = [(v.not_empty, 'phone')]
err = v.validate(data, rules)
if err:
return self.send_error_response(err)
phone = data['phone']
code = '%04d' % ran... | the_stack_v2_python_sparse | controller/user/api.py | tripitakas/cbeta-reader | train | 1 | |
d2bd0ed8fd7c27dd1caf9e876984b125be5b6008 | [
"self.seen = set()\nself.dupe = set()\nself.unique = deque()\nfor val in nums:\n self.add(val)",
"while self.unique and self.unique[0] in self.dupe:\n self.unique.popleft()\nif not self.unique:\n return -1\nreturn self.unique[0]",
"if value in self.seen:\n self.dupe.add(value)\nelse:\n self.seen.... | <|body_start_0|>
self.seen = set()
self.dupe = set()
self.unique = deque()
for val in nums:
self.add(val)
<|end_body_0|>
<|body_start_1|>
while self.unique and self.unique[0] in self.dupe:
self.unique.popleft()
if not self.unique:
retu... | FirstUnique | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirstUnique:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def showFirstUnique(self):
""":rtype: int"""
<|body_1|>
def add(self, value):
""":type value: int :rtype: None"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_072661 | 1,284 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":rtype: int",
"name": "showFirstUnique",
"signature": "def showFirstUnique(self)"
},
{
"docstring": ":type value: int :rtype: None",
"name": "add",
"sign... | 3 | stack_v2_sparse_classes_30k_train_040410 | Implement the Python class `FirstUnique` described below.
Class description:
Implement the FirstUnique class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def showFirstUnique(self): :rtype: int
- def add(self, value): :type value: int :rtype: None | Implement the Python class `FirstUnique` described below.
Class description:
Implement the FirstUnique class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def showFirstUnique(self): :rtype: int
- def add(self, value): :type value: int :rtype: None
<|skeleton|>
class FirstUniq... | cd998e5fdb7d2d5b03ef1d65f30b140be4de6fb9 | <|skeleton|>
class FirstUnique:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def showFirstUnique(self):
""":rtype: int"""
<|body_1|>
def add(self, value):
""":type value: int :rtype: None"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FirstUnique:
def __init__(self, nums):
""":type nums: List[int]"""
self.seen = set()
self.dupe = set()
self.unique = deque()
for val in nums:
self.add(val)
def showFirstUnique(self):
""":rtype: int"""
while self.unique and self.unique[0]... | the_stack_v2_python_sparse | Week4_Day28_First_Unique_Number.py | zecookiez/30-Day-LeetCoding-Challenge | train | 3 | |
d90ae0e31dac304b1612d05a66502d153e4a33a3 | [
"favorite_lines = FavoriteLine.objects.filter(owner=self.request.user)\nserializer = FavoriteLineSerializer(favorite_lines, many=True)\nreturn Response(serializer.data)",
"serializer = FavoriteLineSerializer(data=request.data)\nif serializer.is_valid():\n serializer.save(owner=self.request.user)\n return Re... | <|body_start_0|>
favorite_lines = FavoriteLine.objects.filter(owner=self.request.user)
serializer = FavoriteLineSerializer(favorite_lines, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
serializer = FavoriteLineSerializer(data=request.data)
if serial... | Get, Post or Delete a FavoriteLine instance(s) for the currently authenticated user. | FavoriteLineView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FavoriteLineView:
"""Get, Post or Delete a FavoriteLine instance(s) for the currently authenticated user."""
def get(self, request):
"""Return a list of all the FavoriteLines for the currently authenticated user."""
<|body_0|>
def post(self, request):
"""Create a... | stack_v2_sparse_classes_75kplus_train_072662 | 31,821 | permissive | [
{
"docstring": "Return a list of all the FavoriteLines for the currently authenticated user.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Create a new FavoriteLine for the currently authenticated user.",
"name": "post",
"signature": "def post(self, request)"
... | 4 | null | Implement the Python class `FavoriteLineView` described below.
Class description:
Get, Post or Delete a FavoriteLine instance(s) for the currently authenticated user.
Method signatures and docstrings:
- def get(self, request): Return a list of all the FavoriteLines for the currently authenticated user.
- def post(sel... | Implement the Python class `FavoriteLineView` described below.
Class description:
Get, Post or Delete a FavoriteLine instance(s) for the currently authenticated user.
Method signatures and docstrings:
- def get(self, request): Return a list of all the FavoriteLines for the currently authenticated user.
- def post(sel... | 35955cd9166b086f59157d23ed05a8ffcf82b617 | <|skeleton|>
class FavoriteLineView:
"""Get, Post or Delete a FavoriteLine instance(s) for the currently authenticated user."""
def get(self, request):
"""Return a list of all the FavoriteLines for the currently authenticated user."""
<|body_0|>
def post(self, request):
"""Create a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FavoriteLineView:
"""Get, Post or Delete a FavoriteLine instance(s) for the currently authenticated user."""
def get(self, request):
"""Return a list of all the FavoriteLines for the currently authenticated user."""
favorite_lines = FavoriteLine.objects.filter(owner=self.request.user)
... | the_stack_v2_python_sparse | backend/dublinbus/views.py | Botazio/UCD-DublinBus | train | 5 |
4d004c220ff1b2bfdcaf17e323e9356184086ef7 | [
"self.keys_to_features = {'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'), 'image/filename': tf.FixedLenFeature((), tf.string, default_value=''), 'image/key/sha256': tf.FixedLenFeature((), tf.string, default_value=''), 'im... | <|body_start_0|>
self.keys_to_features = {'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'), 'image/filename': tf.FixedLenFeature((), tf.string, default_value=''), 'image/key/sha256': tf.FixedLenFeature((), tf.string, de... | Tensorflow Example proto decoder. | TfExampleDecoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TfExampleDecoder:
"""Tensorflow Example proto decoder."""
def __init__(self):
"""Constructor sets keys_to_features and items_to_handlers."""
<|body_0|>
def decode(self, tf_example_string_tensor):
"""Decodes serialized tensorflow example and returns a tensor dicti... | stack_v2_sparse_classes_75kplus_train_072663 | 8,543 | permissive | [
{
"docstring": "Constructor sets keys_to_features and items_to_handlers.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Decodes serialized tensorflow example and returns a tensor dictionary. Args: tf_example_string_tensor: a string tensor holding a serialized tensorfl... | 2 | stack_v2_sparse_classes_30k_train_027215 | Implement the Python class `TfExampleDecoder` described below.
Class description:
Tensorflow Example proto decoder.
Method signatures and docstrings:
- def __init__(self): Constructor sets keys_to_features and items_to_handlers.
- def decode(self, tf_example_string_tensor): Decodes serialized tensorflow example and r... | Implement the Python class `TfExampleDecoder` described below.
Class description:
Tensorflow Example proto decoder.
Method signatures and docstrings:
- def __init__(self): Constructor sets keys_to_features and items_to_handlers.
- def decode(self, tf_example_string_tensor): Decodes serialized tensorflow example and r... | 0f7adb97a93ec3e3485c261d030c507eb16b33e4 | <|skeleton|>
class TfExampleDecoder:
"""Tensorflow Example proto decoder."""
def __init__(self):
"""Constructor sets keys_to_features and items_to_handlers."""
<|body_0|>
def decode(self, tf_example_string_tensor):
"""Decodes serialized tensorflow example and returns a tensor dicti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TfExampleDecoder:
"""Tensorflow Example proto decoder."""
def __init__(self):
"""Constructor sets keys_to_features and items_to_handlers."""
self.keys_to_features = {'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, def... | the_stack_v2_python_sparse | models/official/retinanet/object_detection/tf_example_decoder.py | tensorflow/tpu | train | 5,627 |
4e1ccd6f4a660ce2919ceeac94483ae8dd711e41 | [
"res = [0]\nm = len(matrix)\nif m:\n n = len(matrix[0])\nelse:\n return 0\ndp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]\nfor i in range(m):\n for j in range(n):\n if matrix[i][j] == '1':\n if dp[i][j] and dp[i + 1][j] and dp[i][j + 1]:\n dp[i + 1][j + 1] = min(dp[... | <|body_start_0|>
res = [0]
m = len(matrix)
if m:
n = len(matrix[0])
else:
return 0
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m):
for j in range(n):
if matrix[i][j] == '1':
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def maximalSquare0(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = [0]
m ... | stack_v2_sparse_classes_75kplus_train_072664 | 1,273 | no_license | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquare",
"signature": "def maximalSquare(self, matrix)"
},
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquare0",
"signature": "def maximalSquare0(self, matrix)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046961 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int
- def maximalSquare0(self, matrix): :type matrix: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int
- def maximalSquare0(self, matrix): :type matrix: List[List[str]] :rtype: int
<|skeleton|>
class Solut... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def maximalSquare0(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
res = [0]
m = len(matrix)
if m:
n = len(matrix[0])
else:
return 0
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m):... | the_stack_v2_python_sparse | PythonCode/src/0221_Maximal_Square.py | oneyuan/CodeforFun | train | 0 | |
83c740806997b3289cbf64a46f55f1427f7eb91a | [
"self.k = k\nself._df = pd.read_json(path_to_json)\nself._df['Class'] = self._df['Class'].replace(to_replace=[3, 4, 5, 7, 8, 10], value=['Unilamellar', 'Multilamellar', 'Uncertain', 'Empty', 'Full', 'Uncertain'])\nself._df = pd.concat([self._df, pd.get_dummies(self._df['Class'], prefix='Label')], axis=1)\nself._df[... | <|body_start_0|>
self.k = k
self._df = pd.read_json(path_to_json)
self._df['Class'] = self._df['Class'].replace(to_replace=[3, 4, 5, 7, 8, 10], value=['Unilamellar', 'Multilamellar', 'Uncertain', 'Empty', 'Full', 'Uncertain'])
self._df = pd.concat([self._df, pd.get_dummies(self._df['Clas... | KFold | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KFold:
def __init__(self, k, path_to_json, path_to_img):
"""Stratified k-fold cross validation :param k: int, number of folds :param path_to_json: string :param path_to_img: string"""
<|body_0|>
def get_datasets(self, k):
"""Get train and test data sets, where one fo... | stack_v2_sparse_classes_75kplus_train_072665 | 2,059 | no_license | [
{
"docstring": "Stratified k-fold cross validation :param k: int, number of folds :param path_to_json: string :param path_to_img: string",
"name": "__init__",
"signature": "def __init__(self, k, path_to_json, path_to_img)"
},
{
"docstring": "Get train and test data sets, where one fold is used f... | 2 | null | Implement the Python class `KFold` described below.
Class description:
Implement the KFold class.
Method signatures and docstrings:
- def __init__(self, k, path_to_json, path_to_img): Stratified k-fold cross validation :param k: int, number of folds :param path_to_json: string :param path_to_img: string
- def get_dat... | Implement the Python class `KFold` described below.
Class description:
Implement the KFold class.
Method signatures and docstrings:
- def __init__(self, k, path_to_json, path_to_img): Stratified k-fold cross validation :param k: int, number of folds :param path_to_json: string :param path_to_img: string
- def get_dat... | 6a14fd678e05279c623f24debdf837bb51f642b0 | <|skeleton|>
class KFold:
def __init__(self, k, path_to_json, path_to_img):
"""Stratified k-fold cross validation :param k: int, number of folds :param path_to_json: string :param path_to_img: string"""
<|body_0|>
def get_datasets(self, k):
"""Get train and test data sets, where one fo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KFold:
def __init__(self, k, path_to_json, path_to_img):
"""Stratified k-fold cross validation :param k: int, number of folds :param path_to_json: string :param path_to_img: string"""
self.k = k
self._df = pd.read_json(path_to_json)
self._df['Class'] = self._df['Class'].replace... | the_stack_v2_python_sparse | kfold.py | JU-Chang/lipnet | train | 0 | |
31be946072912b60be0a97e44e5fcf713a0fcfe5 | [
"self.input_shape = input_shape\nself.output_size = output_size\nself.warmup_epochs = warmup_epochs\nself.regular_epochs = regular_epochs\nself.batch_size = batch_size\nself.checkpoint_path = checkpoint_path\nself.data_util = DataUtil(path_to_train=path_to_train, path_to_test=path_to_test)\nself.image_size = image_... | <|body_start_0|>
self.input_shape = input_shape
self.output_size = output_size
self.warmup_epochs = warmup_epochs
self.regular_epochs = regular_epochs
self.batch_size = batch_size
self.checkpoint_path = checkpoint_path
self.data_util = DataUtil(path_to_train=path_... | Main class for the InceptionV3 model, having all function that is needed for the model to be trained and tested | CustomInceptionModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomInceptionModel:
"""Main class for the InceptionV3 model, having all function that is needed for the model to be trained and tested"""
def __init__(self, input_shape, output_size, warmup_epochs, regular_epochs, batch_size, checkpoint_path, path_to_train, path_to_test, image_size):
... | stack_v2_sparse_classes_75kplus_train_072666 | 7,922 | no_license | [
{
"docstring": "Constructor for the custom InceptionV3 model :param input_shape: input shape for the model :param output_size: output size of the model, number of output classes :param warmup_epochs: number of training epochs used to train only additional layers added :param regular_epochs: number of training e... | 5 | stack_v2_sparse_classes_30k_train_015825 | Implement the Python class `CustomInceptionModel` described below.
Class description:
Main class for the InceptionV3 model, having all function that is needed for the model to be trained and tested
Method signatures and docstrings:
- def __init__(self, input_shape, output_size, warmup_epochs, regular_epochs, batch_si... | Implement the Python class `CustomInceptionModel` described below.
Class description:
Main class for the InceptionV3 model, having all function that is needed for the model to be trained and tested
Method signatures and docstrings:
- def __init__(self, input_shape, output_size, warmup_epochs, regular_epochs, batch_si... | a6716e3c393177b188d8ecc4b8351ea2a8ddb08a | <|skeleton|>
class CustomInceptionModel:
"""Main class for the InceptionV3 model, having all function that is needed for the model to be trained and tested"""
def __init__(self, input_shape, output_size, warmup_epochs, regular_epochs, batch_size, checkpoint_path, path_to_train, path_to_test, image_size):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomInceptionModel:
"""Main class for the InceptionV3 model, having all function that is needed for the model to be trained and tested"""
def __init__(self, input_shape, output_size, warmup_epochs, regular_epochs, batch_size, checkpoint_path, path_to_train, path_to_test, image_size):
"""Constru... | the_stack_v2_python_sparse | inceptionnet/inception_nn_model.py | reinai/ProteinSubcellularLocalization | train | 0 |
d1de51861655c5b6f23ac101ab5a67507e31988a | [
"self.shooters_total = difficulty\nself.asteroids_total = difficulty\nsuper().__init__(**kwargs)",
"player = GamePlayer.random()\nshooters = ShooterGroup.random(n=self.shooters_total)\nplayers = PlayerGroup(player, shooters, activate=True, shooting=True)\nspaceships = SuperSpaceShipGroup(players, active=True)\nas... | <|body_start_0|>
self.shooters_total = difficulty
self.asteroids_total = difficulty
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
player = GamePlayer.random()
shooters = ShooterGroup.random(n=self.shooters_total)
players = PlayerGroup(player, shooters, activ... | Level in which the goal is to destroy all shooters. | DestroyShooters | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DestroyShooters:
"""Level in which the goal is to destroy all shooters."""
def __init__(self, difficulty, **kwargs):
"""Create the level by creating the groups."""
<|body_0|>
def start(self):
"""Start the game by creating the game group with shooters."""
... | stack_v2_sparse_classes_75kplus_train_072667 | 10,293 | no_license | [
{
"docstring": "Create the level by creating the groups.",
"name": "__init__",
"signature": "def __init__(self, difficulty, **kwargs)"
},
{
"docstring": "Start the game by creating the game group with shooters.",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_053282 | Implement the Python class `DestroyShooters` described below.
Class description:
Level in which the goal is to destroy all shooters.
Method signatures and docstrings:
- def __init__(self, difficulty, **kwargs): Create the level by creating the groups.
- def start(self): Start the game by creating the game group with ... | Implement the Python class `DestroyShooters` described below.
Class description:
Level in which the goal is to destroy all shooters.
Method signatures and docstrings:
- def __init__(self, difficulty, **kwargs): Create the level by creating the groups.
- def start(self): Start the game by creating the game group with ... | ebfcaaf4a028eddb36bbc99184eb3f7a86eb24ed | <|skeleton|>
class DestroyShooters:
"""Level in which the goal is to destroy all shooters."""
def __init__(self, difficulty, **kwargs):
"""Create the level by creating the groups."""
<|body_0|>
def start(self):
"""Start the game by creating the game group with shooters."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DestroyShooters:
"""Level in which the goal is to destroy all shooters."""
def __init__(self, difficulty, **kwargs):
"""Create the level by creating the groups."""
self.shooters_total = difficulty
self.asteroids_total = difficulty
super().__init__(**kwargs)
def start(... | the_stack_v2_python_sparse | Game Structure/geometry/version5/myasteroidgame.py | MarcPartensky/Python-Games | train | 2 |
f2e3089fd4f1179f25a16c39cadd49fb3d572b09 | [
"assert check_argument_types()\nsuper(ReferenceEncoder, self).__init__()\nassert conv_kernel_size % 2 == 1, 'kernel size must be odd.'\nassert len(conv_chans_list) == conv_layers, 'the number of conv layers and length of channels list must be the same.'\nconvs = []\npadding = (conv_kernel_size - 1) // 2\nfor i in r... | <|body_start_0|>
assert check_argument_types()
super(ReferenceEncoder, self).__init__()
assert conv_kernel_size % 2 == 1, 'kernel size must be odd.'
assert len(conv_chans_list) == conv_layers, 'the number of conv layers and length of channels list must be the same.'
convs = []
... | Reference encoder module. This module is refernece encoder introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: https://arxiv.org/abs/1803.09017 Parameters ---... | ReferenceEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReferenceEncoder:
"""Reference encoder module. This module is refernece encoder introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: htt... | stack_v2_sparse_classes_75kplus_train_072668 | 10,798 | permissive | [
{
"docstring": "Initilize reference encoder module.",
"name": "__init__",
"signature": "def __init__(self, idim=80, conv_layers: int=6, conv_chans_list: Sequence[int]=(32, 32, 64, 64, 128, 128), conv_kernel_size: int=3, conv_stride: int=2, gru_layers: int=1, gru_units: int=128)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_041160 | Implement the Python class `ReferenceEncoder` described below.
Class description:
Reference encoder module. This module is refernece encoder introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transf... | Implement the Python class `ReferenceEncoder` described below.
Class description:
Reference encoder module. This module is refernece encoder introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transf... | 8705a2a8405e3c63f2174d69880d2b5525a6c9fd | <|skeleton|>
class ReferenceEncoder:
"""Reference encoder module. This module is refernece encoder introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: htt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReferenceEncoder:
"""Reference encoder module. This module is refernece encoder introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: https://arxiv.or... | the_stack_v2_python_sparse | parakeet/modules/style_encoder.py | PaddlePaddle/Parakeet | train | 609 |
153e083fe8d1a73f7e8d7da8e3c96b70469efdb7 | [
"self.transformer_type = p_transformer_type\nself.field = field\nself.incident_to_match = p_incident_to_match\nself.incidents_df = p_incidents_df\nself.params = p_params",
"transformation = self.params[self.transformer_type]\ntransformer = transformation['transformer'](self.field, transformation['params'], transf... | <|body_start_0|>
self.transformer_type = p_transformer_type
self.field = field
self.incident_to_match = p_incident_to_match
self.incidents_df = p_incidents_df
self.params = p_params
<|end_body_0|>
<|body_start_1|>
transformation = self.params[self.transformer_type]
... | Class for Transformer | Transformer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""Class for Transformer"""
def __init__(self, p_transformer_type, field, p_incidents_df, p_incident_to_match, p_params):
""":param p_transformer_type: One of the key value of TRANSFORMATION dict :param field: incident field used in this transformation :param p_incidents... | stack_v2_sparse_classes_75kplus_train_072669 | 41,203 | permissive | [
{
"docstring": ":param p_transformer_type: One of the key value of TRANSFORMATION dict :param field: incident field used in this transformation :param p_incidents_df: DataFrame of incident (should contains one columns which same name than incident_field) :param p_incident_to_match: DataFrame of the current inci... | 3 | null | Implement the Python class `Transformer` described below.
Class description:
Class for Transformer
Method signatures and docstrings:
- def __init__(self, p_transformer_type, field, p_incidents_df, p_incident_to_match, p_params): :param p_transformer_type: One of the key value of TRANSFORMATION dict :param field: inci... | Implement the Python class `Transformer` described below.
Class description:
Class for Transformer
Method signatures and docstrings:
- def __init__(self, p_transformer_type, field, p_incidents_df, p_incident_to_match, p_params): :param p_transformer_type: One of the key value of TRANSFORMATION dict :param field: inci... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class Transformer:
"""Class for Transformer"""
def __init__(self, p_transformer_type, field, p_incidents_df, p_incident_to_match, p_params):
""":param p_transformer_type: One of the key value of TRANSFORMATION dict :param field: incident field used in this transformation :param p_incidents... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Transformer:
"""Class for Transformer"""
def __init__(self, p_transformer_type, field, p_incidents_df, p_incident_to_match, p_params):
""":param p_transformer_type: One of the key value of TRANSFORMATION dict :param field: incident field used in this transformation :param p_incidents_df: DataFram... | the_stack_v2_python_sparse | Packs/Base/Scripts/DBotFindSimilarIncidents/DBotFindSimilarIncidents.py | demisto/content | train | 1,023 |
4bbd75b185d33458557225779bb8f77f0faed11e | [
"print(f'Running test: {description}')\nnumber_of_qubits = len(valid_states[0])\nnumber_of_valid_states = len(valid_states)\nqubits = circuit.qregs[0]\nbits = ClassicalRegister(number_of_qubits)\ncircuit.add_register(bits)\ncircuit.barrier(qubits)\ncircuit.measure(qubits, bits)\nsimulator = Aer.get_backend('qasm_si... | <|body_start_0|>
print(f'Running test: {description}')
number_of_qubits = len(valid_states[0])
number_of_valid_states = len(valid_states)
qubits = circuit.qregs[0]
bits = ClassicalRegister(number_of_qubits)
circuit.add_register(bits)
circuit.barrier(qubits)
... | This class contains some basic tests to show how Qiskit deals with entanglement. | EntanglementTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntanglementTests:
"""This class contains some basic tests to show how Qiskit deals with entanglement."""
def run_test(self, description, circuit, iterations, valid_states):
"""Runs a given circuit as a unit test, measuring the results and ensuring that the resulting state matches on... | stack_v2_sparse_classes_75kplus_train_072670 | 6,978 | permissive | [
{
"docstring": "Runs a given circuit as a unit test, measuring the results and ensuring that the resulting state matches one of the provided target states. Parameters: description (str): A human-readable description of the test, which will be printed to the log. circuit (QuantumCircuit): The circuit to run duri... | 5 | stack_v2_sparse_classes_30k_test_001119 | Implement the Python class `EntanglementTests` described below.
Class description:
This class contains some basic tests to show how Qiskit deals with entanglement.
Method signatures and docstrings:
- def run_test(self, description, circuit, iterations, valid_states): Runs a given circuit as a unit test, measuring the... | Implement the Python class `EntanglementTests` described below.
Class description:
This class contains some basic tests to show how Qiskit deals with entanglement.
Method signatures and docstrings:
- def run_test(self, description, circuit, iterations, valid_states): Runs a given circuit as a unit test, measuring the... | 941488f8f8a81a4b7d7fe28414ce14fa478a692a | <|skeleton|>
class EntanglementTests:
"""This class contains some basic tests to show how Qiskit deals with entanglement."""
def run_test(self, description, circuit, iterations, valid_states):
"""Runs a given circuit as a unit test, measuring the results and ensuring that the resulting state matches on... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EntanglementTests:
"""This class contains some basic tests to show how Qiskit deals with entanglement."""
def run_test(self, description, circuit, iterations, valid_states):
"""Runs a given circuit as a unit test, measuring the results and ensuring that the resulting state matches one of the prov... | the_stack_v2_python_sparse | Qiskit/QiskitFundamentals/entanglement.py | taibah/qsfe | train | 0 |
d29593434a17bbc0d092cc5bdb0b0d34636017de | [
"node_a = headA\nnode_b = headB\nwhile node_a:\n while node_b:\n if node_a == node_b:\n return node_a.val\n else:\n node_b = node_b.next\n node_b = headB\n node_a = node_a.next",
"tmp_a, tmp_b = (headA, headB)\nwhile tmp_a != tmp_b:\n if tmp_a:\n tmp_a = tmp_... | <|body_start_0|>
node_a = headA
node_b = headB
while node_a:
while node_b:
if node_a == node_b:
return node_a.val
else:
node_b = node_b.next
node_b = headB
node_a = node_a.next
<|end_body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
"""1. 最简单 双循环 超时 :param headA: :param headB: :return:"""
<|body_0|>
def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> ListNode:
"""2. x逆序列 x一个个对比直到不同 x不能破坏原结构: co... | stack_v2_sparse_classes_75kplus_train_072671 | 4,222 | no_license | [
{
"docstring": "1. 最简单 双循环 超时 :param headA: :param headB: :return:",
"name": "getIntersectionNode",
"signature": "def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode"
},
{
"docstring": "2. x逆序列 x一个个对比直到不同 x不能破坏原结构: copy.deepcopy x不行, 内存地址不对了. --- 双指针: headA独立部分长度: a headB... | 2 | stack_v2_sparse_classes_30k_train_021544 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: 1. 最简单 双循环 超时 :param headA: :param headB: :return:
- def getIntersectionNode2(self, headA: ListNode, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: 1. 最简单 双循环 超时 :param headA: :param headB: :return:
- def getIntersectionNode2(self, headA: ListNode, ... | b1680014ce3f55ba952a1e64241c0cbb783cc436 | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
"""1. 最简单 双循环 超时 :param headA: :param headB: :return:"""
<|body_0|>
def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> ListNode:
"""2. x逆序列 x一个个对比直到不同 x不能破坏原结构: co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
"""1. 最简单 双循环 超时 :param headA: :param headB: :return:"""
node_a = headA
node_b = headB
while node_a:
while node_b:
if node_a == node_b:
return ... | the_stack_v2_python_sparse | a_160.py | sun510001/leetcode_jianzhi_offer_2 | train | 0 | |
753af290990432673e7b9818afc1a23dbc678347 | [
"hash_input = set_up_variable_cube(np.zeros((3, 3)).astype(np.float32))\nresult = create_coordinate_hash(hash_input)\nexpected = '54812a6fed0f92fe75d180d63a6bd6c916407ea1e7e5fd32a5f20f86ea997fac'\nself.assertIsInstance(result, str)\nself.assertEqual(result, expected)",
"hash_input1 = set_up_variable_cube(np.zeros... | <|body_start_0|>
hash_input = set_up_variable_cube(np.zeros((3, 3)).astype(np.float32))
result = create_coordinate_hash(hash_input)
expected = '54812a6fed0f92fe75d180d63a6bd6c916407ea1e7e5fd32a5f20f86ea997fac'
self.assertIsInstance(result, str)
self.assertEqual(result, expected)
... | Test wrapper to hash generation to return a hash based on the x and y coordinates of a given cube. | Test_create_coordinate_hash | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_create_coordinate_hash:
"""Test wrapper to hash generation to return a hash based on the x and y coordinates of a given cube."""
def test_basic(self):
"""Test the expected hash is returned for a given cube."""
<|body_0|>
def test_variation(self):
"""Test tha... | stack_v2_sparse_classes_75kplus_train_072672 | 16,545 | permissive | [
{
"docstring": "Test the expected hash is returned for a given cube.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test that two cubes with slightly different coordinates return different hashes.",
"name": "test_variation",
"signature": "def test_variatio... | 2 | stack_v2_sparse_classes_30k_train_013848 | Implement the Python class `Test_create_coordinate_hash` described below.
Class description:
Test wrapper to hash generation to return a hash based on the x and y coordinates of a given cube.
Method signatures and docstrings:
- def test_basic(self): Test the expected hash is returned for a given cube.
- def test_vari... | Implement the Python class `Test_create_coordinate_hash` described below.
Class description:
Test wrapper to hash generation to return a hash based on the x and y coordinates of a given cube.
Method signatures and docstrings:
- def test_basic(self): Test the expected hash is returned for a given cube.
- def test_vari... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_create_coordinate_hash:
"""Test wrapper to hash generation to return a hash based on the x and y coordinates of a given cube."""
def test_basic(self):
"""Test the expected hash is returned for a given cube."""
<|body_0|>
def test_variation(self):
"""Test tha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_create_coordinate_hash:
"""Test wrapper to hash generation to return a hash based on the x and y coordinates of a given cube."""
def test_basic(self):
"""Test the expected hash is returned for a given cube."""
hash_input = set_up_variable_cube(np.zeros((3, 3)).astype(np.float32))
... | the_stack_v2_python_sparse | improver_tests/metadata/test_utilities.py | metoppv/improver | train | 101 |
607d40807b6dac66d5e3a77b88ef132d598ba0e7 | [
"res = []\nfor i in range(len(words)):\n for j in range(len(words)):\n if i == j:\n continue\n concat_words = words[i] + words[j]\n if concat_words == concat_words[::-1]:\n res.append((i, j))\nreturn res",
"d = {w: i for i, w in enumerate(words)}\nres = []\nfor i, w i... | <|body_start_0|>
res = []
for i in range(len(words)):
for j in range(len(words)):
if i == j:
continue
concat_words = words[i] + words[j]
if concat_words == concat_words[::-1]:
res.append((i, j))
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
"""Brute force method O(n^2)"""
<|body_0|>
def palindromePairs(self, words: List[str]) -> List[List[int]]:
"""optimized O(N*k^2), iterate over all words, iterate over all characters, check pali... | stack_v2_sparse_classes_75kplus_train_072673 | 2,241 | no_license | [
{
"docstring": "Brute force method O(n^2)",
"name": "palindromePairs",
"signature": "def palindromePairs(self, words: List[str]) -> List[List[int]]"
},
{
"docstring": "optimized O(N*k^2), iterate over all words, iterate over all characters, check palindrome 4 different cases: Case 1: If s2 is th... | 2 | stack_v2_sparse_classes_30k_train_020369 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def palindromePairs(self, words: List[str]) -> List[List[int]]: Brute force method O(n^2)
- def palindromePairs(self, words: List[str]) -> List[List[int]]: optimized O(N*k^2), it... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def palindromePairs(self, words: List[str]) -> List[List[int]]: Brute force method O(n^2)
- def palindromePairs(self, words: List[str]) -> List[List[int]]: optimized O(N*k^2), it... | e50dc0642f087f37ab3234390be3d8a0ed48fe62 | <|skeleton|>
class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
"""Brute force method O(n^2)"""
<|body_0|>
def palindromePairs(self, words: List[str]) -> List[List[int]]:
"""optimized O(N*k^2), iterate over all words, iterate over all characters, check pali... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
"""Brute force method O(n^2)"""
res = []
for i in range(len(words)):
for j in range(len(words)):
if i == j:
continue
concat_words = words[i] + words... | the_stack_v2_python_sparse | Leetcode/ByteDance/336. Palindrome Pairs.py | brlala/Educative-Grokking-Coding-Exercise | train | 3 | |
02e0e43e1231966465757a2095ded41fa8e41fc3 | [
"if event_id in [4624, 4634, 4647]:\n return self.getEventData(event, 'TargetLogonId')\nreturn self.getEventData(event, 'LogonID')",
"event_id = event.source.get('event_identifier')\nif event_id == 4624:\n account_name = self.getEventData(event, 'TargetUserName')\nelse:\n account_name = self.getEventData... | <|body_start_0|>
if event_id in [4624, 4634, 4647]:
return self.getEventData(event, 'TargetLogonId')
return self.getEventData(event, 'LogonID')
<|end_body_0|>
<|body_start_1|>
event_id = event.source.get('event_identifier')
if event_id == 4624:
account_name = sel... | Sessionizing sketch analyzer for logon sessions, where a session begins with a login event and ends with a logout or startup event. | LogonSessionizerSketchPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogonSessionizerSketchPlugin:
"""Sessionizing sketch analyzer for logon sessions, where a session begins with a login event and ends with a logout or startup event."""
def getLogonId(self, event, event_id):
"""Retrieves the logon ID for an event."""
<|body_0|>
def getSes... | stack_v2_sparse_classes_75kplus_train_072674 | 7,451 | permissive | [
{
"docstring": "Retrieves the logon ID for an event.",
"name": "getLogonId",
"signature": "def getLogonId(self, event, event_id)"
},
{
"docstring": "Creates the session ID for an event.",
"name": "getSessionId",
"signature": "def getSessionId(self, event, session_num)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014283 | Implement the Python class `LogonSessionizerSketchPlugin` described below.
Class description:
Sessionizing sketch analyzer for logon sessions, where a session begins with a login event and ends with a logout or startup event.
Method signatures and docstrings:
- def getLogonId(self, event, event_id): Retrieves the log... | Implement the Python class `LogonSessionizerSketchPlugin` described below.
Class description:
Sessionizing sketch analyzer for logon sessions, where a session begins with a login event and ends with a logout or startup event.
Method signatures and docstrings:
- def getLogonId(self, event, event_id): Retrieves the log... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class LogonSessionizerSketchPlugin:
"""Sessionizing sketch analyzer for logon sessions, where a session begins with a login event and ends with a logout or startup event."""
def getLogonId(self, event, event_id):
"""Retrieves the logon ID for an event."""
<|body_0|>
def getSes... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogonSessionizerSketchPlugin:
"""Sessionizing sketch analyzer for logon sessions, where a session begins with a login event and ends with a logout or startup event."""
def getLogonId(self, event, event_id):
"""Retrieves the logon ID for an event."""
if event_id in [4624, 4634, 4647]:
... | the_stack_v2_python_sparse | timesketch/lib/analyzers/evtx_sessionizers.py | google/timesketch | train | 2,263 |
fe8e4d2b10cb644bb5e60d97d2a77470648f8818 | [
"if self.config.model_arch == ModelArchitecture.F_NET:\n self._init_fourier_transform()\nkey = random.PRNGKey(self.random_seed)\nencoder_blocks = []\nfor layer in range(self.config.num_layers):\n key, mixing_key = random.split(key)\n mixing_arch = ModelArchitecture.BERT if self._is_attention_layer(layer) e... | <|body_start_0|>
if self.config.model_arch == ModelArchitecture.F_NET:
self._init_fourier_transform()
key = random.PRNGKey(self.random_seed)
encoder_blocks = []
for layer in range(self.config.num_layers):
key, mixing_key = random.split(key)
mixing_arch... | Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture. | EncoderModel | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderModel:
"""Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture."""
def setup(self):
"""Initializes encoder with config-dependent mixing layer."""
... | stack_v2_sparse_classes_75kplus_train_072675 | 15,842 | permissive | [
{
"docstring": "Initializes encoder with config-dependent mixing layer.",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Applies model on the inputs. Args: input_ids: Tokenized inputs of shape <int>[BATCH_SIZE, MAX_SEQ_LENGTH]. input_mask: <bool>[BATCH_SIZE, MAX_SEQ_LENGTH] m... | 5 | stack_v2_sparse_classes_30k_train_017840 | Implement the Python class `EncoderModel` described below.
Class description:
Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture.
Method signatures and docstrings:
- def setup(self): Ini... | Implement the Python class `EncoderModel` described below.
Class description:
Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture.
Method signatures and docstrings:
- def setup(self): Ini... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class EncoderModel:
"""Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture."""
def setup(self):
"""Initializes encoder with config-dependent mixing layer."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EncoderModel:
"""Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture."""
def setup(self):
"""Initializes encoder with config-dependent mixing layer."""
if sel... | the_stack_v2_python_sparse | f_net/models.py | Jimmy-INL/google-research | train | 1 |
4606d9324aef0398bdecade3ce14ccbe563e8069 | [
"database.drop_tables([Customer])\ndatabase.create_tables([Customer])\nlogger.info('-- Testing adding new customer --')\nbo.add_customer(1, 'Emily', 'Yang', '121 Main street NewYork', '2062847320', 'yange@hotmail.com', True, 10000)\ncustomer = Customer.get(Customer.customer_id == 1)\nself.assertEqual(customer.name,... | <|body_start_0|>
database.drop_tables([Customer])
database.create_tables([Customer])
logger.info('-- Testing adding new customer --')
bo.add_customer(1, 'Emily', 'Yang', '121 Main street NewYork', '2062847320', 'yange@hotmail.com', True, 10000)
customer = Customer.get(Customer.cu... | This class defines unit test fuctions for basic_operations.py | basic_operationsTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class basic_operationsTests:
"""This class defines unit test fuctions for basic_operations.py"""
def test_add_customer(self):
"""create an empty database for testing"""
<|body_0|>
def test_search_customer(self):
"""This function defines unit test fuction for search_cus... | stack_v2_sparse_classes_75kplus_train_072676 | 4,287 | no_license | [
{
"docstring": "create an empty database for testing",
"name": "test_add_customer",
"signature": "def test_add_customer(self)"
},
{
"docstring": "This function defines unit test fuction for search_customer()",
"name": "test_search_customer",
"signature": "def test_search_customer(self)"
... | 5 | stack_v2_sparse_classes_30k_train_026569 | Implement the Python class `basic_operationsTests` described below.
Class description:
This class defines unit test fuctions for basic_operations.py
Method signatures and docstrings:
- def test_add_customer(self): create an empty database for testing
- def test_search_customer(self): This function defines unit test f... | Implement the Python class `basic_operationsTests` described below.
Class description:
This class defines unit test fuctions for basic_operations.py
Method signatures and docstrings:
- def test_add_customer(self): create an empty database for testing
- def test_search_customer(self): This function defines unit test f... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class basic_operationsTests:
"""This class defines unit test fuctions for basic_operations.py"""
def test_add_customer(self):
"""create an empty database for testing"""
<|body_0|>
def test_search_customer(self):
"""This function defines unit test fuction for search_cus... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class basic_operationsTests:
"""This class defines unit test fuctions for basic_operations.py"""
def test_add_customer(self):
"""create an empty database for testing"""
database.drop_tables([Customer])
database.create_tables([Customer])
logger.info('-- Testing adding new custome... | the_stack_v2_python_sparse | students/zhen_yang/lesson03/assignment/test_basic_operations.py | JavaRod/SP_Python220B_2019 | train | 1 |
79f3b5d95798f3daf18477bfae902a199f400e11 | [
"logging.debug('Initialized row')\nself._as_regex = re.compile('\\n (?P<as_name>.+?)\\\\s\\\\(\\n AS\\\\s(?P<as_number>\\\\d+)\\\\)\\n |\\n (?P<as_number2>\\\\d+).*?\\\\((?P<as... | <|body_start_0|>
logging.debug('Initialized row')
self._as_regex = re.compile('\n (?P<as_name>.+?)\\s\\(\n AS\\s(?P<as_number>\\d+)\\)\n |\n (?P<as_number2>\\d+).*?... | Parent Class for parsing rows of bgpstream.com. For a more in depth explanation see the top of the file. | Data | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Data:
"""Parent Class for parsing rows of bgpstream.com. For a more in depth explanation see the top of the file."""
def __init__(self, csv_dir: str):
"""Initializes regexes and other important info."""
<|body_0|>
def append(self, row: bs4.element.Tag):
"""Parses... | stack_v2_sparse_classes_75kplus_train_072677 | 12,410 | permissive | [
{
"docstring": "Initializes regexes and other important info.",
"name": "__init__",
"signature": "def __init__(self, csv_dir: str)"
},
{
"docstring": "Parses, formats, and appends a row of data from bgpstream.com. For a more in depth explanation see the top of the file.",
"name": "append",
... | 6 | stack_v2_sparse_classes_30k_train_009789 | Implement the Python class `Data` described below.
Class description:
Parent Class for parsing rows of bgpstream.com. For a more in depth explanation see the top of the file.
Method signatures and docstrings:
- def __init__(self, csv_dir: str): Initializes regexes and other important info.
- def append(self, row: bs4... | Implement the Python class `Data` described below.
Class description:
Parent Class for parsing rows of bgpstream.com. For a more in depth explanation see the top of the file.
Method signatures and docstrings:
- def __init__(self, csv_dir: str): Initializes regexes and other important info.
- def append(self, row: bs4... | 91c92584b31bd128d818c7fee86c738367c0712e | <|skeleton|>
class Data:
"""Parent Class for parsing rows of bgpstream.com. For a more in depth explanation see the top of the file."""
def __init__(self, csv_dir: str):
"""Initializes regexes and other important info."""
<|body_0|>
def append(self, row: bs4.element.Tag):
"""Parses... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Data:
"""Parent Class for parsing rows of bgpstream.com. For a more in depth explanation see the top of the file."""
def __init__(self, csv_dir: str):
"""Initializes regexes and other important info."""
logging.debug('Initialized row')
self._as_regex = re.compile('\n ... | the_stack_v2_python_sparse | lib_bgp_data/collectors/bgpstream_website/data_classes.py | jfuruness/lib_bgp_data | train | 16 |
cdc35512ca3fca83e9d59f6ee5dd53612279d744 | [
"self.unchecked_text = kwargs.get('text')\nself.unchecked_image = kwargs.get('image')\nself.checked_text = kwargs.pop('checked_text', None)\nself.checked_image = kwargs.pop('checked_image', None)\nself.on_toggle = kwargs.pop('on_toggle', None)\nself.is_checked = False\nkwargs['command'] = self.toggle\nkwargs['compo... | <|body_start_0|>
self.unchecked_text = kwargs.get('text')
self.unchecked_image = kwargs.get('image')
self.checked_text = kwargs.pop('checked_text', None)
self.checked_image = kwargs.pop('checked_image', None)
self.on_toggle = kwargs.pop('on_toggle', None)
self.is_checked ... | A toggle button which works like a checkbox, and can be checked and unchecked with different text and images | ToggleButton | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToggleButton:
"""A toggle button which works like a checkbox, and can be checked and unchecked with different text and images"""
def __init__(self, master=None, **kwargs):
"""Extra parameters: checked_text (str) checked_image (PhotoImage) on_toggle(is_checked) (function) (text and im... | stack_v2_sparse_classes_75kplus_train_072678 | 1,465 | permissive | [
{
"docstring": "Extra parameters: checked_text (str) checked_image (PhotoImage) on_toggle(is_checked) (function) (text and image both default to the unchecked state)",
"name": "__init__",
"signature": "def __init__(self, master=None, **kwargs)"
},
{
"docstring": "Toggles the button state",
"... | 2 | stack_v2_sparse_classes_30k_train_030619 | Implement the Python class `ToggleButton` described below.
Class description:
A toggle button which works like a checkbox, and can be checked and unchecked with different text and images
Method signatures and docstrings:
- def __init__(self, master=None, **kwargs): Extra parameters: checked_text (str) checked_image (... | Implement the Python class `ToggleButton` described below.
Class description:
A toggle button which works like a checkbox, and can be checked and unchecked with different text and images
Method signatures and docstrings:
- def __init__(self, master=None, **kwargs): Extra parameters: checked_text (str) checked_image (... | a98ed281386c0e5c6e439c4a43b20f813d012bd7 | <|skeleton|>
class ToggleButton:
"""A toggle button which works like a checkbox, and can be checked and unchecked with different text and images"""
def __init__(self, master=None, **kwargs):
"""Extra parameters: checked_text (str) checked_image (PhotoImage) on_toggle(is_checked) (function) (text and im... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ToggleButton:
"""A toggle button which works like a checkbox, and can be checked and unchecked with different text and images"""
def __init__(self, master=None, **kwargs):
"""Extra parameters: checked_text (str) checked_image (PhotoImage) on_toggle(is_checked) (function) (text and image both defa... | the_stack_v2_python_sparse | gui/widgets/toggle_button.py | StetHD/Telebackup | train | 0 |
ba29255d800fcc456a99366c46265846b507eff6 | [
"if request.method in permissions.SAFE_METHODS:\n return True\nreturn request.user.is_staff",
"if request.method in permissions.SAFE_METHODS:\n return True\nreturn request.user.is_staff"
] | <|body_start_0|>
if request.method in permissions.SAFE_METHODS:
return True
return request.user.is_staff
<|end_body_0|>
<|body_start_1|>
if request.method in permissions.SAFE_METHODS:
return True
return request.user.is_staff
<|end_body_1|>
| IsAdminOrReadOnly | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsAdminOrReadOnly:
def has_permission(self, request, view):
"""Admin/Staff are allowed to Write. Others can only Read."""
<|body_0|>
def has_object_permission(self, request, view, obj):
"""Admin/Staff are allowed to Update/Delete. Others can only Retrieve."""
... | stack_v2_sparse_classes_75kplus_train_072679 | 677 | permissive | [
{
"docstring": "Admin/Staff are allowed to Write. Others can only Read.",
"name": "has_permission",
"signature": "def has_permission(self, request, view)"
},
{
"docstring": "Admin/Staff are allowed to Update/Delete. Others can only Retrieve.",
"name": "has_object_permission",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_035645 | Implement the Python class `IsAdminOrReadOnly` described below.
Class description:
Implement the IsAdminOrReadOnly class.
Method signatures and docstrings:
- def has_permission(self, request, view): Admin/Staff are allowed to Write. Others can only Read.
- def has_object_permission(self, request, view, obj): Admin/St... | Implement the Python class `IsAdminOrReadOnly` described below.
Class description:
Implement the IsAdminOrReadOnly class.
Method signatures and docstrings:
- def has_permission(self, request, view): Admin/Staff are allowed to Write. Others can only Read.
- def has_object_permission(self, request, view, obj): Admin/St... | 755e4b4f10aa7b1918b260a5823900fb41bfff1b | <|skeleton|>
class IsAdminOrReadOnly:
def has_permission(self, request, view):
"""Admin/Staff are allowed to Write. Others can only Read."""
<|body_0|>
def has_object_permission(self, request, view, obj):
"""Admin/Staff are allowed to Update/Delete. Others can only Retrieve."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IsAdminOrReadOnly:
def has_permission(self, request, view):
"""Admin/Staff are allowed to Write. Others can only Read."""
if request.method in permissions.SAFE_METHODS:
return True
return request.user.is_staff
def has_object_permission(self, request, view, obj):
... | the_stack_v2_python_sparse | recipe_blog/categories/permissions.py | hossshakiba/recipe-blog-api | train | 3 | |
3bb5face633106b8ea099a82a9264568db440a22 | [
"self.segs = segs\nself.valids = [True for seg in segs]\nself.grid_size = grid_size\nself.grid_dict = None",
"seg1 = self.segs[i1]\nseg2 = self.segs[i2]\nret = []\npoints = seg1.intersect(seg2)\nif len(points) > 0:\n for pt in points:\n pt.trunc()\n segs = self.__split_seg_by_points(seg1, points)\n ... | <|body_start_0|>
self.segs = segs
self.valids = [True for seg in segs]
self.grid_size = grid_size
self.grid_dict = None
<|end_body_0|>
<|body_start_1|>
seg1 = self.segs[i1]
seg2 = self.segs[i2]
ret = []
points = seg1.intersect(seg2)
if len(points)... | Desc: seg split | SegSpliter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegSpliter:
"""Desc: seg split"""
def __init__(self, segs, grid_size):
"""Desc: seg划分 Args: self : self segs : 线段集合 Return: None Raise: None"""
<|body_0|>
def __proc_seg_by_seg(self, i1, i2):
"""Desc: 计算两个seg之间的交点 Args: self : self i1 : seg1 index i2 : seg2 index... | stack_v2_sparse_classes_75kplus_train_072680 | 4,835 | permissive | [
{
"docstring": "Desc: seg划分 Args: self : self segs : 线段集合 Return: None Raise: None",
"name": "__init__",
"signature": "def __init__(self, segs, grid_size)"
},
{
"docstring": "Desc: 计算两个seg之间的交点 Args: self : self i1 : seg1 index i2 : seg2 index Return: None Raise: None",
"name": "__proc_seg_b... | 6 | stack_v2_sparse_classes_30k_test_001537 | Implement the Python class `SegSpliter` described below.
Class description:
Desc: seg split
Method signatures and docstrings:
- def __init__(self, segs, grid_size): Desc: seg划分 Args: self : self segs : 线段集合 Return: None Raise: None
- def __proc_seg_by_seg(self, i1, i2): Desc: 计算两个seg之间的交点 Args: self : self i1 : seg1 ... | Implement the Python class `SegSpliter` described below.
Class description:
Desc: seg split
Method signatures and docstrings:
- def __init__(self, segs, grid_size): Desc: seg划分 Args: self : self segs : 线段集合 Return: None Raise: None
- def __proc_seg_by_seg(self, i1, i2): Desc: 计算两个seg之间的交点 Args: self : self i1 : seg1 ... | b8ec015fa9e16c0a879c619ee1f2aab8a393c7bd | <|skeleton|>
class SegSpliter:
"""Desc: seg split"""
def __init__(self, segs, grid_size):
"""Desc: seg划分 Args: self : self segs : 线段集合 Return: None Raise: None"""
<|body_0|>
def __proc_seg_by_seg(self, i1, i2):
"""Desc: 计算两个seg之间的交点 Args: self : self i1 : seg1 index i2 : seg2 index... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SegSpliter:
"""Desc: seg split"""
def __init__(self, segs, grid_size):
"""Desc: seg划分 Args: self : self segs : 线段集合 Return: None Raise: None"""
self.segs = segs
self.valids = [True for seg in segs]
self.grid_size = grid_size
self.grid_dict = None
def __proc_se... | the_stack_v2_python_sparse | ST_DM/GenRegion/src/generate/gen/segspliter.py | sserdoubleh/Research | train | 10 |
197052fa8a7bbe780105bb07fae107f7608517b2 | [
"if not nums:\n return []\nnums.sort()\nlength = len(nums)\nreference, last, output = ({nums[i]: i for i in range(length)}, nums[-1], set())\nfor i in range(length - 2):\n first = nums[i]\n if first + 2 * last < 0:\n continue\n if first * 3 > 0:\n break\n for j in range(i + 1, length - ... | <|body_start_0|>
if not nums:
return []
nums.sort()
length = len(nums)
reference, last, output = ({nums[i]: i for i in range(length)}, nums[-1], set())
for i in range(length - 2):
first = nums[i]
if first + 2 * last < 0:
continu... | ThreeSum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreeSum:
def get_list(self, nums: List[int]) -> Set[Set[int]]:
"""Approach: Two Pointers Time Complexity: O(n^2) Space Complexity: O(n^2) :param nums: :return:"""
<|body_0|>
def get_list_(self, nums: List[int]) -> List[List]:
"""Approach: Two Pointers Time Complexit... | stack_v2_sparse_classes_75kplus_train_072681 | 3,317 | no_license | [
{
"docstring": "Approach: Two Pointers Time Complexity: O(n^2) Space Complexity: O(n^2) :param nums: :return:",
"name": "get_list",
"signature": "def get_list(self, nums: List[int]) -> Set[Set[int]]"
},
{
"docstring": "Approach: Two Pointers Time Complexity: O(n^2) Space Complexity: O(n^2) :para... | 3 | stack_v2_sparse_classes_30k_train_041688 | Implement the Python class `ThreeSum` described below.
Class description:
Implement the ThreeSum class.
Method signatures and docstrings:
- def get_list(self, nums: List[int]) -> Set[Set[int]]: Approach: Two Pointers Time Complexity: O(n^2) Space Complexity: O(n^2) :param nums: :return:
- def get_list_(self, nums: Li... | Implement the Python class `ThreeSum` described below.
Class description:
Implement the ThreeSum class.
Method signatures and docstrings:
- def get_list(self, nums: List[int]) -> Set[Set[int]]: Approach: Two Pointers Time Complexity: O(n^2) Space Complexity: O(n^2) :param nums: :return:
- def get_list_(self, nums: Li... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class ThreeSum:
def get_list(self, nums: List[int]) -> Set[Set[int]]:
"""Approach: Two Pointers Time Complexity: O(n^2) Space Complexity: O(n^2) :param nums: :return:"""
<|body_0|>
def get_list_(self, nums: List[int]) -> List[List]:
"""Approach: Two Pointers Time Complexit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreeSum:
def get_list(self, nums: List[int]) -> Set[Set[int]]:
"""Approach: Two Pointers Time Complexity: O(n^2) Space Complexity: O(n^2) :param nums: :return:"""
if not nums:
return []
nums.sort()
length = len(nums)
reference, last, output = ({nums[i]: i f... | the_stack_v2_python_sparse | data_structures/three_sum.py | Shiv2157k/leet_code | train | 1 | |
2a8b9a62e7785e9eeeec75721cbfdb0a74077efd | [
"trans_mat = sanitize_matrix(trans_mat)\nself.is_structure_changed = False\nif check_unitcell:\n primitive, self.is_structure_changed = find_spglib_primitive(structure, symprec, angle_tolerance)\n if self.is_structure_changed:\n logger.warning(f'Structure is changed to primitive cell.')\n sym_da... | <|body_start_0|>
trans_mat = sanitize_matrix(trans_mat)
self.is_structure_changed = False
if check_unitcell:
primitive, self.is_structure_changed = find_spglib_primitive(structure, symprec, angle_tolerance)
if self.is_structure_changed:
logger.warning(f'St... | Supercell | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Supercell:
def __init__(self, structure: Structure, trans_mat: Union[int, np.array, List[List]], multiplicity: Optional[int]=None, check_unitcell: bool=False, symprec: float=SYMMETRY_TOLERANCE, angle_tolerance: float=ANGLE_TOL):
"""Supercell class constructed based on a given multiplicit... | stack_v2_sparse_classes_75kplus_train_072682 | 12,027 | permissive | [
{
"docstring": "Supercell class constructed based on a given multiplicity. Args: structure (Structure): Primitive cell structure to be expanded. trans_mat (3x3 np.array, 3 np.array or a scalar): The matrix to be used for expanding the structure. multiplicity (int): The size multiplicity of structure wrt the pri... | 2 | stack_v2_sparse_classes_30k_train_042762 | Implement the Python class `Supercell` described below.
Class description:
Implement the Supercell class.
Method signatures and docstrings:
- def __init__(self, structure: Structure, trans_mat: Union[int, np.array, List[List]], multiplicity: Optional[int]=None, check_unitcell: bool=False, symprec: float=SYMMETRY_TOLE... | Implement the Python class `Supercell` described below.
Class description:
Implement the Supercell class.
Method signatures and docstrings:
- def __init__(self, structure: Structure, trans_mat: Union[int, np.array, List[List]], multiplicity: Optional[int]=None, check_unitcell: bool=False, symprec: float=SYMMETRY_TOLE... | e909796c429e16982cefe549d16881039bce89e7 | <|skeleton|>
class Supercell:
def __init__(self, structure: Structure, trans_mat: Union[int, np.array, List[List]], multiplicity: Optional[int]=None, check_unitcell: bool=False, symprec: float=SYMMETRY_TOLERANCE, angle_tolerance: float=ANGLE_TOL):
"""Supercell class constructed based on a given multiplicit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Supercell:
def __init__(self, structure: Structure, trans_mat: Union[int, np.array, List[List]], multiplicity: Optional[int]=None, check_unitcell: bool=False, symprec: float=SYMMETRY_TOLERANCE, angle_tolerance: float=ANGLE_TOL):
"""Supercell class constructed based on a given multiplicity. Args: struc... | the_stack_v2_python_sparse | pydefect/input_maker/supercell_maker.py | obaica/pydefect | train | 0 | |
c31a672d57091104a2b21833e30684fa548f153a | [
"with open(fileName, 'rU') as f:\n for line in f:\n fields = line.split()\n userID = int(fields[0])\n age = min(UserData.max_age, max(int(fields[1]), 0))\n if len(fields) < 5:\n usertype = UserData.unknown\n else:\n usertype = UserData.__usertype_map.get(f... | <|body_start_0|>
with open(fileName, 'rU') as f:
for line in f:
fields = line.split()
userID = int(fields[0])
age = min(UserData.max_age, max(int(fields[1]), 0))
if len(fields) < 5:
usertype = UserData.unknown
... | Represent user information. Note that differently from the original data file, missing, invalid and erroneous values are always marked with 0. This allows natural tests like `if gender` or `if usertype`. The following five fields exist for each user: age The age of the user in years. Missing or invalid value is indicat... | UserData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserData:
"""Represent user information. Note that differently from the original data file, missing, invalid and erroneous values are always marked with 0. This allows natural tests like `if gender` or `if usertype`. The following five fields exist for each user: age The age of the user in years.... | stack_v2_sparse_classes_75kplus_train_072683 | 8,307 | no_license | [
{
"docstring": "Read user data from ASCII file. The columns of the file are [0] User ID (integer from 0 to N) [1] Age (restricted to [1, 125], 0 means unknown) [2] Gender (0 = unknown, 1 = female, 2 = male) [3] ZIP code (99999 is unknown) [4] User type (0 = postpaid, 1 = prepaid, 2 = unknown) See the documentat... | 3 | null | Implement the Python class `UserData` described below.
Class description:
Represent user information. Note that differently from the original data file, missing, invalid and erroneous values are always marked with 0. This allows natural tests like `if gender` or `if usertype`. The following five fields exist for each ... | Implement the Python class `UserData` described below.
Class description:
Represent user information. Note that differently from the original data file, missing, invalid and erroneous values are always marked with 0. This allows natural tests like `if gender` or `if usertype`. The following five fields exist for each ... | 1a94af99005613e5512878d345757345fe05543b | <|skeleton|>
class UserData:
"""Represent user information. Note that differently from the original data file, missing, invalid and erroneous values are always marked with 0. This allows natural tests like `if gender` or `if usertype`. The following five fields exist for each user: age The age of the user in years.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserData:
"""Represent user information. Note that differently from the original data file, missing, invalid and erroneous values are always marked with 0. This allows natural tests like `if gender` or `if usertype`. The following five fields exist for each user: age The age of the user in years. Missing or i... | the_stack_v2_python_sparse | misc/phone/userdata.py | piotor87/verkko | train | 0 |
1ba9ceaed32c323750bd872d0ec91e22aa8d28fd | [
"super(BasicTh, self).__init__(input_file=input_file, params=params, BaselevelHandlerClass=BaselevelHandlerClass)\nK_sp = self.get_parameter_from_exponent('K_sp', raise_error=False)\nK_ss = self.get_parameter_from_exponent('K_ss', raise_error=False)\nlinear_diffusivity = self._length_factor ** 2.0 * self.get_parame... | <|body_start_0|>
super(BasicTh, self).__init__(input_file=input_file, params=params, BaselevelHandlerClass=BaselevelHandlerClass)
K_sp = self.get_parameter_from_exponent('K_sp', raise_error=False)
K_ss = self.get_parameter_from_exponent('K_ss', raise_error=False)
linear_diffusivity = sel... | A BasicTh computes erosion using linear diffusion, stream power with a smoothed threshold, and Q~A. | BasicTh | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicTh:
"""A BasicTh computes erosion using linear diffusion, stream power with a smoothed threshold, and Q~A."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the LinDifSPThresholdModel."""
<|body_0|>
def run_one_step(self,... | stack_v2_sparse_classes_75kplus_train_072684 | 4,432 | permissive | [
{
"docstring": "Initialize the LinDifSPThresholdModel.",
"name": "__init__",
"signature": "def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None)"
},
{
"docstring": "Advance model for one time-step of duration dt.",
"name": "run_one_step",
"signature": "def run_one_... | 2 | stack_v2_sparse_classes_30k_train_041288 | Implement the Python class `BasicTh` described below.
Class description:
A BasicTh computes erosion using linear diffusion, stream power with a smoothed threshold, and Q~A.
Method signatures and docstrings:
- def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None): Initialize the LinDifSPThreshol... | Implement the Python class `BasicTh` described below.
Class description:
A BasicTh computes erosion using linear diffusion, stream power with a smoothed threshold, and Q~A.
Method signatures and docstrings:
- def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None): Initialize the LinDifSPThreshol... | 1b756477b8a8ab6a8f1275b1b30ec84855c840ea | <|skeleton|>
class BasicTh:
"""A BasicTh computes erosion using linear diffusion, stream power with a smoothed threshold, and Q~A."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the LinDifSPThresholdModel."""
<|body_0|>
def run_one_step(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicTh:
"""A BasicTh computes erosion using linear diffusion, stream power with a smoothed threshold, and Q~A."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the LinDifSPThresholdModel."""
super(BasicTh, self).__init__(input_file=input_file... | the_stack_v2_python_sparse | terrainbento/derived_models/model_002_basicTh/model_002_basicTh.py | mcflugen/terrainbento | train | 0 |
5b0d7616769a182b6ec79855e3584b130c5c06c8 | [
"self.conn = conn\nself._tables = {}\nself._rows = []\nself._global_errors = []\nself._global_warnings = []\nself._load_tables(self.conn)",
"for table, create_table in conn.tables().items():\n try:\n reader = Reader()\n reader.parse(create_table)\n except ValueError as e:\n print('Error... | <|body_start_0|>
self.conn = conn
self._tables = {}
self._rows = []
self._global_errors = []
self._global_warnings = []
self._load_tables(self.conn)
<|end_body_0|>
<|body_start_1|>
for table, create_table in conn.tables().items():
try:
... | Database | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Database:
def __init__(self, conn):
"""Constructor. Accepts a mygrations db wrapper :param conn: mygrations db wrapper :type conn: mygrations.drivers.mysqldb.mysqldb"""
<|body_0|>
def _load_tables(self, conn):
"""Reads a database from the MySQL connection. Accepts a ... | stack_v2_sparse_classes_75kplus_train_072685 | 3,339 | permissive | [
{
"docstring": "Constructor. Accepts a mygrations db wrapper :param conn: mygrations db wrapper :type conn: mygrations.drivers.mysqldb.mysqldb",
"name": "__init__",
"signature": "def __init__(self, conn)"
},
{
"docstring": "Reads a database from the MySQL connection. Accepts a mygrations db wrap... | 3 | stack_v2_sparse_classes_30k_train_034208 | Implement the Python class `Database` described below.
Class description:
Implement the Database class.
Method signatures and docstrings:
- def __init__(self, conn): Constructor. Accepts a mygrations db wrapper :param conn: mygrations db wrapper :type conn: mygrations.drivers.mysqldb.mysqldb
- def _load_tables(self, ... | Implement the Python class `Database` described below.
Class description:
Implement the Database class.
Method signatures and docstrings:
- def __init__(self, conn): Constructor. Accepts a mygrations db wrapper :param conn: mygrations db wrapper :type conn: mygrations.drivers.mysqldb.mysqldb
- def _load_tables(self, ... | 07dd733f3ee9e6e5b37afce7e16de3dcd93be6e1 | <|skeleton|>
class Database:
def __init__(self, conn):
"""Constructor. Accepts a mygrations db wrapper :param conn: mygrations db wrapper :type conn: mygrations.drivers.mysqldb.mysqldb"""
<|body_0|>
def _load_tables(self, conn):
"""Reads a database from the MySQL connection. Accepts a ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Database:
def __init__(self, conn):
"""Constructor. Accepts a mygrations db wrapper :param conn: mygrations db wrapper :type conn: mygrations.drivers.mysqldb.mysqldb"""
self.conn = conn
self._tables = {}
self._rows = []
self._global_errors = []
self._global_warn... | the_stack_v2_python_sparse | mygrations/formats/mysql/db_reader/database.py | cmancone/mygrations | train | 12 | |
0911aecfae2a7fe78165764280f29550ee1bbca7 | [
"QItemDelegate.__init__(self, parent)\nself.itemsDict = itemsDict\nself.column = column",
"if index.column() == self.column:\n list = QListWidget(parent)\n for item in self.itemsDict:\n listItem = QListWidgetItem(item)\n listItem.setCheckState(Qt.Unchecked)\n list.addItem(listItem)\n ... | <|body_start_0|>
QItemDelegate.__init__(self, parent)
self.itemsDict = itemsDict
self.column = column
<|end_body_0|>
<|body_start_1|>
if index.column() == self.column:
list = QListWidget(parent)
for item in self.itemsDict:
listItem = QListWidgetIt... | ListWidgetDelegate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListWidgetDelegate:
def __init__(self, parent, itemsDict, column):
"""Constructor"""
<|body_0|>
def createEditor(self, parent, option, index):
"""Creates a custom editor to edit value relation data"""
<|body_1|>
def setEditorData(self, editor, index):
... | stack_v2_sparse_classes_75kplus_train_072686 | 16,608 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, parent, itemsDict, column)"
},
{
"docstring": "Creates a custom editor to edit value relation data",
"name": "createEditor",
"signature": "def createEditor(self, parent, option, index)"
},
{
"docst... | 4 | stack_v2_sparse_classes_30k_train_038230 | Implement the Python class `ListWidgetDelegate` described below.
Class description:
Implement the ListWidgetDelegate class.
Method signatures and docstrings:
- def __init__(self, parent, itemsDict, column): Constructor
- def createEditor(self, parent, option, index): Creates a custom editor to edit value relation dat... | Implement the Python class `ListWidgetDelegate` described below.
Class description:
Implement the ListWidgetDelegate class.
Method signatures and docstrings:
- def __init__(self, parent, itemsDict, column): Constructor
- def createEditor(self, parent, option, index): Creates a custom editor to edit value relation dat... | edff378f356db3c0577ce34e618c5ae493d296ba | <|skeleton|>
class ListWidgetDelegate:
def __init__(self, parent, itemsDict, column):
"""Constructor"""
<|body_0|>
def createEditor(self, parent, option, index):
"""Creates a custom editor to edit value relation data"""
<|body_1|>
def setEditorData(self, editor, index):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListWidgetDelegate:
def __init__(self, parent, itemsDict, column):
"""Constructor"""
QItemDelegate.__init__(self, parent)
self.itemsDict = itemsDict
self.column = column
def createEditor(self, parent, option, index):
"""Creates a custom editor to edit value relatio... | the_stack_v2_python_sparse | ComplexTools/manageComplex.py | euriconicacio/DsgTools | train | 0 | |
07d5e7af145f1841c2ea9e86bcbd8d43d3ad2d3f | [
"preference = models.Preference.objects.first() or {}\nsubject = [x[1] for x in models.Template.TEMPLATE_CHOICES if x[0] == obj.title]\nemail_test_data = {'username': 'Ivan Ivanov', 'email': preference.test_email, 'link': 'http://site.com/test-link/abcdfegkl/', 'invoice_id': '222', 'invoice_number': '333', 'invoice... | <|body_start_0|>
preference = models.Preference.objects.first() or {}
subject = [x[1] for x in models.Template.TEMPLATE_CHOICES if x[0] == obj.title]
email_test_data = {'username': 'Ivan Ivanov', 'email': preference.test_email, 'link': 'http://site.com/test-link/abcdfegkl/', 'invoice_id': '222',... | TemplateAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateAdmin:
def notification_email(self, request, obj):
"""Для отправления Email"""
<|body_0|>
def notification_sms(self, request, obj):
"""Для отправления SMS"""
<|body_1|>
def get_change_actions(self, request, object_id, form_url):
"""Выбира... | stack_v2_sparse_classes_75kplus_train_072687 | 6,736 | no_license | [
{
"docstring": "Для отправления Email",
"name": "notification_email",
"signature": "def notification_email(self, request, obj)"
},
{
"docstring": "Для отправления SMS",
"name": "notification_sms",
"signature": "def notification_sms(self, request, obj)"
},
{
"docstring": "Выбираем... | 3 | stack_v2_sparse_classes_30k_train_031034 | Implement the Python class `TemplateAdmin` described below.
Class description:
Implement the TemplateAdmin class.
Method signatures and docstrings:
- def notification_email(self, request, obj): Для отправления Email
- def notification_sms(self, request, obj): Для отправления SMS
- def get_change_actions(self, request... | Implement the Python class `TemplateAdmin` described below.
Class description:
Implement the TemplateAdmin class.
Method signatures and docstrings:
- def notification_email(self, request, obj): Для отправления Email
- def notification_sms(self, request, obj): Для отправления SMS
- def get_change_actions(self, request... | 19a592689ea3343e20bdbba93a53f623baea0b73 | <|skeleton|>
class TemplateAdmin:
def notification_email(self, request, obj):
"""Для отправления Email"""
<|body_0|>
def notification_sms(self, request, obj):
"""Для отправления SMS"""
<|body_1|>
def get_change_actions(self, request, object_id, form_url):
"""Выбира... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TemplateAdmin:
def notification_email(self, request, obj):
"""Для отправления Email"""
preference = models.Preference.objects.first() or {}
subject = [x[1] for x in models.Template.TEMPLATE_CHOICES if x[0] == obj.title]
email_test_data = {'username': 'Ivan Ivanov', 'email': pre... | the_stack_v2_python_sparse | api/admin.py | python3django/microservice-notifications | train | 0 | |
025193f000837a77cf88b95b37d345daddd2cfc4 | [
"S = S.upper()\nl = len(S)\ndicts = {char: [[], 0] for char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}\nfor i, char in enumerate(S):\n dicts[char][0].append(i)\nans = 0\nprint(dicts)\nfor i, char in enumerate(S):\n pos = dicts[char][1]\n if pos - 1 >= 0:\n left = dicts[char][0][pos - 1]\n else:\n le... | <|body_start_0|>
S = S.upper()
l = len(S)
dicts = {char: [[], 0] for char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
for i, char in enumerate(S):
dicts[char][0].append(i)
ans = 0
print(dicts)
for i, char in enumerate(S):
pos = dicts[char][1]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniqueLetterString(self, S):
""":type S: str :rtype: int 517 ms"""
<|body_0|>
def uniqueLetterString_1(self, S):
"""136ms :param S: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
S = S.upper()
l = len(S)
dicts... | stack_v2_sparse_classes_75kplus_train_072688 | 2,560 | no_license | [
{
"docstring": ":type S: str :rtype: int 517 ms",
"name": "uniqueLetterString",
"signature": "def uniqueLetterString(self, S)"
},
{
"docstring": "136ms :param S: :return:",
"name": "uniqueLetterString_1",
"signature": "def uniqueLetterString_1(self, S)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017132 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniqueLetterString(self, S): :type S: str :rtype: int 517 ms
- def uniqueLetterString_1(self, S): 136ms :param S: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniqueLetterString(self, S): :type S: str :rtype: int 517 ms
- def uniqueLetterString_1(self, S): 136ms :param S: :return:
<|skeleton|>
class Solution:
def uniqueLetter... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def uniqueLetterString(self, S):
""":type S: str :rtype: int 517 ms"""
<|body_0|>
def uniqueLetterString_1(self, S):
"""136ms :param S: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def uniqueLetterString(self, S):
""":type S: str :rtype: int 517 ms"""
S = S.upper()
l = len(S)
dicts = {char: [[], 0] for char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
for i, char in enumerate(S):
dicts[char][0].append(i)
ans = 0
print(dic... | the_stack_v2_python_sparse | UniqueLetterString_HARD_828.py | 953250587/leetcode-python | train | 2 | |
f4dcb8f3e2261e73cd0b6bf2704b172da60d802f | [
"settings = super().create_default_settings()\nsettings['unit_return'] = UNIT_RETURN\nreturn settings",
"super().customize_call(func, kwargs)\nif 'limits' in kwargs or 'values' in kwargs:\n self.add_values_limits_validation(kwargs.get('values', {}), kwargs.get('limits', {}))\nif UNIT_SUPPORT and 'units' in kwa... | <|body_start_0|>
settings = super().create_default_settings()
settings['unit_return'] = UNIT_RETURN
return settings
<|end_body_0|>
<|body_start_1|>
super().customize_call(func, kwargs)
if 'limits' in kwargs or 'values' in kwargs:
self.add_values_limits_validation(kwa... | Wraps a method with pre and post processing operations. All parameters must be passed as keyword arguments. All public driver methods should be decorated as an Action to make them easy to identify and hence make introspection easier. Parameters ---------- options : str, optional Assertions in the form option_name['opti... | Action | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Action:
"""Wraps a method with pre and post processing operations. All parameters must be passed as keyword arguments. All public driver methods should be decorated as an Action to make them easy to identify and hence make introspection easier. Parameters ---------- options : str, optional Assert... | stack_v2_sparse_classes_75kplus_train_072689 | 20,210 | permissive | [
{
"docstring": "Create the default settings for an action.",
"name": "create_default_settings",
"signature": "def create_default_settings(self) -> Dict[str, Any]"
},
{
"docstring": "Store the function in call attributes and customize pre/post based on the kwargs.",
"name": "customize_call",
... | 4 | stack_v2_sparse_classes_30k_val_002250 | Implement the Python class `Action` described below.
Class description:
Wraps a method with pre and post processing operations. All parameters must be passed as keyword arguments. All public driver methods should be decorated as an Action to make them easy to identify and hence make introspection easier. Parameters --... | Implement the Python class `Action` described below.
Class description:
Wraps a method with pre and post processing operations. All parameters must be passed as keyword arguments. All public driver methods should be decorated as an Action to make them easy to identify and hence make introspection easier. Parameters --... | 6f004d3e2ee2b788fb4693606cc4092147655ce1 | <|skeleton|>
class Action:
"""Wraps a method with pre and post processing operations. All parameters must be passed as keyword arguments. All public driver methods should be decorated as an Action to make them easy to identify and hence make introspection easier. Parameters ---------- options : str, optional Assert... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Action:
"""Wraps a method with pre and post processing operations. All parameters must be passed as keyword arguments. All public driver methods should be decorated as an Action to make them easy to identify and hence make introspection easier. Parameters ---------- options : str, optional Assertions in the f... | the_stack_v2_python_sparse | i3py/core/actions/action.py | Exopy/i3py | train | 1 |
e0818e2c32239b559d52eec66cf4d017cb2e366c | [
"self.organism = organism\nself.params = params\nself.sensors_utility_metric = sensors_utility_metric",
"population = []\nif self.organism is not None and self.organism.outcome_likelihood_estimator is not None:\n population += self.organism.outcome_likelihood_estimator.get_known_outcomes(sensors_prev, actuator... | <|body_start_0|>
self.organism = organism
self.params = params
self.sensors_utility_metric = sensors_utility_metric
<|end_body_0|>
<|body_start_1|>
population = []
if self.organism is not None and self.organism.outcome_likelihood_estimator is not None:
population += ... | An object that generates random sensor state vectors. | OutcomeGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutcomeGenerator:
"""An object that generates random sensor state vectors."""
def __init__(self, organism, params, sensors_utility_metric):
"""An object that generates random sensor state vectors. Arguments: params {OutcomeGeneratorParams} -- Configuration parameters."""
<|bo... | stack_v2_sparse_classes_75kplus_train_072690 | 8,734 | permissive | [
{
"docstring": "An object that generates random sensor state vectors. Arguments: params {OutcomeGeneratorParams} -- Configuration parameters.",
"name": "__init__",
"signature": "def __init__(self, organism, params, sensors_utility_metric)"
},
{
"docstring": "Generates a population of plausible s... | 2 | null | Implement the Python class `OutcomeGenerator` described below.
Class description:
An object that generates random sensor state vectors.
Method signatures and docstrings:
- def __init__(self, organism, params, sensors_utility_metric): An object that generates random sensor state vectors. Arguments: params {OutcomeGene... | Implement the Python class `OutcomeGenerator` described below.
Class description:
An object that generates random sensor state vectors.
Method signatures and docstrings:
- def __init__(self, organism, params, sensors_utility_metric): An object that generates random sensor state vectors. Arguments: params {OutcomeGene... | 13310a7b5aa317bd5733160acee60b26cadc7fea | <|skeleton|>
class OutcomeGenerator:
"""An object that generates random sensor state vectors."""
def __init__(self, organism, params, sensors_utility_metric):
"""An object that generates random sensor state vectors. Arguments: params {OutcomeGeneratorParams} -- Configuration parameters."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OutcomeGenerator:
"""An object that generates random sensor state vectors."""
def __init__(self, organism, params, sensors_utility_metric):
"""An object that generates random sensor state vectors. Arguments: params {OutcomeGeneratorParams} -- Configuration parameters."""
self.organism = o... | the_stack_v2_python_sparse | python/ipl/nnplanner/outcome.py | omedalus/IntrospectivePlanner | train | 0 |
e21665db42c86b148596be54b83043287db3d271 | [
"from sktime.distances._distance_alignment_paths import compute_min_return_path\nfrom sktime.distances._edr_numba import _edr_cost_matrix\nfrom sktime.distances.lower_bounding import resolve_bounding_matrix\nfrom sktime.utils.numba.njit import njit\n_bounding_matrix = resolve_bounding_matrix(x, y, window, itakura_m... | <|body_start_0|>
from sktime.distances._distance_alignment_paths import compute_min_return_path
from sktime.distances._edr_numba import _edr_cost_matrix
from sktime.distances.lower_bounding import resolve_bounding_matrix
from sktime.utils.numba.njit import njit
_bounding_matrix =... | Edit distance for real sequences (EDR) between two time series. ERP was adapted in [1] specifically for distances between trajectories. Like LCSS, EDR uses a distance threshold to define when two elements of a series match. However, rather than simply count matches and look for the longest sequence, ERP applies a (cons... | _EdrDistance | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _EdrDistance:
"""Edit distance for real sequences (EDR) between two time series. ERP was adapted in [1] specifically for distances between trajectories. Like LCSS, EDR uses a distance threshold to define when two elements of a series match. However, rather than simply count matches and look for t... | stack_v2_sparse_classes_75kplus_train_072691 | 8,517 | permissive | [
{
"docstring": "Create a no_python compiled edr alignment path distance callable. Series should be shape (d, m), where d is the number of dimensions, m the series length. Series can be different lengths. Parameters ---------- x: np.ndarray (2d array of shape (d,m1)). First time series. y: np.ndarray (2d array o... | 2 | stack_v2_sparse_classes_30k_train_009808 | Implement the Python class `_EdrDistance` described below.
Class description:
Edit distance for real sequences (EDR) between two time series. ERP was adapted in [1] specifically for distances between trajectories. Like LCSS, EDR uses a distance threshold to define when two elements of a series match. However, rather t... | Implement the Python class `_EdrDistance` described below.
Class description:
Edit distance for real sequences (EDR) between two time series. ERP was adapted in [1] specifically for distances between trajectories. Like LCSS, EDR uses a distance threshold to define when two elements of a series match. However, rather t... | 70b2bfaaa597eb31bc3a1032366dcc0e1f4c8a9f | <|skeleton|>
class _EdrDistance:
"""Edit distance for real sequences (EDR) between two time series. ERP was adapted in [1] specifically for distances between trajectories. Like LCSS, EDR uses a distance threshold to define when two elements of a series match. However, rather than simply count matches and look for t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _EdrDistance:
"""Edit distance for real sequences (EDR) between two time series. ERP was adapted in [1] specifically for distances between trajectories. Like LCSS, EDR uses a distance threshold to define when two elements of a series match. However, rather than simply count matches and look for the longest se... | the_stack_v2_python_sparse | sktime/distances/_edr.py | sktime/sktime | train | 1,117 |
18bec7cf480cba5f0b24a1e2f427480595b3366e | [
"data = dict()\nself.response.out.write(template.render('magicsigdemo.html', data))\nself.response.set_status(200)",
"data = self.request.get('data')\nenvText = self.request.get('env')\nformat = self.request.get('format') or 'magic-envelope'\nif data:\n logging.info('posted Atom data = %s\\n', data)\n useri... | <|body_start_0|>
data = dict()
self.response.out.write(template.render('magicsigdemo.html', data))
self.response.set_status(200)
<|end_body_0|>
<|body_start_1|>
data = self.request.get('data')
envText = self.request.get('env')
format = self.request.get('format') or 'magi... | Handles request to sign an Atom entry. Just a demo, that takes as input an arbitrary Atom entry and signs it (ultimately, using the currently authenticated user's key) and produces as output a Magic Signature. | SignThisHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignThisHandler:
"""Handles request to sign an Atom entry. Just a demo, that takes as input an arbitrary Atom entry and signs it (ultimately, using the currently authenticated user's key) and produces as output a Magic Signature."""
def get(self):
"""Handles initial display of page."... | stack_v2_sparse_classes_75kplus_train_072692 | 4,992 | no_license | [
{
"docstring": "Handles initial display of page.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Handles posting back of data and returns a result via XHR. Just for demo purposes. Accepts either data (an XML document) or env (a magic envelope) and returns output of magic-envelop... | 2 | stack_v2_sparse_classes_30k_train_051688 | Implement the Python class `SignThisHandler` described below.
Class description:
Handles request to sign an Atom entry. Just a demo, that takes as input an arbitrary Atom entry and signs it (ultimately, using the currently authenticated user's key) and produces as output a Magic Signature.
Method signatures and docst... | Implement the Python class `SignThisHandler` described below.
Class description:
Handles request to sign an Atom entry. Just a demo, that takes as input an arbitrary Atom entry and signs it (ultimately, using the currently authenticated user's key) and produces as output a Magic Signature.
Method signatures and docst... | 47543a5eee23dacef1769d309067e69c3ab8f144 | <|skeleton|>
class SignThisHandler:
"""Handles request to sign an Atom entry. Just a demo, that takes as input an arbitrary Atom entry and signs it (ultimately, using the currently authenticated user's key) and produces as output a Magic Signature."""
def get(self):
"""Handles initial display of page."... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SignThisHandler:
"""Handles request to sign an Atom entry. Just a demo, that takes as input an arbitrary Atom entry and signs it (ultimately, using the currently authenticated user's key) and produces as output a Magic Signature."""
def get(self):
"""Handles initial display of page."""
da... | the_stack_v2_python_sparse | salmon-playground/magicsigdemo.py | annando/salmon-protocol | train | 0 |
732af18e55deacb0c0d41224943a551a6831e2de | [
"self.tiles = [-1] * 9\nself.players = players\nif starter is None:\n self.current_player = 0 if random.random() > 0.5 else 1\nelse:\n self.current_player = starter\nif len(labels) == 0:\n self.players[0].label = 'X'\n self.players[1].label = 'O'\nelse:\n self.players[0].label = labels[0]\n self.p... | <|body_start_0|>
self.tiles = [-1] * 9
self.players = players
if starter is None:
self.current_player = 0 if random.random() > 0.5 else 1
else:
self.current_player = starter
if len(labels) == 0:
self.players[0].label = 'X'
self.play... | This class holds and maintains the game state. | Game | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
"""This class holds and maintains the game state."""
def __init__(self, players, labels=[], starter=None):
"""Initialize the game state. :param players: A list consisting of players."""
<|body_0|>
def play(self):
"""Play one move and return True if the game... | stack_v2_sparse_classes_75kplus_train_072693 | 8,882 | permissive | [
{
"docstring": "Initialize the game state. :param players: A list consisting of players.",
"name": "__init__",
"signature": "def __init__(self, players, labels=[], starter=None)"
},
{
"docstring": "Play one move and return True if the game is not completed yet. :return: True if the game is not c... | 4 | stack_v2_sparse_classes_30k_train_017499 | Implement the Python class `Game` described below.
Class description:
This class holds and maintains the game state.
Method signatures and docstrings:
- def __init__(self, players, labels=[], starter=None): Initialize the game state. :param players: A list consisting of players.
- def play(self): Play one move and re... | Implement the Python class `Game` described below.
Class description:
This class holds and maintains the game state.
Method signatures and docstrings:
- def __init__(self, players, labels=[], starter=None): Initialize the game state. :param players: A list consisting of players.
- def play(self): Play one move and re... | 931aabb8cbf27656151c54856eb2ea7d1153203a | <|skeleton|>
class Game:
"""This class holds and maintains the game state."""
def __init__(self, players, labels=[], starter=None):
"""Initialize the game state. :param players: A list consisting of players."""
<|body_0|>
def play(self):
"""Play one move and return True if the game... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Game:
"""This class holds and maintains the game state."""
def __init__(self, players, labels=[], starter=None):
"""Initialize the game state. :param players: A list consisting of players."""
self.tiles = [-1] * 9
self.players = players
if starter is None:
self... | the_stack_v2_python_sparse | master/tic-tac-ai-master/tic-tac-ai-master/game.py | tied/DevArtifacts | train | 0 |
896165e567f7f0ae752d39a762eac3f95bfde3f1 | [
"self.model = model\nroot_model = options.get('root', None)\nif root_model:\n try:\n root_model = try_import(root_model)\n except Exception:\n raise ResourceException('invalid root config %s' % options['root'])\nself.root_model = root_model\nif self.root_model:\n self.root_model._resource_met... | <|body_start_0|>
self.model = model
root_model = options.get('root', None)
if root_model:
try:
root_model = try_import(root_model)
except Exception:
raise ResourceException('invalid root config %s' % options['root'])
self.root_model... | 数据处理配置 | DataOption | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataOption:
"""数据处理配置"""
def __init__(self, model, **options):
"""数据处理配置初始化 :param model: 模型类 :param options: 自定义配置选项"""
<|body_0|>
def has_related(self):
"""是否有直接关联资源 :return: bool"""
<|body_1|>
def get_related(self, obj):
"""获取字段对应的关联资源 :pa... | stack_v2_sparse_classes_75kplus_train_072694 | 8,872 | no_license | [
{
"docstring": "数据处理配置初始化 :param model: 模型类 :param options: 自定义配置选项",
"name": "__init__",
"signature": "def __init__(self, model, **options)"
},
{
"docstring": "是否有直接关联资源 :return: bool",
"name": "has_related",
"signature": "def has_related(self)"
},
{
"docstring": "获取字段对应的关联资源 :p... | 3 | null | Implement the Python class `DataOption` described below.
Class description:
数据处理配置
Method signatures and docstrings:
- def __init__(self, model, **options): 数据处理配置初始化 :param model: 模型类 :param options: 自定义配置选项
- def has_related(self): 是否有直接关联资源 :return: bool
- def get_related(self, obj): 获取字段对应的关联资源 :param obj: 数据对象 :... | Implement the Python class `DataOption` described below.
Class description:
数据处理配置
Method signatures and docstrings:
- def __init__(self, model, **options): 数据处理配置初始化 :param model: 模型类 :param options: 自定义配置选项
- def has_related(self): 是否有直接关联资源 :return: bool
- def get_related(self, obj): 获取字段对应的关联资源 :param obj: 数据对象 :... | a4502d14652c6a926e74be6d0f53b2b50ada9c3c | <|skeleton|>
class DataOption:
"""数据处理配置"""
def __init__(self, model, **options):
"""数据处理配置初始化 :param model: 模型类 :param options: 自定义配置选项"""
<|body_0|>
def has_related(self):
"""是否有直接关联资源 :return: bool"""
<|body_1|>
def get_related(self, obj):
"""获取字段对应的关联资源 :pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataOption:
"""数据处理配置"""
def __init__(self, model, **options):
"""数据处理配置初始化 :param model: 模型类 :param options: 自定义配置选项"""
self.model = model
root_model = options.get('root', None)
if root_model:
try:
root_model = try_import(root_model)
... | the_stack_v2_python_sparse | sv/sv_base/extensions/resource/meta.py | xianzhishenqie/project_template | train | 1 |
3ee5fe48b082c96006c808eee8bd00c69798b935 | [
"self.useEmulator = useEmulator\nself.pollRate = pollRate\nself.allowConfigOverride = allowConfigOverride\nself.dataMsgListener = IDataMessageListener()\nlogging.info('Emulators will be used.')\nhumidityModule = __import__('programmingtheiot.cda.emulated.HumiditySensorEmulatorTask', fromlist=['HumiditySensorEmulato... | <|body_start_0|>
self.useEmulator = useEmulator
self.pollRate = pollRate
self.allowConfigOverride = allowConfigOverride
self.dataMsgListener = IDataMessageListener()
logging.info('Emulators will be used.')
humidityModule = __import__('programmingtheiot.cda.emulated.Humidi... | Shell representation of class for Sensor Adapter Manager. | SensorAdapterManager | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SensorAdapterManager:
"""Shell representation of class for Sensor Adapter Manager."""
def __init__(self, useEmulator: bool=False, pollRate: int=5, allowConfigOverride: bool=True):
"""Constructor"""
<|body_0|>
def handleCameraTelemetry(self):
"""handle the video s... | stack_v2_sparse_classes_75kplus_train_072695 | 7,335 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, useEmulator: bool=False, pollRate: int=5, allowConfigOverride: bool=True)"
},
{
"docstring": "handle the video streaming from the webcam",
"name": "handleCameraTelemetry",
"signature": "def handleCameraTel... | 6 | stack_v2_sparse_classes_30k_train_012527 | Implement the Python class `SensorAdapterManager` described below.
Class description:
Shell representation of class for Sensor Adapter Manager.
Method signatures and docstrings:
- def __init__(self, useEmulator: bool=False, pollRate: int=5, allowConfigOverride: bool=True): Constructor
- def handleCameraTelemetry(self... | Implement the Python class `SensorAdapterManager` described below.
Class description:
Shell representation of class for Sensor Adapter Manager.
Method signatures and docstrings:
- def __init__(self, useEmulator: bool=False, pollRate: int=5, allowConfigOverride: bool=True): Constructor
- def handleCameraTelemetry(self... | c45223ce61a8585fe09c4c15c5db0487d34e9dfc | <|skeleton|>
class SensorAdapterManager:
"""Shell representation of class for Sensor Adapter Manager."""
def __init__(self, useEmulator: bool=False, pollRate: int=5, allowConfigOverride: bool=True):
"""Constructor"""
<|body_0|>
def handleCameraTelemetry(self):
"""handle the video s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SensorAdapterManager:
"""Shell representation of class for Sensor Adapter Manager."""
def __init__(self, useEmulator: bool=False, pollRate: int=5, allowConfigOverride: bool=True):
"""Constructor"""
self.useEmulator = useEmulator
self.pollRate = pollRate
self.allowConfigOve... | the_stack_v2_python_sparse | constrained-device-app/src/main/python/programmingtheiot/cda/system/SensorAdapterManager.py | darasy/Indoor-Fire-Monitoring-System | train | 3 |
c1e2c692a8af5a1edcf065bb85dddc2e1887244b | [
"self._unit_of_measurement = unit_of_measurement\nself._minimum_value = minimum_sensor_value\nself._maximum_value = maximum_sensor_value\nKNXGroupAddress.__init__(self, hass, config)",
"if self._data:\n from knxip.conversion import knx2_to_float\n value = knx2_to_float(self._data)\n if self._minimum_valu... | <|body_start_0|>
self._unit_of_measurement = unit_of_measurement
self._minimum_value = minimum_sensor_value
self._maximum_value = maximum_sensor_value
KNXGroupAddress.__init__(self, hass, config)
<|end_body_0|>
<|body_start_1|>
if self._data:
from knxip.conversion im... | Base Implementation of a 2byte Floating Point KNX Telegram. Defined in KNX 3.7.2 - 3.10 | KNXSensorFloatClass | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KNXSensorFloatClass:
"""Base Implementation of a 2byte Floating Point KNX Telegram. Defined in KNX 3.7.2 - 3.10"""
def __init__(self, hass, config, unit_of_measurement, minimum_sensor_value, maximum_sensor_value):
"""Initialize a KNX Float Sensor."""
<|body_0|>
def state... | stack_v2_sparse_classes_75kplus_train_072696 | 4,164 | permissive | [
{
"docstring": "Initialize a KNX Float Sensor.",
"name": "__init__",
"signature": "def __init__(self, hass, config, unit_of_measurement, minimum_sensor_value, maximum_sensor_value)"
},
{
"docstring": "Return the Value of the KNX Sensor.",
"name": "state",
"signature": "def state(self)"
... | 2 | stack_v2_sparse_classes_30k_train_011128 | Implement the Python class `KNXSensorFloatClass` described below.
Class description:
Base Implementation of a 2byte Floating Point KNX Telegram. Defined in KNX 3.7.2 - 3.10
Method signatures and docstrings:
- def __init__(self, hass, config, unit_of_measurement, minimum_sensor_value, maximum_sensor_value): Initialize... | Implement the Python class `KNXSensorFloatClass` described below.
Class description:
Base Implementation of a 2byte Floating Point KNX Telegram. Defined in KNX 3.7.2 - 3.10
Method signatures and docstrings:
- def __init__(self, hass, config, unit_of_measurement, minimum_sensor_value, maximum_sensor_value): Initialize... | ca0e92aba83de2fd6cb1cc4d14f3b4471f17cf3d | <|skeleton|>
class KNXSensorFloatClass:
"""Base Implementation of a 2byte Floating Point KNX Telegram. Defined in KNX 3.7.2 - 3.10"""
def __init__(self, hass, config, unit_of_measurement, minimum_sensor_value, maximum_sensor_value):
"""Initialize a KNX Float Sensor."""
<|body_0|>
def state... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KNXSensorFloatClass:
"""Base Implementation of a 2byte Floating Point KNX Telegram. Defined in KNX 3.7.2 - 3.10"""
def __init__(self, hass, config, unit_of_measurement, minimum_sensor_value, maximum_sensor_value):
"""Initialize a KNX Float Sensor."""
self._unit_of_measurement = unit_of_me... | the_stack_v2_python_sparse | homeassistant/components/sensor/knx.py | Smart-Torvy/torvy-home-assistant | train | 2 |
bf6972fd314884b665c3d9440a243468710a5e05 | [
"assert label_name in ['Log10_Kd', 'Log10_Ki', 'KIBA']\nsuper(DTACollateFunc, self).__init__()\nself.graph_wrapper = graph_wrapper\nself.is_inference = is_inference\nself.label_name = label_name",
"graph_list = []\nfor data in batch_data_list:\n atom_numeric_feat = np.concatenate([data['atom_degrees'], data['a... | <|body_start_0|>
assert label_name in ['Log10_Kd', 'Log10_Ki', 'KIBA']
super(DTACollateFunc, self).__init__()
self.graph_wrapper = graph_wrapper
self.is_inference = is_inference
self.label_name = label_name
<|end_body_0|>
<|body_start_1|>
graph_list = []
for data... | DTACollateFunc | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DTACollateFunc:
def __init__(self, graph_wrapper, label_name='Log10_Kd', is_inference=False):
"""Collate function for PGL dataloader. Args: graph_wrapper (pgl.graph_wrapper.GraphWrapper): graph wrapper for GNN. label_name (str): the key in the feed dictionary for the drug-target affinity... | stack_v2_sparse_classes_75kplus_train_072697 | 5,431 | permissive | [
{
"docstring": "Collate function for PGL dataloader. Args: graph_wrapper (pgl.graph_wrapper.GraphWrapper): graph wrapper for GNN. label_name (str): the key in the feed dictionary for the drug-target affinity. For Davis, it is `Log10_Kd`; For Kiba, it is `KIBA`. is_inference (bool): when its value is True, there... | 2 | stack_v2_sparse_classes_30k_test_002285 | Implement the Python class `DTACollateFunc` described below.
Class description:
Implement the DTACollateFunc class.
Method signatures and docstrings:
- def __init__(self, graph_wrapper, label_name='Log10_Kd', is_inference=False): Collate function for PGL dataloader. Args: graph_wrapper (pgl.graph_wrapper.GraphWrapper... | Implement the Python class `DTACollateFunc` described below.
Class description:
Implement the DTACollateFunc class.
Method signatures and docstrings:
- def __init__(self, graph_wrapper, label_name='Log10_Kd', is_inference=False): Collate function for PGL dataloader. Args: graph_wrapper (pgl.graph_wrapper.GraphWrapper... | 1c84ea6d51625d2d66b3eef1d9a7cc9a87c99e0e | <|skeleton|>
class DTACollateFunc:
def __init__(self, graph_wrapper, label_name='Log10_Kd', is_inference=False):
"""Collate function for PGL dataloader. Args: graph_wrapper (pgl.graph_wrapper.GraphWrapper): graph wrapper for GNN. label_name (str): the key in the feed dictionary for the drug-target affinity... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DTACollateFunc:
def __init__(self, graph_wrapper, label_name='Log10_Kd', is_inference=False):
"""Collate function for PGL dataloader. Args: graph_wrapper (pgl.graph_wrapper.GraphWrapper): graph wrapper for GNN. label_name (str): the key in the feed dictionary for the drug-target affinity. For Davis, i... | the_stack_v2_python_sparse | apps/drug_target_interaction/graph_dta/data_gen.py | RuikangSun/PaddleHelix | train | 0 | |
0440459c91257265d4e54862f8582033e6b0f453 | [
"self.number = number\nself.task = task\nself.key = key\nself.runs = runs\nself.trynext = trynext\nself.anytime = anytime\nself.json = json\nself.participants = participants\nself.task_debug = task_debug\nself.forced_debug = forced_debug",
"if self.task_debug or self.forced_debug:\n log_debug = log.debug_alway... | <|body_start_0|>
self.number = number
self.task = task
self.key = key
self.runs = runs
self.trynext = trynext
self.anytime = anytime
self.json = json
self.participants = participants
self.task_debug = task_debug
self.forced_debug = forced_d... | Handles scheduling for a single run. | SchedulerWorker | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchedulerWorker:
"""Handles scheduling for a single run."""
def __init__(self, number, task, key, runs, trynext, anytime, json, participants, task_debug, forced_debug):
"""Initialize"""
<|body_0|>
def __call__(self):
"""Do the scheduling"""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus_train_072698 | 35,160 | permissive | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self, number, task, key, runs, trynext, anytime, json, participants, task_debug, forced_debug)"
},
{
"docstring": "Do the scheduling",
"name": "__call__",
"signature": "def __call__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048823 | Implement the Python class `SchedulerWorker` described below.
Class description:
Handles scheduling for a single run.
Method signatures and docstrings:
- def __init__(self, number, task, key, runs, trynext, anytime, json, participants, task_debug, forced_debug): Initialize
- def __call__(self): Do the scheduling | Implement the Python class `SchedulerWorker` described below.
Class description:
Handles scheduling for a single run.
Method signatures and docstrings:
- def __init__(self, number, task, key, runs, trynext, anytime, json, participants, task_debug, forced_debug): Initialize
- def __call__(self): Do the scheduling
<|s... | f6d04c0455e5be4d490df16ec1acb377f9025d9f | <|skeleton|>
class SchedulerWorker:
"""Handles scheduling for a single run."""
def __init__(self, number, task, key, runs, trynext, anytime, json, participants, task_debug, forced_debug):
"""Initialize"""
<|body_0|>
def __call__(self):
"""Do the scheduling"""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SchedulerWorker:
"""Handles scheduling for a single run."""
def __init__(self, number, task, key, runs, trynext, anytime, json, participants, task_debug, forced_debug):
"""Initialize"""
self.number = number
self.task = task
self.key = key
self.runs = runs
s... | the_stack_v2_python_sparse | pscheduler-server/pscheduler-server/daemons/scheduler | perfsonar/pscheduler | train | 53 |
47a19008477a72821fff6755882c7e7b6172654c | [
"ordered_joints_names = ['bthigh', 'bshin', 'bfoot', 'fthigh', 'fshin', 'ffoot']\nindex_start = 8 + 2 * ordered_joints_names.index(joint_name)\nreturn state[index_start:index_start + 1]",
"reward = -10 * next_state[3]\nreward += 0.05 * np.sum(np.square(action))\nfor joint in ['fthigh', 'fshin', 'ffoot']:\n joi... | <|body_start_0|>
ordered_joints_names = ['bthigh', 'bshin', 'bfoot', 'fthigh', 'fshin', 'ffoot']
index_start = 8 + 2 * ordered_joints_names.index(joint_name)
return state[index_start:index_start + 1]
<|end_body_0|>
<|body_start_1|>
reward = -10 * next_state[3]
reward += 0.05 * n... | HalfCheetahEnvNew | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HalfCheetahEnvNew:
def get_joint_state(joint_name, state):
"""helper function to better interpret the state variables"""
<|body_0|>
def calc_reward(state, action, next_state):
"""calculate the reward just based on (s, a, ns) pair"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus_train_072699 | 3,810 | no_license | [
{
"docstring": "helper function to better interpret the state variables",
"name": "get_joint_state",
"signature": "def get_joint_state(joint_name, state)"
},
{
"docstring": "calculate the reward just based on (s, a, ns) pair",
"name": "calc_reward",
"signature": "def calc_reward(state, a... | 2 | stack_v2_sparse_classes_30k_train_054140 | Implement the Python class `HalfCheetahEnvNew` described below.
Class description:
Implement the HalfCheetahEnvNew class.
Method signatures and docstrings:
- def get_joint_state(joint_name, state): helper function to better interpret the state variables
- def calc_reward(state, action, next_state): calculate the rewa... | Implement the Python class `HalfCheetahEnvNew` described below.
Class description:
Implement the HalfCheetahEnvNew class.
Method signatures and docstrings:
- def get_joint_state(joint_name, state): helper function to better interpret the state variables
- def calc_reward(state, action, next_state): calculate the rewa... | 47b81dadf65bcb73c6fb4ebc83c38ab09d750b98 | <|skeleton|>
class HalfCheetahEnvNew:
def get_joint_state(joint_name, state):
"""helper function to better interpret the state variables"""
<|body_0|>
def calc_reward(state, action, next_state):
"""calculate the reward just based on (s, a, ns) pair"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HalfCheetahEnvNew:
def get_joint_state(joint_name, state):
"""helper function to better interpret the state variables"""
ordered_joints_names = ['bthigh', 'bshin', 'bfoot', 'fthigh', 'fshin', 'ffoot']
index_start = 8 + 2 * ordered_joints_names.index(joint_name)
return state[ind... | the_stack_v2_python_sparse | envs.py | farzadab/agile | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.