blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6789042fd28f7c65312f2d8dc337637d9dc2aa44 | [
"self.cells = cells\nself.cell_np = cell_np\nself.dnp = 0\nself.np = 0\nself.dsize = 0.0\nself.size = 1.0\nself.np_req = np_req\nself.tr = kwargs.get('tr', 0.8)\nself.u = kwargs.get('u', 0.4)\nself.e = kwargs.get('e', 3.0)\nself.er = kwargs.get('er', 6.0)\nself.r = kwargs.get('r', 2.0)\nself.t = 0.0\nself.x = self.... | <|body_start_0|>
self.cells = cells
self.cell_np = cell_np
self.dnp = 0
self.np = 0
self.dsize = 0.0
self.size = 1.0
self.np_req = np_req
self.tr = kwargs.get('tr', 0.8)
self.u = kwargs.get('u', 0.4)
self.e = kwargs.get('e', 3.0)
se... | Class representing a cluster in k-means clustering | Cluster | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cluster:
"""Class representing a cluster in k-means clustering"""
def __init__(self, cells, cell_np, np_req, **kwargs):
"""constructor kwargs can be used to finetune the algorithm: t = ratio of old component of center used in the center calculation tr = `t` when the number of particl... | stack_v2_sparse_classes_36k_train_001300 | 12,256 | permissive | [
{
"docstring": "constructor kwargs can be used to finetune the algorithm: t = ratio of old component of center used in the center calculation tr = `t` when the number of particles over/undershoot (reversal) u = ratio of nearest cell center in the new center from the remaining (1-t) (other component is the centr... | 4 | stack_v2_sparse_classes_30k_train_017284 | Implement the Python class `Cluster` described below.
Class description:
Class representing a cluster in k-means clustering
Method signatures and docstrings:
- def __init__(self, cells, cell_np, np_req, **kwargs): constructor kwargs can be used to finetune the algorithm: t = ratio of old component of center used in t... | Implement the Python class `Cluster` described below.
Class description:
Class representing a cluster in k-means clustering
Method signatures and docstrings:
- def __init__(self, cells, cell_np, np_req, **kwargs): constructor kwargs can be used to finetune the algorithm: t = ratio of old component of center used in t... | 5bb1fc46a9c84aefd42758356a9986689db05454 | <|skeleton|>
class Cluster:
"""Class representing a cluster in k-means clustering"""
def __init__(self, cells, cell_np, np_req, **kwargs):
"""constructor kwargs can be used to finetune the algorithm: t = ratio of old component of center used in the center calculation tr = `t` when the number of particl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cluster:
"""Class representing a cluster in k-means clustering"""
def __init__(self, cells, cell_np, np_req, **kwargs):
"""constructor kwargs can be used to finetune the algorithm: t = ratio of old component of center used in the center calculation tr = `t` when the number of particles over/under... | the_stack_v2_python_sparse | source/pysph/parallel/load_balancer_mkmeans.py | pankajp/pysph | train | 1 |
a3ac01b465bcaf541c7789b907369192bae807dd | [
"vrs_session = session.VerseSession.instance()\ntry:\n scene_data_node = vrs_session.nodes[context.scene.verse_data_node_id]\nexcept KeyError:\n return {'CANCELLED'}\nelse:\n object_node = object3d.VerseObject(session=vrs_session, parent=scene_data_node, obj=context.active_object)\n object_node.mesh_nod... | <|body_start_0|>
vrs_session = session.VerseSession.instance()
try:
scene_data_node = vrs_session.nodes[context.scene.verse_data_node_id]
except KeyError:
return {'CANCELLED'}
else:
object_node = object3d.VerseObject(session=vrs_session, parent=scene_d... | This operator tries to share Blender Mesh object at Verse server. | VerseObjectOtShare | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerseObjectOtShare:
"""This operator tries to share Blender Mesh object at Verse server."""
def invoke(self, context, event):
"""This method will try to create new node representing Mesh Object at Verse server"""
<|body_0|>
def poll(cls, context):
"""This class m... | stack_v2_sparse_classes_36k_train_001301 | 18,592 | no_license | [
{
"docstring": "This method will try to create new node representing Mesh Object at Verse server",
"name": "invoke",
"signature": "def invoke(self, context, event)"
},
{
"docstring": "This class method is used, when Blender check, if this operator can be executed",
"name": "poll",
"signa... | 2 | null | Implement the Python class `VerseObjectOtShare` described below.
Class description:
This operator tries to share Blender Mesh object at Verse server.
Method signatures and docstrings:
- def invoke(self, context, event): This method will try to create new node representing Mesh Object at Verse server
- def poll(cls, c... | Implement the Python class `VerseObjectOtShare` described below.
Class description:
This operator tries to share Blender Mesh object at Verse server.
Method signatures and docstrings:
- def invoke(self, context, event): This method will try to create new node representing Mesh Object at Verse server
- def poll(cls, c... | 7b796d30dfd22b7706a93e4419ed913d18d29a44 | <|skeleton|>
class VerseObjectOtShare:
"""This operator tries to share Blender Mesh object at Verse server."""
def invoke(self, context, event):
"""This method will try to create new node representing Mesh Object at Verse server"""
<|body_0|>
def poll(cls, context):
"""This class m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VerseObjectOtShare:
"""This operator tries to share Blender Mesh object at Verse server."""
def invoke(self, context, event):
"""This method will try to create new node representing Mesh Object at Verse server"""
vrs_session = session.VerseSession.instance()
try:
scene... | the_stack_v2_python_sparse | All_In_One/addons/io_verse/ui_object3d.py | 2434325680/Learnbgame | train | 0 |
2fe5a00572b6625fafe40aec96317a6f31b4d2ab | [
"def recur(root, res):\n if not root:\n res.append('#')\n else:\n res.append(root.val)\n for child in root.children:\n recur(child, res)\n res.append('#')\nres = []\nrecur(root, res)\nreturn ','.join(map(str, res))",
"tokens = data.split(',')\n\ndef recur(i):\n if t... | <|body_start_0|>
def recur(root, res):
if not root:
res.append('#')
else:
res.append(root.val)
for child in root.children:
recur(child, res)
res.append('#')
res = []
recur(root, res)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_001302 | 1,535 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def deserialize(self, ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | 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: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | 2722c0deafcd094ce64140a9a837b4027d29ed6f | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
def recur(root, res):
if not root:
res.append('#')
else:
res.append(root.val)
for child in root.children:
... | the_stack_v2_python_sparse | 428_deser_n_ary_tree_h/main_opt.py | chao-shi/lclc | train | 0 | |
1dc8ad5096f3a292c399f0d7c87651f4cfcf1517 | [
"if not os.path.isfile(ProjectManager.preferences):\n raise NoConfigException\nwith open(ProjectManager.preferences, 'r') as stream:\n config = yaml.full_load(stream)\nreturn config",
"if not cls._cache or ProjectManager.preferences != cls._last_path:\n cls._cache = cls._load()\n cls._cache_time = dat... | <|body_start_0|>
if not os.path.isfile(ProjectManager.preferences):
raise NoConfigException
with open(ProjectManager.preferences, 'r') as stream:
config = yaml.full_load(stream)
return config
<|end_body_0|>
<|body_start_1|>
if not cls._cache or ProjectManager.pre... | Class for reading config file. Re-checking file on disk after a set interval to pick up changes. | Config | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
"""Class for reading config file. Re-checking file on disk after a set interval to pick up changes."""
def _load(cls):
"""Reading config file from disk and parsing to a dictionary using the yaml module. Returns: dict: Config object"""
<|body_0|>
def get(cls):
... | stack_v2_sparse_classes_36k_train_001303 | 1,750 | permissive | [
{
"docstring": "Reading config file from disk and parsing to a dictionary using the yaml module. Returns: dict: Config object",
"name": "_load",
"signature": "def _load(cls)"
},
{
"docstring": "Reads config file from disk if no config object has been loaded or if the available config object has ... | 2 | stack_v2_sparse_classes_30k_train_013622 | Implement the Python class `Config` described below.
Class description:
Class for reading config file. Re-checking file on disk after a set interval to pick up changes.
Method signatures and docstrings:
- def _load(cls): Reading config file from disk and parsing to a dictionary using the yaml module. Returns: dict: C... | Implement the Python class `Config` described below.
Class description:
Class for reading config file. Re-checking file on disk after a set interval to pick up changes.
Method signatures and docstrings:
- def _load(cls): Reading config file from disk and parsing to a dictionary using the yaml module. Returns: dict: C... | 9b005cd8f4724636d1377a3d2ac18b8ace20279f | <|skeleton|>
class Config:
"""Class for reading config file. Re-checking file on disk after a set interval to pick up changes."""
def _load(cls):
"""Reading config file from disk and parsing to a dictionary using the yaml module. Returns: dict: Config object"""
<|body_0|>
def get(cls):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Config:
"""Class for reading config file. Re-checking file on disk after a set interval to pick up changes."""
def _load(cls):
"""Reading config file from disk and parsing to a dictionary using the yaml module. Returns: dict: Config object"""
if not os.path.isfile(ProjectManager.preferenc... | the_stack_v2_python_sparse | twicorder/config.py | thimic/twicorder-search | train | 2 |
8fd77d3a7aec255f2bea44bc7933a04eeeb1ef2f | [
"self.s = s\nself.prev_obj_list = []\nself.start_text = 'Welcome!\\nPlease press toggle\\nto see the next goal condition!'\nself.show_instr_func = show_instr_func\nself.switch_instr_func = switch_instr_func\nself.is_showing = True\nself.condition_text = s.add_vr_overlay_text(text_data=self.start_text, font_size=40,... | <|body_start_0|>
self.s = s
self.prev_obj_list = []
self.start_text = 'Welcome!\nPlease press toggle\nto see the next goal condition!'
self.show_instr_func = show_instr_func
self.switch_instr_func = switch_instr_func
self.is_showing = True
self.condition_text = s.... | Class that handles switching of various ATUS conditions - including overlays and objects. | VrConditionSwitcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VrConditionSwitcher:
"""Class that handles switching of various ATUS conditions - including overlays and objects."""
def __init__(self, s, show_instr_func, switch_instr_func):
""":param s: reference to simulator"""
<|body_0|>
def refresh_condition(self, switch=True):
... | stack_v2_sparse_classes_36k_train_001304 | 14,851 | permissive | [
{
"docstring": ":param s: reference to simulator",
"name": "__init__",
"signature": "def __init__(self, s, show_instr_func, switch_instr_func)"
},
{
"docstring": "Switches to the next condition. This involves displaying the text for the new condition, as well as highlighting/un-highlighting the ... | 3 | stack_v2_sparse_classes_30k_train_011891 | Implement the Python class `VrConditionSwitcher` described below.
Class description:
Class that handles switching of various ATUS conditions - including overlays and objects.
Method signatures and docstrings:
- def __init__(self, s, show_instr_func, switch_instr_func): :param s: reference to simulator
- def refresh_c... | Implement the Python class `VrConditionSwitcher` described below.
Class description:
Class that handles switching of various ATUS conditions - including overlays and objects.
Method signatures and docstrings:
- def __init__(self, s, show_instr_func, switch_instr_func): :param s: reference to simulator
- def refresh_c... | 6800954d8e6aca0bfabfa3d4d649cf672e369e87 | <|skeleton|>
class VrConditionSwitcher:
"""Class that handles switching of various ATUS conditions - including overlays and objects."""
def __init__(self, s, show_instr_func, switch_instr_func):
""":param s: reference to simulator"""
<|body_0|>
def refresh_condition(self, switch=True):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VrConditionSwitcher:
"""Class that handles switching of various ATUS conditions - including overlays and objects."""
def __init__(self, s, show_instr_func, switch_instr_func):
""":param s: reference to simulator"""
self.s = s
self.prev_obj_list = []
self.start_text = 'Welc... | the_stack_v2_python_sparse | igibson/render/mesh_renderer/mesh_renderer_vr.py | sycz00/iGibson | train | 0 |
4374c60819b78a63e3833bdac510a3ab9266988f | [
"integration = self._ledfx.integrations.get(integration_id)\nif integration is None or integration.type != 'spotify':\n response = {'not found': 404}\n return web.json_response(data=response, status=404)\nresponse = integration.get_triggers()\nreturn web.json_response(data=response, status=200)",
"integrati... | <|body_start_0|>
integration = self._ledfx.integrations.get(integration_id)
if integration is None or integration.type != 'spotify':
response = {'not found': 404}
return web.json_response(data=response, status=404)
response = integration.get_triggers()
return web.... | REST end-point for querying and managing a Spotify integration | QLCEndpoint | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-3.0-only",
"GPL-3.0-or-later",
"LGPL-2.1-or-later",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QLCEndpoint:
"""REST end-point for querying and managing a Spotify integration"""
async def get(self, integration_id) -> web.Response:
"""Get all song triggers"""
<|body_0|>
async def put(self, integration_id, request) -> web.Response:
"""Update a Spotify song tr... | stack_v2_sparse_classes_36k_train_001305 | 4,383 | permissive | [
{
"docstring": "Get all song triggers",
"name": "get",
"signature": "async def get(self, integration_id) -> web.Response"
},
{
"docstring": "Update a Spotify song trigger",
"name": "put",
"signature": "async def put(self, integration_id, request) -> web.Response"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_train_021407 | Implement the Python class `QLCEndpoint` described below.
Class description:
REST end-point for querying and managing a Spotify integration
Method signatures and docstrings:
- async def get(self, integration_id) -> web.Response: Get all song triggers
- async def put(self, integration_id, request) -> web.Response: Upd... | Implement the Python class `QLCEndpoint` described below.
Class description:
REST end-point for querying and managing a Spotify integration
Method signatures and docstrings:
- async def get(self, integration_id) -> web.Response: Get all song triggers
- async def put(self, integration_id, request) -> web.Response: Upd... | 3146ba9e9d10a2d01cdd4cb15ea37fc0c7bd020f | <|skeleton|>
class QLCEndpoint:
"""REST end-point for querying and managing a Spotify integration"""
async def get(self, integration_id) -> web.Response:
"""Get all song triggers"""
<|body_0|>
async def put(self, integration_id, request) -> web.Response:
"""Update a Spotify song tr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QLCEndpoint:
"""REST end-point for querying and managing a Spotify integration"""
async def get(self, integration_id) -> web.Response:
"""Get all song triggers"""
integration = self._ledfx.integrations.get(integration_id)
if integration is None or integration.type != 'spotify':
... | the_stack_v2_python_sparse | ledfx/api/integration_spotify.py | THATDONFC/LedFx | train | 0 |
7b3fd1b4d7ad2f761b44c130da4a361968f8cefe | [
"embed = Embed(title=self.word, description=utils.truncate(self.definition, 2048))\nif self.example:\n embed.add_field(name='Example', value=utils.truncate(self.example, 1024), inline=False)\nembed.add_field(name='👍', value=utils.commas(self.thumbs_up))\nembed.add_field(name='👎', value=utils.commas(self.thumbs... | <|body_start_0|>
embed = Embed(title=self.word, description=utils.truncate(self.definition, 2048))
if self.example:
embed.add_field(name='Example', value=utils.truncate(self.example, 1024), inline=False)
embed.add_field(name='👍', value=utils.commas(self.thumbs_up))
embed.add... | Represents an Urban Dictionary entry. | UrbanDefinition | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UrbanDefinition:
"""Represents an Urban Dictionary entry."""
def embed(self) -> Embed:
"""Makes a :class:``discord.Embed`` from an ``UrbanDefinition``."""
<|body_0|>
async def query(cls, session: ClientSession, word: str) -> Union[None, 'UrbanDefinition']:
"""Que... | stack_v2_sparse_classes_36k_train_001306 | 5,625 | permissive | [
{
"docstring": "Makes a :class:``discord.Embed`` from an ``UrbanDefinition``.",
"name": "embed",
"signature": "def embed(self) -> Embed"
},
{
"docstring": "Queries UrbanDictionary for a definition.",
"name": "query",
"signature": "async def query(cls, session: ClientSession, word: str) -... | 2 | stack_v2_sparse_classes_30k_train_013190 | Implement the Python class `UrbanDefinition` described below.
Class description:
Represents an Urban Dictionary entry.
Method signatures and docstrings:
- def embed(self) -> Embed: Makes a :class:``discord.Embed`` from an ``UrbanDefinition``.
- async def query(cls, session: ClientSession, word: str) -> Union[None, 'U... | Implement the Python class `UrbanDefinition` described below.
Class description:
Represents an Urban Dictionary entry.
Method signatures and docstrings:
- def embed(self) -> Embed: Makes a :class:``discord.Embed`` from an ``UrbanDefinition``.
- async def query(cls, session: ClientSession, word: str) -> Union[None, 'U... | 5a0e73b8ac71cd3dc0f724f07aff8a54feb69551 | <|skeleton|>
class UrbanDefinition:
"""Represents an Urban Dictionary entry."""
def embed(self) -> Embed:
"""Makes a :class:``discord.Embed`` from an ``UrbanDefinition``."""
<|body_0|>
async def query(cls, session: ClientSession, word: str) -> Union[None, 'UrbanDefinition']:
"""Que... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UrbanDefinition:
"""Represents an Urban Dictionary entry."""
def embed(self) -> Embed:
"""Makes a :class:``discord.Embed`` from an ``UrbanDefinition``."""
embed = Embed(title=self.word, description=utils.truncate(self.definition, 2048))
if self.example:
embed.add_field... | the_stack_v2_python_sparse | dog/ext/fun.py | Snarloff/dogbot | train | 1 |
18ed9cec03c68322933006e420c2449900ca7482 | [
"assert isinstance(Category, MappedSupport), 'Invalid mapped class %s' % Category\nassert issubclass(CategoryAction, WithCategoryAction), 'Invalid category action class %s' % CategoryAction\npks = [pk for pk in mappingFor(Category).columns if pk.primary_key]\nassert pks, 'Cannot detect any primary key for %s' % Cat... | <|body_start_0|>
assert isinstance(Category, MappedSupport), 'Invalid mapped class %s' % Category
assert issubclass(CategoryAction, WithCategoryAction), 'Invalid category action class %s' % CategoryAction
pks = [pk for pk in mappingFor(Category).columns if pk.primary_key]
assert pks, 'Ca... | Provides support for handling the action categories. By CATEGORY object is meant the object that has been configured to have the actions mapping on it. | ActionCategoryServiceAlchemy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionCategoryServiceAlchemy:
"""Provides support for handling the action categories. By CATEGORY object is meant the object that has been configured to have the actions mapping on it."""
def __init__(self, Category, CategoryAction):
"""Construct the action category service alchemy. ... | stack_v2_sparse_classes_36k_train_001307 | 4,702 | no_license | [
{
"docstring": "Construct the action category service alchemy. @param Category: Base class The category mapped class that organizes the actions based on. @param CategoryAction: class of WithCategoryAction The action category relation mapped class.",
"name": "__init__",
"signature": "def __init__(self, C... | 6 | stack_v2_sparse_classes_30k_train_006900 | Implement the Python class `ActionCategoryServiceAlchemy` described below.
Class description:
Provides support for handling the action categories. By CATEGORY object is meant the object that has been configured to have the actions mapping on it.
Method signatures and docstrings:
- def __init__(self, Category, Categor... | Implement the Python class `ActionCategoryServiceAlchemy` described below.
Class description:
Provides support for handling the action categories. By CATEGORY object is meant the object that has been configured to have the actions mapping on it.
Method signatures and docstrings:
- def __init__(self, Category, Categor... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class ActionCategoryServiceAlchemy:
"""Provides support for handling the action categories. By CATEGORY object is meant the object that has been configured to have the actions mapping on it."""
def __init__(self, Category, CategoryAction):
"""Construct the action category service alchemy. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionCategoryServiceAlchemy:
"""Provides support for handling the action categories. By CATEGORY object is meant the object that has been configured to have the actions mapping on it."""
def __init__(self, Category, CategoryAction):
"""Construct the action category service alchemy. @param Catego... | the_stack_v2_python_sparse | plugins/gui-action/gui/action/core/impl/category.py | cristidomsa/Ally-Py | train | 0 |
5cdf4f096f3d83c2a7fc7243e48c06cf07fd4358 | [
"super().setupUI(Form)\nself.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)\nself.label_4.setToolTip('')\nself.label_4.setAlignment(QtCore.Qt.AlignCenter)\nself.label_4.setObjectName('label_4')\nself.verticalLayout_2.addWidget(self.label_4)\nself.label_8 = QtWidgets.QLabel(self.verticalLayoutWidget)\nself.la... | <|body_start_0|>
super().setupUI(Form)
self.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_4.setToolTip('')
self.label_4.setAlignment(QtCore.Qt.AlignCenter)
self.label_4.setObjectName('label_4')
self.verticalLayout_2.addWidget(self.label_4)
self.... | TMTWindowWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TMTWindowWidget:
def setupUi(self, Form):
"""Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget)"""
<|body_0|>
def retranslateUi(sel... | stack_v2_sparse_classes_36k_train_001308 | 2,685 | no_license | [
{
"docstring": "Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget)",
"name": "setupUi",
"signature": "def setupUi(self, Form)"
},
{
"docstring": "Método... | 2 | stack_v2_sparse_classes_30k_train_016562 | Implement the Python class `TMTWindowWidget` described below.
Class description:
Implement the TMTWindowWidget class.
Method signatures and docstrings:
- def setupUi(self, Form): Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la... | Implement the Python class `TMTWindowWidget` described below.
Class description:
Implement the TMTWindowWidget class.
Method signatures and docstrings:
- def setupUi(self, Form): Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la... | 5d1d68fc4476ed866ecfc305112854d9a49c3876 | <|skeleton|>
class TMTWindowWidget:
def setupUi(self, Form):
"""Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget)"""
<|body_0|>
def retranslateUi(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TMTWindowWidget:
def setupUi(self, Form):
"""Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget)"""
super().setupUI(Form)
self.label_4 = QtWidg... | the_stack_v2_python_sparse | src/main/python/vistas/TMTWindowWidget.py | ProyectoIntegrador2018/reportes-neurociencias | train | 1 | |
aa3827ace2e5554bf982e5dad99076878354973c | [
"super(NonLocalBlock, self).__init__()\nself.compression_factor = 1 if args.use_precomputed_hiddens else compression_factor\nself.theta_conv = nn.Conv2d(inplanes, inplanes // 2, kernel_size=1, bias=False)\nself.phi_conv = nn.Conv2d(inplanes, inplanes // 2, kernel_size=1, bias=False)\nself.g_conv = nn.Conv2d(inplane... | <|body_start_0|>
super(NonLocalBlock, self).__init__()
self.compression_factor = 1 if args.use_precomputed_hiddens else compression_factor
self.theta_conv = nn.Conv2d(inplanes, inplanes // 2, kernel_size=1, bias=False)
self.phi_conv = nn.Conv2d(inplanes, inplanes // 2, kernel_size=1, bia... | An embedded gaussian non-local block. | NonLocalBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NonLocalBlock:
"""An embedded gaussian non-local block."""
def __init__(self, args, inplanes, planes, stride=1, downsample=None, compression_factor=2):
"""Initializes the NonLocalBlock. Arguments: inplanes(int): The depth (number of channels) of the input. planes(int): The depth (num... | stack_v2_sparse_classes_36k_train_001309 | 4,206 | permissive | [
{
"docstring": "Initializes the NonLocalBlock. Arguments: inplanes(int): The depth (number of channels) of the input. planes(int): The depth (number of channels) of the output. downsample(nn.Module): When not none, used to downsample output to planes. compression_factor(int): The compression factor to use when ... | 2 | stack_v2_sparse_classes_30k_train_003128 | Implement the Python class `NonLocalBlock` described below.
Class description:
An embedded gaussian non-local block.
Method signatures and docstrings:
- def __init__(self, args, inplanes, planes, stride=1, downsample=None, compression_factor=2): Initializes the NonLocalBlock. Arguments: inplanes(int): The depth (numb... | Implement the Python class `NonLocalBlock` described below.
Class description:
An embedded gaussian non-local block.
Method signatures and docstrings:
- def __init__(self, args, inplanes, planes, stride=1, downsample=None, compression_factor=2): Initializes the NonLocalBlock. Arguments: inplanes(int): The depth (numb... | 12bace8fd6ce9c5bb129fd0d30a46a00a2f7b054 | <|skeleton|>
class NonLocalBlock:
"""An embedded gaussian non-local block."""
def __init__(self, args, inplanes, planes, stride=1, downsample=None, compression_factor=2):
"""Initializes the NonLocalBlock. Arguments: inplanes(int): The depth (number of channels) of the input. planes(int): The depth (num... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NonLocalBlock:
"""An embedded gaussian non-local block."""
def __init__(self, args, inplanes, planes, stride=1, downsample=None, compression_factor=2):
"""Initializes the NonLocalBlock. Arguments: inplanes(int): The depth (number of channels) of the input. planes(int): The depth (number of channe... | the_stack_v2_python_sparse | onconet/models/blocks/non_local_block.py | yala/Mirai | train | 66 |
3ca2f8b2dd0b84b9f9491d80ba02bcd19da80d24 | [
"if not root:\n return ''\nreturn '{} '.format(root.val) + self.serialize(root.left) + self.serialize(root.right)",
"if not data:\n return\nstack = []\ndata = [int(d) for d in data[:-1].split(' ')]\nroot = node = TreeNode(data[0])\nfor val in data[1:]:\n if val < node.val:\n node.left = TreeNode(v... | <|body_start_0|>
if not root:
return ''
return '{} '.format(root.val) + self.serialize(root.left) + self.serialize(root.right)
<|end_body_0|>
<|body_start_1|>
if not data:
return
stack = []
data = [int(d) for d in data[:-1].split(' ')]
root = node... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_001310 | 1,716 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_001516 | 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:... | 9126c2089e41d4d7fd3a204115eba2b5074076ad | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
return '{} '.format(root.val) + self.serialize(root.left) + self.serialize(root.right)
def deserialize(self, data):
"""Decodes you... | the_stack_v2_python_sparse | 449_Serialize and Deserialize BST.py | Shwan-Yu/Data_Structures_and_Algorithms | train | 0 | |
d0bb79136380543f446c01d8ce83cb64fa6b5495 | [
"self.version = None\nself.provider = None\nself.mkguid = None\nself.mkversion = None\nself.flags = None\nself.description = None\nself.cipherAlgo = None\nself.keyLen = 0\nself.hmac = None\nself.strong = None\nself.hashAlgo = None\nself.hashLen = 0\nself.cipherText = None\nself.salt = None\nself.blob = None\nself.s... | <|body_start_0|>
self.version = None
self.provider = None
self.mkguid = None
self.mkversion = None
self.flags = None
self.description = None
self.cipherAlgo = None
self.keyLen = 0
self.hmac = None
self.strong = None
self.hashAlgo = ... | Represents a DPAPI blob | DPAPIBlob | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DPAPIBlob:
"""Represents a DPAPI blob"""
def __init__(self, raw=None):
"""Constructs a DPAPIBlob. If raw is set, automatically calls parse()."""
<|body_0|>
def parse(self, data):
"""Parses the given data. May raise exceptions if incorrect data are given. You shou... | stack_v2_sparse_classes_36k_train_001311 | 5,243 | permissive | [
{
"docstring": "Constructs a DPAPIBlob. If raw is set, automatically calls parse().",
"name": "__init__",
"signature": "def __init__(self, raw=None)"
},
{
"docstring": "Parses the given data. May raise exceptions if incorrect data are given. You should not call this function yourself; DataStruct... | 4 | stack_v2_sparse_classes_30k_train_005600 | Implement the Python class `DPAPIBlob` described below.
Class description:
Represents a DPAPI blob
Method signatures and docstrings:
- def __init__(self, raw=None): Constructs a DPAPIBlob. If raw is set, automatically calls parse().
- def parse(self, data): Parses the given data. May raise exceptions if incorrect dat... | Implement the Python class `DPAPIBlob` described below.
Class description:
Represents a DPAPI blob
Method signatures and docstrings:
- def __init__(self, raw=None): Constructs a DPAPIBlob. If raw is set, automatically calls parse().
- def parse(self, data): Parses the given data. May raise exceptions if incorrect dat... | 4b1d1327ebfbd550ba7e5f1b5562c1f3db61311e | <|skeleton|>
class DPAPIBlob:
"""Represents a DPAPI blob"""
def __init__(self, raw=None):
"""Constructs a DPAPIBlob. If raw is set, automatically calls parse()."""
<|body_0|>
def parse(self, data):
"""Parses the given data. May raise exceptions if incorrect data are given. You shou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DPAPIBlob:
"""Represents a DPAPI blob"""
def __init__(self, raw=None):
"""Constructs a DPAPIBlob. If raw is set, automatically calls parse()."""
self.version = None
self.provider = None
self.mkguid = None
self.mkversion = None
self.flags = None
self... | the_stack_v2_python_sparse | sandworm/Resources/browser-creds/Windows/lazagne/config/DPAPI/blob.py | center-for-threat-informed-defense/adversary_emulation_library | train | 1,220 |
8088bc5b2311607af3c9946eb29481f6881a7730 | [
"if not provider:\n raise ValueError('Stats provider input must not be empty.')\nself._provider = provider\nself._methods = methods\nself._ignore_missing = ignore_missing",
"instance = self._provider.provide(config, injector)\nif self._methods:\n collector: Collector = injector.inject_or(Collector)\n if ... | <|body_start_0|>
if not provider:
raise ValueError('Stats provider input must not be empty.')
self._provider = provider
self._methods = methods
self._ignore_missing = ignore_missing
<|end_body_0|>
<|body_start_1|>
instance = self._provider.provide(config, injector)
... | Add statistics to the results of another provider. | StatsProvider | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatsProvider:
"""Add statistics to the results of another provider."""
def __init__(self, provider: BaseProvider, methods: Sequence[str], *, ignore_missing: bool=True):
"""Initialize the statistics provider instance."""
<|body_0|>
def provide(self, config: BaseSettings,... | stack_v2_sparse_classes_36k_train_001312 | 4,857 | permissive | [
{
"docstring": "Initialize the statistics provider instance.",
"name": "__init__",
"signature": "def __init__(self, provider: BaseProvider, methods: Sequence[str], *, ignore_missing: bool=True)"
},
{
"docstring": "Provide the object instance given a config and injector.",
"name": "provide",
... | 2 | stack_v2_sparse_classes_30k_train_005490 | Implement the Python class `StatsProvider` described below.
Class description:
Add statistics to the results of another provider.
Method signatures and docstrings:
- def __init__(self, provider: BaseProvider, methods: Sequence[str], *, ignore_missing: bool=True): Initialize the statistics provider instance.
- def pro... | Implement the Python class `StatsProvider` described below.
Class description:
Add statistics to the results of another provider.
Method signatures and docstrings:
- def __init__(self, provider: BaseProvider, methods: Sequence[str], *, ignore_missing: bool=True): Initialize the statistics provider instance.
- def pro... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class StatsProvider:
"""Add statistics to the results of another provider."""
def __init__(self, provider: BaseProvider, methods: Sequence[str], *, ignore_missing: bool=True):
"""Initialize the statistics provider instance."""
<|body_0|>
def provide(self, config: BaseSettings,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StatsProvider:
"""Add statistics to the results of another provider."""
def __init__(self, provider: BaseProvider, methods: Sequence[str], *, ignore_missing: bool=True):
"""Initialize the statistics provider instance."""
if not provider:
raise ValueError('Stats provider input ... | the_stack_v2_python_sparse | aries_cloudagent/config/provider.py | hyperledger/aries-cloudagent-python | train | 370 |
dde744716a950b843b40130d30136c03deff475a | [
"self._executable = executable\nself._command = command\nself._args = args",
"subproc = Popen([self._executable, self._command] + self._args, stderr=PIPE)\nerr = ''\nwhile subproc.poll() is None:\n line = subproc.stderr.readline().decode('utf-8')\n err += line\n sys.stderr.write(line)\n sys.stderr.flu... | <|body_start_0|>
self._executable = executable
self._command = command
self._args = args
<|end_body_0|>
<|body_start_1|>
subproc = Popen([self._executable, self._command] + self._args, stderr=PIPE)
err = ''
while subproc.poll() is None:
line = subproc.stderr.... | SubcommandProcess | [
"Apache-2.0",
"BSD-3-Clause",
"Python-2.0",
"GPL-3.0-only",
"LicenseRef-scancode-public-domain",
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubcommandProcess:
def __init__(self, executable, command, args):
"""Representes a subcommand running by a forked process :param executable: executable to run :type executable: executable :param command: command to run by executable :type command: str :param args: arguments for command :... | stack_v2_sparse_classes_36k_train_001313 | 19,291 | permissive | [
{
"docstring": "Representes a subcommand running by a forked process :param executable: executable to run :type executable: executable :param command: command to run by executable :type command: str :param args: arguments for command :type args: [str]",
"name": "__init__",
"signature": "def __init__(sel... | 2 | stack_v2_sparse_classes_30k_train_000172 | Implement the Python class `SubcommandProcess` described below.
Class description:
Implement the SubcommandProcess class.
Method signatures and docstrings:
- def __init__(self, executable, command, args): Representes a subcommand running by a forked process :param executable: executable to run :type executable: execu... | Implement the Python class `SubcommandProcess` described below.
Class description:
Implement the SubcommandProcess class.
Method signatures and docstrings:
- def __init__(self, executable, command, args): Representes a subcommand running by a forked process :param executable: executable to run :type executable: execu... | 7da04b533fa77a04a3b05fe55a9fec13715a2e1e | <|skeleton|>
class SubcommandProcess:
def __init__(self, executable, command, args):
"""Representes a subcommand running by a forked process :param executable: executable to run :type executable: executable :param command: command to run by executable :type command: str :param args: arguments for command :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubcommandProcess:
def __init__(self, executable, command, args):
"""Representes a subcommand running by a forked process :param executable: executable to run :type executable: executable :param command: command to run by executable :type command: str :param args: arguments for command :type args: [st... | the_stack_v2_python_sparse | docker/jenkins-executor/bin/dcos-cli/dcos/subcommand.py | softonic/deploy-marathon-bluegreen | train | 2 | |
7db9398fc31ab0e3a8f14db31f3ce0c6f105b9b3 | [
"test_utils.set_competition_round()\ngroup = Group.objects.create(name='Test Group')\ngroup.save()\nself.team = Team.objects.create(group=group, name='A')\nself.user = User.objects.create_user('user', 'user@test.com')\nprofile = self.user.get_profile()\nprofile.team = self.team\nprofile.save()",
"profile = self.u... | <|body_start_0|>
test_utils.set_competition_round()
group = Group.objects.create(name='Test Group')
group.save()
self.team = Team.objects.create(group=group, name='A')
self.user = User.objects.create_user('user', 'user@test.com')
profile = self.user.get_profile()
... | Team Energy Goal Test | TeamEnergyGoalTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamEnergyGoalTest:
"""Team Energy Goal Test"""
def setUp(self):
"""setup"""
<|body_0|>
def testTeamEnergyGoal(self):
"""Test energy goal"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test_utils.set_competition_round()
group = Group.ob... | stack_v2_sparse_classes_36k_train_001314 | 3,231 | permissive | [
{
"docstring": "setup",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test energy goal",
"name": "testTeamEnergyGoal",
"signature": "def testTeamEnergyGoal(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010747 | Implement the Python class `TeamEnergyGoalTest` described below.
Class description:
Team Energy Goal Test
Method signatures and docstrings:
- def setUp(self): setup
- def testTeamEnergyGoal(self): Test energy goal | Implement the Python class `TeamEnergyGoalTest` described below.
Class description:
Team Energy Goal Test
Method signatures and docstrings:
- def setUp(self): setup
- def testTeamEnergyGoal(self): Test energy goal
<|skeleton|>
class TeamEnergyGoalTest:
"""Team Energy Goal Test"""
def setUp(self):
""... | 4b7dd685012ec64758affe0ecee3103596d16aa7 | <|skeleton|>
class TeamEnergyGoalTest:
"""Team Energy Goal Test"""
def setUp(self):
"""setup"""
<|body_0|>
def testTeamEnergyGoal(self):
"""Test energy goal"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamEnergyGoalTest:
"""Team Energy Goal Test"""
def setUp(self):
"""setup"""
test_utils.set_competition_round()
group = Group.objects.create(name='Test Group')
group.save()
self.team = Team.objects.create(group=group, name='A')
self.user = User.objects.crea... | the_stack_v2_python_sparse | makahiki/apps/widgets/resource_goal/tests.py | justinslee/Wai-Not-Makahiki | train | 1 |
536fce87c6c80651254a716fdf6c5268173018ab | [
"if link_map_key in self.LINK_MAP:\n link_tuple = self.LINK_MAP[link_map_key]\n link = self.find_element(link_tuple[0])\n if not self.fixed:\n actions.scroll.into_view(self.driver, link)\n link.click()\n return None if link_tuple[1] is None else link_tuple[1](self.driver)",
"if link_map_key ... | <|body_start_0|>
if link_map_key in self.LINK_MAP:
link_tuple = self.LINK_MAP[link_map_key]
link = self.find_element(link_tuple[0])
if not self.fixed:
actions.scroll.into_view(self.driver, link)
link.click()
return None if link_tuple[1]... | Page object prototype for navbars :var LINK_MAP: Maps link text to a tuple containing its locator and the page object class for the target page, modal, section, etc (or None if need be). Override in subclasses :var HOVER_MAP: Maps link text to a tuple containing its locator and the page object class for the menu, dropd... | NavObject | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NavObject:
"""Page object prototype for navbars :var LINK_MAP: Maps link text to a tuple containing its locator and the page object class for the target page, modal, section, etc (or None if need be). Override in subclasses :var HOVER_MAP: Maps link text to a tuple containing its locator and the ... | stack_v2_sparse_classes_36k_train_001315 | 4,428 | permissive | [
{
"docstring": "Click one of the page links and return a page object class for the link target :param link_map_key: Key into :attr:`LINK_MAP` for the link to click on :return: Corresponding page object class for the link target (if applicable)",
"name": "click_page_link",
"signature": "def click_page_li... | 2 | null | Implement the Python class `NavObject` described below.
Class description:
Page object prototype for navbars :var LINK_MAP: Maps link text to a tuple containing its locator and the page object class for the target page, modal, section, etc (or None if need be). Override in subclasses :var HOVER_MAP: Maps link text to ... | Implement the Python class `NavObject` described below.
Class description:
Page object prototype for navbars :var LINK_MAP: Maps link text to a tuple containing its locator and the page object class for the target page, modal, section, etc (or None if need be). Override in subclasses :var HOVER_MAP: Maps link text to ... | 31c91905611dee9cc13dbf37e7c0cfbf9ca0173f | <|skeleton|>
class NavObject:
"""Page object prototype for navbars :var LINK_MAP: Maps link text to a tuple containing its locator and the page object class for the target page, modal, section, etc (or None if need be). Override in subclasses :var HOVER_MAP: Maps link text to a tuple containing its locator and the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NavObject:
"""Page object prototype for navbars :var LINK_MAP: Maps link text to a tuple containing its locator and the page object class for the target page, modal, section, etc (or None if need be). Override in subclasses :var HOVER_MAP: Maps link text to a tuple containing its locator and the page object c... | the_stack_v2_python_sparse | venv/lib/python3.5/site-packages/webdriver_test_tools/pageobject/nav.py | alexmudra/python_experiments | train | 0 |
1d828ad10edfefced22e2923e6794a76fea29e96 | [
"operation = EventOperation(data.get(EVENT_OPERATION))\ntopic = data.get(EVENT_TOPIC, '')\nsource = data.get(EVENT_SOURCE, '')\nsource_idx = data.get(EVENT_SOURCE_IDX, '')\nvalue = data.get(EVENT_VALUE, '')\nif (topic_base := EventTopic(topic)) == EventTopic.UNKNOWN:\n _topic_base, _, _source_idx = topic.rpartit... | <|body_start_0|>
operation = EventOperation(data.get(EVENT_OPERATION))
topic = data.get(EVENT_TOPIC, '')
source = data.get(EVENT_SOURCE, '')
source_idx = data.get(EVENT_SOURCE_IDX, '')
value = data.get(EVENT_VALUE, '')
if (topic_base := EventTopic(topic)) == EventTopic.UN... | Event data from deCONZ websocket. | Event | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Event:
"""Event data from deCONZ websocket."""
def from_dict(cls, data: dict[str, Any]) -> 'Event':
"""Create event instance from dict."""
<|body_0|>
def from_bytes(data: bytes) -> 'Event':
"""Parse metadata xml."""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_001316 | 6,665 | permissive | [
{
"docstring": "Create event instance from dict.",
"name": "from_dict",
"signature": "def from_dict(cls, data: dict[str, Any]) -> 'Event'"
},
{
"docstring": "Parse metadata xml.",
"name": "from_bytes",
"signature": "def from_bytes(data: bytes) -> 'Event'"
}
] | 2 | stack_v2_sparse_classes_30k_val_000298 | Implement the Python class `Event` described below.
Class description:
Event data from deCONZ websocket.
Method signatures and docstrings:
- def from_dict(cls, data: dict[str, Any]) -> 'Event': Create event instance from dict.
- def from_bytes(data: bytes) -> 'Event': Parse metadata xml. | Implement the Python class `Event` described below.
Class description:
Event data from deCONZ websocket.
Method signatures and docstrings:
- def from_dict(cls, data: dict[str, Any]) -> 'Event': Create event instance from dict.
- def from_bytes(data: bytes) -> 'Event': Parse metadata xml.
<|skeleton|>
class Event:
... | c1536b6f949936013b59aa3052bea9c9bf4b1d15 | <|skeleton|>
class Event:
"""Event data from deCONZ websocket."""
def from_dict(cls, data: dict[str, Any]) -> 'Event':
"""Create event instance from dict."""
<|body_0|>
def from_bytes(data: bytes) -> 'Event':
"""Parse metadata xml."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Event:
"""Event data from deCONZ websocket."""
def from_dict(cls, data: dict[str, Any]) -> 'Event':
"""Create event instance from dict."""
operation = EventOperation(data.get(EVENT_OPERATION))
topic = data.get(EVENT_TOPIC, '')
source = data.get(EVENT_SOURCE, '')
so... | the_stack_v2_python_sparse | axis/models/event.py | Kane610/axis | train | 23 |
e2f05121a93e621de458a8022c2a7aadd8891c34 | [
"src_relationships, dst_relationships = Relationship.objects.get_for_model(self)\ncontent_type = ContentType.objects.get_for_model(self)\nsides = {RelationshipSideChoices.SIDE_SOURCE: src_relationships, RelationshipSideChoices.SIDE_DESTINATION: dst_relationships}\nresp = {RelationshipSideChoices.SIDE_SOURCE: Ordere... | <|body_start_0|>
src_relationships, dst_relationships = Relationship.objects.get_for_model(self)
content_type = ContentType.objects.get_for_model(self)
sides = {RelationshipSideChoices.SIDE_SOURCE: src_relationships, RelationshipSideChoices.SIDE_DESTINATION: dst_relationships}
resp = {Re... | Abstract class for any model which may have custom relationships associated with it. | RelationshipModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelationshipModel:
"""Abstract class for any model which may have custom relationships associated with it."""
def get_relationships(self, include_hidden=False):
"""Return a dictionary of queryset for all custom relationships Returns: response { "source": { <relationship #1>: <queryse... | stack_v2_sparse_classes_36k_train_001317 | 18,231 | permissive | [
{
"docstring": "Return a dictionary of queryset for all custom relationships Returns: response { \"source\": { <relationship #1>: <queryset #1>, <relationship #2>: <queryset #2>, }, \"destination\": { <relationship #3>: <queryset #3>, <relationship #4>: <queryset #4>, }, }",
"name": "get_relationships",
... | 2 | null | Implement the Python class `RelationshipModel` described below.
Class description:
Abstract class for any model which may have custom relationships associated with it.
Method signatures and docstrings:
- def get_relationships(self, include_hidden=False): Return a dictionary of queryset for all custom relationships Re... | Implement the Python class `RelationshipModel` described below.
Class description:
Abstract class for any model which may have custom relationships associated with it.
Method signatures and docstrings:
- def get_relationships(self, include_hidden=False): Return a dictionary of queryset for all custom relationships Re... | d441b2d92415bd3122fe86ea21544d0acd98e95a | <|skeleton|>
class RelationshipModel:
"""Abstract class for any model which may have custom relationships associated with it."""
def get_relationships(self, include_hidden=False):
"""Return a dictionary of queryset for all custom relationships Returns: response { "source": { <relationship #1>: <queryse... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelationshipModel:
"""Abstract class for any model which may have custom relationships associated with it."""
def get_relationships(self, include_hidden=False):
"""Return a dictionary of queryset for all custom relationships Returns: response { "source": { <relationship #1>: <queryset #1>, <relat... | the_stack_v2_python_sparse | nautobot/extras/models/relationships.py | hellerve/nautobot | train | 1 |
55635ed1a1d82ecec7a592001e19eda422acfeee | [
"latest = 1\ncurr = 0\nwhile True:\n curr = latest\n latest = (latest + x / latest) / 2\n if abs(latest - curr) < 1e-07:\n break\nreturn int(curr)",
"if x == 0:\n return 0\nleft, right = (1, x >> 1)\nwhile left < right:\n mid = left + right + 1 >> 1\n v = mid * mid\n if v > x:\n ... | <|body_start_0|>
latest = 1
curr = 0
while True:
curr = latest
latest = (latest + x / latest) / 2
if abs(latest - curr) < 1e-07:
break
return int(curr)
<|end_body_0|>
<|body_start_1|>
if x == 0:
return 0
lef... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sqrt(self, x):
"""数学分析法,牛顿迭代法:"""
<|body_0|>
def sqrt1(self, x):
"""二分法很好理解,要知道任何一个正整数的算术平方根是不可能大于这个数的一般的,所以基于这个特性,我们可以利用二分查找找[1, x / 2]那个数与x最接近。 注意的是,我们找中位数的时候,要找右中位数, 因为当遇到x = 9的时候,我们计算到区间[3, 4],如果此时去中位数按照以前mid = (left + right) // 2的话, 此时mid = 3, 那么 m... | stack_v2_sparse_classes_36k_train_001318 | 1,782 | no_license | [
{
"docstring": "数学分析法,牛顿迭代法:",
"name": "sqrt",
"signature": "def sqrt(self, x)"
},
{
"docstring": "二分法很好理解,要知道任何一个正整数的算术平方根是不可能大于这个数的一般的,所以基于这个特性,我们可以利用二分查找找[1, x / 2]那个数与x最接近。 注意的是,我们找中位数的时候,要找右中位数, 因为当遇到x = 9的时候,我们计算到区间[3, 4],如果此时去中位数按照以前mid = (left + right) // 2的话, 此时mid = 3, 那么 mid * mid = 9... | 2 | stack_v2_sparse_classes_30k_train_017651 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sqrt(self, x): 数学分析法,牛顿迭代法:
- def sqrt1(self, x): 二分法很好理解,要知道任何一个正整数的算术平方根是不可能大于这个数的一般的,所以基于这个特性,我们可以利用二分查找找[1, x / 2]那个数与x最接近。 注意的是,我们找中位数的时候,要找右中位数, 因为当遇到x = 9的时候,我们计算到区间[3... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sqrt(self, x): 数学分析法,牛顿迭代法:
- def sqrt1(self, x): 二分法很好理解,要知道任何一个正整数的算术平方根是不可能大于这个数的一般的,所以基于这个特性,我们可以利用二分查找找[1, x / 2]那个数与x最接近。 注意的是,我们找中位数的时候,要找右中位数, 因为当遇到x = 9的时候,我们计算到区间[3... | 0cc970aaa03aa9300319a1e39e052e4beeec6698 | <|skeleton|>
class Solution:
def sqrt(self, x):
"""数学分析法,牛顿迭代法:"""
<|body_0|>
def sqrt1(self, x):
"""二分法很好理解,要知道任何一个正整数的算术平方根是不可能大于这个数的一般的,所以基于这个特性,我们可以利用二分查找找[1, x / 2]那个数与x最接近。 注意的是,我们找中位数的时候,要找右中位数, 因为当遇到x = 9的时候,我们计算到区间[3, 4],如果此时去中位数按照以前mid = (left + right) // 2的话, 此时mid = 3, 那么 m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sqrt(self, x):
"""数学分析法,牛顿迭代法:"""
latest = 1
curr = 0
while True:
curr = latest
latest = (latest + x / latest) / 2
if abs(latest - curr) < 1e-07:
break
return int(curr)
def sqrt1(self, x):
""... | the_stack_v2_python_sparse | leetcode.69x的平方根.py | NonCover/- | train | 2 | |
5e9791417050a60409cd4a1b3d7cc4863b9a7134 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ManagedDeviceOverview()",
"from .device_exchange_access_state_summary import DeviceExchangeAccessStateSummary\nfrom .device_operating_system_summary import DeviceOperatingSystemSummary\nfrom .entity import Entity\nfrom .device_exchange... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ManagedDeviceOverview()
<|end_body_0|>
<|body_start_1|>
from .device_exchange_access_state_summary import DeviceExchangeAccessStateSummary
from .device_operating_system_summary import De... | Summary data for managed devices | ManagedDeviceOverview | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManagedDeviceOverview:
"""Summary data for managed devices"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedDeviceOverview:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to... | stack_v2_sparse_classes_36k_train_001319 | 4,046 | 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: ManagedDeviceOverview",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | stack_v2_sparse_classes_30k_train_009812 | Implement the Python class `ManagedDeviceOverview` described below.
Class description:
Summary data for managed devices
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedDeviceOverview: Creates a new instance of the appropriate class based on discr... | Implement the Python class `ManagedDeviceOverview` described below.
Class description:
Summary data for managed devices
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedDeviceOverview: Creates a new instance of the appropriate class based on discr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ManagedDeviceOverview:
"""Summary data for managed devices"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedDeviceOverview:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManagedDeviceOverview:
"""Summary data for managed devices"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedDeviceOverview:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the dis... | the_stack_v2_python_sparse | msgraph/generated/models/managed_device_overview.py | microsoftgraph/msgraph-sdk-python | train | 135 |
11ce7a7ac72194d13464380542092cdbf9129f97 | [
"self.buffer = deque()\nself.max_size = max_size\nself.min_size = min_size",
"if len(self.buffer) > self.max_size:\n self.buffer.popleft()\nself.buffer.append(exp)",
"sampled_buffer = random.sample(self.buffer, batch_size)\nstate, next_state, reward, action, done = zip(*sampled_buffer)\nstate, next_state = (... | <|body_start_0|>
self.buffer = deque()
self.max_size = max_size
self.min_size = min_size
<|end_body_0|>
<|body_start_1|>
if len(self.buffer) > self.max_size:
self.buffer.popleft()
self.buffer.append(exp)
<|end_body_1|>
<|body_start_2|>
sampled_buffer = rando... | Experience Buffer where the episode information is stored | ExpBuffer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpBuffer:
"""Experience Buffer where the episode information is stored"""
def __init__(self, max_size=10000, min_size=5000):
"""Initializes the maximum size of the buffer. Args: max_size: Height of the imag"""
<|body_0|>
def add_exp(self, exp):
"""Adds an experi... | stack_v2_sparse_classes_36k_train_001320 | 1,959 | permissive | [
{
"docstring": "Initializes the maximum size of the buffer. Args: max_size: Height of the imag",
"name": "__init__",
"signature": "def __init__(self, max_size=10000, min_size=5000)"
},
{
"docstring": "Adds an experience to the buffer.",
"name": "add_exp",
"signature": "def add_exp(self, ... | 3 | null | Implement the Python class `ExpBuffer` described below.
Class description:
Experience Buffer where the episode information is stored
Method signatures and docstrings:
- def __init__(self, max_size=10000, min_size=5000): Initializes the maximum size of the buffer. Args: max_size: Height of the imag
- def add_exp(self,... | Implement the Python class `ExpBuffer` described below.
Class description:
Experience Buffer where the episode information is stored
Method signatures and docstrings:
- def __init__(self, max_size=10000, min_size=5000): Initializes the maximum size of the buffer. Args: max_size: Height of the imag
- def add_exp(self,... | 975a95032ce5b7012d1772c7f1f5cfe606eae839 | <|skeleton|>
class ExpBuffer:
"""Experience Buffer where the episode information is stored"""
def __init__(self, max_size=10000, min_size=5000):
"""Initializes the maximum size of the buffer. Args: max_size: Height of the imag"""
<|body_0|>
def add_exp(self, exp):
"""Adds an experi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExpBuffer:
"""Experience Buffer where the episode information is stored"""
def __init__(self, max_size=10000, min_size=5000):
"""Initializes the maximum size of the buffer. Args: max_size: Height of the imag"""
self.buffer = deque()
self.max_size = max_size
self.min_size =... | the_stack_v2_python_sparse | blogs/rl-on-gcp/DQN_Breakout/rl_on_gcp/trainer/buffer.py | GoogleCloudPlatform/training-data-analyst | train | 7,311 |
486bf90aaebe5f015056c626ce14a695a50a6c63 | [
"super().__init__()\nself.city_list = cities\nself.overhead_time_queue = queue\nProducerThread.id_counter += 1\nself.id = ProducerThread.id_counter",
"count = 1\nfor city in self.city_list:\n overhead_times = ISSDataRequest.get_overhead_pass(city)\n logging.info('Producer %d is adding to the queue', self.id... | <|body_start_0|>
super().__init__()
self.city_list = cities
self.overhead_time_queue = queue
ProducerThread.id_counter += 1
self.id = ProducerThread.id_counter
<|end_body_0|>
<|body_start_1|>
count = 1
for city in self.city_list:
overhead_times = ISSD... | Adds the data retrieved from endpoint to the queue. | ProducerThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProducerThread:
"""Adds the data retrieved from endpoint to the queue."""
def __init__(self, cities: list, queue: CityOverheadTimeQueue):
""":param cities: a list of City objects :param queue: a CityOverheadTimeQueue"""
<|body_0|>
def run(self) -> None:
"""Retrie... | stack_v2_sparse_classes_36k_train_001321 | 3,229 | no_license | [
{
"docstring": ":param cities: a list of City objects :param queue: a CityOverheadTimeQueue",
"name": "__init__",
"signature": "def __init__(self, cities: list, queue: CityOverheadTimeQueue)"
},
{
"docstring": "Retrieves data for each city and adds it to the queue.",
"name": "run",
"sign... | 2 | stack_v2_sparse_classes_30k_train_009636 | Implement the Python class `ProducerThread` described below.
Class description:
Adds the data retrieved from endpoint to the queue.
Method signatures and docstrings:
- def __init__(self, cities: list, queue: CityOverheadTimeQueue): :param cities: a list of City objects :param queue: a CityOverheadTimeQueue
- def run(... | Implement the Python class `ProducerThread` described below.
Class description:
Adds the data retrieved from endpoint to the queue.
Method signatures and docstrings:
- def __init__(self, cities: list, queue: CityOverheadTimeQueue): :param cities: a list of City objects :param queue: a CityOverheadTimeQueue
- def run(... | 11c3806aee78fa0e78bdf8037d4c203645df5500 | <|skeleton|>
class ProducerThread:
"""Adds the data retrieved from endpoint to the queue."""
def __init__(self, cities: list, queue: CityOverheadTimeQueue):
""":param cities: a list of City objects :param queue: a CityOverheadTimeQueue"""
<|body_0|>
def run(self) -> None:
"""Retrie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProducerThread:
"""Adds the data retrieved from endpoint to the queue."""
def __init__(self, cities: list, queue: CityOverheadTimeQueue):
""":param cities: a list of City objects :param queue: a CityOverheadTimeQueue"""
super().__init__()
self.city_list = cities
self.overh... | the_stack_v2_python_sparse | Labs/Lab10/producer_consumer.py | chrisyandev/PythonAssignments | train | 0 |
f0bdc18bbdc65c9e968d24215b8e50bef2352cc7 | [
"super(Conv2dSubsampling, self).__init__()\nself.conv = torch.nn.Sequential(torch.nn.Conv2d(1, odim, 3, 2), torch.nn.ReLU(), torch.nn.Conv2d(odim, odim, 3, 2), torch.nn.ReLU())\nself.out = torch.nn.Sequential(torch.nn.Linear(odim * (((idim - 1) // 2 - 1) // 2), odim), pos_enc if pos_enc is not None else PositionalE... | <|body_start_0|>
super(Conv2dSubsampling, self).__init__()
self.conv = torch.nn.Sequential(torch.nn.Conv2d(1, odim, 3, 2), torch.nn.ReLU(), torch.nn.Conv2d(odim, odim, 3, 2), torch.nn.ReLU())
self.out = torch.nn.Sequential(torch.nn.Linear(odim * (((idim - 1) // 2 - 1) // 2), odim), pos_enc if po... | Convolutional 2D subsampling (to 1/4 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer. | Conv2dSubsampling | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv2dSubsampling:
"""Convolutional 2D subsampling (to 1/4 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer."""
def __init__(self, idim, odim, dropout_rate, pos_enc=None):
... | stack_v2_sparse_classes_36k_train_001322 | 14,351 | permissive | [
{
"docstring": "Construct an Conv2dSubsampling object.",
"name": "__init__",
"signature": "def __init__(self, idim, odim, dropout_rate, pos_enc=None)"
},
{
"docstring": "Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tensor): Input mask (#batch, 1, time). R... | 3 | null | Implement the Python class `Conv2dSubsampling` described below.
Class description:
Convolutional 2D subsampling (to 1/4 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer.
Method signatures and docstri... | Implement the Python class `Conv2dSubsampling` described below.
Class description:
Convolutional 2D subsampling (to 1/4 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer.
Method signatures and docstri... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class Conv2dSubsampling:
"""Convolutional 2D subsampling (to 1/4 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer."""
def __init__(self, idim, odim, dropout_rate, pos_enc=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conv2dSubsampling:
"""Convolutional 2D subsampling (to 1/4 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer."""
def __init__(self, idim, odim, dropout_rate, pos_enc=None):
"""Con... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transformer/subsampling.py | espnet/espnet | train | 7,242 |
8330a4bfea177d657c992e789822f66b79aef722 | [
"if not self.user:\n raise Exception('self.user is required')\nif not self.facebook_id:\n raise Exception('self.facebook_id is required')\nif not self.name:\n raise Exception('self.name is required')",
"self._validate_attrs()\ntry:\n self.save()\n return self\nexcept Exception:\n return None"
] | <|body_start_0|>
if not self.user:
raise Exception('self.user is required')
if not self.facebook_id:
raise Exception('self.facebook_id is required')
if not self.name:
raise Exception('self.name is required')
<|end_body_0|>
<|body_start_1|>
self._valid... | FacebookModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FacebookModel:
def _validate_attrs(self):
"""Validates required attributes"""
<|body_0|>
def parse_and_save(self):
"""save if it doesnt exist"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.user:
raise Exception('self.user is... | stack_v2_sparse_classes_36k_train_001323 | 1,931 | no_license | [
{
"docstring": "Validates required attributes",
"name": "_validate_attrs",
"signature": "def _validate_attrs(self)"
},
{
"docstring": "save if it doesnt exist",
"name": "parse_and_save",
"signature": "def parse_and_save(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015503 | Implement the Python class `FacebookModel` described below.
Class description:
Implement the FacebookModel class.
Method signatures and docstrings:
- def _validate_attrs(self): Validates required attributes
- def parse_and_save(self): save if it doesnt exist | Implement the Python class `FacebookModel` described below.
Class description:
Implement the FacebookModel class.
Method signatures and docstrings:
- def _validate_attrs(self): Validates required attributes
- def parse_and_save(self): save if it doesnt exist
<|skeleton|>
class FacebookModel:
def _validate_attrs... | 3c6f741e0d74f51bc85f7b73c8b188f2a726a7e6 | <|skeleton|>
class FacebookModel:
def _validate_attrs(self):
"""Validates required attributes"""
<|body_0|>
def parse_and_save(self):
"""save if it doesnt exist"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FacebookModel:
def _validate_attrs(self):
"""Validates required attributes"""
if not self.user:
raise Exception('self.user is required')
if not self.facebook_id:
raise Exception('self.facebook_id is required')
if not self.name:
raise Exceptio... | the_stack_v2_python_sparse | estagiario/apps/social_user/models/fb_model.py | pedromarins/estagiario | train | 0 | |
dbf4c6bb8984a5fb75df28f25a3c3cdad35c4ce1 | [
"super(Vgg16, self).__init__(name=name)\nself._output_size = output_size\nself._hidden_channels = [64, 64, 128, 128, 128, 256, 256, 256, 512, 512, 512]\nself._num_layers = len(self._hidden_channels)\nself._kernel_shapes = [[3, 3]] * self._num_layers\nself._strides = [1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1]\nself._paddings... | <|body_start_0|>
super(Vgg16, self).__init__(name=name)
self._output_size = output_size
self._hidden_channels = [64, 64, 128, 128, 128, 256, 256, 256, 512, 512, 512]
self._num_layers = len(self._hidden_channels)
self._kernel_shapes = [[3, 3]] * self._num_layers
self._stri... | Vgg16 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vgg16:
def __init__(self, output_size, name='vgg16', activation=tf.nn.relu, **extra_params):
"""Args: num_outputs (type): number of outputs of the module. name (type): module name. activation (type): activation used for the internal layers. **extra_params (type): alls the additional keyw... | stack_v2_sparse_classes_36k_train_001324 | 48,282 | permissive | [
{
"docstring": "Args: num_outputs (type): number of outputs of the module. name (type): module name. activation (type): activation used for the internal layers. **extra_params (type): alls the additional keyword arguments will be passed to the snt.Conv2D layers.",
"name": "__init__",
"signature": "def _... | 2 | stack_v2_sparse_classes_30k_train_015444 | Implement the Python class `Vgg16` described below.
Class description:
Implement the Vgg16 class.
Method signatures and docstrings:
- def __init__(self, output_size, name='vgg16', activation=tf.nn.relu, **extra_params): Args: num_outputs (type): number of outputs of the module. name (type): module name. activation (t... | Implement the Python class `Vgg16` described below.
Class description:
Implement the Vgg16 class.
Method signatures and docstrings:
- def __init__(self, output_size, name='vgg16', activation=tf.nn.relu, **extra_params): Args: num_outputs (type): number of outputs of the module. name (type): module name. activation (t... | a10c33346803239db8a64c104db7f22ec4e05bef | <|skeleton|>
class Vgg16:
def __init__(self, output_size, name='vgg16', activation=tf.nn.relu, **extra_params):
"""Args: num_outputs (type): number of outputs of the module. name (type): module name. activation (type): activation used for the internal layers. **extra_params (type): alls the additional keyw... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vgg16:
def __init__(self, output_size, name='vgg16', activation=tf.nn.relu, **extra_params):
"""Args: num_outputs (type): number of outputs of the module. name (type): module name. activation (type): activation used for the internal layers. **extra_params (type): alls the additional keyword arguments ... | the_stack_v2_python_sparse | argo/core/utils/utils_modules.py | ricvo/argo | train | 0 | |
8bf7683b7b932457dc1d9220b19b13db35f5354b | [
"l = len(gas)\nindex_list = []\nfor i in range(l):\n if gas[i] < cost[i]:\n continue\n g = gas[i] + gas[(i + 1) % l] - cost[i] - cost[(i + 1) % l]\n if g > 0:\n index_list.append(i)\nif len(index_list) == 0:\n return -1\nng = 0\nfor index in index_list:\n for i in range(index, l + index... | <|body_start_0|>
l = len(gas)
index_list = []
for i in range(l):
if gas[i] < cost[i]:
continue
g = gas[i] + gas[(i + 1) % l] - cost[i] - cost[(i + 1) % l]
if g > 0:
index_list.append(i)
if len(index_list) == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit2(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_001325 | 2,544 | no_license | [
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit",
"signature": "def canCompleteCircuit(self, gas, cost)"
},
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit2",
"signature": "def canCo... | 2 | stack_v2_sparse_classes_30k_train_012703 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit2(self, gas, cost): :type gas: List[int] :type cost: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit2(self, gas, cost): :type gas: List[int] :type cost: List[... | 4c395a31e627b6096a601b9e30f82073ddc9b02b | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit2(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
l = len(gas)
index_list = []
for i in range(l):
if gas[i] < cost[i]:
continue
g = gas[i] + gas[(i + 1) % l] - cost[i] - cost[(... | the_stack_v2_python_sparse | leetcode/medium/Gas_Station.py | xiangzz159/Python-Study | train | 0 | |
542738865fd41683e7ba3231bf9954c3927a2d91 | [
"test_tuples = [(1, 1, '1')]\nfor n, k, expected in test_tuples:\n self.assertEqual(self.solver.getPermutation(n, k), expected)",
"test_tuples = [(2, 1, '12'), (2, 2, '21')]\nfor n, k, expected in test_tuples:\n self.assertEqual(self.solver.getPermutation(n, k), expected)",
"test_tuples = [(3, 1, '123'), ... | <|body_start_0|>
test_tuples = [(1, 1, '1')]
for n, k, expected in test_tuples:
self.assertEqual(self.solver.getPermutation(n, k), expected)
<|end_body_0|>
<|body_start_1|>
test_tuples = [(2, 1, '12'), (2, 2, '21')]
for n, k, expected in test_tuples:
self.assertE... | TestPermutationSequence | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPermutationSequence:
def test_permutations_1(self):
"""it should return the kth permutation of 1 number"""
<|body_0|>
def test_permutations_2(self):
"""it should return the kth permutation of 2 numbers"""
<|body_1|>
def test_permutations_3(self):
... | stack_v2_sparse_classes_36k_train_001326 | 1,159 | no_license | [
{
"docstring": "it should return the kth permutation of 1 number",
"name": "test_permutations_1",
"signature": "def test_permutations_1(self)"
},
{
"docstring": "it should return the kth permutation of 2 numbers",
"name": "test_permutations_2",
"signature": "def test_permutations_2(self)... | 3 | stack_v2_sparse_classes_30k_train_010273 | Implement the Python class `TestPermutationSequence` described below.
Class description:
Implement the TestPermutationSequence class.
Method signatures and docstrings:
- def test_permutations_1(self): it should return the kth permutation of 1 number
- def test_permutations_2(self): it should return the kth permutatio... | Implement the Python class `TestPermutationSequence` described below.
Class description:
Implement the TestPermutationSequence class.
Method signatures and docstrings:
- def test_permutations_1(self): it should return the kth permutation of 1 number
- def test_permutations_2(self): it should return the kth permutatio... | 3e810afed2a7872ac9ad4c35f1caf81965641cfe | <|skeleton|>
class TestPermutationSequence:
def test_permutations_1(self):
"""it should return the kth permutation of 1 number"""
<|body_0|>
def test_permutations_2(self):
"""it should return the kth permutation of 2 numbers"""
<|body_1|>
def test_permutations_3(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPermutationSequence:
def test_permutations_1(self):
"""it should return the kth permutation of 1 number"""
test_tuples = [(1, 1, '1')]
for n, k, expected in test_tuples:
self.assertEqual(self.solver.getPermutation(n, k), expected)
def test_permutations_2(self):
... | the_stack_v2_python_sparse | numericalMethods/permutationSequence/test.py | JamesShoaf/AlgorithmPractice | train | 1 | |
0ba84e03548de0d6a0ad143431b2f3dab44fde45 | [
"self._signal_fraction = 0.056\nself._nd_fractions = {'150Nd2v': 0.056, '144Nd': 0.238, '176Lu': 1.2e-07, '138La': 5e-07, '147Sm': 5e-07, '148Sm': 5e-07, '227Ac': 1e-18, '235U': 5e-11, '238U': 1e-15, '232Th': 1e-14}\nself._scint_fractions = {'14C': 1e-18, '40K': 1.3e-18, '39Ar': 2.75e-24, '85Kr': 2.4e-25, '238U': 1... | <|body_start_0|>
self._signal_fraction = 0.056
self._nd_fractions = {'150Nd2v': 0.056, '144Nd': 0.238, '176Lu': 1.2e-07, '138La': 5e-07, '147Sm': 5e-07, '148Sm': 5e-07, '227Ac': 1e-18, '235U': 5e-11, '238U': 1e-15, '232Th': 1e-14}
self._scint_fractions = {'14C': 1e-18, '40K': 1.3e-18, '39Ar': 2.... | Generates a full raw data set for Nd loaded scintillator. | NdDataGen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NdDataGen:
"""Generates a full raw data set for Nd loaded scintillator."""
def __init__(self, scint_mass, loading):
"""Initialise the target fractions dict, etc..."""
<|body_0|>
def set_scint_fraction(self, isotope, fraction):
"""Set the fraction of an isotope in... | stack_v2_sparse_classes_36k_train_001327 | 4,196 | no_license | [
{
"docstring": "Initialise the target fractions dict, etc...",
"name": "__init__",
"signature": "def __init__(self, scint_mass, loading)"
},
{
"docstring": "Set the fraction of an isotope in the scintillator.",
"name": "set_scint_fraction",
"signature": "def set_scint_fraction(self, isot... | 4 | stack_v2_sparse_classes_30k_train_002794 | Implement the Python class `NdDataGen` described below.
Class description:
Generates a full raw data set for Nd loaded scintillator.
Method signatures and docstrings:
- def __init__(self, scint_mass, loading): Initialise the target fractions dict, etc...
- def set_scint_fraction(self, isotope, fraction): Set the frac... | Implement the Python class `NdDataGen` described below.
Class description:
Generates a full raw data set for Nd loaded scintillator.
Method signatures and docstrings:
- def __init__(self, scint_mass, loading): Initialise the target fractions dict, etc...
- def set_scint_fraction(self, isotope, fraction): Set the frac... | 5e7c0a1b9857688b6d141f7d6bcf6985d0c10833 | <|skeleton|>
class NdDataGen:
"""Generates a full raw data set for Nd loaded scintillator."""
def __init__(self, scint_mass, loading):
"""Initialise the target fractions dict, etc..."""
<|body_0|>
def set_scint_fraction(self, isotope, fraction):
"""Set the fraction of an isotope in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NdDataGen:
"""Generates a full raw data set for Nd loaded scintillator."""
def __init__(self, scint_mass, loading):
"""Initialise the target fractions dict, etc..."""
self._signal_fraction = 0.056
self._nd_fractions = {'150Nd2v': 0.056, '144Nd': 0.238, '176Lu': 1.2e-07, '138La': 5... | the_stack_v2_python_sparse | src/generators/nd_data_gen.py | pgjones/snopy | train | 1 |
5d9aaa0422098bfa6a3c9002460492d59000f002 | [
"if type(multipliers) is list:\n assert len(multipliers[0]) % 3 == 0\n assert len(multipliers) == 2\n self.n = int(len(multipliers[0]) // 3)\n assert binom(self.n, 2) == len(multipliers[1]), 'Wrong number of couplings.'\n multipliers = np.concatenate(multipliers)\nelse:\n assert type(multipliers) ... | <|body_start_0|>
if type(multipliers) is list:
assert len(multipliers[0]) % 3 == 0
assert len(multipliers) == 2
self.n = int(len(multipliers[0]) // 3)
assert binom(self.n, 2) == len(multipliers[1]), 'Wrong number of couplings.'
multipliers = np.concate... | Three-state spin model constraining means and pairwise correlations. | Potts3 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Potts3:
"""Three-state spin model constraining means and pairwise correlations."""
def __init__(self, multipliers, rng=None, n_cpus=None, verbose=False):
"""Parameters ---------- multipliers : list of ndarray Can be a list of vectors [fields, couplings]."""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_001328 | 12,395 | permissive | [
{
"docstring": "Parameters ---------- multipliers : list of ndarray Can be a list of vectors [fields, couplings].",
"name": "__init__",
"signature": "def __init__(self, multipliers, rng=None, n_cpus=None, verbose=False)"
},
{
"docstring": "Set multipliers to a new value. Need to redefine some fu... | 2 | stack_v2_sparse_classes_30k_train_020191 | Implement the Python class `Potts3` described below.
Class description:
Three-state spin model constraining means and pairwise correlations.
Method signatures and docstrings:
- def __init__(self, multipliers, rng=None, n_cpus=None, verbose=False): Parameters ---------- multipliers : list of ndarray Can be a list of v... | Implement the Python class `Potts3` described below.
Class description:
Three-state spin model constraining means and pairwise correlations.
Method signatures and docstrings:
- def __init__(self, multipliers, rng=None, n_cpus=None, verbose=False): Parameters ---------- multipliers : list of ndarray Can be a list of v... | f25863705f8e459771ef60ea51c4bd6587904c78 | <|skeleton|>
class Potts3:
"""Three-state spin model constraining means and pairwise correlations."""
def __init__(self, multipliers, rng=None, n_cpus=None, verbose=False):
"""Parameters ---------- multipliers : list of ndarray Can be a list of vectors [fields, couplings]."""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Potts3:
"""Three-state spin model constraining means and pairwise correlations."""
def __init__(self, multipliers, rng=None, n_cpus=None, verbose=False):
"""Parameters ---------- multipliers : list of ndarray Can be a list of vectors [fields, couplings]."""
if type(multipliers) is list:
... | the_stack_v2_python_sparse | coniii/models.py | eltrompetero/coniii | train | 18 |
8def01fb848c51ca717c6725ca0ca466e169e915 | [
"fixture = [('C:\\\\Program Files\\\\Realtek\\\\Audio\\\\blah.exe -s', 'C:\\\\Program Files\\\\Realtek\\\\Audio\\\\blah.exe'), (\"'C:\\\\Program Files\\\\Realtek\\\\Audio\\\\blah.exe' -s\", 'C:\\\\Program Files\\\\Realtek\\\\Audio\\\\blah.exe'), ('C:\\\\Program Files\\\\NVIDIA Corporation\\\\nwiz.exe /quiet /blah',... | <|body_start_0|>
fixture = [('C:\\Program Files\\Realtek\\Audio\\blah.exe -s', 'C:\\Program Files\\Realtek\\Audio\\blah.exe'), ("'C:\\Program Files\\Realtek\\Audio\\blah.exe' -s", 'C:\\Program Files\\Realtek\\Audio\\blah.exe'), ('C:\\Program Files\\NVIDIA Corporation\\nwiz.exe /quiet /blah', 'C:\\Program Files\... | Tests for CreateWindowsRegistryExecutablePathsDetector() detector. | WindowsRegistryExecutablePathsDetectorTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindowsRegistryExecutablePathsDetectorTest:
"""Tests for CreateWindowsRegistryExecutablePathsDetector() detector."""
def testExtractsPathsFromNonRunDllStrings(self):
"""Test it extracts paths from non-rundll strings."""
<|body_0|>
def testExctactsPathsFromRunDllStrings(s... | stack_v2_sparse_classes_36k_train_001329 | 8,407 | permissive | [
{
"docstring": "Test it extracts paths from non-rundll strings.",
"name": "testExtractsPathsFromNonRunDllStrings",
"signature": "def testExtractsPathsFromNonRunDllStrings(self)"
},
{
"docstring": "Test it extracts paths from rundll strings.",
"name": "testExctactsPathsFromRunDllStrings",
... | 4 | stack_v2_sparse_classes_30k_train_007497 | Implement the Python class `WindowsRegistryExecutablePathsDetectorTest` described below.
Class description:
Tests for CreateWindowsRegistryExecutablePathsDetector() detector.
Method signatures and docstrings:
- def testExtractsPathsFromNonRunDllStrings(self): Test it extracts paths from non-rundll strings.
- def test... | Implement the Python class `WindowsRegistryExecutablePathsDetectorTest` described below.
Class description:
Tests for CreateWindowsRegistryExecutablePathsDetector() detector.
Method signatures and docstrings:
- def testExtractsPathsFromNonRunDllStrings(self): Test it extracts paths from non-rundll strings.
- def test... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class WindowsRegistryExecutablePathsDetectorTest:
"""Tests for CreateWindowsRegistryExecutablePathsDetector() detector."""
def testExtractsPathsFromNonRunDllStrings(self):
"""Test it extracts paths from non-rundll strings."""
<|body_0|>
def testExctactsPathsFromRunDllStrings(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WindowsRegistryExecutablePathsDetectorTest:
"""Tests for CreateWindowsRegistryExecutablePathsDetector() detector."""
def testExtractsPathsFromNonRunDllStrings(self):
"""Test it extracts paths from non-rundll strings."""
fixture = [('C:\\Program Files\\Realtek\\Audio\\blah.exe -s', 'C:\\Pr... | the_stack_v2_python_sparse | grr/core/grr_response_core/path_detection/windows_test.py | google/grr | train | 4,683 |
a2367671900f7143df73031b193cf75f010b3ade | [
"try:\n user_details = User.objects.get(username=username)\n user_following_data = get_user_following_data(user_details)\n return Response({'message': get_followers_found_message(username), 'following': user_following_data['following'], 'followers': user_following_data['followers'], 'followingCount': user_... | <|body_start_0|>
try:
user_details = User.objects.get(username=username)
user_following_data = get_user_following_data(user_details)
return Response({'message': get_followers_found_message(username), 'following': user_following_data['following'], 'followers': user_following_d... | A view that allows users to follow each other if the user is authenticated and verified. | ProfileFollowUserAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileFollowUserAPIView:
"""A view that allows users to follow each other if the user is authenticated and verified."""
def get(self, request, username):
"""View to return a users following i.e followers and those they are following. Params ------- request: Object with request data ... | stack_v2_sparse_classes_36k_train_001330 | 11,549 | permissive | [
{
"docstring": "View to return a users following i.e followers and those they are following. Params ------- request: Object with request data and functions. username: String providing the user to follow. Returns -------- Response object: { \"message\": \"message body\", \"following\": List, \"followers\": List,... | 3 | stack_v2_sparse_classes_30k_train_000474 | Implement the Python class `ProfileFollowUserAPIView` described below.
Class description:
A view that allows users to follow each other if the user is authenticated and verified.
Method signatures and docstrings:
- def get(self, request, username): View to return a users following i.e followers and those they are fol... | Implement the Python class `ProfileFollowUserAPIView` described below.
Class description:
A view that allows users to follow each other if the user is authenticated and verified.
Method signatures and docstrings:
- def get(self, request, username): View to return a users following i.e followers and those they are fol... | 5a31840856de4b361fe2594dfa7a33d7774d3fe2 | <|skeleton|>
class ProfileFollowUserAPIView:
"""A view that allows users to follow each other if the user is authenticated and verified."""
def get(self, request, username):
"""View to return a users following i.e followers and those they are following. Params ------- request: Object with request data ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileFollowUserAPIView:
"""A view that allows users to follow each other if the user is authenticated and verified."""
def get(self, request, username):
"""View to return a users following i.e followers and those they are following. Params ------- request: Object with request data and functions... | the_stack_v2_python_sparse | authors/apps/profiles/views.py | bl4ck4ndbr0wn/ah-centauri-backend | train | 0 |
3db427bc4e54fae296e6d7dc252b4bb05b8fa09b | [
"name = 'RandomSampling'\nsuper(RandomSampling, self).__init__(name, xmin, xmax, use_logger)\nif self.use_logger:\n self.logger = ml.SciopeLogger().get_logger()\n self.logger.info('Random design in {0} dimensions initialized'.format(len(self.xmin)))",
"num_variables = len(self.xmin)\nx = np.random.rand(n, n... | <|body_start_0|>
name = 'RandomSampling'
super(RandomSampling, self).__init__(name, xmin, xmax, use_logger)
if self.use_logger:
self.logger = ml.SciopeLogger().get_logger()
self.logger.info('Random design in {0} dimensions initialized'.format(len(self.xmin)))
<|end_body_0... | Random Sampling implemented through gpflowopt Properties/variables: * name (RandomSampling) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated points) * logger (a logging object to display/save events - set by derived class... | RandomSampling | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomSampling:
"""Random Sampling implemented through gpflowopt Properties/variables: * name (RandomSampling) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated points) * logger (a logging object to ... | stack_v2_sparse_classes_36k_train_001331 | 2,961 | permissive | [
{
"docstring": "[summary] Parameters ---------- xmin : vector or 1D array Specifies the lower bound of the hypercube within which the design is generated xmax : vector or 1D array Specifies the upper bound of the hypercube within which the design is generated use_logger : bool, optional controls whether logging... | 2 | stack_v2_sparse_classes_30k_train_016648 | Implement the Python class `RandomSampling` described below.
Class description:
Random Sampling implemented through gpflowopt Properties/variables: * name (RandomSampling) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated... | Implement the Python class `RandomSampling` described below.
Class description:
Random Sampling implemented through gpflowopt Properties/variables: * name (RandomSampling) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated... | 5122107dedcee9c39458e83d853ec35f91268780 | <|skeleton|>
class RandomSampling:
"""Random Sampling implemented through gpflowopt Properties/variables: * name (RandomSampling) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated points) * logger (a logging object to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomSampling:
"""Random Sampling implemented through gpflowopt Properties/variables: * name (RandomSampling) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated points) * logger (a logging object to display/save ... | the_stack_v2_python_sparse | sciope/designs/random_sampling.py | rmjiang7/sciope | train | 0 |
d4ec8f8729eecd0b281f940eee5246c88529ae16 | [
"stk = collections.deque()\nret = ''\nwhile root is not None or len(stk):\n if root is not None:\n ret += ',' + str(root.val) + ':' + str(len(root.children))\n if len(root.children):\n stk.append([root, 1])\n root = root.children[0]\n else:\n root = None\n ... | <|body_start_0|>
stk = collections.deque()
ret = ''
while root is not None or len(stk):
if root is not None:
ret += ',' + str(root.val) + ':' + str(len(root.children))
if len(root.children):
stk.append([root, 1])
... | Codec2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec2:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_001332 | 4,629 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def deserialize(self, ... | 2 | null | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: N... | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: N... | 9190d3d178f1733aa226973757ee7e045b7bab00 | <|skeleton|>
class Codec2:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec2:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
stk = collections.deque()
ret = ''
while root is not None or len(stk):
if root is not None:
ret += ',' + str(root.val) + ':' + str(len(root.child... | the_stack_v2_python_sparse | SerializeAndDeserializeN-aryTree.py | ellinx/LC-python | train | 1 | |
2957dce908b37f3c6b41a108522b9a04f00df5fc | [
"self.python_worktree = python_worktree\nself.root = python_worktree.worktree.root\nself.pytest_path = str()\nself.python_path = str()\nself.projects = list()\nself.tests_path = list()\nvenv_path = python_worktree.venv_path\nif venv_path:\n self.pytest_path = qipy.venv.find_script(venv_path, 'py.test')\nelse:\n ... | <|body_start_0|>
self.python_worktree = python_worktree
self.root = python_worktree.worktree.root
self.pytest_path = str()
self.python_path = str()
self.projects = list()
self.tests_path = list()
venv_path = python_worktree.venv_path
if venv_path:
... | PythonTestCollector | PythonTestCollector | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PythonTestCollector:
"""PythonTestCollector"""
def __init__(self, python_worktree):
"""PythonTestCollector Init"""
<|body_0|>
def get_list_of_pytest(rep):
"""Get List of PyTest"""
<|body_1|>
def create_pytest_json(self, json_path, pytest_list, projec... | stack_v2_sparse_classes_36k_train_001333 | 3,424 | permissive | [
{
"docstring": "PythonTestCollector Init",
"name": "__init__",
"signature": "def __init__(self, python_worktree)"
},
{
"docstring": "Get List of PyTest",
"name": "get_list_of_pytest",
"signature": "def get_list_of_pytest(rep)"
},
{
"docstring": "Create PyTest JSON",
"name": "... | 5 | stack_v2_sparse_classes_30k_val_001007 | Implement the Python class `PythonTestCollector` described below.
Class description:
PythonTestCollector
Method signatures and docstrings:
- def __init__(self, python_worktree): PythonTestCollector Init
- def get_list_of_pytest(rep): Get List of PyTest
- def create_pytest_json(self, json_path, pytest_list, project): ... | Implement the Python class `PythonTestCollector` described below.
Class description:
PythonTestCollector
Method signatures and docstrings:
- def __init__(self, python_worktree): PythonTestCollector Init
- def get_list_of_pytest(rep): Get List of PyTest
- def create_pytest_json(self, json_path, pytest_list, project): ... | efea6fa3744664348717fe5e8df708a3cf392072 | <|skeleton|>
class PythonTestCollector:
"""PythonTestCollector"""
def __init__(self, python_worktree):
"""PythonTestCollector Init"""
<|body_0|>
def get_list_of_pytest(rep):
"""Get List of PyTest"""
<|body_1|>
def create_pytest_json(self, json_path, pytest_list, projec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PythonTestCollector:
"""PythonTestCollector"""
def __init__(self, python_worktree):
"""PythonTestCollector Init"""
self.python_worktree = python_worktree
self.root = python_worktree.worktree.root
self.pytest_path = str()
self.python_path = str()
self.projec... | the_stack_v2_python_sparse | python/qitest/collector.py | aldebaran/qibuild | train | 60 |
b635424293149346fe8bfa02ee35698d6dbbfa4f | [
"self.db = ConnectionDB.ConnectionDB(jobname)\nself.collection = 'models'\nself.jobname = jobname",
"try:\n latest_model = self.db.get_lastest_entity(collection=self.collection)\n model = latest_model['model']\n return pickle.loads(model)\nexcept Exception as e:\n logger.exception(e)",
"try:\n pi... | <|body_start_0|>
self.db = ConnectionDB.ConnectionDB(jobname)
self.collection = 'models'
self.jobname = jobname
<|end_body_0|>
<|body_start_1|>
try:
latest_model = self.db.get_lastest_entity(collection=self.collection)
model = latest_model['model']
re... | ModelDB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelDB:
def __init__(self, jobname):
"""Init Gets connection with the database"""
<|body_0|>
def get_last_model(self):
"""Loads from the database collection the latest model The model is unpickled before returning :return: the latest model"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_001334 | 1,512 | no_license | [
{
"docstring": "Init Gets connection with the database",
"name": "__init__",
"signature": "def __init__(self, jobname)"
},
{
"docstring": "Loads from the database collection the latest model The model is unpickled before returning :return: the latest model",
"name": "get_last_model",
"si... | 3 | stack_v2_sparse_classes_30k_train_013465 | Implement the Python class `ModelDB` described below.
Class description:
Implement the ModelDB class.
Method signatures and docstrings:
- def __init__(self, jobname): Init Gets connection with the database
- def get_last_model(self): Loads from the database collection the latest model The model is unpickled before re... | Implement the Python class `ModelDB` described below.
Class description:
Implement the ModelDB class.
Method signatures and docstrings:
- def __init__(self, jobname): Init Gets connection with the database
- def get_last_model(self): Loads from the database collection the latest model The model is unpickled before re... | 9f8731d746aeb971267f210bccfebb5bec30927d | <|skeleton|>
class ModelDB:
def __init__(self, jobname):
"""Init Gets connection with the database"""
<|body_0|>
def get_last_model(self):
"""Loads from the database collection the latest model The model is unpickled before returning :return: the latest model"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelDB:
def __init__(self, jobname):
"""Init Gets connection with the database"""
self.db = ConnectionDB.ConnectionDB(jobname)
self.collection = 'models'
self.jobname = jobname
def get_last_model(self):
"""Loads from the database collection the latest model The mo... | the_stack_v2_python_sparse | optace-backend/Database/ModelDB.py | davidissamattos/OptACE | train | 0 | |
fced14c5b2e955582adc849d7c06ea7e5dc014d8 | [
"if Singleton.__instance == None:\n Singleton()\nreturn Singleton.__instance",
"if Singleton.__instance != None:\n raise Exception('This class is a singleton!')\nelse:\n Singleton.__instance = self\n embeddingFile = '/home/owner/PhD/dr.norbert/dataset/shorttext/glove.42B.300d/glove.42B.300d.txt'\n ... | <|body_start_0|>
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
<|end_body_0|>
<|body_start_1|>
if Singleton.__instance != None:
raise Exception('This class is a singleton!')
else:
Singleton.__instance = self
embe... | Singleton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Singleton:
def getInstance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if Singleton.__instance == None:
Singleton()
return Single... | stack_v2_sparse_classes_36k_train_001335 | 1,386 | no_license | [
{
"docstring": "Static access method.",
"name": "getInstance",
"signature": "def getInstance()"
},
{
"docstring": "Virtually private constructor.",
"name": "__init__",
"signature": "def __init__(self)"
}
] | 2 | null | Implement the Python class `Singleton` described below.
Class description:
Implement the Singleton class.
Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self): Virtually private constructor. | Implement the Python class `Singleton` described below.
Class description:
Implement the Singleton class.
Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self): Virtually private constructor.
<|skeleton|>
class Singleton:
def getInstance():
"""Static access me... | f7600a3501064000ddfd849653c7b36f5cc742f7 | <|skeleton|>
class Singleton:
def getInstance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Singleton:
def getInstance():
"""Static access method."""
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
def __init__(self):
"""Virtually private constructor."""
if Singleton.__instance != None:
raise Exception('Thi... | the_stack_v2_python_sparse | BatchClustering/CacheEmbeddings.py | rashadulrakib/short-text-stream-clustering | train | 7 | |
6364968a8d0c1cb2c18f1c467261b272386e1e38 | [
"if request.version != 'v1':\n return Response(status=status.HTTP_505_HTTP_VERSION_NOT_SUPPORTED)\nserializer = SearchNotRequiredSerializer(data={'service': 'all', 'types': 'coming_soon'}, context={'request': request, 'kwargs': kwargs})\nserializer.is_valid(raise_exception=True)\nreturn Response(data=serializer.... | <|body_start_0|>
if request.version != 'v1':
return Response(status=status.HTTP_505_HTTP_VERSION_NOT_SUPPORTED)
serializer = SearchNotRequiredSerializer(data={'service': 'all', 'types': 'coming_soon'}, context={'request': request, 'kwargs': kwargs})
serializer.is_valid(raise_exceptio... | Releases view. | ReleasesView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReleasesView:
"""Releases view."""
def get(self, request, *args, **kwargs):
"""GET request"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""POST request."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if request.version != 'v1':
... | stack_v2_sparse_classes_36k_train_001336 | 12,742 | no_license | [
{
"docstring": "GET request",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "POST request.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002983 | Implement the Python class `ReleasesView` described below.
Class description:
Releases view.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): GET request
- def post(self, request, *args, **kwargs): POST request. | Implement the Python class `ReleasesView` described below.
Class description:
Releases view.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): GET request
- def post(self, request, *args, **kwargs): POST request.
<|skeleton|>
class ReleasesView:
"""Releases view."""
def get(self, ... | cd8767b5eeaef3a09d77c936781b4126fd8591de | <|skeleton|>
class ReleasesView:
"""Releases view."""
def get(self, request, *args, **kwargs):
"""GET request"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""POST request."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReleasesView:
"""Releases view."""
def get(self, request, *args, **kwargs):
"""GET request"""
if request.version != 'v1':
return Response(status=status.HTTP_505_HTTP_VERSION_NOT_SUPPORTED)
serializer = SearchNotRequiredSerializer(data={'service': 'all', 'types': 'comin... | the_stack_v2_python_sparse | api/services/views.py | ignite7/backproject | train | 0 |
1418815a0fadb068c2e60d2c558cbec7b5427438 | [
"instance = self.get_object()\ninstance.hit_count = instance.hit_count + 1\ninstance.save()\nreturn redirect(instance.url)",
"serializer = self.get_serializer(data=request.data)\nif serializer.is_valid(raise_exception=True):\n instance = serializer.save()\n headers = self.get_success_headers(serializer.data... | <|body_start_0|>
instance = self.get_object()
instance.hit_count = instance.hit_count + 1
instance.save()
return redirect(instance.url)
<|end_body_0|>
<|body_start_1|>
serializer = self.get_serializer(data=request.data)
if serializer.is_valid(raise_exception=True):
... | Uses a ModelViewSet to minimize code into one location | URLViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class URLViewSet:
"""Uses a ModelViewSet to minimize code into one location"""
def retrieve(self, request, *args, **kwargs):
"""Custom retrieve method increments hit_count by 1 every time its called and redirects user to longer url"""
<|body_0|>
def create(self, request, *args... | stack_v2_sparse_classes_36k_train_001337 | 1,354 | no_license | [
{
"docstring": "Custom retrieve method increments hit_count by 1 every time its called and redirects user to longer url",
"name": "retrieve",
"signature": "def retrieve(self, request, *args, **kwargs)"
},
{
"docstring": "Custom create method to return the total short url, as per the instructions... | 2 | stack_v2_sparse_classes_30k_train_014841 | Implement the Python class `URLViewSet` described below.
Class description:
Uses a ModelViewSet to minimize code into one location
Method signatures and docstrings:
- def retrieve(self, request, *args, **kwargs): Custom retrieve method increments hit_count by 1 every time its called and redirects user to longer url
-... | Implement the Python class `URLViewSet` described below.
Class description:
Uses a ModelViewSet to minimize code into one location
Method signatures and docstrings:
- def retrieve(self, request, *args, **kwargs): Custom retrieve method increments hit_count by 1 every time its called and redirects user to longer url
-... | 8148b216f053e0bcae2e3fe6b0f86ac88d6f8823 | <|skeleton|>
class URLViewSet:
"""Uses a ModelViewSet to minimize code into one location"""
def retrieve(self, request, *args, **kwargs):
"""Custom retrieve method increments hit_count by 1 every time its called and redirects user to longer url"""
<|body_0|>
def create(self, request, *args... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class URLViewSet:
"""Uses a ModelViewSet to minimize code into one location"""
def retrieve(self, request, *args, **kwargs):
"""Custom retrieve method increments hit_count by 1 every time its called and redirects user to longer url"""
instance = self.get_object()
instance.hit_count = in... | the_stack_v2_python_sparse | shortener/views.py | thesabermaniac/ShortURL | train | 0 |
db1c45859152c75f31452876f0b307639f78202a | [
"tmp_sum = 0\npieces = 1\nfor num in arr:\n if tmp_sum + num > largestSum:\n pieces += 1\n tmp_sum = num\n else:\n tmp_sum += num\nreturn pieces",
"lo = max(nums)\nhi = sum(nums)\nwhile lo < hi:\n mid = lo + (hi - lo) / 2\n pieces = self.split(nums, largestSum=mid)\n if pieces ... | <|body_start_0|>
tmp_sum = 0
pieces = 1
for num in arr:
if tmp_sum + num > largestSum:
pieces += 1
tmp_sum = num
else:
tmp_sum += num
return pieces
<|end_body_0|>
<|body_start_1|>
lo = max(nums)
hi =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def split(self, arr, largestSum):
"""Tells the no. of possible pieces which can make num same as largestSum"""
<|body_0|>
def splitArray(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_001338 | 1,421 | no_license | [
{
"docstring": "Tells the no. of possible pieces which can make num same as largestSum",
"name": "split",
"signature": "def split(self, arr, largestSum)"
},
{
"docstring": ":type nums: List[int] :type m: int :rtype: int",
"name": "splitArray",
"signature": "def splitArray(self, nums, m)"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def split(self, arr, largestSum): Tells the no. of possible pieces which can make num same as largestSum
- def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtyp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def split(self, arr, largestSum): Tells the no. of possible pieces which can make num same as largestSum
- def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtyp... | 877933424e6d2c590d6ac53db18bee951a3d9de4 | <|skeleton|>
class Solution:
def split(self, arr, largestSum):
"""Tells the no. of possible pieces which can make num same as largestSum"""
<|body_0|>
def splitArray(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def split(self, arr, largestSum):
"""Tells the no. of possible pieces which can make num same as largestSum"""
tmp_sum = 0
pieces = 1
for num in arr:
if tmp_sum + num > largestSum:
pieces += 1
tmp_sum = num
else:... | the_stack_v2_python_sparse | leetcode/410.split-array-largest-sum.py | siddhism/leetcode | train | 0 | |
2bec2467868a6ea19ba8b4692674e90015e600bc | [
"self.api_group = api_group\nself.api_version = api_version\nself.kind = kind\nself.name = name\nself.namespace = namespace\nself.resource_version = resource_version\nself.uid = uid",
"if dictionary is None:\n return None\napi_group = dictionary.get('apiGroup')\napi_version = dictionary.get('apiVersion')\nkind... | <|body_start_0|>
self.api_group = api_group
self.api_version = api_version
self.kind = kind
self.name = name
self.namespace = namespace
self.resource_version = resource_version
self.uid = uid
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'ObjectReference' model. ObjectReference contains enough information to let you inspect or modify the referred object. Attributes: api_group (string): API group make it easier to extend the Kubernetes API. The API group is specified in a REST path and in the apiVersion field. api_version (string):... | ObjectReference | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectReference:
"""Implementation of the 'ObjectReference' model. ObjectReference contains enough information to let you inspect or modify the referred object. Attributes: api_group (string): API group make it easier to extend the Kubernetes API. The API group is specified in a REST path and in ... | stack_v2_sparse_classes_36k_train_001339 | 3,170 | permissive | [
{
"docstring": "Constructor for the ObjectReference class",
"name": "__init__",
"signature": "def __init__(self, api_group=None, api_version=None, kind=None, name=None, namespace=None, resource_version=None, uid=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: ... | 2 | stack_v2_sparse_classes_30k_train_001127 | Implement the Python class `ObjectReference` described below.
Class description:
Implementation of the 'ObjectReference' model. ObjectReference contains enough information to let you inspect or modify the referred object. Attributes: api_group (string): API group make it easier to extend the Kubernetes API. The API gr... | Implement the Python class `ObjectReference` described below.
Class description:
Implementation of the 'ObjectReference' model. ObjectReference contains enough information to let you inspect or modify the referred object. Attributes: api_group (string): API group make it easier to extend the Kubernetes API. The API gr... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ObjectReference:
"""Implementation of the 'ObjectReference' model. ObjectReference contains enough information to let you inspect or modify the referred object. Attributes: api_group (string): API group make it easier to extend the Kubernetes API. The API group is specified in a REST path and in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectReference:
"""Implementation of the 'ObjectReference' model. ObjectReference contains enough information to let you inspect or modify the referred object. Attributes: api_group (string): API group make it easier to extend the Kubernetes API. The API group is specified in a REST path and in the apiVersio... | the_stack_v2_python_sparse | cohesity_management_sdk/models/object_reference.py | cohesity/management-sdk-python | train | 24 |
9f2065af49d9664128352b00bc328f2204476599 | [
"self.name = name\nself.birthday = birthday\nself.premium = premium",
"if self.birthday == datetime.date.today():\n print('Happy Birthday!')\nelse:\n current_year = datetime.date.today().year\n birth_month = self.birthday.month\n birth_day = self.birthday.day\n print(datetime.date(current_year, bir... | <|body_start_0|>
self.name = name
self.birthday = birthday
self.premium = premium
<|end_body_0|>
<|body_start_1|>
if self.birthday == datetime.date.today():
print('Happy Birthday!')
else:
current_year = datetime.date.today().year
birth_month =... | User | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
def __init__(self, name, birthday, premium):
"""A Demo class representing a user for an application. Attributes ---------- name: (str) The users' name. birthday: (datetime.date) The date of birth for the user. premium: (bool) Represents whether a user is a premium user or not. Meth... | stack_v2_sparse_classes_36k_train_001340 | 23,101 | permissive | [
{
"docstring": "A Demo class representing a user for an application. Attributes ---------- name: (str) The users' name. birthday: (datetime.date) The date of birth for the user. premium: (bool) Represents whether a user is a premium user or not. Methods ------- next_birthday: Determines the users' birthday in t... | 2 | stack_v2_sparse_classes_30k_train_010786 | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def __init__(self, name, birthday, premium): A Demo class representing a user for an application. Attributes ---------- name: (str) The users' name. birthday: (datetime.date) The date of... | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def __init__(self, name, birthday, premium): A Demo class representing a user for an application. Attributes ---------- name: (str) The users' name. birthday: (datetime.date) The date of... | 767ba750e5cae0d213b9abfd709ff8f6e4d4a1ac | <|skeleton|>
class User:
def __init__(self, name, birthday, premium):
"""A Demo class representing a user for an application. Attributes ---------- name: (str) The users' name. birthday: (datetime.date) The date of birth for the user. premium: (bool) Represents whether a user is a premium user or not. Meth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class User:
def __init__(self, name, birthday, premium):
"""A Demo class representing a user for an application. Attributes ---------- name: (str) The users' name. birthday: (datetime.date) The date of birth for the user. premium: (bool) Represents whether a user is a premium user or not. Methods ------- ne... | the_stack_v2_python_sparse | Solutions.py | Descent098/PYTH-101 | train | 0 | |
9c62a47a8fbb331afcccecbaad161ea36c3f815f | [
"specs = super(ExpectedImprovement, cls).getInputSpecification()\nspecs.description = \"If this node is present within the acquisition node,\\n the expected improvement acqusition function is utilized.\\n This function is derived by applying Bayesian optimal decision ma... | <|body_start_0|>
specs = super(ExpectedImprovement, cls).getInputSpecification()
specs.description = "If this node is present within the acquisition node,\n the expected improvement acqusition function is utilized.\n This function is derived by applying Baye... | Provides class for the Expected Improvement (EI) acquisition function | ExpectedImprovement | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpectedImprovement:
"""Provides class for the Expected Improvement (EI) acquisition function"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for sp... | stack_v2_sparse_classes_36k_train_001341 | 5,235 | permissive | [
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for specifying input of cls.",
"name": "getInputSpecification",
"signature": "def getInputSpecification(cls)"
},
{
"docstring": "Evalu... | 3 | stack_v2_sparse_classes_30k_train_006466 | Implement the Python class `ExpectedImprovement` described below.
Class description:
Provides class for the Expected Improvement (EI) acquisition function
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data for class cls. @ In, None @ ... | Implement the Python class `ExpectedImprovement` described below.
Class description:
Provides class for the Expected Improvement (EI) acquisition function
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data for class cls. @ In, None @ ... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class ExpectedImprovement:
"""Provides class for the Expected Improvement (EI) acquisition function"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for sp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExpectedImprovement:
"""Provides class for the Expected Improvement (EI) acquisition function"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for specifying inpu... | the_stack_v2_python_sparse | ravenframework/Optimizers/acquisitionFunctions/ExpectedImprovement.py | idaholab/raven | train | 201 |
f645543120c50c0703a92307df4f470ea97edac9 | [
"try:\n j = nums.index(0)\nexcept ValueError:\n return\nnums_len = len(nums)\ni = j + 1\nwhile i < nums_len and nums[i] == 0:\n i += 1\nwhile i < nums_len:\n nums[j] = nums[i]\n nums[i] = 0\n j += 1\n while i < nums_len and nums[i] == 0:\n i += 1",
"i = 0\nfor num in nums:\n if num ... | <|body_start_0|>
try:
j = nums.index(0)
except ValueError:
return
nums_len = len(nums)
i = j + 1
while i < nums_len and nums[i] == 0:
i += 1
while i < nums_len:
nums[j] = nums[i]
nums[i] = 0
j += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_001342 | 882 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes",
"signature": "def moveZeroes(self, nums: List[int]) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes2",
"signature": "def moveZeroes2(self,... | 2 | stack_v2_sparse_classes_30k_train_000867 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes2(self, nums: List[int]) -> None: Do not return anything, mod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes2(self, nums: List[int]) -> None: Do not return anything, mod... | 0d1015717666ad78d4cf79df51b606feb307c908 | <|skeleton|>
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
try:
j = nums.index(0)
except ValueError:
return
nums_len = len(nums)
i = j + 1
while i < nums_len and nums[i] == 0:
... | the_stack_v2_python_sparse | LeetCode/Interview questions/Easy/Array/8__567_Move_Zeroes/solution.py | aleksanderprofic/Problem-Solving | train | 0 | |
8617996fd65b7a78dcdb47385f693aa67a039f01 | [
"self.ai_settings = ai_settings\nself.reset_stats()\nself.game_active = False\nself.max_score = 0",
"self.ships_left = self.ai_settings.ship_lives\nself.score = 0\nself.level = 1"
] | <|body_start_0|>
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = False
self.max_score = 0
<|end_body_0|>
<|body_start_1|>
self.ships_left = self.ai_settings.ship_lives
self.score = 0
self.level = 1
<|end_body_1|>
| follow all the information of the game | GameStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameStats:
"""follow all the information of the game"""
def __init__(self, ai_settings):
"""initialize all the information"""
<|body_0|>
def reset_stats(self):
"""initialize all the information the may be changed on the procedure of running program"""
<|b... | stack_v2_sparse_classes_36k_train_001343 | 608 | no_license | [
{
"docstring": "initialize all the information",
"name": "__init__",
"signature": "def __init__(self, ai_settings)"
},
{
"docstring": "initialize all the information the may be changed on the procedure of running program",
"name": "reset_stats",
"signature": "def reset_stats(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018602 | Implement the Python class `GameStats` described below.
Class description:
follow all the information of the game
Method signatures and docstrings:
- def __init__(self, ai_settings): initialize all the information
- def reset_stats(self): initialize all the information the may be changed on the procedure of running p... | Implement the Python class `GameStats` described below.
Class description:
follow all the information of the game
Method signatures and docstrings:
- def __init__(self, ai_settings): initialize all the information
- def reset_stats(self): initialize all the information the may be changed on the procedure of running p... | a5261982057f5a2d8fdf673b23593b7abd722c36 | <|skeleton|>
class GameStats:
"""follow all the information of the game"""
def __init__(self, ai_settings):
"""initialize all the information"""
<|body_0|>
def reset_stats(self):
"""initialize all the information the may be changed on the procedure of running program"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameStats:
"""follow all the information of the game"""
def __init__(self, ai_settings):
"""initialize all the information"""
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = False
self.max_score = 0
def reset_stats(self):
"""initia... | the_stack_v2_python_sparse | Part2/alien_invasion/game_stats.py | bigbillfighter/Python-Tutorial | train | 0 |
1b6ba4a0e8c4993d17518255b568cd541ba12ddc | [
"super(_RequestCallbackManager, self).validate_callback(callback)\nif isinstance(callback, (type, types.ClassType)):\n if not issubclass(callback, RequestCallback):\n raise ValueError('Type mismatch on callback argument')\nelif not issubclass(callback.__class__, RequestCallback):\n raise ValueError('Ty... | <|body_start_0|>
super(_RequestCallbackManager, self).validate_callback(callback)
if isinstance(callback, (type, types.ClassType)):
if not issubclass(callback, RequestCallback):
raise ValueError('Type mismatch on callback argument')
elif not issubclass(callback.__clas... | Manager for {@link RequestCallback} message callbacks. | _RequestCallbackManager | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _RequestCallbackManager:
"""Manager for {@link RequestCallback} message callbacks."""
def validate_callback(self, callback):
"""Validates if `callback` is a valid RequestCallback. :param callback: Callback to validate."""
<|body_0|>
def handle_fire(self, request_callback... | stack_v2_sparse_classes_36k_train_001344 | 12,867 | permissive | [
{
"docstring": "Validates if `callback` is a valid RequestCallback. :param callback: Callback to validate.",
"name": "validate_callback",
"signature": "def validate_callback(self, callback)"
},
{
"docstring": "Runs `request_callback` for `request`. :param request_callback: {@link dxlclient.callb... | 2 | stack_v2_sparse_classes_30k_train_021320 | Implement the Python class `_RequestCallbackManager` described below.
Class description:
Manager for {@link RequestCallback} message callbacks.
Method signatures and docstrings:
- def validate_callback(self, callback): Validates if `callback` is a valid RequestCallback. :param callback: Callback to validate.
- def ha... | Implement the Python class `_RequestCallbackManager` described below.
Class description:
Manager for {@link RequestCallback} message callbacks.
Method signatures and docstrings:
- def validate_callback(self, callback): Validates if `callback` is a valid RequestCallback. :param callback: Callback to validate.
- def ha... | 7bbc003592022f5776006d467f591a214a119013 | <|skeleton|>
class _RequestCallbackManager:
"""Manager for {@link RequestCallback} message callbacks."""
def validate_callback(self, callback):
"""Validates if `callback` is a valid RequestCallback. :param callback: Callback to validate."""
<|body_0|>
def handle_fire(self, request_callback... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _RequestCallbackManager:
"""Manager for {@link RequestCallback} message callbacks."""
def validate_callback(self, callback):
"""Validates if `callback` is a valid RequestCallback. :param callback: Callback to validate."""
super(_RequestCallbackManager, self).validate_callback(callback)
... | the_stack_v2_python_sparse | src/main/resources/dxlclient/_callback_manager.py | att/OpenDXLJythonClient | train | 4 |
d523b61526f1452425ad0b0ee3691c295330b892 | [
"tp = thread_pool.ThreadPool(5, 10)\ntp.start()\ntp.join()\ntp = thread_pool.ThreadPool(5, 10)\nself.assertRaises(ValueError, tp.join)\ntp.start()\ntp.join()\nself.assertRaises(ValueError, tp.start)\ntp = thread_pool.ThreadPool(5, 10)\ntp.start()\nself.assertRaises(ValueError, tp.start)\nself.assertRaises(ValueErro... | <|body_start_0|>
tp = thread_pool.ThreadPool(5, 10)
tp.start()
tp.join()
tp = thread_pool.ThreadPool(5, 10)
self.assertRaises(ValueError, tp.join)
tp.start()
tp.join()
self.assertRaises(ValueError, tp.start)
tp = thread_pool.ThreadPool(5, 10)
... | Tests for ThreadPool. | ThreadPoolTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadPoolTests:
"""Tests for ThreadPool."""
def test_basic(self):
"""Ensures that the thread pool maintains consistent state."""
<|body_0|>
def test_submit(self):
"""Ensures that tasks can be submitted to the pool."""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_001345 | 4,782 | permissive | [
{
"docstring": "Ensures that the thread pool maintains consistent state.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Ensures that tasks can be submitted to the pool.",
"name": "test_submit",
"signature": "def test_submit(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012542 | Implement the Python class `ThreadPoolTests` described below.
Class description:
Tests for ThreadPool.
Method signatures and docstrings:
- def test_basic(self): Ensures that the thread pool maintains consistent state.
- def test_submit(self): Ensures that tasks can be submitted to the pool. | Implement the Python class `ThreadPoolTests` described below.
Class description:
Tests for ThreadPool.
Method signatures and docstrings:
- def test_basic(self): Ensures that the thread pool maintains consistent state.
- def test_submit(self): Ensures that tasks can be submitted to the pool.
<|skeleton|>
class Thread... | 7ee6027ba1c2ae2baaeb3a501c70752d5c6f6433 | <|skeleton|>
class ThreadPoolTests:
"""Tests for ThreadPool."""
def test_basic(self):
"""Ensures that the thread pool maintains consistent state."""
<|body_0|>
def test_submit(self):
"""Ensures that tasks can be submitted to the pool."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreadPoolTests:
"""Tests for ThreadPool."""
def test_basic(self):
"""Ensures that the thread pool maintains consistent state."""
tp = thread_pool.ThreadPool(5, 10)
tp.start()
tp.join()
tp = thread_pool.ThreadPool(5, 10)
self.assertRaises(ValueError, tp.joi... | the_stack_v2_python_sparse | tools/gcutil/gcutil-1.5.0/lib/google_compute_engine/gcelib/thread_pool_test.py | FYJen/GoogleCloud | train | 0 |
653e5f4e373186ad630615eb450ef9685c6732e5 | [
"left = 0\nright = len(nums) - 1\nwhile left <= right:\n if nums[left] + nums[right] > target:\n right -= 1\n elif nums[left] + nums[right] < target:\n left += 1\n elif nums[left] + nums[right] == target:\n return [nums[left], nums[right]]\nreturn []",
"num_tar = {target - i for i in... | <|body_start_0|>
left = 0
right = len(nums) - 1
while left <= right:
if nums[left] + nums[right] > target:
right -= 1
elif nums[left] + nums[right] < target:
left += 1
elif nums[left] + nums[right] == target:
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target: int):
"""双指针方法,利用有序特性,分别从前后扫描"""
<|body_0|>
def twoSum_hash(self, nums, target: int):
"""利用哈希表复杂度O(n)空间复杂度O(n)"""
<|body_1|>
def twoSum_bin(self, nums, target: int):
"""二分查找解法,复杂度O(nlogn)会超时"""
<|b... | stack_v2_sparse_classes_36k_train_001346 | 2,505 | no_license | [
{
"docstring": "双指针方法,利用有序特性,分别从前后扫描",
"name": "twoSum",
"signature": "def twoSum(self, nums, target: int)"
},
{
"docstring": "利用哈希表复杂度O(n)空间复杂度O(n)",
"name": "twoSum_hash",
"signature": "def twoSum_hash(self, nums, target: int)"
},
{
"docstring": "二分查找解法,复杂度O(nlogn)会超时",
"na... | 4 | stack_v2_sparse_classes_30k_train_011335 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target: int): 双指针方法,利用有序特性,分别从前后扫描
- def twoSum_hash(self, nums, target: int): 利用哈希表复杂度O(n)空间复杂度O(n)
- def twoSum_bin(self, nums, target: int): 二分查找解法,复杂度O... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target: int): 双指针方法,利用有序特性,分别从前后扫描
- def twoSum_hash(self, nums, target: int): 利用哈希表复杂度O(n)空间复杂度O(n)
- def twoSum_bin(self, nums, target: int): 二分查找解法,复杂度O... | c9eed637887753eb28d78cf252ea3763231e23a2 | <|skeleton|>
class Solution:
def twoSum(self, nums, target: int):
"""双指针方法,利用有序特性,分别从前后扫描"""
<|body_0|>
def twoSum_hash(self, nums, target: int):
"""利用哈希表复杂度O(n)空间复杂度O(n)"""
<|body_1|>
def twoSum_bin(self, nums, target: int):
"""二分查找解法,复杂度O(nlogn)会超时"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums, target: int):
"""双指针方法,利用有序特性,分别从前后扫描"""
left = 0
right = len(nums) - 1
while left <= right:
if nums[left] + nums[right] > target:
right -= 1
elif nums[left] + nums[right] < target:
left +=... | the_stack_v2_python_sparse | CODE/剑指 Offer 57. 和为s的两个数字.py | moshlwx/leetcode | train | 5 | |
39b2c46ebe665b6b8a12e7e522c2d6549927d612 | [
"self.num = numerator\nself.denom = denominator\nif self.denom == 0:\n raise ZeroDivisionError('you cannot divide by zero')\nself._reduce()",
"d = gcd(self.num, self.denom)\nself.num /= d\nself.denom /= d\nif self.denom < 0:\n self.num = -self.num\n self.denom = -self.denom\nif self.num == 0:\n self.d... | <|body_start_0|>
self.num = numerator
self.denom = denominator
if self.denom == 0:
raise ZeroDivisionError('you cannot divide by zero')
self._reduce()
<|end_body_0|>
<|body_start_1|>
d = gcd(self.num, self.denom)
self.num /= d
self.denom /= d
... | This class represents a franctional value. E.g. 1/10 | Fraction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fraction:
"""This class represents a franctional value. E.g. 1/10"""
def __init__(self, numerator, denominator):
"""Initialize this fraction to (numerator / denominator)."""
<|body_0|>
def _reduce(self):
"""Reduce the fraction to its canonical (simplified) form. ... | stack_v2_sparse_classes_36k_train_001347 | 960 | no_license | [
{
"docstring": "Initialize this fraction to (numerator / denominator).",
"name": "__init__",
"signature": "def __init__(self, numerator, denominator)"
},
{
"docstring": "Reduce the fraction to its canonical (simplified) form. E.g. 2/4 becomes 1/2.",
"name": "_reduce",
"signature": "def _... | 2 | stack_v2_sparse_classes_30k_train_013520 | Implement the Python class `Fraction` described below.
Class description:
This class represents a franctional value. E.g. 1/10
Method signatures and docstrings:
- def __init__(self, numerator, denominator): Initialize this fraction to (numerator / denominator).
- def _reduce(self): Reduce the fraction to its canonica... | Implement the Python class `Fraction` described below.
Class description:
This class represents a franctional value. E.g. 1/10
Method signatures and docstrings:
- def __init__(self, numerator, denominator): Initialize this fraction to (numerator / denominator).
- def _reduce(self): Reduce the fraction to its canonica... | eb67298353f763da82ea6498e5c254e2b246faf8 | <|skeleton|>
class Fraction:
"""This class represents a franctional value. E.g. 1/10"""
def __init__(self, numerator, denominator):
"""Initialize this fraction to (numerator / denominator)."""
<|body_0|>
def _reduce(self):
"""Reduce the fraction to its canonical (simplified) form. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fraction:
"""This class represents a franctional value. E.g. 1/10"""
def __init__(self, numerator, denominator):
"""Initialize this fraction to (numerator / denominator)."""
self.num = numerator
self.denom = denominator
if self.denom == 0:
raise ZeroDivisionErr... | the_stack_v2_python_sparse | OOP/ryan_henning/demo1/fraction.py | wmarshall484/DSI_LECTURES_2 | train | 1 |
45f366ef9f2a59998aa56022d3fab2bc53c878c1 | [
"text = 'test @username'\nhtml = 'test <a href=\"https://www.instagram.com/username/\">@username</a>'\nself.assertEqual(linkify_text(text), html)",
"text = 'test #hashtag test'\nhtml = 'test <a href=\"https://www.instagram.com/explore/tags/hashtag/\">#hashtag</a> test'\nself.assertEqual(linkify_text(text), html)"... | <|body_start_0|>
text = 'test @username'
html = 'test <a href="https://www.instagram.com/username/">@username</a>'
self.assertEqual(linkify_text(text), html)
<|end_body_0|>
<|body_start_1|>
text = 'test #hashtag test'
html = 'test <a href="https://www.instagram.com/explore/tags/... | LinkifyInstagramCaption | [
"ECL-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkifyInstagramCaption:
def test_username(self):
"""An Instagram caption with a username is properly linkified to HTML"""
<|body_0|>
def test_hashtag(self):
"""An Instagram caption with a hashtag is properly linkified to HTML"""
<|body_1|>
def test_hash... | stack_v2_sparse_classes_36k_train_001348 | 1,949 | permissive | [
{
"docstring": "An Instagram caption with a username is properly linkified to HTML",
"name": "test_username",
"signature": "def test_username(self)"
},
{
"docstring": "An Instagram caption with a hashtag is properly linkified to HTML",
"name": "test_hashtag",
"signature": "def test_hasht... | 5 | null | Implement the Python class `LinkifyInstagramCaption` described below.
Class description:
Implement the LinkifyInstagramCaption class.
Method signatures and docstrings:
- def test_username(self): An Instagram caption with a username is properly linkified to HTML
- def test_hashtag(self): An Instagram caption with a ha... | Implement the Python class `LinkifyInstagramCaption` described below.
Class description:
Implement the LinkifyInstagramCaption class.
Method signatures and docstrings:
- def test_username(self): An Instagram caption with a username is properly linkified to HTML
- def test_hashtag(self): An Instagram caption with a ha... | f0baf62d0418ea5bb548c082aa84966aca363e56 | <|skeleton|>
class LinkifyInstagramCaption:
def test_username(self):
"""An Instagram caption with a username is properly linkified to HTML"""
<|body_0|>
def test_hashtag(self):
"""An Instagram caption with a hashtag is properly linkified to HTML"""
<|body_1|>
def test_hash... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkifyInstagramCaption:
def test_username(self):
"""An Instagram caption with a username is properly linkified to HTML"""
text = 'test @username'
html = 'test <a href="https://www.instagram.com/username/">@username</a>'
self.assertEqual(linkify_text(text), html)
def test_... | the_stack_v2_python_sparse | libraries/instagram/tests.py | cca/libraries_wagtail | train | 11 | |
75239f2e0f0a59cb9b706c37c00e2bb14010b311 | [
"Parametre.__init__(self, 'lister', 'list')\nself.schema = ''\nself.aide_courte = 'liste les attitudes existantes'\nself.aide_longue = 'Cette sous-commande offre une liste des attitudes existantes.'",
"attitudes = None\nif personnage.est_immortel():\n attitudes = type(self).importeur.communication.attitudes.va... | <|body_start_0|>
Parametre.__init__(self, 'lister', 'list')
self.schema = ''
self.aide_courte = 'liste les attitudes existantes'
self.aide_longue = 'Cette sous-commande offre une liste des attitudes existantes.'
<|end_body_0|>
<|body_start_1|>
attitudes = None
if personn... | Commande 'attitudes lister'. | PrmLister | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmLister:
"""Commande 'attitudes lister'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametre... | stack_v2_sparse_classes_36k_train_001349 | 3,460 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008859 | Implement the Python class `PrmLister` described below.
Class description:
Commande 'attitudes lister'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmLister` described below.
Class description:
Commande 'attitudes lister'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmLister:
"""Commande 'attitu... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmLister:
"""Commande 'attitudes lister'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmLister:
"""Commande 'attitudes lister'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'lister', 'list')
self.schema = ''
self.aide_courte = 'liste les attitudes existantes'
self.aide_longue = 'Cette sous-commande offre une liste... | the_stack_v2_python_sparse | src/primaires/communication/commandes/attitudes/lister.py | vincent-lg/tsunami | train | 5 |
c5b5b78c8ab45565985a2c5dd665d68b28055567 | [
"try:\n user = User.objects.get(username=request.user)\n if user.tfa_secret_code is None:\n key = pyotp.random_base32()\n user.tfa_secret_code = key\n user.save()\n data = {'secret_code': user.tfa_secret_code}\n return Utils.dispatch_success(request, data)\nexcept Exception as e:\n ... | <|body_start_0|>
try:
user = User.objects.get(username=request.user)
if user.tfa_secret_code is None:
key = pyotp.random_base32()
user.tfa_secret_code = key
user.save()
data = {'secret_code': user.tfa_secret_code}
re... | TwoFactorAuthenticationDetails | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoFactorAuthenticationDetails:
def get(self, request):
"""Gets TOTP Secret Key for a user"""
<|body_0|>
def post(self, request):
"""Check weather the totp is valid or not"""
<|body_1|>
def put(self, request):
"""Updates Two factor flag"""
... | stack_v2_sparse_classes_36k_train_001350 | 28,880 | no_license | [
{
"docstring": "Gets TOTP Secret Key for a user",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Check weather the totp is valid or not",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Updates Two factor flag",
"name": "put"... | 3 | stack_v2_sparse_classes_30k_train_007867 | Implement the Python class `TwoFactorAuthenticationDetails` described below.
Class description:
Implement the TwoFactorAuthenticationDetails class.
Method signatures and docstrings:
- def get(self, request): Gets TOTP Secret Key for a user
- def post(self, request): Check weather the totp is valid or not
- def put(se... | Implement the Python class `TwoFactorAuthenticationDetails` described below.
Class description:
Implement the TwoFactorAuthenticationDetails class.
Method signatures and docstrings:
- def get(self, request): Gets TOTP Secret Key for a user
- def post(self, request): Check weather the totp is valid or not
- def put(se... | 11b80dbd665e3592ed862403dd8c8d65b6791b30 | <|skeleton|>
class TwoFactorAuthenticationDetails:
def get(self, request):
"""Gets TOTP Secret Key for a user"""
<|body_0|>
def post(self, request):
"""Check weather the totp is valid or not"""
<|body_1|>
def put(self, request):
"""Updates Two factor flag"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwoFactorAuthenticationDetails:
def get(self, request):
"""Gets TOTP Secret Key for a user"""
try:
user = User.objects.get(username=request.user)
if user.tfa_secret_code is None:
key = pyotp.random_base32()
user.tfa_secret_code = key
... | the_stack_v2_python_sparse | portalbackend/lendapi/v1/accounts/views.py | mthangaraj/ix-ec-backend | train | 0 | |
af2c8b5b42665c3f2cc106999c8aef9c05ecda48 | [
"if app_label is None:\n raise TypeError('app_label must be a str.')\nself._iterations = 0\nwhile True:\n result = self.optimize_inner(operations, app_label)\n self._iterations += 1\n if result == operations:\n return result\n operations = result",
"new_operations = []\nfor i, operation in e... | <|body_start_0|>
if app_label is None:
raise TypeError('app_label must be a str.')
self._iterations = 0
while True:
result = self.optimize_inner(operations, app_label)
self._iterations += 1
if result == operations:
return result
... | Power the optimization process, where you provide a list of Operations and you are returned a list of equal or shorter length - operations are merged into one if possible. For example, a CreateModel and an AddField can be optimized into a new CreateModel, and CreateModel and DeleteModel can be optimized into nothing. | MigrationOptimizer | [
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"GPL-1.0-or-later",
"Python-2.0.1",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-other-permissive",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MigrationOptimizer:
"""Power the optimization process, where you provide a list of Operations and you are returned a list of equal or shorter length - operations are merged into one if possible. For example, a CreateModel and an AddField can be optimized into a new CreateModel, and CreateModel an... | stack_v2_sparse_classes_36k_train_001351 | 3,255 | permissive | [
{
"docstring": "Main optimization entry point. Pass in a list of Operation instances, get out a new list of Operation instances. Unfortunately, due to the scope of the optimization (two combinable operations might be separated by several hundred others), this can't be done as a peephole optimization with checks... | 2 | null | Implement the Python class `MigrationOptimizer` described below.
Class description:
Power the optimization process, where you provide a list of Operations and you are returned a list of equal or shorter length - operations are merged into one if possible. For example, a CreateModel and an AddField can be optimized int... | Implement the Python class `MigrationOptimizer` described below.
Class description:
Power the optimization process, where you provide a list of Operations and you are returned a list of equal or shorter length - operations are merged into one if possible. For example, a CreateModel and an AddField can be optimized int... | c74a6fad5475495756a5bdb18b2cab2b68d429bc | <|skeleton|>
class MigrationOptimizer:
"""Power the optimization process, where you provide a list of Operations and you are returned a list of equal or shorter length - operations are merged into one if possible. For example, a CreateModel and an AddField can be optimized into a new CreateModel, and CreateModel an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MigrationOptimizer:
"""Power the optimization process, where you provide a list of Operations and you are returned a list of equal or shorter length - operations are merged into one if possible. For example, a CreateModel and an AddField can be optimized into a new CreateModel, and CreateModel and DeleteModel... | the_stack_v2_python_sparse | django/db/migrations/optimizer.py | django/django | train | 73,530 |
57307d145b3497c968be744a00fbc9316eeec546 | [
"result = []\n\ndef preOrder(root):\n if root:\n result.append(str(root.val))\n preOrder(root.left)\n preOrder(root.right)\n else:\n result.append('#')\npreOrder(root)\nreturn ','.join(result)",
"s = s.split(',')\nnum = [-1]\n\ndef Change(num):\n num[0] += 1\n if num[0] < l... | <|body_start_0|>
result = []
def preOrder(root):
if root:
result.append(str(root.val))
preOrder(root.left)
preOrder(root.right)
else:
result.append('#')
preOrder(root)
return ','.join(result)
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def Serialize(self, root):
"""题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 :param root: :return:"""
<|body_0|>
def Deserialize(self, s):
"""题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 :param s: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
... | stack_v2_sparse_classes_36k_train_001352 | 1,260 | no_license | [
{
"docstring": "题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 :param root: :return:",
"name": "Serialize",
"signature": "def Serialize(self, root)"
},
{
"docstring": "题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 :param s: :return:",
"name": "Deserialize",
"signature": "def Deserialize(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015912 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Serialize(self, root): 题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 :param root: :return:
- def Deserialize(self, s): 题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 :param s: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Serialize(self, root): 题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 :param root: :return:
- def Deserialize(self, s): 题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 :param s: :return:
<|skeleton|>
class Solu... | c6e50be39292f8eefd7d3312ac5d0141bbe06f5b | <|skeleton|>
class Solution:
def Serialize(self, root):
"""题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 :param root: :return:"""
<|body_0|>
def Deserialize(self, s):
"""题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 :param s: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def Serialize(self, root):
"""题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 :param root: :return:"""
result = []
def preOrder(root):
if root:
result.append(str(root.val))
preOrder(root.left)
preOrder(root.right)
else:
... | the_stack_v2_python_sparse | Tree/37_序列化二叉树.py | MingjunGuo/python__offer | train | 0 | |
50dcedb5b79f4d133d14e025353f7f129f3473e6 | [
"self.prev = prev\nself.top = Toplevel()\nself.top.focus_set()\nself.top.grab_set()\nself._make_widgets()",
"_frame_entry1 = Frame(self.top)\n_frame_entry2 = Frame(self.top)\n_frame_entry3 = Frame(self.top)\nLabel(_frame_entry1, text='Name: ', font=('arial', '16', 'bold')).pack(side=LEFT)\nLabel(_frame_entry2, te... | <|body_start_0|>
self.prev = prev
self.top = Toplevel()
self.top.focus_set()
self.top.grab_set()
self._make_widgets()
<|end_body_0|>
<|body_start_1|>
_frame_entry1 = Frame(self.top)
_frame_entry2 = Frame(self.top)
_frame_entry3 = Frame(self.top)
L... | Діалогове вікно для вказання параметрів пошуку | Dialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dialog:
"""Діалогове вікно для вказання параметрів пошуку"""
def __init__(self, prev):
"""Ініціалізація :param prev: вікно, яке викликало"""
<|body_0|>
def _make_widgets(self):
"""Створення віджетів"""
<|body_1|>
def _ok_handler(self, ev=None):
... | stack_v2_sparse_classes_36k_train_001353 | 6,820 | no_license | [
{
"docstring": "Ініціалізація :param prev: вікно, яке викликало",
"name": "__init__",
"signature": "def __init__(self, prev)"
},
{
"docstring": "Створення віджетів",
"name": "_make_widgets",
"signature": "def _make_widgets(self)"
},
{
"docstring": "Обробка натиснення кнопки",
... | 3 | null | Implement the Python class `Dialog` described below.
Class description:
Діалогове вікно для вказання параметрів пошуку
Method signatures and docstrings:
- def __init__(self, prev): Ініціалізація :param prev: вікно, яке викликало
- def _make_widgets(self): Створення віджетів
- def _ok_handler(self, ev=None): Обробка н... | Implement the Python class `Dialog` described below.
Class description:
Діалогове вікно для вказання параметрів пошуку
Method signatures and docstrings:
- def __init__(self, prev): Ініціалізація :param prev: вікно, яке викликало
- def _make_widgets(self): Створення віджетів
- def _ok_handler(self, ev=None): Обробка н... | e44bf2b535b34bc31fb323c20901a77b0b3072f2 | <|skeleton|>
class Dialog:
"""Діалогове вікно для вказання параметрів пошуку"""
def __init__(self, prev):
"""Ініціалізація :param prev: вікно, яке викликало"""
<|body_0|>
def _make_widgets(self):
"""Створення віджетів"""
<|body_1|>
def _ok_handler(self, ev=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dialog:
"""Діалогове вікно для вказання параметрів пошуку"""
def __init__(self, prev):
"""Ініціалізація :param prev: вікно, яке викликало"""
self.prev = prev
self.top = Toplevel()
self.top.focus_set()
self.top.grab_set()
self._make_widgets()
def _make_... | the_stack_v2_python_sparse | dz_others/subject24_gui/t24_12/gui.py | davendiy/ads_course2 | train | 0 |
94e007859303aca79153ba1780b9bb65208f6c10 | [
"theta = Substitution()\nisGood = unifyTerm(x.toTerm(), y.toTerm(), theta)\nif isGood:\n return theta\nelse:\n return None",
"if x == y:\n return True\nif isinstance(x, (GdlConstant,)) and isinstance(y, (GdlConstant,)):\n if not x == y:\n return False\nelif isinstance(x, (GdlVariable,)):\n i... | <|body_start_0|>
theta = Substitution()
isGood = unifyTerm(x.toTerm(), y.toTerm(), theta)
if isGood:
return theta
else:
return None
<|end_body_0|>
<|body_start_1|>
if x == y:
return True
if isinstance(x, (GdlConstant,)) and isinstance(... | generated source for class Unifier | Unifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Unifier:
"""generated source for class Unifier"""
def unify(cls, x, y):
"""generated source for method unify"""
<|body_0|>
def unifyTerm(cls, x, y, theta):
"""generated source for method unifyTerm"""
<|body_1|>
def unifyVariable(cls, var, x, theta):
... | stack_v2_sparse_classes_36k_train_001354 | 2,129 | permissive | [
{
"docstring": "generated source for method unify",
"name": "unify",
"signature": "def unify(cls, x, y)"
},
{
"docstring": "generated source for method unifyTerm",
"name": "unifyTerm",
"signature": "def unifyTerm(cls, x, y, theta)"
},
{
"docstring": "generated source for method u... | 3 | null | Implement the Python class `Unifier` described below.
Class description:
generated source for class Unifier
Method signatures and docstrings:
- def unify(cls, x, y): generated source for method unify
- def unifyTerm(cls, x, y, theta): generated source for method unifyTerm
- def unifyVariable(cls, var, x, theta): gene... | Implement the Python class `Unifier` described below.
Class description:
generated source for class Unifier
Method signatures and docstrings:
- def unify(cls, x, y): generated source for method unify
- def unifyTerm(cls, x, y, theta): generated source for method unifyTerm
- def unifyVariable(cls, var, x, theta): gene... | 4e6e6e876c3a4294cd711647051da2d9c1836b60 | <|skeleton|>
class Unifier:
"""generated source for class Unifier"""
def unify(cls, x, y):
"""generated source for method unify"""
<|body_0|>
def unifyTerm(cls, x, y, theta):
"""generated source for method unifyTerm"""
<|body_1|>
def unifyVariable(cls, var, x, theta):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Unifier:
"""generated source for class Unifier"""
def unify(cls, x, y):
"""generated source for method unify"""
theta = Substitution()
isGood = unifyTerm(x.toTerm(), y.toTerm(), theta)
if isGood:
return theta
else:
return None
def unify... | the_stack_v2_python_sparse | ggpy/cruft/autocode/Unifier.py | hobson/ggpy | train | 1 |
6912719ddd454307106777e35f3e6f03ce3ee769 | [
"self.reuse = False\nself.batch_size = batch_size\nself.num_channels = num_channels\nself.layer_stage_sizes = layer_stage_sizes\nself.name = name\nself.num_classes = num_classes\nself.batch_norm_use = batch_norm_use\nself.inner_layer_depth = inner_layer_depth\nself.strided_dim_reduction = strided_dim_reduction\nsel... | <|body_start_0|>
self.reuse = False
self.batch_size = batch_size
self.num_channels = num_channels
self.layer_stage_sizes = layer_stage_sizes
self.name = name
self.num_classes = num_classes
self.batch_norm_use = batch_norm_use
self.inner_layer_depth = inner... | FCCLayerClassifier | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FCCLayerClassifier:
def __init__(self, batch_size, layer_stage_sizes, name, num_classes, num_channels=1, batch_norm_use=False, inner_layer_depth=2, strided_dim_reduction=True):
"""Initializes a VGG Classifier architecture :param batch_size: The size of the data batch :param layer_stage_s... | stack_v2_sparse_classes_36k_train_001355 | 9,392 | permissive | [
{
"docstring": "Initializes a VGG Classifier architecture :param batch_size: The size of the data batch :param layer_stage_sizes: A list containing the filters for each layer stage, where layer stage is a series of convolutional layers with stride=1 and no max pooling followed by a dimensionality reducing stage... | 2 | null | Implement the Python class `FCCLayerClassifier` described below.
Class description:
Implement the FCCLayerClassifier class.
Method signatures and docstrings:
- def __init__(self, batch_size, layer_stage_sizes, name, num_classes, num_channels=1, batch_norm_use=False, inner_layer_depth=2, strided_dim_reduction=True): I... | Implement the Python class `FCCLayerClassifier` described below.
Class description:
Implement the FCCLayerClassifier class.
Method signatures and docstrings:
- def __init__(self, batch_size, layer_stage_sizes, name, num_classes, num_channels=1, batch_norm_use=False, inner_layer_depth=2, strided_dim_reduction=True): I... | 2831df3ef210cb3e259bbc43dd39159533f4a33e | <|skeleton|>
class FCCLayerClassifier:
def __init__(self, batch_size, layer_stage_sizes, name, num_classes, num_channels=1, batch_norm_use=False, inner_layer_depth=2, strided_dim_reduction=True):
"""Initializes a VGG Classifier architecture :param batch_size: The size of the data batch :param layer_stage_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FCCLayerClassifier:
def __init__(self, batch_size, layer_stage_sizes, name, num_classes, num_channels=1, batch_norm_use=False, inner_layer_depth=2, strided_dim_reduction=True):
"""Initializes a VGG Classifier architecture :param batch_size: The size of the data batch :param layer_stage_sizes: A list c... | the_stack_v2_python_sparse | network_architectures.py | comRamona/ACL-2018-Multimodal-Sentiment-Analysis-Multicomp | train | 0 | |
669ba5d3ddcb833f1e01465ccec198b7daee4b80 | [
"super(Linear, self).__init__()\nself.matmul = nn.MatMul()\nself.matmul_w = Parameter(Tensor(np.random.uniform(0, 1, linear_weight_shape).astype(np.float32)), name=None)\nself.add = P.Add()\nself.add_bias = Parameter(Tensor(np.random.uniform(0, 1, linear_bias_shape).astype(np.float32)), name=None)\nself.relu = nn.R... | <|body_start_0|>
super(Linear, self).__init__()
self.matmul = nn.MatMul()
self.matmul_w = Parameter(Tensor(np.random.uniform(0, 1, linear_weight_shape).astype(np.float32)), name=None)
self.add = P.Add()
self.add_bias = Parameter(Tensor(np.random.uniform(0, 1, linear_bias_shape).a... | module of reader downstream | Linear | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linear:
"""module of reader downstream"""
def __init__(self, linear_weight_shape, linear_bias_shape):
"""init function"""
<|body_0|>
def construct(self, hidden_state):
"""construct function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(L... | stack_v2_sparse_classes_36k_train_001356 | 9,011 | permissive | [
{
"docstring": "init function",
"name": "__init__",
"signature": "def __init__(self, linear_weight_shape, linear_bias_shape)"
},
{
"docstring": "construct function",
"name": "construct",
"signature": "def construct(self, hidden_state)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018188 | Implement the Python class `Linear` described below.
Class description:
module of reader downstream
Method signatures and docstrings:
- def __init__(self, linear_weight_shape, linear_bias_shape): init function
- def construct(self, hidden_state): construct function | Implement the Python class `Linear` described below.
Class description:
module of reader downstream
Method signatures and docstrings:
- def __init__(self, linear_weight_shape, linear_bias_shape): init function
- def construct(self, hidden_state): construct function
<|skeleton|>
class Linear:
"""module of reader ... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class Linear:
"""module of reader downstream"""
def __init__(self, linear_weight_shape, linear_bias_shape):
"""init function"""
<|body_0|>
def construct(self, hidden_state):
"""construct function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Linear:
"""module of reader downstream"""
def __init__(self, linear_weight_shape, linear_bias_shape):
"""init function"""
super(Linear, self).__init__()
self.matmul = nn.MatMul()
self.matmul_w = Parameter(Tensor(np.random.uniform(0, 1, linear_weight_shape).astype(np.float3... | the_stack_v2_python_sparse | research/nlp/tprr/src/reader_downstream.py | mindspore-ai/models | train | 301 |
4b5138967c1399153a6017b312fffa391e733bdc | [
"cube = set_up_variable_cube(np.ones((12, 12), dtype=np.float32), time=datetime(2017, 2, 17, 6, 0), frt=datetime(2017, 2, 17, 6, 0))\ncube.remove_coord('forecast_period')\nself.time_points = np.arange(1487311200, 1487354400, 3600).astype(np.int64)\nself.cube = add_coordinate(cube, self.time_points, 'time', dtype=np... | <|body_start_0|>
cube = set_up_variable_cube(np.ones((12, 12), dtype=np.float32), time=datetime(2017, 2, 17, 6, 0), frt=datetime(2017, 2, 17, 6, 0))
cube.remove_coord('forecast_period')
self.time_points = np.arange(1487311200, 1487354400, 3600).astype(np.int64)
self.cube = add_coordinate... | Test construction of an iris.Constraint from a python datetime object. | Test_datetime_constraint | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_datetime_constraint:
"""Test construction of an iris.Constraint from a python datetime object."""
def setUp(self):
"""Set up test cubes"""
<|body_0|>
def test_constraint_list_equality(self):
"""Check a list of constraints is as expected."""
<|body_1|... | stack_v2_sparse_classes_36k_train_001357 | 19,622 | permissive | [
{
"docstring": "Set up test cubes",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Check a list of constraints is as expected.",
"name": "test_constraint_list_equality",
"signature": "def test_constraint_list_equality(self)"
},
{
"docstring": "Check type is ir... | 5 | null | Implement the Python class `Test_datetime_constraint` described below.
Class description:
Test construction of an iris.Constraint from a python datetime object.
Method signatures and docstrings:
- def setUp(self): Set up test cubes
- def test_constraint_list_equality(self): Check a list of constraints is as expected.... | Implement the Python class `Test_datetime_constraint` described below.
Class description:
Test construction of an iris.Constraint from a python datetime object.
Method signatures and docstrings:
- def setUp(self): Set up test cubes
- def test_constraint_list_equality(self): Check a list of constraints is as expected.... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_datetime_constraint:
"""Test construction of an iris.Constraint from a python datetime object."""
def setUp(self):
"""Set up test cubes"""
<|body_0|>
def test_constraint_list_equality(self):
"""Check a list of constraints is as expected."""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_datetime_constraint:
"""Test construction of an iris.Constraint from a python datetime object."""
def setUp(self):
"""Set up test cubes"""
cube = set_up_variable_cube(np.ones((12, 12), dtype=np.float32), time=datetime(2017, 2, 17, 6, 0), frt=datetime(2017, 2, 17, 6, 0))
cube.... | the_stack_v2_python_sparse | improver_tests/utilities/temporal/test_temporal.py | metoppv/improver | train | 101 |
2275bb3ac505e1c2f83836bb1a13346cc516b341 | [
"self.headers = headers\nself.retries = retries\nself.proxies = proxies\nself.downder = Downder(headers, retries, proxies, delay, timeout)\nself.timeout = timeout",
"page = self.downder.download(url)\nsoup_all = BeautifulSoup(page, 'lxml')\ngl_item_list = soup_all.find_all('li', attrs={'class': 'gl-item'})\nrow_l... | <|body_start_0|>
self.headers = headers
self.retries = retries
self.proxies = proxies
self.downder = Downder(headers, retries, proxies, delay, timeout)
self.timeout = timeout
<|end_body_0|>
<|body_start_1|>
page = self.downder.download(url)
soup_all = BeautifulSo... | 爬虫类 | ItemSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemSpider:
"""爬虫类"""
def __init__(self, headers=None, retries=3, proxies=None, delay=3, timeout=30):
"""初始化"""
<|body_0|>
def find_all(self, url):
"""通过一个网址,爬取信息"""
<|body_1|>
def fetch_data(self, url, filename, page_start, page_end, page_offset, ca... | stack_v2_sparse_classes_36k_train_001358 | 6,930 | no_license | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self, headers=None, retries=3, proxies=None, delay=3, timeout=30)"
},
{
"docstring": "通过一个网址,爬取信息",
"name": "find_all",
"signature": "def find_all(self, url)"
},
{
"docstring": "根据页数搜索所有信息",
"name": "fetch_d... | 3 | null | Implement the Python class `ItemSpider` described below.
Class description:
爬虫类
Method signatures and docstrings:
- def __init__(self, headers=None, retries=3, proxies=None, delay=3, timeout=30): 初始化
- def find_all(self, url): 通过一个网址,爬取信息
- def fetch_data(self, url, filename, page_start, page_end, page_offset, callba... | Implement the Python class `ItemSpider` described below.
Class description:
爬虫类
Method signatures and docstrings:
- def __init__(self, headers=None, retries=3, proxies=None, delay=3, timeout=30): 初始化
- def find_all(self, url): 通过一个网址,爬取信息
- def fetch_data(self, url, filename, page_start, page_end, page_offset, callba... | 173f3a5fa24176df4c53bd36771cc733a1221dfd | <|skeleton|>
class ItemSpider:
"""爬虫类"""
def __init__(self, headers=None, retries=3, proxies=None, delay=3, timeout=30):
"""初始化"""
<|body_0|>
def find_all(self, url):
"""通过一个网址,爬取信息"""
<|body_1|>
def fetch_data(self, url, filename, page_start, page_end, page_offset, ca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ItemSpider:
"""爬虫类"""
def __init__(self, headers=None, retries=3, proxies=None, delay=3, timeout=30):
"""初始化"""
self.headers = headers
self.retries = retries
self.proxies = proxies
self.downder = Downder(headers, retries, proxies, delay, timeout)
self.timeo... | the_stack_v2_python_sparse | 0303system-yanchunwei/joker_work/core/down.py | Joker2018goon/myGitRepo | train | 1 |
5369909a36a75796885ae0bcc2ddcc97023aec63 | [
"if self.HAS_INTEGRAL_ID_TYPE:\n try:\n return int(str_id)\n except ValueError:\n raise QueryError('%s ID must be integral' % self.MODEL_CLASS.__name__)\nreturn str_id",
"search_base = self.request.get('searchBase', None)\nsearch_term = self.request.get('search', None)\nhas_base = search_base ... | <|body_start_0|>
if self.HAS_INTEGRAL_ID_TYPE:
try:
return int(str_id)
except ValueError:
raise QueryError('%s ID must be integral' % self.MODEL_CLASS.__name__)
return str_id
<|end_body_0|>
<|body_start_1|>
search_base = self.request.get('... | Base handler class for model queries. The primary use of this module is to access Upvote's stored Entities. This class provides a generic interface for this use-case. | BaseQueryHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseQueryHandler:
"""Base handler class for model queries. The primary use of this module is to access Upvote's stored Entities. This class provides a generic interface for this use-case."""
def _ConvertToIDType(self, str_id):
"""Converts the string form of the model ID to the correc... | stack_v2_sparse_classes_36k_train_001359 | 11,090 | permissive | [
{
"docstring": "Converts the string form of the model ID to the correct type. Args: str_id: The ID string. Returns: The ID query coerced to the correct type. Raises: QueryError: If type coercion fails.",
"name": "_ConvertToIDType",
"signature": "def _ConvertToIDType(self, str_id)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_003601 | Implement the Python class `BaseQueryHandler` described below.
Class description:
Base handler class for model queries. The primary use of this module is to access Upvote's stored Entities. This class provides a generic interface for this use-case.
Method signatures and docstrings:
- def _ConvertToIDType(self, str_id... | Implement the Python class `BaseQueryHandler` described below.
Class description:
Base handler class for model queries. The primary use of this module is to access Upvote's stored Entities. This class provides a generic interface for this use-case.
Method signatures and docstrings:
- def _ConvertToIDType(self, str_id... | e05d477bb13e470127b109eb8905a66a06eed5ac | <|skeleton|>
class BaseQueryHandler:
"""Base handler class for model queries. The primary use of this module is to access Upvote's stored Entities. This class provides a generic interface for this use-case."""
def _ConvertToIDType(self, str_id):
"""Converts the string form of the model ID to the correc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseQueryHandler:
"""Base handler class for model queries. The primary use of this module is to access Upvote's stored Entities. This class provides a generic interface for this use-case."""
def _ConvertToIDType(self, str_id):
"""Converts the string form of the model ID to the correct type. Args:... | the_stack_v2_python_sparse | upvote/gae/modules/upvote_app/api/handlers/base.py | codegrande/upvote | train | 0 |
d457c9fe405a9070a851369b5dff1a65512123e8 | [
"TreatmentInfoView.validate_treatment_info_request(id_patient, id_treatment_cycle, id_treatment)\ntreatment_report = TreatmentService.treatment_report(id_treatment)\nreturn FileResponse(treatment_report, filename=id_treatment + '_report.pdf')",
"Utils.validate_uuid(id_patient)\nUtils.validate_uuid(id_treatment_cy... | <|body_start_0|>
TreatmentInfoView.validate_treatment_info_request(id_patient, id_treatment_cycle, id_treatment)
treatment_report = TreatmentService.treatment_report(id_treatment)
return FileResponse(treatment_report, filename=id_treatment + '_report.pdf')
<|end_body_0|>
<|body_start_1|>
... | All endpoints related to treatment report actions | TreatmentReportView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreatmentReportView:
"""All endpoints related to treatment report actions"""
def get(request, id_patient, id_treatment_cycle, id_treatment):
"""Action when calling the endpoint with GET"""
<|body_0|>
def validate_treatment_info_request(id_patient, id_treatment_cycle, id_... | stack_v2_sparse_classes_36k_train_001360 | 2,875 | no_license | [
{
"docstring": "Action when calling the endpoint with GET",
"name": "get",
"signature": "def get(request, id_patient, id_treatment_cycle, id_treatment)"
},
{
"docstring": "Validates the treatment information received in the request body :param id_patient: Id of the patient received :param id_tre... | 2 | stack_v2_sparse_classes_30k_train_017045 | Implement the Python class `TreatmentReportView` described below.
Class description:
All endpoints related to treatment report actions
Method signatures and docstrings:
- def get(request, id_patient, id_treatment_cycle, id_treatment): Action when calling the endpoint with GET
- def validate_treatment_info_request(id_... | Implement the Python class `TreatmentReportView` described below.
Class description:
All endpoints related to treatment report actions
Method signatures and docstrings:
- def get(request, id_patient, id_treatment_cycle, id_treatment): Action when calling the endpoint with GET
- def validate_treatment_info_request(id_... | 941e8b2870f8724db3d5103dda5157fd597cfcc7 | <|skeleton|>
class TreatmentReportView:
"""All endpoints related to treatment report actions"""
def get(request, id_patient, id_treatment_cycle, id_treatment):
"""Action when calling the endpoint with GET"""
<|body_0|>
def validate_treatment_info_request(id_patient, id_treatment_cycle, id_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TreatmentReportView:
"""All endpoints related to treatment report actions"""
def get(request, id_patient, id_treatment_cycle, id_treatment):
"""Action when calling the endpoint with GET"""
TreatmentInfoView.validate_treatment_info_request(id_patient, id_treatment_cycle, id_treatment)
... | the_stack_v2_python_sparse | backend/martin_helder/views/treatment_report_view.py | JoaoAlvaroFerreira/FEUP-LGP | train | 1 |
a59456d188ef7fd86aa0bc5546658f0fd306d697 | [
"if not isinstance(course_location, Location):\n course_location = Location(course_location)\ncourse = {}\ndescriptor = get_modulestore(course_location).get_item(course_location)\nfor field in descriptor.fields + descriptor.lms.fields:\n if field.scope != Scope.settings:\n continue\n if field.name n... | <|body_start_0|>
if not isinstance(course_location, Location):
course_location = Location(course_location)
course = {}
descriptor = get_modulestore(course_location).get_item(course_location)
for field in descriptor.fields + descriptor.lms.fields:
if field.scope !=... | For CRUD operations on metadata fields which do not have specific editors on the other pages including any user generated ones. The objects have no predefined attrs but instead are obj encodings of the editable metadata. | CourseMetadata | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseMetadata:
"""For CRUD operations on metadata fields which do not have specific editors on the other pages including any user generated ones. The objects have no predefined attrs but instead are obj encodings of the editable metadata."""
def fetch(cls, course_location):
"""Fetch... | stack_v2_sparse_classes_36k_train_001361 | 3,895 | no_license | [
{
"docstring": "Fetch the key:value editable course details for the given course from persistence and return a CourseMetadata model.",
"name": "fetch",
"signature": "def fetch(cls, course_location)"
},
{
"docstring": "Decode the json into CourseMetadata and save any changed attrs to the db. Ensu... | 3 | stack_v2_sparse_classes_30k_train_017744 | Implement the Python class `CourseMetadata` described below.
Class description:
For CRUD operations on metadata fields which do not have specific editors on the other pages including any user generated ones. The objects have no predefined attrs but instead are obj encodings of the editable metadata.
Method signatures... | Implement the Python class `CourseMetadata` described below.
Class description:
For CRUD operations on metadata fields which do not have specific editors on the other pages including any user generated ones. The objects have no predefined attrs but instead are obj encodings of the editable metadata.
Method signatures... | 5fa3a818c3d41bd9c3eb25122e1d376c8910269c | <|skeleton|>
class CourseMetadata:
"""For CRUD operations on metadata fields which do not have specific editors on the other pages including any user generated ones. The objects have no predefined attrs but instead are obj encodings of the editable metadata."""
def fetch(cls, course_location):
"""Fetch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CourseMetadata:
"""For CRUD operations on metadata fields which do not have specific editors on the other pages including any user generated ones. The objects have no predefined attrs but instead are obj encodings of the editable metadata."""
def fetch(cls, course_location):
"""Fetch the key:valu... | the_stack_v2_python_sparse | ExtractFeatures/Data/pratik98/course_metadata.py | vivekaxl/LexisNexis | train | 9 |
de1f222ffb031e182a3148f12e3a49e58bf15f7f | [
"if root == None:\n return\nelif root.left == None and root.right == None and (root.val == sum):\n result.append([i for i in value_list] + [root.val])\n return\nelse:\n self.hasPathSum_recurse(root.left, sum - root.val, result, value_list + [root.val])\n self.hasPathSum_recurse(root.right, sum - root... | <|body_start_0|>
if root == None:
return
elif root.left == None and root.right == None and (root.val == sum):
result.append([i for i in value_list] + [root.val])
return
else:
self.hasPathSum_recurse(root.left, sum - root.val, result, value_list + [... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasPathSum_recurse(self, root, sum, result, value_list):
""":type root: TreeNode :type sum: int :rtype: bool"""
<|body_0|>
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_001362 | 1,020 | no_license | [
{
"docstring": ":type root: TreeNode :type sum: int :rtype: bool",
"name": "hasPathSum_recurse",
"signature": "def hasPathSum_recurse(self, root, sum, result, value_list)"
},
{
"docstring": ":type root: TreeNode :type sum: int :rtype: List[List[int]]",
"name": "pathSum",
"signature": "de... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum_recurse(self, root, sum, result, value_list): :type root: TreeNode :type sum: int :rtype: bool
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum_recurse(self, root, sum, result, value_list): :type root: TreeNode :type sum: int :rtype: bool
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int ... | e4ba57613fc76e75bd4ec567540ba99bbbba8326 | <|skeleton|>
class Solution:
def hasPathSum_recurse(self, root, sum, result, value_list):
""":type root: TreeNode :type sum: int :rtype: bool"""
<|body_0|>
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hasPathSum_recurse(self, root, sum, result, value_list):
""":type root: TreeNode :type sum: int :rtype: bool"""
if root == None:
return
elif root.left == None and root.right == None and (root.val == sum):
result.append([i for i in value_list] + [ro... | the_stack_v2_python_sparse | leetcode/113.PathSumII.py | AaronTengDeChuan/leetcode | train | 0 | |
76570dd624add2ea2a6f38eb59acaa3f4522abd8 | [
"self.screen_width = 1200\nself.screen_height = 700\nself.bg_color = (230, 230, 230)\nself.ship_limit = 3\nself.bullet_width = 3\nself.bullet_height = 15\nself.bullet_color = (60, 60, 60)\nself.bullets_allowed = 5\nself.fleet_drop_speed = 10\nself.speedup_scale = 1.1\nself.score_scale = 1.5\nself.initialize_dynamic... | <|body_start_0|>
self.screen_width = 1200
self.screen_height = 700
self.bg_color = (230, 230, 230)
self.ship_limit = 3
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = (60, 60, 60)
self.bullets_allowed = 5
self.fleet_drop_speed = 1... | Storing all settings for the game Alien Invasion | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""Storing all settings for the game Alien Invasion"""
def __init__(self):
"""init static settings"""
<|body_0|>
def initialize_dynamic_settings(self):
"""Initialize settings when speed up"""
<|body_1|>
def increase_speed(self):
"""... | stack_v2_sparse_classes_36k_train_001363 | 1,468 | no_license | [
{
"docstring": "init static settings",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Initialize settings when speed up",
"name": "initialize_dynamic_settings",
"signature": "def initialize_dynamic_settings(self)"
},
{
"docstring": "Speedup settings",
... | 3 | stack_v2_sparse_classes_30k_train_021444 | Implement the Python class `Settings` described below.
Class description:
Storing all settings for the game Alien Invasion
Method signatures and docstrings:
- def __init__(self): init static settings
- def initialize_dynamic_settings(self): Initialize settings when speed up
- def increase_speed(self): Speedup setting... | Implement the Python class `Settings` described below.
Class description:
Storing all settings for the game Alien Invasion
Method signatures and docstrings:
- def __init__(self): init static settings
- def initialize_dynamic_settings(self): Initialize settings when speed up
- def increase_speed(self): Speedup setting... | ed71b6266b2d2b5ddefadcb958f17695fb9db6cf | <|skeleton|>
class Settings:
"""Storing all settings for the game Alien Invasion"""
def __init__(self):
"""init static settings"""
<|body_0|>
def initialize_dynamic_settings(self):
"""Initialize settings when speed up"""
<|body_1|>
def increase_speed(self):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Settings:
"""Storing all settings for the game Alien Invasion"""
def __init__(self):
"""init static settings"""
self.screen_width = 1200
self.screen_height = 700
self.bg_color = (230, 230, 230)
self.ship_limit = 3
self.bullet_width = 3
self.bullet_h... | the_stack_v2_python_sparse | python/python/eric/part2_project/project01_game_aliens/settings.py | aojie654/codes_store | train | 2 |
6641253a39e23c071aa98b6f7d64ad9b788a9da8 | [
"epm = self.getOrDefault(self.estimatorParamMaps)\nnumModels = len(epm)\nnFolds = self.getOrDefault(self.numFolds)\nsplit_ratio = 1.0 / nFolds\npasses = dataset[dataset['label'] == 1]\nfails = dataset[dataset['label'] == 0]\npass_splits = passes.randomSplit([split_ratio for i in range(nFolds)])\nfail_splits = fails... | <|body_start_0|>
epm = self.getOrDefault(self.estimatorParamMaps)
numModels = len(epm)
nFolds = self.getOrDefault(self.numFolds)
split_ratio = 1.0 / nFolds
passes = dataset[dataset['label'] == 1]
fails = dataset[dataset['label'] == 0]
pass_splits = passes.randomSp... | Spark by default does not have Stratified folding so extending cross validator | StratifiedCrossValidator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StratifiedCrossValidator:
"""Spark by default does not have Stratified folding so extending cross validator"""
def stratify_data(self, dataset):
"""Returns an array of dataframes with the same ratio of passes and failures. Currently only supports binary classification problems."""
... | stack_v2_sparse_classes_36k_train_001364 | 2,328 | no_license | [
{
"docstring": "Returns an array of dataframes with the same ratio of passes and failures. Currently only supports binary classification problems.",
"name": "stratify_data",
"signature": "def stratify_data(self, dataset)"
},
{
"docstring": "Fits dataset",
"name": "_fit",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_008111 | Implement the Python class `StratifiedCrossValidator` described below.
Class description:
Spark by default does not have Stratified folding so extending cross validator
Method signatures and docstrings:
- def stratify_data(self, dataset): Returns an array of dataframes with the same ratio of passes and failures. Curr... | Implement the Python class `StratifiedCrossValidator` described below.
Class description:
Spark by default does not have Stratified folding so extending cross validator
Method signatures and docstrings:
- def stratify_data(self, dataset): Returns an array of dataframes with the same ratio of passes and failures. Curr... | 6eb21f9ffe3440a96904ce7946113dbad18c0e66 | <|skeleton|>
class StratifiedCrossValidator:
"""Spark by default does not have Stratified folding so extending cross validator"""
def stratify_data(self, dataset):
"""Returns an array of dataframes with the same ratio of passes and failures. Currently only supports binary classification problems."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StratifiedCrossValidator:
"""Spark by default does not have Stratified folding so extending cross validator"""
def stratify_data(self, dataset):
"""Returns an array of dataframes with the same ratio of passes and failures. Currently only supports binary classification problems."""
epm = s... | the_stack_v2_python_sparse | pyspark/common/stratified_cross_validator.py | jazz0829/dsci-contractprediction | train | 1 |
b238a7ba5b1bad0317e54fe8f2d7d971fdc9ed76 | [
"try:\n user = UserModel.get_user_by_id(id)\nexcept:\n return ({'msg': SERVER_ERROR}, 500)\nif user:\n return (user_schema.dump(user), 200)\nreturn ({'msg': NOT_FOUND_ERROR.format(id)}, 404)",
"try:\n user = UserModel.get_user_by_id(id)\nexcept:\n return {'msg': SERVER_ERROR}\nif user:\n user.de... | <|body_start_0|>
try:
user = UserModel.get_user_by_id(id)
except:
return ({'msg': SERVER_ERROR}, 500)
if user:
return (user_schema.dump(user), 200)
return ({'msg': NOT_FOUND_ERROR.format(id)}, 404)
<|end_body_0|>
<|body_start_1|>
try:
... | Resource for user. | User | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
"""Resource for user."""
def get(cls, id: int):
"""Endpoint for getting user details."""
<|body_0|>
def delete(cls, id: int):
"""Endpoint for deleting user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
user = UserModel.... | stack_v2_sparse_classes_36k_train_001365 | 4,070 | no_license | [
{
"docstring": "Endpoint for getting user details.",
"name": "get",
"signature": "def get(cls, id: int)"
},
{
"docstring": "Endpoint for deleting user.",
"name": "delete",
"signature": "def delete(cls, id: int)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001186 | Implement the Python class `User` described below.
Class description:
Resource for user.
Method signatures and docstrings:
- def get(cls, id: int): Endpoint for getting user details.
- def delete(cls, id: int): Endpoint for deleting user. | Implement the Python class `User` described below.
Class description:
Resource for user.
Method signatures and docstrings:
- def get(cls, id: int): Endpoint for getting user details.
- def delete(cls, id: int): Endpoint for deleting user.
<|skeleton|>
class User:
"""Resource for user."""
def get(cls, id: in... | 6f8dfbff5f06bead56b2c56122a533d1bd148c2b | <|skeleton|>
class User:
"""Resource for user."""
def get(cls, id: int):
"""Endpoint for getting user details."""
<|body_0|>
def delete(cls, id: int):
"""Endpoint for deleting user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class User:
"""Resource for user."""
def get(cls, id: int):
"""Endpoint for getting user details."""
try:
user = UserModel.get_user_by_id(id)
except:
return ({'msg': SERVER_ERROR}, 500)
if user:
return (user_schema.dump(user), 200)
ret... | the_stack_v2_python_sparse | section13/resources/user.py | ExperimentalHypothesis/flask-restful-web-api | train | 0 |
8d4fa8356881310e995a0e73a4c5044b69db2198 | [
"if len(nums) == 0:\n return 0\nif len(nums) <= 2:\n return max(nums)\nreturn max(self.rec_rob(nums[:-1]), self.rec_rob(nums[:-2]) + nums[len(nums) - 1])",
"if len(nums) == 0:\n return 0\nif len(nums) <= 2:\n return max(nums)\na = nums[0]\nb = nums[1]\nfor i in range(len(nums) - 2):\n tmp = max(b, ... | <|body_start_0|>
if len(nums) == 0:
return 0
if len(nums) <= 2:
return max(nums)
return max(self.rec_rob(nums[:-1]), self.rec_rob(nums[:-2]) + nums[len(nums) - 1])
<|end_body_0|>
<|body_start_1|>
if len(nums) == 0:
return 0
if len(nums) <= 2:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rec_rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def dp_rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == 0:
return 0
if len... | stack_v2_sparse_classes_36k_train_001366 | 967 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rec_rob",
"signature": "def rec_rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "dp_rob",
"signature": "def dp_rob(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rec_rob(self, nums): :type nums: List[int] :rtype: int
- def dp_rob(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rec_rob(self, nums): :type nums: List[int] :rtype: int
- def dp_rob(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rec_rob(self, nums):... | e93f93fd58d1945708d6aa300dcbcd17d0708274 | <|skeleton|>
class Solution:
def rec_rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def dp_rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rec_rob(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 0:
return 0
if len(nums) <= 2:
return max(nums)
return max(self.rec_rob(nums[:-1]), self.rec_rob(nums[:-2]) + nums[len(nums) - 1])
def dp_rob(self, nums):
... | the_stack_v2_python_sparse | LeetCode/Python/DP/198. House Robber.py | Alfonsxh/LeetCode-Challenge-python | train | 1 | |
2d43ee9133a47b53caef7d151d3fb3622d3d8ba1 | [
"self.test_data_true = dictionary_class_helper_true()\nself.test_data_true.set_action(2)\nself.test_data_false = dictionary_class_helper_false()\nself.sock_conn = socketconnection.SocketConnection(self.test_data_true.car_id)\nself.valid_dict = self.test_data_true.get_socket_dictionary()\nself.invalid_dict = self.te... | <|body_start_0|>
self.test_data_true = dictionary_class_helper_true()
self.test_data_true.set_action(2)
self.test_data_false = dictionary_class_helper_false()
self.sock_conn = socketconnection.SocketConnection(self.test_data_true.car_id)
self.valid_dict = self.test_data_true.get_... | As :class:TestSocketResponseAction1`, but for action 2 (validating a face recognition) Test a dictionary that has all but one parameter correct. These should return a dictionary with None, which is returned to the test as False. i.e., invalid booking details. | TestSocketResponseAction2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSocketResponseAction2:
"""As :class:TestSocketResponseAction1`, but for action 2 (validating a face recognition) Test a dictionary that has all but one parameter correct. These should return a dictionary with None, which is returned to the test as False. i.e., invalid booking details."""
... | stack_v2_sparse_classes_36k_train_001367 | 23,291 | no_license | [
{
"docstring": "It is necessary to instantiate the data classes and extract the relevant dictionaries. This test suite also requires a socket connection.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test an incorrect car_id",
"name": "test_a2_invalid_car_id",
"sig... | 6 | null | Implement the Python class `TestSocketResponseAction2` described below.
Class description:
As :class:TestSocketResponseAction1`, but for action 2 (validating a face recognition) Test a dictionary that has all but one parameter correct. These should return a dictionary with None, which is returned to the test as False.... | Implement the Python class `TestSocketResponseAction2` described below.
Class description:
As :class:TestSocketResponseAction1`, but for action 2 (validating a face recognition) Test a dictionary that has all but one parameter correct. These should return a dictionary with None, which is returned to the test as False.... | 8f68cc2a6ca568e803a6bfea49a452a5b0c1a2cf | <|skeleton|>
class TestSocketResponseAction2:
"""As :class:TestSocketResponseAction1`, but for action 2 (validating a face recognition) Test a dictionary that has all but one parameter correct. These should return a dictionary with None, which is returned to the test as False. i.e., invalid booking details."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSocketResponseAction2:
"""As :class:TestSocketResponseAction1`, but for action 2 (validating a face recognition) Test a dictionary that has all but one parameter correct. These should return a dictionary with None, which is returned to the test as False. i.e., invalid booking details."""
def setUp(se... | the_stack_v2_python_sparse | AgentPi/agenttesting.py | JiewenGuan/Iot-Carshare | train | 0 |
4181eddc971c53140fc5014438b061fafec7609e | [
"if self.available():\n data = json_body(self.request)\n version = data.get('version')\n if version and version != 'current':\n document = Versioner(self.context).retrieve(version)\n else:\n document = self.context\n if hasattr(document, '_v_bumblebee_last_converted'):\n delattr(... | <|body_start_0|>
if self.available():
data = json_body(self.request)
version = data.get('version')
if version and version != 'current':
document = Versioner(self.context).retrieve(version)
else:
document = self.context
i... | Sometimes creating a bumblebee preview fails and in rare circumstances this leaves bumblebee in an inconsistent state (GEVER-side). It also may happen that the bumblebee service is down temporarily and the documents can't be registered. These documents won't show a preview until the document is modified and thus trigge... | RevivePreview | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RevivePreview:
"""Sometimes creating a bumblebee preview fails and in rare circumstances this leaves bumblebee in an inconsistent state (GEVER-side). It also may happen that the bumblebee service is down temporarily and the documents can't be registered. These documents won't show a preview until... | stack_v2_sparse_classes_36k_train_001368 | 2,864 | no_license | [
{
"docstring": "Handles the reviving process.",
"name": "__call__",
"signature": "def __call__(self)"
},
{
"docstring": "Checks if reviving is available for the current object",
"name": "available",
"signature": "def available(self)"
}
] | 2 | null | Implement the Python class `RevivePreview` described below.
Class description:
Sometimes creating a bumblebee preview fails and in rare circumstances this leaves bumblebee in an inconsistent state (GEVER-side). It also may happen that the bumblebee service is down temporarily and the documents can't be registered. The... | Implement the Python class `RevivePreview` described below.
Class description:
Sometimes creating a bumblebee preview fails and in rare circumstances this leaves bumblebee in an inconsistent state (GEVER-side). It also may happen that the bumblebee service is down temporarily and the documents can't be registered. The... | a01bec6c00d203c21a1b0449f8d489d0033c02b7 | <|skeleton|>
class RevivePreview:
"""Sometimes creating a bumblebee preview fails and in rare circumstances this leaves bumblebee in an inconsistent state (GEVER-side). It also may happen that the bumblebee service is down temporarily and the documents can't be registered. These documents won't show a preview until... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RevivePreview:
"""Sometimes creating a bumblebee preview fails and in rare circumstances this leaves bumblebee in an inconsistent state (GEVER-side). It also may happen that the bumblebee service is down temporarily and the documents can't be registered. These documents won't show a preview until the document... | the_stack_v2_python_sparse | opengever/bumblebee/browser/revive_preview.py | 4teamwork/opengever.core | train | 19 |
f3d0e1bb4c192f4a35051562027f0c6b72d4d45d | [
"colors = {'ORG': '#7aecec', 'PRODUCT': '#bfeeb7', 'GPE': '#feca74', 'LOC': '#ff9561', 'PERSON': '#aa9cfc', 'NORP': '#c887fb', 'FACILITY': '#9cc9cc', 'EVENT': '#ffeb80', 'LAW': '#ff8197', 'LANGUAGE': '#ff8197', 'WORK_OF_ART': '#f0d0ff', 'DATE': '#bfe1d9', 'TIME': '#bfe1d9', 'MONEY': '#e4e7d2', 'QUANTITY': '#e4e7d2'... | <|body_start_0|>
colors = {'ORG': '#7aecec', 'PRODUCT': '#bfeeb7', 'GPE': '#feca74', 'LOC': '#ff9561', 'PERSON': '#aa9cfc', 'NORP': '#c887fb', 'FACILITY': '#9cc9cc', 'EVENT': '#ffeb80', 'LAW': '#ff8197', 'LANGUAGE': '#ff8197', 'WORK_OF_ART': '#f0d0ff', 'DATE': '#bfe1d9', 'TIME': '#bfe1d9', 'MONEY': '#e4e7d2', '... | Render named entities as HTML. | EntityRenderer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityRenderer:
"""Render named entities as HTML."""
def __init__(self, options={}):
"""Initialise dependency renderer. options (dict): Visualiser-specific options (colors, ents)"""
<|body_0|>
def render(self, parsed, page=False, minify=False):
"""Render complete... | stack_v2_sparse_classes_36k_train_001369 | 9,566 | permissive | [
{
"docstring": "Initialise dependency renderer. options (dict): Visualiser-specific options (colors, ents)",
"name": "__init__",
"signature": "def __init__(self, options={})"
},
{
"docstring": "Render complete markup. parsed (list): Dependency parses to render. page (bool): Render parses wrapped... | 3 | stack_v2_sparse_classes_30k_train_003818 | Implement the Python class `EntityRenderer` described below.
Class description:
Render named entities as HTML.
Method signatures and docstrings:
- def __init__(self, options={}): Initialise dependency renderer. options (dict): Visualiser-specific options (colors, ents)
- def render(self, parsed, page=False, minify=Fa... | Implement the Python class `EntityRenderer` described below.
Class description:
Render named entities as HTML.
Method signatures and docstrings:
- def __init__(self, options={}): Initialise dependency renderer. options (dict): Visualiser-specific options (colors, ents)
- def render(self, parsed, page=False, minify=Fa... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class EntityRenderer:
"""Render named entities as HTML."""
def __init__(self, options={}):
"""Initialise dependency renderer. options (dict): Visualiser-specific options (colors, ents)"""
<|body_0|>
def render(self, parsed, page=False, minify=False):
"""Render complete... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EntityRenderer:
"""Render named entities as HTML."""
def __init__(self, options={}):
"""Initialise dependency renderer. options (dict): Visualiser-specific options (colors, ents)"""
colors = {'ORG': '#7aecec', 'PRODUCT': '#bfeeb7', 'GPE': '#feca74', 'LOC': '#ff9561', 'PERSON': '#aa9cfc', ... | the_stack_v2_python_sparse | Spacy/source2.7/spacy/displacy/render.py | ryfeus/lambda-packs | train | 1,283 |
1617e9435ed4a4ff6c6c662217cc9f9648ff7831 | [
"self.total_bytes_tiered = total_bytes_tiered\nself.admitted_time_usecs = admitted_time_usecs\nself.end_time_usecs = end_time_usecs\nself.permit_grant_time_usecs = permit_grant_time_usecs\nself.queue_duration_usecs = queue_duration_usecs\nself.start_time_usecs = start_time_usecs\nself.time_taken_usecs = time_taken_... | <|body_start_0|>
self.total_bytes_tiered = total_bytes_tiered
self.admitted_time_usecs = admitted_time_usecs
self.end_time_usecs = end_time_usecs
self.permit_grant_time_usecs = permit_grant_time_usecs
self.queue_duration_usecs = queue_duration_usecs
self.start_time_usecs ... | Implementation of the 'BackupSourceStats' model. Specifies statistics about a Backup task in a Protection Job Run. Specifies statistics for one backup task. One backup task is used to backup on Protection Source. This structure is also used to aggregate stats of a Backup tasks in a Protection Job Run. Attributes: total... | BackupSourceStats | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackupSourceStats:
"""Implementation of the 'BackupSourceStats' model. Specifies statistics about a Backup task in a Protection Job Run. Specifies statistics for one backup task. One backup task is used to backup on Protection Source. This structure is also used to aggregate stats of a Backup tas... | stack_v2_sparse_classes_36k_train_001370 | 8,122 | permissive | [
{
"docstring": "Constructor for the BackupSourceStats class",
"name": "__init__",
"signature": "def __init__(self, total_bytes_tiered=None, admitted_time_usecs=None, end_time_usecs=None, permit_grant_time_usecs=None, queue_duration_usecs=None, start_time_usecs=None, time_taken_usecs=None, total_bytes_re... | 2 | null | Implement the Python class `BackupSourceStats` described below.
Class description:
Implementation of the 'BackupSourceStats' model. Specifies statistics about a Backup task in a Protection Job Run. Specifies statistics for one backup task. One backup task is used to backup on Protection Source. This structure is also ... | Implement the Python class `BackupSourceStats` described below.
Class description:
Implementation of the 'BackupSourceStats' model. Specifies statistics about a Backup task in a Protection Job Run. Specifies statistics for one backup task. One backup task is used to backup on Protection Source. This structure is also ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class BackupSourceStats:
"""Implementation of the 'BackupSourceStats' model. Specifies statistics about a Backup task in a Protection Job Run. Specifies statistics for one backup task. One backup task is used to backup on Protection Source. This structure is also used to aggregate stats of a Backup tas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BackupSourceStats:
"""Implementation of the 'BackupSourceStats' model. Specifies statistics about a Backup task in a Protection Job Run. Specifies statistics for one backup task. One backup task is used to backup on Protection Source. This structure is also used to aggregate stats of a Backup tasks in a Prote... | the_stack_v2_python_sparse | cohesity_management_sdk/models/backup_source_stats.py | cohesity/management-sdk-python | train | 24 |
ef2887efb6068cbb4f2cd26af992a776e5dad166 | [
"params = clean_locals(locals())\nendpoint = 'homepageleaders'\nr = self.request(endpoint, params)\ndf = self.process_response(r, idx_data, 'resultSets')\nreturn df",
"params = clean_locals(locals())\nendpoint = 'homepagev2'\nr = self.request(endpoint, params)\ndf = self.process_response(r, idx_data, 'resultSets'... | <|body_start_0|>
params = clean_locals(locals())
endpoint = 'homepageleaders'
r = self.request(endpoint, params)
df = self.process_response(r, idx_data, 'resultSets')
return df
<|end_body_0|>
<|body_start_1|>
params = clean_locals(locals())
endpoint = 'homepagev2... | Homepage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Homepage:
def leaders(self, idx_data, league_id=enums.LeagueID.Default, stat_category=enums.StatCategory.Default, season=enums.Season.Default, season_type=enums.SeasonType.Default, player_or_team=enums.PlayerOrTeam.Default, game_scope=enums.GameScope.Default, player_scope=enums.PlayerScope.Defau... | stack_v2_sparse_classes_36k_train_001371 | 7,389 | permissive | [
{
"docstring": "Get top 5 players/teams by a particular stat. :param idx_data: the index to retrieve data from json. :type idx_data: int :param league_id: league to filter for. :type league_id: nba.enums.LeagueID :param stat_category: Stat to sort leaders table by. :type stat_category: nba.enums.StatCategory :p... | 3 | stack_v2_sparse_classes_30k_test_001036 | Implement the Python class `Homepage` described below.
Class description:
Implement the Homepage class.
Method signatures and docstrings:
- def leaders(self, idx_data, league_id=enums.LeagueID.Default, stat_category=enums.StatCategory.Default, season=enums.Season.Default, season_type=enums.SeasonType.Default, player_... | Implement the Python class `Homepage` described below.
Class description:
Implement the Homepage class.
Method signatures and docstrings:
- def leaders(self, idx_data, league_id=enums.LeagueID.Default, stat_category=enums.StatCategory.Default, season=enums.Season.Default, season_type=enums.SeasonType.Default, player_... | 87feec5fc8ff6654fdb65229a047e0ff3023a9ff | <|skeleton|>
class Homepage:
def leaders(self, idx_data, league_id=enums.LeagueID.Default, stat_category=enums.StatCategory.Default, season=enums.Season.Default, season_type=enums.SeasonType.Default, player_or_team=enums.PlayerOrTeam.Default, game_scope=enums.GameScope.Default, player_scope=enums.PlayerScope.Defau... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Homepage:
def leaders(self, idx_data, league_id=enums.LeagueID.Default, stat_category=enums.StatCategory.Default, season=enums.Season.Default, season_type=enums.SeasonType.Default, player_or_team=enums.PlayerOrTeam.Default, game_scope=enums.GameScope.Default, player_scope=enums.PlayerScope.Default):
"... | the_stack_v2_python_sparse | nba/endpoints/homepage.py | rozzac90/nba | train | 1 | |
eb48736fcd35a984ba57d8c6a1c89bf58a71b006 | [
"n = len(heights)\nif n <= 0:\n return 0\nif n == 1:\n return heights[0]\nstack = []\nres = heights[0]\nfor i in range(n + 1):\n while len(stack) > 0 and (i >= n or heights[stack[-1]] >= heights[i]):\n top = stack[-1]\n stack.pop(-1)\n area = (i - 1 - (stack[-1] if len(stack) > 0 else ... | <|body_start_0|>
n = len(heights)
if n <= 0:
return 0
if n == 1:
return heights[0]
stack = []
res = heights[0]
for i in range(n + 1):
while len(stack) > 0 and (i >= n or heights[stack[-1]] >= heights[i]):
top = stack[-1]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_0|>
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(heights... | stack_v2_sparse_classes_36k_train_001372 | 1,400 | no_license | [
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, heights)"
},
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalRectangle",
"signature": "def maximalRectangle(self, matrix)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
<|skeleton|>
class ... | 176cc1db3291843fb068f06d0180766dd8c3122c | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_0|>
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
n = len(heights)
if n <= 0:
return 0
if n == 1:
return heights[0]
stack = []
res = heights[0]
for i in range(n + 1):
while l... | the_stack_v2_python_sparse | 2019/stack/largest_rectangle_in_histogram_84.py | yehongyu/acode | train | 0 | |
f33f764617eb62dc99f6da5d7e4f03a484289520 | [
"d = departmentmanage(self.driver)\nd.open_departmentmanage()\nself.assertEqual(d.verify(), True)\nd.delete()\nself.assertEqual(d.reason(), '请选择一条数据')\nfunction.screenshot(self.driver, 'department_unselect.jpg')",
"d = departmentmanage(self.driver)\nd.open_departmentmanage()\nself.assertEqual(d.verify(), True)\nd... | <|body_start_0|>
d = departmentmanage(self.driver)
d.open_departmentmanage()
self.assertEqual(d.verify(), True)
d.delete()
self.assertEqual(d.reason(), '请选择一条数据')
function.screenshot(self.driver, 'department_unselect.jpg')
<|end_body_0|>
<|body_start_1|>
d = depa... | Test030_Deparment_List_Error | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test030_Deparment_List_Error:
def test_unselect(self):
"""不选择任何部门"""
<|body_0|>
def test_multiselect(self):
"""选择两个部门"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d = departmentmanage(self.driver)
d.open_departmentmanage()
self.as... | stack_v2_sparse_classes_36k_train_001373 | 966 | no_license | [
{
"docstring": "不选择任何部门",
"name": "test_unselect",
"signature": "def test_unselect(self)"
},
{
"docstring": "选择两个部门",
"name": "test_multiselect",
"signature": "def test_multiselect(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004925 | Implement the Python class `Test030_Deparment_List_Error` described below.
Class description:
Implement the Test030_Deparment_List_Error class.
Method signatures and docstrings:
- def test_unselect(self): 不选择任何部门
- def test_multiselect(self): 选择两个部门 | Implement the Python class `Test030_Deparment_List_Error` described below.
Class description:
Implement the Test030_Deparment_List_Error class.
Method signatures and docstrings:
- def test_unselect(self): 不选择任何部门
- def test_multiselect(self): 选择两个部门
<|skeleton|>
class Test030_Deparment_List_Error:
def test_unse... | 6f42c25249fc642cecc270578a180820988d45b5 | <|skeleton|>
class Test030_Deparment_List_Error:
def test_unselect(self):
"""不选择任何部门"""
<|body_0|>
def test_multiselect(self):
"""选择两个部门"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test030_Deparment_List_Error:
def test_unselect(self):
"""不选择任何部门"""
d = departmentmanage(self.driver)
d.open_departmentmanage()
self.assertEqual(d.verify(), True)
d.delete()
self.assertEqual(d.reason(), '请选择一条数据')
function.screenshot(self.driver, 'depar... | the_stack_v2_python_sparse | GlxssLive_web/TestCase/Manage_Department/Test030_department_list_error.py | rrmiracle/GlxssLive | train | 0 | |
1d7f9d9cff65c9a641e48dde27800fd1c2dbd801 | [
"\"\"\"\n s = lcoa\n dict = [\"lco\", \"lcoa\", \"coa\"]\n\n 代表input s的每個char位置(含以前)的string是否在word dict內.\n [True, False, False, True, True]\n\n 一定要測試 ok[j] 因為這代表著ok[j]以前的字有沒有中,\n 如果沒有,則即使s[j:i]中也不能算,因為之前的字為孤魂野鬼,沒中.\n \"\"\"\nfrom __builtin__ import xrange\nok = [Tru... | <|body_start_0|>
"""
s = lcoa
dict = ["lco", "lcoa", "coa"]
代表input s的每個char位置(含以前)的string是否在word dict內.
[True, False, False, True, True]
一定要測試 ok[j] 因為這代表著ok[j]以前的字有沒有中,
如果沒有,則即使s[j:i]中也不能算,因為之前的字為孤魂野鬼,沒中.
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def rewrite(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
def rewrite2(self, s, wordDict):
... | stack_v2_sparse_classes_36k_train_001374 | 3,090 | no_license | [
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
},
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "rewrite",
"signature": "def rewrite(self, s, wordDict)"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def rewrite(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def rewrite(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def ... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def rewrite(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
def rewrite2(self, s, wordDict):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
"""
s = lcoa
dict = ["lco", "lcoa", "coa"]
代表input s的每個char位置(含以前)的string是否在word dict內.
[True, False, False, True, True]
... | the_stack_v2_python_sparse | co_fb/139_Word_Break.py | vsdrun/lc_public | train | 6 | |
ddd674a2949a18620c22f63ed1cf34bf921ef3e1 | [
"super(PaintingGenreBot, self).__init__()\nself.use_from_page = False\nself.genres = {'Q1400853': 'Q134307', 'Q2414609': 'Q2864737', 'Q214127': 'Q1047337', 'Q107425': 'Q191163', 'Q29969011': 'Q1935974', 'Q333357': 'Q128115', 'Q162150': 'Q128115', 'Q18535': 'Q2839016', 'Q11766730': 'Q2839016', 'Q11766734': 'Q158607'... | <|body_start_0|>
super(PaintingGenreBot, self).__init__()
self.use_from_page = False
self.genres = {'Q1400853': 'Q134307', 'Q2414609': 'Q2864737', 'Q214127': 'Q1047337', 'Q107425': 'Q191163', 'Q29969011': 'Q1935974', 'Q333357': 'Q128115', 'Q162150': 'Q128115', 'Q18535': 'Q2839016', 'Q11766730': ... | A bot to normalize painting genre. Uses the WikidataBot for the basics. | PaintingGenreBot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaintingGenreBot:
"""A bot to normalize painting genre. Uses the WikidataBot for the basics."""
def __init__(self):
"""No arguments, bot makes it's own generator based on the genres"""
<|body_0|>
def getGenerator(self):
"""Get a generator of paintings that have o... | stack_v2_sparse_classes_36k_train_001375 | 3,923 | no_license | [
{
"docstring": "No arguments, bot makes it's own generator based on the genres",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Get a generator of paintings that have one of the replacable genres :return: A generator that yields ItemPages",
"name": "getGenerator",
... | 3 | stack_v2_sparse_classes_30k_train_017035 | Implement the Python class `PaintingGenreBot` described below.
Class description:
A bot to normalize painting genre. Uses the WikidataBot for the basics.
Method signatures and docstrings:
- def __init__(self): No arguments, bot makes it's own generator based on the genres
- def getGenerator(self): Get a generator of ... | Implement the Python class `PaintingGenreBot` described below.
Class description:
A bot to normalize painting genre. Uses the WikidataBot for the basics.
Method signatures and docstrings:
- def __init__(self): No arguments, bot makes it's own generator based on the genres
- def getGenerator(self): Get a generator of ... | 99a96e49cfe6b2d3151da7ad5469792d80171be3 | <|skeleton|>
class PaintingGenreBot:
"""A bot to normalize painting genre. Uses the WikidataBot for the basics."""
def __init__(self):
"""No arguments, bot makes it's own generator based on the genres"""
<|body_0|>
def getGenerator(self):
"""Get a generator of paintings that have o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaintingGenreBot:
"""A bot to normalize painting genre. Uses the WikidataBot for the basics."""
def __init__(self):
"""No arguments, bot makes it's own generator based on the genres"""
super(PaintingGenreBot, self).__init__()
self.use_from_page = False
self.genres = {'Q140... | the_stack_v2_python_sparse | bot/wikidata/painting_genre_normalization.py | multichill/toollabs | train | 18 |
5c152ad5d16c4196dbb6ff37aa3979e6c7cdbc41 | [
"queryset = Sight.objects.filter(is_valid=True, is_top=True)\ntry:\n p = Paginator(queryset, 20)\n page_obj = p.page(1)\n data = serializers.SightListSerializer(page_obj).to_dict()\n cache.set(constants.INDEX_SIGHT_TOP_KEY, json.dumps(data), constants.INDEX_SIGHT_TIMEOUT)\nexcept EmptyPage as e:\n pr... | <|body_start_0|>
queryset = Sight.objects.filter(is_valid=True, is_top=True)
try:
p = Paginator(queryset, 20)
page_obj = p.page(1)
data = serializers.SightListSerializer(page_obj).to_dict()
cache.set(constants.INDEX_SIGHT_TOP_KEY, json.dumps(data), constan... | 景点基础信息 | SightAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SightAdmin:
"""景点基础信息"""
def cache_top_sight(self):
"""缓存精选景点"""
<|body_0|>
def cache_hot_sight(self):
"""缓存热门景点"""
<|body_1|>
def save_form(self, request, form, change):
"""新增\\修改时缓存数据"""
<|body_2|>
def delete_model(self, reques... | stack_v2_sparse_classes_36k_train_001376 | 3,222 | no_license | [
{
"docstring": "缓存精选景点",
"name": "cache_top_sight",
"signature": "def cache_top_sight(self)"
},
{
"docstring": "缓存热门景点",
"name": "cache_hot_sight",
"signature": "def cache_hot_sight(self)"
},
{
"docstring": "新增\\\\修改时缓存数据",
"name": "save_form",
"signature": "def save_form... | 4 | null | Implement the Python class `SightAdmin` described below.
Class description:
景点基础信息
Method signatures and docstrings:
- def cache_top_sight(self): 缓存精选景点
- def cache_hot_sight(self): 缓存热门景点
- def save_form(self, request, form, change): 新增\\修改时缓存数据
- def delete_model(self, request, obj): 物理删除时,更新redis缓存 | Implement the Python class `SightAdmin` described below.
Class description:
景点基础信息
Method signatures and docstrings:
- def cache_top_sight(self): 缓存精选景点
- def cache_hot_sight(self): 缓存热门景点
- def save_form(self, request, form, change): 新增\\修改时缓存数据
- def delete_model(self, request, obj): 物理删除时,更新redis缓存
<|skeleton|>
c... | 499c43bc9bdb12f940ca13d8881bb0020dedf545 | <|skeleton|>
class SightAdmin:
"""景点基础信息"""
def cache_top_sight(self):
"""缓存精选景点"""
<|body_0|>
def cache_hot_sight(self):
"""缓存热门景点"""
<|body_1|>
def save_form(self, request, form, change):
"""新增\\修改时缓存数据"""
<|body_2|>
def delete_model(self, reques... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SightAdmin:
"""景点基础信息"""
def cache_top_sight(self):
"""缓存精选景点"""
queryset = Sight.objects.filter(is_valid=True, is_top=True)
try:
p = Paginator(queryset, 20)
page_obj = p.page(1)
data = serializers.SightListSerializer(page_obj).to_dict()
... | the_stack_v2_python_sparse | sight/admin.py | GlobalYZ/recruitmentDjango | train | 1 |
1bca4912bbdb05d7f7b9e81843528bb279737402 | [
"self.antall_ansatte_field = antall_ansatte_field\nself.antall_ansatte_field_specified = antall_ansatte_field_specified\nself.telefon_field = telefon_field\nself.telefon_field_specified = telefon_field_specified\nself.telefax_field = telefax_field\nself.telefax_field_specified = telefax_field_specified\nself.stifte... | <|body_start_0|>
self.antall_ansatte_field = antall_ansatte_field
self.antall_ansatte_field_specified = antall_ansatte_field_specified
self.telefon_field = telefon_field
self.telefon_field_specified = telefon_field_specified
self.telefax_field = telefax_field
self.telefax... | Implementation of the 'AvdelingData' model. TODO: type model description here. Attributes: antall_ansatte_field (int): TODO: type description here. antall_ansatte_field_specified (bool): TODO: type description here. telefon_field (int): TODO: type description here. telefon_field_specified (bool): TODO: type description... | AvdelingData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AvdelingData:
"""Implementation of the 'AvdelingData' model. TODO: type model description here. Attributes: antall_ansatte_field (int): TODO: type description here. antall_ansatte_field_specified (bool): TODO: type description here. telefon_field (int): TODO: type description here. telefon_field_... | stack_v2_sparse_classes_36k_train_001377 | 7,158 | permissive | [
{
"docstring": "Constructor for the AvdelingData class",
"name": "__init__",
"signature": "def __init__(self, antall_ansatte_field=None, antall_ansatte_field_specified=None, telefon_field=None, telefon_field_specified=None, telefax_field=None, telefax_field_specified=None, stiftet_dato_field=None, brans... | 2 | null | Implement the Python class `AvdelingData` described below.
Class description:
Implementation of the 'AvdelingData' model. TODO: type model description here. Attributes: antall_ansatte_field (int): TODO: type description here. antall_ansatte_field_specified (bool): TODO: type description here. telefon_field (int): TODO... | Implement the Python class `AvdelingData` described below.
Class description:
Implementation of the 'AvdelingData' model. TODO: type model description here. Attributes: antall_ansatte_field (int): TODO: type description here. antall_ansatte_field_specified (bool): TODO: type description here. telefon_field (int): TODO... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class AvdelingData:
"""Implementation of the 'AvdelingData' model. TODO: type model description here. Attributes: antall_ansatte_field (int): TODO: type description here. antall_ansatte_field_specified (bool): TODO: type description here. telefon_field (int): TODO: type description here. telefon_field_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AvdelingData:
"""Implementation of the 'AvdelingData' model. TODO: type model description here. Attributes: antall_ansatte_field (int): TODO: type description here. antall_ansatte_field_specified (bool): TODO: type description here. telefon_field (int): TODO: type description here. telefon_field_specified (bo... | the_stack_v2_python_sparse | idfy_rest_client/models/avdeling_data.py | dealflowteam/Idfy | train | 0 |
d3d6e1a3f05607b97e62f2ce8ac2e225cf403f18 | [
"self._alphabet = [l.upper() for l in alphabet]\nself._letter_to_id = dict(((letter, id) for id, letter in enumerate(self._alphabet)))\nself.encoding_size = len(self._alphabet)",
"onehot = numpy.zeros(self.encoding_size, dtype=float)\nonehot[self._letter_to_id[residue]] = 1\nreturn onehot"
] | <|body_start_0|>
self._alphabet = [l.upper() for l in alphabet]
self._letter_to_id = dict(((letter, id) for id, letter in enumerate(self._alphabet)))
self.encoding_size = len(self._alphabet)
<|end_body_0|>
<|body_start_1|>
onehot = numpy.zeros(self.encoding_size, dtype=float)
on... | Residue identity (one-hot) encoder. Attributes: encoding_size: (int) The number of encoding dimensions for a single residue. | ResidueIdentityEncoder | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidueIdentityEncoder:
"""Residue identity (one-hot) encoder. Attributes: encoding_size: (int) The number of encoding dimensions for a single residue."""
def __init__(self, alphabet):
"""Constructor. Args: alphabet: (seq<char>) The alphabet of valid tokens for the sequence; e.g., th... | stack_v2_sparse_classes_36k_train_001378 | 2,702 | permissive | [
{
"docstring": "Constructor. Args: alphabet: (seq<char>) The alphabet of valid tokens for the sequence; e.g., the 20x 1-letter residue codes for standard peptides.",
"name": "__init__",
"signature": "def __init__(self, alphabet)"
},
{
"docstring": "Encodes a single residue as a one hot identity ... | 2 | null | Implement the Python class `ResidueIdentityEncoder` described below.
Class description:
Residue identity (one-hot) encoder. Attributes: encoding_size: (int) The number of encoding dimensions for a single residue.
Method signatures and docstrings:
- def __init__(self, alphabet): Constructor. Args: alphabet: (seq<char>... | Implement the Python class `ResidueIdentityEncoder` described below.
Class description:
Residue identity (one-hot) encoder. Attributes: encoding_size: (int) The number of encoding dimensions for a single residue.
Method signatures and docstrings:
- def __init__(self, alphabet): Constructor. Args: alphabet: (seq<char>... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ResidueIdentityEncoder:
"""Residue identity (one-hot) encoder. Attributes: encoding_size: (int) The number of encoding dimensions for a single residue."""
def __init__(self, alphabet):
"""Constructor. Args: alphabet: (seq<char>) The alphabet of valid tokens for the sequence; e.g., th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResidueIdentityEncoder:
"""Residue identity (one-hot) encoder. Attributes: encoding_size: (int) The number of encoding dimensions for a single residue."""
def __init__(self, alphabet):
"""Constructor. Args: alphabet: (seq<char>) The alphabet of valid tokens for the sequence; e.g., the 20x 1-lette... | the_stack_v2_python_sparse | aav/util/residue_encoding.py | Jimmy-INL/google-research | train | 1 |
6727d0823ebc4b00846bc7eb6387aac3611391a9 | [
"if name is None:\n return jsonify(responses.missing_parameters)\nsensor = Sensor.objects(name=name).first()\nif sensor is None:\n return jsonify(responses.invalid_uuid)\ntags_owned = [{'name': tag.name, 'value': tag.value} for tag in sensor.tags]\nmetadata = Sensor._get_collection().find({'name': name}, {'me... | <|body_start_0|>
if name is None:
return jsonify(responses.missing_parameters)
sensor = Sensor.objects(name=name).first()
if sensor is None:
return jsonify(responses.invalid_uuid)
tags_owned = [{'name': tag.name, 'value': tag.value} for tag in sensor.tags]
... | SensorService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SensorService:
def get(self, name):
"""Retrieve sensor details based on uuid specified Args as data: name : <name of sensor> Returns (JSON): { 'building': <name of building in which sensor is present>, 'name' : <sensor uuid>, 'tags' : tags_owned, 'metadata' : metadata, 'source_identifier... | stack_v2_sparse_classes_36k_train_001379 | 3,642 | permissive | [
{
"docstring": "Retrieve sensor details based on uuid specified Args as data: name : <name of sensor> Returns (JSON): { 'building': <name of building in which sensor is present>, 'name' : <sensor uuid>, 'tags' : tags_owned, 'metadata' : metadata, 'source_identifier' : str(sensor.source_identifier), 'source_name... | 2 | stack_v2_sparse_classes_30k_train_002566 | Implement the Python class `SensorService` described below.
Class description:
Implement the SensorService class.
Method signatures and docstrings:
- def get(self, name): Retrieve sensor details based on uuid specified Args as data: name : <name of sensor> Returns (JSON): { 'building': <name of building in which sens... | Implement the Python class `SensorService` described below.
Class description:
Implement the SensorService class.
Method signatures and docstrings:
- def get(self, name): Retrieve sensor details based on uuid specified Args as data: name : <name of sensor> Returns (JSON): { 'building': <name of building in which sens... | 53ba7519c56d46af1e32a77aab5cf1c5cd8143fc | <|skeleton|>
class SensorService:
def get(self, name):
"""Retrieve sensor details based on uuid specified Args as data: name : <name of sensor> Returns (JSON): { 'building': <name of building in which sensor is present>, 'name' : <sensor uuid>, 'tags' : tags_owned, 'metadata' : metadata, 'source_identifier... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SensorService:
def get(self, name):
"""Retrieve sensor details based on uuid specified Args as data: name : <name of sensor> Returns (JSON): { 'building': <name of building in which sensor is present>, 'name' : <sensor uuid>, 'tags' : tags_owned, 'metadata' : metadata, 'source_identifier' : str(sensor... | the_stack_v2_python_sparse | BuildingDepot-v3.2.8/buildingdepot/CentralService/app/rest_api/sensors/sensor.py | Entromorgan/GIoTTo | train | 0 | |
53c74e937fa9d39ce722aa19722214074ff54a8a | [
"n = len(matrix)\nfor i in range(n >> 1):\n size = n - (i << 1)\n tmp = matrix[i][i:i + size]\n for j in range(size):\n matrix[i][i + size - 1 - j] = matrix[i + j][i]\n for j in range(size):\n matrix[i + j][i] = matrix[n - 1 - i][i + j]\n for j in range(size):\n matrix[n - 1 - i]... | <|body_start_0|>
n = len(matrix)
for i in range(n >> 1):
size = n - (i << 1)
tmp = matrix[i][i:i + size]
for j in range(size):
matrix[i][i + size - 1 - j] = matrix[i + j][i]
for j in range(size):
matrix[i + j][i] = matrix[n ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p... | stack_v2_sparse_classes_36k_train_001380 | 2,222 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "rotate1",
"signature": "def rotate1(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate1(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate(self, matrix): :type matrix: List[List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate1(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate(self, matrix): :type matrix: List[List[... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def rotate1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
n = len(matrix)
for i in range(n >> 1):
size = n - (i << 1)
tmp = matrix[i][i:i + size]
for j in range(size)... | the_stack_v2_python_sparse | Matrix/q048_rotate_image.py | sevenhe716/LeetCode | train | 0 | |
9683ccf32244172450491a5094d50d75ffbc132d | [
"memo = {}\nl = len(A)\ncount = len(A[0])\n\ndef dfs(i, cur_state, ans):\n if i >= count:\n return ans\n if (i, cur_state) in memo:\n return memo[i, cur_state]\n next_state = ''.join([A[k][i] for k in range(l)])\n ans_temp = ans\n if all([ord(cur_state[k]) <= ord(next_state[k]) for k in... | <|body_start_0|>
memo = {}
l = len(A)
count = len(A[0])
def dfs(i, cur_state, ans):
if i >= count:
return ans
if (i, cur_state) in memo:
return memo[i, cur_state]
next_state = ''.join([A[k][i] for k in range(l)])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDeletionSize(self, A):
""":type A: List[str] :rtype: int"""
<|body_0|>
def minDeletionSize_1(self, A):
""":type A: List[str] :rtype: int 1352 ms"""
<|body_1|>
def minDeletionSize_2(self, A):
""":type A: List[str] :rtype: int 112m... | stack_v2_sparse_classes_36k_train_001381 | 5,098 | no_license | [
{
"docstring": ":type A: List[str] :rtype: int",
"name": "minDeletionSize",
"signature": "def minDeletionSize(self, A)"
},
{
"docstring": ":type A: List[str] :rtype: int 1352 ms",
"name": "minDeletionSize_1",
"signature": "def minDeletionSize_1(self, A)"
},
{
"docstring": ":type ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDeletionSize(self, A): :type A: List[str] :rtype: int
- def minDeletionSize_1(self, A): :type A: List[str] :rtype: int 1352 ms
- def minDeletionSize_2(self, A): :type A: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDeletionSize(self, A): :type A: List[str] :rtype: int
- def minDeletionSize_1(self, A): :type A: List[str] :rtype: int 1352 ms
- def minDeletionSize_2(self, A): :type A: L... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def minDeletionSize(self, A):
""":type A: List[str] :rtype: int"""
<|body_0|>
def minDeletionSize_1(self, A):
""":type A: List[str] :rtype: int 1352 ms"""
<|body_1|>
def minDeletionSize_2(self, A):
""":type A: List[str] :rtype: int 112m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDeletionSize(self, A):
""":type A: List[str] :rtype: int"""
memo = {}
l = len(A)
count = len(A[0])
def dfs(i, cur_state, ans):
if i >= count:
return ans
if (i, cur_state) in memo:
return memo[i, c... | the_stack_v2_python_sparse | DeleteColumnsToMakeSortedIII_HARD_960.py | 953250587/leetcode-python | train | 2 | |
292b6152824f32b105728d4c1dc9e42c666eca79 | [
"schema = TaskSchema()\ntask = Task.get_by_id(task_id)\nif not task:\n return (dict(status='fail', message=f'Task with id {task_id} not found'), 404)\ntask_data, errors = schema.dumps(task)\nif errors:\n return (dict(status='fail', message=errors), 500)\nreturn (dict(status='success', data=dict(task=json.load... | <|body_start_0|>
schema = TaskSchema()
task = Task.get_by_id(task_id)
if not task:
return (dict(status='fail', message=f'Task with id {task_id} not found'), 404)
task_data, errors = schema.dumps(task)
if errors:
return (dict(status='fail', message=errors),... | TaskDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskDetailView:
def get(self, task_id):
"""Getting individual task"""
<|body_0|>
def patch(self, task_id):
"""Update a single task"""
<|body_1|>
def delete(self, task_id):
"""Delete a single task"""
<|body_2|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_001382 | 2,917 | no_license | [
{
"docstring": "Getting individual task",
"name": "get",
"signature": "def get(self, task_id)"
},
{
"docstring": "Update a single task",
"name": "patch",
"signature": "def patch(self, task_id)"
},
{
"docstring": "Delete a single task",
"name": "delete",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_003296 | Implement the Python class `TaskDetailView` described below.
Class description:
Implement the TaskDetailView class.
Method signatures and docstrings:
- def get(self, task_id): Getting individual task
- def patch(self, task_id): Update a single task
- def delete(self, task_id): Delete a single task | Implement the Python class `TaskDetailView` described below.
Class description:
Implement the TaskDetailView class.
Method signatures and docstrings:
- def get(self, task_id): Getting individual task
- def patch(self, task_id): Update a single task
- def delete(self, task_id): Delete a single task
<|skeleton|>
class... | 015d70b8f79df6c1a5629add35767cee52f424f5 | <|skeleton|>
class TaskDetailView:
def get(self, task_id):
"""Getting individual task"""
<|body_0|>
def patch(self, task_id):
"""Update a single task"""
<|body_1|>
def delete(self, task_id):
"""Delete a single task"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskDetailView:
def get(self, task_id):
"""Getting individual task"""
schema = TaskSchema()
task = Task.get_by_id(task_id)
if not task:
return (dict(status='fail', message=f'Task with id {task_id} not found'), 404)
task_data, errors = schema.dumps(task)
... | the_stack_v2_python_sparse | app/controllers/task.py | MutegekiHenry/project-cohort-backend | train | 0 | |
dcad37a8101e1054ceb0404e5dcec42041a1f2a3 | [
"BaseController.__init__(self, veh_id, car_following_params, delay=time_delay, fail_safe=fail_safe, noise=noise)\nself.veh_id = veh_id\nself.k_d = k_d\nself.k_v = k_v\nself.k_c = k_c\nself.d_des = d_des\nself.v_des = v_des",
"lead_id = env.k.vehicle.get_leader(self.veh_id)\nif not lead_id:\n return self.max_ac... | <|body_start_0|>
BaseController.__init__(self, veh_id, car_following_params, delay=time_delay, fail_safe=fail_safe, noise=noise)
self.veh_id = veh_id
self.k_d = k_d
self.k_v = k_v
self.k_c = k_c
self.d_des = d_des
self.v_des = v_des
<|end_body_0|>
<|body_start_1|... | CFM controller. Usage ----- See BaseController for usage example. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : SumoCarFollowingParams see parent class k_d : float headway gain (default: 1) k_v : float gain on difference between lead velocity and current (default: 1) k_c :... | CFMController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CFMController:
"""CFM controller. Usage ----- See BaseController for usage example. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : SumoCarFollowingParams see parent class k_d : float headway gain (default: 1) k_v : float gain on difference between lea... | stack_v2_sparse_classes_36k_train_001383 | 17,548 | permissive | [
{
"docstring": "Instantiate a CFM controller.",
"name": "__init__",
"signature": "def __init__(self, veh_id, car_following_params, k_d=1, k_v=1, k_c=1, d_des=1, v_des=8, time_delay=0.0, noise=0, fail_safe=None)"
},
{
"docstring": "See parent class.",
"name": "get_accel",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_test_000750 | Implement the Python class `CFMController` described below.
Class description:
CFM controller. Usage ----- See BaseController for usage example. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : SumoCarFollowingParams see parent class k_d : float headway gain (default: 1) k_v... | Implement the Python class `CFMController` described below.
Class description:
CFM controller. Usage ----- See BaseController for usage example. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : SumoCarFollowingParams see parent class k_d : float headway gain (default: 1) k_v... | badac3da17f04d8d8ae5691ee8ba2af9d56fac35 | <|skeleton|>
class CFMController:
"""CFM controller. Usage ----- See BaseController for usage example. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : SumoCarFollowingParams see parent class k_d : float headway gain (default: 1) k_v : float gain on difference between lea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CFMController:
"""CFM controller. Usage ----- See BaseController for usage example. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : SumoCarFollowingParams see parent class k_d : float headway gain (default: 1) k_v : float gain on difference between lead velocity an... | the_stack_v2_python_sparse | flow/controllers/car_following_models.py | parthjaggi/flow | train | 6 |
07340b4d679cd33c16d1845e1d7bfd2491726135 | [
"result = []\nfor i in range(len(nums1)):\n j = 0\n while j < len(nums2):\n print(j, i)\n tmp = []\n if nums1[i] == nums2[j]:\n tmp.append(nums1[i])\n m = i + 1\n n = j + 1\n while m < len(nums1) and n < len(nums2) and (nums1[m] == nums2[n]):\n ... | <|body_start_0|>
result = []
for i in range(len(nums1)):
j = 0
while j < len(nums2):
print(j, i)
tmp = []
if nums1[i] == nums2[j]:
tmp.append(nums1[i])
m = i + 1
n = j + 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersection_all(self, nums1, nums2):
"""所有交际全部打印出来"""
<|body_0|>
def intersection_chars(self, nums1, nums2):
"""只打印交集元素,出现多次只返回一次"""
<|body_1|>
def intersec(self, nums1, nums2):
"""只打印交集元素,出现多次只返回多次"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_36k_train_001384 | 1,624 | no_license | [
{
"docstring": "所有交际全部打印出来",
"name": "intersection_all",
"signature": "def intersection_all(self, nums1, nums2)"
},
{
"docstring": "只打印交集元素,出现多次只返回一次",
"name": "intersection_chars",
"signature": "def intersection_chars(self, nums1, nums2)"
},
{
"docstring": "只打印交集元素,出现多次只返回多次",
... | 3 | stack_v2_sparse_classes_30k_train_009857 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersection_all(self, nums1, nums2): 所有交际全部打印出来
- def intersection_chars(self, nums1, nums2): 只打印交集元素,出现多次只返回一次
- def intersec(self, nums1, nums2): 只打印交集元素,出现多次只返回多次 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersection_all(self, nums1, nums2): 所有交际全部打印出来
- def intersection_chars(self, nums1, nums2): 只打印交集元素,出现多次只返回一次
- def intersec(self, nums1, nums2): 只打印交集元素,出现多次只返回多次
<|skel... | 94cf951ed064e1c7417f2c280075206c3da7503f | <|skeleton|>
class Solution:
def intersection_all(self, nums1, nums2):
"""所有交际全部打印出来"""
<|body_0|>
def intersection_chars(self, nums1, nums2):
"""只打印交集元素,出现多次只返回一次"""
<|body_1|>
def intersec(self, nums1, nums2):
"""只打印交集元素,出现多次只返回多次"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def intersection_all(self, nums1, nums2):
"""所有交际全部打印出来"""
result = []
for i in range(len(nums1)):
j = 0
while j < len(nums2):
print(j, i)
tmp = []
if nums1[i] == nums2[j]:
tmp.append(... | the_stack_v2_python_sparse | array/intersection_of_two_list.py | tinghe0928/leetcode | train | 0 | |
84df8be10b6ed116635f6def1b64b8adc92a48a8 | [
"import collections as cc\nunion = cc.defaultdict(list)\n\ndef find(node):\n if not union[node]:\n return node\n return find(union[node][0])\n\ndef uf(edge):\n x, y = (edge[0], edge[1])\n x = find(x)\n y = find(y)\n if x == y:\n return edge\n union[x].append(y)\nfor e in edges:\n ... | <|body_start_0|>
import collections as cc
union = cc.defaultdict(list)
def find(node):
if not union[node]:
return node
return find(union[node][0])
def uf(edge):
x, y = (edge[0], edge[1])
x = find(x)
y = find(y)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findRedundantConnection(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findRedundantConnection_smart(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_001385 | 2,993 | no_license | [
{
"docstring": ":type edges: List[List[int]] :rtype: List[int]",
"name": "findRedundantConnection",
"signature": "def findRedundantConnection(self, edges)"
},
{
"docstring": ":type edges: List[List[int]] :rtype: List[int]",
"name": "findRedundantConnection_smart",
"signature": "def findR... | 2 | stack_v2_sparse_classes_30k_train_012145 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRedundantConnection(self, edges): :type edges: List[List[int]] :rtype: List[int]
- def findRedundantConnection_smart(self, edges): :type edges: List[List[int]] :rtype: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRedundantConnection(self, edges): :type edges: List[List[int]] :rtype: List[int]
- def findRedundantConnection_smart(self, edges): :type edges: List[List[int]] :rtype: Li... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def findRedundantConnection(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findRedundantConnection_smart(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findRedundantConnection(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
import collections as cc
union = cc.defaultdict(list)
def find(node):
if not union[node]:
return node
return find(union[node][0])
... | the_stack_v2_python_sparse | co_google/684_Redundant_Connection.py | vsdrun/lc_public | train | 6 | |
8c6f01dd556b6e26df0a159a1fb837685f1e5aa3 | [
"consumer = oauth2.Consumer(consumer_key, consumer_secret)\nclient = oauth2.Client(consumer)\nresp, content = client.request('%s?scope=%s' % (OAUTH_SETTINGS['request_token_url'], OAUTH_SETTINGS['scope']), 'GET')\nif resp['status'] != '200':\n raise Exception('Invalid response %s.' % resp['status'])\nurlparts = c... | <|body_start_0|>
consumer = oauth2.Consumer(consumer_key, consumer_secret)
client = oauth2.Client(consumer)
resp, content = client.request('%s?scope=%s' % (OAUTH_SETTINGS['request_token_url'], OAUTH_SETTINGS['scope']), 'GET')
if resp['status'] != '200':
raise Exception('Inval... | OAuth | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OAuth:
def generateAuthorizationURL(self, consumer_key, consumer_secret, domain, callback_url=None):
"""Fetch the OAuthToken and generate the authorization URL. Returns: the Authorization URL"""
<|body_0|>
def authorize(self, consumer_key, consumer_secret, oauth_token, oauth... | stack_v2_sparse_classes_36k_train_001386 | 2,982 | permissive | [
{
"docstring": "Fetch the OAuthToken and generate the authorization URL. Returns: the Authorization URL",
"name": "generateAuthorizationURL",
"signature": "def generateAuthorizationURL(self, consumer_key, consumer_secret, domain, callback_url=None)"
},
{
"docstring": "Upgrade OAuth to Access Tok... | 2 | null | Implement the Python class `OAuth` described below.
Class description:
Implement the OAuth class.
Method signatures and docstrings:
- def generateAuthorizationURL(self, consumer_key, consumer_secret, domain, callback_url=None): Fetch the OAuthToken and generate the authorization URL. Returns: the Authorization URL
- ... | Implement the Python class `OAuth` described below.
Class description:
Implement the OAuth class.
Method signatures and docstrings:
- def generateAuthorizationURL(self, consumer_key, consumer_secret, domain, callback_url=None): Fetch the OAuthToken and generate the authorization URL. Returns: the Authorization URL
- ... | e3c50ee4ec8364c61cfff3ea68ece1098674f4d6 | <|skeleton|>
class OAuth:
def generateAuthorizationURL(self, consumer_key, consumer_secret, domain, callback_url=None):
"""Fetch the OAuthToken and generate the authorization URL. Returns: the Authorization URL"""
<|body_0|>
def authorize(self, consumer_key, consumer_secret, oauth_token, oauth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OAuth:
def generateAuthorizationURL(self, consumer_key, consumer_secret, domain, callback_url=None):
"""Fetch the OAuthToken and generate the authorization URL. Returns: the Authorization URL"""
consumer = oauth2.Consumer(consumer_key, consumer_secret)
client = oauth2.Client(consumer)
... | the_stack_v2_python_sparse | earthengine/gft-mod/src/authorization/oauth.py | MapofLife/MOL | train | 19 | |
4f5a89c4fad10a90ba40cdfc35b09ecf88deda5d | [
"assert isinstance(response, scrapy.http.response.html.HtmlResponse)\nBOARDS = ['Kayak Fishing']\nURLS = ['https://www.anglersnet.co.uk/forums/index.php?/forum/26-kayak-fishing/']\nPAGES = [103]\nassert len(BOARDS) == len(URLS) == len(PAGES), 'Setup list lengths DO NOT match'\nfor i, root_url in enumerate(URLS):\n ... | <|body_start_0|>
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
BOARDS = ['Kayak Fishing']
URLS = ['https://www.anglersnet.co.uk/forums/index.php?/forum/26-kayak-fishing/']
PAGES = [103]
assert len(BOARDS) == len(URLS) == len(PAGES), 'Setup list lengths DO NO... | scrape reports from angling addicts forum | AnglersNetSpiderKayak | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnglersNetSpiderKayak:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board"""
<|body_0|>
def crawl_board_threads(self, response):
"""crawl"""
<|body_1|>
def parse_thread(self, response):
... | stack_v2_sparse_classes_36k_train_001387 | 7,068 | no_license | [
{
"docstring": "generate links to pages in a board",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "crawl",
"name": "crawl_board_threads",
"signature": "def crawl_board_threads(self, response)"
},
{
"docstring": "open a report thread and parse all th... | 3 | null | Implement the Python class `AnglersNetSpiderKayak` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board
- def crawl_board_threads(self, response): crawl
- def parse_thread(self, response): open a... | Implement the Python class `AnglersNetSpiderKayak` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board
- def crawl_board_threads(self, response): crawl
- def parse_thread(self, response): open a... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class AnglersNetSpiderKayak:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board"""
<|body_0|>
def crawl_board_threads(self, response):
"""crawl"""
<|body_1|>
def parse_thread(self, response):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnglersNetSpiderKayak:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board"""
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
BOARDS = ['Kayak Fishing']
URLS = ['https://www.anglersnet.co.uk/f... | the_stack_v2_python_sparse | imgscrape/spiders/anglersnet.py | gmonkman/python | train | 0 |
1f16d2407d6e8ae2c82ce5f213a9a3f718abb94f | [
"with self.conn:\n with self.conn.cursor() as curs:\n pextra.execute_values(curs, 'INSERT INTO IbDailyData (trade_symbol_id, date, open, high, low, close, volume, average, barCount) VALUES %s ON CONFLICT DO NOTHING', df.to_dict('records'), template='(%(trade_symbol_id)s, %(date)s, %(open)s, %(high)s, %(lo... | <|body_start_0|>
with self.conn:
with self.conn.cursor() as curs:
pextra.execute_values(curs, 'INSERT INTO IbDailyData (trade_symbol_id, date, open, high, low, close, volume, average, barCount) VALUES %s ON CONFLICT DO NOTHING', df.to_dict('records'), template='(%(trade_symbol_id)s, ... | Manager of CRUD operations on a database defined in db.sql. | IbSqlWriterBackend | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IbSqlWriterBackend:
"""Manager of CRUD operations on a database defined in db.sql."""
def insert_bulk_daily_data(self, df: pd.DataFrame) -> None:
"""Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dataframe from s3"""
<|body_0|>
def insert_dail... | stack_v2_sparse_classes_36k_train_001388 | 6,148 | permissive | [
{
"docstring": "Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dataframe from s3",
"name": "insert_bulk_daily_data",
"signature": "def insert_bulk_daily_data(self, df: pd.DataFrame) -> None"
},
{
"docstring": "Insert daily data for a particular TradeSymbol entry. :par... | 5 | null | Implement the Python class `IbSqlWriterBackend` described below.
Class description:
Manager of CRUD operations on a database defined in db.sql.
Method signatures and docstrings:
- def insert_bulk_daily_data(self, df: pd.DataFrame) -> None: Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dat... | Implement the Python class `IbSqlWriterBackend` described below.
Class description:
Manager of CRUD operations on a database defined in db.sql.
Method signatures and docstrings:
- def insert_bulk_daily_data(self, df: pd.DataFrame) -> None: Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dat... | 363c59fa29df2ba2719cbad2f8a19ae12cc54a92 | <|skeleton|>
class IbSqlWriterBackend:
"""Manager of CRUD operations on a database defined in db.sql."""
def insert_bulk_daily_data(self, df: pd.DataFrame) -> None:
"""Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dataframe from s3"""
<|body_0|>
def insert_dail... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IbSqlWriterBackend:
"""Manager of CRUD operations on a database defined in db.sql."""
def insert_bulk_daily_data(self, df: pd.DataFrame) -> None:
"""Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dataframe from s3"""
with self.conn:
with self.conn.c... | the_stack_v2_python_sparse | im/ib/ib_sql_writer_backend.py | srlindemann/amp | train | 0 |
10de8d543c7c703bdbb720befb22297ac9103456 | [
"dp = [[0 for _ in range(n)] for _ in range(m)]\nfor i in range(m):\n dp[i][0] = 1\nfor j in range(n):\n dp[0][j] = 1\nfor i in range(1, m):\n for j in range(1, n):\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\nreturn dp[m - 1][n - 1]",
"dp = [1 for _ in range(n)]\nfor i in range(1, m):\n for j in ... | <|body_start_0|>
dp = [[0 for _ in range(n)] for _ in range(m)]
for i in range(m):
dp[i][0] = 1
for j in range(n):
dp[0][j] = 1
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePaths1(self, m: int, n: int) -> int:
"""动态规划: (1) 定义目标: 到Finish(m, n)的路径f(m,n) 总共有total条 (2)迁移方程: f(m ,n) = f(m-1, n) + f(m , n-1) (3) 初始状态: f(1, n) = 1, f(m, 1) = 1 (只能一直向一个方向走)"""
<|body_0|>
def uniquePaths(self, m: int, n: int) -> int:
"""上面的解法... | stack_v2_sparse_classes_36k_train_001389 | 1,167 | no_license | [
{
"docstring": "动态规划: (1) 定义目标: 到Finish(m, n)的路径f(m,n) 总共有total条 (2)迁移方程: f(m ,n) = f(m-1, n) + f(m , n-1) (3) 初始状态: f(1, n) = 1, f(m, 1) = 1 (只能一直向一个方向走)",
"name": "uniquePaths1",
"signature": "def uniquePaths1(self, m: int, n: int) -> int"
},
{
"docstring": "上面的解法 使用了二维数组,实际上下一行的值只依赖上一行的值, 所以只... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths1(self, m: int, n: int) -> int: 动态规划: (1) 定义目标: 到Finish(m, n)的路径f(m,n) 总共有total条 (2)迁移方程: f(m ,n) = f(m-1, n) + f(m , n-1) (3) 初始状态: f(1, n) = 1, f(m, 1) = 1 (只能一直... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths1(self, m: int, n: int) -> int: 动态规划: (1) 定义目标: 到Finish(m, n)的路径f(m,n) 总共有total条 (2)迁移方程: f(m ,n) = f(m-1, n) + f(m , n-1) (3) 初始状态: f(1, n) = 1, f(m, 1) = 1 (只能一直... | f0f4ba0cb91096e55e21b7a2240afbd347187351 | <|skeleton|>
class Solution:
def uniquePaths1(self, m: int, n: int) -> int:
"""动态规划: (1) 定义目标: 到Finish(m, n)的路径f(m,n) 总共有total条 (2)迁移方程: f(m ,n) = f(m-1, n) + f(m , n-1) (3) 初始状态: f(1, n) = 1, f(m, 1) = 1 (只能一直向一个方向走)"""
<|body_0|>
def uniquePaths(self, m: int, n: int) -> int:
"""上面的解法... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePaths1(self, m: int, n: int) -> int:
"""动态规划: (1) 定义目标: 到Finish(m, n)的路径f(m,n) 总共有total条 (2)迁移方程: f(m ,n) = f(m-1, n) + f(m , n-1) (3) 初始状态: f(1, n) = 1, f(m, 1) = 1 (只能一直向一个方向走)"""
dp = [[0 for _ in range(n)] for _ in range(m)]
for i in range(m):
dp[i][... | the_stack_v2_python_sparse | coding_test/62_uniquePath.py | zhuheng-mark/myDL | train | 2 | |
f26fba5c89144d5d975f21349b412ab12e1c1395 | [
"if isinstance(vertex, list):\n return np.vstack((self.exact_geodesic_distance(v) for v in vertex)).min(0)\nelse:\n return self.call_vtp_geodesic(vertex)",
"if config.has_option('geodesic', 'vtp_path'):\n vtp_path = config.get('geodesic', 'vtp_path')\nelse:\n raise ExactGeodesicException('must set con... | <|body_start_0|>
if isinstance(vertex, list):
return np.vstack((self.exact_geodesic_distance(v) for v in vertex)).min(0)
else:
return self.call_vtp_geodesic(vertex)
<|end_body_0|>
<|body_start_1|>
if config.has_option('geodesic', 'vtp_path'):
vtp_path = confi... | Mixin for computing exact geodesic distance along surface | ExactGeodesicMixin | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExactGeodesicMixin:
"""Mixin for computing exact geodesic distance along surface"""
def exact_geodesic_distance(self, vertex):
"""Compute exact geodesic distance along surface - uses VTP geodesic algorithm Parameters ---------- - vertex : int or list of int index of vertex or vertice... | stack_v2_sparse_classes_36k_train_001390 | 2,587 | permissive | [
{
"docstring": "Compute exact geodesic distance along surface - uses VTP geodesic algorithm Parameters ---------- - vertex : int or list of int index of vertex or vertices to compute geodesic distance from",
"name": "exact_geodesic_distance",
"signature": "def exact_geodesic_distance(self, vertex)"
},... | 2 | null | Implement the Python class `ExactGeodesicMixin` described below.
Class description:
Mixin for computing exact geodesic distance along surface
Method signatures and docstrings:
- def exact_geodesic_distance(self, vertex): Compute exact geodesic distance along surface - uses VTP geodesic algorithm Parameters ----------... | Implement the Python class `ExactGeodesicMixin` described below.
Class description:
Mixin for computing exact geodesic distance along surface
Method signatures and docstrings:
- def exact_geodesic_distance(self, vertex): Compute exact geodesic distance along surface - uses VTP geodesic algorithm Parameters ----------... | e07c4b93d49d9eb9b40c853597b9bba82b4c2738 | <|skeleton|>
class ExactGeodesicMixin:
"""Mixin for computing exact geodesic distance along surface"""
def exact_geodesic_distance(self, vertex):
"""Compute exact geodesic distance along surface - uses VTP geodesic algorithm Parameters ---------- - vertex : int or list of int index of vertex or vertice... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExactGeodesicMixin:
"""Mixin for computing exact geodesic distance along surface"""
def exact_geodesic_distance(self, vertex):
"""Compute exact geodesic distance along surface - uses VTP geodesic algorithm Parameters ---------- - vertex : int or list of int index of vertex or vertices to compute ... | the_stack_v2_python_sparse | cortex/polyutils/exact_geodesic.py | gallantlab/pycortex | train | 522 |
e04541ffaf3fd42fb9eafd1b284fd6c1cdff0f20 | [
"super(Ronald, self).__init__(image=Ronald.image, x=games.screen.width / 2, y=y, dx=speed)\nself.odds_change = odds_change\nself.time_til_drop = 0",
"if self.left < 0 or self.right > games.screen.width:\n self.dx = -self.dx\nelif random.randrange(self.odds_change) == 0:\n self.dx = -self.dx\nself.check_drop... | <|body_start_0|>
super(Ronald, self).__init__(image=Ronald.image, x=games.screen.width / 2, y=y, dx=speed)
self.odds_change = odds_change
self.time_til_drop = 0
<|end_body_0|>
<|body_start_1|>
if self.left < 0 or self.right > games.screen.width:
self.dx = -self.dx
el... | Рональд, который, двигаясь влево-вправо, разбрасывает бургеры | Ronald | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ronald:
"""Рональд, который, двигаясь влево-вправо, разбрасывает бургеры"""
def __init__(self, y=55, speed=2, odds_change=200):
"""Инициализирует объект Ronald"""
<|body_0|>
def update(self):
"""Определяет, надо ли сменить направление."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_001391 | 5,097 | no_license | [
{
"docstring": "Инициализирует объект Ronald",
"name": "__init__",
"signature": "def __init__(self, y=55, speed=2, odds_change=200)"
},
{
"docstring": "Определяет, надо ли сменить направление.",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Уменьшает интерв... | 3 | stack_v2_sparse_classes_30k_train_010219 | Implement the Python class `Ronald` described below.
Class description:
Рональд, который, двигаясь влево-вправо, разбрасывает бургеры
Method signatures and docstrings:
- def __init__(self, y=55, speed=2, odds_change=200): Инициализирует объект Ronald
- def update(self): Определяет, надо ли сменить направление.
- def ... | Implement the Python class `Ronald` described below.
Class description:
Рональд, который, двигаясь влево-вправо, разбрасывает бургеры
Method signatures and docstrings:
- def __init__(self, y=55, speed=2, odds_change=200): Инициализирует объект Ronald
- def update(self): Определяет, надо ли сменить направление.
- def ... | 19244b259eec779381c5deb348d2ddf5f439a364 | <|skeleton|>
class Ronald:
"""Рональд, который, двигаясь влево-вправо, разбрасывает бургеры"""
def __init__(self, y=55, speed=2, odds_change=200):
"""Инициализирует объект Ronald"""
<|body_0|>
def update(self):
"""Определяет, надо ли сменить направление."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ronald:
"""Рональд, который, двигаясь влево-вправо, разбрасывает бургеры"""
def __init__(self, y=55, speed=2, odds_change=200):
"""Инициализирует объект Ronald"""
super(Ronald, self).__init__(image=Ronald.image, x=games.screen.width / 2, y=y, dx=speed)
self.odds_change = odds_chan... | the_stack_v2_python_sparse | Graphics/burger_panic.py | kononenkoie/CS50_examples_PYTHON | train | 0 |
b01617f019d054e432b5e5dc658970142c446ebc | [
"m, n = (len(word1), len(word2))\ndp = [[-1] * (n + 1) for _ in range(m + 1)]\nfor i in range(m + 1):\n dp[i][0] = i\nfor j in range(n + 1):\n dp[0][j] = j\nfor i in range(1, m + 1):\n for j in range(1, n + 1):\n if word1[i - 1] == word2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1]\n else... | <|body_start_0|>
m, n = (len(word1), len(word2))
dp = [[-1] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
if word1[i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDistance(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_0|>
def minDistance_TLE(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m... | stack_v2_sparse_classes_36k_train_001392 | 2,975 | no_license | [
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "minDistance",
"signature": "def minDistance(self, word1, word2)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "minDistance_TLE",
"signature": "def minDistance_TLE(self, word1, word2)"
... | 2 | stack_v2_sparse_classes_30k_test_001199 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1, word2): :type word1: str :type word2: str :rtype: int
- def minDistance_TLE(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1, word2): :type word1: str :type word2: str :rtype: int
- def minDistance_TLE(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|ske... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def minDistance(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_0|>
def minDistance_TLE(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDistance(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
m, n = (len(word1), len(word2))
dp = [[-1] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j... | the_stack_v2_python_sparse | src/lt_72.py | oxhead/CodingYourWay | train | 0 | |
c28aabb17dd9cedbbbf30fa079b98038debb31d4 | [
"super(LinkFunction, self).__init__(need_log)\nself._link_type = link_type\nassert self._link_type in (constant.LinkType.LINEAR, constant.LinkType.LOGISTIC, constant.LinkType.POISSON)",
"if self._link_type == constant.LinkType.LINEAR:\n return z\nelif self._link_type == constant.LinkType.LOGISTIC:\n return ... | <|body_start_0|>
super(LinkFunction, self).__init__(need_log)
self._link_type = link_type
assert self._link_type in (constant.LinkType.LINEAR, constant.LinkType.LOGISTIC, constant.LinkType.POISSON)
<|end_body_0|>
<|body_start_1|>
if self._link_type == constant.LinkType.LINEAR:
... | LinkFunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkFunction:
def __init__(self, link_type=constant.LinkType.LOGISTIC, need_log=False):
""":param link_type: constant.LINK_TYPE.LINEAR, constant.LINK_TYPE.LOGISTIC or constant.LINK_TYPE.POISSON :param need_log: bool"""
<|body_0|>
def eval(self, z):
"""Evaluate the fu... | stack_v2_sparse_classes_36k_train_001393 | 2,325 | no_license | [
{
"docstring": ":param link_type: constant.LINK_TYPE.LINEAR, constant.LINK_TYPE.LOGISTIC or constant.LINK_TYPE.POISSON :param need_log: bool",
"name": "__init__",
"signature": "def __init__(self, link_type=constant.LinkType.LOGISTIC, need_log=False)"
},
{
"docstring": "Evaluate the function of z... | 4 | stack_v2_sparse_classes_30k_train_010522 | Implement the Python class `LinkFunction` described below.
Class description:
Implement the LinkFunction class.
Method signatures and docstrings:
- def __init__(self, link_type=constant.LinkType.LOGISTIC, need_log=False): :param link_type: constant.LINK_TYPE.LINEAR, constant.LINK_TYPE.LOGISTIC or constant.LINK_TYPE.P... | Implement the Python class `LinkFunction` described below.
Class description:
Implement the LinkFunction class.
Method signatures and docstrings:
- def __init__(self, link_type=constant.LinkType.LOGISTIC, need_log=False): :param link_type: constant.LINK_TYPE.LINEAR, constant.LINK_TYPE.LOGISTIC or constant.LINK_TYPE.P... | db959eef96f95fcdd92185f0cb728d1d0b99857b | <|skeleton|>
class LinkFunction:
def __init__(self, link_type=constant.LinkType.LOGISTIC, need_log=False):
""":param link_type: constant.LINK_TYPE.LINEAR, constant.LINK_TYPE.LOGISTIC or constant.LINK_TYPE.POISSON :param need_log: bool"""
<|body_0|>
def eval(self, z):
"""Evaluate the fu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkFunction:
def __init__(self, link_type=constant.LinkType.LOGISTIC, need_log=False):
""":param link_type: constant.LINK_TYPE.LINEAR, constant.LINK_TYPE.LOGISTIC or constant.LINK_TYPE.POISSON :param need_log: bool"""
super(LinkFunction, self).__init__(need_log)
self._link_type = link... | the_stack_v2_python_sparse | fl/operator/link_function.py | som-don/jeddak | train | 0 | |
fa34e8a5fe904f840c9d9d95546b2735fa3811f1 | [
"yubikey_otps = []\nfor yk in Yubikey_OTP.objects.filter(user=request.user).all():\n yubikey_otps.append({'id': yk.id, 'active': yk.active, 'title': yk.title})\nreturn Response({'yubikey_otps': yubikey_otps}, status=status.HTTP_200_OK)",
"serializer = self.get_serializer(data=request.data)\nif not serializer.i... | <|body_start_0|>
yubikey_otps = []
for yk in Yubikey_OTP.objects.filter(user=request.user).all():
yubikey_otps.append({'id': yk.id, 'active': yk.active, 'title': yk.title})
return Response({'yubikey_otps': yubikey_otps}, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
... | UserYubikeyOTP | [
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserYubikeyOTP:
def get(self, request, *args, **kwargs):
"""Checks the REST Token and returns a list of all YubiKey OTPs :param request: :type request: :param args: :type args: :param kwargs: :type kwargs: :return: 200 :rtype:"""
<|body_0|>
def put(self, request, *args, **kw... | stack_v2_sparse_classes_36k_train_001394 | 4,205 | permissive | [
{
"docstring": "Checks the REST Token and returns a list of all YubiKey OTPs :param request: :type request: :param args: :type args: :param kwargs: :type kwargs: :return: 200 :rtype:",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Checks the REST Token ... | 4 | null | Implement the Python class `UserYubikeyOTP` described below.
Class description:
Implement the UserYubikeyOTP class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Checks the REST Token and returns a list of all YubiKey OTPs :param request: :type request: :param args: :type args: :param k... | Implement the Python class `UserYubikeyOTP` described below.
Class description:
Implement the UserYubikeyOTP class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Checks the REST Token and returns a list of all YubiKey OTPs :param request: :type request: :param args: :type args: :param k... | 8936aa8ccdee8b9617ef7d894cb9a9a9f6f473cf | <|skeleton|>
class UserYubikeyOTP:
def get(self, request, *args, **kwargs):
"""Checks the REST Token and returns a list of all YubiKey OTPs :param request: :type request: :param args: :type args: :param kwargs: :type kwargs: :return: 200 :rtype:"""
<|body_0|>
def put(self, request, *args, **kw... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserYubikeyOTP:
def get(self, request, *args, **kwargs):
"""Checks the REST Token and returns a list of all YubiKey OTPs :param request: :type request: :param args: :type args: :param kwargs: :type kwargs: :return: 200 :rtype:"""
yubikey_otps = []
for yk in Yubikey_OTP.objects.filter(u... | the_stack_v2_python_sparse | psono/restapi/views/user_yubikey_otp.py | psono/psono-server | train | 76 | |
c31addfe8449ea7885b74c326ea777b979dc6e60 | [
"if exists(path_to_save_dir):\n self.pathdir = path_to_save_dir\n if self.pathdir[-1] != '/':\n self.pathdir += '/'\nelse:\n raise ValueError(f'Path {path_to_save_dir} does not exist')\nself.projname = project_name if project_name is not None else 'unnamed_project'\nenum = 1\nif exists(self.pathdir ... | <|body_start_0|>
if exists(path_to_save_dir):
self.pathdir = path_to_save_dir
if self.pathdir[-1] != '/':
self.pathdir += '/'
else:
raise ValueError(f'Path {path_to_save_dir} does not exist')
self.projname = project_name if project_name is not ... | The SaveIntermediate class. The SaveIntermediatePass stores individual CircuitGates in pickle or qasm format. | SaveIntermediatePass | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaveIntermediatePass:
"""The SaveIntermediate class. The SaveIntermediatePass stores individual CircuitGates in pickle or qasm format."""
def __init__(self, path_to_save_dir: str, project_name: str | None=None, save_as_qasm: bool=True) -> None:
"""Constructor for the SaveIntermediate... | stack_v2_sparse_classes_36k_train_001395 | 7,234 | permissive | [
{
"docstring": "Constructor for the SaveIntermediatePass. Args: path_to_save_dir (str): Path to the directory in which inter- qasm for circuit blocks should be saved. project_name (str): Name of the project files. Raises: ValueError: If `path_to_save_dir` is not an existing directory.",
"name": "__init__",
... | 2 | null | Implement the Python class `SaveIntermediatePass` described below.
Class description:
The SaveIntermediate class. The SaveIntermediatePass stores individual CircuitGates in pickle or qasm format.
Method signatures and docstrings:
- def __init__(self, path_to_save_dir: str, project_name: str | None=None, save_as_qasm:... | Implement the Python class `SaveIntermediatePass` described below.
Class description:
The SaveIntermediate class. The SaveIntermediatePass stores individual CircuitGates in pickle or qasm format.
Method signatures and docstrings:
- def __init__(self, path_to_save_dir: str, project_name: str | None=None, save_as_qasm:... | c89112d15072e8ffffb68cf1757b184e2aeb3dc8 | <|skeleton|>
class SaveIntermediatePass:
"""The SaveIntermediate class. The SaveIntermediatePass stores individual CircuitGates in pickle or qasm format."""
def __init__(self, path_to_save_dir: str, project_name: str | None=None, save_as_qasm: bool=True) -> None:
"""Constructor for the SaveIntermediate... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SaveIntermediatePass:
"""The SaveIntermediate class. The SaveIntermediatePass stores individual CircuitGates in pickle or qasm format."""
def __init__(self, path_to_save_dir: str, project_name: str | None=None, save_as_qasm: bool=True) -> None:
"""Constructor for the SaveIntermediatePass. Args: p... | the_stack_v2_python_sparse | bqskit/passes/io/intermediate.py | BQSKit/bqskit | train | 54 |
6113ea3c26d75c108dcc37d675c162ac01ad4526 | [
"@lru_cache(None)\ndef line(n, r):\n if n < r:\n return [0] * r\n if r == 1:\n return [n]\n pline = line(n, r - 1)\n ret = [0] * r\n for i in range(r - 1):\n if i == 0:\n ret[i] = 0.5 * max(0, pline[i] - 1)\n else:\n ret[i] = 0.5 * max(0, pline[i - 1]... | <|body_start_0|>
@lru_cache(None)
def line(n, r):
if n < r:
return [0] * r
if r == 1:
return [n]
pline = line(n, r - 1)
ret = [0] * r
for i in range(r - 1):
if i == 0:
ret[i] =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
"""09/17/2020 23:41"""
<|body_0|>
def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
"""09/17/2020 23:46"""
<|body_1|>
def champagn... | stack_v2_sparse_classes_36k_train_001396 | 4,308 | no_license | [
{
"docstring": "09/17/2020 23:41",
"name": "champagneTower",
"signature": "def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float"
},
{
"docstring": "09/17/2020 23:46",
"name": "champagneTower",
"signature": "def champagneTower(self, poured: int, query_row: int,... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: 09/17/2020 23:41
- def champagneTower(self, poured: int, query_row: int, query_glass: int) -> fl... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: 09/17/2020 23:41
- def champagneTower(self, poured: int, query_row: int, query_glass: int) -> fl... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
"""09/17/2020 23:41"""
<|body_0|>
def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
"""09/17/2020 23:46"""
<|body_1|>
def champagn... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
"""09/17/2020 23:41"""
@lru_cache(None)
def line(n, r):
if n < r:
return [0] * r
if r == 1:
return [n]
pline = line(n, r - 1)
... | the_stack_v2_python_sparse | leetcode/solved/815_Champagne_Tower/solution.py | sungminoh/algorithms | train | 0 | |
06ea7904436cf2143621688f92fe768fb6d18a75 | [
"user = User.objects.create_user(username='username', email='myemail@test.com', password='password', first_name='first', last_name='last')\ndata = {'username': 'changed', 'first_name': 'changed', 'last_name': 'changed', 'email': 'changed@change.ie'}\nform = EditProfileForm(data, instance=user)\nself.assertTrue(form... | <|body_start_0|>
user = User.objects.create_user(username='username', email='myemail@test.com', password='password', first_name='first', last_name='last')
data = {'username': 'changed', 'first_name': 'changed', 'last_name': 'changed', 'email': 'changed@change.ie'}
form = EditProfileForm(data, in... | test the edit profile form | Test_Edit_Profile_Form | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_Edit_Profile_Form:
"""test the edit profile form"""
def test_Edit_Profile_Form(self):
"""Test that the Edit Profile Form returns valid when there is valid changes"""
<|body_0|>
def test_correct_message_for_no_username_input(self):
"""Test that the error mess... | stack_v2_sparse_classes_36k_train_001397 | 9,772 | no_license | [
{
"docstring": "Test that the Edit Profile Form returns valid when there is valid changes",
"name": "test_Edit_Profile_Form",
"signature": "def test_Edit_Profile_Form(self)"
},
{
"docstring": "Test that the error message 'This field is required' occurs when there is no username inputted in the f... | 3 | stack_v2_sparse_classes_30k_train_000661 | Implement the Python class `Test_Edit_Profile_Form` described below.
Class description:
test the edit profile form
Method signatures and docstrings:
- def test_Edit_Profile_Form(self): Test that the Edit Profile Form returns valid when there is valid changes
- def test_correct_message_for_no_username_input(self): Tes... | Implement the Python class `Test_Edit_Profile_Form` described below.
Class description:
test the edit profile form
Method signatures and docstrings:
- def test_Edit_Profile_Form(self): Test that the Edit Profile Form returns valid when there is valid changes
- def test_correct_message_for_no_username_input(self): Tes... | a80148cb642cb09dac57cff18483be14fed67dfd | <|skeleton|>
class Test_Edit_Profile_Form:
"""test the edit profile form"""
def test_Edit_Profile_Form(self):
"""Test that the Edit Profile Form returns valid when there is valid changes"""
<|body_0|>
def test_correct_message_for_no_username_input(self):
"""Test that the error mess... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_Edit_Profile_Form:
"""test the edit profile form"""
def test_Edit_Profile_Form(self):
"""Test that the Edit Profile Form returns valid when there is valid changes"""
user = User.objects.create_user(username='username', email='myemail@test.com', password='password', first_name='first'... | the_stack_v2_python_sparse | accounts/tests_forms.py | sarahbarron/Stream-3-Project | train | 1 |
8201a924ad155921c1b92325df801de801f31a61 | [
"i = 0\nwhile i < len(arr) - 1:\n if arr[i] == 0:\n arr[i + 1:] = [0] + arr[i + 1:-1]\n i += 2\n else:\n i += 1",
"i = 0\nwhile i < len(arr) - 1:\n if arr[i] == 0:\n arr.pop(-1)\n arr.insert(i, 0)\n i += 2\n else:\n i += 1"
] | <|body_start_0|>
i = 0
while i < len(arr) - 1:
if arr[i] == 0:
arr[i + 1:] = [0] + arr[i + 1:-1]
i += 2
else:
i += 1
<|end_body_0|>
<|body_start_1|>
i = 0
while i < len(arr) - 1:
if arr[i] == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def duplicateZeros(self, arr):
""":type arr: List[int] :rtype: None Do not return anything, modify arr in-place instead."""
<|body_0|>
def duplicateZeros(self, arr):
""":type arr: List[int] :rtype: None Do not return anything, modify arr in-place instead.""... | stack_v2_sparse_classes_36k_train_001398 | 809 | no_license | [
{
"docstring": ":type arr: List[int] :rtype: None Do not return anything, modify arr in-place instead.",
"name": "duplicateZeros",
"signature": "def duplicateZeros(self, arr)"
},
{
"docstring": ":type arr: List[int] :rtype: None Do not return anything, modify arr in-place instead.",
"name": ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def duplicateZeros(self, arr): :type arr: List[int] :rtype: None Do not return anything, modify arr in-place instead.
- def duplicateZeros(self, arr): :type arr: List[int] :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def duplicateZeros(self, arr): :type arr: List[int] :rtype: None Do not return anything, modify arr in-place instead.
- def duplicateZeros(self, arr): :type arr: List[int] :rtype... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def duplicateZeros(self, arr):
""":type arr: List[int] :rtype: None Do not return anything, modify arr in-place instead."""
<|body_0|>
def duplicateZeros(self, arr):
""":type arr: List[int] :rtype: None Do not return anything, modify arr in-place instead.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def duplicateZeros(self, arr):
""":type arr: List[int] :rtype: None Do not return anything, modify arr in-place instead."""
i = 0
while i < len(arr) - 1:
if arr[i] == 0:
arr[i + 1:] = [0] + arr[i + 1:-1]
i += 2
else:
... | the_stack_v2_python_sparse | 1089_Duplicate_Zeros.py | bingli8802/leetcode | train | 0 | |
5001b2c9e117b9ad67f0c5dee4284f791f534e61 | [
"self.distance = np.float64(distance)\nself.initial_speed = np.float64(initial_speed)\nself.acceleration = np.float64(acceleration)\nself.__post_init__()",
"def _final_speed() -> np.float64:\n \"\"\"Get final speed of the block.\"\"\"\n speed_squared = self.initial_speed ** 2 + self.acceleration * self.dist... | <|body_start_0|>
self.distance = np.float64(distance)
self.initial_speed = np.float64(initial_speed)
self.acceleration = np.float64(acceleration)
self.__post_init__()
<|end_body_0|>
<|body_start_1|>
def _final_speed() -> np.float64:
"""Get final speed of the block.""... | One of three groups that makes up a move. | Block | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Block:
"""One of three groups that makes up a move."""
def __init__(self, distance: CoordinateValue, initial_speed: CoordinateValue, acceleration: CoordinateValue) -> None:
"""Constructor."""
<|body_0|>
def __post_init__(self) -> None:
"""Initialize field values ... | stack_v2_sparse_classes_36k_train_001399 | 9,911 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, distance: CoordinateValue, initial_speed: CoordinateValue, acceleration: CoordinateValue) -> None"
},
{
"docstring": "Initialize field values in post-init processing.",
"name": "__post_init__",
"signature... | 2 | null | Implement the Python class `Block` described below.
Class description:
One of three groups that makes up a move.
Method signatures and docstrings:
- def __init__(self, distance: CoordinateValue, initial_speed: CoordinateValue, acceleration: CoordinateValue) -> None: Constructor.
- def __post_init__(self) -> None: Ini... | Implement the Python class `Block` described below.
Class description:
One of three groups that makes up a move.
Method signatures and docstrings:
- def __init__(self, distance: CoordinateValue, initial_speed: CoordinateValue, acceleration: CoordinateValue) -> None: Constructor.
- def __post_init__(self) -> None: Ini... | 026b523c8c9e5d45910c490efb89194d72595be9 | <|skeleton|>
class Block:
"""One of three groups that makes up a move."""
def __init__(self, distance: CoordinateValue, initial_speed: CoordinateValue, acceleration: CoordinateValue) -> None:
"""Constructor."""
<|body_0|>
def __post_init__(self) -> None:
"""Initialize field values ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Block:
"""One of three groups that makes up a move."""
def __init__(self, distance: CoordinateValue, initial_speed: CoordinateValue, acceleration: CoordinateValue) -> None:
"""Constructor."""
self.distance = np.float64(distance)
self.initial_speed = np.float64(initial_speed)
... | the_stack_v2_python_sparse | hardware/opentrons_hardware/hardware_control/motion_planning/types.py | Opentrons/opentrons | train | 326 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.