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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0bea03f6d7e35831afecad5fd5adec10e058a2aa | [
"super().__init__(name, parent_object_handle, parent_link, up)\nself.bounds = bounds\nself.rotation = rotation if rotation is not None else mn.Quaternion()",
"scaled_region = mn.Range3D.from_center(self.bounds.center(), sample_region_scale * self.bounds.size() / 2)\nsample_range = [scaled_region.min, scaled_regio... | <|body_start_0|>
super().__init__(name, parent_object_handle, parent_link, up)
self.bounds = bounds
self.rotation = rotation if rotation is not None else mn.Quaternion()
<|end_body_0|>
<|body_start_1|>
scaled_region = mn.Range3D.from_center(self.bounds.center(), sample_region_scale * se... | Defines an AABB Receptacle volume above a surface for sampling object placements within a scene. | AABBReceptacle | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-NC-SA-3.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AABBReceptacle:
"""Defines an AABB Receptacle volume above a surface for sampling object placements within a scene."""
def __init__(self, name: str, bounds: mn.Range3D, parent_object_handle: str=None, parent_link: Optional[int]=None, up: Optional[mn.Vector3]=None, rotation: Optional[mn.Quate... | stack_v2_sparse_classes_75kplus_train_065800 | 39,034 | permissive | [
{
"docstring": ":param name: The name of the Receptacle. Should be unique and descriptive for any one object. :param bounds: The AABB of the Receptacle. :param up: The \"up\" direction of the Receptacle in local AABB space. Used for optionally culling receptacles in un-supportive states such as inverted surface... | 5 | stack_v2_sparse_classes_30k_train_010142 | Implement the Python class `AABBReceptacle` described below.
Class description:
Defines an AABB Receptacle volume above a surface for sampling object placements within a scene.
Method signatures and docstrings:
- def __init__(self, name: str, bounds: mn.Range3D, parent_object_handle: str=None, parent_link: Optional[i... | Implement the Python class `AABBReceptacle` described below.
Class description:
Defines an AABB Receptacle volume above a surface for sampling object placements within a scene.
Method signatures and docstrings:
- def __init__(self, name: str, bounds: mn.Range3D, parent_object_handle: str=None, parent_link: Optional[i... | f5b29e62df0788d70ba3618fc738fa4e947428ba | <|skeleton|>
class AABBReceptacle:
"""Defines an AABB Receptacle volume above a surface for sampling object placements within a scene."""
def __init__(self, name: str, bounds: mn.Range3D, parent_object_handle: str=None, parent_link: Optional[int]=None, up: Optional[mn.Vector3]=None, rotation: Optional[mn.Quate... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AABBReceptacle:
"""Defines an AABB Receptacle volume above a surface for sampling object placements within a scene."""
def __init__(self, name: str, bounds: mn.Range3D, parent_object_handle: str=None, parent_link: Optional[int]=None, up: Optional[mn.Vector3]=None, rotation: Optional[mn.Quaternion]=None) ... | the_stack_v2_python_sparse | habitat-lab/habitat/datasets/rearrange/samplers/receptacle.py | facebookresearch/habitat-lab | train | 792 |
f8f1726bad3d7bea6ef1db8341607f7b26dcf439 | [
"if value in EMPTY_VALUES:\n return None\nif type(value) in [str, unicode]:\n try:\n value = value.replace(\"'\", '\"')\n value = json.loads(value)\n except ValueError:\n msg = self.error_messages['invalid']\n raise serializers.ValidationError(msg)\nif value:\n day = value.ge... | <|body_start_0|>
if value in EMPTY_VALUES:
return None
if type(value) in [str, unicode]:
try:
value = value.replace("'", '"')
value = json.loads(value)
except ValueError:
msg = self.error_messages['invalid']
... | A serializer field for handling three part date time JSON formatted datetime.date. Expected input format: { "day": 25, "month": 12, "year": 2012 } | ThreePartDateField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreePartDateField:
"""A serializer field for handling three part date time JSON formatted datetime.date. Expected input format: { "day": 25, "month": 12, "year": 2012 }"""
def to_internal_value(self, value):
"""Parse json data and return a date object"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus_train_065801 | 4,517 | permissive | [
{
"docstring": "Parse json data and return a date object",
"name": "to_internal_value",
"signature": "def to_internal_value(self, value)"
},
{
"docstring": "Transform datetime.date object to json.",
"name": "to_representation",
"signature": "def to_representation(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012160 | Implement the Python class `ThreePartDateField` described below.
Class description:
A serializer field for handling three part date time JSON formatted datetime.date. Expected input format: { "day": 25, "month": 12, "year": 2012 }
Method signatures and docstrings:
- def to_internal_value(self, value): Parse json data... | Implement the Python class `ThreePartDateField` described below.
Class description:
A serializer field for handling three part date time JSON formatted datetime.date. Expected input format: { "day": 25, "month": 12, "year": 2012 }
Method signatures and docstrings:
- def to_internal_value(self, value): Parse json data... | 51d40345b41eb68fb4d65ae273f3496d1012e2f3 | <|skeleton|>
class ThreePartDateField:
"""A serializer field for handling three part date time JSON formatted datetime.date. Expected input format: { "day": 25, "month": 12, "year": 2012 }"""
def to_internal_value(self, value):
"""Parse json data and return a date object"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreePartDateField:
"""A serializer field for handling three part date time JSON formatted datetime.date. Expected input format: { "day": 25, "month": 12, "year": 2012 }"""
def to_internal_value(self, value):
"""Parse json data and return a date object"""
if value in EMPTY_VALUES:
... | the_stack_v2_python_sparse | cla_backend/apps/core/drf/fields.py | ministryofjustice/cla_backend | train | 4 |
9a7927458a53a7b0d61ea7af7d0298ff04929895 | [
"try:\n assert isinstance(filename, str), 'filepath must be a string'\nexcept AssertionError as excep:\n raise FitsLoaderError(excep) from excep\nself.data = Data([], [], [])\nself._opener(filename)",
"try:\n with fits.open(filename) as _file:\n self._unpack(_file)\nexcept Exception as excep:\n ... | <|body_start_0|>
try:
assert isinstance(filename, str), 'filepath must be a string'
except AssertionError as excep:
raise FitsLoaderError(excep) from excep
self.data = Data([], [], [])
self._opener(filename)
<|end_body_0|>
<|body_start_1|>
try:
... | FitLoader can open a fits file, unpack it and returns a Data object storing the data and the exposure time. | FitsLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FitsLoader:
"""FitLoader can open a fits file, unpack it and returns a Data object storing the data and the exposure time."""
def __init__(self, filename):
"""Loads a Fits file, creates and returns a Data object."""
<|body_0|>
def _opener(self, filename):
"""Open... | stack_v2_sparse_classes_75kplus_train_065802 | 1,511 | no_license | [
{
"docstring": "Loads a Fits file, creates and returns a Data object.",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Opens the file and sends it to be unpacked.",
"name": "_opener",
"signature": "def _opener(self, filename)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_023675 | Implement the Python class `FitsLoader` described below.
Class description:
FitLoader can open a fits file, unpack it and returns a Data object storing the data and the exposure time.
Method signatures and docstrings:
- def __init__(self, filename): Loads a Fits file, creates and returns a Data object.
- def _opener(... | Implement the Python class `FitsLoader` described below.
Class description:
FitLoader can open a fits file, unpack it and returns a Data object storing the data and the exposure time.
Method signatures and docstrings:
- def __init__(self, filename): Loads a Fits file, creates and returns a Data object.
- def _opener(... | 2587b9657a91e4063c1a47c847e73cc90be215ff | <|skeleton|>
class FitsLoader:
"""FitLoader can open a fits file, unpack it and returns a Data object storing the data and the exposure time."""
def __init__(self, filename):
"""Loads a Fits file, creates and returns a Data object."""
<|body_0|>
def _opener(self, filename):
"""Open... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FitsLoader:
"""FitLoader can open a fits file, unpack it and returns a Data object storing the data and the exposure time."""
def __init__(self, filename):
"""Loads a Fits file, creates and returns a Data object."""
try:
assert isinstance(filename, str), 'filepath must be a st... | the_stack_v2_python_sparse | CCD Reduction Files v2/FitsLoader.py | characterisation-micro-lenses/CCD-Reducer | train | 0 |
7f3bc960a9d58351b7edd72c74944ffeed386a64 | [
"args = parse_argstring(self.problog, line)\nif args.knowledge == 'nnf':\n knowledge = DDNNF\nelif args.knowledge == 'sdd':\n knowledge = SDD\nelif args.knowledge is None:\n if SDD.is_available():\n knowledge = SDD\n else:\n knowledge = DDNNF\nelse:\n warnings.warn(\"Unknown option for ... | <|body_start_0|>
args = parse_argstring(self.problog, line)
if args.knowledge == 'nnf':
knowledge = DDNNF
elif args.knowledge == 'sdd':
knowledge = SDD
elif args.knowledge is None:
if SDD.is_available():
knowledge = SDD
else... | ProbLogMagics | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProbLogMagics:
def problog(self, line, cell=None):
"""problog line/cell magic"""
<|body_0|>
def problogstr(self, line):
"""problog string magic"""
<|body_1|>
def problogobj(self, line):
"""problog object magic"""
<|body_2|>
def probl... | stack_v2_sparse_classes_75kplus_train_065803 | 6,134 | permissive | [
{
"docstring": "problog line/cell magic",
"name": "problog",
"signature": "def problog(self, line, cell=None)"
},
{
"docstring": "problog string magic",
"name": "problogstr",
"signature": "def problogstr(self, line)"
},
{
"docstring": "problog object magic",
"name": "problogo... | 5 | null | Implement the Python class `ProbLogMagics` described below.
Class description:
Implement the ProbLogMagics class.
Method signatures and docstrings:
- def problog(self, line, cell=None): problog line/cell magic
- def problogstr(self, line): problog string magic
- def problogobj(self, line): problog object magic
- def ... | Implement the Python class `ProbLogMagics` described below.
Class description:
Implement the ProbLogMagics class.
Method signatures and docstrings:
- def problog(self, line, cell=None): problog line/cell magic
- def problogstr(self, line): problog string magic
- def problogobj(self, line): problog object magic
- def ... | 70ab18747ec0b32b59ed1936a04872acffdbd2f9 | <|skeleton|>
class ProbLogMagics:
def problog(self, line, cell=None):
"""problog line/cell magic"""
<|body_0|>
def problogstr(self, line):
"""problog string magic"""
<|body_1|>
def problogobj(self, line):
"""problog object magic"""
<|body_2|>
def probl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProbLogMagics:
def problog(self, line, cell=None):
"""problog line/cell magic"""
args = parse_argstring(self.problog, line)
if args.knowledge == 'nnf':
knowledge = DDNNF
elif args.knowledge == 'sdd':
knowledge = SDD
elif args.knowledge is None:
... | the_stack_v2_python_sparse | venv/Lib/site-packages/problog/magic.py | szervoudakis/OpinionMine | train | 1 | |
a2a03d18c4de1bc7f6276c8a7a4d64b321a0596f | [
"self._links = {}\nself.nodes = set()\nfor a, b, cost in directed_links:\n if a not in self._links:\n self._links[a] = {}\n self._links[a][b] = int(cost)\n self.nodes.add(a)\n self.nodes.add(b)",
"if node not in self.nodes:\n raise KeyError(\"Node not known: '{}'\".format(node))\ntry:\n r... | <|body_start_0|>
self._links = {}
self.nodes = set()
for a, b, cost in directed_links:
if a not in self._links:
self._links[a] = {}
self._links[a][b] = int(cost)
self.nodes.add(a)
self.nodes.add(b)
<|end_body_0|>
<|body_start_1|>
... | Graph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Graph:
def __init__(self, directed_links):
"""Build a representation for a graph given a list of 3-tuples representing edges made of (A, B, cost) where A -> B is a directed link."""
<|body_0|>
def links(self, node):
"""Return the edges coming from the given node in a... | stack_v2_sparse_classes_75kplus_train_065804 | 6,038 | no_license | [
{
"docstring": "Build a representation for a graph given a list of 3-tuples representing edges made of (A, B, cost) where A -> B is a directed link.",
"name": "__init__",
"signature": "def __init__(self, directed_links)"
},
{
"docstring": "Return the edges coming from the given node in a diction... | 2 | null | Implement the Python class `Graph` described below.
Class description:
Implement the Graph class.
Method signatures and docstrings:
- def __init__(self, directed_links): Build a representation for a graph given a list of 3-tuples representing edges made of (A, B, cost) where A -> B is a directed link.
- def links(sel... | Implement the Python class `Graph` described below.
Class description:
Implement the Graph class.
Method signatures and docstrings:
- def __init__(self, directed_links): Build a representation for a graph given a list of 3-tuples representing edges made of (A, B, cost) where A -> B is a directed link.
- def links(sel... | a3d3971efbd8b310eee247e280146d6b6908d0c3 | <|skeleton|>
class Graph:
def __init__(self, directed_links):
"""Build a representation for a graph given a list of 3-tuples representing edges made of (A, B, cost) where A -> B is a directed link."""
<|body_0|>
def links(self, node):
"""Return the edges coming from the given node in a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Graph:
def __init__(self, directed_links):
"""Build a representation for a graph given a list of 3-tuples representing edges made of (A, B, cost) where A -> B is a directed link."""
self._links = {}
self.nodes = set()
for a, b, cost in directed_links:
if a not in se... | the_stack_v2_python_sparse | alexander-bauer/Search.py | UMBC-AI/AIProject1 | train | 0 | |
bb500431a9791aa2cd1b040a8e76d0898f142f15 | [
"if data is not None:\n if type(data) is not list:\n raise TypeError('data must be a list')\n if len(data) <= 1:\n raise ValueError('data must contain multiple values')\n self.lambtha = 1 / (sum(data) / len(data))\nelse:\n lambtha = float(lambtha)\n if lambtha < 1:\n raise ValueE... | <|body_start_0|>
if data is not None:
if type(data) is not list:
raise TypeError('data must be a list')
if len(data) <= 1:
raise ValueError('data must contain multiple values')
self.lambtha = 1 / (sum(data) / len(data))
else:
... | Exponential | Exponential | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exponential:
"""Exponential"""
def __init__(self, data=None, lambtha=1.0):
"""Initialize"""
<|body_0|>
def pdf(self, x):
"""PDF for a given tme period"""
<|body_1|>
def cdf(self, x):
"""CDF for a given number of “successes”"""
<|body_... | stack_v2_sparse_classes_75kplus_train_065805 | 1,002 | no_license | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
},
{
"docstring": "PDF for a given tme period",
"name": "pdf",
"signature": "def pdf(self, x)"
},
{
"docstring": "CDF for a given number of “successes”",
"name": "cdf",
... | 3 | null | Implement the Python class `Exponential` described below.
Class description:
Exponential
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Initialize
- def pdf(self, x): PDF for a given tme period
- def cdf(self, x): CDF for a given number of “successes” | Implement the Python class `Exponential` described below.
Class description:
Exponential
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Initialize
- def pdf(self, x): PDF for a given tme period
- def cdf(self, x): CDF for a given number of “successes”
<|skeleton|>
class Exponential:
... | 9ff78818c132d1233c11b8fc8fd469878b23b14e | <|skeleton|>
class Exponential:
"""Exponential"""
def __init__(self, data=None, lambtha=1.0):
"""Initialize"""
<|body_0|>
def pdf(self, x):
"""PDF for a given tme period"""
<|body_1|>
def cdf(self, x):
"""CDF for a given number of “successes”"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Exponential:
"""Exponential"""
def __init__(self, data=None, lambtha=1.0):
"""Initialize"""
if data is not None:
if type(data) is not list:
raise TypeError('data must be a list')
if len(data) <= 1:
raise ValueError('data must contain... | the_stack_v2_python_sparse | math/0x03-probability/exponential.py | Nzparra/holbertonschool-machine_learning | train | 0 |
d58a4da7cbf47ab83a5ce8df84a343e7b438624a | [
"super(DeleteGroupTest, self).setUp()\nself.create_group0_response = self.autoscale_behaviors.create_scaling_group_given(gc_min_entities=0)\nself.group0 = self.create_group0_response.entity\nself.assertEquals(self.create_group0_response.status_code, 201)\nself.policy_up_execute = {'change': 2}\nself.policy_webhook ... | <|body_start_0|>
super(DeleteGroupTest, self).setUp()
self.create_group0_response = self.autoscale_behaviors.create_scaling_group_given(gc_min_entities=0)
self.group0 = self.create_group0_response.entity
self.assertEquals(self.create_group0_response.status_code, 201)
self.policy_... | System tests to verify various delete scaling group scenarios | DeleteGroupTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteGroupTest:
"""System tests to verify various delete scaling group scenarios"""
def setUp(self):
"""Create 2 scaling groups, one with minentities>0 with a scaling up policy and webhook another with minentities=0"""
<|body_0|>
def test_system_delete_group_with_minent... | stack_v2_sparse_classes_75kplus_train_065806 | 5,662 | permissive | [
{
"docstring": "Create 2 scaling groups, one with minentities>0 with a scaling up policy and webhook another with minentities=0",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "A scaling group cannot be deleted when minentities > zero",
"name": "test_system_delete_group_w... | 6 | stack_v2_sparse_classes_30k_train_014034 | Implement the Python class `DeleteGroupTest` described below.
Class description:
System tests to verify various delete scaling group scenarios
Method signatures and docstrings:
- def setUp(self): Create 2 scaling groups, one with minentities>0 with a scaling up policy and webhook another with minentities=0
- def test... | Implement the Python class `DeleteGroupTest` described below.
Class description:
System tests to verify various delete scaling group scenarios
Method signatures and docstrings:
- def setUp(self): Create 2 scaling groups, one with minentities>0 with a scaling up policy and webhook another with minentities=0
- def test... | 7199cdd67255fe116dbcbedea660c13453671134 | <|skeleton|>
class DeleteGroupTest:
"""System tests to verify various delete scaling group scenarios"""
def setUp(self):
"""Create 2 scaling groups, one with minentities>0 with a scaling up policy and webhook another with minentities=0"""
<|body_0|>
def test_system_delete_group_with_minent... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeleteGroupTest:
"""System tests to verify various delete scaling group scenarios"""
def setUp(self):
"""Create 2 scaling groups, one with minentities>0 with a scaling up policy and webhook another with minentities=0"""
super(DeleteGroupTest, self).setUp()
self.create_group0_respo... | the_stack_v2_python_sparse | autoscale_cloudroast/test_repo/autoscale/system/group/test_system_delete_group.py | rackerlabs/otter | train | 20 |
b94ee346b3b81a27026c223ab788ae242b99f3fd | [
"parser.add_argument('BOMName', type=str, help='Provide a BillOfMaterial Name which was used for Asset')\nparser.add_argument('Quantity', type=int, help='Number of Asset to be created')\nparser.add_argument('ProductName', type=str, help='Provide a Product Name')\nparser.add_argument('WarehouseName', type=str, help=... | <|body_start_0|>
parser.add_argument('BOMName', type=str, help='Provide a BillOfMaterial Name which was used for Asset')
parser.add_argument('Quantity', type=int, help='Number of Asset to be created')
parser.add_argument('ProductName', type=str, help='Provide a Product Name')
parser.add_... | . | Command | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""."""
def add_arguments(self, parser):
"""Mandatory Arguments."""
<|body_0|>
def handle(self, *args, **options):
"""."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
parser.add_argument('BOMName', type=str, help='Provide a BillOfMater... | stack_v2_sparse_classes_75kplus_train_065807 | 3,898 | no_license | [
{
"docstring": "Mandatory Arguments.",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": ".",
"name": "handle",
"signature": "def handle(self, *args, **options)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016080 | Implement the Python class `Command` described below.
Class description:
.
Method signatures and docstrings:
- def add_arguments(self, parser): Mandatory Arguments.
- def handle(self, *args, **options): . | Implement the Python class `Command` described below.
Class description:
.
Method signatures and docstrings:
- def add_arguments(self, parser): Mandatory Arguments.
- def handle(self, *args, **options): .
<|skeleton|>
class Command:
"""."""
def add_arguments(self, parser):
"""Mandatory Arguments."""... | 0c9c041624b1133d04c0389a9270140b68c10b21 | <|skeleton|>
class Command:
"""."""
def add_arguments(self, parser):
"""Mandatory Arguments."""
<|body_0|>
def handle(self, *args, **options):
"""."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Command:
"""."""
def add_arguments(self, parser):
"""Mandatory Arguments."""
parser.add_argument('BOMName', type=str, help='Provide a BillOfMaterial Name which was used for Asset')
parser.add_argument('Quantity', type=int, help='Number of Asset to be created')
parser.add_a... | the_stack_v2_python_sparse | aims/inventory/management/commands/create_assets.py | anmolsrivastava18/ERP_Repository | train | 0 |
881417ed40147b934579f46cd6fecf7404fb4fe9 | [
"for m in self:\n if hasattr(m, 'condition') and m is not self:\n cast(Callable, m.condition)(z)",
"for nm, m in self.named_children():\n try:\n if hasattr(m, 'condition') and z is not None:\n x = m(x, z)\n else:\n x = m(x)\n except Exception as e:\n rais... | <|body_start_0|>
for m in self:
if hasattr(m, 'condition') and m is not self:
cast(Callable, m.condition)(z)
<|end_body_0|>
<|body_start_1|>
for nm, m in self.named_children():
try:
if hasattr(m, 'condition') and z is not None:
... | An extension to torch's Sequential that allows conditioning either as a second forward argument or `condition()` | CondSeq | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CondSeq:
"""An extension to torch's Sequential that allows conditioning either as a second forward argument or `condition()`"""
def condition(self, z: Any) -> None:
"""Conditions all the layers on z Args: z: conditioning"""
<|body_0|>
def forward(self, x: Any, z: Optiona... | stack_v2_sparse_classes_75kplus_train_065808 | 1,123 | permissive | [
{
"docstring": "Conditions all the layers on z Args: z: conditioning",
"name": "condition",
"signature": "def condition(self, z: Any) -> None"
},
{
"docstring": "Forward pass Args: x: input z (optional): conditioning. condition() must be called first if left None",
"name": "forward",
"si... | 2 | stack_v2_sparse_classes_30k_test_002372 | Implement the Python class `CondSeq` described below.
Class description:
An extension to torch's Sequential that allows conditioning either as a second forward argument or `condition()`
Method signatures and docstrings:
- def condition(self, z: Any) -> None: Conditions all the layers on z Args: z: conditioning
- def ... | Implement the Python class `CondSeq` described below.
Class description:
An extension to torch's Sequential that allows conditioning either as a second forward argument or `condition()`
Method signatures and docstrings:
- def condition(self, z: Any) -> None: Conditions all the layers on z Args: z: conditioning
- def ... | 3b09ea9a4cfa195aa78dcac676aab1c43815bd53 | <|skeleton|>
class CondSeq:
"""An extension to torch's Sequential that allows conditioning either as a second forward argument or `condition()`"""
def condition(self, z: Any) -> None:
"""Conditions all the layers on z Args: z: conditioning"""
<|body_0|>
def forward(self, x: Any, z: Optiona... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CondSeq:
"""An extension to torch's Sequential that allows conditioning either as a second forward argument or `condition()`"""
def condition(self, z: Any) -> None:
"""Conditions all the layers on z Args: z: conditioning"""
for m in self:
if hasattr(m, 'condition') and m is no... | the_stack_v2_python_sparse | torchelie/nn/condseq.py | Vermeille/Torchelie | train | 124 |
76a214d6fed3e526235f851a11ec816d0ac8964f | [
"self.antivirus_provider_name = antivirus_provider_name\nself.entity_id = entity_id\nself.file_path = file_path\nself.infection_detection_timestamp = infection_detection_timestamp\nself.modified_timestamp_usecs = modified_timestamp_usecs\nself.remediation_state = remediation_state\nself.root_inode_id = root_inode_i... | <|body_start_0|>
self.antivirus_provider_name = antivirus_provider_name
self.entity_id = entity_id
self.file_path = file_path
self.infection_detection_timestamp = infection_detection_timestamp
self.modified_timestamp_usecs = modified_timestamp_usecs
self.remediation_state... | Implementation of the 'InfectedFile' model. Specifies the Result parameters for all infected files. Attributes: antivirus_provider_name (string): Specifies the name of antivirus service provider. entity_id (long|int): Specifies the entity id of the infected file. file_path (string): Specifies file path of the infected ... | InfectedFile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfectedFile:
"""Implementation of the 'InfectedFile' model. Specifies the Result parameters for all infected files. Attributes: antivirus_provider_name (string): Specifies the name of antivirus service provider. entity_id (long|int): Specifies the entity id of the infected file. file_path (strin... | stack_v2_sparse_classes_75kplus_train_065809 | 5,701 | permissive | [
{
"docstring": "Constructor for the InfectedFile class",
"name": "__init__",
"signature": "def __init__(self, antivirus_provider_name=None, entity_id=None, file_path=None, infection_detection_timestamp=None, modified_timestamp_usecs=None, remediation_state=None, root_inode_id=None, scan_timestamp_usecs=... | 2 | stack_v2_sparse_classes_30k_train_014540 | Implement the Python class `InfectedFile` described below.
Class description:
Implementation of the 'InfectedFile' model. Specifies the Result parameters for all infected files. Attributes: antivirus_provider_name (string): Specifies the name of antivirus service provider. entity_id (long|int): Specifies the entity id... | Implement the Python class `InfectedFile` described below.
Class description:
Implementation of the 'InfectedFile' model. Specifies the Result parameters for all infected files. Attributes: antivirus_provider_name (string): Specifies the name of antivirus service provider. entity_id (long|int): Specifies the entity id... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class InfectedFile:
"""Implementation of the 'InfectedFile' model. Specifies the Result parameters for all infected files. Attributes: antivirus_provider_name (string): Specifies the name of antivirus service provider. entity_id (long|int): Specifies the entity id of the infected file. file_path (strin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InfectedFile:
"""Implementation of the 'InfectedFile' model. Specifies the Result parameters for all infected files. Attributes: antivirus_provider_name (string): Specifies the name of antivirus service provider. entity_id (long|int): Specifies the entity id of the infected file. file_path (string): Specifies... | the_stack_v2_python_sparse | cohesity_management_sdk/models/infected_file.py | cohesity/management-sdk-python | train | 24 |
3c58da696a26f28cf48bca9f77e455ec019e67f9 | [
"super(UnmanagedInstanceGroupMigration, self).__init__()\nself.instance_group = self.build_instance_group()\nself.instance_migration_handlers = []\nself.migration_status = MigrationStatus(0)",
"instance_group_helper = InstanceGroupHelper(self.compute, self.project, self.instance_group_name, self.region, self.zone... | <|body_start_0|>
super(UnmanagedInstanceGroupMigration, self).__init__()
self.instance_group = self.build_instance_group()
self.instance_migration_handlers = []
self.migration_status = MigrationStatus(0)
<|end_body_0|>
<|body_start_1|>
instance_group_helper = InstanceGroupHelper... | UnmanagedInstanceGroupMigration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnmanagedInstanceGroupMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target... | stack_v2_sparse_classes_75kplus_train_065810 | 6,427 | permissive | [
{
"docstring": "Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target network subnetwork_name: target subnetwork preserve_external_ip: whether to preserve instances' external IPs zone: zone of a zonal instance group region: region of regio... | 4 | stack_v2_sparse_classes_30k_train_013555 | Implement the Python class `UnmanagedInstanceGroupMigration` described below.
Class description:
Implement the UnmanagedInstanceGroupMigration class.
Method signatures and docstrings:
- def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name): Initia... | Implement the Python class `UnmanagedInstanceGroupMigration` described below.
Class description:
Implement the UnmanagedInstanceGroupMigration class.
Method signatures and docstrings:
- def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name): Initia... | 1132e44d696ab9da4d1079ebc3d32ed4382cdc28 | <|skeleton|>
class UnmanagedInstanceGroupMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnmanagedInstanceGroupMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target network subne... | the_stack_v2_python_sparse | vm_network_migration/handlers/instance_group_migration/unmanaged_instance_group_migration.py | googleinterns/vm-network-migration | train | 1 | |
1dc9ede2c51686593a2e93c3715934571636e051 | [
"super(MLP, self).__init__()\nassert type(input_dim) == int\nassert type(output_dim) == int\nassert type(hidden_layer_sizes) == list\nassert all((type(n) is int for n in hidden_layer_sizes))\nself._mlp = nn.Sequential()\nself._mlp.add_module('fc0', nn.Linear(input_dim, hidden_layer_sizes[0]))\nself._mlp.add_module(... | <|body_start_0|>
super(MLP, self).__init__()
assert type(input_dim) == int
assert type(output_dim) == int
assert type(hidden_layer_sizes) == list
assert all((type(n) is int for n in hidden_layer_sizes))
self._mlp = nn.Sequential()
self._mlp.add_module('fc0', nn.Li... | A Multi-layer Perceptron. | MLP | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLP:
"""A Multi-layer Perceptron."""
def __init__(self, input_dim: int, output_dim: int, hidden_layer_sizes: List[int], nonlinearity: nn.Module, dropout: Optional[float]=None, batchnorm: Optional[bool]=False) -> None:
"""Initialize the MLP. Activations are softpluses. Parameters ----... | stack_v2_sparse_classes_75kplus_train_065811 | 13,993 | permissive | [
{
"docstring": "Initialize the MLP. Activations are softpluses. Parameters ---------- input_dim : int Dimension of the input. output_dim : int Dimension of the output variable. hidden_layer_sizes : List[int] List of sizes of all hidden layers. nonlinearity : torch.nn.Module A the nonlinearity to use (must be a ... | 2 | stack_v2_sparse_classes_30k_train_003033 | Implement the Python class `MLP` described below.
Class description:
A Multi-layer Perceptron.
Method signatures and docstrings:
- def __init__(self, input_dim: int, output_dim: int, hidden_layer_sizes: List[int], nonlinearity: nn.Module, dropout: Optional[float]=None, batchnorm: Optional[bool]=False) -> None: Initia... | Implement the Python class `MLP` described below.
Class description:
A Multi-layer Perceptron.
Method signatures and docstrings:
- def __init__(self, input_dim: int, output_dim: int, hidden_layer_sizes: List[int], nonlinearity: nn.Module, dropout: Optional[float]=None, batchnorm: Optional[bool]=False) -> None: Initia... | 184b1537c22ebc2f614677be8fe171de785bda42 | <|skeleton|>
class MLP:
"""A Multi-layer Perceptron."""
def __init__(self, input_dim: int, output_dim: int, hidden_layer_sizes: List[int], nonlinearity: nn.Module, dropout: Optional[float]=None, batchnorm: Optional[bool]=False) -> None:
"""Initialize the MLP. Activations are softpluses. Parameters ----... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLP:
"""A Multi-layer Perceptron."""
def __init__(self, input_dim: int, output_dim: int, hidden_layer_sizes: List[int], nonlinearity: nn.Module, dropout: Optional[float]=None, batchnorm: Optional[bool]=False) -> None:
"""Initialize the MLP. Activations are softpluses. Parameters ---------- input_... | the_stack_v2_python_sparse | dynamics_learning/networks/models.py | cristovaoiglesias/replay-overshooting | train | 0 |
8e4d26ae43fcf03ee4b84e35a944842645709c66 | [
"Block.__init__(self, scenario, args)\nif self.language is None:\n raise LoadingException('Language must be defined!')",
"if tnode.voice != 'passive' and tnode.gram_diathesis != 'pas':\n if tnode.lex_anode and tnode.lex_anode.morphcat_pos == 'V':\n tnode.set_deref_attr('wild/conjugated', tnode.lex_an... | <|body_start_0|>
Block.__init__(self, scenario, args)
if self.language is None:
raise LoadingException('Language must be defined!')
<|end_body_0|>
<|body_start_1|>
if tnode.voice != 'passive' and tnode.gram_diathesis != 'pas':
if tnode.lex_anode and tnode.lex_anode.morph... | Add compound passive auxiliary 'být'. Arguments: language: the language of the target tree selector: the selector of the target tree | AddAuxVerbCompoundPassive | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddAuxVerbCompoundPassive:
"""Add compound passive auxiliary 'být'. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
<|body_0|>
def p... | stack_v2_sparse_classes_75kplus_train_065812 | 1,843 | permissive | [
{
"docstring": "Constructor, just checking the argument values",
"name": "__init__",
"signature": "def __init__(self, scenario, args)"
},
{
"docstring": "Add compound passive auxiliary to a node, where appropriate.",
"name": "process_tnode",
"signature": "def process_tnode(self, tnode)"
... | 2 | stack_v2_sparse_classes_30k_train_018844 | Implement the Python class `AddAuxVerbCompoundPassive` described below.
Class description:
Add compound passive auxiliary 'být'. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario, args): Constructor, just chec... | Implement the Python class `AddAuxVerbCompoundPassive` described below.
Class description:
Add compound passive auxiliary 'být'. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario, args): Constructor, just chec... | 73af644ec35c8a1cd0c37cd478c2afc1db717e0b | <|skeleton|>
class AddAuxVerbCompoundPassive:
"""Add compound passive auxiliary 'být'. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
<|body_0|>
def p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddAuxVerbCompoundPassive:
"""Add compound passive auxiliary 'být'. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
Block.__init__(self, scenario, arg... | the_stack_v2_python_sparse | alex/components/nlg/tectotpl/block/t2a/cs/addauxverbcompoundpassive.py | oplatek/alex | train | 0 |
d177b7651982ec05e6d12cc2bb899d3f6663a8b0 | [
"result = self.versions_client.list_versions()\nversions = result['versions']\nself.assertEqual(versions[0]['id'], 'v2.0', 'The first listed version should be v2.0')",
"result = self.versions_client.list_versions()\nversions = result['versions']\nfor version in versions:\n links = [x for x in version['links'] ... | <|body_start_0|>
result = self.versions_client.list_versions()
versions = result['versions']
self.assertEqual(versions[0]['id'], 'v2.0', 'The first listed version should be v2.0')
<|end_body_0|>
<|body_start_1|>
result = self.versions_client.list_versions()
versions = result['ve... | TestVersions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestVersions:
def test_list_api_versions(self):
"""Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on the service and get a list of the versioned endpoints that you can access. This comes back as a status ... | stack_v2_sparse_classes_75kplus_train_065813 | 3,232 | permissive | [
{
"docstring": "Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on the service and get a list of the versioned endpoints that you can access. This comes back as a status 300 request. It's important that this is available to API c... | 2 | stack_v2_sparse_classes_30k_train_010874 | Implement the Python class `TestVersions` described below.
Class description:
Implement the TestVersions class.
Method signatures and docstrings:
- def test_list_api_versions(self): Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on th... | Implement the Python class `TestVersions` described below.
Class description:
Implement the TestVersions class.
Method signatures and docstrings:
- def test_list_api_versions(self): Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on th... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class TestVersions:
def test_list_api_versions(self):
"""Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on the service and get a list of the versioned endpoints that you can access. This comes back as a status ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestVersions:
def test_list_api_versions(self):
"""Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on the service and get a list of the versioned endpoints that you can access. This comes back as a status 300 request. I... | the_stack_v2_python_sparse | tempest/api/compute/test_versions.py | openstack/tempest | train | 270 | |
b4cc6bcb27a43d153bc09ea98392be10defb41b1 | [
"cluster = self.get_object_or_404(objects.Cluster, cluster_id)\nself.check_net_provider(cluster)\nreturn self.serializer.serialize_for_cluster(cluster)",
"data = jsonutils.loads(web.data())\ncluster = self.get_object_or_404(objects.Cluster, cluster_id)\nself.check_net_provider(cluster)\nself.check_if_network_conf... | <|body_start_0|>
cluster = self.get_object_or_404(objects.Cluster, cluster_id)
self.check_net_provider(cluster)
return self.serializer.serialize_for_cluster(cluster)
<|end_body_0|>
<|body_start_1|>
data = jsonutils.loads(web.data())
cluster = self.get_object_or_404(objects.Clust... | Neutron Network configuration handler | NeutronNetworkConfigurationHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeutronNetworkConfigurationHandler:
"""Neutron Network configuration handler"""
def GET(self, cluster_id):
""":returns: JSONized network configuration for cluster. :http: * 200 (OK) * 404 (cluster not found in db)"""
<|body_0|>
def PUT(self, cluster_id):
""":retu... | stack_v2_sparse_classes_75kplus_train_065814 | 8,763 | permissive | [
{
"docstring": ":returns: JSONized network configuration for cluster. :http: * 200 (OK) * 404 (cluster not found in db)",
"name": "GET",
"signature": "def GET(self, cluster_id)"
},
{
"docstring": ":returns: JSONized Task object. :http: * 200 (task successfully executed) * 202 (network checking t... | 2 | stack_v2_sparse_classes_30k_train_036040 | Implement the Python class `NeutronNetworkConfigurationHandler` described below.
Class description:
Neutron Network configuration handler
Method signatures and docstrings:
- def GET(self, cluster_id): :returns: JSONized network configuration for cluster. :http: * 200 (OK) * 404 (cluster not found in db)
- def PUT(sel... | Implement the Python class `NeutronNetworkConfigurationHandler` described below.
Class description:
Neutron Network configuration handler
Method signatures and docstrings:
- def GET(self, cluster_id): :returns: JSONized network configuration for cluster. :http: * 200 (OK) * 404 (cluster not found in db)
- def PUT(sel... | 976baf842242a5f97c95bdc3e20328fa0558bf69 | <|skeleton|>
class NeutronNetworkConfigurationHandler:
"""Neutron Network configuration handler"""
def GET(self, cluster_id):
""":returns: JSONized network configuration for cluster. :http: * 200 (OK) * 404 (cluster not found in db)"""
<|body_0|>
def PUT(self, cluster_id):
""":retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeutronNetworkConfigurationHandler:
"""Neutron Network configuration handler"""
def GET(self, cluster_id):
""":returns: JSONized network configuration for cluster. :http: * 200 (OK) * 404 (cluster not found in db)"""
cluster = self.get_object_or_404(objects.Cluster, cluster_id)
se... | the_stack_v2_python_sparse | nailgun/nailgun/api/v1/handlers/network_configuration.py | nebril/fuel-web | train | 1 |
289900c85d72c31fffaa62c69d84edb5a5e6070c | [
"n = 0\npower = 1\nfor i in reversed(range(0, len(digits))):\n n += digits[i] * power\n power *= 10\nn += 1\nresult = []\nfor digit in str(n):\n result.append(int(digit))\nreturn result",
"for i in reversed(range(0, len(digits))):\n if digits[i] == 9:\n digits[i] = 0\n else:\n digits[... | <|body_start_0|>
n = 0
power = 1
for i in reversed(range(0, len(digits))):
n += digits[i] * power
power *= 10
n += 1
result = []
for digit in str(n):
result.append(int(digit))
return result
<|end_body_0|>
<|body_start_1|>
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne2(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = 0
power = 1
... | stack_v2_sparse_classes_75kplus_train_065815 | 1,988 | permissive | [
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne",
"signature": "def plusOne(self, digits)"
},
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne2",
"signature": "def plusOne2(self, digits)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006782 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne2(self, digits): :type digits: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne2(self, digits): :type digits: List[int] :rtype: List[int]
<|skeleton|>
class Solution:
de... | 9217d1dddbb7171134854a27023ea79ccfaf80d6 | <|skeleton|>
class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne2(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
n = 0
power = 1
for i in reversed(range(0, len(digits))):
n += digits[i] * power
power *= 10
n += 1
result = []
for digit in str(n):
... | the_stack_v2_python_sparse | leetcode/src/plusone.py | chadccollins/algo | train | 0 | |
f1b9ffd0783dc24d6f107a342142a255d5d6ab9e | [
"super(GRU, self).__init__()\nself.dict_size = conf_dict['dict_size']\nself.task_mode = conf_dict['task_mode']\nself.emb_dim = conf_dict['net']['emb_dim']\nself.gru_dim = conf_dict['net']['gru_dim']\nself.hidden_dim = conf_dict['net']['hidden_dim']\nself.emb_layer = layers.EmbeddingLayer(self.dict_size, self.emb_di... | <|body_start_0|>
super(GRU, self).__init__()
self.dict_size = conf_dict['dict_size']
self.task_mode = conf_dict['task_mode']
self.emb_dim = conf_dict['net']['emb_dim']
self.gru_dim = conf_dict['net']['gru_dim']
self.hidden_dim = conf_dict['net']['hidden_dim']
self... | GRU | GRU | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRU:
"""GRU"""
def __init__(self, conf_dict):
"""initialize"""
<|body_0|>
def forward(self, left, right):
"""Forward network"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(GRU, self).__init__()
self.dict_size = conf_dict['dict_siz... | stack_v2_sparse_classes_75kplus_train_065816 | 3,335 | permissive | [
{
"docstring": "initialize",
"name": "__init__",
"signature": "def __init__(self, conf_dict)"
},
{
"docstring": "Forward network",
"name": "forward",
"signature": "def forward(self, left, right)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034141 | Implement the Python class `GRU` described below.
Class description:
GRU
Method signatures and docstrings:
- def __init__(self, conf_dict): initialize
- def forward(self, left, right): Forward network | Implement the Python class `GRU` described below.
Class description:
GRU
Method signatures and docstrings:
- def __init__(self, conf_dict): initialize
- def forward(self, left, right): Forward network
<|skeleton|>
class GRU:
"""GRU"""
def __init__(self, conf_dict):
"""initialize"""
<|body_0|... | a60babdf382aba71fe447b3259441b4bed947414 | <|skeleton|>
class GRU:
"""GRU"""
def __init__(self, conf_dict):
"""initialize"""
<|body_0|>
def forward(self, left, right):
"""Forward network"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GRU:
"""GRU"""
def __init__(self, conf_dict):
"""initialize"""
super(GRU, self).__init__()
self.dict_size = conf_dict['dict_size']
self.task_mode = conf_dict['task_mode']
self.emb_dim = conf_dict['net']['emb_dim']
self.gru_dim = conf_dict['net']['gru_dim']
... | the_stack_v2_python_sparse | dygraph/similarity_net/nets/gru.py | littletomatodonkey/models | train | 5 |
39b2110306ffbf176b3fc00fee4e37696b58f44c | [
"heads, tails = data\ntest_stat = abs(heads - tails)\nreturn test_stat",
"heads, tails = self.data\nn = heads + tails\nsample = [random.choice('HT') for _ in range(n)]\nhist = thinkstats2.Hist(sample)\ndata = (hist['H'], hist['T'])\nreturn data"
] | <|body_start_0|>
heads, tails = data
test_stat = abs(heads - tails)
return test_stat
<|end_body_0|>
<|body_start_1|>
heads, tails = self.data
n = heads + tails
sample = [random.choice('HT') for _ in range(n)]
hist = thinkstats2.Hist(sample)
data = (hist['... | Tests the hypothesis that a coin is fair. | CoinTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoinTest:
"""Tests the hypothesis that a coin is fair."""
def TestStatistic(self, data):
"""Computes the test statistic. data: data in whatever form is relevant"""
<|body_0|>
def RunModel(self):
"""Run the model of the null hypothesis. returns: simulated data"""
... | stack_v2_sparse_classes_75kplus_train_065817 | 10,162 | permissive | [
{
"docstring": "Computes the test statistic. data: data in whatever form is relevant",
"name": "TestStatistic",
"signature": "def TestStatistic(self, data)"
},
{
"docstring": "Run the model of the null hypothesis. returns: simulated data",
"name": "RunModel",
"signature": "def RunModel(s... | 2 | stack_v2_sparse_classes_30k_train_049559 | Implement the Python class `CoinTest` described below.
Class description:
Tests the hypothesis that a coin is fair.
Method signatures and docstrings:
- def TestStatistic(self, data): Computes the test statistic. data: data in whatever form is relevant
- def RunModel(self): Run the model of the null hypothesis. return... | Implement the Python class `CoinTest` described below.
Class description:
Tests the hypothesis that a coin is fair.
Method signatures and docstrings:
- def TestStatistic(self, data): Computes the test statistic. data: data in whatever form is relevant
- def RunModel(self): Run the model of the null hypothesis. return... | 30a85d5137db95e01461ad21519bc1bdf294044b | <|skeleton|>
class CoinTest:
"""Tests the hypothesis that a coin is fair."""
def TestStatistic(self, data):
"""Computes the test statistic. data: data in whatever form is relevant"""
<|body_0|>
def RunModel(self):
"""Run the model of the null hypothesis. returns: simulated data"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CoinTest:
"""Tests the hypothesis that a coin is fair."""
def TestStatistic(self, data):
"""Computes the test statistic. data: data in whatever form is relevant"""
heads, tails = data
test_stat = abs(heads - tails)
return test_stat
def RunModel(self):
"""Run t... | the_stack_v2_python_sparse | CompStats/hypothesis.py | sunny2309/scipy_conf_notebooks | train | 2 |
a0f71b2a2b7decfe934062ac897d7db9cf815647 | [
"self.threads = 0\nself._size = None\nself._image_files = []\nself._lock = threading.Lock()",
"self._image_files = image_files\nself._size = size\nwhile self._image_files:\n if self.threads < 4:\n new_thread = threading.Thread(target=self._resize_image)\n self.threads += 1\n new_thread.sta... | <|body_start_0|>
self.threads = 0
self._size = None
self._image_files = []
self._lock = threading.Lock()
<|end_body_0|>
<|body_start_1|>
self._image_files = image_files
self._size = size
while self._image_files:
if self.threads < 4:
ne... | Class for multi threaded image resizing. | ImageResizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageResizer:
"""Class for multi threaded image resizing."""
def __init__(self):
"""Define instance variables."""
<|body_0|>
def resize_images(self, image_files: list, size: tuple):
"""Resize specified images to size and save them in a new files."""
<|bod... | stack_v2_sparse_classes_75kplus_train_065818 | 2,542 | permissive | [
{
"docstring": "Define instance variables.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Resize specified images to size and save them in a new files.",
"name": "resize_images",
"signature": "def resize_images(self, image_files: list, size: tuple)"
},
{
... | 3 | null | Implement the Python class `ImageResizer` described below.
Class description:
Class for multi threaded image resizing.
Method signatures and docstrings:
- def __init__(self): Define instance variables.
- def resize_images(self, image_files: list, size: tuple): Resize specified images to size and save them in a new fi... | Implement the Python class `ImageResizer` described below.
Class description:
Class for multi threaded image resizing.
Method signatures and docstrings:
- def __init__(self): Define instance variables.
- def resize_images(self, image_files: list, size: tuple): Resize specified images to size and save them in a new fi... | 73b554d9796510fc86e5fc55016732aa866266c6 | <|skeleton|>
class ImageResizer:
"""Class for multi threaded image resizing."""
def __init__(self):
"""Define instance variables."""
<|body_0|>
def resize_images(self, image_files: list, size: tuple):
"""Resize specified images to size and save them in a new files."""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageResizer:
"""Class for multi threaded image resizing."""
def __init__(self):
"""Define instance variables."""
self.threads = 0
self._size = None
self._image_files = []
self._lock = threading.Lock()
def resize_images(self, image_files: list, size: tuple):
... | the_stack_v2_python_sparse | Threading/Bulk Thumbnail Creator/bulk_thumbnail_creator.py | fossabot/IdeaBag2-Solutions | train | 0 |
e131aa8787bcc60ee35b90ab7cf58f156808a27b | [
"grocery_products = grocery.get_category_to_product()\nproducts = grocery_products[category]\nmax = 0\nfor item in products:\n if max < item.get_price():\n max = item.get_price()\nreturn max",
"grocery_products = grocery.get_category_to_product()\nproducts = grocery_products[category]\nmin = float('inf'... | <|body_start_0|>
grocery_products = grocery.get_category_to_product()
products = grocery_products[category]
max = 0
for item in products:
if max < item.get_price():
max = item.get_price()
return max
<|end_body_0|>
<|body_start_1|>
grocery_prod... | A utility class that does some statistical analysis on a given object | StatisticalAnalysis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatisticalAnalysis:
"""A utility class that does some statistical analysis on a given object"""
def get_max(self, grocery, category):
"""(StatisticalAnalysis, GroceryStore, str) -> float returns the maximum product price of a given category"""
<|body_0|>
def get_min(sel... | stack_v2_sparse_classes_75kplus_train_065819 | 7,362 | no_license | [
{
"docstring": "(StatisticalAnalysis, GroceryStore, str) -> float returns the maximum product price of a given category",
"name": "get_max",
"signature": "def get_max(self, grocery, category)"
},
{
"docstring": "(StatisticalAnalysis, GroceryStore, str) -> float returns the minimum product price ... | 3 | stack_v2_sparse_classes_30k_train_025405 | Implement the Python class `StatisticalAnalysis` described below.
Class description:
A utility class that does some statistical analysis on a given object
Method signatures and docstrings:
- def get_max(self, grocery, category): (StatisticalAnalysis, GroceryStore, str) -> float returns the maximum product price of a ... | Implement the Python class `StatisticalAnalysis` described below.
Class description:
A utility class that does some statistical analysis on a given object
Method signatures and docstrings:
- def get_max(self, grocery, category): (StatisticalAnalysis, GroceryStore, str) -> float returns the maximum product price of a ... | b7ff2ea7882c2e9f8c7edd45d04684e8e03b4502 | <|skeleton|>
class StatisticalAnalysis:
"""A utility class that does some statistical analysis on a given object"""
def get_max(self, grocery, category):
"""(StatisticalAnalysis, GroceryStore, str) -> float returns the maximum product price of a given category"""
<|body_0|>
def get_min(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StatisticalAnalysis:
"""A utility class that does some statistical analysis on a given object"""
def get_max(self, grocery, category):
"""(StatisticalAnalysis, GroceryStore, str) -> float returns the maximum product price of a given category"""
grocery_products = grocery.get_category_to_p... | the_stack_v2_python_sparse | Marzieh and Harrington's Practicals/product/product.py | bryan-ojay/csca08 | train | 0 |
213a90e54d97c7db15b4c9972c1dcb083ec0a937 | [
"self.data = data\nself.period_begin = period_beg\nself.period_end = period_end\nself.observations = []",
"increase = Increase(self.data.copy(deep=True), self.period_begin, self.period_end)\nincrease.analyse()\nself.observations.extend(increase.observations)\ndecrease = Decrease(self.data.copy(deep=True), self.pe... | <|body_start_0|>
self.data = data
self.period_begin = period_beg
self.period_end = period_end
self.observations = []
<|end_body_0|>
<|body_start_1|>
increase = Increase(self.data.copy(deep=True), self.period_begin, self.period_end)
increase.analyse()
self.observa... | A class for running the analysis over the given data. | Analyse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Analyse:
"""A class for running the analysis over the given data."""
def __init__(self, data, period_beg, period_end):
"""The init function. Args: data (pd.dataframe): The dataframe to be used for running the analysis period_beg (datetime.datetime): The datetime of the beginning of t... | stack_v2_sparse_classes_75kplus_train_065820 | 2,087 | no_license | [
{
"docstring": "The init function. Args: data (pd.dataframe): The dataframe to be used for running the analysis period_beg (datetime.datetime): The datetime of the beginning of the period period_end (datetime.datetime): The datetime of the end of the period",
"name": "__init__",
"signature": "def __init... | 4 | stack_v2_sparse_classes_30k_train_038918 | Implement the Python class `Analyse` described below.
Class description:
A class for running the analysis over the given data.
Method signatures and docstrings:
- def __init__(self, data, period_beg, period_end): The init function. Args: data (pd.dataframe): The dataframe to be used for running the analysis period_be... | Implement the Python class `Analyse` described below.
Class description:
A class for running the analysis over the given data.
Method signatures and docstrings:
- def __init__(self, data, period_beg, period_end): The init function. Args: data (pd.dataframe): The dataframe to be used for running the analysis period_be... | 5e62f96e541118ae924303b730f18d248022cac0 | <|skeleton|>
class Analyse:
"""A class for running the analysis over the given data."""
def __init__(self, data, period_beg, period_end):
"""The init function. Args: data (pd.dataframe): The dataframe to be used for running the analysis period_beg (datetime.datetime): The datetime of the beginning of t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Analyse:
"""A class for running the analysis over the given data."""
def __init__(self, data, period_beg, period_end):
"""The init function. Args: data (pd.dataframe): The dataframe to be used for running the analysis period_beg (datetime.datetime): The datetime of the beginning of the period per... | the_stack_v2_python_sparse | NLGengine/analyse.py | StanMey/Robotreporter | train | 3 |
fd8c34f609363a555db9d7d6a84b88c6e4b6c466 | [
"@lru_cache(None)\ndef dfs(curSum: int, visited: int) -> bool:\n if curSum >= target:\n return True\n for select in range(1, upper + 1):\n if visited >> select & 1:\n continue\n if curSum + select >= target or not dfs(curSum + select, visited | 1 << select):\n return... | <|body_start_0|>
@lru_cache(None)
def dfs(curSum: int, visited: int) -> bool:
if curSum >= target:
return True
for select in range(1, upper + 1):
if visited >> select & 1:
continue
if curSum + select >= target or... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canIWin(self, upper: int, target: int) -> bool:
"""2^n*n 每次dfs不用重新计算cur,因为curSum由visted唯一确定,两种的时间复杂度都是 O(2^n*n)"""
<|body_0|>
def canIWin2(self, upper: int, target: int) -> bool:
"""2^n*n 会慢一些"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_065821 | 1,839 | no_license | [
{
"docstring": "2^n*n 每次dfs不用重新计算cur,因为curSum由visted唯一确定,两种的时间复杂度都是 O(2^n*n)",
"name": "canIWin",
"signature": "def canIWin(self, upper: int, target: int) -> bool"
},
{
"docstring": "2^n*n 会慢一些",
"name": "canIWin2",
"signature": "def canIWin2(self, upper: int, target: int) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_029065 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canIWin(self, upper: int, target: int) -> bool: 2^n*n 每次dfs不用重新计算cur,因为curSum由visted唯一确定,两种的时间复杂度都是 O(2^n*n)
- def canIWin2(self, upper: int, target: int) -> bool: 2^n*n 会慢一些 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canIWin(self, upper: int, target: int) -> bool: 2^n*n 每次dfs不用重新计算cur,因为curSum由visted唯一确定,两种的时间复杂度都是 O(2^n*n)
- def canIWin2(self, upper: int, target: int) -> bool: 2^n*n 会慢一些... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def canIWin(self, upper: int, target: int) -> bool:
"""2^n*n 每次dfs不用重新计算cur,因为curSum由visted唯一确定,两种的时间复杂度都是 O(2^n*n)"""
<|body_0|>
def canIWin2(self, upper: int, target: int) -> bool:
"""2^n*n 会慢一些"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def canIWin(self, upper: int, target: int) -> bool:
"""2^n*n 每次dfs不用重新计算cur,因为curSum由visted唯一确定,两种的时间复杂度都是 O(2^n*n)"""
@lru_cache(None)
def dfs(curSum: int, visited: int) -> bool:
if curSum >= target:
return True
for select in range(1, ... | the_stack_v2_python_sparse | 11_动态规划/dp分类/状压dp/visited上携带参数/464. 我能赢吗.py | 981377660LMT/algorithm-study | train | 225 | |
3c875d131c594ef952aa23bbd6e2681ff12ba75d | [
"r = self.client.put('/api/search/', SEARCH_SEARVICE_AREA_OBJECT_SUCCESS, content_type='application/json')\nself.assertTrue(r.data['success'])\nself.assertEqual(r.status_code, status.HTTP_200_OK)",
"r = self.client.put('/api/search/', SEARCH_SEARVICE_AREA_OBJECT_FAILURE, content_type='application/json')\nself.ass... | <|body_start_0|>
r = self.client.put('/api/search/', SEARCH_SEARVICE_AREA_OBJECT_SUCCESS, content_type='application/json')
self.assertTrue(r.data['success'])
self.assertEqual(r.status_code, status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
r = self.client.put('/api/search/', SEARCH_SE... | SearchServiceArea | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchServiceArea:
def test_success(self):
"""Test Success"""
<|body_0|>
def test_failure(self):
"""Test Failure"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
r = self.client.put('/api/search/', SEARCH_SEARVICE_AREA_OBJECT_SUCCESS, content_type='a... | stack_v2_sparse_classes_75kplus_train_065822 | 11,905 | permissive | [
{
"docstring": "Test Success",
"name": "test_success",
"signature": "def test_success(self)"
},
{
"docstring": "Test Failure",
"name": "test_failure",
"signature": "def test_failure(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031420 | Implement the Python class `SearchServiceArea` described below.
Class description:
Implement the SearchServiceArea class.
Method signatures and docstrings:
- def test_success(self): Test Success
- def test_failure(self): Test Failure | Implement the Python class `SearchServiceArea` described below.
Class description:
Implement the SearchServiceArea class.
Method signatures and docstrings:
- def test_success(self): Test Success
- def test_failure(self): Test Failure
<|skeleton|>
class SearchServiceArea:
def test_success(self):
"""Test ... | c667e1bc2163ba49591e367bd5c882fe1b1f8df0 | <|skeleton|>
class SearchServiceArea:
def test_success(self):
"""Test Success"""
<|body_0|>
def test_failure(self):
"""Test Failure"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SearchServiceArea:
def test_success(self):
"""Test Success"""
r = self.client.put('/api/search/', SEARCH_SEARVICE_AREA_OBJECT_SUCCESS, content_type='application/json')
self.assertTrue(r.data['success'])
self.assertEqual(r.status_code, status.HTTP_200_OK)
def test_failure(s... | the_stack_v2_python_sparse | service_area/tests.py | jinayshah86/service-provider-locator | train | 0 | |
5246d142c7f1ed38fcf1314b844cf3d739d33b21 | [
"search_fail = 1\nfor i in range(n):\n if i in cols:\n pass\n else:\n temp_flag = 1\n for j in range(len(rows)):\n if abs(num - rows[j]) == abs(i - cols[j]):\n temp_flag = 0\n else:\n pass\n if temp_flag:\n search_fail ... | <|body_start_0|>
search_fail = 1
for i in range(n):
if i in cols:
pass
else:
temp_flag = 1
for j in range(len(rows)):
if abs(num - rows[j]) == abs(i - cols[j]):
temp_flag = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def iteration(self, n, num, rows, cols, final_rows, final_cols):
""":type n: int :rtype: List[List[str]]"""
<|body_0|>
def solveNQueens(self, n):
""":type n: int :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
searc... | stack_v2_sparse_classes_75kplus_train_065823 | 1,965 | no_license | [
{
"docstring": ":type n: int :rtype: List[List[str]]",
"name": "iteration",
"signature": "def iteration(self, n, num, rows, cols, final_rows, final_cols)"
},
{
"docstring": ":type n: int :rtype: List[List[str]]",
"name": "solveNQueens",
"signature": "def solveNQueens(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024452 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def iteration(self, n, num, rows, cols, final_rows, final_cols): :type n: int :rtype: List[List[str]]
- def solveNQueens(self, n): :type n: int :rtype: List[List[str]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def iteration(self, n, num, rows, cols, final_rows, final_cols): :type n: int :rtype: List[List[str]]
- def solveNQueens(self, n): :type n: int :rtype: List[List[str]]
<|skeleto... | b1ce588fc256b9a0a5d680f38be1e5dd0a9b087d | <|skeleton|>
class Solution:
def iteration(self, n, num, rows, cols, final_rows, final_cols):
""":type n: int :rtype: List[List[str]]"""
<|body_0|>
def solveNQueens(self, n):
""":type n: int :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def iteration(self, n, num, rows, cols, final_rows, final_cols):
""":type n: int :rtype: List[List[str]]"""
search_fail = 1
for i in range(n):
if i in cols:
pass
else:
temp_flag = 1
for j in range(len(row... | the_stack_v2_python_sparse | 51_N-Queens.py | LiJiaqi96/Play-with-Leetcode | train | 0 | |
163337103a3d53ae6c36cf906a3bcb6aa2facd18 | [
"self.head = Node(None)\nself.last = self.head\nself.dic = dict()\nself.capacity = capacity",
"if key in self.dic:\n if self.last is not self.dic[key][1]:\n self.dic[key][1].pre.next = self.dic[key][1].next\n self.dic[key][1].next.pre = self.dic[key][1].pre\n self.last.next = self.dic[key]... | <|body_start_0|>
self.head = Node(None)
self.last = self.head
self.dic = dict()
self.capacity = capacity
<|end_body_0|>
<|body_start_1|>
if key in self.dic:
if self.last is not self.dic[key][1]:
self.dic[key][1].pre.next = self.dic[key][1].next
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_065824 | 3,225 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_046939 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | c82d375f8d9d4feeaba243eb5c990c1ba3ec73d2 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.head = Node(None)
self.last = self.head
self.dic = dict()
self.capacity = capacity
def get(self, key):
""":type key: int :rtype: int"""
if key in self.dic:
if self.la... | the_stack_v2_python_sparse | 146_LRU.py | 0as1s/leetcode | train | 0 | |
8930e7e3c92f4a32b27f51ca43f124040bf5c7f4 | [
"try:\n if request.user.role.name == 'Customer':\n serializer = CustomerSerializer(Customer.objects.get(email=request.user.email))\n elif request.user.role.name in ['Coach Manager', 'Head Coach']:\n serializer = CoachUserSerializer(Coach.objects.get(email=request.user.email))\n elif request.u... | <|body_start_0|>
try:
if request.user.role.name == 'Customer':
serializer = CustomerSerializer(Customer.objects.get(email=request.user.email))
elif request.user.role.name in ['Coach Manager', 'Head Coach']:
serializer = CoachUserSerializer(Coach.objects.ge... | RegistrationDataView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationDataView:
def get(self, request):
"""get profile data"""
<|body_0|>
def post(self, request):
"""Update user data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
if request.user.role.name == 'Customer':
se... | stack_v2_sparse_classes_75kplus_train_065825 | 13,372 | no_license | [
{
"docstring": "get profile data",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Update user data",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | null | Implement the Python class `RegistrationDataView` described below.
Class description:
Implement the RegistrationDataView class.
Method signatures and docstrings:
- def get(self, request): get profile data
- def post(self, request): Update user data | Implement the Python class `RegistrationDataView` described below.
Class description:
Implement the RegistrationDataView class.
Method signatures and docstrings:
- def get(self, request): get profile data
- def post(self, request): Update user data
<|skeleton|>
class RegistrationDataView:
def get(self, request)... | 367cccca72f0eae6c3ccb70fabb371dc905f915e | <|skeleton|>
class RegistrationDataView:
def get(self, request):
"""get profile data"""
<|body_0|>
def post(self, request):
"""Update user data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegistrationDataView:
def get(self, request):
"""get profile data"""
try:
if request.user.role.name == 'Customer':
serializer = CustomerSerializer(Customer.objects.get(email=request.user.email))
elif request.user.role.name in ['Coach Manager', 'Head Coac... | the_stack_v2_python_sparse | customer/views/profile_view.py | vshaladhav97/first_kick | train | 0 | |
0361320c7de07ad261f2fea08a05f3f5cb605d02 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | FederatedLearningServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FederatedLearningServicer:
"""Missing associated documentation comment in .proto file."""
def GetJob(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def GetTensorRecord(self, request, context):
"""Missing associa... | stack_v2_sparse_classes_75kplus_train_065826 | 7,291 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetJob",
"signature": "def GetJob(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetTensorRecord",
"signature": "def GetTensorRecord(self, ... | 4 | stack_v2_sparse_classes_30k_train_017111 | Implement the Python class `FederatedLearningServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetJob(self, request, context): Missing associated documentation comment in .proto file.
- def GetTensorRecord(self, request, cont... | Implement the Python class `FederatedLearningServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetJob(self, request, context): Missing associated documentation comment in .proto file.
- def GetTensorRecord(self, request, cont... | 1223619661f82733b5d66f8901cac7f16002c610 | <|skeleton|>
class FederatedLearningServicer:
"""Missing associated documentation comment in .proto file."""
def GetJob(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def GetTensorRecord(self, request, context):
"""Missing associa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FederatedLearningServicer:
"""Missing associated documentation comment in .proto file."""
def GetJob(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!... | the_stack_v2_python_sparse | src/appfl/protos/federated_learning_pb2_grpc.py | APPFL/APPFL | train | 39 |
5716191e2f070ef8397849ff602a1cfa6936bdb1 | [
"data = []\nwith open(file_path, '-r') as f:\n dict_data = json.load(f.read())\n for i in dict_data:\n data.append(tuple(i.values()))\nreturn data",
"page = Home_page(browser)\npage.get(StaticConfig.pchome_url)\nif page.monetate_icon is True:\n page.monetate_icon.click()\nelse:\n pass\npage.sea... | <|body_start_0|>
data = []
with open(file_path, '-r') as f:
dict_data = json.load(f.read())
for i in dict_data:
data.append(tuple(i.values()))
return data
<|end_body_0|>
<|body_start_1|>
page = Home_page(browser)
page.get(StaticConfig.pcho... | 搜索测试 | Test_Search | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_Search:
"""搜索测试"""
def get_data(self, file_path):
"""读取参数化文件"""
<|body_0|>
def test_1search_key_word(self, name, key_words, browser):
"""首页关键字搜索"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = []
with open(file_path, '-r') as... | stack_v2_sparse_classes_75kplus_train_065827 | 1,360 | no_license | [
{
"docstring": "读取参数化文件",
"name": "get_data",
"signature": "def get_data(self, file_path)"
},
{
"docstring": "首页关键字搜索",
"name": "test_1search_key_word",
"signature": "def test_1search_key_word(self, name, key_words, browser)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003314 | Implement the Python class `Test_Search` described below.
Class description:
搜索测试
Method signatures and docstrings:
- def get_data(self, file_path): 读取参数化文件
- def test_1search_key_word(self, name, key_words, browser): 首页关键字搜索 | Implement the Python class `Test_Search` described below.
Class description:
搜索测试
Method signatures and docstrings:
- def get_data(self, file_path): 读取参数化文件
- def test_1search_key_word(self, name, key_words, browser): 首页关键字搜索
<|skeleton|>
class Test_Search:
"""搜索测试"""
def get_data(self, file_path):
... | 567836fc9aebcc67acb2816364ba89ffa8d356db | <|skeleton|>
class Test_Search:
"""搜索测试"""
def get_data(self, file_path):
"""读取参数化文件"""
<|body_0|>
def test_1search_key_word(self, name, key_words, browser):
"""首页关键字搜索"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_Search:
"""搜索测试"""
def get_data(self, file_path):
"""读取参数化文件"""
data = []
with open(file_path, '-r') as f:
dict_data = json.load(f.read())
for i in dict_data:
data.append(tuple(i.values()))
return data
def test_1search_key_... | the_stack_v2_python_sparse | pytestFrame/test_case/test_pczh/test_mainsteam.py | JasonTang7/inspiration | train | 0 |
3e0565af8f5a79dc390eaf4f4cd97d50de9dd3f9 | [
"transactions_to_include = cast(list[str], self._parameter('transactions_to_include'))\ntransactions_to_ignore = cast(list[str], self._parameter('transactions_to_ignore'))\ncounts = dict(failed=0, success=0)\nfor response in responses:\n count = await self.__parse_response(response, transactions_to_include, tran... | <|body_start_0|>
transactions_to_include = cast(list[str], self._parameter('transactions_to_include'))
transactions_to_ignore = cast(list[str], self._parameter('transactions_to_ignore'))
counts = dict(failed=0, success=0)
for response in responses:
count = await self.__parse_... | Collector for the number of performance test transactions. | PerformanceTestRunnerTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PerformanceTestRunnerTests:
"""Collector for the number of performance test transactions."""
async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement:
"""Override to parse the transactions from the responses and return the transactions with the desired... | stack_v2_sparse_classes_75kplus_train_065828 | 2,267 | permissive | [
{
"docstring": "Override to parse the transactions from the responses and return the transactions with the desired status.",
"name": "_parse_source_responses",
"signature": "async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement"
},
{
"docstring": "Parse the tra... | 2 | stack_v2_sparse_classes_30k_train_050122 | Implement the Python class `PerformanceTestRunnerTests` described below.
Class description:
Collector for the number of performance test transactions.
Method signatures and docstrings:
- async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement: Override to parse the transactions from t... | Implement the Python class `PerformanceTestRunnerTests` described below.
Class description:
Collector for the number of performance test transactions.
Method signatures and docstrings:
- async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement: Override to parse the transactions from t... | 602b6970e5d9088cb89cc6d488337349e54e1c9a | <|skeleton|>
class PerformanceTestRunnerTests:
"""Collector for the number of performance test transactions."""
async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement:
"""Override to parse the transactions from the responses and return the transactions with the desired... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PerformanceTestRunnerTests:
"""Collector for the number of performance test transactions."""
async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement:
"""Override to parse the transactions from the responses and return the transactions with the desired status."""
... | the_stack_v2_python_sparse | components/collector/src/source_collectors/performancetest_runner/tests.py | Erik-Stel/quality-time | train | 0 |
7c9c7c0f46469cd613145f619274e4bf3ddfa473 | [
"self.image_pause_not_mouseover = pygame.image.load('images/pause_not_mouseover.png')\nself.image_pause_mouseover = pygame.image.load('images/pause_mouseover.png')\nself.image_resume_not_mouseover = pygame.image.load('images/resume_not_mouseover.png')\nself.image_resume_mouseover = pygame.image.load('images/resume_... | <|body_start_0|>
self.image_pause_not_mouseover = pygame.image.load('images/pause_not_mouseover.png')
self.image_pause_mouseover = pygame.image.load('images/pause_mouseover.png')
self.image_resume_not_mouseover = pygame.image.load('images/resume_not_mouseover.png')
self.image_resume_mous... | 暂停按钮类 | PauseButton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PauseButton:
"""暂停按钮类"""
def __init__(self, window):
"""初始化暂停按钮"""
<|body_0|>
def switch_image(self, event):
"""切换暂停按钮的图片"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.image_pause_not_mouseover = pygame.image.load('images/pause_not_mouseo... | stack_v2_sparse_classes_75kplus_train_065829 | 2,550 | no_license | [
{
"docstring": "初始化暂停按钮",
"name": "__init__",
"signature": "def __init__(self, window)"
},
{
"docstring": "切换暂停按钮的图片",
"name": "switch_image",
"signature": "def switch_image(self, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010324 | Implement the Python class `PauseButton` described below.
Class description:
暂停按钮类
Method signatures and docstrings:
- def __init__(self, window): 初始化暂停按钮
- def switch_image(self, event): 切换暂停按钮的图片 | Implement the Python class `PauseButton` described below.
Class description:
暂停按钮类
Method signatures and docstrings:
- def __init__(self, window): 初始化暂停按钮
- def switch_image(self, event): 切换暂停按钮的图片
<|skeleton|>
class PauseButton:
"""暂停按钮类"""
def __init__(self, window):
"""初始化暂停按钮"""
<|body_0... | 66f7f801e1395207778484e1543ea26309d4b354 | <|skeleton|>
class PauseButton:
"""暂停按钮类"""
def __init__(self, window):
"""初始化暂停按钮"""
<|body_0|>
def switch_image(self, event):
"""切换暂停按钮的图片"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PauseButton:
"""暂停按钮类"""
def __init__(self, window):
"""初始化暂停按钮"""
self.image_pause_not_mouseover = pygame.image.load('images/pause_not_mouseover.png')
self.image_pause_mouseover = pygame.image.load('images/pause_mouseover.png')
self.image_resume_not_mouseover = pygame.ima... | the_stack_v2_python_sparse | python/practise/PlaneWar/pause_button.py | anzhihe/learning | train | 1,443 |
da1d0770a5ac15ff0003879059628c7aea0babc3 | [
"balance_after = self.oracle_db_lib().execute_sql(DbVar.SELECT_BALANCE.format(msisdn=sub_out['MSISDN']))[0]['BALANCE']\nif balance_before - int(tariff) * int(duration) == balance_after:\n return True\nelse:\n return False",
"start_date = datetime.strptime(call_history['START_DATE'], '%Y-%m-%dT%H:%M:%S')\nen... | <|body_start_0|>
balance_after = self.oracle_db_lib().execute_sql(DbVar.SELECT_BALANCE.format(msisdn=sub_out['MSISDN']))[0]['BALANCE']
if balance_before - int(tariff) * int(duration) == balance_after:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
... | Check | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Check:
def is_check_balance_sub_out(self, sub_out, balance_before, tariff, duration):
"""Проверка списания средств за исходящий звонок. Args: sub_out: Данные абонента, совершающего звонок. balance_before: Баланс абонента до совершения звонка. tariff: Стоимость минуты вызова. duration: Дл... | stack_v2_sparse_classes_75kplus_train_065830 | 3,465 | no_license | [
{
"docstring": "Проверка списания средств за исходящий звонок. Args: sub_out: Данные абонента, совершающего звонок. balance_before: Баланс абонента до совершения звонка. tariff: Стоимость минуты вызова. duration: Длительность вызова в минутах. Returns: True/False при верном/не верном списании.",
"name": "is... | 2 | stack_v2_sparse_classes_30k_train_003646 | Implement the Python class `Check` described below.
Class description:
Implement the Check class.
Method signatures and docstrings:
- def is_check_balance_sub_out(self, sub_out, balance_before, tariff, duration): Проверка списания средств за исходящий звонок. Args: sub_out: Данные абонента, совершающего звонок. balan... | Implement the Python class `Check` described below.
Class description:
Implement the Check class.
Method signatures and docstrings:
- def is_check_balance_sub_out(self, sub_out, balance_before, tariff, duration): Проверка списания средств за исходящий звонок. Args: sub_out: Данные абонента, совершающего звонок. balan... | 59cdd1f8af3bb43150f4844c1c0ef56c8523afd5 | <|skeleton|>
class Check:
def is_check_balance_sub_out(self, sub_out, balance_before, tariff, duration):
"""Проверка списания средств за исходящий звонок. Args: sub_out: Данные абонента, совершающего звонок. balance_before: Баланс абонента до совершения звонка. tariff: Стоимость минуты вызова. duration: Дл... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Check:
def is_check_balance_sub_out(self, sub_out, balance_before, tariff, duration):
"""Проверка списания средств за исходящий звонок. Args: sub_out: Данные абонента, совершающего звонок. balance_before: Баланс абонента до совершения звонка. tariff: Стоимость минуты вызова. duration: Длительность выз... | the_stack_v2_python_sparse | library/application/db/Check.py | malyura/Task3 | train | 0 | |
5de1527ca426dcf624f23d6cc5abbc0b27f35a71 | [
"if not num:\n return '0'\nhard_code = 4294967295\nif num < 0:\n num = abs(num)\n num = hard_code ^ num\n num += 1\nres = ''\nwhile num:\n res = hex_map[num % 16] + res\n num = num / 16\nreturn res.lstrip('0')",
"flag = False\nif num < 0:\n flag = True\n num = -num\nh = ''\nwhile num:\n ... | <|body_start_0|>
if not num:
return '0'
hard_code = 4294967295
if num < 0:
num = abs(num)
num = hard_code ^ num
num += 1
res = ''
while num:
res = hex_map[num % 16] + res
num = num / 16
return res.lst... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def toHex(self, num):
""":type num: int :rtype: str"""
<|body_0|>
def _toHex(self, num):
""":type num: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not num:
return '0'
hard_code = 4294967295
... | stack_v2_sparse_classes_75kplus_train_065831 | 2,454 | permissive | [
{
"docstring": ":type num: int :rtype: str",
"name": "toHex",
"signature": "def toHex(self, num)"
},
{
"docstring": ":type num: int :rtype: str",
"name": "_toHex",
"signature": "def _toHex(self, num)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020060 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def toHex(self, num): :type num: int :rtype: str
- def _toHex(self, num): :type num: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def toHex(self, num): :type num: int :rtype: str
- def _toHex(self, num): :type num: int :rtype: str
<|skeleton|>
class Solution:
def toHex(self, num):
""":type num... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def toHex(self, num):
""":type num: int :rtype: str"""
<|body_0|>
def _toHex(self, num):
""":type num: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def toHex(self, num):
""":type num: int :rtype: str"""
if not num:
return '0'
hard_code = 4294967295
if num < 0:
num = abs(num)
num = hard_code ^ num
num += 1
res = ''
while num:
res = hex_map... | the_stack_v2_python_sparse | 405.convert-a-number-to-hexadecimal.py | windard/leeeeee | train | 0 | |
d467ffa0d89c676f0953d514242778c7a87a35b9 | [
"try:\n resource_id = UUID(resource_id)\nexcept ValueError:\n raise Http404()\nresources = handler_get_request(request, dataset_name)\nfor resource in resources:\n if resource.ckan_id == resource_id:\n return JsonResponse(serialize(resource), safe=True)\nraise Http404()",
"request.PUT, request._fi... | <|body_start_0|>
try:
resource_id = UUID(resource_id)
except ValueError:
raise Http404()
resources = handler_get_request(request, dataset_name)
for resource in resources:
if resource.ckan_id == resource_id:
return JsonResponse(serialize... | ResourceShow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceShow:
def get(self, request, dataset_name, resource_id):
"""Voir la ressource."""
<|body_0|>
def put(self, request, dataset_name, resource_id):
"""Modifier la ressource."""
<|body_1|>
def delete(self, request, dataset_name, resource_id):
... | stack_v2_sparse_classes_75kplus_train_065832 | 11,508 | permissive | [
{
"docstring": "Voir la ressource.",
"name": "get",
"signature": "def get(self, request, dataset_name, resource_id)"
},
{
"docstring": "Modifier la ressource.",
"name": "put",
"signature": "def put(self, request, dataset_name, resource_id)"
},
{
"docstring": "Supprimer la ressour... | 3 | stack_v2_sparse_classes_30k_train_001512 | Implement the Python class `ResourceShow` described below.
Class description:
Implement the ResourceShow class.
Method signatures and docstrings:
- def get(self, request, dataset_name, resource_id): Voir la ressource.
- def put(self, request, dataset_name, resource_id): Modifier la ressource.
- def delete(self, reque... | Implement the Python class `ResourceShow` described below.
Class description:
Implement the ResourceShow class.
Method signatures and docstrings:
- def get(self, request, dataset_name, resource_id): Voir la ressource.
- def put(self, request, dataset_name, resource_id): Modifier la ressource.
- def delete(self, reque... | c73e67f22fa9bb38577c286271d02c2d9a708e40 | <|skeleton|>
class ResourceShow:
def get(self, request, dataset_name, resource_id):
"""Voir la ressource."""
<|body_0|>
def put(self, request, dataset_name, resource_id):
"""Modifier la ressource."""
<|body_1|>
def delete(self, request, dataset_name, resource_id):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResourceShow:
def get(self, request, dataset_name, resource_id):
"""Voir la ressource."""
try:
resource_id = UUID(resource_id)
except ValueError:
raise Http404()
resources = handler_get_request(request, dataset_name)
for resource in resources:
... | the_stack_v2_python_sparse | api/views/resource.py | DataSud/DataSud-2017-2019 | train | 1 | |
5a0c8bd06ef9e1de63baff9c166389d221796e1c | [
"for param in params:\n if param not in self.__info__['space']:\n print('Error: not supported parameters {}'.format(param))\nif self.dataset_type == PROBLEM.CLASSIFICATION:\n model = RandomForestClassifier(n_estimators=int(params['Num estimators']), max_depth=int(params['Max depth']), max_features=int(... | <|body_start_0|>
for param in params:
if param not in self.__info__['space']:
print('Error: not supported parameters {}'.format(param))
if self.dataset_type == PROBLEM.CLASSIFICATION:
model = RandomForestClassifier(n_estimators=int(params['Num estimators']), max_d... | Parameter accepted: - n_estimators: number of trees in the forest. - max_depth: maximum depth of the trees - max_features: number of features to consider when looking for a split - min_split: the minimum number of samples to split an internal node | RandomForest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomForest:
"""Parameter accepted: - n_estimators: number of trees in the forest. - max_depth: maximum depth of the trees - max_features: number of features to consider when looking for a split - min_split: the minimum number of samples to split an internal node"""
def train(self, params):... | stack_v2_sparse_classes_75kplus_train_065833 | 3,549 | no_license | [
{
"docstring": "Train the model with the given hyper-parameters. Args: :param params: dictionary of hyper-parameters. :return: trained model.",
"name": "train",
"signature": "def train(self, params)"
},
{
"docstring": "Classify the test set of the chosen dataset and produce the result correspond... | 2 | stack_v2_sparse_classes_30k_val_002569 | Implement the Python class `RandomForest` described below.
Class description:
Parameter accepted: - n_estimators: number of trees in the forest. - max_depth: maximum depth of the trees - max_features: number of features to consider when looking for a split - min_split: the minimum number of samples to split an interna... | Implement the Python class `RandomForest` described below.
Class description:
Parameter accepted: - n_estimators: number of trees in the forest. - max_depth: maximum depth of the trees - max_features: number of features to consider when looking for a split - min_split: the minimum number of samples to split an interna... | 27f861c09615aedfd96cffdebf7d9653f72b4d7b | <|skeleton|>
class RandomForest:
"""Parameter accepted: - n_estimators: number of trees in the forest. - max_depth: maximum depth of the trees - max_features: number of features to consider when looking for a split - min_split: the minimum number of samples to split an internal node"""
def train(self, params):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomForest:
"""Parameter accepted: - n_estimators: number of trees in the forest. - max_depth: maximum depth of the trees - max_features: number of features to consider when looking for a split - min_split: the minimum number of samples to split an internal node"""
def train(self, params):
"""T... | the_stack_v2_python_sparse | API/Metrics/RandomForest.py | AndreaCorsini1/Ahmet | train | 1 |
3e457d361a5fb776d738868cee7524937b147789 | [
"self.config = config\nself.train_transform = None\nself.test_transform = None\nself.contrastive_transforms = None\nself.train_dataset = None\nself.test_dataset = None\nself.get_transforms()\nself.load_dataset()",
"train_transforms = self.config.cfg['dataloader']['transforms']['train']\ntest_transforms = self.con... | <|body_start_0|>
self.config = config
self.train_transform = None
self.test_transform = None
self.contrastive_transforms = None
self.train_dataset = None
self.test_dataset = None
self.get_transforms()
self.load_dataset()
<|end_body_0|>
<|body_start_1|>
... | The class defines the flow of loading the dataloaders for CUB-200-2011 dataset for contrastive SSL training. | Cub2002011Contrastive | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cub2002011Contrastive:
"""The class defines the flow of loading the dataloaders for CUB-200-2011 dataset for contrastive SSL training."""
def __init__(self, config):
"""Constructor, the function parse the configuration parameters and load the CUB_200_2011 dataset. :param config: Conf... | stack_v2_sparse_classes_75kplus_train_065834 | 5,001 | permissive | [
{
"docstring": "Constructor, the function parse the configuration parameters and load the CUB_200_2011 dataset. :param config: Configuration class object",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "The function reads the train and test transformations speci... | 4 | stack_v2_sparse_classes_30k_train_003360 | Implement the Python class `Cub2002011Contrastive` described below.
Class description:
The class defines the flow of loading the dataloaders for CUB-200-2011 dataset for contrastive SSL training.
Method signatures and docstrings:
- def __init__(self, config): Constructor, the function parse the configuration paramete... | Implement the Python class `Cub2002011Contrastive` described below.
Class description:
The class defines the flow of loading the dataloaders for CUB-200-2011 dataset for contrastive SSL training.
Method signatures and docstrings:
- def __init__(self, config): Constructor, the function parse the configuration paramete... | 9a4bf0a112b818caca8794868a903dc736839a43 | <|skeleton|>
class Cub2002011Contrastive:
"""The class defines the flow of loading the dataloaders for CUB-200-2011 dataset for contrastive SSL training."""
def __init__(self, config):
"""Constructor, the function parse the configuration parameters and load the CUB_200_2011 dataset. :param config: Conf... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cub2002011Contrastive:
"""The class defines the flow of loading the dataloaders for CUB-200-2011 dataset for contrastive SSL training."""
def __init__(self, config):
"""Constructor, the function parse the configuration parameters and load the CUB_200_2011 dataset. :param config: Configuration cla... | the_stack_v2_python_sparse | dataloader/cub_200_2011_contrastive.py | Niousha12/ssl_for_fgvc | train | 0 |
e9330b98bdbe5f9c2bc7d18e804baa8c47687ecc | [
"mime_type = flask.request.args['mime_type']\nupload_path = 'quests/%s/%s' % (quest_id, file_name)\nreturn s3.s3_upload_signature(upload_path, mime_type)",
"bucket = s3.get_bucket()\nkey = 'quests/%s/%s' % (quest_id, file_name)\nbucket.delete_key(key)"
] | <|body_start_0|>
mime_type = flask.request.args['mime_type']
upload_path = 'quests/%s/%s' % (quest_id, file_name)
return s3.s3_upload_signature(upload_path, mime_type)
<|end_body_0|>
<|body_start_1|>
bucket = s3.get_bucket()
key = 'quests/%s/%s' % (quest_id, file_name)
b... | Handle individual assets attached to a quest. | QuestStaticAsset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestStaticAsset:
"""Handle individual assets attached to a quest."""
def get(quest_id, file_name):
"""Return a signed request to upload the given file name to the given quest and the URL for the resource upon its upload."""
<|body_0|>
def delete(quest_id, file_name):
... | stack_v2_sparse_classes_75kplus_train_065835 | 6,641 | no_license | [
{
"docstring": "Return a signed request to upload the given file name to the given quest and the URL for the resource upon its upload.",
"name": "get",
"signature": "def get(quest_id, file_name)"
},
{
"docstring": "Delete the given asset.",
"name": "delete",
"signature": "def delete(ques... | 2 | null | Implement the Python class `QuestStaticAsset` described below.
Class description:
Handle individual assets attached to a quest.
Method signatures and docstrings:
- def get(quest_id, file_name): Return a signed request to upload the given file name to the given quest and the URL for the resource upon its upload.
- def... | Implement the Python class `QuestStaticAsset` described below.
Class description:
Handle individual assets attached to a quest.
Method signatures and docstrings:
- def get(quest_id, file_name): Return a signed request to upload the given file name to the given quest and the URL for the resource upon its upload.
- def... | 00cfe84a44c7410ba3985adcc073be083a4bc27e | <|skeleton|>
class QuestStaticAsset:
"""Handle individual assets attached to a quest."""
def get(quest_id, file_name):
"""Return a signed request to upload the given file name to the given quest and the URL for the resource upon its upload."""
<|body_0|>
def delete(quest_id, file_name):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuestStaticAsset:
"""Handle individual assets attached to a quest."""
def get(quest_id, file_name):
"""Return a signed request to upload the given file name to the given quest and the URL for the resource upon its upload."""
mime_type = flask.request.args['mime_type']
upload_path ... | the_stack_v2_python_sparse | backend/src/backend/quests/views.py | freedomgames/Planet-Lab | train | 6 |
341d8807eb407681ac4a7202b209f63a5642d24b | [
"super().__init__()\nself.message_function = SchnetMessageFunction(node_size, edge_size)\nself.state_transition_function = nn.Sequential(nn.Linear(node_size, node_size), ShiftedSoftplus(), nn.Linear(node_size, node_size))",
"nodes = node_state[edges[:, 0]]\nmessages = self.message_function(nodes, edge_state)\nmes... | <|body_start_0|>
super().__init__()
self.message_function = SchnetMessageFunction(node_size, edge_size)
self.state_transition_function = nn.Sequential(nn.Linear(node_size, node_size), ShiftedSoftplus(), nn.Linear(node_size, node_size))
<|end_body_0|>
<|body_start_1|>
nodes = node_state[... | Interaction network | Interaction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interaction:
"""Interaction network"""
def __init__(self, node_size, edge_size):
"""Args: node_size (int): Size of node state edge_size (int): Size of edge state"""
<|body_0|>
def forward(self, node_state, edges, edge_state):
"""Args: node_state (tensor): Node st... | stack_v2_sparse_classes_75kplus_train_065836 | 7,647 | no_license | [
{
"docstring": "Args: node_size (int): Size of node state edge_size (int): Size of edge state",
"name": "__init__",
"signature": "def __init__(self, node_size, edge_size)"
},
{
"docstring": "Args: node_state (tensor): Node states (num_nodes, node_size) edges (tensor): Directed edges with node in... | 2 | stack_v2_sparse_classes_30k_train_012223 | Implement the Python class `Interaction` described below.
Class description:
Interaction network
Method signatures and docstrings:
- def __init__(self, node_size, edge_size): Args: node_size (int): Size of node state edge_size (int): Size of edge state
- def forward(self, node_state, edges, edge_state): Args: node_st... | Implement the Python class `Interaction` described below.
Class description:
Interaction network
Method signatures and docstrings:
- def __init__(self, node_size, edge_size): Args: node_size (int): Size of node state edge_size (int): Size of edge state
- def forward(self, node_state, edges, edge_state): Args: node_st... | 117b1898d389b4b1727f0531c1f7eb827384f5c8 | <|skeleton|>
class Interaction:
"""Interaction network"""
def __init__(self, node_size, edge_size):
"""Args: node_size (int): Size of node state edge_size (int): Size of edge state"""
<|body_0|>
def forward(self, node_state, edges, edge_state):
"""Args: node_state (tensor): Node st... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Interaction:
"""Interaction network"""
def __init__(self, node_size, edge_size):
"""Args: node_size (int): Size of node state edge_size (int): Size of edge state"""
super().__init__()
self.message_function = SchnetMessageFunction(node_size, edge_size)
self.state_transition... | the_stack_v2_python_sparse | models/layer.py | bhastrup/RL-on-energy-surfaces | train | 0 |
bcc44a2caa5cdf2bc494cc3a36a8f3a235a34e45 | [
"electric_appliance = ElectricAppliances('1', '2', '3', '4', '5', '6')\nself.assertIsNotNone(electric_appliance.product_code)\nself.assertIsNotNone(electric_appliance.description)\nself.assertIsNotNone(electric_appliance.market_price)\nself.assertIsNotNone(electric_appliance.rental_price)\nself.assertIsNotNone(elec... | <|body_start_0|>
electric_appliance = ElectricAppliances('1', '2', '3', '4', '5', '6')
self.assertIsNotNone(electric_appliance.product_code)
self.assertIsNotNone(electric_appliance.description)
self.assertIsNotNone(electric_appliance.market_price)
self.assertIsNotNone(electric_ap... | Contains unit tests for ElectricAppliances.py Class | TestElectricAppliancesClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestElectricAppliancesClass:
"""Contains unit tests for ElectricAppliances.py Class"""
def test_initializer(self):
"""Tests the initializer of the Inventory class. Verifies classes attributes are filled when class is instantiated. :return: None"""
<|body_0|>
def test_ret... | stack_v2_sparse_classes_75kplus_train_065837 | 6,045 | no_license | [
{
"docstring": "Tests the initializer of the Inventory class. Verifies classes attributes are filled when class is instantiated. :return: None",
"name": "test_initializer",
"signature": "def test_initializer(self)"
},
{
"docstring": "Tests the return as dictionary method of the electric applianc... | 2 | null | Implement the Python class `TestElectricAppliancesClass` described below.
Class description:
Contains unit tests for ElectricAppliances.py Class
Method signatures and docstrings:
- def test_initializer(self): Tests the initializer of the Inventory class. Verifies classes attributes are filled when class is instantiat... | Implement the Python class `TestElectricAppliancesClass` described below.
Class description:
Contains unit tests for ElectricAppliances.py Class
Method signatures and docstrings:
- def test_initializer(self): Tests the initializer of the Inventory class. Verifies classes attributes are filled when class is instantiat... | 46d6282518f02029a556e94e607612a47daf675a | <|skeleton|>
class TestElectricAppliancesClass:
"""Contains unit tests for ElectricAppliances.py Class"""
def test_initializer(self):
"""Tests the initializer of the Inventory class. Verifies classes attributes are filled when class is instantiated. :return: None"""
<|body_0|>
def test_ret... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestElectricAppliancesClass:
"""Contains unit tests for ElectricAppliances.py Class"""
def test_initializer(self):
"""Tests the initializer of the Inventory class. Verifies classes attributes are filled when class is instantiated. :return: None"""
electric_appliance = ElectricAppliances('... | the_stack_v2_python_sparse | students/KyleCreek/lesson01/assignment/test_unit.py | Washirican/Python220A_2019 | train | 2 |
5cb3c9e1b70a1229780162308f977b12230bcb72 | [
"if len(triangle) == 1:\n return triangle[0][0]\ntriangle[1][0] = triangle[0][0] + triangle[1][0]\ntriangle[1][1] = triangle[0][0] + triangle[1][1]\nfor i in range(2, len(triangle)):\n for j in range(len(triangle[i])):\n if j == 0:\n triangle[i][j] = triangle[i - 1][j] + triangle[i][j]\n ... | <|body_start_0|>
if len(triangle) == 1:
return triangle[0][0]
triangle[1][0] = triangle[0][0] + triangle[1][0]
triangle[1][1] = triangle[0][0] + triangle[1][1]
for i in range(2, len(triangle)):
for j in range(len(triangle[i])):
if j == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int 自顶向下"""
<|body_0|>
def minimumTotal2(self, triangle):
""":type triangle: List[List[int]] :rtype: int 自底向上"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if l... | stack_v2_sparse_classes_75kplus_train_065838 | 1,395 | no_license | [
{
"docstring": ":type triangle: List[List[int]] :rtype: int 自顶向下",
"name": "minimumTotal",
"signature": "def minimumTotal(self, triangle)"
},
{
"docstring": ":type triangle: List[List[int]] :rtype: int 自底向上",
"name": "minimumTotal2",
"signature": "def minimumTotal2(self, triangle)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042258 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int 自顶向下
- def minimumTotal2(self, triangle): :type triangle: List[List[int]] :rtype: int 自底向上 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int 自顶向下
- def minimumTotal2(self, triangle): :type triangle: List[List[int]] :rtype: int 自底向上
<|skelet... | 013f6f222c6c2a617787b258f8a37003a9f51526 | <|skeleton|>
class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int 自顶向下"""
<|body_0|>
def minimumTotal2(self, triangle):
""":type triangle: List[List[int]] :rtype: int 自底向上"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int 自顶向下"""
if len(triangle) == 1:
return triangle[0][0]
triangle[1][0] = triangle[0][0] + triangle[1][0]
triangle[1][1] = triangle[0][0] + triangle[1][1]
for i in range(2... | the_stack_v2_python_sparse | dp/minimum_total.py | terrifyzhao/leetcode | train | 0 | |
71938574137ab9b0df5c1b16301b1795a23a8fea | [
"if self.master:\n if hasattr(self.master, 'notify_task'):\n self.master.notify_task(_task, _progress)\n else:\n print(self.__class__.__name__ + ': Internal deficiency, ' + self.master.__class__.__name__ + ' should have a notify_task function\\nTask:\\n' + _task + '\\n' + str(_progress))\nelse:\... | <|body_start_0|>
if self.master:
if hasattr(self.master, 'notify_task'):
self.master.notify_task(_task, _progress)
else:
print(self.__class__.__name__ + ': Internal deficiency, ' + self.master.__class__.__name__ + ' should have a notify_task function\nTask... | This class introduces all properties that a frame in BPM tools should hold. | BPMFrame | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BPMFrame:
"""This class introduces all properties that a frame in BPM tools should hold."""
def notify_task(self, _task, _progress):
"""This function checks if the master widget has a notify_task function, and if so, calls it. This way, notifications travel upwards in the widget stru... | stack_v2_sparse_classes_75kplus_train_065839 | 11,721 | permissive | [
{
"docstring": "This function checks if the master widget has a notify_task function, and if so, calls it. This way, notifications travel upwards in the widget structure until someone has a notify_task that's different. See the main_tk_replicator.ReplicatorMain for an example, :param _task: Text that defines th... | 2 | stack_v2_sparse_classes_30k_train_020847 | Implement the Python class `BPMFrame` described below.
Class description:
This class introduces all properties that a frame in BPM tools should hold.
Method signatures and docstrings:
- def notify_task(self, _task, _progress): This function checks if the master widget has a notify_task function, and if so, calls it. ... | Implement the Python class `BPMFrame` described below.
Class description:
This class introduces all properties that a frame in BPM tools should hold.
Method signatures and docstrings:
- def notify_task(self, _task, _progress): This function checks if the master widget has a notify_task function, and if so, calls it. ... | 4d7a31c0d68042b4110e1fa3e733711e0fdd473e | <|skeleton|>
class BPMFrame:
"""This class introduces all properties that a frame in BPM tools should hold."""
def notify_task(self, _task, _progress):
"""This function checks if the master widget has a notify_task function, and if so, calls it. This way, notifications travel upwards in the widget stru... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BPMFrame:
"""This class introduces all properties that a frame in BPM tools should hold."""
def notify_task(self, _task, _progress):
"""This function checks if the master widget has a notify_task function, and if so, calls it. This way, notifications travel upwards in the widget structure until s... | the_stack_v2_python_sparse | qal/tools/gui/widgets_misc.py | OptimalBPM/qal | train | 3 |
a27a5566cc9abd9a16170ac9112b169bfe2dfd38 | [
"self.sample_rate = sample_rate\nself.distributed = distributed\nif distributed:\n batch_sampler = DistributedUniformWithReplacementSampler(total_size=len(dataset), sample_rate=sample_rate, generator=generator)\nelse:\n batch_sampler = UniformWithReplacementSampler(num_samples=len(dataset), sample_rate=sample... | <|body_start_0|>
self.sample_rate = sample_rate
self.distributed = distributed
if distributed:
batch_sampler = DistributedUniformWithReplacementSampler(total_size=len(dataset), sample_rate=sample_rate, generator=generator)
else:
batch_sampler = UniformWithReplacem... | DataLoader subclass that always does Poisson sampling and supports empty batches by default. Typically instantiated via ``DPDataLoader.from_data_loader()`` method based on another DataLoader. DPDataLoader would preserve the behaviour of the original data loader, except for the two aspects. First, it switches ``batch_sa... | DPDataLoader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DPDataLoader:
"""DataLoader subclass that always does Poisson sampling and supports empty batches by default. Typically instantiated via ``DPDataLoader.from_data_loader()`` method based on another DataLoader. DPDataLoader would preserve the behaviour of the original data loader, except for the tw... | stack_v2_sparse_classes_75kplus_train_065840 | 11,242 | permissive | [
{
"docstring": "Args: dataset: See :class:`torch.utils.data.DataLoader` sample_rate: probability with which each element of the dataset is included in the next batch. num_workers: See :class:`torch.utils.data.DataLoader` collate_fn: See :class:`torch.utils.data.DataLoader` pin_memory: See :class:`torch.utils.da... | 2 | null | Implement the Python class `DPDataLoader` described below.
Class description:
DataLoader subclass that always does Poisson sampling and supports empty batches by default. Typically instantiated via ``DPDataLoader.from_data_loader()`` method based on another DataLoader. DPDataLoader would preserve the behaviour of the ... | Implement the Python class `DPDataLoader` described below.
Class description:
DataLoader subclass that always does Poisson sampling and supports empty batches by default. Typically instantiated via ``DPDataLoader.from_data_loader()`` method based on another DataLoader. DPDataLoader would preserve the behaviour of the ... | 79bdfac28afb526430a938d38513c46936f8670a | <|skeleton|>
class DPDataLoader:
"""DataLoader subclass that always does Poisson sampling and supports empty batches by default. Typically instantiated via ``DPDataLoader.from_data_loader()`` method based on another DataLoader. DPDataLoader would preserve the behaviour of the original data loader, except for the tw... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DPDataLoader:
"""DataLoader subclass that always does Poisson sampling and supports empty batches by default. Typically instantiated via ``DPDataLoader.from_data_loader()`` method based on another DataLoader. DPDataLoader would preserve the behaviour of the original data loader, except for the two aspects. Fi... | the_stack_v2_python_sparse | opacus/data_loader.py | pytorch/opacus | train | 1,358 |
b4d5db81e7499e35850d69122b3e50f7f8f8e582 | [
"super(FunctionComponent, self).__init__(opts)\nself.opts = opts\nself.options = opts.get(FunctionComponent.SECTION_HDR, {})\nself.init_function()",
"self.opts = opts\nself.options = opts.get(FunctionComponent.SECTION_HDR, {})\nself.init_function()",
"self.template_dir = self.options.get('template_dir')\nif sel... | <|body_start_0|>
super(FunctionComponent, self).__init__(opts)
self.opts = opts
self.options = opts.get(FunctionComponent.SECTION_HDR, {})
self.init_function()
<|end_body_0|>
<|body_start_1|>
self.opts = opts
self.options = opts.get(FunctionComponent.SECTION_HDR, {})
... | Component that implements Resilient function 'fn-netdevice | FunctionComponent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionComponent:
"""Component that implements Resilient function 'fn-netdevice"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _reload(self, event, opts):
"""Configuration options have changed, save new... | stack_v2_sparse_classes_75kplus_train_065841 | 5,616 | permissive | [
{
"docstring": "constructor provides access to the configuration options",
"name": "__init__",
"signature": "def __init__(self, opts)"
},
{
"docstring": "Configuration options have changed, save new values",
"name": "_reload",
"signature": "def _reload(self, event, opts)"
},
{
"d... | 6 | stack_v2_sparse_classes_30k_train_051381 | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements Resilient function 'fn-netdevice
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _reload(self, event, opts): Configuration options h... | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements Resilient function 'fn-netdevice
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _reload(self, event, opts): Configuration options h... | 6878c78b94eeca407998a41ce8db2cc00f2b6758 | <|skeleton|>
class FunctionComponent:
"""Component that implements Resilient function 'fn-netdevice"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _reload(self, event, opts):
"""Configuration options have changed, save new... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FunctionComponent:
"""Component that implements Resilient function 'fn-netdevice"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
super(FunctionComponent, self).__init__(opts)
self.opts = opts
self.options = opts.get(FunctionCompo... | the_stack_v2_python_sparse | fn_netdevice/fn_netdevice/components/network_device.py | ibmresilient/resilient-community-apps | train | 81 |
d2adb7515c3325b99272d0bde593db0043e8739c | [
"res = 0\nfor i in range(n + 1):\n for j in range(n // 2 + 1):\n for k in range(n // 5 + 1):\n if i + j * 2 + k * 5 == n:\n res += 1\nreturn res",
"w = [1, 2, 5]\nm = 3\ndp = [[0] * (n + 1) for _ in range(m + 1)]\nfor i in range(m + 1):\n dp[i][0] = 1\nfor i in range(1, m + ... | <|body_start_0|>
res = 0
for i in range(n + 1):
for j in range(n // 2 + 1):
for k in range(n // 5 + 1):
if i + j * 2 + k * 5 == n:
res += 1
return res
<|end_body_0|>
<|body_start_1|>
w = [1, 2, 5]
m = 3
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numOfsum1(self, n):
"""n 分钱 1_最短回文串.py 2 5 分硬币不限,凑成1元有多少种方法. 暴力 O(n^3)"""
<|body_0|>
def numOfsum1_dp(self, n):
"""n 元钱 1_最短回文串.py 2 5 分硬币不限,凑成100分有多少种方法. w[3] = [1_最短回文串.py, 2, 5] 动态规划 dp[i][j] 把第一个硬币凑成j分钱一共有多少种方法。 sum = n1*1_最短回文串.py+n2*2+n5*5 dp[i][j... | stack_v2_sparse_classes_75kplus_train_065842 | 2,299 | no_license | [
{
"docstring": "n 分钱 1_最短回文串.py 2 5 分硬币不限,凑成1元有多少种方法. 暴力 O(n^3)",
"name": "numOfsum1",
"signature": "def numOfsum1(self, n)"
},
{
"docstring": "n 元钱 1_最短回文串.py 2 5 分硬币不限,凑成100分有多少种方法. w[3] = [1_最短回文串.py, 2, 5] 动态规划 dp[i][j] 把第一个硬币凑成j分钱一共有多少种方法。 sum = n1*1_最短回文串.py+n2*2+n5*5 dp[i][j] = dp[i-1_最短回... | 3 | stack_v2_sparse_classes_30k_train_015515 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numOfsum1(self, n): n 分钱 1_最短回文串.py 2 5 分硬币不限,凑成1元有多少种方法. 暴力 O(n^3)
- def numOfsum1_dp(self, n): n 元钱 1_最短回文串.py 2 5 分硬币不限,凑成100分有多少种方法. w[3] = [1_最短回文串.py, 2, 5] 动态规划 dp[i][... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numOfsum1(self, n): n 分钱 1_最短回文串.py 2 5 分硬币不限,凑成1元有多少种方法. 暴力 O(n^3)
- def numOfsum1_dp(self, n): n 元钱 1_最短回文串.py 2 5 分硬币不限,凑成100分有多少种方法. w[3] = [1_最短回文串.py, 2, 5] 动态规划 dp[i][... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def numOfsum1(self, n):
"""n 分钱 1_最短回文串.py 2 5 分硬币不限,凑成1元有多少种方法. 暴力 O(n^3)"""
<|body_0|>
def numOfsum1_dp(self, n):
"""n 元钱 1_最短回文串.py 2 5 分硬币不限,凑成100分有多少种方法. w[3] = [1_最短回文串.py, 2, 5] 动态规划 dp[i][j] 把第一个硬币凑成j分钱一共有多少种方法。 sum = n1*1_最短回文串.py+n2*2+n5*5 dp[i][j... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numOfsum1(self, n):
"""n 分钱 1_最短回文串.py 2 5 分硬币不限,凑成1元有多少种方法. 暴力 O(n^3)"""
res = 0
for i in range(n + 1):
for j in range(n // 2 + 1):
for k in range(n // 5 + 1):
if i + j * 2 + k * 5 == n:
res += 1
... | the_stack_v2_python_sparse | 4_LEETCODE/11_Interview/字节跳动/凑成1元的个数.py | fzingithub/SwordRefers2Offer | train | 1 | |
341c9408d0606b00a640efc1abc4d1a19f69955c | [
"if value is not None:\n if isinstance(value, dict):\n return value\n else:\n return value.to_dict()",
"try:\n if isinstance(value, dict):\n sub_instance = kwargs['obj_type']()\n sub_instance.from_dict(value)\n sub_instance.validate_dict(value)\n return sub_insta... | <|body_start_0|>
if value is not None:
if isinstance(value, dict):
return value
else:
return value.to_dict()
<|end_body_0|>
<|body_start_1|>
try:
if isinstance(value, dict):
sub_instance = kwargs['obj_type']()
... | ObjectType | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectType:
def serialize(value, **kwargs):
"""Convert a value to a JSON serializable value"""
<|body_0|>
def deserialize(value, **kwargs):
"""Convert value to object"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if value is not None:
... | stack_v2_sparse_classes_75kplus_train_065843 | 1,336 | no_license | [
{
"docstring": "Convert a value to a JSON serializable value",
"name": "serialize",
"signature": "def serialize(value, **kwargs)"
},
{
"docstring": "Convert value to object",
"name": "deserialize",
"signature": "def deserialize(value, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016558 | Implement the Python class `ObjectType` described below.
Class description:
Implement the ObjectType class.
Method signatures and docstrings:
- def serialize(value, **kwargs): Convert a value to a JSON serializable value
- def deserialize(value, **kwargs): Convert value to object | Implement the Python class `ObjectType` described below.
Class description:
Implement the ObjectType class.
Method signatures and docstrings:
- def serialize(value, **kwargs): Convert a value to a JSON serializable value
- def deserialize(value, **kwargs): Convert value to object
<|skeleton|>
class ObjectType:
... | e2ef4c7b56c4e7e06964fe6f64ae6c497ac31727 | <|skeleton|>
class ObjectType:
def serialize(value, **kwargs):
"""Convert a value to a JSON serializable value"""
<|body_0|>
def deserialize(value, **kwargs):
"""Convert value to object"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ObjectType:
def serialize(value, **kwargs):
"""Convert a value to a JSON serializable value"""
if value is not None:
if isinstance(value, dict):
return value
else:
return value.to_dict()
def deserialize(value, **kwargs):
"""C... | the_stack_v2_python_sparse | nio/properties/util/object_type.py | niolabs/nio | train | 5 | |
294ae95e05189483dd990fecba8da66c3d6a457e | [
"dimension = 0\ndimension = np.array(dimensions)\nposition = np.array(positions)\ns = np.array(array.shape)[:2]\nif (position > s).any() or (dimension > s).any() or (dimension < position[0]).any() or (dimension < position[1]).any() or (dimension <= 1).any():\n raise BaseException(f\"The positions {position} + di... | <|body_start_0|>
dimension = 0
dimension = np.array(dimensions)
position = np.array(positions)
s = np.array(array.shape)[:2]
if (position > s).any() or (dimension > s).any() or (dimension < position[0]).any() or (dimension < position[1]).any() or (dimension <= 1).any():
... | All methods take in a NumPy array and return a new modified one. We are assuming that all inputs are correct, ie, you don't have to protect your functions against input errors. | ScrapBooker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScrapBooker:
"""All methods take in a NumPy array and return a new modified one. We are assuming that all inputs are correct, ie, you don't have to protect your functions against input errors."""
def crop(self, array, dimensions, positions=(0, 0)):
"""Crop the image as a rectangle wi... | stack_v2_sparse_classes_75kplus_train_065844 | 2,576 | no_license | [
{
"docstring": "Crop the image as a rectangle with the given dimensions (meaning, the new height and width for the image), whose top left corner is given by the position argument. The position should be (0,0) by default.",
"name": "crop",
"signature": "def crop(self, array, dimensions, positions=(0, 0))... | 4 | null | Implement the Python class `ScrapBooker` described below.
Class description:
All methods take in a NumPy array and return a new modified one. We are assuming that all inputs are correct, ie, you don't have to protect your functions against input errors.
Method signatures and docstrings:
- def crop(self, array, dimens... | Implement the Python class `ScrapBooker` described below.
Class description:
All methods take in a NumPy array and return a new modified one. We are assuming that all inputs are correct, ie, you don't have to protect your functions against input errors.
Method signatures and docstrings:
- def crop(self, array, dimens... | 9f46cfdda584f49ebf50f1b69eb42923b884ac02 | <|skeleton|>
class ScrapBooker:
"""All methods take in a NumPy array and return a new modified one. We are assuming that all inputs are correct, ie, you don't have to protect your functions against input errors."""
def crop(self, array, dimensions, positions=(0, 0)):
"""Crop the image as a rectangle wi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScrapBooker:
"""All methods take in a NumPy array and return a new modified one. We are assuming that all inputs are correct, ie, you don't have to protect your functions against input errors."""
def crop(self, array, dimensions, positions=(0, 0)):
"""Crop the image as a rectangle with the given ... | the_stack_v2_python_sparse | Python/day03/ex02/ScrapBooker.py | TheoZerbibi/BootCamp42AI | train | 0 |
2260e33e2798ca0570715e345b4b0e56987b6e0f | [
"self.one_time_use = one_time_use\nself.ip_white_list = ip_white_list\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\none_time_use = dictionary.get('oneTimeUse')\nip_white_list = dictionary.get('ipWhiteList')\nfor key in cls._names.values():\n if key in dictionar... | <|body_start_0|>
self.one_time_use = one_time_use
self.ip_white_list = ip_white_list
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
one_time_use = dictionary.get('oneTimeUse')
ip_white_lis... | Implementation of the 'Security' model. TODO: type model description here. Attributes: one_time_use (bool): (Coming soon) The link can only be used one time ip_white_list (list of string): (Coming soon) Define a list of IP's that are allowed to see / sign the document | Security | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Security:
"""Implementation of the 'Security' model. TODO: type model description here. Attributes: one_time_use (bool): (Coming soon) The link can only be used one time ip_white_list (list of string): (Coming soon) Define a list of IP's that are allowed to see / sign the document"""
def __i... | stack_v2_sparse_classes_75kplus_train_065845 | 2,187 | permissive | [
{
"docstring": "Constructor for the Security class",
"name": "__init__",
"signature": "def __init__(self, one_time_use=None, ip_white_list=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary represent... | 2 | stack_v2_sparse_classes_30k_train_030273 | Implement the Python class `Security` described below.
Class description:
Implementation of the 'Security' model. TODO: type model description here. Attributes: one_time_use (bool): (Coming soon) The link can only be used one time ip_white_list (list of string): (Coming soon) Define a list of IP's that are allowed to ... | Implement the Python class `Security` described below.
Class description:
Implementation of the 'Security' model. TODO: type model description here. Attributes: one_time_use (bool): (Coming soon) The link can only be used one time ip_white_list (list of string): (Coming soon) Define a list of IP's that are allowed to ... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class Security:
"""Implementation of the 'Security' model. TODO: type model description here. Attributes: one_time_use (bool): (Coming soon) The link can only be used one time ip_white_list (list of string): (Coming soon) Define a list of IP's that are allowed to see / sign the document"""
def __i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Security:
"""Implementation of the 'Security' model. TODO: type model description here. Attributes: one_time_use (bool): (Coming soon) The link can only be used one time ip_white_list (list of string): (Coming soon) Define a list of IP's that are allowed to see / sign the document"""
def __init__(self, o... | the_stack_v2_python_sparse | idfy_rest_client/models/security.py | dealflowteam/Idfy | train | 0 |
d21fb303484c0c215d25c41b4fd7a1b8bd076b33 | [
"attributes = {'src': True, 'href': True, 'link': True, 'script': True, 'url': True}\nhost = self.queue_item.response.url\nsoup = self.queue_item.get_soup_response()\nbase_element = soup.find('base', href=True)\nelements = soup.select('[{}]'.format('],['.join(attributes.keys())))\nif base_element:\n host = URLHe... | <|body_start_0|>
attributes = {'src': True, 'href': True, 'link': True, 'script': True, 'url': True}
host = self.queue_item.response.url
soup = self.queue_item.get_soup_response()
base_element = soup.find('base', href=True)
elements = soup.select('[{}]'.format('],['.join(attribut... | The HTMLSoupLinkScraper finds URLs from href attributes in HTML using BeautifulSoup. Attributes: content_types list(str): The supported content types. | HTMLSoupLinkScraper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTMLSoupLinkScraper:
"""The HTMLSoupLinkScraper finds URLs from href attributes in HTML using BeautifulSoup. Attributes: content_types list(str): The supported content types."""
def derived_get_requests(self):
"""Get all the new requests that were found in the response. Returns: list... | stack_v2_sparse_classes_75kplus_train_065846 | 3,351 | permissive | [
{
"docstring": "Get all the new requests that were found in the response. Returns: list(:class:`nyawc.http.Request`): A list of new requests that were found.",
"name": "derived_get_requests",
"signature": "def derived_get_requests(self)"
},
{
"docstring": "Trim grave accents manually (because Be... | 2 | stack_v2_sparse_classes_30k_val_002567 | Implement the Python class `HTMLSoupLinkScraper` described below.
Class description:
The HTMLSoupLinkScraper finds URLs from href attributes in HTML using BeautifulSoup. Attributes: content_types list(str): The supported content types.
Method signatures and docstrings:
- def derived_get_requests(self): Get all the ne... | Implement the Python class `HTMLSoupLinkScraper` described below.
Class description:
The HTMLSoupLinkScraper finds URLs from href attributes in HTML using BeautifulSoup. Attributes: content_types list(str): The supported content types.
Method signatures and docstrings:
- def derived_get_requests(self): Get all the ne... | ef14f94c2d9e6c5acdc4e8f5ee7044278c4af9ef | <|skeleton|>
class HTMLSoupLinkScraper:
"""The HTMLSoupLinkScraper finds URLs from href attributes in HTML using BeautifulSoup. Attributes: content_types list(str): The supported content types."""
def derived_get_requests(self):
"""Get all the new requests that were found in the response. Returns: list... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HTMLSoupLinkScraper:
"""The HTMLSoupLinkScraper finds URLs from href attributes in HTML using BeautifulSoup. Attributes: content_types list(str): The supported content types."""
def derived_get_requests(self):
"""Get all the new requests that were found in the response. Returns: list(:class:`nyaw... | the_stack_v2_python_sparse | lib/third/nyawc/scrapers/HTMLSoupLinkScraper.py | xz-zone/WSPIH | train | 3 |
3291518765de97f0f982300620b5e850ba7544b9 | [
"super(DynamicNet, self).__init__()\nself.input_linear = torch.nn.Linear(D_in, H)\nself.middle_linear = torch.nn.Linear(H, H)\nself.output_linear = torch.nn.Linear(H, D_out)",
"h_relu = self.input_linear(x).clamp(min=0)\nfor _ in range(random.randint(0, 3)):\n h_relu = self.middle_linear(h_relu).clamp(min=0)\n... | <|body_start_0|>
super(DynamicNet, self).__init__()
self.input_linear = torch.nn.Linear(D_in, H)
self.middle_linear = torch.nn.Linear(H, H)
self.output_linear = torch.nn.Linear(H, D_out)
<|end_body_0|>
<|body_start_1|>
h_relu = self.input_linear(x).clamp(min=0)
for _ in ... | DynamicNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we construct three nn.Linear instances that we will use in the forward pass."""
<|body_0|>
def forward(self, x):
"""For the forward pass of the model, we randomly choose either 0, 1, 2, or 3 and re... | stack_v2_sparse_classes_75kplus_train_065847 | 3,890 | no_license | [
{
"docstring": "In the constructor we construct three nn.Linear instances that we will use in the forward pass.",
"name": "__init__",
"signature": "def __init__(self, D_in, H, D_out)"
},
{
"docstring": "For the forward pass of the model, we randomly choose either 0, 1, 2, or 3 and reuse the midd... | 2 | stack_v2_sparse_classes_30k_train_020767 | Implement the Python class `DynamicNet` described below.
Class description:
Implement the DynamicNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we construct three nn.Linear instances that we will use in the forward pass.
- def forward(self, x): For the forward pa... | Implement the Python class `DynamicNet` described below.
Class description:
Implement the DynamicNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we construct three nn.Linear instances that we will use in the forward pass.
- def forward(self, x): For the forward pa... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class DynamicNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we construct three nn.Linear instances that we will use in the forward pass."""
<|body_0|>
def forward(self, x):
"""For the forward pass of the model, we randomly choose either 0, 1, 2, or 3 and re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DynamicNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we construct three nn.Linear instances that we will use in the forward pass."""
super(DynamicNet, self).__init__()
self.input_linear = torch.nn.Linear(D_in, H)
self.middle_linear = torch.nn.Linear(H, H)
... | the_stack_v2_python_sparse | generated/test_jcjohnson_pytorch_examples.py | jansel/pytorch-jit-paritybench | train | 35 | |
355a16efa955647b5048196e95ef8e784c4fca2a | [
"super(Net2, self).__init__()\nself.conv1 = nn.Conv2d(3, 64, 4, padding=(2, 2))\nself.conv2 = nn.Conv2d(64, 64, 4, padding=(2, 2))\nself.conv3 = nn.Conv2d(64, 128, 4, padding=(2, 2))\nself.conv4 = nn.Conv2d(128, 128, 4, padding=(2, 2))\nself.conv5 = nn.Conv2d(128, 128, 4, padding=(2, 2))\nself.conv6 = nn.Conv2d(128... | <|body_start_0|>
super(Net2, self).__init__()
self.conv1 = nn.Conv2d(3, 64, 4, padding=(2, 2))
self.conv2 = nn.Conv2d(64, 64, 4, padding=(2, 2))
self.conv3 = nn.Conv2d(64, 128, 4, padding=(2, 2))
self.conv4 = nn.Conv2d(128, 128, 4, padding=(2, 2))
self.conv5 = nn.Conv2d(1... | Simple net for distributed training using Pytorch. | Net2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Net2:
"""Simple net for distributed training using Pytorch."""
def __init__(self):
"""Simple net Builder."""
<|body_0|>
def forward(self, x):
"""Forward pass."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Net2, self).__init__()
s... | stack_v2_sparse_classes_75kplus_train_065848 | 7,754 | no_license | [
{
"docstring": "Simple net Builder.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Forward pass.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | null | Implement the Python class `Net2` described below.
Class description:
Simple net for distributed training using Pytorch.
Method signatures and docstrings:
- def __init__(self): Simple net Builder.
- def forward(self, x): Forward pass. | Implement the Python class `Net2` described below.
Class description:
Simple net for distributed training using Pytorch.
Method signatures and docstrings:
- def __init__(self): Simple net Builder.
- def forward(self, x): Forward pass.
<|skeleton|>
class Net2:
"""Simple net for distributed training using Pytorch.... | 73c10db832c4100da7454d3122c29bd22dd0e690 | <|skeleton|>
class Net2:
"""Simple net for distributed training using Pytorch."""
def __init__(self):
"""Simple net Builder."""
<|body_0|>
def forward(self, x):
"""Forward pass."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Net2:
"""Simple net for distributed training using Pytorch."""
def __init__(self):
"""Simple net Builder."""
super(Net2, self).__init__()
self.conv1 = nn.Conv2d(3, 64, 4, padding=(2, 2))
self.conv2 = nn.Conv2d(64, 64, 4, padding=(2, 2))
self.conv3 = nn.Conv2d(64, 1... | the_stack_v2_python_sparse | distributed_training_tutorial/PyTorch_Distr.py | share020/dl | train | 2 |
edc06ce2aab9d882a9685ef01bbc52c50681b51b | [
"super().__init__(FILTER_NAME_TIME_THROTTLE, window_size, precision=precision, entity=entity)\nself._time_window = window_size\nself._last_emitted_at: datetime | None = None\nself._only_numbers = False",
"window_start = new_state.timestamp - self._time_window\nif not self._last_emitted_at or self._last_emitted_at... | <|body_start_0|>
super().__init__(FILTER_NAME_TIME_THROTTLE, window_size, precision=precision, entity=entity)
self._time_window = window_size
self._last_emitted_at: datetime | None = None
self._only_numbers = False
<|end_body_0|>
<|body_start_1|>
window_start = new_state.timesta... | Time Throttle Filter. One sample per time period. | TimeThrottleFilter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeThrottleFilter:
"""Time Throttle Filter. One sample per time period."""
def __init__(self, *, window_size: timedelta, entity: str, precision: int | None=None) -> None:
"""Initialize Filter."""
<|body_0|>
def _filter_state(self, new_state: FilterState) -> FilterState:... | stack_v2_sparse_classes_75kplus_train_065849 | 23,958 | permissive | [
{
"docstring": "Initialize Filter.",
"name": "__init__",
"signature": "def __init__(self, *, window_size: timedelta, entity: str, precision: int | None=None) -> None"
},
{
"docstring": "Implement the filter.",
"name": "_filter_state",
"signature": "def _filter_state(self, new_state: Filt... | 2 | stack_v2_sparse_classes_30k_train_052837 | Implement the Python class `TimeThrottleFilter` described below.
Class description:
Time Throttle Filter. One sample per time period.
Method signatures and docstrings:
- def __init__(self, *, window_size: timedelta, entity: str, precision: int | None=None) -> None: Initialize Filter.
- def _filter_state(self, new_sta... | Implement the Python class `TimeThrottleFilter` described below.
Class description:
Time Throttle Filter. One sample per time period.
Method signatures and docstrings:
- def __init__(self, *, window_size: timedelta, entity: str, precision: int | None=None) -> None: Initialize Filter.
- def _filter_state(self, new_sta... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class TimeThrottleFilter:
"""Time Throttle Filter. One sample per time period."""
def __init__(self, *, window_size: timedelta, entity: str, precision: int | None=None) -> None:
"""Initialize Filter."""
<|body_0|>
def _filter_state(self, new_state: FilterState) -> FilterState:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimeThrottleFilter:
"""Time Throttle Filter. One sample per time period."""
def __init__(self, *, window_size: timedelta, entity: str, precision: int | None=None) -> None:
"""Initialize Filter."""
super().__init__(FILTER_NAME_TIME_THROTTLE, window_size, precision=precision, entity=entity)... | the_stack_v2_python_sparse | homeassistant/components/filter/sensor.py | home-assistant/core | train | 35,501 |
598f5c5a046c0ae1aea4b5bd889668f98dec243d | [
"if name == '__setstate__':\n raise AttributeError\nreturn self[name]",
"if name in self:\n self[name] = value\nelse:\n super(CaseInfo, self).__setattr__(name, value)",
"tokens = key.split('.', 1)\nfkey = tokens[0]\nif len(tokens) == 2:\n self[fkey]._set_through(tokens[1], val)\nelse:\n self[fkey... | <|body_start_0|>
if name == '__setstate__':
raise AttributeError
return self[name]
<|end_body_0|>
<|body_start_1|>
if name in self:
self[name] = value
else:
super(CaseInfo, self).__setattr__(name, value)
<|end_body_1|>
<|body_start_2|>
tokens... | Generic case information abstract class. It's the base class that all case information classes should subclass, to form hierarchical information object. | CaseInfo | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaseInfo:
"""Generic case information abstract class. It's the base class that all case information classes should subclass, to form hierarchical information object."""
def __getattr__(self, name):
"""Consult self dictionary for attribute. It's a shorthand."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_065850 | 7,485 | permissive | [
{
"docstring": "Consult self dictionary for attribute. It's a shorthand.",
"name": "__getattr__",
"signature": "def __getattr__(self, name)"
},
{
"docstring": "Save to self dictionary first, then self object table. @note: This method is overriden as a stupid-preventer. It makes attribute setting... | 4 | stack_v2_sparse_classes_30k_train_022769 | Implement the Python class `CaseInfo` described below.
Class description:
Generic case information abstract class. It's the base class that all case information classes should subclass, to form hierarchical information object.
Method signatures and docstrings:
- def __getattr__(self, name): Consult self dictionary fo... | Implement the Python class `CaseInfo` described below.
Class description:
Generic case information abstract class. It's the base class that all case information classes should subclass, to form hierarchical information object.
Method signatures and docstrings:
- def __getattr__(self, name): Consult self dictionary fo... | ff0c71c5081dc67522d42bc65719e16c8365ab47 | <|skeleton|>
class CaseInfo:
"""Generic case information abstract class. It's the base class that all case information classes should subclass, to form hierarchical information object."""
def __getattr__(self, name):
"""Consult self dictionary for attribute. It's a shorthand."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CaseInfo:
"""Generic case information abstract class. It's the base class that all case information classes should subclass, to form hierarchical information object."""
def __getattr__(self, name):
"""Consult self dictionary for attribute. It's a shorthand."""
if name == '__setstate__':
... | the_stack_v2_python_sparse | solvcon/case_core.py | gitter-badger/solvcon | train | 1 |
2c815cda2e73d4f29c7ff81090e25265a0a09dcc | [
"self._phrases = None\nself._window = []\nself._window_size = window_size\nself._line_nr = 0\nself._read_length = read_length\nself._progress_line_nr = progress_line_nr",
"for i in range(len(self._window)):\n phrase = ' '.join(self._window[i:])\n if phrase in self._phrases:\n self._phrases[phrase].ap... | <|body_start_0|>
self._phrases = None
self._window = []
self._window_size = window_size
self._line_nr = 0
self._read_length = read_length
self._progress_line_nr = progress_line_nr
<|end_body_0|>
<|body_start_1|>
for i in range(len(self._window)):
phra... | An Indexer can parse a text file, using a phrase dictionary, and record for each phrase the line number it occurs on in the text | Indexer | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Indexer:
"""An Indexer can parse a text file, using a phrase dictionary, and record for each phrase the line number it occurs on in the text"""
def __init__(self, window_size=10, read_length=1024, progress_line_nr=1000):
"""constructor, takes configuration options for the Indexer the... | stack_v2_sparse_classes_75kplus_train_065851 | 4,214 | permissive | [
{
"docstring": "constructor, takes configuration options for the Indexer the window size, i.e., the maximal length of phrases to index, read_length, i.e., the buffer length for file read operations, and progress line numbers, i.e., the number of lines after which to report indexing progress",
"name": "__ini... | 3 | stack_v2_sparse_classes_30k_train_051172 | Implement the Python class `Indexer` described below.
Class description:
An Indexer can parse a text file, using a phrase dictionary, and record for each phrase the line number it occurs on in the text
Method signatures and docstrings:
- def __init__(self, window_size=10, read_length=1024, progress_line_nr=1000): con... | Implement the Python class `Indexer` described below.
Class description:
An Indexer can parse a text file, using a phrase dictionary, and record for each phrase the line number it occurs on in the text
Method signatures and docstrings:
- def __init__(self, window_size=10, read_length=1024, progress_line_nr=1000): con... | e748466a2af9f3388a8b0ed091aa061dbfc752d6 | <|skeleton|>
class Indexer:
"""An Indexer can parse a text file, using a phrase dictionary, and record for each phrase the line number it occurs on in the text"""
def __init__(self, window_size=10, read_length=1024, progress_line_nr=1000):
"""constructor, takes configuration options for the Indexer the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Indexer:
"""An Indexer can parse a text file, using a phrase dictionary, and record for each phrase the line number it occurs on in the text"""
def __init__(self, window_size=10, read_length=1024, progress_line_nr=1000):
"""constructor, takes configuration options for the Indexer the window size,... | the_stack_v2_python_sparse | Python/PhraseIndexing/indexer.py | gjbex/training-material | train | 130 |
4851e4686903f19666dda6a3cfc702b198be0a55 | [
"context = context or {}\nrp_obj = self.pool.get('res.partner')\nacc_part_brw = rp_obj._find_accounting_partner(rp_obj.browse(cr, uid, partner_id))\nreturn {'value': {'partner_vat': acc_part_brw.vat[2:]}}",
"context = context or {}\nrate_brw = self.pool.get('islr.rates').browse(cr, uid, rate_id)\nreturn {'value':... | <|body_start_0|>
context = context or {}
rp_obj = self.pool.get('res.partner')
acc_part_brw = rp_obj._find_accounting_partner(rp_obj.browse(cr, uid, partner_id))
return {'value': {'partner_vat': acc_part_brw.vat[2:]}}
<|end_body_0|>
<|body_start_1|>
context = context or {}
... | IslrXmlWhLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IslrXmlWhLine:
def onchange_partner_vat(self, cr, uid, ids, partner_id, context=None):
"""Changing the partner, the partner_vat field is updated."""
<|body_0|>
def onchange_code_perc(self, cr, uid, ids, rate_id, context=None):
"""Changing the rate of the islr, the po... | stack_v2_sparse_classes_75kplus_train_065852 | 17,669 | no_license | [
{
"docstring": "Changing the partner, the partner_vat field is updated.",
"name": "onchange_partner_vat",
"signature": "def onchange_partner_vat(self, cr, uid, ids, partner_id, context=None)"
},
{
"docstring": "Changing the rate of the islr, the porcent_rete and concept_code fields is updated.",... | 2 | stack_v2_sparse_classes_30k_train_016891 | Implement the Python class `IslrXmlWhLine` described below.
Class description:
Implement the IslrXmlWhLine class.
Method signatures and docstrings:
- def onchange_partner_vat(self, cr, uid, ids, partner_id, context=None): Changing the partner, the partner_vat field is updated.
- def onchange_code_perc(self, cr, uid, ... | Implement the Python class `IslrXmlWhLine` described below.
Class description:
Implement the IslrXmlWhLine class.
Method signatures and docstrings:
- def onchange_partner_vat(self, cr, uid, ids, partner_id, context=None): Changing the partner, the partner_vat field is updated.
- def onchange_code_perc(self, cr, uid, ... | 718327d01e5b4408add58682c5ad1901fa35b450 | <|skeleton|>
class IslrXmlWhLine:
def onchange_partner_vat(self, cr, uid, ids, partner_id, context=None):
"""Changing the partner, the partner_vat field is updated."""
<|body_0|>
def onchange_code_perc(self, cr, uid, ids, rate_id, context=None):
"""Changing the rate of the islr, the po... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IslrXmlWhLine:
def onchange_partner_vat(self, cr, uid, ids, partner_id, context=None):
"""Changing the partner, the partner_vat field is updated."""
context = context or {}
rp_obj = self.pool.get('res.partner')
acc_part_brw = rp_obj._find_accounting_partner(rp_obj.browse(cr, ui... | the_stack_v2_python_sparse | l10n_ve_withholding_islr/model/islr_xml_wh.py | Vauxoo/odoo-venezuela | train | 15 | |
c519df02a897bfc79dd41dc39ff728de42a708c3 | [
"res = ''\nqueue = [root]\nwhile queue:\n node = queue.pop(0)\n if node:\n res += str(node.val)\n queue.append(node.left)\n queue.append(node.right)\n else:\n res += 'n'\n res += ' '\nreturn res",
"tree = data.split()\nif tree[0] == 'n':\n return None\nroot = TreeNode(in... | <|body_start_0|>
res = ''
queue = [root]
while queue:
node = queue.pop(0)
if node:
res += str(node.val)
queue.append(node.left)
queue.append(node.right)
else:
res += 'n'
res += ' '
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_065853 | 2,210 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_val_001479 | 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:... | b7c59c826bcd17cb1333571eb9f13f5c2b89b4ee | <|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"""
res = ''
queue = [root]
while queue:
node = queue.pop(0)
if node:
res += str(node.val)
queue.append(node.left)
... | the_stack_v2_python_sparse | 算法小抄/二叉树/二叉树的序列化与反序列化.py | Asunqingwen/LeetCode | train | 0 | |
282e9437ca84b25cc93dada91d69c43b0c2c9307 | [
"eq = self.assertEqual\neq(0, Tag.objects.all().count())\ntitle = 'Hello Posts!'\nemail = 'john@this.edu'\njane = User.objects.create(email=email)\nhtml = '<b>Hello World!</b>'\npost = Post(title=title, author=jane, type=Post.FORUM, content=html)\npost.save()\npost.add_tags('t1,t2, t3')\neq(3, Tag.objects.all().cou... | <|body_start_0|>
eq = self.assertEqual
eq(0, Tag.objects.all().count())
title = 'Hello Posts!'
email = 'john@this.edu'
jane = User.objects.create(email=email)
html = '<b>Hello World!</b>'
post = Post(title=title, author=jane, type=Post.FORUM, content=html)
... | PostTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostTest:
def test_tagging(self):
"""Testing tagging."""
<|body_0|>
def test_post_creation(self):
"""Testing post creation."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
eq = self.assertEqual
eq(0, Tag.objects.all().count())
title ... | stack_v2_sparse_classes_75kplus_train_065854 | 3,577 | permissive | [
{
"docstring": "Testing tagging.",
"name": "test_tagging",
"signature": "def test_tagging(self)"
},
{
"docstring": "Testing post creation.",
"name": "test_post_creation",
"signature": "def test_post_creation(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006760 | Implement the Python class `PostTest` described below.
Class description:
Implement the PostTest class.
Method signatures and docstrings:
- def test_tagging(self): Testing tagging.
- def test_post_creation(self): Testing post creation. | Implement the Python class `PostTest` described below.
Class description:
Implement the PostTest class.
Method signatures and docstrings:
- def test_tagging(self): Testing tagging.
- def test_post_creation(self): Testing post creation.
<|skeleton|>
class PostTest:
def test_tagging(self):
"""Testing tagg... | d4300f0b622af9f14666068cad31e3c20bc94a2d | <|skeleton|>
class PostTest:
def test_tagging(self):
"""Testing tagging."""
<|body_0|>
def test_post_creation(self):
"""Testing post creation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostTest:
def test_tagging(self):
"""Testing tagging."""
eq = self.assertEqual
eq(0, Tag.objects.all().count())
title = 'Hello Posts!'
email = 'john@this.edu'
jane = User.objects.create(email=email)
html = '<b>Hello World!</b>'
post = Post(title=... | the_stack_v2_python_sparse | biostar/apps/posts/tests.py | tvvocold/biostar-central | train | 1 | |
b4a77d1a610144d7c390d9ecb0b8f4b22519627a | [
"msg = Message(message_direction=Message.OUTBOUND, type='text', data={'_vnd': {'v1': {'author': {'type': 'OPERATOR'}, 'chat': {'owner': '27820001001'}}}})\nself.assertEqual(msg.is_operator_message, True)\nmsg.data = {}\nself.assertEqual(msg.is_operator_message, False)",
"msg = Message(message_direction=Message.OU... | <|body_start_0|>
msg = Message(message_direction=Message.OUTBOUND, type='text', data={'_vnd': {'v1': {'author': {'type': 'OPERATOR'}, 'chat': {'owner': '27820001001'}}}})
self.assertEqual(msg.is_operator_message, True)
msg.data = {}
self.assertEqual(msg.is_operator_message, False)
<|end_... | MessageTests | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageTests:
def test_is_operator_message(self):
"""Whether this message is from an operator or not"""
<|body_0|>
def test_has_label(self):
"""Test if a message contains a label"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
msg = Message(message_... | stack_v2_sparse_classes_75kplus_train_065855 | 19,794 | permissive | [
{
"docstring": "Whether this message is from an operator or not",
"name": "test_is_operator_message",
"signature": "def test_is_operator_message(self)"
},
{
"docstring": "Test if a message contains a label",
"name": "test_has_label",
"signature": "def test_has_label(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051552 | Implement the Python class `MessageTests` described below.
Class description:
Implement the MessageTests class.
Method signatures and docstrings:
- def test_is_operator_message(self): Whether this message is from an operator or not
- def test_has_label(self): Test if a message contains a label | Implement the Python class `MessageTests` described below.
Class description:
Implement the MessageTests class.
Method signatures and docstrings:
- def test_is_operator_message(self): Whether this message is from an operator or not
- def test_has_label(self): Test if a message contains a label
<|skeleton|>
class Mes... | e1ea0beaf079f4f4d5f9562fb9d9a4f0670f459f | <|skeleton|>
class MessageTests:
def test_is_operator_message(self):
"""Whether this message is from an operator or not"""
<|body_0|>
def test_has_label(self):
"""Test if a message contains a label"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MessageTests:
def test_is_operator_message(self):
"""Whether this message is from an operator or not"""
msg = Message(message_direction=Message.OUTBOUND, type='text', data={'_vnd': {'v1': {'author': {'type': 'OPERATOR'}, 'chat': {'owner': '27820001001'}}}})
self.assertEqual(msg.is_oper... | the_stack_v2_python_sparse | eventstore/test_models.py | praekeltfoundation/ndoh-hub | train | 0 | |
e284aabd93da6d7d4bdb25400def0c0fc6c22c8e | [
"if not nums:\n return nums\nr = []\nfor i in range(len(nums) - k + 1):\n r.append(max(nums[i:i + k]))\nreturn r",
"q, res = (collections.deque(), [])\nfor i in range(len(nums)):\n if i - k >= 0:\n res.append(nums[q[0]])\n while q and q[0] <= i - k:\n q.popleft()\n while q and... | <|body_start_0|>
if not nums:
return nums
r = []
for i in range(len(nums) - k + 1):
r.append(max(nums[i:i + k]))
return r
<|end_body_0|>
<|body_start_1|>
q, res = (collections.deque(), [])
for i in range(len(nums)):
if i - k >= 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxSlidingWindow2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_065856 | 1,409 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxSlidingWindow",
"signature": "def maxSlidingWindow(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxSlidingWindow2",
"signature": "def maxSlidingWindow2... | 2 | stack_v2_sparse_classes_30k_train_025252 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxSlidingWindow2(self, nums, k): :type nums: List[int] :type k: int :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxSlidingWindow2(self, nums, k): :type nums: List[int] :type k: int :rtype: List[... | 1ca8298361b6a030d2569c06a34d955cc5e4b1bb | <|skeleton|>
class Solution:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxSlidingWindow2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
if not nums:
return nums
r = []
for i in range(len(nums) - k + 1):
r.append(max(nums[i:i + k]))
return r
def maxSlidingWindow2(self, nu... | the_stack_v2_python_sparse | ch20/misung/ch20_1_misung.py | hyo-eun-kim/algorithm-study | train | 0 | |
b36932ac651676df21d21a1b691baa0bba9c1681 | [
"cached = DDCache['user_agents'][self.ua_hash].get('name_version_pairs', None)\nif cached is not None:\n return cached\nname_version_pairs = key_value_pairs(ua=self.user_agent)\nDDCache['user_agents'][self.ua_hash]['name_version_pairs'] = name_version_pairs\nreturn name_version_pairs",
"app_details = self.appd... | <|body_start_0|>
cached = DDCache['user_agents'][self.ua_hash].get('name_version_pairs', None)
if cached is not None:
return cached
name_version_pairs = key_value_pairs(ua=self.user_agent)
DDCache['user_agents'][self.ua_hash]['name_version_pairs'] = name_version_pairs
... | BaseClientParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseClientParser:
def name_version_pairs(self) -> list:
"""Extract key/value pairs from User Agent String, based on various patterns of: <name><sep><version>"""
<|body_0|>
def matches_manual_appdetails(self):
"""Check the name_version_pairs data before checking regex... | stack_v2_sparse_classes_75kplus_train_065857 | 7,781 | permissive | [
{
"docstring": "Extract key/value pairs from User Agent String, based on various patterns of: <name><sep><version>",
"name": "name_version_pairs",
"signature": "def name_version_pairs(self) -> list"
},
{
"docstring": "Check the name_version_pairs data before checking regexes. This can make tests... | 3 | null | Implement the Python class `BaseClientParser` described below.
Class description:
Implement the BaseClientParser class.
Method signatures and docstrings:
- def name_version_pairs(self) -> list: Extract key/value pairs from User Agent String, based on various patterns of: <name><sep><version>
- def matches_manual_appd... | Implement the Python class `BaseClientParser` described below.
Class description:
Implement the BaseClientParser class.
Method signatures and docstrings:
- def name_version_pairs(self) -> list: Extract key/value pairs from User Agent String, based on various patterns of: <name><sep><version>
- def matches_manual_appd... | c40f9f12ed4c066d4f42095e96e9a87a8581d99d | <|skeleton|>
class BaseClientParser:
def name_version_pairs(self) -> list:
"""Extract key/value pairs from User Agent String, based on various patterns of: <name><sep><version>"""
<|body_0|>
def matches_manual_appdetails(self):
"""Check the name_version_pairs data before checking regex... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseClientParser:
def name_version_pairs(self) -> list:
"""Extract key/value pairs from User Agent String, based on various patterns of: <name><sep><version>"""
cached = DDCache['user_agents'][self.ua_hash].get('name_version_pairs', None)
if cached is not None:
return cache... | the_stack_v2_python_sparse | src/lib/device_detector/parser/client/base.py | martbhell/wasthereannhlgamelastnight | train | 5 | |
d1231e51cbd1d743e3184945fa8236cb5c537b33 | [
"tx = cuda.threadIdx.x\nty = cuda.threadIdx.y\nidx = cuda.blockIdx.x * cuda.blockDim.x + tx\nidy = cuda.blockIdx.y * cuda.blockDim.y + ty\nsize += 1\nif idx < size and idy < size:\n index_r = idx * size\n sAb = cuda.shared.array(shape=(tpb, tpb), dtype=float64)\n sAb[tx, ty] = Ab[index_r + idy]\n cuda.s... | <|body_start_0|>
tx = cuda.threadIdx.x
ty = cuda.threadIdx.y
idx = cuda.blockIdx.x * cuda.blockDim.x + tx
idy = cuda.blockIdx.y * cuda.blockDim.y + ty
size += 1
if idx < size and idy < size:
index_r = idx * size
sAb = cuda.shared.array(shape=(tpb, ... | GaussianElimination | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianElimination:
def gaussian_elimination(Ab, size, i):
"""Performs Gaussian elimination for each row of a column. @param A Augmented matrix representing a SLAE. @param size Size of coefficiente matrix. @param i Integer representing the current column in which all threads are perform... | stack_v2_sparse_classes_75kplus_train_065858 | 3,783 | no_license | [
{
"docstring": "Performs Gaussian elimination for each row of a column. @param A Augmented matrix representing a SLAE. @param size Size of coefficiente matrix. @param i Integer representing the current column in which all threads are performing row operations. @return None",
"name": "gaussian_elimination",
... | 2 | stack_v2_sparse_classes_30k_train_031697 | Implement the Python class `GaussianElimination` described below.
Class description:
Implement the GaussianElimination class.
Method signatures and docstrings:
- def gaussian_elimination(Ab, size, i): Performs Gaussian elimination for each row of a column. @param A Augmented matrix representing a SLAE. @param size Si... | Implement the Python class `GaussianElimination` described below.
Class description:
Implement the GaussianElimination class.
Method signatures and docstrings:
- def gaussian_elimination(Ab, size, i): Performs Gaussian elimination for each row of a column. @param A Augmented matrix representing a SLAE. @param size Si... | b2b89a18260c25134d50c37a4fbb48981de79218 | <|skeleton|>
class GaussianElimination:
def gaussian_elimination(Ab, size, i):
"""Performs Gaussian elimination for each row of a column. @param A Augmented matrix representing a SLAE. @param size Size of coefficiente matrix. @param i Integer representing the current column in which all threads are perform... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaussianElimination:
def gaussian_elimination(Ab, size, i):
"""Performs Gaussian elimination for each row of a column. @param A Augmented matrix representing a SLAE. @param size Size of coefficiente matrix. @param i Integer representing the current column in which all threads are performing row operat... | the_stack_v2_python_sparse | project/gaussian_elimination/gaussian_elimination.py | tllano11/Numerical-Methods | train | 3 | |
8beb911f5a654a74b00dcf2975f5188507b67993 | [
"if associate_with.internal_id is None:\n raise ValueError('Model to associate with must have an internal ID: %s' % associate_with)\nif isinstance(associate, InternalIdModel):\n associate = [associate]\nsession = self._database_connector.create_session()\nsqlalchemy_associated_with_type = get_equivalent_sqlal... | <|body_start_0|>
if associate_with.internal_id is None:
raise ValueError('Model to associate with must have an internal ID: %s' % associate_with)
if isinstance(associate, InternalIdModel):
associate = [associate]
session = self._database_connector.create_session()
... | SQLAlchemy metadata_mapper that deals with models that can be associated with other models via a join table. | SQLAssociationMapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLAssociationMapper:
"""SQLAlchemy metadata_mapper that deals with models that can be associated with other models via a join table."""
def _set_association(self, associate: Union[InternalIdModel, Iterable[InternalIdModel]], associate_with: InternalIdModel, relationship_property_name: str):... | stack_v2_sparse_classes_75kplus_train_065859 | 10,822 | permissive | [
{
"docstring": "Associates the given models to another model, linked to via the specified relationship property. :param associate: the models to associate :param associate_with: the model to associate with :param relationship_property_name: the property on `associate_with` in which the relationship is expressed... | 2 | stack_v2_sparse_classes_30k_val_001599 | Implement the Python class `SQLAssociationMapper` described below.
Class description:
SQLAlchemy metadata_mapper that deals with models that can be associated with other models via a join table.
Method signatures and docstrings:
- def _set_association(self, associate: Union[InternalIdModel, Iterable[InternalIdModel]]... | Implement the Python class `SQLAssociationMapper` described below.
Class description:
SQLAlchemy metadata_mapper that deals with models that can be associated with other models via a join table.
Method signatures and docstrings:
- def _set_association(self, associate: Union[InternalIdModel, Iterable[InternalIdModel]]... | d998016f44c54666f76f90d8d3efa90e12730fff | <|skeleton|>
class SQLAssociationMapper:
"""SQLAlchemy metadata_mapper that deals with models that can be associated with other models via a join table."""
def _set_association(self, associate: Union[InternalIdModel, Iterable[InternalIdModel]], associate_with: InternalIdModel, relationship_property_name: str):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SQLAssociationMapper:
"""SQLAlchemy metadata_mapper that deals with models that can be associated with other models via a join table."""
def _set_association(self, associate: Union[InternalIdModel, Iterable[InternalIdModel]], associate_with: InternalIdModel, relationship_property_name: str):
"""A... | the_stack_v2_python_sparse | subrepos/wtsi-hgi.python-sequencescape-db/sequencescape/_sqlalchemy/mappers.py | wtsi-hgi/openstack-tenant-cleaner | train | 0 |
c4d3bb0ba74c8a302027dda80c5c671b7c59293b | [
"model = model if isinstance(model, SpaceForDialogIntent) else Model.from_pretrained(model)\nif preprocessor is None:\n preprocessor = DialogIntentPredictionPreprocessor(model.model_dir)\nself.model = model\nsuper().__init__(model=model, preprocessor=preprocessor, **kwargs)\nself.categories = preprocessor.catego... | <|body_start_0|>
model = model if isinstance(model, SpaceForDialogIntent) else Model.from_pretrained(model)
if preprocessor is None:
preprocessor = DialogIntentPredictionPreprocessor(model.model_dir)
self.model = model
super().__init__(model=model, preprocessor=preprocessor, ... | DialogIntentPredictionPipeline | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DialogIntentPredictionPipeline:
def __init__(self, model: Union[SpaceForDialogIntent, str], preprocessor: DialogIntentPredictionPreprocessor=None, **kwargs):
"""Use `model` and `preprocessor` to create a dialog intent prediction pipeline Args: model (str or SpaceForDialogIntent): Supply ... | stack_v2_sparse_classes_75kplus_train_065860 | 2,215 | permissive | [
{
"docstring": "Use `model` and `preprocessor` to create a dialog intent prediction pipeline Args: model (str or SpaceForDialogIntent): Supply either a local model dir or a model id from the model hub, or a SpaceForDialogIntent instance. preprocessor (DialogIntentPredictionPreprocessor): An optional preprocesso... | 2 | stack_v2_sparse_classes_30k_train_022336 | Implement the Python class `DialogIntentPredictionPipeline` described below.
Class description:
Implement the DialogIntentPredictionPipeline class.
Method signatures and docstrings:
- def __init__(self, model: Union[SpaceForDialogIntent, str], preprocessor: DialogIntentPredictionPreprocessor=None, **kwargs): Use `mod... | Implement the Python class `DialogIntentPredictionPipeline` described below.
Class description:
Implement the DialogIntentPredictionPipeline class.
Method signatures and docstrings:
- def __init__(self, model: Union[SpaceForDialogIntent, str], preprocessor: DialogIntentPredictionPreprocessor=None, **kwargs): Use `mod... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class DialogIntentPredictionPipeline:
def __init__(self, model: Union[SpaceForDialogIntent, str], preprocessor: DialogIntentPredictionPreprocessor=None, **kwargs):
"""Use `model` and `preprocessor` to create a dialog intent prediction pipeline Args: model (str or SpaceForDialogIntent): Supply ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DialogIntentPredictionPipeline:
def __init__(self, model: Union[SpaceForDialogIntent, str], preprocessor: DialogIntentPredictionPreprocessor=None, **kwargs):
"""Use `model` and `preprocessor` to create a dialog intent prediction pipeline Args: model (str or SpaceForDialogIntent): Supply either a local... | the_stack_v2_python_sparse | ai/modelscope/modelscope/pipelines/nlp/dialog_intent_prediction_pipeline.py | alldatacenter/alldata | train | 774 | |
95d06424783b8fca437e2ce510e70d5942a60b08 | [
"super(VAEGMPLoss, self).__init__()\nself.layer_outputs = None\nself.beta = beta\nself.reduction = reduction",
"if self.layer_outputs is None:\n raise ValueError('This loss needs intermediate layers outputs. Please register an appropriate callback.')\nq_z_given_x = self.layer_outputs['q_z_given_x']\nz = self.l... | <|body_start_0|>
super(VAEGMPLoss, self).__init__()
self.layer_outputs = None
self.beta = beta
self.reduction = reduction
<|end_body_0|>
<|body_start_1|>
if self.layer_outputs is None:
raise ValueError('This loss needs intermediate layers outputs. Please register an ... | VAEGMP Loss. | VAEGMPLoss | [
"LicenseRef-scancode-cecill-b-en"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VAEGMPLoss:
"""VAEGMP Loss."""
def __init__(self, beta=1.0, reduction='entropy'):
"""Init class. Parameters ---------- beta: float, default 1 the weight of KL term regularization. reduction: str, default 'entropy' how to reduce the loss."""
<|body_0|>
def __call__(self, ... | stack_v2_sparse_classes_75kplus_train_065861 | 40,199 | permissive | [
{
"docstring": "Init class. Parameters ---------- beta: float, default 1 the weight of KL term regularization. reduction: str, default 'entropy' how to reduce the loss.",
"name": "__init__",
"signature": "def __init__(self, beta=1.0, reduction='entropy')"
},
{
"docstring": "Compute loss.",
"... | 2 | stack_v2_sparse_classes_30k_train_043920 | Implement the Python class `VAEGMPLoss` described below.
Class description:
VAEGMP Loss.
Method signatures and docstrings:
- def __init__(self, beta=1.0, reduction='entropy'): Init class. Parameters ---------- beta: float, default 1 the weight of KL term regularization. reduction: str, default 'entropy' how to reduce... | Implement the Python class `VAEGMPLoss` described below.
Class description:
VAEGMP Loss.
Method signatures and docstrings:
- def __init__(self, beta=1.0, reduction='entropy'): Init class. Parameters ---------- beta: float, default 1 the weight of KL term regularization. reduction: str, default 'entropy' how to reduce... | 28eb248a04b40d180677e8fa20f2297c6967da0b | <|skeleton|>
class VAEGMPLoss:
"""VAEGMP Loss."""
def __init__(self, beta=1.0, reduction='entropy'):
"""Init class. Parameters ---------- beta: float, default 1 the weight of KL term regularization. reduction: str, default 'entropy' how to reduce the loss."""
<|body_0|>
def __call__(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VAEGMPLoss:
"""VAEGMP Loss."""
def __init__(self, beta=1.0, reduction='entropy'):
"""Init class. Parameters ---------- beta: float, default 1 the weight of KL term regularization. reduction: str, default 'entropy' how to reduce the loss."""
super(VAEGMPLoss, self).__init__()
self.... | the_stack_v2_python_sparse | pynet/losses/generative.py | myMyth0211/pynet | train | 0 |
913d0fe63d4598c97a7f5bd212341eb3615e320e | [
"self.only_direct = kwargs.get('only_direct', False)\ntry:\n del kwargs['only_direct']\nexcept KeyError:\n pass\nsuper(MUCJabberBot, self).__init__(*args, **kwargs)\nuser, domain = str(self.jid).split('@')\nself.direct_message_re = re.compile('^%s(@%s)?[^\\\\w]? ' % (user, domain))",
"message = mess.getBody... | <|body_start_0|>
self.only_direct = kwargs.get('only_direct', False)
try:
del kwargs['only_direct']
except KeyError:
pass
super(MUCJabberBot, self).__init__(*args, **kwargs)
user, domain = str(self.jid).split('@')
self.direct_message_re = re.compil... | Add features in JabberBot to allow it to handle specific caractheristics of multiple users chatroom (MUC). | MUCJabberBot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MUCJabberBot:
"""Add features in JabberBot to allow it to handle specific caractheristics of multiple users chatroom (MUC)."""
def __init__(self, *args, **kwargs):
"""Initialize variables."""
<|body_0|>
def callback_message(self, conn, mess):
"""Changes the behav... | stack_v2_sparse_classes_75kplus_train_065862 | 2,341 | no_license | [
{
"docstring": "Initialize variables.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Changes the behaviour of the JabberBot in order to allow it to answer direct messages. This is used often when it is connected in MUCs (multiple users chatroom).",
... | 2 | stack_v2_sparse_classes_30k_train_041611 | Implement the Python class `MUCJabberBot` described below.
Class description:
Add features in JabberBot to allow it to handle specific caractheristics of multiple users chatroom (MUC).
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize variables.
- def callback_message(self, conn, mes... | Implement the Python class `MUCJabberBot` described below.
Class description:
Add features in JabberBot to allow it to handle specific caractheristics of multiple users chatroom (MUC).
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize variables.
- def callback_message(self, conn, mes... | 1897867f2db96cc24ba76a4cb7ef3a7c373b4289 | <|skeleton|>
class MUCJabberBot:
"""Add features in JabberBot to allow it to handle specific caractheristics of multiple users chatroom (MUC)."""
def __init__(self, *args, **kwargs):
"""Initialize variables."""
<|body_0|>
def callback_message(self, conn, mess):
"""Changes the behav... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MUCJabberBot:
"""Add features in JabberBot to allow it to handle specific caractheristics of multiple users chatroom (MUC)."""
def __init__(self, *args, **kwargs):
"""Initialize variables."""
self.only_direct = kwargs.get('only_direct', False)
try:
del kwargs['only_dir... | the_stack_v2_python_sparse | eve_django/eve_bot/mucbot.py | zhyrohaad/eve-code | train | 0 |
c783eac9327ad43e302fbfb66b43e5ec7bc3c1bf | [
"if not quota_max_calls:\n use_rate_limiter = False\nself._instances = None\nsuper(CloudSqlRepositoryClient, self).__init__(API_NAME, versions=['v1beta4'], quota_max_calls=quota_max_calls, quota_period=quota_period, use_rate_limiter=use_rate_limiter)",
"if not self._instances:\n self._instances = self._init... | <|body_start_0|>
if not quota_max_calls:
use_rate_limiter = False
self._instances = None
super(CloudSqlRepositoryClient, self).__init__(API_NAME, versions=['v1beta4'], quota_max_calls=quota_max_calls, quota_period=quota_period, use_rate_limiter=use_rate_limiter)
<|end_body_0|>
<|bod... | Cloud SQL Admin API Respository. | CloudSqlRepositoryClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudSqlRepositoryClient:
"""Cloud SQL Admin API Respository."""
def __init__(self, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to t... | stack_v2_sparse_classes_75kplus_train_065863 | 4,834 | permissive | [
{
"docstring": "Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to track requests over. use_rate_limiter (bool): Set to false to disable the use of a rate limiter for this service.",
"name": "__init__",
"signature": "def __... | 2 | stack_v2_sparse_classes_30k_train_049074 | Implement the Python class `CloudSqlRepositoryClient` described below.
Class description:
Cloud SQL Admin API Respository.
Method signatures and docstrings:
- def __init__(self, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True): Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period... | Implement the Python class `CloudSqlRepositoryClient` described below.
Class description:
Cloud SQL Admin API Respository.
Method signatures and docstrings:
- def __init__(self, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True): Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class CloudSqlRepositoryClient:
"""Cloud SQL Admin API Respository."""
def __init__(self, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CloudSqlRepositoryClient:
"""Cloud SQL Admin API Respository."""
def __init__(self, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to track requests... | the_stack_v2_python_sparse | google/cloud/forseti/common/gcp_api/cloudsql.py | kevensen/forseti-security | train | 1 |
0518b552a4faa6d011c8a12dc5848a8000a9fa08 | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects",
"if list_dictionaries is None or len(list_dictionaries) == 0:\n return '[]'\nelse:\n return json.dumps(list_dictionaries)",
"if list_objs is None:\n list_objs = []\ndicts = []\nfor elements in ra... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
<|end_body_0|>
<|body_start_1|>
if list_dictionaries is None or len(list_dictionaries) == 0:
return '[]'
else:
return jso... | Base class with constructor method Args: None. Attributes: __nb_objects(int): id counter | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""Base class with constructor method Args: None. Attributes: __nb_objects(int): id counter"""
def __init__(self, id=None):
"""Constructor method Args: id (int): id argument"""
<|body_0|>
def to_json_string(list_dictionaries):
"""returns the JSON string rep... | stack_v2_sparse_classes_75kplus_train_065864 | 2,883 | no_license | [
{
"docstring": "Constructor method Args: id (int): id argument",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "returns the JSON string representation of list_dictionaries Args: list_dictonaries (list): list of dictionaries",
"name": "to_json_string",
"... | 6 | stack_v2_sparse_classes_30k_train_020103 | Implement the Python class `Base` described below.
Class description:
Base class with constructor method Args: None. Attributes: __nb_objects(int): id counter
Method signatures and docstrings:
- def __init__(self, id=None): Constructor method Args: id (int): id argument
- def to_json_string(list_dictionaries): return... | Implement the Python class `Base` described below.
Class description:
Base class with constructor method Args: None. Attributes: __nb_objects(int): id counter
Method signatures and docstrings:
- def __init__(self, id=None): Constructor method Args: id (int): id argument
- def to_json_string(list_dictionaries): return... | 77311f452e8d62145b5e7afe151557ed7a6d210a | <|skeleton|>
class Base:
"""Base class with constructor method Args: None. Attributes: __nb_objects(int): id counter"""
def __init__(self, id=None):
"""Constructor method Args: id (int): id argument"""
<|body_0|>
def to_json_string(list_dictionaries):
"""returns the JSON string rep... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Base:
"""Base class with constructor method Args: None. Attributes: __nb_objects(int): id counter"""
def __init__(self, id=None):
"""Constructor method Args: id (int): id argument"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
s... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | Matteo-lu/holbertonschool-higher_level_programming | train | 0 |
69687f30b83f26d9974865f4999b4110701369ae | [
"self.filename = None\nself.src_path = None\nself.unknown_short = None\nself.unknown_long_1 = None\nself.unknown_long_2 = None\nself.temp_path = None\nself.actual_size = None\nself.data = None\nself.package = package\nif bindata is not None:\n self.parse(data=bindata)",
"if not self.package:\n self.native_d... | <|body_start_0|>
self.filename = None
self.src_path = None
self.unknown_short = None
self.unknown_long_1 = None
self.unknown_long_2 = None
self.temp_path = None
self.actual_size = None
self.data = None
self.package = package
if bindata is n... | OLE object contained into an OLENativeStream structure. (see MS-OLEDS 2.3.6 OLENativeStream) | OleNativeStream | [
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OleNativeStream:
"""OLE object contained into an OLENativeStream structure. (see MS-OLEDS 2.3.6 OLENativeStream)"""
def __init__(self, bindata=None, package=False):
"""Constructor for OleNativeStream. If bindata is provided, it will be parsed using the parse() method. :param bindata:... | stack_v2_sparse_classes_75kplus_train_065865 | 18,572 | permissive | [
{
"docstring": "Constructor for OleNativeStream. If bindata is provided, it will be parsed using the parse() method. :param bindata: bytes, OLENativeStream structure containing an OLE object :param package: bool, set to True when extracting from an OLE Package object",
"name": "__init__",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_003440 | Implement the Python class `OleNativeStream` described below.
Class description:
OLE object contained into an OLENativeStream structure. (see MS-OLEDS 2.3.6 OLENativeStream)
Method signatures and docstrings:
- def __init__(self, bindata=None, package=False): Constructor for OleNativeStream. If bindata is provided, it... | Implement the Python class `OleNativeStream` described below.
Class description:
OLE object contained into an OLENativeStream structure. (see MS-OLEDS 2.3.6 OLENativeStream)
Method signatures and docstrings:
- def __init__(self, bindata=None, package=False): Constructor for OleNativeStream. If bindata is provided, it... | 6e44429b912216455446aaee06336b6d28859bfb | <|skeleton|>
class OleNativeStream:
"""OLE object contained into an OLENativeStream structure. (see MS-OLEDS 2.3.6 OLENativeStream)"""
def __init__(self, bindata=None, package=False):
"""Constructor for OleNativeStream. If bindata is provided, it will be parsed using the parse() method. :param bindata:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OleNativeStream:
"""OLE object contained into an OLENativeStream structure. (see MS-OLEDS 2.3.6 OLENativeStream)"""
def __init__(self, bindata=None, package=False):
"""Constructor for OleNativeStream. If bindata is provided, it will be parsed using the parse() method. :param bindata: bytes, OLENa... | the_stack_v2_python_sparse | fame/env/lib/python2.7/site-packages/oletools/oleobj.py | MaikSoriano/TFM | train | 1 |
c6e1b2e3f9b1b14f4881ee9baa0e1999835e5ac2 | [
"units = Unit('hour')\nwidth = 5\nweights_instance = ChooseDefaultWeightsTriangular(width, units=units)\nexpected_width = 5\nexpected_unit = units\nself.assertEqual(weights_instance.width, expected_width)\nself.assertEqual(weights_instance.parameters_units, expected_unit)",
"units = 'hour'\nwidth = 5\nweights_ins... | <|body_start_0|>
units = Unit('hour')
width = 5
weights_instance = ChooseDefaultWeightsTriangular(width, units=units)
expected_width = 5
expected_unit = units
self.assertEqual(weights_instance.width, expected_width)
self.assertEqual(weights_instance.parameters_uni... | Tests for the __init__ method in ChooseDefaultWeightsTriangular class | Test___init__ | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test___init__:
"""Tests for the __init__ method in ChooseDefaultWeightsTriangular class"""
def test_cf_unit_input(self):
"""Test the case where an instance of cf_units.Unit is passed in"""
<|body_0|>
def test_string_input(self):
"""Test the case where a string is... | stack_v2_sparse_classes_75kplus_train_065866 | 13,166 | permissive | [
{
"docstring": "Test the case where an instance of cf_units.Unit is passed in",
"name": "test_cf_unit_input",
"signature": "def test_cf_unit_input(self)"
},
{
"docstring": "Test the case where a string is passed and gets converted to a Unit instance",
"name": "test_string_input",
"signat... | 2 | stack_v2_sparse_classes_30k_train_002035 | Implement the Python class `Test___init__` described below.
Class description:
Tests for the __init__ method in ChooseDefaultWeightsTriangular class
Method signatures and docstrings:
- def test_cf_unit_input(self): Test the case where an instance of cf_units.Unit is passed in
- def test_string_input(self): Test the c... | Implement the Python class `Test___init__` described below.
Class description:
Tests for the __init__ method in ChooseDefaultWeightsTriangular class
Method signatures and docstrings:
- def test_cf_unit_input(self): Test the case where an instance of cf_units.Unit is passed in
- def test_string_input(self): Test the c... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test___init__:
"""Tests for the __init__ method in ChooseDefaultWeightsTriangular class"""
def test_cf_unit_input(self):
"""Test the case where an instance of cf_units.Unit is passed in"""
<|body_0|>
def test_string_input(self):
"""Test the case where a string is... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test___init__:
"""Tests for the __init__ method in ChooseDefaultWeightsTriangular class"""
def test_cf_unit_input(self):
"""Test the case where an instance of cf_units.Unit is passed in"""
units = Unit('hour')
width = 5
weights_instance = ChooseDefaultWeightsTriangular(wid... | the_stack_v2_python_sparse | improver_tests/blending/weights/test_ChooseDefaultWeightsTriangular.py | metoppv/improver | train | 101 |
eb9a8cf46e986e429392775fb513b43e27880d56 | [
"self.root = {'5': {}, '10': {}, '20': {}, '50': {}, '100': {}}\nself.validator = re.compile('^[A-M][A-L](?!00000000)\\\\d{8}(?!O)(?!Z)[A-Z]$')\nif fname:\n with open(fname, 'r') as file:\n text = file.read().splitlines()\n for line in text:\n line = line.split(' ')\n self.ins... | <|body_start_0|>
self.root = {'5': {}, '10': {}, '20': {}, '50': {}, '100': {}}
self.validator = re.compile('^[A-M][A-L](?!00000000)\\d{8}(?!O)(?!Z)[A-Z]$')
if fname:
with open(fname, 'r') as file:
text = file.read().splitlines()
for line in text:
... | WatchListDict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WatchListDict:
def __init__(self, fname=''):
"""This magic method initializes a root variable to a dictionary with each denomination being a key to an empty dictionary."""
<|body_0|>
def insert(self, serial_num, denom):
"""This method adds a serial number to the watc... | stack_v2_sparse_classes_75kplus_train_065867 | 4,827 | no_license | [
{
"docstring": "This magic method initializes a root variable to a dictionary with each denomination being a key to an empty dictionary.",
"name": "__init__",
"signature": "def __init__(self, fname='')"
},
{
"docstring": "This method adds a serial number to the watchlistDict.",
"name": "inse... | 3 | stack_v2_sparse_classes_30k_train_004282 | Implement the Python class `WatchListDict` described below.
Class description:
Implement the WatchListDict class.
Method signatures and docstrings:
- def __init__(self, fname=''): This magic method initializes a root variable to a dictionary with each denomination being a key to an empty dictionary.
- def insert(self... | Implement the Python class `WatchListDict` described below.
Class description:
Implement the WatchListDict class.
Method signatures and docstrings:
- def __init__(self, fname=''): This magic method initializes a root variable to a dictionary with each denomination being a key to an empty dictionary.
- def insert(self... | e773e87668af057c8adb1e012aa5d81f42c70f2a | <|skeleton|>
class WatchListDict:
def __init__(self, fname=''):
"""This magic method initializes a root variable to a dictionary with each denomination being a key to an empty dictionary."""
<|body_0|>
def insert(self, serial_num, denom):
"""This method adds a serial number to the watc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WatchListDict:
def __init__(self, fname=''):
"""This magic method initializes a root variable to a dictionary with each denomination being a key to an empty dictionary."""
self.root = {'5': {}, '10': {}, '20': {}, '50': {}, '100': {}}
self.validator = re.compile('^[A-M][A-L](?!00000000... | the_stack_v2_python_sparse | HW/HW2/hw2.py | SiddhantBhardwaj2018/ISTA-350 | train | 0 | |
e5ab5511bfc15c6f36690c752b5cbeb03171476d | [
"context = super(ExhibitionListView, self).get_context_data(**kwargs)\ncontext['now'] = 'active'\ncontext['title'] = 'Расписание выставок.'\nreturn context",
"qs = super(ExhibitionListView, self).get_queryset()\nqs = qs.filter(date__gte=timezone.now())\nreturn qs"
] | <|body_start_0|>
context = super(ExhibitionListView, self).get_context_data(**kwargs)
context['now'] = 'active'
context['title'] = 'Расписание выставок.'
return context
<|end_body_0|>
<|body_start_1|>
qs = super(ExhibitionListView, self).get_queryset()
qs = qs.filter(dat... | List of exhibition which will | ExhibitionListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExhibitionListView:
"""List of exhibition which will"""
def get_context_data(self, **kwargs):
"""Extends context data :param kwargs: :return: context"""
<|body_0|>
def get_queryset(self):
"""Filter exhibition :return: exhibition which will"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_065868 | 5,515 | no_license | [
{
"docstring": "Extends context data :param kwargs: :return: context",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Filter exhibition :return: exhibition which will",
"name": "get_queryset",
"signature": "def get_queryset(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054336 | Implement the Python class `ExhibitionListView` described below.
Class description:
List of exhibition which will
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Extends context data :param kwargs: :return: context
- def get_queryset(self): Filter exhibition :return: exhibition which will | Implement the Python class `ExhibitionListView` described below.
Class description:
List of exhibition which will
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Extends context data :param kwargs: :return: context
- def get_queryset(self): Filter exhibition :return: exhibition which will
<... | 8eb18b831e034302f90585a179110336bb18af45 | <|skeleton|>
class ExhibitionListView:
"""List of exhibition which will"""
def get_context_data(self, **kwargs):
"""Extends context data :param kwargs: :return: context"""
<|body_0|>
def get_queryset(self):
"""Filter exhibition :return: exhibition which will"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExhibitionListView:
"""List of exhibition which will"""
def get_context_data(self, **kwargs):
"""Extends context data :param kwargs: :return: context"""
context = super(ExhibitionListView, self).get_context_data(**kwargs)
context['now'] = 'active'
context['title'] = 'Распи... | the_stack_v2_python_sparse | exhibition/views.py | YevheniiaSmyrnova/butterflies | train | 0 |
725e4d0467b321246204125762617869a830bbbd | [
"if not self.is_empty():\n for p in self._subtree_preorder(self.root()):\n yield p",
"for c in self.children(p):\n for other in self._subtree_preorder(c):\n yield other\nyield p"
] | <|body_start_0|>
if not self.is_empty():
for p in self._subtree_preorder(self.root()):
yield p
<|end_body_0|>
<|body_start_1|>
for c in self.children(p):
for other in self._subtree_preorder(c):
yield other
yield p
<|end_body_1|>
| TreeTraversals | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeTraversals:
def postorder(self):
"""Generate a postorder iteration of positions in the tree."""
<|body_0|>
def _subtre_postorder(self, p):
"""Generate a postorder iteration of positions in subtree rooted at p."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_75kplus_train_065869 | 740 | permissive | [
{
"docstring": "Generate a postorder iteration of positions in the tree.",
"name": "postorder",
"signature": "def postorder(self)"
},
{
"docstring": "Generate a postorder iteration of positions in subtree rooted at p.",
"name": "_subtre_postorder",
"signature": "def _subtre_postorder(sel... | 2 | stack_v2_sparse_classes_30k_train_000544 | Implement the Python class `TreeTraversals` described below.
Class description:
Implement the TreeTraversals class.
Method signatures and docstrings:
- def postorder(self): Generate a postorder iteration of positions in the tree.
- def _subtre_postorder(self, p): Generate a postorder iteration of positions in subtree... | Implement the Python class `TreeTraversals` described below.
Class description:
Implement the TreeTraversals class.
Method signatures and docstrings:
- def postorder(self): Generate a postorder iteration of positions in the tree.
- def _subtre_postorder(self, p): Generate a postorder iteration of positions in subtree... | fc18b54128cd5bc7639a14999d8f990190b524eb | <|skeleton|>
class TreeTraversals:
def postorder(self):
"""Generate a postorder iteration of positions in the tree."""
<|body_0|>
def _subtre_postorder(self, p):
"""Generate a postorder iteration of positions in subtree rooted at p."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TreeTraversals:
def postorder(self):
"""Generate a postorder iteration of positions in the tree."""
if not self.is_empty():
for p in self._subtree_preorder(self.root()):
yield p
def _subtre_postorder(self, p):
"""Generate a postorder iteration of positi... | the_stack_v2_python_sparse | CHAPTER 08 (trees)/postorder_traversals.py | ahammadshawki8/DSA-Implementations-in-Python | train | 2 | |
697d43254289ce54ac3ea2745d14ddcfda16c393 | [
"repeat = set()\nma, mi = (0, 14)\nfor num in nums:\n if num == 0:\n continue\n ma = max(ma, num)\n mi = min(mi, num)\n if num in repeat:\n return False\n repeat.add(num)\nreturn ma - mi < 5",
"repeat = set()\nma, mi = (0, 14)\nfor num in nums:\n if num == 0:\n continue\n ... | <|body_start_0|>
repeat = set()
ma, mi = (0, 14)
for num in nums:
if num == 0:
continue
ma = max(ma, num)
mi = min(mi, num)
if num in repeat:
return False
repeat.add(num)
return ma - mi < 5
<|end_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isStraight_1(self, nums: List[int]) -> bool:
"""方法一: 集合 Set + 遍历 时间复杂度 O(N) = O(5) = O(1): 其中 N 为 nums 长度,本题中 N≡5 ;遍历数组使用 O(N) 时间。 空间复杂度 O(N) = O(5) = O(1): 用于判重的辅助 Set 使用 O(N) 额外空间。 :param nums: :return:"""
<|body_0|>
def isStraight_2(self, nums: List[int]) ->... | stack_v2_sparse_classes_75kplus_train_065870 | 2,241 | no_license | [
{
"docstring": "方法一: 集合 Set + 遍历 时间复杂度 O(N) = O(5) = O(1): 其中 N 为 nums 长度,本题中 N≡5 ;遍历数组使用 O(N) 时间。 空间复杂度 O(N) = O(5) = O(1): 用于判重的辅助 Set 使用 O(N) 额外空间。 :param nums: :return:",
"name": "isStraight_1",
"signature": "def isStraight_1(self, nums: List[int]) -> bool"
},
{
"docstring": "方法二:排序 + 遍历 时间复... | 2 | stack_v2_sparse_classes_30k_train_031661 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isStraight_1(self, nums: List[int]) -> bool: 方法一: 集合 Set + 遍历 时间复杂度 O(N) = O(5) = O(1): 其中 N 为 nums 长度,本题中 N≡5 ;遍历数组使用 O(N) 时间。 空间复杂度 O(N) = O(5) = O(1): 用于判重的辅助 Set 使用 O(N) ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isStraight_1(self, nums: List[int]) -> bool: 方法一: 集合 Set + 遍历 时间复杂度 O(N) = O(5) = O(1): 其中 N 为 nums 长度,本题中 N≡5 ;遍历数组使用 O(N) 时间。 空间复杂度 O(N) = O(5) = O(1): 用于判重的辅助 Set 使用 O(N) ... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def isStraight_1(self, nums: List[int]) -> bool:
"""方法一: 集合 Set + 遍历 时间复杂度 O(N) = O(5) = O(1): 其中 N 为 nums 长度,本题中 N≡5 ;遍历数组使用 O(N) 时间。 空间复杂度 O(N) = O(5) = O(1): 用于判重的辅助 Set 使用 O(N) 额外空间。 :param nums: :return:"""
<|body_0|>
def isStraight_2(self, nums: List[int]) ->... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isStraight_1(self, nums: List[int]) -> bool:
"""方法一: 集合 Set + 遍历 时间复杂度 O(N) = O(5) = O(1): 其中 N 为 nums 长度,本题中 N≡5 ;遍历数组使用 O(N) 时间。 空间复杂度 O(N) = O(5) = O(1): 用于判重的辅助 Set 使用 O(N) 额外空间。 :param nums: :return:"""
repeat = set()
ma, mi = (0, 14)
for num in nums:
... | the_stack_v2_python_sparse | 剑指 Offer(第 2 版)/isStraight.py | MaoningGuan/LeetCode | train | 3 | |
7a434521b9e8f5b04fee20104f0f981af13f825b | [
"super(EncoderBlock, self).__init__()\nself.mha = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(... | <|body_start_0|>
super(EncoderBlock, self).__init__()
self.mha = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)
... | Encoder Block class | EncoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderBlock:
"""Encoder Block class"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Function that initilizes"""
<|body_0|>
def call(self, x, training, mask=None):
"""Function that returns a tensor that contains block’s output"""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus_train_065871 | 1,303 | no_license | [
{
"docstring": "Function that initilizes",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "Function that returns a tensor that contains block’s output",
"name": "call",
"signature": "def call(self, x, training, mask=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054357 | Implement the Python class `EncoderBlock` described below.
Class description:
Encoder Block class
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): Function that initilizes
- def call(self, x, training, mask=None): Function that returns a tensor that contains block’s output | Implement the Python class `EncoderBlock` described below.
Class description:
Encoder Block class
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): Function that initilizes
- def call(self, x, training, mask=None): Function that returns a tensor that contains block’s output
<|skel... | 9dbf8221d4eb22dbc2487cb55e84a801a38aa5c8 | <|skeleton|>
class EncoderBlock:
"""Encoder Block class"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Function that initilizes"""
<|body_0|>
def call(self, x, training, mask=None):
"""Function that returns a tensor that contains block’s output"""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EncoderBlock:
"""Encoder Block class"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Function that initilizes"""
super(EncoderBlock, self).__init__()
self.mha = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
s... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/7-transformer_encoder_block.py | yasmineholb/holbertonschool-machine_learning | train | 0 |
0a5c9dc448b7c035fc8fa798f2834cfafa6134e5 | [
"while True:\n yield c\npass",
"gna = GNA.LinearCongruentialGenerator(seed=seed)\nwhile True:\n u1 = gna.next()\n u2 = gna.next()\n Z = math.sqrt(-2 * math.log(u1))\n if Z1:\n Z *= math.cos(2 * math.pi * u2)\n else:\n Z *= math.sin(2 * math.pi * u2)\n yield (media + desvio_padra... | <|body_start_0|>
while True:
yield c
pass
<|end_body_0|>
<|body_start_1|>
gna = GNA.LinearCongruentialGenerator(seed=seed)
while True:
u1 = gna.next()
u2 = gna.next()
Z = math.sqrt(-2 * math.log(u1))
if Z1:
Z *=... | Classe responsável pela geração de variáveis aleatórias. | FGVA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FGVA:
"""Classe responsável pela geração de variáveis aleatórias."""
def Constante(c):
"""Criador de um gerador de valores constante. @param c: valor constante a ser retornada pelo gerador. @return: um gerador de valores constantes"""
<|body_0|>
def Normal(media, desvio_... | stack_v2_sparse_classes_75kplus_train_065872 | 3,436 | no_license | [
{
"docstring": "Criador de um gerador de valores constante. @param c: valor constante a ser retornada pelo gerador. @return: um gerador de valores constantes",
"name": "Constante",
"signature": "def Constante(c)"
},
{
"docstring": "Criador de um gerador de valores seguindo uma distribuição norma... | 5 | stack_v2_sparse_classes_30k_train_040291 | Implement the Python class `FGVA` described below.
Class description:
Classe responsável pela geração de variáveis aleatórias.
Method signatures and docstrings:
- def Constante(c): Criador de um gerador de valores constante. @param c: valor constante a ser retornada pelo gerador. @return: um gerador de valores consta... | Implement the Python class `FGVA` described below.
Class description:
Classe responsável pela geração de variáveis aleatórias.
Method signatures and docstrings:
- def Constante(c): Criador de um gerador de valores constante. @param c: valor constante a ser retornada pelo gerador. @return: um gerador de valores consta... | f914f50ab02f222b13aa35ae2dc0be30ba309925 | <|skeleton|>
class FGVA:
"""Classe responsável pela geração de variáveis aleatórias."""
def Constante(c):
"""Criador de um gerador de valores constante. @param c: valor constante a ser retornada pelo gerador. @return: um gerador de valores constantes"""
<|body_0|>
def Normal(media, desvio_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FGVA:
"""Classe responsável pela geração de variáveis aleatórias."""
def Constante(c):
"""Criador de um gerador de valores constante. @param c: valor constante a ser retornada pelo gerador. @return: um gerador de valores constantes"""
while True:
yield c
pass
def ... | the_stack_v2_python_sparse | src/Simulador/FGVA.py | cesarecorrea94/MeS.py | train | 0 |
f3a956b2141053b8acb3a7d0271923fc3f9e103a | [
"assert issubclass(splitter.__class__, wx.SplitterWindow), u'SplitterWindow manager type error'\nsetattr(self, '_last_sash_position_%s' % splitter.GetId(), splitter.GetSashPosition())\nif resize_panel == 0:\n splitter.SetSashPosition(1, redraw=redraw)\nelif resize_panel == 1:\n split_mode = splitter.GetSplitM... | <|body_start_0|>
assert issubclass(splitter.__class__, wx.SplitterWindow), u'SplitterWindow manager type error'
setattr(self, '_last_sash_position_%s' % splitter.GetId(), splitter.GetSashPosition())
if resize_panel == 0:
splitter.SetSashPosition(1, redraw=redraw)
elif resize_... | Splitter window manager. | iqSplitterWindowManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class iqSplitterWindowManager:
"""Splitter window manager."""
def collapseSplitterWindowPanel(self, splitter, toolbar=None, collapse_tool=None, expand_tool=None, resize_panel=0, redraw=True):
"""Collapse the splitter panel. :param splitter: wx.SplitterWindow object. :param toolbar: ToolBar... | stack_v2_sparse_classes_75kplus_train_065873 | 3,572 | no_license | [
{
"docstring": "Collapse the splitter panel. :param splitter: wx.SplitterWindow object. :param toolbar: ToolBar object. :param collapse_tool: Collapse tool. :param expand_tool: Expand tool. :param resize_panel: Resizable panel index. :param redraw: Redrawing object? :return: True/False.",
"name": "collapseS... | 2 | stack_v2_sparse_classes_30k_train_034668 | Implement the Python class `iqSplitterWindowManager` described below.
Class description:
Splitter window manager.
Method signatures and docstrings:
- def collapseSplitterWindowPanel(self, splitter, toolbar=None, collapse_tool=None, expand_tool=None, resize_panel=0, redraw=True): Collapse the splitter panel. :param sp... | Implement the Python class `iqSplitterWindowManager` described below.
Class description:
Splitter window manager.
Method signatures and docstrings:
- def collapseSplitterWindowPanel(self, splitter, toolbar=None, collapse_tool=None, expand_tool=None, resize_panel=0, redraw=True): Collapse the splitter panel. :param sp... | 7550e242746cb2fb1219474463f8db21f8e3e114 | <|skeleton|>
class iqSplitterWindowManager:
"""Splitter window manager."""
def collapseSplitterWindowPanel(self, splitter, toolbar=None, collapse_tool=None, expand_tool=None, resize_panel=0, redraw=True):
"""Collapse the splitter panel. :param splitter: wx.SplitterWindow object. :param toolbar: ToolBar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class iqSplitterWindowManager:
"""Splitter window manager."""
def collapseSplitterWindowPanel(self, splitter, toolbar=None, collapse_tool=None, expand_tool=None, resize_panel=0, redraw=True):
"""Collapse the splitter panel. :param splitter: wx.SplitterWindow object. :param toolbar: ToolBar object. :par... | the_stack_v2_python_sparse | iq/engine/wx/splitter_manager.py | XHermitOne/iq_framework | train | 1 |
3129433c1ee56338d3e7aecd45e77590651e34b2 | [
"m, n = (len(nums1), len(nums2))\nif m == 0:\n if n & 1 == 0:\n return (nums2[n // 2] + nums2[n // 2 - 1]) / 2\n return nums2[n // 2]\nif n == 0:\n if m & 1 == 0:\n return (nums1[m // 2] + nums1[m // 2 - 1]) / 2\n return nums1[m // 2]\ntotal = m + n\nif total & 1 == 1:\n return self.fin... | <|body_start_0|>
m, n = (len(nums1), len(nums2))
if m == 0:
if n & 1 == 0:
return (nums2[n // 2] + nums2[n // 2 - 1]) / 2
return nums2[n // 2]
if n == 0:
if m & 1 == 0:
return (nums1[m // 2] + nums1[m // 2 - 1]) / 2
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
"""两个有序数组求中位数,问题一般化为,求两个有序数组的第k个数,当k = (m+n)/2时为原问题的解。 怎么求第k个数?分别求出第一个和第二个数组的第 k / 2个数 a 和 b,然后比较 a 和 b,当a < b , 说明第 k 个数位于 a数组的第 k / 2个数后半段,或者b数组的 第 k / 2 个数前半段,问题规模缩小了一半, 然后递归处理就行。 时间复杂度是 O(log(m+n... | stack_v2_sparse_classes_75kplus_train_065874 | 3,908 | no_license | [
{
"docstring": "两个有序数组求中位数,问题一般化为,求两个有序数组的第k个数,当k = (m+n)/2时为原问题的解。 怎么求第k个数?分别求出第一个和第二个数组的第 k / 2个数 a 和 b,然后比较 a 和 b,当a < b , 说明第 k 个数位于 a数组的第 k / 2个数后半段,或者b数组的 第 k / 2 个数前半段,问题规模缩小了一半, 然后递归处理就行。 时间复杂度是 O(log(m+n)) :param nums1: :param nums2: :return:",
"name": "findMedianSortedArrays",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_035076 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 两个有序数组求中位数,问题一般化为,求两个有序数组的第k个数,当k = (m+n)/2时为原问题的解。 怎么求第k个数?分别求出第一个和第二个数组的第 k / 2个数 a 和 b,然后比较 a 和 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 两个有序数组求中位数,问题一般化为,求两个有序数组的第k个数,当k = (m+n)/2时为原问题的解。 怎么求第k个数?分别求出第一个和第二个数组的第 k / 2个数 a 和 b,然后比较 a 和 ... | 971cc2f674d53cf33a621a3a608f32a53603438a | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
"""两个有序数组求中位数,问题一般化为,求两个有序数组的第k个数,当k = (m+n)/2时为原问题的解。 怎么求第k个数?分别求出第一个和第二个数组的第 k / 2个数 a 和 b,然后比较 a 和 b,当a < b , 说明第 k 个数位于 a数组的第 k / 2个数后半段,或者b数组的 第 k / 2 个数前半段,问题规模缩小了一半, 然后递归处理就行。 时间复杂度是 O(log(m+n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
"""两个有序数组求中位数,问题一般化为,求两个有序数组的第k个数,当k = (m+n)/2时为原问题的解。 怎么求第k个数?分别求出第一个和第二个数组的第 k / 2个数 a 和 b,然后比较 a 和 b,当a < b , 说明第 k 个数位于 a数组的第 k / 2个数后半段,或者b数组的 第 k / 2 个数前半段,问题规模缩小了一半, 然后递归处理就行。 时间复杂度是 O(log(m+n)) :param nums... | the_stack_v2_python_sparse | LeetCode/困难/4寻找两个有序数组的中位数.py | xiyangxitian1/learn_days | train | 0 | |
9ad57a251cdb7e76e23e230c304e9553e0906a8e | [
"self.k = k\nself.top_k_heap = nums\nheapify(self.top_k_heap)\nwhile len(self.top_k_heap) > k:\n heappop(self.top_k_heap)",
"if len(self.top_k_heap) < self.k:\n heappush(self.top_k_heap, val)\nelif val > self.top_k_heap[0]:\n heapreplace(self.top_k_heap, val)\nreturn self.top_k_heap[0]"
] | <|body_start_0|>
self.k = k
self.top_k_heap = nums
heapify(self.top_k_heap)
while len(self.top_k_heap) > k:
heappop(self.top_k_heap)
<|end_body_0|>
<|body_start_1|>
if len(self.top_k_heap) < self.k:
heappush(self.top_k_heap, val)
elif val > self.t... | 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.top_k_heap = nums
heapify(... | stack_v2_sparse_classes_75kplus_train_065875 | 776 | 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_037172 | 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... | 0ceccdb262149f7916cb30fa5f3dae93aef9e9cd | <|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.top_k_heap = nums
heapify(self.top_k_heap)
while len(self.top_k_heap) > k:
heappop(self.top_k_heap)
def add(self, val):
""":type val: int :rtype: i... | the_stack_v2_python_sparse | easy/703_kth_largest_element_in_a_stream.py | esddse/leetcode | train | 0 | |
99008db66631ce402de3bca9aa1899ddbc49a729 | [
"_input_table = DataFrame({'ID': [0, 1, 1, 2], 'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5]})\n_groupings = [{'operator': 'mean', 'columns': ['a', 'b']}]\n_expected = DataFrame({'ID': [0, 1, 1, 2], 'meanab': [1.5, 2.5, 3.5, 4.5]})\n_ca = aggregate_columns.ColumnAggregator(_input_table)\n_ca.aggregate(_groupings)\nassert_fr... | <|body_start_0|>
_input_table = DataFrame({'ID': [0, 1, 1, 2], 'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5]})
_groupings = [{'operator': 'mean', 'columns': ['a', 'b']}]
_expected = DataFrame({'ID': [0, 1, 1, 2], 'meanab': [1.5, 2.5, 3.5, 4.5]})
_ca = aggregate_columns.ColumnAggregator(_input_tab... | Tests for the ``aggregate_columns.ColumnAggregator._mean`` module. Assert final data frames match expectations. | PreprocessMeanTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreprocessMeanTests:
"""Tests for the ``aggregate_columns.ColumnAggregator._mean`` module. Assert final data frames match expectations."""
def test_aggregate_mean_columns_1():
"""Test aggregating with the "mean" operation over two columns on an example DataFrame."""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_065876 | 2,876 | permissive | [
{
"docstring": "Test aggregating with the \"mean\" operation over two columns on an example DataFrame.",
"name": "test_aggregate_mean_columns_1",
"signature": "def test_aggregate_mean_columns_1()"
},
{
"docstring": "Test aggregating with the \"mean\" operation over three columns on an example Da... | 4 | stack_v2_sparse_classes_30k_train_029351 | Implement the Python class `PreprocessMeanTests` described below.
Class description:
Tests for the ``aggregate_columns.ColumnAggregator._mean`` module. Assert final data frames match expectations.
Method signatures and docstrings:
- def test_aggregate_mean_columns_1(): Test aggregating with the "mean" operation over ... | Implement the Python class `PreprocessMeanTests` described below.
Class description:
Tests for the ``aggregate_columns.ColumnAggregator._mean`` module. Assert final data frames match expectations.
Method signatures and docstrings:
- def test_aggregate_mean_columns_1(): Test aggregating with the "mean" operation over ... | 2e89bc55a61ce2a4ce77646bb427f5b3040f672c | <|skeleton|>
class PreprocessMeanTests:
"""Tests for the ``aggregate_columns.ColumnAggregator._mean`` module. Assert final data frames match expectations."""
def test_aggregate_mean_columns_1():
"""Test aggregating with the "mean" operation over two columns on an example DataFrame."""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PreprocessMeanTests:
"""Tests for the ``aggregate_columns.ColumnAggregator._mean`` module. Assert final data frames match expectations."""
def test_aggregate_mean_columns_1():
"""Test aggregating with the "mean" operation over two columns on an example DataFrame."""
_input_table = DataFra... | the_stack_v2_python_sparse | numom2b_preprocessing/unittests/column_aggregate_tests/test_aggregate_mean.py | hayesall/nuMoM2b_preprocessing | train | 2 |
cee2e8568aa7b67d2ce5726e2c87294f62a3d761 | [
"super().__init__(**kwargs)\nself._output_shape = output_shape\nif isinstance(cp_spacing, int):\n cp_spacing = (cp_spacing, cp_spacing, cp_spacing)\nself.cp_spacing = cp_spacing",
"super().build(input_shape=input_shape)\nb = {0: lambda u: np.float64((1 - u) ** 3 / 6), 1: lambda u: np.float64((3 * u ** 3 - 6 * ... | <|body_start_0|>
super().__init__(**kwargs)
self._output_shape = output_shape
if isinstance(cp_spacing, int):
cp_spacing = (cp_spacing, cp_spacing, cp_spacing)
self.cp_spacing = cp_spacing
<|end_body_0|>
<|body_start_1|>
super().build(input_shape=input_shape)
... | Layer for BSplines interpolation with precomputed cubic spline kernel_size. It assumes a full sized image from which: 1. it compute the contol points values by down-sampling the initial image 2. performs the interpolation 3. crops the image around the valid values. | BSplines3DTransform | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSplines3DTransform:
"""Layer for BSplines interpolation with precomputed cubic spline kernel_size. It assumes a full sized image from which: 1. it compute the contol points values by down-sampling the initial image 2. performs the interpolation 3. crops the image around the valid values."""
... | stack_v2_sparse_classes_75kplus_train_065877 | 20,226 | permissive | [
{
"docstring": "Init. :param cp_spacing: int or tuple of three ints specifying the spacing (in pixels) in each dimension. When a single int is used, the same spacing to all dimensions is used :param output_shape: (batch_size, dim0, dim1, dim2, 3) of the high resolution deformation fields. :param kwargs: additio... | 4 | null | Implement the Python class `BSplines3DTransform` described below.
Class description:
Layer for BSplines interpolation with precomputed cubic spline kernel_size. It assumes a full sized image from which: 1. it compute the contol points values by down-sampling the initial image 2. performs the interpolation 3. crops the... | Implement the Python class `BSplines3DTransform` described below.
Class description:
Layer for BSplines interpolation with precomputed cubic spline kernel_size. It assumes a full sized image from which: 1. it compute the contol points values by down-sampling the initial image 2. performs the interpolation 3. crops the... | 650a2f1a88ad3c6932be305d6a98a36e26feedc6 | <|skeleton|>
class BSplines3DTransform:
"""Layer for BSplines interpolation with precomputed cubic spline kernel_size. It assumes a full sized image from which: 1. it compute the contol points values by down-sampling the initial image 2. performs the interpolation 3. crops the image around the valid values."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BSplines3DTransform:
"""Layer for BSplines interpolation with precomputed cubic spline kernel_size. It assumes a full sized image from which: 1. it compute the contol points values by down-sampling the initial image 2. performs the interpolation 3. crops the image around the valid values."""
def __init__... | the_stack_v2_python_sparse | deepreg/model/layer.py | DeepRegNet/DeepReg | train | 509 |
3213c128818ca2e58b540d652e346cf6f98f4ca9 | [
"super().__init__(parent)\nShotBoard.create_background(self, (200, 200, 200), (64, 64, 64))\nself.placed_shots = []",
"new_shot = engine.RectGameObject(self, engine.math.Vector2(32, 32), 0, (255, 0, 0) if hit else (64, 64, 64))\nprint(self.get_top_left())\nnew_shot.transform.set_world_position(at * Board.CELL_SIZ... | <|body_start_0|>
super().__init__(parent)
ShotBoard.create_background(self, (200, 200, 200), (64, 64, 64))
self.placed_shots = []
<|end_body_0|>
<|body_start_1|>
new_shot = engine.RectGameObject(self, engine.math.Vector2(32, 32), 0, (255, 0, 0) if hit else (64, 64, 64))
print(se... | Board object that renders all the shots from the player. | ShotBoard | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShotBoard:
"""Board object that renders all the shots from the player."""
def __init__(self, parent):
"""Class constructor. Creates a new board on the screen. :param parent: The parent of the board."""
<|body_0|>
def add_shot(self, at, hit):
"""Adds a new shot on... | stack_v2_sparse_classes_75kplus_train_065878 | 1,233 | permissive | [
{
"docstring": "Class constructor. Creates a new board on the screen. :param parent: The parent of the board.",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Adds a new shot on the board. :param at: Where to put the shot. :param hit: True if the shot is a hit."... | 2 | stack_v2_sparse_classes_30k_train_000996 | Implement the Python class `ShotBoard` described below.
Class description:
Board object that renders all the shots from the player.
Method signatures and docstrings:
- def __init__(self, parent): Class constructor. Creates a new board on the screen. :param parent: The parent of the board.
- def add_shot(self, at, hit... | Implement the Python class `ShotBoard` described below.
Class description:
Board object that renders all the shots from the player.
Method signatures and docstrings:
- def __init__(self, parent): Class constructor. Creates a new board on the screen. :param parent: The parent of the board.
- def add_shot(self, at, hit... | a2b2d7b6221977e615ce0a0dbc18cb7c1fce05f1 | <|skeleton|>
class ShotBoard:
"""Board object that renders all the shots from the player."""
def __init__(self, parent):
"""Class constructor. Creates a new board on the screen. :param parent: The parent of the board."""
<|body_0|>
def add_shot(self, at, hit):
"""Adds a new shot on... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShotBoard:
"""Board object that renders all the shots from the player."""
def __init__(self, parent):
"""Class constructor. Creates a new board on the screen. :param parent: The parent of the board."""
super().__init__(parent)
ShotBoard.create_background(self, (200, 200, 200), (64... | the_stack_v2_python_sparse | battleships/objects/ShotBoard.py | yShimoka/Python-Bataille-Navale | train | 0 |
8f8c4a81c0ba8382b02f2f9621847f1933797ac8 | [
"self.agent_num = agent_num\nself.PID_acc = PIDController(1.0, 0, 0)\nself.PID_steer = PIDController(2.0, 0, 0)\nself.not_initiliazed = True",
"if not (isinstance(action, VelocityAction) or action == None):\n raise Exception('Action is not of type VelocityAction')\nif not state.dynamic_objects['controlled_cars... | <|body_start_0|>
self.agent_num = agent_num
self.PID_acc = PIDController(1.0, 0, 0)
self.PID_steer = PIDController(2.0, 0, 0)
self.not_initiliazed = True
<|end_body_0|>
<|body_start_1|>
if not (isinstance(action, VelocityAction) or action == None):
raise Exception('A... | Hierarichal agent which implements the full plannning stack except the velocity component The planner first generates a nominal trajecotry, then at each timestep recives a target velocity to track with PID controller. Attributes ---------- agent_num : int Index of this agent in the world. Used to access its object in s... | VelocityActionAgent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VelocityActionAgent:
"""Hierarichal agent which implements the full plannning stack except the velocity component The planner first generates a nominal trajecotry, then at each timestep recives a target velocity to track with PID controller. Attributes ---------- agent_num : int Index of this age... | stack_v2_sparse_classes_75kplus_train_065879 | 2,362 | permissive | [
{
"docstring": "Initializes the VelocityActionAgent Class Parameters ---------- agent_num: int The number which specifies the agent in the dictionary state.dynamic_objects['controlled_cars']",
"name": "__init__",
"signature": "def __init__(self, agent_num=0)"
},
{
"docstring": "Returns action ba... | 2 | null | Implement the Python class `VelocityActionAgent` described below.
Class description:
Hierarichal agent which implements the full plannning stack except the velocity component The planner first generates a nominal trajecotry, then at each timestep recives a target velocity to track with PID controller. Attributes -----... | Implement the Python class `VelocityActionAgent` described below.
Class description:
Hierarichal agent which implements the full plannning stack except the velocity component The planner first generates a nominal trajecotry, then at each timestep recives a target velocity to track with PID controller. Attributes -----... | c4d420e2bad173e5ddd0f93e98449c786d90f2db | <|skeleton|>
class VelocityActionAgent:
"""Hierarichal agent which implements the full plannning stack except the velocity component The planner first generates a nominal trajecotry, then at each timestep recives a target velocity to track with PID controller. Attributes ---------- agent_num : int Index of this age... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VelocityActionAgent:
"""Hierarichal agent which implements the full plannning stack except the velocity component The planner first generates a nominal trajecotry, then at each timestep recives a target velocity to track with PID controller. Attributes ---------- agent_num : int Index of this agent in the wor... | the_stack_v2_python_sparse | gym_urbandriving/agents/hierarchical/velocity_action_agent.py | mikolajblaz/Urban_Driving_Simulator | train | 0 |
61d160842ef84f27c2cb9d56eadb23b74f3ad5ea | [
"self.plugin_bundle_id = plugin_bundle_id\nself.filter_browsers = filter_browsers\nself.filter_sockets = filter_sockets\nself.vendor_config = vendor_config",
"if dictionary is None:\n return None\nvendor_config = None\nif dictionary.get('VendorConfig') != None:\n vendor_config = list()\n for structure in... | <|body_start_0|>
self.plugin_bundle_id = plugin_bundle_id
self.filter_browsers = filter_browsers
self.filter_sockets = filter_sockets
self.vendor_config = vendor_config
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
vendor_config = None
... | Implementation of the 'addNetworkSmProfileClarity' model. TODO: type model description here. Attributes: plugin_bundle_id (string): The bundle ID of the application, defaults to com.cisco.ciscosecurity.app filter_browsers (bool): Whether or not to enable browser traffic filtering (one of true, false). Defaults to true ... | AddNetworkSmProfileClarityModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddNetworkSmProfileClarityModel:
"""Implementation of the 'addNetworkSmProfileClarity' model. TODO: type model description here. Attributes: plugin_bundle_id (string): The bundle ID of the application, defaults to com.cisco.ciscosecurity.app filter_browsers (bool): Whether or not to enable browse... | stack_v2_sparse_classes_75kplus_train_065880 | 3,010 | permissive | [
{
"docstring": "Constructor for the AddNetworkSmProfileClarityModel class",
"name": "__init__",
"signature": "def __init__(self, vendor_config=None, plugin_bundle_id=None, filter_browsers=None, filter_sockets=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dic... | 2 | stack_v2_sparse_classes_30k_train_054124 | Implement the Python class `AddNetworkSmProfileClarityModel` described below.
Class description:
Implementation of the 'addNetworkSmProfileClarity' model. TODO: type model description here. Attributes: plugin_bundle_id (string): The bundle ID of the application, defaults to com.cisco.ciscosecurity.app filter_browsers ... | Implement the Python class `AddNetworkSmProfileClarityModel` described below.
Class description:
Implementation of the 'addNetworkSmProfileClarity' model. TODO: type model description here. Attributes: plugin_bundle_id (string): The bundle ID of the application, defaults to com.cisco.ciscosecurity.app filter_browsers ... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class AddNetworkSmProfileClarityModel:
"""Implementation of the 'addNetworkSmProfileClarity' model. TODO: type model description here. Attributes: plugin_bundle_id (string): The bundle ID of the application, defaults to com.cisco.ciscosecurity.app filter_browsers (bool): Whether or not to enable browse... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddNetworkSmProfileClarityModel:
"""Implementation of the 'addNetworkSmProfileClarity' model. TODO: type model description here. Attributes: plugin_bundle_id (string): The bundle ID of the application, defaults to com.cisco.ciscosecurity.app filter_browsers (bool): Whether or not to enable browser traffic fil... | the_stack_v2_python_sparse | meraki_sdk/models/add_network_sm_profile_clarity_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
47552d6db6bcb88abd05f2143761042e90b1bf93 | [
"self.Kp = Kp\nself.Ki = Ki\nself.Kd = Kd\nself.last_prop = 0.0\nself.last_pv = None\nself.min_output = min_output\nself.reset(setpoint)",
"self.setpoint = setpoint\nself.last_diff = 0\nself.error_integral = 0",
"if self.last_pv is None:\n self.last_pv = pv\nerror = self.setpoint - pv\nself.error_integral +=... | <|body_start_0|>
self.Kp = Kp
self.Ki = Ki
self.Kd = Kd
self.last_prop = 0.0
self.last_pv = None
self.min_output = min_output
self.reset(setpoint)
<|end_body_0|>
<|body_start_1|>
self.setpoint = setpoint
self.last_diff = 0
self.error_integ... | PID controller. Designed for single-direction applications, i.e. a motor that spins in one direction with varying power. | PID | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PID:
"""PID controller. Designed for single-direction applications, i.e. a motor that spins in one direction with varying power."""
def __init__(self, setpoint, Kp, Ki, Kd, min_output=0.15):
"""Initialize PID controller. min_output defines the lowest value the output can take, beyond... | stack_v2_sparse_classes_75kplus_train_065881 | 1,744 | permissive | [
{
"docstring": "Initialize PID controller. min_output defines the lowest value the output can take, beyond which it will get dropped to 0. The controller is output is constrained at a maximum of 1.",
"name": "__init__",
"signature": "def __init__(self, setpoint, Kp, Ki, Kd, min_output=0.15)"
},
{
... | 3 | stack_v2_sparse_classes_30k_test_003004 | Implement the Python class `PID` described below.
Class description:
PID controller. Designed for single-direction applications, i.e. a motor that spins in one direction with varying power.
Method signatures and docstrings:
- def __init__(self, setpoint, Kp, Ki, Kd, min_output=0.15): Initialize PID controller. min_ou... | Implement the Python class `PID` described below.
Class description:
PID controller. Designed for single-direction applications, i.e. a motor that spins in one direction with varying power.
Method signatures and docstrings:
- def __init__(self, setpoint, Kp, Ki, Kd, min_output=0.15): Initialize PID controller. min_ou... | 388f8aec1839f88c2a972a072128e087cf0401db | <|skeleton|>
class PID:
"""PID controller. Designed for single-direction applications, i.e. a motor that spins in one direction with varying power."""
def __init__(self, setpoint, Kp, Ki, Kd, min_output=0.15):
"""Initialize PID controller. min_output defines the lowest value the output can take, beyond... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PID:
"""PID controller. Designed for single-direction applications, i.e. a motor that spins in one direction with varying power."""
def __init__(self, setpoint, Kp, Ki, Kd, min_output=0.15):
"""Initialize PID controller. min_output defines the lowest value the output can take, beyond which it wil... | the_stack_v2_python_sparse | boilerio/pid.py | adpeace/boilerio | train | 5 |
e4c5a55248ade2918cc7967c9e80180f625c7ed7 | [
"super(DCUENet, self).__init__()\nself.data_type = dict_args['data_type']\nself.feature_dim = dict_args['feature_dim']\nself.user_embdim = dict_args['user_embdim']\nself.user_count = dict_args['user_count']\nself.bn_momentum = dict_args['bn_momentum']\nself.dropout = dict_args['dropout']\nself.model_type = dict_arg... | <|body_start_0|>
super(DCUENet, self).__init__()
self.data_type = dict_args['data_type']
self.feature_dim = dict_args['feature_dim']
self.user_embdim = dict_args['user_embdim']
self.user_count = dict_args['user_count']
self.bn_momentum = dict_args['bn_momentum']
s... | PyTorch class implementing DCUE Model. | DCUENet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DCUENet:
"""PyTorch class implementing DCUE Model."""
def __init__(self, dict_args):
"""Initialize DCUE network. Takes a single argument dict_args that is a dictionary containing: data_type: 'scatter' or 'mel' feature_dim: The dimension of the embedded feature vectors for both users ... | stack_v2_sparse_classes_75kplus_train_065882 | 5,238 | no_license | [
{
"docstring": "Initialize DCUE network. Takes a single argument dict_args that is a dictionary containing: data_type: 'scatter' or 'mel' feature_dim: The dimension of the embedded feature vectors for both users and audio. user_embdim: The dimension of the user lookup embedding. user_count: The count of users t... | 2 | stack_v2_sparse_classes_30k_train_045955 | Implement the Python class `DCUENet` described below.
Class description:
PyTorch class implementing DCUE Model.
Method signatures and docstrings:
- def __init__(self, dict_args): Initialize DCUE network. Takes a single argument dict_args that is a dictionary containing: data_type: 'scatter' or 'mel' feature_dim: The ... | Implement the Python class `DCUENet` described below.
Class description:
PyTorch class implementing DCUE Model.
Method signatures and docstrings:
- def __init__(self, dict_args): Initialize DCUE network. Takes a single argument dict_args that is a dictionary containing: data_type: 'scatter' or 'mel' feature_dim: The ... | 55a62c62d26534f3f1a0d7d529cc79d4796680a1 | <|skeleton|>
class DCUENet:
"""PyTorch class implementing DCUE Model."""
def __init__(self, dict_args):
"""Initialize DCUE network. Takes a single argument dict_args that is a dictionary containing: data_type: 'scatter' or 'mel' feature_dim: The dimension of the embedded feature vectors for both users ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DCUENet:
"""PyTorch class implementing DCUE Model."""
def __init__(self, dict_args):
"""Initialize DCUE network. Takes a single argument dict_args that is a dictionary containing: data_type: 'scatter' or 'mel' feature_dim: The dimension of the embedded feature vectors for both users and audio. us... | the_stack_v2_python_sparse | dc/dcue/dcue.py | yamato2199/DeepContentRecommenders | train | 1 |
3c89be919f036dd07c75ab383db5eaea182a00c3 | [
"temp = s[0]\ncount = 0\nls = []\nfor x in s:\n if temp == x:\n count += 1\n else:\n ls.append((temp, count))\n temp = x\n count = 1\nls.append((temp, count))\nreturn ls",
"S = self.makeCharCountArr(S)\nans = 0\nfor word in words:\n word = self.makeCharCountArr(word)\n chec... | <|body_start_0|>
temp = s[0]
count = 0
ls = []
for x in s:
if temp == x:
count += 1
else:
ls.append((temp, count))
temp = x
count = 1
ls.append((temp, count))
return ls
<|end_body_0|>
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def makeCharCountArr(self, s):
"""Complexity O(N) N = len(s) :type s: str :rtype: List[(char, int)]"""
<|body_0|>
def expressiveWords(self, S, words):
"""Complexity O(a*b) a = len(S) b = len(words) c = len(max length word) :type S: str :type words: List[str... | stack_v2_sparse_classes_75kplus_train_065883 | 1,598 | permissive | [
{
"docstring": "Complexity O(N) N = len(s) :type s: str :rtype: List[(char, int)]",
"name": "makeCharCountArr",
"signature": "def makeCharCountArr(self, s)"
},
{
"docstring": "Complexity O(a*b) a = len(S) b = len(words) c = len(max length word) :type S: str :type words: List[str] :rtype: int",
... | 2 | stack_v2_sparse_classes_30k_train_016310 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def makeCharCountArr(self, s): Complexity O(N) N = len(s) :type s: str :rtype: List[(char, int)]
- def expressiveWords(self, S, words): Complexity O(a*b) a = len(S) b = len(words... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def makeCharCountArr(self, s): Complexity O(N) N = len(s) :type s: str :rtype: List[(char, int)]
- def expressiveWords(self, S, words): Complexity O(a*b) a = len(S) b = len(words... | d137df53fa2489821b3c17ac22f24d9a1ae86304 | <|skeleton|>
class Solution:
def makeCharCountArr(self, s):
"""Complexity O(N) N = len(s) :type s: str :rtype: List[(char, int)]"""
<|body_0|>
def expressiveWords(self, S, words):
"""Complexity O(a*b) a = len(S) b = len(words) c = len(max length word) :type S: str :type words: List[str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def makeCharCountArr(self, s):
"""Complexity O(N) N = len(s) :type s: str :rtype: List[(char, int)]"""
temp = s[0]
count = 0
ls = []
for x in s:
if temp == x:
count += 1
else:
ls.append((temp, count))
... | the_stack_v2_python_sparse | medium/expressive-words.py | trilliwon/LeetCode | train | 0 | |
965e3c624b23fab44e891569585adbf16c30e37c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ApiApplication()",
"from .permission_scope import PermissionScope\nfrom .pre_authorized_application import PreAuthorizedApplication\nfrom .permission_scope import PermissionScope\nfrom .pre_authorized_application import PreAuthorizedAp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ApiApplication()
<|end_body_0|>
<|body_start_1|>
from .permission_scope import PermissionScope
from .pre_authorized_application import PreAuthorizedApplication
from .permission_s... | ApiApplication | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiApplication:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApiApplication:
"""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 Retur... | stack_v2_sparse_classes_75kplus_train_065884 | 6,135 | 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: ApiApplication",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | null | Implement the Python class `ApiApplication` described below.
Class description:
Implement the ApiApplication class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApiApplication: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `ApiApplication` described below.
Class description:
Implement the ApiApplication class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApiApplication: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ApiApplication:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApiApplication:
"""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 Retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApiApplication:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApiApplication:
"""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: ApiApplica... | the_stack_v2_python_sparse | msgraph/generated/models/api_application.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
e5101eb2823b74724e422188dda13b0345cf4723 | [
"threading.Thread.__init__(self)\nself.daemon = True\nself.bot = botClass()\nself.commandsQueue = commandsQueue",
"self.bot._Print('Thread started')\nwhile not self.commandsQueue.empty():\n command = self.commandsQueue.get()\n SocialBotCommand(self.bot, command).Execute()\n self.commandsQueue.task_done()... | <|body_start_0|>
threading.Thread.__init__(self)
self.daemon = True
self.bot = botClass()
self.commandsQueue = commandsQueue
<|end_body_0|>
<|body_start_1|>
self.bot._Print('Thread started')
while not self.commandsQueue.empty():
command = self.commandsQueue.g... | Ботом заданного класса выполняем набор команд в отдельном потоке | SocialBotThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SocialBotThread:
"""Ботом заданного класса выполняем набор команд в отдельном потоке"""
def __init__(self, botClass, commandsQueue):
"""Инициализация"""
<|body_0|>
def run(self):
"""Главный метод"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
t... | stack_v2_sparse_classes_75kplus_train_065885 | 7,553 | no_license | [
{
"docstring": "Инициализация",
"name": "__init__",
"signature": "def __init__(self, botClass, commandsQueue)"
},
{
"docstring": "Главный метод",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025632 | Implement the Python class `SocialBotThread` described below.
Class description:
Ботом заданного класса выполняем набор команд в отдельном потоке
Method signatures and docstrings:
- def __init__(self, botClass, commandsQueue): Инициализация
- def run(self): Главный метод | Implement the Python class `SocialBotThread` described below.
Class description:
Ботом заданного класса выполняем набор команд в отдельном потоке
Method signatures and docstrings:
- def __init__(self, botClass, commandsQueue): Инициализация
- def run(self): Главный метод
<|skeleton|>
class SocialBotThread:
"""Бо... | d2771bf04aa187dda6d468883a5a167237589369 | <|skeleton|>
class SocialBotThread:
"""Ботом заданного класса выполняем набор команд в отдельном потоке"""
def __init__(self, botClass, commandsQueue):
"""Инициализация"""
<|body_0|>
def run(self):
"""Главный метод"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SocialBotThread:
"""Ботом заданного класса выполняем набор команд в отдельном потоке"""
def __init__(self, botClass, commandsQueue):
"""Инициализация"""
threading.Thread.__init__(self)
self.daemon = True
self.bot = botClass()
self.commandsQueue = commandsQueue
... | the_stack_v2_python_sparse | stumbleupon/botlaunch.py | cash2one/doorscenter | train | 0 |
8eaf5aaf3731827073f0e7f2c161f6a82242fa0d | [
"values = tuple((i.split(',') for i in values))\nself.full_dict = dict(zip(names, values))\nself.simple_dict = dict(((i, j[0]) for i, j in self.full_dict.iteritems()))",
"import itertools as it\nnames = matrix_dict.keys()\nvalue_combinations = it.product(*matrix_dict.values())\nreturn [JobsDoneJob._MatrixRow(name... | <|body_start_0|>
values = tuple((i.split(',') for i in values))
self.full_dict = dict(zip(names, values))
self.simple_dict = dict(((i, j[0]) for i, j in self.full_dict.iteritems()))
<|end_body_0|>
<|body_start_1|>
import itertools as it
names = matrix_dict.keys()
value_c... | Holds a combination of matrix values. :ivar dict(unicode,list(unicode)) full_dict: Maps names to a list of values. The first value represents the main value, all others are considered aliases :ivar dict(unicode,unicode) simple_dict: Maps names to the main value. .. seealso:: `full_dict` | _MatrixRow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _MatrixRow:
"""Holds a combination of matrix values. :ivar dict(unicode,list(unicode)) full_dict: Maps names to a list of values. The first value represents the main value, all others are considered aliases :ivar dict(unicode,unicode) simple_dict: Maps names to the main value. .. seealso:: `full_... | stack_v2_sparse_classes_75kplus_train_065886 | 19,128 | no_license | [
{
"docstring": "Create a matrix-row instance from a matrix-dict and a value tuple. :param list(unicode) names: List of variables names. :param list(unicode) values: List of values assumed by this row. One value for each name in names parameter.",
"name": "__init__",
"signature": "def __init__(self, name... | 2 | stack_v2_sparse_classes_30k_train_015007 | Implement the Python class `_MatrixRow` described below.
Class description:
Holds a combination of matrix values. :ivar dict(unicode,list(unicode)) full_dict: Maps names to a list of values. The first value represents the main value, all others are considered aliases :ivar dict(unicode,unicode) simple_dict: Maps names... | Implement the Python class `_MatrixRow` described below.
Class description:
Holds a combination of matrix values. :ivar dict(unicode,list(unicode)) full_dict: Maps names to a list of values. The first value represents the main value, all others are considered aliases :ivar dict(unicode,unicode) simple_dict: Maps names... | 8320689d0d3c4e58cc882872018ec49d7e2e41db | <|skeleton|>
class _MatrixRow:
"""Holds a combination of matrix values. :ivar dict(unicode,list(unicode)) full_dict: Maps names to a list of values. The first value represents the main value, all others are considered aliases :ivar dict(unicode,unicode) simple_dict: Maps names to the main value. .. seealso:: `full_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _MatrixRow:
"""Holds a combination of matrix values. :ivar dict(unicode,list(unicode)) full_dict: Maps names to a list of values. The first value represents the main value, all others are considered aliases :ivar dict(unicode,unicode) simple_dict: Maps names to the main value. .. seealso:: `full_dict`"""
... | the_stack_v2_python_sparse | source/python/jobs_done10/jobs_done_job.py | allenbhuiyan/jobs_done10 | train | 0 |
9c0c3b64e469c154e4385b71e27e8bd3a22eebf6 | [
"bundle_uuid = self.get_query_argument('bundle_uuid', default=None)\nlimit = int(self.get_query_argument('limit', default=1000))\nskip = int(self.get_query_argument('skip', default=0))\nquery: Dict[str, Any] = {'bundle_uuid': bundle_uuid}\nprojection: Dict[str, bool] = {'_id': False}\nresults = []\nlogging.debug(f'... | <|body_start_0|>
bundle_uuid = self.get_query_argument('bundle_uuid', default=None)
limit = int(self.get_query_argument('limit', default=1000))
skip = int(self.get_query_argument('skip', default=0))
query: Dict[str, Any] = {'bundle_uuid': bundle_uuid}
projection: Dict[str, bool] ... | MetadataHandler handles collection level routes for Metadata. | MetadataHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetadataHandler:
"""MetadataHandler handles collection level routes for Metadata."""
async def get(self) -> None:
"""Handle GET /Metadata."""
<|body_0|>
async def delete(self) -> None:
"""Handle DELETE /Metadata?bundle_uuid={uuid}."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_065887 | 42,572 | permissive | [
{
"docstring": "Handle GET /Metadata.",
"name": "get",
"signature": "async def get(self) -> None"
},
{
"docstring": "Handle DELETE /Metadata?bundle_uuid={uuid}.",
"name": "delete",
"signature": "async def delete(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_049948 | Implement the Python class `MetadataHandler` described below.
Class description:
MetadataHandler handles collection level routes for Metadata.
Method signatures and docstrings:
- async def get(self) -> None: Handle GET /Metadata.
- async def delete(self) -> None: Handle DELETE /Metadata?bundle_uuid={uuid}. | Implement the Python class `MetadataHandler` described below.
Class description:
MetadataHandler handles collection level routes for Metadata.
Method signatures and docstrings:
- async def get(self) -> None: Handle GET /Metadata.
- async def delete(self) -> None: Handle DELETE /Metadata?bundle_uuid={uuid}.
<|skeleto... | 12719efa84be2281debe98a18c69bbe7a6d0f399 | <|skeleton|>
class MetadataHandler:
"""MetadataHandler handles collection level routes for Metadata."""
async def get(self) -> None:
"""Handle GET /Metadata."""
<|body_0|>
async def delete(self) -> None:
"""Handle DELETE /Metadata?bundle_uuid={uuid}."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetadataHandler:
"""MetadataHandler handles collection level routes for Metadata."""
async def get(self) -> None:
"""Handle GET /Metadata."""
bundle_uuid = self.get_query_argument('bundle_uuid', default=None)
limit = int(self.get_query_argument('limit', default=1000))
skip... | the_stack_v2_python_sparse | lta/rest_server.py | blinkdog/lta | train | 0 |
002897a70130ecb22eead94ca11bea361d47a279 | [
"a = TreeNode('A')\nb = TreeNode('B')\nc = TreeNode('C')\nd = TreeNode('D', a, b)\nx = TreeNode('X', d, c)\na.children.append(d)\nb.children.append(d)\nd.children.append(x)\nc.children.append(x)\nself.assertEqual(tree_diameter(x), 4)",
"n13 = TreeNode('13')\nn10 = TreeNode('10', n13)\nn9 = TreeNode('9', n10)\nn12... | <|body_start_0|>
a = TreeNode('A')
b = TreeNode('B')
c = TreeNode('C')
d = TreeNode('D', a, b)
x = TreeNode('X', d, c)
a.children.append(d)
b.children.append(d)
d.children.append(x)
c.children.append(x)
self.assertEqual(tree_diameter(x), 4)... | Test for: [#4 bonus] Binary tree diameter. | TestTreeDiameter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTreeDiameter:
"""Test for: [#4 bonus] Binary tree diameter."""
def test_5_node_tree(self):
"""Input tree: X |\\ D C /| A B"""
<|body_0|>
def test_12_node_tree(self):
"""Input tree: 1 |\\ 2 3 | 4 /| 6 5 / | 7 8 | | 11 9 | | 12 10 | 13"""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus_train_065888 | 2,188 | no_license | [
{
"docstring": "Input tree: X |\\\\ D C /| A B",
"name": "test_5_node_tree",
"signature": "def test_5_node_tree(self)"
},
{
"docstring": "Input tree: 1 |\\\\ 2 3 | 4 /| 6 5 / | 7 8 | | 11 9 | | 12 10 | 13",
"name": "test_12_node_tree",
"signature": "def test_12_node_tree(self)"
}
] | 2 | null | Implement the Python class `TestTreeDiameter` described below.
Class description:
Test for: [#4 bonus] Binary tree diameter.
Method signatures and docstrings:
- def test_5_node_tree(self): Input tree: X |\\ D C /| A B
- def test_12_node_tree(self): Input tree: 1 |\\ 2 3 | 4 /| 6 5 / | 7 8 | | 11 9 | | 12 10 | 13 | Implement the Python class `TestTreeDiameter` described below.
Class description:
Test for: [#4 bonus] Binary tree diameter.
Method signatures and docstrings:
- def test_5_node_tree(self): Input tree: X |\\ D C /| A B
- def test_12_node_tree(self): Input tree: 1 |\\ 2 3 | 4 /| 6 5 / | 7 8 | | 11 9 | | 12 10 | 13
<|s... | 3678646116c8e43bef1f52f384eb4a236a269788 | <|skeleton|>
class TestTreeDiameter:
"""Test for: [#4 bonus] Binary tree diameter."""
def test_5_node_tree(self):
"""Input tree: X |\\ D C /| A B"""
<|body_0|>
def test_12_node_tree(self):
"""Input tree: 1 |\\ 2 3 | 4 /| 6 5 / | 7 8 | | 11 9 | | 12 10 | 13"""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestTreeDiameter:
"""Test for: [#4 bonus] Binary tree diameter."""
def test_5_node_tree(self):
"""Input tree: X |\\ D C /| A B"""
a = TreeNode('A')
b = TreeNode('B')
c = TreeNode('C')
d = TreeNode('D', a, b)
x = TreeNode('X', d, c)
a.children.append... | the_stack_v2_python_sparse | interview_test_tasks/browser_vendor/final/task_4_bonus/test.py | fifajan/py-stuff | train | 2 |
8b80971c5953e6902efd617d9045733337592a8b | [
"self.federal_tax = TaxCanadaJurisdiction(inflation_adjust)\nself.provincial_tax = TaxCanadaJurisdiction(inflation_adjust, province)\nself.province = province\njurisdictions = (self.federal_tax, self.provincial_tax)\nsuper().__init__(jurisdictions)",
"if 'deductions' in kwargs:\n deductions = kwargs['deduction... | <|body_start_0|>
self.federal_tax = TaxCanadaJurisdiction(inflation_adjust)
self.provincial_tax = TaxCanadaJurisdiction(inflation_adjust, province)
self.province = province
jurisdictions = (self.federal_tax, self.provincial_tax)
super().__init__(jurisdictions)
<|end_body_0|>
<|b... | Federal and provincial tax treatment for a Canadian resident. Attributes: inflation_adjust: A method with the following form: `inflation_adjust(target_year, base_year) -> Decimal`. See documentation for `Tax` for more information. province (str): The province in which income tax is paid. | TaxCanada | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaxCanada:
"""Federal and provincial tax treatment for a Canadian resident. Attributes: inflation_adjust: A method with the following form: `inflation_adjust(target_year, base_year) -> Decimal`. See documentation for `Tax` for more information. province (str): The province in which income tax is ... | stack_v2_sparse_classes_75kplus_train_065889 | 9,716 | no_license | [
{
"docstring": "Initializes TaxCanada. Args: inflation_adjust: A method with the following form: `inflation_adjust(target_year, base_year) -> Decimal`. Can be passed as dict or Decimal-convertible scalar, which will be converted to a callable object. See documentation for `Tax` for more information. province (s... | 2 | stack_v2_sparse_classes_30k_train_029213 | Implement the Python class `TaxCanada` described below.
Class description:
Federal and provincial tax treatment for a Canadian resident. Attributes: inflation_adjust: A method with the following form: `inflation_adjust(target_year, base_year) -> Decimal`. See documentation for `Tax` for more information. province (str... | Implement the Python class `TaxCanada` described below.
Class description:
Federal and provincial tax treatment for a Canadian resident. Attributes: inflation_adjust: A method with the following form: `inflation_adjust(target_year, base_year) -> Decimal`. See documentation for `Tax` for more information. province (str... | c7dc58d2447f1d7fea74ef14a41818be276179d1 | <|skeleton|>
class TaxCanada:
"""Federal and provincial tax treatment for a Canadian resident. Attributes: inflation_adjust: A method with the following form: `inflation_adjust(target_year, base_year) -> Decimal`. See documentation for `Tax` for more information. province (str): The province in which income tax is ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TaxCanada:
"""Federal and provincial tax treatment for a Canadian resident. Attributes: inflation_adjust: A method with the following form: `inflation_adjust(target_year, base_year) -> Decimal`. See documentation for `Tax` for more information. province (str): The province in which income tax is paid."""
... | the_stack_v2_python_sparse | forecaster/canada/tax.py | dxcv/forecaster | train | 0 |
afc72a467be362c0c8f667042990d8148c3ba3ee | [
"url_list = response.xpath('//div[@class=\"p-name p-name-type-2\"]//a/@href').extract()\nfor url in url_list:\n request = scrapy.Request(url, callback=self.parse_product)\n yield request",
"product = MilkpriceItem()\nname_list = response.xpath('//div[@class=\"sku-name\"]/text()').extract()\nname_list = [x.s... | <|body_start_0|>
url_list = response.xpath('//div[@class="p-name p-name-type-2"]//a/@href').extract()
for url in url_list:
request = scrapy.Request(url, callback=self.parse_product)
yield request
<|end_body_0|>
<|body_start_1|>
product = MilkpriceItem()
name_list... | JingdongNewSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JingdongNewSpider:
def parse(self, response):
"""解析商品列表页,获取每个产品的link"""
<|body_0|>
def parse_product(self, response):
"""解析每个商品详情里的价格,名称"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
url_list = response.xpath('//div[@class="p-name p-name-type-2"]/... | stack_v2_sparse_classes_75kplus_train_065890 | 2,247 | no_license | [
{
"docstring": "解析商品列表页,获取每个产品的link",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "解析每个商品详情里的价格,名称",
"name": "parse_product",
"signature": "def parse_product(self, response)"
}
] | 2 | null | Implement the Python class `JingdongNewSpider` described below.
Class description:
Implement the JingdongNewSpider class.
Method signatures and docstrings:
- def parse(self, response): 解析商品列表页,获取每个产品的link
- def parse_product(self, response): 解析每个商品详情里的价格,名称 | Implement the Python class `JingdongNewSpider` described below.
Class description:
Implement the JingdongNewSpider class.
Method signatures and docstrings:
- def parse(self, response): 解析商品列表页,获取每个产品的link
- def parse_product(self, response): 解析每个商品详情里的价格,名称
<|skeleton|>
class JingdongNewSpider:
def parse(self, ... | 715dc16c7716426234c7f1ab166d973bbdfa75ba | <|skeleton|>
class JingdongNewSpider:
def parse(self, response):
"""解析商品列表页,获取每个产品的link"""
<|body_0|>
def parse_product(self, response):
"""解析每个商品详情里的价格,名称"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JingdongNewSpider:
def parse(self, response):
"""解析商品列表页,获取每个产品的link"""
url_list = response.xpath('//div[@class="p-name p-name-type-2"]//a/@href').extract()
for url in url_list:
request = scrapy.Request(url, callback=self.parse_product)
yield request
def pa... | the_stack_v2_python_sparse | milkprice/spiders/jingdong.py | SummerStoneS/web-scraping | train | 0 | |
16361925bc8dc93e9b8e3925fca08a72a4481964 | [
"handler = self.get_handler()\nattrdate = handler.getncattr('first_meas_time')\nreturn datetime.strptime(attrdate, '%Y-%m-%d %H:%M:%S.%f')",
"handler = self.get_handler()\nattrdate = handler.getncattr('last_meas_time')\nreturn datetime.strptime(attrdate, '%Y-%m-%d %H:%M:%S.%f')"
] | <|body_start_0|>
handler = self.get_handler()
attrdate = handler.getncattr('first_meas_time')
return datetime.strptime(attrdate, '%Y-%m-%d %H:%M:%S.%f')
<|end_body_0|>
<|body_start_1|>
handler = self.get_handler()
attrdate = handler.getncattr('last_meas_time')
return dat... | Mapper for CryoSat-2 Altimeter files from NOAA RADS 4.0. Overrides the NCFile mapper to take into account some specific attributes naming | Cryosat2NCFile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cryosat2NCFile:
"""Mapper for CryoSat-2 Altimeter files from NOAA RADS 4.0. Overrides the NCFile mapper to take into account some specific attributes naming"""
def get_start_time(self):
"""Returns the minimum date of the file temporal coverage"""
<|body_0|>
def get_end_t... | stack_v2_sparse_classes_75kplus_train_065891 | 1,156 | no_license | [
{
"docstring": "Returns the minimum date of the file temporal coverage",
"name": "get_start_time",
"signature": "def get_start_time(self)"
},
{
"docstring": "Returns the maximum date of the file temporal coverage",
"name": "get_end_time",
"signature": "def get_end_time(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000370 | Implement the Python class `Cryosat2NCFile` described below.
Class description:
Mapper for CryoSat-2 Altimeter files from NOAA RADS 4.0. Overrides the NCFile mapper to take into account some specific attributes naming
Method signatures and docstrings:
- def get_start_time(self): Returns the minimum date of the file t... | Implement the Python class `Cryosat2NCFile` described below.
Class description:
Mapper for CryoSat-2 Altimeter files from NOAA RADS 4.0. Overrides the NCFile mapper to take into account some specific attributes naming
Method signatures and docstrings:
- def get_start_time(self): Returns the minimum date of the file t... | 3c354f2ca69dc981eb4117976351e8d7454ad505 | <|skeleton|>
class Cryosat2NCFile:
"""Mapper for CryoSat-2 Altimeter files from NOAA RADS 4.0. Overrides the NCFile mapper to take into account some specific attributes naming"""
def get_start_time(self):
"""Returns the minimum date of the file temporal coverage"""
<|body_0|>
def get_end_t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cryosat2NCFile:
"""Mapper for CryoSat-2 Altimeter files from NOAA RADS 4.0. Overrides the NCFile mapper to take into account some specific attributes naming"""
def get_start_time(self):
"""Returns the minimum date of the file temporal coverage"""
handler = self.get_handler()
attrd... | the_stack_v2_python_sparse | cerbere/cerbere/mapper/cryosat2ncfile.py | whigg/PySOL | train | 0 |
2f570fbd2246bf9fe154ba17abc8c1d82904d10d | [
"self.child_vec = child_vec\nself.device_id = device_id\nself.device_length = device_length\nself.stripe_size = stripe_size\nself.thin_pool_chunk_size = thin_pool_chunk_size\nself.mtype = mtype",
"if dictionary is None:\n return None\nchild_vec = None\nif dictionary.get('childVec') != None:\n child_vec = li... | <|body_start_0|>
self.child_vec = child_vec
self.device_id = device_id
self.device_length = device_length
self.stripe_size = stripe_size
self.thin_pool_chunk_size = thin_pool_chunk_size
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'DeviceTree' model. A logical volume is built on a tree where leaves are the slices of partitions (PartitionSlice) defined below and intermediate nodes are assembled by combining nodes in some mode (linear layout, striped, mirrored, RAID etc). A DeviceTree is a block device formed by combining one... | DeviceTree | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceTree:
"""Implementation of the 'DeviceTree' model. A logical volume is built on a tree where leaves are the slices of partitions (PartitionSlice) defined below and intermediate nodes are assembled by combining nodes in some mode (linear layout, striped, mirrored, RAID etc). A DeviceTree is ... | stack_v2_sparse_classes_75kplus_train_065892 | 3,683 | permissive | [
{
"docstring": "Constructor for the DeviceTree class",
"name": "__init__",
"signature": "def __init__(self, child_vec=None, device_id=None, device_length=None, stripe_size=None, thin_pool_chunk_size=None, mtype=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: d... | 2 | stack_v2_sparse_classes_30k_train_037998 | Implement the Python class `DeviceTree` described below.
Class description:
Implementation of the 'DeviceTree' model. A logical volume is built on a tree where leaves are the slices of partitions (PartitionSlice) defined below and intermediate nodes are assembled by combining nodes in some mode (linear layout, striped... | Implement the Python class `DeviceTree` described below.
Class description:
Implementation of the 'DeviceTree' model. A logical volume is built on a tree where leaves are the slices of partitions (PartitionSlice) defined below and intermediate nodes are assembled by combining nodes in some mode (linear layout, striped... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DeviceTree:
"""Implementation of the 'DeviceTree' model. A logical volume is built on a tree where leaves are the slices of partitions (PartitionSlice) defined below and intermediate nodes are assembled by combining nodes in some mode (linear layout, striped, mirrored, RAID etc). A DeviceTree is ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeviceTree:
"""Implementation of the 'DeviceTree' model. A logical volume is built on a tree where leaves are the slices of partitions (PartitionSlice) defined below and intermediate nodes are assembled by combining nodes in some mode (linear layout, striped, mirrored, RAID etc). A DeviceTree is a block devic... | the_stack_v2_python_sparse | cohesity_management_sdk/models/device_tree.py | cohesity/management-sdk-python | train | 24 |
0bf30ac6cc76253dce5a64e710ff14ccdea1e0f9 | [
"coins = [0] * N\nfor relation in trust:\n coins[relation[0] - 1] -= 1\n coins[relation[1] - 1] += 1\nfor index, coin in enumerate(coins):\n if coin == N - 1:\n return index + 1\nreturn -1",
"coins = dict(zip(range(1, N + 1), [0] * N))\nfor relation in trust:\n coins[relation[0]] = coins.get(re... | <|body_start_0|>
coins = [0] * N
for relation in trust:
coins[relation[0] - 1] -= 1
coins[relation[1] - 1] += 1
for index, coin in enumerate(coins):
if coin == N - 1:
return index + 1
return -1
<|end_body_0|>
<|body_start_1|>
c... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _findJudge(self, N, trust):
""":type N: int :type trust: List[List[int]] :rtype: int"""
<|body_0|>
def findJudge(self, N, trust):
""":type N: int :type trust: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_065893 | 2,589 | permissive | [
{
"docstring": ":type N: int :type trust: List[List[int]] :rtype: int",
"name": "_findJudge",
"signature": "def _findJudge(self, N, trust)"
},
{
"docstring": ":type N: int :type trust: List[List[int]] :rtype: int",
"name": "findJudge",
"signature": "def findJudge(self, N, trust)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004277 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _findJudge(self, N, trust): :type N: int :type trust: List[List[int]] :rtype: int
- def findJudge(self, N, trust): :type N: int :type trust: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _findJudge(self, N, trust): :type N: int :type trust: List[List[int]] :rtype: int
- def findJudge(self, N, trust): :type N: int :type trust: List[List[int]] :rtype: int
<|sk... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _findJudge(self, N, trust):
""":type N: int :type trust: List[List[int]] :rtype: int"""
<|body_0|>
def findJudge(self, N, trust):
""":type N: int :type trust: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _findJudge(self, N, trust):
""":type N: int :type trust: List[List[int]] :rtype: int"""
coins = [0] * N
for relation in trust:
coins[relation[0] - 1] -= 1
coins[relation[1] - 1] += 1
for index, coin in enumerate(coins):
if coin ... | the_stack_v2_python_sparse | 997.find-the-town-judge.py | windard/leeeeee | train | 0 | |
159793f0158d9c7e34f0768a2754b38dbf8cfbbf | [
"query = self.query(Platform)\nsearch_args = search_arguments.parse_args()\nif search_args['q']:\n query = query.filter(Platform.search_filter(search_args['q']))\nreturn query",
"args = platform_arguments.parse_args()\nplatform = Platform(**args)\nself.session.add(platform)\nself.session.commit()\nreturn platf... | <|body_start_0|>
query = self.query(Platform)
search_args = search_arguments.parse_args()
if search_args['q']:
query = query.filter(Platform.search_filter(search_args['q']))
return query
<|end_body_0|>
<|body_start_1|>
args = platform_arguments.parse_args()
p... | List all platforms | PlatformList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlatformList:
"""List all platforms"""
def get(self):
"""List all platforms"""
<|body_0|>
def post(self):
"""Create a new platform :raises IntegrityError: Raised when the slug is not unique"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
query =... | stack_v2_sparse_classes_75kplus_train_065894 | 3,154 | no_license | [
{
"docstring": "List all platforms",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a new platform :raises IntegrityError: Raised when the slug is not unique",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000403 | Implement the Python class `PlatformList` described below.
Class description:
List all platforms
Method signatures and docstrings:
- def get(self): List all platforms
- def post(self): Create a new platform :raises IntegrityError: Raised when the slug is not unique | Implement the Python class `PlatformList` described below.
Class description:
List all platforms
Method signatures and docstrings:
- def get(self): List all platforms
- def post(self): Create a new platform :raises IntegrityError: Raised when the slug is not unique
<|skeleton|>
class PlatformList:
"""List all pl... | 5f4493bedb36c29e80740676bbb179901272d91e | <|skeleton|>
class PlatformList:
"""List all platforms"""
def get(self):
"""List all platforms"""
<|body_0|>
def post(self):
"""Create a new platform :raises IntegrityError: Raised when the slug is not unique"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlatformList:
"""List all platforms"""
def get(self):
"""List all platforms"""
query = self.query(Platform)
search_args = search_arguments.parse_args()
if search_args['q']:
query = query.filter(Platform.search_filter(search_args['q']))
return query
... | the_stack_v2_python_sparse | matcher/api/namespaces/platforms.py | sandhose/obs-matcher | train | 2 |
00f121880a7a9d7cb86d44e8cbf79c34afeacd4c | [
"if buttons:\n key = (buttons, modifiers)\nelse:\n key = None\nreturn super(MouseMoveEventManager, self).registerCallback(key, function, node, capture)",
"if event.getObjectPaths():\n newPath = event.getObjectPaths()[0]\nelse:\n newPath = ()\nlastPath = self.lastPath\nif lastPath and lastPath != newPa... | <|body_start_0|>
if buttons:
key = (buttons, modifiers)
else:
key = None
return super(MouseMoveEventManager, self).registerCallback(key, function, node, capture)
<|end_body_0|>
<|body_start_1|>
if event.getObjectPaths():
newPath = event.getObjectPaths... | Manager for MouseMoveEvent instances lastPath -- tracks the last-pointed-to path, used to generate mousein and mouseout event types. | MouseMoveEventManager | [
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MouseMoveEventManager:
"""Manager for MouseMoveEvent instances lastPath -- tracks the last-pointed-to path, used to generate mousein and mouseout event types."""
def registerCallback(self, buttons=(), modifiers=(0, 0, 0), function=None, node=None, capture=0):
"""Register a function t... | stack_v2_sparse_classes_75kplus_train_065895 | 16,446 | permissive | [
{
"docstring": "Register a function to receive keyboard events matching the given specification To deregister, pass None as the function. buttons -- tuple of active buttons (in ascending order) Valid Values: () -- move with no buttons (n,) -- drag with single button 'n' depressed (n,n+x) -- drag with two button... | 2 | stack_v2_sparse_classes_30k_train_013068 | Implement the Python class `MouseMoveEventManager` described below.
Class description:
Manager for MouseMoveEvent instances lastPath -- tracks the last-pointed-to path, used to generate mousein and mouseout event types.
Method signatures and docstrings:
- def registerCallback(self, buttons=(), modifiers=(0, 0, 0), fu... | Implement the Python class `MouseMoveEventManager` described below.
Class description:
Manager for MouseMoveEvent instances lastPath -- tracks the last-pointed-to path, used to generate mousein and mouseout event types.
Method signatures and docstrings:
- def registerCallback(self, buttons=(), modifiers=(0, 0, 0), fu... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class MouseMoveEventManager:
"""Manager for MouseMoveEvent instances lastPath -- tracks the last-pointed-to path, used to generate mousein and mouseout event types."""
def registerCallback(self, buttons=(), modifiers=(0, 0, 0), function=None, node=None, capture=0):
"""Register a function t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MouseMoveEventManager:
"""Manager for MouseMoveEvent instances lastPath -- tracks the last-pointed-to path, used to generate mousein and mouseout event types."""
def registerCallback(self, buttons=(), modifiers=(0, 0, 0), function=None, node=None, capture=0):
"""Register a function to receive key... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/events/mouseevents.py | alexus37/AugmentedRealityChess | train | 1 |
6304e591a3b594add44c787aa38d81a92d73702f | [
"self.__interval = interval\nself.__function = function\nself.__args = args\nself.__kwargs = kwargs\nself.__thread = False\nself.__lock = _thread.allocate_lock()",
"self.__lock.acquire()\nself.__active = True\nif not self.__thread:\n self.__thread = True\n _thread.start_new_thread(self.__run, ())\nself.__lo... | <|body_start_0|>
self.__interval = interval
self.__function = function
self.__args = args
self.__kwargs = kwargs
self.__thread = False
self.__lock = _thread.allocate_lock()
<|end_body_0|>
<|body_start_1|>
self.__lock.acquire()
self.__active = True
... | Continuous(interval, function, *args, **kwargs) -> Continuous | Continuous | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Continuous:
"""Continuous(interval, function, *args, **kwargs) -> Continuous"""
def __init__(self, interval, function, *args, **kwargs):
"""Initialize the Continuous object."""
<|body_0|>
def start(self):
"""Start the Continuous object."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_065896 | 3,139 | no_license | [
{
"docstring": "Initialize the Continuous object.",
"name": "__init__",
"signature": "def __init__(self, interval, function, *args, **kwargs)"
},
{
"docstring": "Start the Continuous object.",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "Stop the Continuous ... | 4 | null | Implement the Python class `Continuous` described below.
Class description:
Continuous(interval, function, *args, **kwargs) -> Continuous
Method signatures and docstrings:
- def __init__(self, interval, function, *args, **kwargs): Initialize the Continuous object.
- def start(self): Start the Continuous object.
- def... | Implement the Python class `Continuous` described below.
Class description:
Continuous(interval, function, *args, **kwargs) -> Continuous
Method signatures and docstrings:
- def __init__(self, interval, function, *args, **kwargs): Initialize the Continuous object.
- def start(self): Start the Continuous object.
- def... | 45837fc39f99b5f7f69919ed2f6732e6b7bec936 | <|skeleton|>
class Continuous:
"""Continuous(interval, function, *args, **kwargs) -> Continuous"""
def __init__(self, interval, function, *args, **kwargs):
"""Initialize the Continuous object."""
<|body_0|>
def start(self):
"""Start the Continuous object."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Continuous:
"""Continuous(interval, function, *args, **kwargs) -> Continuous"""
def __init__(self, interval, function, *args, **kwargs):
"""Initialize the Continuous object."""
self.__interval = interval
self.__function = function
self.__args = args
self.__kwargs =... | the_stack_v2_python_sparse | Python 2.X/ZERO/Projects/zero/timer.py | jacobbridges/my-chaos | train | 0 |
872c29a17e321d711840131d9b7749332b4128b0 | [
"message: str = message.lower()\nmessage = message.translate(Utilities.translation)\nwords: List[str] = message.split()\nreturn list(map(lambda word: Utilities.analyzer.parse(word)[0].normal_form, words))",
"if len(lst) < 2:\n return []\nfor i in range(1, len(lst)):\n yield ((lst[i - 1], i - 1), (lst[i], i)... | <|body_start_0|>
message: str = message.lower()
message = message.translate(Utilities.translation)
words: List[str] = message.split()
return list(map(lambda word: Utilities.analyzer.parse(word)[0].normal_form, words))
<|end_body_0|>
<|body_start_1|>
if len(lst) < 2:
... | Utilities | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Utilities:
def parse(message: str) -> List[str]:
"""Очистить сообщение от знаков препинания, привести к нижнему регистру и привести все слова в начальную форму."""
<|body_0|>
def pairs(lst: List[any]) -> List[Tuple[Tuple[any, int], Tuple[any, int]]]:
"""Представляет ... | stack_v2_sparse_classes_75kplus_train_065897 | 1,652 | no_license | [
{
"docstring": "Очистить сообщение от знаков препинания, привести к нижнему регистру и привести все слова в начальную форму.",
"name": "parse",
"signature": "def parse(message: str) -> List[str]"
},
{
"docstring": "Представляет одномерный список в виде списка пар соседних элементов вместе с их и... | 3 | stack_v2_sparse_classes_30k_train_013588 | Implement the Python class `Utilities` described below.
Class description:
Implement the Utilities class.
Method signatures and docstrings:
- def parse(message: str) -> List[str]: Очистить сообщение от знаков препинания, привести к нижнему регистру и привести все слова в начальную форму.
- def pairs(lst: List[any]) -... | Implement the Python class `Utilities` described below.
Class description:
Implement the Utilities class.
Method signatures and docstrings:
- def parse(message: str) -> List[str]: Очистить сообщение от знаков препинания, привести к нижнему регистру и привести все слова в начальную форму.
- def pairs(lst: List[any]) -... | 7038ce73aaadf22f6748f9cd2b95f1ace34f014e | <|skeleton|>
class Utilities:
def parse(message: str) -> List[str]:
"""Очистить сообщение от знаков препинания, привести к нижнему регистру и привести все слова в начальную форму."""
<|body_0|>
def pairs(lst: List[any]) -> List[Tuple[Tuple[any, int], Tuple[any, int]]]:
"""Представляет ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Utilities:
def parse(message: str) -> List[str]:
"""Очистить сообщение от знаков препинания, привести к нижнему регистру и привести все слова в начальную форму."""
message: str = message.lower()
message = message.translate(Utilities.translation)
words: List[str] = message.split... | the_stack_v2_python_sparse | dialog_system/utilities.py | qwerfah/SII7 | train | 0 | |
7c671b15df685309504152d3e02717a8da3e33be | [
"self.name = name\nself.supply_variable = supply_variable\nself.vacant_variable = vacant_variable\nself.choosers = choosers\nself.alternatives = alternatives\nself.summary_alts_xref = summary_alts_xref",
"choosers, alternatives = self.calculate_model_variables()\nchoosers = choosers[choosers[self.choice_column] =... | <|body_start_0|>
self.name = name
self.supply_variable = supply_variable
self.vacant_variable = vacant_variable
self.choosers = choosers
self.alternatives = alternatives
self.summary_alts_xref = summary_alts_xref
<|end_body_0|>
<|body_start_1|>
choosers, alternat... | A discrete choice model with parameters needed for simulation. Initialize with MNLDiscreteChoiceModel's init parameters or with from_yaml, then add simulation parameters with set_simulation_params(). | SimulationChoiceModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulationChoiceModel:
"""A discrete choice model with parameters needed for simulation. Initialize with MNLDiscreteChoiceModel's init parameters or with from_yaml, then add simulation parameters with set_simulation_params()."""
def set_simulation_params(self, name, supply_variable, vacant_v... | stack_v2_sparse_classes_75kplus_train_065898 | 24,201 | no_license | [
{
"docstring": "Add simulation parameters as additional attributes. Parameters ---------- name : str Name of the model. supply_variable : str The name of the column in the alternatives table indicating number of available spaces, vacant or not, that can be occupied by choosers. vacant_variable : str The name of... | 5 | null | Implement the Python class `SimulationChoiceModel` described below.
Class description:
A discrete choice model with parameters needed for simulation. Initialize with MNLDiscreteChoiceModel's init parameters or with from_yaml, then add simulation parameters with set_simulation_params().
Method signatures and docstring... | Implement the Python class `SimulationChoiceModel` described below.
Class description:
A discrete choice model with parameters needed for simulation. Initialize with MNLDiscreteChoiceModel's init parameters or with from_yaml, then add simulation parameters with set_simulation_params().
Method signatures and docstring... | 07809c2f03ea43a43c8d801b08d500f2aaf139f3 | <|skeleton|>
class SimulationChoiceModel:
"""A discrete choice model with parameters needed for simulation. Initialize with MNLDiscreteChoiceModel's init parameters or with from_yaml, then add simulation parameters with set_simulation_params()."""
def set_simulation_params(self, name, supply_variable, vacant_v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimulationChoiceModel:
"""A discrete choice model with parameters needed for simulation. Initialize with MNLDiscreteChoiceModel's init parameters or with from_yaml, then add simulation parameters with set_simulation_params()."""
def set_simulation_params(self, name, supply_variable, vacant_variable, choo... | the_stack_v2_python_sparse | utils.py | SEMCOG/semcog_urbansim | train | 7 |
544f5e62c2f227188c7b2bc508cf4ab1d06dd812 | [
"self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]",
"while len(self.x_values) < self.num_points:\n x_direction = choice([1, -1])\n x_distance = choice([0, 1, 2, 3, 4])\n x_step = x_direction * x_distance\n y_direction = choice([1, -1])\n y_distance = choice([0, 1, 2, 3, 4])\n ... | <|body_start_0|>
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
while len(self.x_values) < self.num_points:
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction *... | 一个生成随机漫步数据的类 | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步数据属性"""
<|body_0|>
def fill_walk(self):
"""计算随机漫步包含的所有点"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.num_points = num_points
self.x_values = [0]
... | stack_v2_sparse_classes_75kplus_train_065899 | 991 | no_license | [
{
"docstring": "初始化随机漫步数据属性",
"name": "__init__",
"signature": "def __init__(self, num_points=5000)"
},
{
"docstring": "计算随机漫步包含的所有点",
"name": "fill_walk",
"signature": "def fill_walk(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002153 | Implement the Python class `RandomWalk` described below.
Class description:
一个生成随机漫步数据的类
Method signatures and docstrings:
- def __init__(self, num_points=5000): 初始化随机漫步数据属性
- def fill_walk(self): 计算随机漫步包含的所有点 | Implement the Python class `RandomWalk` described below.
Class description:
一个生成随机漫步数据的类
Method signatures and docstrings:
- def __init__(self, num_points=5000): 初始化随机漫步数据属性
- def fill_walk(self): 计算随机漫步包含的所有点
<|skeleton|>
class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=5000):
"""... | 538311d7a7f29b78e080884c97276c74234720de | <|skeleton|>
class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步数据属性"""
<|body_0|>
def fill_walk(self):
"""计算随机漫步包含的所有点"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步数据属性"""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""计算随机漫步包含的所有点"""
while len(self.x_values) < self.num_points:
x... | the_stack_v2_python_sparse | random_walk.py | juelianzhiren/python_demo | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.