blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2e7bd406646c184a4023fb971d9f6c240a9f45dd | [
"wx.CheckBox.__init__(self, parent)\nself.__atlasList = parent\nself.__atlasID = atlasID\nself.__listIdx = listIdx\nself.__atlasInfoPanel = atlasInfoPanel\nself.SetValue(enabled)\nself.Bind(wx.EVT_CHECKBOX, self.__onEnable)",
"self.__atlasList.SetSelection(self.__listIdx)\nif self.GetValue():\n self.__atlasInf... | <|body_start_0|>
wx.CheckBox.__init__(self, parent)
self.__atlasList = parent
self.__atlasID = atlasID
self.__listIdx = listIdx
self.__atlasInfoPanel = atlasInfoPanel
self.SetValue(enabled)
self.Bind(wx.EVT_CHECKBOX, self.__onEnable)
<|end_body_0|>
<|body_start_1... | An ``AtlasListWidget`` is a ``wx.CheckBox`` which is used by the :class:`AtlasInfoPanel`. An ``AtlasListWidget`` is shown alongside each atlas in the atlas list. Toggling the checkbox will add/remove information for the respective atlas (see :meth:`AtlasInfoPanel.enableAtlasInfo` and :meth:`AtlasInfoPanel.disableAtlasI... | AtlasListWidget | [
"BSD-3-Clause",
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AtlasListWidget:
"""An ``AtlasListWidget`` is a ``wx.CheckBox`` which is used by the :class:`AtlasInfoPanel`. An ``AtlasListWidget`` is shown alongside each atlas in the atlas list. Toggling the checkbox will add/remove information for the respective atlas (see :meth:`AtlasInfoPanel.enableAtlasIn... | stack_v2_sparse_classes_10k_train_007300 | 17,603 | permissive | [
{
"docstring": "Create an ``AtlasListWidget``. :arg parent: The :mod:`wx` parent object, assumed to be an :class:`.EditableListBox`. :arg listIdx: Index of this ``AtlasListWidget`` in the ``EditableListBox``. :arg atlasInfoPanel: the :class:`AtlasInfoPanel` instance that owns this ``AtlasListWidget``. :arg atla... | 2 | null | Implement the Python class `AtlasListWidget` described below.
Class description:
An ``AtlasListWidget`` is a ``wx.CheckBox`` which is used by the :class:`AtlasInfoPanel`. An ``AtlasListWidget`` is shown alongside each atlas in the atlas list. Toggling the checkbox will add/remove information for the respective atlas (... | Implement the Python class `AtlasListWidget` described below.
Class description:
An ``AtlasListWidget`` is a ``wx.CheckBox`` which is used by the :class:`AtlasInfoPanel`. An ``AtlasListWidget`` is shown alongside each atlas in the atlas list. Toggling the checkbox will add/remove information for the respective atlas (... | 46ccb4fe2b2346eb57576247f49714032b61307a | <|skeleton|>
class AtlasListWidget:
"""An ``AtlasListWidget`` is a ``wx.CheckBox`` which is used by the :class:`AtlasInfoPanel`. An ``AtlasListWidget`` is shown alongside each atlas in the atlas list. Toggling the checkbox will add/remove information for the respective atlas (see :meth:`AtlasInfoPanel.enableAtlasIn... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AtlasListWidget:
"""An ``AtlasListWidget`` is a ``wx.CheckBox`` which is used by the :class:`AtlasInfoPanel`. An ``AtlasListWidget`` is shown alongside each atlas in the atlas list. Toggling the checkbox will add/remove information for the respective atlas (see :meth:`AtlasInfoPanel.enableAtlasInfo` and :meth... | the_stack_v2_python_sparse | fsleyes/controls/atlasinfopanel.py | sanjayankur31/fsleyes | train | 1 |
03e838c9d32770daa684acfa8c610e6d1f535f86 | [
"self.world: BulletWorld = world if world else BulletWorld.current_bullet_world\nself.object: Object = object\nself.link: str = urdf_link_name\nself.resolution: float = resolution\nself.origin: Pose = object.get_link_pose(urdf_link_name)\nself.height: int = 0\nself.width: int = 0\nself.map: np.ndarray = []\nself.ge... | <|body_start_0|>
self.world: BulletWorld = world if world else BulletWorld.current_bullet_world
self.object: Object = object
self.link: str = urdf_link_name
self.resolution: float = resolution
self.origin: Pose = object.get_link_pose(urdf_link_name)
self.height: int = 0
... | Semantic Costmaps represent a 2D distribution over a link of an Object. An example of this would be a Costmap for a table surface. | SemanticCostmap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SemanticCostmap:
"""Semantic Costmaps represent a 2D distribution over a link of an Object. An example of this would be a Costmap for a table surface."""
def __init__(self, object, urdf_link_name, size=100, resolution=0.02, world=None):
"""Creates a semantic costmap for the given par... | stack_v2_sparse_classes_10k_train_007301 | 37,310 | no_license | [
{
"docstring": "Creates a semantic costmap for the given parameter. The semantic costmap will be on top of the link of the given Object. :param object: The object of which the link is a part :param urdf_link_name: The link name, as stated in the URDF :param resolution: Resolution of the final costmap :param wor... | 3 | stack_v2_sparse_classes_30k_train_007064 | Implement the Python class `SemanticCostmap` described below.
Class description:
Semantic Costmaps represent a 2D distribution over a link of an Object. An example of this would be a Costmap for a table surface.
Method signatures and docstrings:
- def __init__(self, object, urdf_link_name, size=100, resolution=0.02, ... | Implement the Python class `SemanticCostmap` described below.
Class description:
Semantic Costmaps represent a 2D distribution over a link of an Object. An example of this would be a Costmap for a table surface.
Method signatures and docstrings:
- def __init__(self, object, urdf_link_name, size=100, resolution=0.02, ... | f9ef666d6d4685660c9517652f2c568ed2c9367c | <|skeleton|>
class SemanticCostmap:
"""Semantic Costmaps represent a 2D distribution over a link of an Object. An example of this would be a Costmap for a table surface."""
def __init__(self, object, urdf_link_name, size=100, resolution=0.02, world=None):
"""Creates a semantic costmap for the given par... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SemanticCostmap:
"""Semantic Costmaps represent a 2D distribution over a link of an Object. An example of this would be a Costmap for a table surface."""
def __init__(self, object, urdf_link_name, size=100, resolution=0.02, world=None):
"""Creates a semantic costmap for the given parameter. The s... | the_stack_v2_python_sparse | src/pycram/costmaps.py | cram2/pycram | train | 12 |
46d07e2d02b0f1f3caec381051a04537d03b5a00 | [
"modForTypeDict = Effectiveness.modByType[attackType]\nif pokeType in modForTypeDict:\n return modForTypeDict[pokeType]\nelse:\n return 1",
"mod = 1\nif not attackType == '':\n for type in target.getTypes():\n mod = mod * Effectiveness.getMod(attackType, type)\nreturn (mod, Effectiveness.respond(m... | <|body_start_0|>
modForTypeDict = Effectiveness.modByType[attackType]
if pokeType in modForTypeDict:
return modForTypeDict[pokeType]
else:
return 1
<|end_body_0|>
<|body_start_1|>
mod = 1
if not attackType == '':
for type in target.getTypes():... | Used to get effectiveness of attacks based on TYPE | Effectiveness | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Effectiveness:
"""Used to get effectiveness of attacks based on TYPE"""
def getMod(attackType, pokeType):
"""Returns the modifier bonus of the Effectiveness of an attack against a Pokemon's Type"""
<|body_0|>
def getEffectiveness(attackType, target):
"""Returns t... | stack_v2_sparse_classes_10k_train_007302 | 3,718 | no_license | [
{
"docstring": "Returns the modifier bonus of the Effectiveness of an attack against a Pokemon's Type",
"name": "getMod",
"signature": "def getMod(attackType, pokeType)"
},
{
"docstring": "Returns the effectiveness of an attack against a pokemon",
"name": "getEffectiveness",
"signature":... | 3 | null | Implement the Python class `Effectiveness` described below.
Class description:
Used to get effectiveness of attacks based on TYPE
Method signatures and docstrings:
- def getMod(attackType, pokeType): Returns the modifier bonus of the Effectiveness of an attack against a Pokemon's Type
- def getEffectiveness(attackTyp... | Implement the Python class `Effectiveness` described below.
Class description:
Used to get effectiveness of attacks based on TYPE
Method signatures and docstrings:
- def getMod(attackType, pokeType): Returns the modifier bonus of the Effectiveness of an attack against a Pokemon's Type
- def getEffectiveness(attackTyp... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class Effectiveness:
"""Used to get effectiveness of attacks based on TYPE"""
def getMod(attackType, pokeType):
"""Returns the modifier bonus of the Effectiveness of an attack against a Pokemon's Type"""
<|body_0|>
def getEffectiveness(attackType, target):
"""Returns t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Effectiveness:
"""Used to get effectiveness of attacks based on TYPE"""
def getMod(attackType, pokeType):
"""Returns the modifier bonus of the Effectiveness of an attack against a Pokemon's Type"""
modForTypeDict = Effectiveness.modByType[attackType]
if pokeType in modForTypeDict:... | the_stack_v2_python_sparse | src/Battle/Attack/DamageDelegates/effectiveness.py | sgtnourry/Pokemon-Project | train | 0 |
5a7c5fc8ca6cbd6a2f3105cac2c37bf878eddfa5 | [
"super().__init__(number)\nself.platform = platform\nself.length_of_display = display_size",
"assert not text.embed_commas\nmapping = TextToSegmentMapper.map_segment_text_to_segments(text, self.length_of_display, FOURTEEN_SEGMENTS)\nresult = map(lambda x: x.get_vpe_encoding(), mapping)\ncommand = platform_pb2.Com... | <|body_start_0|>
super().__init__(number)
self.platform = platform
self.length_of_display = display_size
<|end_body_0|>
<|body_start_1|>
assert not text.embed_commas
mapping = TextToSegmentMapper.map_segment_text_to_segments(text, self.length_of_display, FOURTEEN_SEGMENTS)
... | VPE segment display. | VisualPinballEngineSegmentDisplay | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisualPinballEngineSegmentDisplay:
"""VPE segment display."""
def __init__(self, number, display_size, platform):
"""Initialise segment display."""
<|body_0|>
def _set_text(self, text: ColoredSegmentDisplayText) -> None:
"""Set text to VPE segment displays."""
... | stack_v2_sparse_classes_10k_train_007303 | 18,330 | permissive | [
{
"docstring": "Initialise segment display.",
"name": "__init__",
"signature": "def __init__(self, number, display_size, platform)"
},
{
"docstring": "Set text to VPE segment displays.",
"name": "_set_text",
"signature": "def _set_text(self, text: ColoredSegmentDisplayText) -> None"
}
... | 2 | stack_v2_sparse_classes_30k_train_001173 | Implement the Python class `VisualPinballEngineSegmentDisplay` described below.
Class description:
VPE segment display.
Method signatures and docstrings:
- def __init__(self, number, display_size, platform): Initialise segment display.
- def _set_text(self, text: ColoredSegmentDisplayText) -> None: Set text to VPE se... | Implement the Python class `VisualPinballEngineSegmentDisplay` described below.
Class description:
VPE segment display.
Method signatures and docstrings:
- def __init__(self, number, display_size, platform): Initialise segment display.
- def _set_text(self, text: ColoredSegmentDisplayText) -> None: Set text to VPE se... | 9f90c8b1586363b65340017bfa3af5d56d32c6d9 | <|skeleton|>
class VisualPinballEngineSegmentDisplay:
"""VPE segment display."""
def __init__(self, number, display_size, platform):
"""Initialise segment display."""
<|body_0|>
def _set_text(self, text: ColoredSegmentDisplayText) -> None:
"""Set text to VPE segment displays."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VisualPinballEngineSegmentDisplay:
"""VPE segment display."""
def __init__(self, number, display_size, platform):
"""Initialise segment display."""
super().__init__(number)
self.platform = platform
self.length_of_display = display_size
def _set_text(self, text: Colore... | the_stack_v2_python_sparse | mpf/platforms/visual_pinball_engine/visual_pinball_engine.py | missionpinball/mpf | train | 191 |
db8b773aca99167c2b0c06142b324d3ac0c5385a | [
"super(ModuleUIFrame, self).__init__(parent)\nself.columnconfigure(0, weight=1)\nself.rowconfigure(0, weight=1)\napi_frame = ttk.LabelFrame(self, padding=8, text='Google API')\napi_frame.grid(row=0, column=0, sticky='W E N S')\napi_frame.columnconfigure(0, weight=1)\nself.reddit_api_user_agent = tk.StringVar()\nttk... | <|body_start_0|>
super(ModuleUIFrame, self).__init__(parent)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
api_frame = ttk.LabelFrame(self, padding=8, text='Google API')
api_frame.grid(row=0, column=0, sticky='W E N S')
api_frame.columnconfigure(0, weig... | The UI for the gamedeals module | ModuleUIFrame | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleUIFrame:
"""The UI for the gamedeals module"""
def __init__(self, parent):
"""Create a new UI for the module Args: parent: A tk or ttk object"""
<|body_0|>
def update_google_key(self):
"""Updates the Google API key with the text value"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_007304 | 2,701 | permissive | [
{
"docstring": "Create a new UI for the module Args: parent: A tk or ttk object",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Updates the Google API key with the text value",
"name": "update_google_key",
"signature": "def update_google_key(self)"
}
... | 2 | stack_v2_sparse_classes_30k_train_003748 | Implement the Python class `ModuleUIFrame` described below.
Class description:
The UI for the gamedeals module
Method signatures and docstrings:
- def __init__(self, parent): Create a new UI for the module Args: parent: A tk or ttk object
- def update_google_key(self): Updates the Google API key with the text value | Implement the Python class `ModuleUIFrame` described below.
Class description:
The UI for the gamedeals module
Method signatures and docstrings:
- def __init__(self, parent): Create a new UI for the module Args: parent: A tk or ttk object
- def update_google_key(self): Updates the Google API key with the text value
... | 3e044b7152a04ebf15e95bd332f476724b40c652 | <|skeleton|>
class ModuleUIFrame:
"""The UI for the gamedeals module"""
def __init__(self, parent):
"""Create a new UI for the module Args: parent: A tk or ttk object"""
<|body_0|>
def update_google_key(self):
"""Updates the Google API key with the text value"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModuleUIFrame:
"""The UI for the gamedeals module"""
def __init__(self, parent):
"""Create a new UI for the module Args: parent: A tk or ttk object"""
super(ModuleUIFrame, self).__init__(parent)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
api_f... | the_stack_v2_python_sparse | modis/discord_modis/modules/gamedeals/_ui.py | OKEPlazmA/modis | train | 0 |
c4e849864d94b8b94dc15c79409964e27fd5d805 | [
"try:\n response = requests.get(CONF.api.github_api_capabilities_url)\n LOG.debug('Response Status: %s / Used Requests Cache: %s' % (response.status_code, getattr(response, 'from_cache', False)))\n if response.status_code == 200:\n regex = re.compile('^[0-9]{4}\\\\.[0-9]{2}\\\\.json$')\n capa... | <|body_start_0|>
try:
response = requests.get(CONF.api.github_api_capabilities_url)
LOG.debug('Response Status: %s / Used Requests Cache: %s' % (response.status_code, getattr(response, 'from_cache', False)))
if response.status_code == 200:
regex = re.compile('... | /v1/capabilities handler. This acts as a proxy for retrieving capability files from the openstack/defcore Github repository. | CapabilitiesController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CapabilitiesController:
"""/v1/capabilities handler. This acts as a proxy for retrieving capability files from the openstack/defcore Github repository."""
def get(self):
"""Get a list of all available capabilities."""
<|body_0|>
def get_one(self, file_name):
"""H... | stack_v2_sparse_classes_10k_train_007305 | 8,563 | permissive | [
{
"docstring": "Get a list of all available capabilities.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Handler for getting contents of specific capability file.",
"name": "get_one",
"signature": "def get_one(self, file_name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004664 | Implement the Python class `CapabilitiesController` described below.
Class description:
/v1/capabilities handler. This acts as a proxy for retrieving capability files from the openstack/defcore Github repository.
Method signatures and docstrings:
- def get(self): Get a list of all available capabilities.
- def get_on... | Implement the Python class `CapabilitiesController` described below.
Class description:
/v1/capabilities handler. This acts as a proxy for retrieving capability files from the openstack/defcore Github repository.
Method signatures and docstrings:
- def get(self): Get a list of all available capabilities.
- def get_on... | 711f7527c430873edbed72e4f85af916b2088014 | <|skeleton|>
class CapabilitiesController:
"""/v1/capabilities handler. This acts as a proxy for retrieving capability files from the openstack/defcore Github repository."""
def get(self):
"""Get a list of all available capabilities."""
<|body_0|>
def get_one(self, file_name):
"""H... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CapabilitiesController:
"""/v1/capabilities handler. This acts as a proxy for retrieving capability files from the openstack/defcore Github repository."""
def get(self):
"""Get a list of all available capabilities."""
try:
response = requests.get(CONF.api.github_api_capabiliti... | the_stack_v2_python_sparse | refstack/api/controllers/v1.py | russell/refstack | train | 0 |
9d1c2795f0a9bf3d8a64e65dbf49753e00a56502 | [
"object_type = self.kwargs.get('object_type', 'posts')\nif object_type == 'comments':\n return CommentSerializer\nreturn PostListSerializer",
"object_type = self.kwargs.get('object_type', 'posts')\nusername = self.kwargs.get('username', None)\nUser = get_user_model()\nif not User.objects.filter(username=userna... | <|body_start_0|>
object_type = self.kwargs.get('object_type', 'posts')
if object_type == 'comments':
return CommentSerializer
return PostListSerializer
<|end_body_0|>
<|body_start_1|>
object_type = self.kwargs.get('object_type', 'posts')
username = self.kwargs.get('u... | Return list of user related objects (blogposts, comments). | UserObjects | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserObjects:
"""Return list of user related objects (blogposts, comments)."""
def get_serializer_class(self):
"""Determine serializer for different object type."""
<|body_0|>
def get_queryset(self):
"""Determine queryset for different object type."""
<|bo... | stack_v2_sparse_classes_10k_train_007306 | 19,438 | no_license | [
{
"docstring": "Determine serializer for different object type.",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Determine queryset for different object type.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000039 | Implement the Python class `UserObjects` described below.
Class description:
Return list of user related objects (blogposts, comments).
Method signatures and docstrings:
- def get_serializer_class(self): Determine serializer for different object type.
- def get_queryset(self): Determine queryset for different object ... | Implement the Python class `UserObjects` described below.
Class description:
Return list of user related objects (blogposts, comments).
Method signatures and docstrings:
- def get_serializer_class(self): Determine serializer for different object type.
- def get_queryset(self): Determine queryset for different object ... | 3e77877d1805ae2b361c9b3f564e73f698a3f4c6 | <|skeleton|>
class UserObjects:
"""Return list of user related objects (blogposts, comments)."""
def get_serializer_class(self):
"""Determine serializer for different object type."""
<|body_0|>
def get_queryset(self):
"""Determine queryset for different object type."""
<|bo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserObjects:
"""Return list of user related objects (blogposts, comments)."""
def get_serializer_class(self):
"""Determine serializer for different object type."""
object_type = self.kwargs.get('object_type', 'posts')
if object_type == 'comments':
return CommentSeriali... | the_stack_v2_python_sparse | api/views.py | zagorboda/django-blog | train | 0 |
d813a4f9013c9770cf1b0828877f4ed64c0c29e9 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SimulationAutomationRun()",
"from .entity import Entity\nfrom .simulation_automation_run_status import SimulationAutomationRunStatus\nfrom .entity import Entity\nfrom .simulation_automation_run_status import SimulationAutomationRunStat... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SimulationAutomationRun()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .simulation_automation_run_status import SimulationAutomationRunStatus
from .entity impo... | SimulationAutomationRun | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulationAutomationRun:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomationRun:
"""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 creat... | stack_v2_sparse_classes_10k_train_007307 | 3,312 | 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: SimulationAutomationRun",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimin... | 3 | null | Implement the Python class `SimulationAutomationRun` described below.
Class description:
Implement the SimulationAutomationRun class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomationRun: Creates a new instance of the appropriate clas... | Implement the Python class `SimulationAutomationRun` described below.
Class description:
Implement the SimulationAutomationRun class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomationRun: Creates a new instance of the appropriate clas... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SimulationAutomationRun:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomationRun:
"""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 creat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SimulationAutomationRun:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomationRun:
"""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 R... | the_stack_v2_python_sparse | msgraph/generated/models/simulation_automation_run.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
e8ff0dffb9b020e19adc98e9c51bbec241ea1562 | [
"self.set_header('Cache-Control', 'no-cache, no-store, must-revalidate')\nself.set_header('Pragma', 'no-cache')\nself.set_header('Expires', '0')\nusuario = self.get_secure_cookie('user')\nif usuario:\n self.redirect('/')\nelse:\n self.clear_cookie('user')\n self.render('user/login/view.html')",
"self.set... | <|body_start_0|>
self.set_header('Cache-Control', 'no-cache, no-store, must-revalidate')
self.set_header('Pragma', 'no-cache')
self.set_header('Expires', '0')
usuario = self.get_secure_cookie('user')
if usuario:
self.redirect('/')
else:
self.clear_... | Login | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Login:
def get(self):
"""Renderiza el login"""
<|body_0|>
def post(self):
"""Inicia sesión en la aplicación. Si se inicia sesión con éxito enctonces se guarda el usuario en la cookie caso contrario se vuelve al login."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_10k_train_007308 | 1,796 | permissive | [
{
"docstring": "Renderiza el login",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Inicia sesión en la aplicación. Si se inicia sesión con éxito enctonces se guarda el usuario en la cookie caso contrario se vuelve al login.",
"name": "post",
"signature": "def post(self)"... | 2 | stack_v2_sparse_classes_30k_train_001640 | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- def get(self): Renderiza el login
- def post(self): Inicia sesión en la aplicación. Si se inicia sesión con éxito enctonces se guarda el usuario en la cookie caso contrario se vuelve a... | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- def get(self): Renderiza el login
- def post(self): Inicia sesión en la aplicación. Si se inicia sesión con éxito enctonces se guarda el usuario en la cookie caso contrario se vuelve a... | da59c7b659348c15af0ed8376fe808622d9aec2c | <|skeleton|>
class Login:
def get(self):
"""Renderiza el login"""
<|body_0|>
def post(self):
"""Inicia sesión en la aplicación. Si se inicia sesión con éxito enctonces se guarda el usuario en la cookie caso contrario se vuelve al login."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Login:
def get(self):
"""Renderiza el login"""
self.set_header('Cache-Control', 'no-cache, no-store, must-revalidate')
self.set_header('Pragma', 'no-cache')
self.set_header('Expires', '0')
usuario = self.get_secure_cookie('user')
if usuario:
self.red... | the_stack_v2_python_sparse | server/user/login/controllers.py | shiross/crm-web | train | 1 | |
9da0217b0d7b2f92c19e794eae1c8eefd4359b64 | [
"self.domain1 = FEDomain()\nself.fets_eval = FETS2D4Q(mats_eval=MATS2DElastic())\nself.d1 = FERefinementGrid(name='d1', domain=self.domain1)\nself.g1 = FEGrid(coord_max=(1.0, 1.0, 0.0), shape=(2, 2), fets_eval=self.fets_eval, level=self.d1)",
"elem_X_map = self.g1.elem_X_map\negm = [0.0, 0.0, 0.5, 0.0, 0.5, 0.5, ... | <|body_start_0|>
self.domain1 = FEDomain()
self.fets_eval = FETS2D4Q(mats_eval=MATS2DElastic())
self.d1 = FERefinementGrid(name='d1', domain=self.domain1)
self.g1 = FEGrid(coord_max=(1.0, 1.0, 0.0), shape=(2, 2), fets_eval=self.fets_eval, level=self.d1)
<|end_body_0|>
<|body_start_1|>
... | Test the retrieval of geometric information of FEDomain. | FEDomainGeoMap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FEDomainGeoMap:
"""Test the retrieval of geometric information of FEDomain."""
def setUp(self):
"""Construct the FEDomain with one FERefinementGrids (2,2)"""
<|body_0|>
def test_elem_X_map(self):
"""Test the retrieval of geometric information of FEDomain."""
... | stack_v2_sparse_classes_10k_train_007309 | 5,633 | no_license | [
{
"docstring": "Construct the FEDomain with one FERefinementGrids (2,2)",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the retrieval of geometric information of FEDomain.",
"name": "test_elem_X_map",
"signature": "def test_elem_X_map(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001125 | Implement the Python class `FEDomainGeoMap` described below.
Class description:
Test the retrieval of geometric information of FEDomain.
Method signatures and docstrings:
- def setUp(self): Construct the FEDomain with one FERefinementGrids (2,2)
- def test_elem_X_map(self): Test the retrieval of geometric information... | Implement the Python class `FEDomainGeoMap` described below.
Class description:
Test the retrieval of geometric information of FEDomain.
Method signatures and docstrings:
- def setUp(self): Construct the FEDomain with one FERefinementGrids (2,2)
- def test_elem_X_map(self): Test the retrieval of geometric information... | 00de9f0eec52835d839a3c6c1407cac11a496339 | <|skeleton|>
class FEDomainGeoMap:
"""Test the retrieval of geometric information of FEDomain."""
def setUp(self):
"""Construct the FEDomain with one FERefinementGrids (2,2)"""
<|body_0|>
def test_elem_X_map(self):
"""Test the retrieval of geometric information of FEDomain."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FEDomainGeoMap:
"""Test the retrieval of geometric information of FEDomain."""
def setUp(self):
"""Construct the FEDomain with one FERefinementGrids (2,2)"""
self.domain1 = FEDomain()
self.fets_eval = FETS2D4Q(mats_eval=MATS2DElastic())
self.d1 = FERefinementGrid(name='d1'... | the_stack_v2_python_sparse | ibvpy/mesh/__test__.py | simvisage/bmcs | train | 1 |
72340638ade9752291fe9777c32a082104b07a78 | [
"res = []\nqueue = []\nfor num in nums:\n if len(queue) < k:\n queue.append(num)\n if len(queue) == k:\n res.append(max(queue))\n queue.pop(0)\nreturn res",
"res = []\nqueue = []\nfor i, num in enumerate(nums):\n if queue and i - queue[0] == k:\n queue.pop(0)\n while queue ... | <|body_start_0|>
res = []
queue = []
for num in nums:
if len(queue) < k:
queue.append(num)
if len(queue) == k:
res.append(max(queue))
queue.pop(0)
return res
<|end_body_0|>
<|body_start_1|>
res = []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxInWindows(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxInWindows(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_007310 | 1,338 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxInWindows",
"signature": "def maxInWindows(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxInWindows",
"signature": "def maxInWindows(self, nums, k)"
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxInWindows(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxInWindows(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxInWindows(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxInWindows(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
<|s... | 967b0fbb40ae491b552bc3365a481e66324cb6f2 | <|skeleton|>
class Solution:
def maxInWindows(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxInWindows(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxInWindows(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
res = []
queue = []
for num in nums:
if len(queue) < k:
queue.append(num)
if len(queue) == k:
res.append(max(queue))
... | the_stack_v2_python_sparse | jianzhi_offer/57_滑动窗口的最大值.py | ryanatgz/data_structure_and_algorithm | train | 0 | |
88fb343bfca6642cac6e1470b2edce2348407dd6 | [
"new_kwargs = self.supports.copy()\nnew_kwargs.update(kwargs)\nreturn TernaryRegistrationFactory._check_registered_widget(self, *args, **new_kwargs)",
"if self.supports['equation_physics'] != WidgetType.supports['equation_physics']:\n err_str = \"Factory {0} accepts '{1}' physics while solver {2} supports '{3}... | <|body_start_0|>
new_kwargs = self.supports.copy()
new_kwargs.update(kwargs)
return TernaryRegistrationFactory._check_registered_widget(self, *args, **new_kwargs)
<|end_body_0|>
<|body_start_1|>
if self.supports['equation_physics'] != WidgetType.supports['equation_physics']:
... | Factory for constant density acoustic wave (time-domain) solvers. Widgets (classes) can be registered with an instance of this class. Arguments to the factory's `__call__` method are then passed to a function specified by the registered factory, which validates the input and returns a instance of the class that best ma... | SolverFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolverFactory:
"""Factory for constant density acoustic wave (time-domain) solvers. Widgets (classes) can be registered with an instance of this class. Arguments to the factory's `__call__` method are then passed to a function specified by the registered factory, which validates the input and ret... | stack_v2_sparse_classes_10k_train_007311 | 4,473 | no_license | [
{
"docstring": "Implementation of a basic check to see if arguments match a widget.",
"name": "_check_registered_widget",
"signature": "def _check_registered_widget(self, *args, **kwargs)"
},
{
"docstring": "Register a widget with the factory. If `validation_function` is not specified, tests `Wi... | 2 | stack_v2_sparse_classes_30k_train_006997 | Implement the Python class `SolverFactory` described below.
Class description:
Factory for constant density acoustic wave (time-domain) solvers. Widgets (classes) can be registered with an instance of this class. Arguments to the factory's `__call__` method are then passed to a function specified by the registered fac... | Implement the Python class `SolverFactory` described below.
Class description:
Factory for constant density acoustic wave (time-domain) solvers. Widgets (classes) can be registered with an instance of this class. Arguments to the factory's `__call__` method are then passed to a function specified by the registered fac... | 1fb1a80839ceebef12a8d71aa9c295b65b08bac4 | <|skeleton|>
class SolverFactory:
"""Factory for constant density acoustic wave (time-domain) solvers. Widgets (classes) can be registered with an instance of this class. Arguments to the factory's `__call__` method are then passed to a function specified by the registered factory, which validates the input and ret... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SolverFactory:
"""Factory for constant density acoustic wave (time-domain) solvers. Widgets (classes) can be registered with an instance of this class. Arguments to the factory's `__call__` method are then passed to a function specified by the registered factory, which validates the input and returns a instan... | the_stack_v2_python_sparse | pysit/solvers/solver_factory.py | simonlegrand/pysit | train | 1 |
98c13f6904e9569bae18bb2f8cd49abdf5f98cc2 | [
"count = 0\nwhile n:\n if n & 1 == 1:\n count += 1\n n = n >> 1\n if count > 1:\n return False\nif count == 0:\n return False\nreturn True",
"if n == 0:\n return False\ncount = 0\nfor i in range(2):\n count += 1\n n = n & n - 1\n if n == 0:\n break\nif count != 1:\n ... | <|body_start_0|>
count = 0
while n:
if n & 1 == 1:
count += 1
n = n >> 1
if count > 1:
return False
if count == 0:
return False
return True
<|end_body_0|>
<|body_start_1|>
if n == 0:
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfTwo3(self, n: int) -> bool:
"""位运算 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1. 计算1的个数是否为1"""
<|body_0|>
def isPowerOfTwo2(self, n: int) -> bool:
"""位运算(推荐) 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1。 计算1的个数是否为1"""
<|body_1... | stack_v2_sparse_classes_10k_train_007312 | 1,448 | no_license | [
{
"docstring": "位运算 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1. 计算1的个数是否为1",
"name": "isPowerOfTwo3",
"signature": "def isPowerOfTwo3(self, n: int) -> bool"
},
{
"docstring": "位运算(推荐) 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1。 计算1的个数是否为1",
"name": "isPowerOfTwo2",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_007133 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo3(self, n: int) -> bool: 位运算 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1. 计算1的个数是否为1
- def isPowerOfTwo2(self, n: int) -> bool: 位运算(推荐) 1 2 10 2 100 4 1000 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo3(self, n: int) -> bool: 位运算 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1. 计算1的个数是否为1
- def isPowerOfTwo2(self, n: int) -> bool: 位运算(推荐) 1 2 10 2 100 4 1000 ... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def isPowerOfTwo3(self, n: int) -> bool:
"""位运算 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1. 计算1的个数是否为1"""
<|body_0|>
def isPowerOfTwo2(self, n: int) -> bool:
"""位运算(推荐) 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1。 计算1的个数是否为1"""
<|body_1... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isPowerOfTwo3(self, n: int) -> bool:
"""位运算 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1. 计算1的个数是否为1"""
count = 0
while n:
if n & 1 == 1:
count += 1
n = n >> 1
if count > 1:
return False
if c... | the_stack_v2_python_sparse | leetcode/231_2的幂.py | tenqaz/crazy_arithmetic | train | 0 | |
eb607464bf4a290475e750e3e218a9925c788e6b | [
"if isinstance(value, str):\n return json.loads(value)\nreturn value",
"if isinstance(data, str):\n try:\n return json.loads(data)\n except ValueError as e:\n raise serializers.ValidationError(str(e)) from e\nreturn data",
"if isinstance(data, str):\n return json.loads(data)\nreturn da... | <|body_start_0|>
if isinstance(value, str):
return json.loads(value)
return value
<|end_body_0|>
<|body_start_1|>
if isinstance(data, str):
try:
return json.loads(data)
except ValueError as e:
raise serializers.ValidationError(... | Deserialize a string instance containing a JSON document to a Python object. | JsonField | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonField:
"""Deserialize a string instance containing a JSON document to a Python object."""
def to_representation(self, value):
"""Deserialize ``value`` a `str` instance containing a JSON document to a Python object."""
<|body_0|>
def to_internal_value(self, data):
... | stack_v2_sparse_classes_10k_train_007313 | 1,166 | permissive | [
{
"docstring": "Deserialize ``value`` a `str` instance containing a JSON document to a Python object.",
"name": "to_representation",
"signature": "def to_representation(self, value)"
},
{
"docstring": "Deserialize ``value`` a `str` instance containing a JSON document to a Python object.",
"n... | 3 | stack_v2_sparse_classes_30k_train_000442 | Implement the Python class `JsonField` described below.
Class description:
Deserialize a string instance containing a JSON document to a Python object.
Method signatures and docstrings:
- def to_representation(self, value): Deserialize ``value`` a `str` instance containing a JSON document to a Python object.
- def to... | Implement the Python class `JsonField` described below.
Class description:
Deserialize a string instance containing a JSON document to a Python object.
Method signatures and docstrings:
- def to_representation(self, value): Deserialize ``value`` a `str` instance containing a JSON document to a Python object.
- def to... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class JsonField:
"""Deserialize a string instance containing a JSON document to a Python object."""
def to_representation(self, value):
"""Deserialize ``value`` a `str` instance containing a JSON document to a Python object."""
<|body_0|>
def to_internal_value(self, data):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JsonField:
"""Deserialize a string instance containing a JSON document to a Python object."""
def to_representation(self, value):
"""Deserialize ``value`` a `str` instance containing a JSON document to a Python object."""
if isinstance(value, str):
return json.loads(value)
... | the_stack_v2_python_sparse | onadata/libs/serializers/fields/json_field.py | onaio/onadata | train | 177 |
09f14001bf83041998c835ce9d6bd84c2291bb63 | [
"self.ti_dicts = ti_dicts\nself.transforms = transforms\nself.log = _logger\nself.transformed_collection: list[TransformABC] = []\nself._validate_transforms()",
"if len(self.transforms) > 1:\n for transform in self.transforms:\n if transform.applies is None:\n raise ValueError('If more than o... | <|body_start_0|>
self.ti_dicts = ti_dicts
self.transforms = transforms
self.log = _logger
self.transformed_collection: list[TransformABC] = []
self._validate_transforms()
<|end_body_0|>
<|body_start_1|>
if len(self.transforms) > 1:
for transform in self.trans... | Transform Abstract Base Class | TransformsABC | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformsABC:
"""Transform Abstract Base Class"""
def __init__(self, ti_dicts: list[dict], transforms: list[GroupTransformModel | IndicatorTransformModel]):
"""Initialize instance properties."""
<|body_0|>
def _validate_transforms(self):
"""Validate the transfor... | stack_v2_sparse_classes_10k_train_007314 | 25,335 | permissive | [
{
"docstring": "Initialize instance properties.",
"name": "__init__",
"signature": "def __init__(self, ti_dicts: list[dict], transforms: list[GroupTransformModel | IndicatorTransformModel])"
},
{
"docstring": "Validate the transform model.",
"name": "_validate_transforms",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_003384 | Implement the Python class `TransformsABC` described below.
Class description:
Transform Abstract Base Class
Method signatures and docstrings:
- def __init__(self, ti_dicts: list[dict], transforms: list[GroupTransformModel | IndicatorTransformModel]): Initialize instance properties.
- def _validate_transforms(self): ... | Implement the Python class `TransformsABC` described below.
Class description:
Transform Abstract Base Class
Method signatures and docstrings:
- def __init__(self, ti_dicts: list[dict], transforms: list[GroupTransformModel | IndicatorTransformModel]): Initialize instance properties.
- def _validate_transforms(self): ... | 30dc147e40d63d1082ec2a5e6c62005b60c29c37 | <|skeleton|>
class TransformsABC:
"""Transform Abstract Base Class"""
def __init__(self, ti_dicts: list[dict], transforms: list[GroupTransformModel | IndicatorTransformModel]):
"""Initialize instance properties."""
<|body_0|>
def _validate_transforms(self):
"""Validate the transfor... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TransformsABC:
"""Transform Abstract Base Class"""
def __init__(self, ti_dicts: list[dict], transforms: list[GroupTransformModel | IndicatorTransformModel]):
"""Initialize instance properties."""
self.ti_dicts = ti_dicts
self.transforms = transforms
self.log = _logger
... | the_stack_v2_python_sparse | tcex/api/tc/ti_transform/transform_abc.py | ThreatConnect-Inc/tcex | train | 24 |
a39273827da5a139d0ae4b1b1a2ee992980b92b8 | [
"super().__init__()\nself.flows = torch.nn.ModuleList()\nfor i in range(flows):\n self.flows += [ResidualAffineCouplingLayer(in_channels=in_channels, hidden_channels=hidden_channels, kernel_size=kernel_size, base_dilation=base_dilation, layers=layers, stacks=1, global_channels=global_channels, dropout_rate=dropo... | <|body_start_0|>
super().__init__()
self.flows = torch.nn.ModuleList()
for i in range(flows):
self.flows += [ResidualAffineCouplingLayer(in_channels=in_channels, hidden_channels=hidden_channels, kernel_size=kernel_size, base_dilation=base_dilation, layers=layers, stacks=1, global_cha... | Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`: https://ar... | ResidualAffineCouplingBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualAffineCouplingBlock:
"""Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversar... | stack_v2_sparse_classes_10k_train_007315 | 7,596 | permissive | [
{
"docstring": "Initilize ResidualAffineCouplingBlock module. Args: in_channels (int): Number of input channels. hidden_channels (int): Number of hidden channels. flows (int): Number of flows. kernel_size (int): Kernel size for WaveNet. base_dilation (int): Base dilation factor for WaveNet. layers (int): Number... | 2 | null | Implement the Python class `ResidualAffineCouplingBlock` described below.
Class description:
Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditiona... | Implement the Python class `ResidualAffineCouplingBlock` described below.
Class description:
Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditiona... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class ResidualAffineCouplingBlock:
"""Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResidualAffineCouplingBlock:
"""Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning ... | the_stack_v2_python_sparse | espnet2/gan_tts/vits/residual_coupling.py | espnet/espnet | train | 7,242 |
0fec9cb4b8d86dfaea25aec8c1361f09dd7e1b5d | [
"super(Visibility, self).__init__()\nself.D_1 = D_1\nself.D_2 = D_2\nself.W_1 = W_1\nself.W_2 = W_2\nself.in_channels_xyz = in_channels_xyz\nself.in_channels_dir = in_channels_dir\nself.skips = skips\nfor i in range(D_1):\n if i == 0:\n layer = nn.Linear(in_channels_xyz, W_1)\n elif i in skips:\n ... | <|body_start_0|>
super(Visibility, self).__init__()
self.D_1 = D_1
self.D_2 = D_2
self.W_1 = W_1
self.W_2 = W_2
self.in_channels_xyz = in_channels_xyz
self.in_channels_dir = in_channels_dir
self.skips = skips
for i in range(D_1):
if i =... | Visibility | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Visibility:
def __init__(self, D_1=8, D_2=4, W_1=256, W_2=128, in_channels_xyz=63, in_channels_dir=27, skips=[4]):
"""D_1: number of layers for density (sigma) encoder W_1: number of hidden units in each layer in_channels_xyz: number of input channels for xyz (3+3*7*2=45 by default) in_c... | stack_v2_sparse_classes_10k_train_007316 | 18,983 | no_license | [
{
"docstring": "D_1: number of layers for density (sigma) encoder W_1: number of hidden units in each layer in_channels_xyz: number of input channels for xyz (3+3*7*2=45 by default) in_channels_dir: number of input channels for direction (3+3*4*2=27 by default) skips: add skip connection in the Dth layer",
... | 2 | stack_v2_sparse_classes_30k_train_004340 | Implement the Python class `Visibility` described below.
Class description:
Implement the Visibility class.
Method signatures and docstrings:
- def __init__(self, D_1=8, D_2=4, W_1=256, W_2=128, in_channels_xyz=63, in_channels_dir=27, skips=[4]): D_1: number of layers for density (sigma) encoder W_1: number of hidden... | Implement the Python class `Visibility` described below.
Class description:
Implement the Visibility class.
Method signatures and docstrings:
- def __init__(self, D_1=8, D_2=4, W_1=256, W_2=128, in_channels_xyz=63, in_channels_dir=27, skips=[4]): D_1: number of layers for density (sigma) encoder W_1: number of hidden... | 3b6e9d85e77077d1ad3b669fe88799d6a19e6d99 | <|skeleton|>
class Visibility:
def __init__(self, D_1=8, D_2=4, W_1=256, W_2=128, in_channels_xyz=63, in_channels_dir=27, skips=[4]):
"""D_1: number of layers for density (sigma) encoder W_1: number of hidden units in each layer in_channels_xyz: number of input channels for xyz (3+3*7*2=45 by default) in_c... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Visibility:
def __init__(self, D_1=8, D_2=4, W_1=256, W_2=128, in_channels_xyz=63, in_channels_dir=27, skips=[4]):
"""D_1: number of layers for density (sigma) encoder W_1: number of hidden units in each layer in_channels_xyz: number of input channels for xyz (3+3*7*2=45 by default) in_channels_dir: n... | the_stack_v2_python_sparse | models/nert.py | jcn16/nert | train | 0 | |
d9bf4a4d995e547f97c3ef55cf5049b6a7f9024e | [
"if not cls.ALERT_PROCESSOR:\n cls.ALERT_PROCESSOR = AlertProcessor()\nreturn cls.ALERT_PROCESSOR",
"output_config = load_config(include={'outputs.json'})['outputs']\nself.config = resources.merge_required_outputs(output_config, env['STREAMALERT_PREFIX'])\nself.alerts_table = AlertTable(env['ALERTS_TABLE'])",
... | <|body_start_0|>
if not cls.ALERT_PROCESSOR:
cls.ALERT_PROCESSOR = AlertProcessor()
return cls.ALERT_PROCESSOR
<|end_body_0|>
<|body_start_1|>
output_config = load_config(include={'outputs.json'})['outputs']
self.config = resources.merge_required_outputs(output_config, env['... | Orchestrates delivery of alerts to the appropriate dispatchers. | AlertProcessor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlertProcessor:
"""Orchestrates delivery of alerts to the appropriate dispatchers."""
def get_instance(cls):
"""Get an instance of the AlertProcessor, using a cached version if possible."""
<|body_0|>
def __init__(self):
"""Initialization logic that can be cached... | stack_v2_sparse_classes_10k_train_007317 | 6,845 | permissive | [
{
"docstring": "Get an instance of the AlertProcessor, using a cached version if possible.",
"name": "get_instance",
"signature": "def get_instance(cls)"
},
{
"docstring": "Initialization logic that can be cached across invocations",
"name": "__init__",
"signature": "def __init__(self)"
... | 6 | stack_v2_sparse_classes_30k_train_003126 | Implement the Python class `AlertProcessor` described below.
Class description:
Orchestrates delivery of alerts to the appropriate dispatchers.
Method signatures and docstrings:
- def get_instance(cls): Get an instance of the AlertProcessor, using a cached version if possible.
- def __init__(self): Initialization log... | Implement the Python class `AlertProcessor` described below.
Class description:
Orchestrates delivery of alerts to the appropriate dispatchers.
Method signatures and docstrings:
- def get_instance(cls): Get an instance of the AlertProcessor, using a cached version if possible.
- def __init__(self): Initialization log... | 75ba140d2e1aa6e903313d88326920adcb8bff45 | <|skeleton|>
class AlertProcessor:
"""Orchestrates delivery of alerts to the appropriate dispatchers."""
def get_instance(cls):
"""Get an instance of the AlertProcessor, using a cached version if possible."""
<|body_0|>
def __init__(self):
"""Initialization logic that can be cached... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AlertProcessor:
"""Orchestrates delivery of alerts to the appropriate dispatchers."""
def get_instance(cls):
"""Get an instance of the AlertProcessor, using a cached version if possible."""
if not cls.ALERT_PROCESSOR:
cls.ALERT_PROCESSOR = AlertProcessor()
return cls.A... | the_stack_v2_python_sparse | streamalert/alert_processor/main.py | avmi/streamalert | train | 0 |
e995551f989d9afd3ce9a01a19a5ec812d41e6aa | [
"self.__logger = State().getLogger('DetectionCore_Component_Logger')\nself.__logger.info('Starting __init__()', 'HorizontalLineRemoveDetector:__init__')\nself.__indexOfProcessMat = indexOfProcessMat\nself.__anchorPoint = anchorPoint\nself.__kernelWidth = kernelWidth\nself.__kernelHeight = kernelHeight\nself.__morph... | <|body_start_0|>
self.__logger = State().getLogger('DetectionCore_Component_Logger')
self.__logger.info('Starting __init__()', 'HorizontalLineRemoveDetector:__init__')
self.__indexOfProcessMat = indexOfProcessMat
self.__anchorPoint = anchorPoint
self.__kernelWidth = kernelWidth
... | HorizontalLineRemoveDetector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HorizontalLineRemoveDetector:
def __init__(self, indexOfProcessMat=0, anchorPoint=(-1, -1), kernelWidth=1, kernelHeight=3, morphOfKernel=cv2.MORPH_RECT, showImagesInWindow=True):
"""To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!"""
<|body_0|>
def detect(self, mats):
... | stack_v2_sparse_classes_10k_train_007318 | 3,792 | no_license | [
{
"docstring": "To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!",
"name": "__init__",
"signature": "def __init__(self, indexOfProcessMat=0, anchorPoint=(-1, -1), kernelWidth=1, kernelHeight=3, morphOfKernel=cv2.MORPH_RECT, showImagesInWindow=True)"
},
{
"docstring": "To-Do: Bitte Kommentar b... | 2 | stack_v2_sparse_classes_30k_val_000028 | Implement the Python class `HorizontalLineRemoveDetector` described below.
Class description:
Implement the HorizontalLineRemoveDetector class.
Method signatures and docstrings:
- def __init__(self, indexOfProcessMat=0, anchorPoint=(-1, -1), kernelWidth=1, kernelHeight=3, morphOfKernel=cv2.MORPH_RECT, showImagesInWin... | Implement the Python class `HorizontalLineRemoveDetector` described below.
Class description:
Implement the HorizontalLineRemoveDetector class.
Method signatures and docstrings:
- def __init__(self, indexOfProcessMat=0, anchorPoint=(-1, -1), kernelWidth=1, kernelHeight=3, morphOfKernel=cv2.MORPH_RECT, showImagesInWin... | 3daaa72b193ebfb55894b47b6a752cdc2192bb6b | <|skeleton|>
class HorizontalLineRemoveDetector:
def __init__(self, indexOfProcessMat=0, anchorPoint=(-1, -1), kernelWidth=1, kernelHeight=3, morphOfKernel=cv2.MORPH_RECT, showImagesInWindow=True):
"""To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!"""
<|body_0|>
def detect(self, mats):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HorizontalLineRemoveDetector:
def __init__(self, indexOfProcessMat=0, anchorPoint=(-1, -1), kernelWidth=1, kernelHeight=3, morphOfKernel=cv2.MORPH_RECT, showImagesInWindow=True):
"""To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!"""
self.__logger = State().getLogger('DetectionCore_Componen... | the_stack_v2_python_sparse | SheetMusicScanner/DetectionCore_Component/Detector/HorizontalLineRemoveDetector.py | jadeskon/score-scan | train | 0 | |
4c55d1d11be9471bd623e486fc8554279b5ba68d | [
"if source.ctype not in ConstructType.features:\n raise ValueError(\"Expected source to be of ctype 'features'.\")\nsuper().__init__(expected=(source,))\nself.interface = interface\nself.temperature = temperature",
"strengths, = self.extract_inputs(inputs)\ncmds_by_dims = group_by_dims(self.interface.cmds)\npa... | <|body_start_0|>
if source.ctype not in ConstructType.features:
raise ValueError("Expected source to be of ctype 'features'.")
super().__init__(expected=(source,))
self.interface = interface
self.temperature = temperature
<|end_body_0|>
<|body_start_1|>
strengths, = ... | Selects actions and paramaters according to Boltzmann distributions. Action and parameter features are selected from a given client interface. For parameter features, if a parameter feature is found to be of a singleton dimension (i.e., a dimension with only one value), it is treated like a continuous parameter and its... | ActionSelector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionSelector:
"""Selects actions and paramaters according to Boltzmann distributions. Action and parameter features are selected from a given client interface. For parameter features, if a parameter feature is found to be of a singleton dimension (i.e., a dimension with only one value), it is t... | stack_v2_sparse_classes_10k_train_007319 | 7,721 | permissive | [
{
"docstring": "Initialize an ``ActionSelector`` instance. :param dims: Registered action dimensions. :param temperature: Temperature of the Boltzmann distribution.",
"name": "__init__",
"signature": "def __init__(self, source, interface, temperature)"
},
{
"docstring": "Select actionable chunks... | 2 | stack_v2_sparse_classes_30k_val_000269 | Implement the Python class `ActionSelector` described below.
Class description:
Selects actions and paramaters according to Boltzmann distributions. Action and parameter features are selected from a given client interface. For parameter features, if a parameter feature is found to be of a singleton dimension (i.e., a ... | Implement the Python class `ActionSelector` described below.
Class description:
Selects actions and paramaters according to Boltzmann distributions. Action and parameter features are selected from a given client interface. For parameter features, if a parameter feature is found to be of a singleton dimension (i.e., a ... | d8ff4c545785ec6cddc989dded9c1a9d3dd91514 | <|skeleton|>
class ActionSelector:
"""Selects actions and paramaters according to Boltzmann distributions. Action and parameter features are selected from a given client interface. For parameter features, if a parameter feature is found to be of a singleton dimension (i.e., a dimension with only one value), it is t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ActionSelector:
"""Selects actions and paramaters according to Boltzmann distributions. Action and parameter features are selected from a given client interface. For parameter features, if a parameter feature is found to be of a singleton dimension (i.e., a dimension with only one value), it is treated like a... | the_stack_v2_python_sparse | pyClarion/components/propagators.py | HZeng3/pyClarion | train | 0 |
58f65d75ad373949cf0198f5c14d8a296cf06d03 | [
"super().__init__(coordinator=coordinator, kind=kind, name=name, item_id=item_id, icon=icon)\nself._state_key = state_key\nself._state = None\nself._last_action = 0\nself._state_delay = 30",
"state_int = 0\nif self._last_action < time.time() - self._state_delay:\n state_int = int(self.coordinator.data[self._it... | <|body_start_0|>
super().__init__(coordinator=coordinator, kind=kind, name=name, item_id=item_id, icon=icon)
self._state_key = state_key
self._state = None
self._last_action = 0
self._state_delay = 30
<|end_body_0|>
<|body_start_1|>
state_int = 0
if self._last_ac... | Define an Omnilogic Base Switch entity to be extended. | OmniLogicSwitch | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OmniLogicSwitch:
"""Define an Omnilogic Base Switch entity to be extended."""
def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None:
"""Initialize Entities."""
<|body_0|>
def is_on(self):
... | stack_v2_sparse_classes_10k_train_007320 | 8,137 | permissive | [
{
"docstring": "Initialize Entities.",
"name": "__init__",
"signature": "def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None"
},
{
"docstring": "Return the on/off state of the switch.",
"name": "is_on",
"sig... | 2 | null | Implement the Python class `OmniLogicSwitch` described below.
Class description:
Define an Omnilogic Base Switch entity to be extended.
Method signatures and docstrings:
- def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None: Initialize E... | Implement the Python class `OmniLogicSwitch` described below.
Class description:
Define an Omnilogic Base Switch entity to be extended.
Method signatures and docstrings:
- def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None: Initialize E... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OmniLogicSwitch:
"""Define an Omnilogic Base Switch entity to be extended."""
def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None:
"""Initialize Entities."""
<|body_0|>
def is_on(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OmniLogicSwitch:
"""Define an Omnilogic Base Switch entity to be extended."""
def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None:
"""Initialize Entities."""
super().__init__(coordinator=coordinator, kind=kin... | the_stack_v2_python_sparse | homeassistant/components/omnilogic/switch.py | home-assistant/core | train | 35,501 |
99c3c1b966c4f3037e7b35909ea5c5a885bf9c03 | [
"session = DBSession()\nsession.merge(t_trans_detail)\nsession.commit()\nsession.close()",
"session = DBSession()\nif 'trans_sq' in kwargs:\n _trans_sq = kwargs['trans_sq']\nselect = session.query(T_trans_detail).filter(T_trans_detail.trans_sq == _trans_sq).first()\nprint(select)\nsession.close()\nreturn selec... | <|body_start_0|>
session = DBSession()
session.merge(t_trans_detail)
session.commit()
session.close()
<|end_body_0|>
<|body_start_1|>
session = DBSession()
if 'trans_sq' in kwargs:
_trans_sq = kwargs['trans_sq']
select = session.query(T_trans_detail).... | 交易model类 | T_trans_detail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class T_trans_detail:
"""交易model类"""
def save(t_trans_detail):
"""新加/修改交易表 :param trans: :return:"""
<|body_0|>
def select(self, **kwargs):
"""新加/修改交易表 :param trans: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
session = DBSession()
... | stack_v2_sparse_classes_10k_train_007321 | 8,115 | no_license | [
{
"docstring": "新加/修改交易表 :param trans: :return:",
"name": "save",
"signature": "def save(t_trans_detail)"
},
{
"docstring": "新加/修改交易表 :param trans: :return:",
"name": "select",
"signature": "def select(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004099 | Implement the Python class `T_trans_detail` described below.
Class description:
交易model类
Method signatures and docstrings:
- def save(t_trans_detail): 新加/修改交易表 :param trans: :return:
- def select(self, **kwargs): 新加/修改交易表 :param trans: :return: | Implement the Python class `T_trans_detail` described below.
Class description:
交易model类
Method signatures and docstrings:
- def save(t_trans_detail): 新加/修改交易表 :param trans: :return:
- def select(self, **kwargs): 新加/修改交易表 :param trans: :return:
<|skeleton|>
class T_trans_detail:
"""交易model类"""
def save(t_tr... | 1bc744a6d331b4b733f6b6658b8310eb0c30524e | <|skeleton|>
class T_trans_detail:
"""交易model类"""
def save(t_trans_detail):
"""新加/修改交易表 :param trans: :return:"""
<|body_0|>
def select(self, **kwargs):
"""新加/修改交易表 :param trans: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class T_trans_detail:
"""交易model类"""
def save(t_trans_detail):
"""新加/修改交易表 :param trans: :return:"""
session = DBSession()
session.merge(t_trans_detail)
session.commit()
session.close()
def select(self, **kwargs):
"""新加/修改交易表 :param trans: :return:"""
... | the_stack_v2_python_sparse | investment/transaction/models.py | cliicy/vtrade | train | 0 |
69a5d7cb9e4791d5730c7dac0b76819ab291faeb | [
"self.root = None\nfor item in container:\n self.insert(item)",
"def _str(indent: str, root: _BSTNode) -> str:\n \"\"\"\n Return a 'sideways' representation of the values in the BST rooted\n at root, with right subtree indented above root, and left indented\n below root, eac... | <|body_start_0|>
self.root = None
for item in container:
self.insert(item)
<|end_body_0|>
<|body_start_1|>
def _str(indent: str, root: _BSTNode) -> str:
"""
Return a 'sideways' representation of the values in the BST rooted
at root... | A Binary Search Tree. | BST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BST:
"""A Binary Search Tree."""
def __init__(self, container=[]):
"""(BST, list) -> NoneType Initialize this BST by inserting the items from container (default []) one by one, in the order given."""
<|body_0|>
def __str__(self):
"""(BST) -> str Return a "sideway... | stack_v2_sparse_classes_10k_train_007322 | 3,829 | no_license | [
{
"docstring": "(BST, list) -> NoneType Initialize this BST by inserting the items from container (default []) one by one, in the order given.",
"name": "__init__",
"signature": "def __init__(self, container=[])"
},
{
"docstring": "(BST) -> str Return a \"sideways\" representation of the values ... | 5 | stack_v2_sparse_classes_30k_train_001593 | Implement the Python class `BST` described below.
Class description:
A Binary Search Tree.
Method signatures and docstrings:
- def __init__(self, container=[]): (BST, list) -> NoneType Initialize this BST by inserting the items from container (default []) one by one, in the order given.
- def __str__(self): (BST) -> ... | Implement the Python class `BST` described below.
Class description:
A Binary Search Tree.
Method signatures and docstrings:
- def __init__(self, container=[]): (BST, list) -> NoneType Initialize this BST by inserting the items from container (default []) one by one, in the order given.
- def __str__(self): (BST) -> ... | c7437d387dc2b9a8039c60d8786373899c2e28bd | <|skeleton|>
class BST:
"""A Binary Search Tree."""
def __init__(self, container=[]):
"""(BST, list) -> NoneType Initialize this BST by inserting the items from container (default []) one by one, in the order given."""
<|body_0|>
def __str__(self):
"""(BST) -> str Return a "sideway... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BST:
"""A Binary Search Tree."""
def __init__(self, container=[]):
"""(BST, list) -> NoneType Initialize this BST by inserting the items from container (default []) one by one, in the order given."""
self.root = None
for item in container:
self.insert(item)
def __... | the_stack_v2_python_sparse | CSC148/06 Tree(BST)/lab9/BST_rec1.py | xxcocoymlxx/Study-Notes | train | 2 |
ac2b9a4348543ce1c9ad4a3cefd2fe31343db183 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ConditionalAccessApplications()",
"from .conditional_access_filter import ConditionalAccessFilter\nfrom .conditional_access_filter import ConditionalAccessFilter\nfields: Dict[str, Callable[[Any], None]] = {'applicationFilter': lambda ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ConditionalAccessApplications()
<|end_body_0|>
<|body_start_1|>
from .conditional_access_filter import ConditionalAccessFilter
from .conditional_access_filter import ConditionalAccessFil... | ConditionalAccessApplications | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionalAccessApplications:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessApplications:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator val... | stack_v2_sparse_classes_10k_train_007323 | 4,721 | 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: ConditionalAccessApplications",
"name": "create_from_discriminator_value",
"signature": "def create_from_dis... | 3 | null | Implement the Python class `ConditionalAccessApplications` described below.
Class description:
Implement the ConditionalAccessApplications class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessApplications: Creates a new instance of th... | Implement the Python class `ConditionalAccessApplications` described below.
Class description:
Implement the ConditionalAccessApplications class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessApplications: Creates a new instance of th... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ConditionalAccessApplications:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessApplications:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator val... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConditionalAccessApplications:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessApplications:
"""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_stack_v2_python_sparse | msgraph/generated/models/conditional_access_applications.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
f7dfcee8746eda0689fe4578f293d584e1e9594a | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('arshadr_rcallah_shaikh1', 'arshadr_rcallah_shaikh1')\nurl = 'http://files.zillowstatic.com/research/public/City/City_ZriPerSqft_AllHomes.csv'\ns = requests.get(url).content\ndf = pd.read_csv(io.StringIO(... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('arshadr_rcallah_shaikh1', 'arshadr_rcallah_shaikh1')
url = 'http://files.zillowstatic.com/research/public/City/City_ZriPerSqft_AllHomes.csv'
s = r... | price_per_sqft_data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class price_per_sqft_data:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing ever... | stack_v2_sparse_classes_10k_train_007324 | 4,679 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `price_per_sqft_data` described below.
Class description:
Implement the price_per_sqft_data class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), start... | Implement the Python class `price_per_sqft_data` described below.
Class description:
Implement the price_per_sqft_data class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), start... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class price_per_sqft_data:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing ever... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class price_per_sqft_data:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('arshadr_rcallah_shaikh1', 'arsh... | the_stack_v2_python_sparse | arshadr_rcallah_shaikh1/price_per_sqft_data.py | maximega/course-2019-spr-proj | train | 2 | |
975296a4650182c30efa9be0b715349428d05f5b | [
"lst = []\nfor i in range(1, n + 1):\n s = str(i)\n for j in s:\n lst.append(j)\nreturn int(lst[n - 1])",
"groups = [9, 180, 2700, 36000, 450000, 5400000, 63000000, 720000000, 8100000000]\ng = bisect.bisect_left(groups, n)\nnth = n - sum(groups[:g]) - 1\nd, m = divmod(nth, g + 1)\nnumber = d + pow(10... | <|body_start_0|>
lst = []
for i in range(1, n + 1):
s = str(i)
for j in s:
lst.append(j)
return int(lst[n - 1])
<|end_body_0|>
<|body_start_1|>
groups = [9, 180, 2700, 36000, 450000, 5400000, 63000000, 720000000, 8100000000]
g = bisect.bis... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findNthDigit1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def findNthDigit(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
lst = []
for i in range(1, n + 1):
s = str(i)
... | stack_v2_sparse_classes_10k_train_007325 | 3,069 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "findNthDigit1",
"signature": "def findNthDigit1(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "findNthDigit",
"signature": "def findNthDigit(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000583 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findNthDigit1(self, n): :type n: int :rtype: int
- def findNthDigit(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findNthDigit1(self, n): :type n: int :rtype: int
- def findNthDigit(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def findNthDigit1(self, n):
... | a57282895fb213b68e5d81db301903721a92d80f | <|skeleton|>
class Solution:
def findNthDigit1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def findNthDigit(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findNthDigit1(self, n):
""":type n: int :rtype: int"""
lst = []
for i in range(1, n + 1):
s = str(i)
for j in s:
lst.append(j)
return int(lst[n - 1])
def findNthDigit(self, n):
""":type n: int :rtype: int"""
... | the_stack_v2_python_sparse | Python/400_nth-digit.py | antonylu/leetcode2 | train | 0 | |
04a36bcdfda888677e735b3eb761cf5833ed0641 | [
"self.v_deprecate = v_deprecate\nself.v_remove = v_remove\nself.v_current = v_current\nself.details = details\nif self.v_deprecate is None and self.v_remove is not None:\n raise TypeError('Cannot set `v_remove` without also setting `v_deprecate`')\nself.is_deprecated = False\nself.is_unsupported = False\nif self... | <|body_start_0|>
self.v_deprecate = v_deprecate
self.v_remove = v_remove
self.v_current = v_current
self.details = details
if self.v_deprecate is None and self.v_remove is not None:
raise TypeError('Cannot set `v_remove` without also setting `v_deprecate`')
se... | Deprecated | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Deprecated:
def __init__(self, v_deprecate=None, v_remove=None, v_current=None, details=''):
"""Decorator to mark a function or class as deprecated. Issue warning when the function is called or the class is instantiated, and add a warning to the docstring. The optional `details` argument... | stack_v2_sparse_classes_10k_train_007326 | 16,173 | permissive | [
{
"docstring": "Decorator to mark a function or class as deprecated. Issue warning when the function is called or the class is instantiated, and add a warning to the docstring. The optional `details` argument will be appended to the deprecation message and the docstring Parameters ---------- v_deprecate: String... | 6 | stack_v2_sparse_classes_30k_train_005084 | Implement the Python class `Deprecated` described below.
Class description:
Implement the Deprecated class.
Method signatures and docstrings:
- def __init__(self, v_deprecate=None, v_remove=None, v_current=None, details=''): Decorator to mark a function or class as deprecated. Issue warning when the function is calle... | Implement the Python class `Deprecated` described below.
Class description:
Implement the Deprecated class.
Method signatures and docstrings:
- def __init__(self, v_deprecate=None, v_remove=None, v_current=None, details=''): Decorator to mark a function or class as deprecated. Issue warning when the function is calle... | 3709d5e97dd23efa0df1b79982ae029789e1af57 | <|skeleton|>
class Deprecated:
def __init__(self, v_deprecate=None, v_remove=None, v_current=None, details=''):
"""Decorator to mark a function or class as deprecated. Issue warning when the function is called or the class is instantiated, and add a warning to the docstring. The optional `details` argument... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Deprecated:
def __init__(self, v_deprecate=None, v_remove=None, v_current=None, details=''):
"""Decorator to mark a function or class as deprecated. Issue warning when the function is called or the class is instantiated, and add a warning to the docstring. The optional `details` argument will be appen... | the_stack_v2_python_sparse | hyperparameter_hunter/utils/version_utils.py | shaoeric/hyperparameter_hunter | train | 0 | |
95f8d5cdb04db131eec782075bf3a3abf601f4e7 | [
"self.momentum = momentum\nvelocitys = dict()\nfor k, v in model.params.items():\n velocitys[k] = np.zeros_like(v)\nself.velocitys = velocitys",
"momentum = self.momentum\nvelocitys = self.velocitys\nparams = model.params\ngrads = model.grads\nfor k in grads:\n velocitys[k] = momentum * velocitys[k] + learn... | <|body_start_0|>
self.momentum = momentum
velocitys = dict()
for k, v in model.params.items():
velocitys[k] = np.zeros_like(v)
self.velocitys = velocitys
<|end_body_0|>
<|body_start_1|>
momentum = self.momentum
velocitys = self.velocitys
params = mode... | SGDmomentumOptim | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SGDmomentumOptim:
def __init__(self, model, momentum=0.5):
"""Inputs: :param model: a neural netowrk class object :param momentum: (float)"""
<|body_0|>
def step(self, model, learning_rate):
"""Implement a one-step SGD+momentum update on network's parameters Inputs: ... | stack_v2_sparse_classes_10k_train_007327 | 9,004 | no_license | [
{
"docstring": "Inputs: :param model: a neural netowrk class object :param momentum: (float)",
"name": "__init__",
"signature": "def __init__(self, model, momentum=0.5)"
},
{
"docstring": "Implement a one-step SGD+momentum update on network's parameters Inputs: :param model: a neural network cla... | 2 | stack_v2_sparse_classes_30k_train_004753 | Implement the Python class `SGDmomentumOptim` described below.
Class description:
Implement the SGDmomentumOptim class.
Method signatures and docstrings:
- def __init__(self, model, momentum=0.5): Inputs: :param model: a neural netowrk class object :param momentum: (float)
- def step(self, model, learning_rate): Impl... | Implement the Python class `SGDmomentumOptim` described below.
Class description:
Implement the SGDmomentumOptim class.
Method signatures and docstrings:
- def __init__(self, model, momentum=0.5): Inputs: :param model: a neural netowrk class object :param momentum: (float)
- def step(self, model, learning_rate): Impl... | a401d09c28432109e9ced10e5011bff97dda05b9 | <|skeleton|>
class SGDmomentumOptim:
def __init__(self, model, momentum=0.5):
"""Inputs: :param model: a neural netowrk class object :param momentum: (float)"""
<|body_0|>
def step(self, model, learning_rate):
"""Implement a one-step SGD+momentum update on network's parameters Inputs: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SGDmomentumOptim:
def __init__(self, model, momentum=0.5):
"""Inputs: :param model: a neural netowrk class object :param momentum: (float)"""
self.momentum = momentum
velocitys = dict()
for k, v in model.params.items():
velocitys[k] = np.zeros_like(v)
self.v... | the_stack_v2_python_sparse | assignment2/E4040.2017.Assign2.xw2501/E4040.2017.Assign2.xw2501/ecbm4040/optimizers.py | xw2501/Deep_Learning_study | train | 7 | |
03e838c9d32770daa684acfa8c610e6d1f535f86 | [
"self.gau: np.ndarray = self._gaussian_window(mean, sigma)\nself.map: np.ndarray = np.outer(self.gau, self.gau)\nself.size: float = mean\nself.origin: Pose = Pose() if not origin else origin\nCostmap.__init__(self, resolution, mean, mean, self.origin, self.map)",
"n = np.arange(0, mean) - (mean - 1.0) / 2.0\nsig2... | <|body_start_0|>
self.gau: np.ndarray = self._gaussian_window(mean, sigma)
self.map: np.ndarray = np.outer(self.gau, self.gau)
self.size: float = mean
self.origin: Pose = Pose() if not origin else origin
Costmap.__init__(self, resolution, mean, mean, self.origin, self.map)
<|end_... | Gaussian Costmaps are 2D gaussian distributions around the origin with the given mean and sigma | GaussianCostmap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianCostmap:
"""Gaussian Costmaps are 2D gaussian distributions around the origin with the given mean and sigma"""
def __init__(self, mean: int, sigma: float, resolution: Optional[float]=0.02, origin: Optional[Pose]=None):
"""This Costmap creates a 2D gaussian distribution around... | stack_v2_sparse_classes_10k_train_007328 | 37,310 | no_license | [
{
"docstring": "This Costmap creates a 2D gaussian distribution around the origin with the specified size. :param mean: The mean input for the gaussian distribution, this also specifies the length of the side of the resulting costmap. The costmap is Created as a square. :param sigma: The sigma input for the gau... | 2 | stack_v2_sparse_classes_30k_train_004780 | Implement the Python class `GaussianCostmap` described below.
Class description:
Gaussian Costmaps are 2D gaussian distributions around the origin with the given mean and sigma
Method signatures and docstrings:
- def __init__(self, mean: int, sigma: float, resolution: Optional[float]=0.02, origin: Optional[Pose]=None... | Implement the Python class `GaussianCostmap` described below.
Class description:
Gaussian Costmaps are 2D gaussian distributions around the origin with the given mean and sigma
Method signatures and docstrings:
- def __init__(self, mean: int, sigma: float, resolution: Optional[float]=0.02, origin: Optional[Pose]=None... | f9ef666d6d4685660c9517652f2c568ed2c9367c | <|skeleton|>
class GaussianCostmap:
"""Gaussian Costmaps are 2D gaussian distributions around the origin with the given mean and sigma"""
def __init__(self, mean: int, sigma: float, resolution: Optional[float]=0.02, origin: Optional[Pose]=None):
"""This Costmap creates a 2D gaussian distribution around... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GaussianCostmap:
"""Gaussian Costmaps are 2D gaussian distributions around the origin with the given mean and sigma"""
def __init__(self, mean: int, sigma: float, resolution: Optional[float]=0.02, origin: Optional[Pose]=None):
"""This Costmap creates a 2D gaussian distribution around the origin w... | the_stack_v2_python_sparse | src/pycram/costmaps.py | cram2/pycram | train | 12 |
bf4592de8476d14f3ecaf7f2210601fad3542d0a | [
"out = [[]]\nfor elem in nums:\n out += [curr + [elem] for curr in out]\nreturn out",
"out = []\nfor elem in nums:\n list1 = []\n for i in out:\n list1.append(i + [elem])\n out.extend(list1[:])\n out.append([elem])\nout.append([])\nreturn out"
] | <|body_start_0|>
out = [[]]
for elem in nums:
out += [curr + [elem] for curr in out]
return out
<|end_body_0|>
<|body_start_1|>
out = []
for elem in nums:
list1 = []
for i in out:
list1.append(i + [elem])
out.extend... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subsets_single_line(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
out = [[]]
... | stack_v2_sparse_classes_10k_train_007329 | 1,197 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsets_single_line",
"signature": "def subsets_single_line(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsets",
"signature": "def subsets(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005196 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsets_single_line(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def subsets(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsets_single_line(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def subsets(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class So... | 8731e2ccfbda9323ea5c8629599806cd1c37c3bf | <|skeleton|>
class Solution:
def subsets_single_line(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def subsets_single_line(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
out = [[]]
for elem in nums:
out += [curr + [elem] for curr in out]
return out
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]""... | the_stack_v2_python_sparse | problems/greedy/Subsets.py | jonu4u/DataStructuresInPython | train | 0 | |
ee2c801c1b275cce525003c47caa7225648ff0a3 | [
"self.capacity = capacity\nself.head = Node(0, 0)\nself.tail = Node(0, 0)\nself.head.next = self.tail\nself.tail.previous = self.head\nself.map = {}",
"current = self.tail.previous\ncurrent.next = node\nnode.previous = current\nself.tail.previous = node\nnode.next = self.tail",
"previous_node = node.previous\nn... | <|body_start_0|>
self.capacity = capacity
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.next = self.tail
self.tail.previous = self.head
self.map = {}
<|end_body_0|>
<|body_start_1|>
current = self.tail.previous
current.next = node
node.p... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":param capacity: the defined capacity of the cache =================================== This method initializes a doubly linked list with two nodes: head and tail, connected to one another. A map is also initialized. Given a key, this map is used... | stack_v2_sparse_classes_10k_train_007330 | 4,381 | no_license | [
{
"docstring": ":param capacity: the defined capacity of the cache =================================== This method initializes a doubly linked list with two nodes: head and tail, connected to one another. A map is also initialized. Given a key, this map is used for a constant lookup for the corresponding node i... | 5 | stack_v2_sparse_classes_30k_train_007097 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :param capacity: the defined capacity of the cache =================================== This method initializes a doubly linked list with two nodes: ... | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :param capacity: the defined capacity of the cache =================================== This method initializes a doubly linked list with two nodes: ... | 01cba9d7bf940fbfcaa4dfe15afdb9733e726e22 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":param capacity: the defined capacity of the cache =================================== This method initializes a doubly linked list with two nodes: head and tail, connected to one another. A map is also initialized. Given a key, this map is used... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":param capacity: the defined capacity of the cache =================================== This method initializes a doubly linked list with two nodes: head and tail, connected to one another. A map is also initialized. Given a key, this map is used for a constan... | the_stack_v2_python_sparse | AlgorithmProblems/leetcode_146.py | nabinn/DS_and_Algorithms | train | 1 | |
3717b6d79da8580f017c2c91375b795d6161e9e6 | [
"self.content = []\nif not content is None:\n self.append(content)\nself.attr = kwargs",
"if isinstance(content, str):\n self.content.append(TextEntry(content))\nelse:\n self.content.append(content)",
"file_out.write(cur_ind + '<{}'.format(self.tag))\nfor key, val in self.attr.items():\n file_out.wr... | <|body_start_0|>
self.content = []
if not content is None:
self.append(content)
self.attr = kwargs
<|end_body_0|>
<|body_start_1|>
if isinstance(content, str):
self.content.append(TextEntry(content))
else:
self.content.append(content)
<|end_bo... | An element represents one level of html tag, which can contain more nested elements | Element | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Element:
"""An element represents one level of html tag, which can contain more nested elements"""
def __init__(self, content=None, **kwargs):
"""Optional content is the next element nested under this one"""
<|body_0|>
def append(self, content):
"""Content to be ... | stack_v2_sparse_classes_10k_train_007331 | 4,165 | no_license | [
{
"docstring": "Optional content is the next element nested under this one",
"name": "__init__",
"signature": "def __init__(self, content=None, **kwargs)"
},
{
"docstring": "Content to be appended is either an Element or a string, which will be used to append a new TextElement",
"name": "app... | 3 | null | Implement the Python class `Element` described below.
Class description:
An element represents one level of html tag, which can contain more nested elements
Method signatures and docstrings:
- def __init__(self, content=None, **kwargs): Optional content is the next element nested under this one
- def append(self, con... | Implement the Python class `Element` described below.
Class description:
An element represents one level of html tag, which can contain more nested elements
Method signatures and docstrings:
- def __init__(self, content=None, **kwargs): Optional content is the next element nested under this one
- def append(self, con... | e298b1151dab639659d8dfa56f47bcb43dd3438f | <|skeleton|>
class Element:
"""An element represents one level of html tag, which can contain more nested elements"""
def __init__(self, content=None, **kwargs):
"""Optional content is the next element nested under this one"""
<|body_0|>
def append(self, content):
"""Content to be ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Element:
"""An element represents one level of html tag, which can contain more nested elements"""
def __init__(self, content=None, **kwargs):
"""Optional content is the next element nested under this one"""
self.content = []
if not content is None:
self.append(content... | the_stack_v2_python_sparse | students/RoyC/Lesson07/html_render.py | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | train | 13 |
78e10f6bc4b8a3840324f633a5fc7870948f0730 | [
"m = self.gap().InvariantBilinearForm()['matrix'].matrix()\nm.set_immutable()\nreturn m",
"m = self.gap().InvariantQuadraticForm()['matrix'].matrix()\nm.set_immutable()\nreturn m"
] | <|body_start_0|>
m = self.gap().InvariantBilinearForm()['matrix'].matrix()
m.set_immutable()
return m
<|end_body_0|>
<|body_start_1|>
m = self.gap().InvariantQuadraticForm()['matrix'].matrix()
m.set_immutable()
return m
<|end_body_1|>
| OrthogonalMatrixGroup_gap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrthogonalMatrixGroup_gap:
def invariant_bilinear_form(self):
"""Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix `M` such that, for every group element g, the identity `g m g^T = m` holds. In characteristic different from two, this uniquely determin... | stack_v2_sparse_classes_10k_train_007332 | 13,931 | no_license | [
{
"docstring": "Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix `M` such that, for every group element g, the identity `g m g^T = m` holds. In characteristic different from two, this uniquely determines the orthogonal group. EXAMPLES:: sage: G = GO(4, GF(7), -1) sage: G.in... | 2 | stack_v2_sparse_classes_30k_train_003854 | Implement the Python class `OrthogonalMatrixGroup_gap` described below.
Class description:
Implement the OrthogonalMatrixGroup_gap class.
Method signatures and docstrings:
- def invariant_bilinear_form(self): Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix `M` such that, for eve... | Implement the Python class `OrthogonalMatrixGroup_gap` described below.
Class description:
Implement the OrthogonalMatrixGroup_gap class.
Method signatures and docstrings:
- def invariant_bilinear_form(self): Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix `M` such that, for eve... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class OrthogonalMatrixGroup_gap:
def invariant_bilinear_form(self):
"""Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix `M` such that, for every group element g, the identity `g m g^T = m` holds. In characteristic different from two, this uniquely determin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OrthogonalMatrixGroup_gap:
def invariant_bilinear_form(self):
"""Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix `M` such that, for every group element g, the identity `g m g^T = m` holds. In characteristic different from two, this uniquely determines the orthogo... | the_stack_v2_python_sparse | sage/src/sage/groups/matrix_gps/orthogonal.py | bopopescu/geosci | train | 0 | |
b60734479f1c0cb2ccbcb23571f67dd1c408a627 | [
"rights = access.GSoCChecker(params)\nrights['any_access'] = ['allow']\nrights['show'] = [('checkIsSurveyReadable', grading_survey_logic)]\nrights['create'] = ['checkIsUser']\nrights['edit'] = [('checkIsSurveyWritable', grading_survey_logic)]\nrights['delete'] = ['checkIsDeveloper']\nrights['list'] = ['checkDocumen... | <|body_start_0|>
rights = access.GSoCChecker(params)
rights['any_access'] = ['allow']
rights['show'] = [('checkIsSurveyReadable', grading_survey_logic)]
rights['create'] = ['checkIsUser']
rights['edit'] = [('checkIsSurveyWritable', grading_survey_logic)]
rights['delete'] ... | View methods for the GradingProjectSurvey model. | View | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
"""View methods for the GradingProjectSurvey model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
... | stack_v2_sparse_classes_10k_train_007333 | 9,757 | permissive | [
{
"docstring": "Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View",
"name": "__init__",
"signature": "def __init__(self, params=None)"
},
{
"docstring": "Returns t... | 3 | null | Implement the Python class `View` described below.
Class description:
View methods for the GradingProjectSurvey model.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete vie... | Implement the Python class `View` described below.
Class description:
View methods for the GradingProjectSurvey model.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete vie... | 9bd45c168f8ddb5c0e6c04eacdcaeafd61908be7 | <|skeleton|>
class View:
"""View methods for the GradingProjectSurvey model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class View:
"""View methods for the GradingProjectSurvey model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
rights... | the_stack_v2_python_sparse | app/soc/modules/gsoc/views/models/grading_project_survey.py | pombredanne/Melange-1 | train | 0 |
00dfefaa2e5862a770a21fca1ff2cf2270656e93 | [
"dummy: ListNode = ListNode(0)\nlength: int = 0\ndummy.next = head\nfirst: ListNode = head\nwhile first != None:\n length += 1\n first = first.next\nlength -= n\nfirst = dummy\nwhile length > 0:\n length -= 1\n first = first.next\nfirst.next = first.next.next\nreturn dummy.next",
"dummy: ListNode = Li... | <|body_start_0|>
dummy: ListNode = ListNode(0)
length: int = 0
dummy.next = head
first: ListNode = head
while first != None:
length += 1
first = first.next
length -= n
first = dummy
while length > 0:
length -= 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""2 pass solution :param head: :param n: :return:"""
<|body_0|>
def removeNthFromEndOnePass(self, head: ListNode, n: int) -> ListNode:
"""1 pass solution :param head: :param n: :return:"""
... | stack_v2_sparse_classes_10k_train_007334 | 1,462 | no_license | [
{
"docstring": "2 pass solution :param head: :param n: :return:",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode"
},
{
"docstring": "1 pass solution :param head: :param n: :return:",
"name": "removeNthFromEndOnePass",
"signature":... | 2 | stack_v2_sparse_classes_30k_val_000180 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 2 pass solution :param head: :param n: :return:
- def removeNthFromEndOnePass(self, head: ListNode, n: int) -> Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 2 pass solution :param head: :param n: :return:
- def removeNthFromEndOnePass(self, head: ListNode, n: int) -> Lis... | 7138db92a5fabf2347ff669a77268083dfced8da | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""2 pass solution :param head: :param n: :return:"""
<|body_0|>
def removeNthFromEndOnePass(self, head: ListNode, n: int) -> ListNode:
"""1 pass solution :param head: :param n: :return:"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""2 pass solution :param head: :param n: :return:"""
dummy: ListNode = ListNode(0)
length: int = 0
dummy.next = head
first: ListNode = head
while first != None:
length += 1
... | the_stack_v2_python_sparse | leetcode/19_remove_Nth_node_from_end_of_list.py | Merical/education_ai | train | 0 | |
038a932f3f7c9c167dba128def9a9a1f7f291cfe | [
"EasyFrame.__init__(self, title='Color Meter')\nself.rgbLabel = self.addLabel(text='RGB : x000000', row=0, column=0)\nself.canvas = self.addCanvas(row=1, column=0)\nself.canvas['bg'] = 'black'\nself.redScale = self.addScale(label='Red', row=0, column=1, orient=VERTICAL, from_=0, to=255, length=300, tickinterval=15,... | <|body_start_0|>
EasyFrame.__init__(self, title='Color Meter')
self.rgbLabel = self.addLabel(text='RGB : x000000', row=0, column=0)
self.canvas = self.addCanvas(row=1, column=0)
self.canvas['bg'] = 'black'
self.redScale = self.addScale(label='Red', row=0, column=1, orient=VERTICA... | ColorMeter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorMeter:
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def setColor(self, value):
"""Gets the RGB values from the scales, converts them to hex, and builds a six-digit hex string to update the view."""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_10k_train_007335 | 2,667 | no_license | [
{
"docstring": "Sets up the window and widgets.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Gets the RGB values from the scales, converts them to hex, and builds a six-digit hex string to update the view.",
"name": "setColor",
"signature": "def setColor(sel... | 2 | stack_v2_sparse_classes_30k_train_003799 | Implement the Python class `ColorMeter` described below.
Class description:
Implement the ColorMeter class.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def setColor(self, value): Gets the RGB values from the scales, converts them to hex, and builds a six-digit hex string ... | Implement the Python class `ColorMeter` described below.
Class description:
Implement the ColorMeter class.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def setColor(self, value): Gets the RGB values from the scales, converts them to hex, and builds a six-digit hex string ... | eca69d000dc77681a30734b073b2383c97ccc02e | <|skeleton|>
class ColorMeter:
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def setColor(self, value):
"""Gets the RGB values from the scales, converts them to hex, and builds a six-digit hex string to update the view."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ColorMeter:
def __init__(self):
"""Sets up the window and widgets."""
EasyFrame.__init__(self, title='Color Meter')
self.rgbLabel = self.addLabel(text='RGB : x000000', row=0, column=0)
self.canvas = self.addCanvas(row=1, column=0)
self.canvas['bg'] = 'black'
sel... | the_stack_v2_python_sparse | gui/breezy/scaledemo2.py | lforet/robomow | train | 11 | |
baf805206c9f377705c1288d0e95895b89490361 | [
"left = 0\nwhile left <= right:\n mid = left + (right - left >> 1)\n if nums[mid] == target:\n return mid\n if nums[mid] > target:\n right = mid - 1\n else:\n left = mid + 1\nreturn -1",
"n = len(arr)\nret = 0\ndp = [[0 for i in range(n)] for j in range(n)]\nfor i in range(1, n):\... | <|body_start_0|>
left = 0
while left <= right:
mid = left + (right - left >> 1)
if nums[mid] == target:
return mid
if nums[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def binary_search(self, nums, right, target):
"""二分查找"""
<|body_0|>
def lenLongestFibSubseq(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left = 0
while left <= right:
m... | stack_v2_sparse_classes_10k_train_007336 | 860 | no_license | [
{
"docstring": "二分查找",
"name": "binary_search",
"signature": "def binary_search(self, nums, right, target)"
},
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "lenLongestFibSubseq",
"signature": "def lenLongestFibSubseq(self, arr)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002408 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binary_search(self, nums, right, target): 二分查找
- def lenLongestFibSubseq(self, arr): :type arr: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binary_search(self, nums, right, target): 二分查找
- def lenLongestFibSubseq(self, arr): :type arr: List[int] :rtype: int
<|skeleton|>
class Solution:
def binary_search(sel... | 4b30dd6a3f683c8dc71a85f7b947232613a28dc1 | <|skeleton|>
class Solution:
def binary_search(self, nums, right, target):
"""二分查找"""
<|body_0|>
def lenLongestFibSubseq(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def binary_search(self, nums, right, target):
"""二分查找"""
left = 0
while left <= right:
mid = left + (right - left >> 1)
if nums[mid] == target:
return mid
if nums[mid] > target:
right = mid - 1
el... | the_stack_v2_python_sparse | 最长斐波那契数列__时间超时.py | saintifly/leetcode | train | 0 | |
81999fc2bd998aa8c191e3856d329f6d45631c35 | [
"super().__init__(self.PROBLEM_NAME)\nself.input_linked_list1 = input_linked_list1\nself.input_linked_list2 = input_linked_list2",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nnode1 = self.input_linked_list1.head\nnode2 = self.input_linked_list2.head\ncarry = 0\nsum_list = LinkedList()\nwhile node1... | <|body_start_0|>
super().__init__(self.PROBLEM_NAME)
self.input_linked_list1 = input_linked_list1
self.input_linked_list2 = input_linked_list2
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
node1 = self.input_linked_list1.head
n... | Add Two Numbers | AddTwoNumbers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddTwoNumbers:
"""Add Two Numbers"""
def __init__(self, input_linked_list1, input_linked_list2):
"""Add Two Numbers Args: input_linked_list1: First linked list input_linked_list2: Second linked list Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Sol... | stack_v2_sparse_classes_10k_train_007337 | 2,269 | no_license | [
{
"docstring": "Add Two Numbers Args: input_linked_list1: First linked list input_linked_list2: Second linked list Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, input_linked_list1, input_linked_list2)"
},
{
"docstring": "Solve the problem Note: O(n) (runtime) ... | 2 | stack_v2_sparse_classes_30k_train_004796 | Implement the Python class `AddTwoNumbers` described below.
Class description:
Add Two Numbers
Method signatures and docstrings:
- def __init__(self, input_linked_list1, input_linked_list2): Add Two Numbers Args: input_linked_list1: First linked list input_linked_list2: Second linked list Returns: None Raises: None
-... | Implement the Python class `AddTwoNumbers` described below.
Class description:
Add Two Numbers
Method signatures and docstrings:
- def __init__(self, input_linked_list1, input_linked_list2): Add Two Numbers Args: input_linked_list1: First linked list input_linked_list2: Second linked list Returns: None Raises: None
-... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class AddTwoNumbers:
"""Add Two Numbers"""
def __init__(self, input_linked_list1, input_linked_list2):
"""Add Two Numbers Args: input_linked_list1: First linked list input_linked_list2: Second linked list Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Sol... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AddTwoNumbers:
"""Add Two Numbers"""
def __init__(self, input_linked_list1, input_linked_list2):
"""Add Two Numbers Args: input_linked_list1: First linked list input_linked_list2: Second linked list Returns: None Raises: None"""
super().__init__(self.PROBLEM_NAME)
self.input_linke... | the_stack_v2_python_sparse | python/problems/linked_list/add_two_numbers.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
cb650fce896ea601a9bfbd655be976a3ebce29be | [
"y_real = Variable(input_shape=y_true_shape if y_true_shape else y_pred_shape)\ny_pred = Variable(input_shape=y_pred_shape)\nloss_var = loss_func(y_real, y_pred)\nsuper(CustomLoss, self).__init__(None, 'float', [y_real, y_pred], loss_var)",
"input = y_pred\ntarget = y_true\njinput, input_is_table = Layer.check_in... | <|body_start_0|>
y_real = Variable(input_shape=y_true_shape if y_true_shape else y_pred_shape)
y_pred = Variable(input_shape=y_pred_shape)
loss_var = loss_func(y_real, y_pred)
super(CustomLoss, self).__init__(None, 'float', [y_real, y_pred], loss_var)
<|end_body_0|>
<|body_start_1|>
... | CustomLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomLoss:
def __init__(self, loss_func, y_pred_shape, y_true_shape=None):
""":param loss_func: a function which accept y_true and y_pred :param y_pred_shape: The pred shape without batch dim. :param y_true_shape: The target shape without batch dim. It should be the same as y_pred_shape... | stack_v2_sparse_classes_10k_train_007338 | 18,832 | permissive | [
{
"docstring": ":param loss_func: a function which accept y_true and y_pred :param y_pred_shape: The pred shape without batch dim. :param y_true_shape: The target shape without batch dim. It should be the same as y_pred_shape by default. i.e input_shape=[3], then the feeding data would be [None, 3]",
"name"... | 3 | stack_v2_sparse_classes_30k_train_002134 | Implement the Python class `CustomLoss` described below.
Class description:
Implement the CustomLoss class.
Method signatures and docstrings:
- def __init__(self, loss_func, y_pred_shape, y_true_shape=None): :param loss_func: a function which accept y_true and y_pred :param y_pred_shape: The pred shape without batch ... | Implement the Python class `CustomLoss` described below.
Class description:
Implement the CustomLoss class.
Method signatures and docstrings:
- def __init__(self, loss_func, y_pred_shape, y_true_shape=None): :param loss_func: a function which accept y_true and y_pred :param y_pred_shape: The pred shape without batch ... | 4ffa012a426e0d16ed13b707b03d8787ddca6aa4 | <|skeleton|>
class CustomLoss:
def __init__(self, loss_func, y_pred_shape, y_true_shape=None):
""":param loss_func: a function which accept y_true and y_pred :param y_pred_shape: The pred shape without batch dim. :param y_true_shape: The target shape without batch dim. It should be the same as y_pred_shape... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomLoss:
def __init__(self, loss_func, y_pred_shape, y_true_shape=None):
""":param loss_func: a function which accept y_true and y_pred :param y_pred_shape: The pred shape without batch dim. :param y_true_shape: The target shape without batch dim. It should be the same as y_pred_shape by default. i... | the_stack_v2_python_sparse | python/dllib/src/bigdl/dllib/keras/autograd.py | intel-analytics/BigDL | train | 4,913 | |
7d7f05f3d91e0e686f6b21602d64b6f280f8b29d | [
"forward = {i: set() for i in range(numCourses)}\nbackward = collections.defaultdict(set)\nfor i, j in prerequisites:\n forward[i].add(j)\n backward[j].add(i)\nqueue = collections.deque([node for node in forward if len(forward[node]) == 0])\ncount, res = (0, [])\nwhile queue:\n node = queue.popleft()\n ... | <|body_start_0|>
forward = {i: set() for i in range(numCourses)}
backward = collections.defaultdict(set)
for i, j in prerequisites:
forward[i].add(j)
backward[j].add(i)
queue = collections.deque([node for node in forward if len(forward[node]) == 0])
count,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findOrder(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findOrder_1(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rt... | stack_v2_sparse_classes_10k_train_007339 | 3,709 | no_license | [
{
"docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]",
"name": "findOrder",
"signature": "def findOrder(self, numCourses, prerequisites)"
},
{
"docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool",
"name": "findOrder_1"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findOrder(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]
- def findOrder_1(self, numCourses, prerequisites): :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findOrder(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]
- def findOrder_1(self, numCourses, prerequisites): :... | 3d9e0ad2f6ed92ec969556f75d97c51ea4854719 | <|skeleton|>
class Solution:
def findOrder(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findOrder_1(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rt... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findOrder(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]"""
forward = {i: set() for i in range(numCourses)}
backward = collections.defaultdict(set)
for i, j in prerequisites:
forward[i]... | the_stack_v2_python_sparse | Solutions/0210_findOrder.py | YoupengLi/leetcode-sorting | train | 3 | |
e5052b3e8de9ce4477920d5e426c0fa347c0468f | [
"self.config = config\nself.model = VBCAR(config['model'])\nuser_fea = torch.tensor(config['user_fea'], requires_grad=False, device=config['model']['device_str'], dtype=torch.float32)\nitem_fea = torch.tensor(config['item_fea'], requires_grad=False, device=config['model']['device_str'], dtype=torch.float32)\nself.m... | <|body_start_0|>
self.config = config
self.model = VBCAR(config['model'])
user_fea = torch.tensor(config['user_fea'], requires_grad=False, device=config['model']['device_str'], dtype=torch.float32)
item_fea = torch.tensor(config['item_fea'], requires_grad=False, device=config['model']['d... | Engine for training & evaluating GMF model. | VBCAREngine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VBCAREngine:
"""Engine for training & evaluating GMF model."""
def __init__(self, config):
"""Initialize VBCAREngine Class."""
<|body_0|>
def train_single_batch(self, batch_data, ratings=None):
"""Train the model in a single batch."""
<|body_1|>
def ... | stack_v2_sparse_classes_10k_train_007340 | 11,137 | permissive | [
{
"docstring": "Initialize VBCAREngine Class.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Train the model in a single batch.",
"name": "train_single_batch",
"signature": "def train_single_batch(self, batch_data, ratings=None)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_002714 | Implement the Python class `VBCAREngine` described below.
Class description:
Engine for training & evaluating GMF model.
Method signatures and docstrings:
- def __init__(self, config): Initialize VBCAREngine Class.
- def train_single_batch(self, batch_data, ratings=None): Train the model in a single batch.
- def trai... | Implement the Python class `VBCAREngine` described below.
Class description:
Engine for training & evaluating GMF model.
Method signatures and docstrings:
- def __init__(self, config): Initialize VBCAREngine Class.
- def train_single_batch(self, batch_data, ratings=None): Train the model in a single batch.
- def trai... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class VBCAREngine:
"""Engine for training & evaluating GMF model."""
def __init__(self, config):
"""Initialize VBCAREngine Class."""
<|body_0|>
def train_single_batch(self, batch_data, ratings=None):
"""Train the model in a single batch."""
<|body_1|>
def ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VBCAREngine:
"""Engine for training & evaluating GMF model."""
def __init__(self, config):
"""Initialize VBCAREngine Class."""
self.config = config
self.model = VBCAR(config['model'])
user_fea = torch.tensor(config['user_fea'], requires_grad=False, device=config['model']['... | the_stack_v2_python_sparse | beta_rec/models/vbcar.py | beta-team/beta-recsys | train | 156 |
a6fe4fceaeacd915c9e40ab1af13fc6f0518e332 | [
"wx.PopupWindow.__init__(self, parent)\nPopupListBase.__init__(self)\nself._list = wx.ListBox(self, choices=choices, pos=(0, 0), style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_NO_HEADER)\nsizer = wx.BoxSizer(wx.HORIZONTAL)\nsizer.Add(self._list, 0, wx.EXPAND)\nself.SetSizer(sizer)\ntxt_h = self.GetTextExtent('/')[1]... | <|body_start_0|>
wx.PopupWindow.__init__(self, parent)
PopupListBase.__init__(self)
self._list = wx.ListBox(self, choices=choices, pos=(0, 0), style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_NO_HEADER)
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self._list, 0, wx.EXPAND)
s... | Popuplist for Windows/GTK | PopupWinList | [
"BSD-3-Clause",
"LicenseRef-scancode-python-cwi",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-free-unknown",
"Python-2.0",
"LGPL-2.0-or-later",
"WxWindows-exception-3.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PopupWinList:
"""Popuplist for Windows/GTK"""
def __init__(self, parent, choices=list(), pos=wx.DefaultPosition):
"""Create the popup window and its list control"""
<|body_0|>
def OnSize(self, evt):
"""Resize the list box to the correct size to fit."""
<|... | stack_v2_sparse_classes_10k_train_007341 | 44,291 | permissive | [
{
"docstring": "Create the popup window and its list control",
"name": "__init__",
"signature": "def __init__(self, parent, choices=list(), pos=wx.DefaultPosition)"
},
{
"docstring": "Resize the list box to the correct size to fit.",
"name": "OnSize",
"signature": "def OnSize(self, evt)"... | 5 | stack_v2_sparse_classes_30k_train_007265 | Implement the Python class `PopupWinList` described below.
Class description:
Popuplist for Windows/GTK
Method signatures and docstrings:
- def __init__(self, parent, choices=list(), pos=wx.DefaultPosition): Create the popup window and its list control
- def OnSize(self, evt): Resize the list box to the correct size ... | Implement the Python class `PopupWinList` described below.
Class description:
Popuplist for Windows/GTK
Method signatures and docstrings:
- def __init__(self, parent, choices=list(), pos=wx.DefaultPosition): Create the popup window and its list control
- def OnSize(self, evt): Resize the list box to the correct size ... | 77d66c719b5746f37af51ad593e2941ed6fbba17 | <|skeleton|>
class PopupWinList:
"""Popuplist for Windows/GTK"""
def __init__(self, parent, choices=list(), pos=wx.DefaultPosition):
"""Create the popup window and its list control"""
<|body_0|>
def OnSize(self, evt):
"""Resize the list box to the correct size to fit."""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PopupWinList:
"""Popuplist for Windows/GTK"""
def __init__(self, parent, choices=list(), pos=wx.DefaultPosition):
"""Create the popup window and its list control"""
wx.PopupWindow.__init__(self, parent)
PopupListBase.__init__(self)
self._list = wx.ListBox(self, choices=cho... | the_stack_v2_python_sparse | base/lib/python2.7/site-packages/wx-3.0-gtk2/wx/tools/Editra/src/ed_cmdbar.py | jorgediazjr/dials-dev20191018 | train | 0 |
9b90606d3456f8603f6db3ae0aea5585b0173077 | [
"picking_obj = self.pool.get('stock.picking')\nseq_obj_name = self._name\nvals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)\nnew_id = picking_obj.create(cr, user, vals, context)\nreturn new_id",
"picking_obj = self.pool.get('stock.picking')\nwrite_boolean = picking_obj.write(cr, uid, ids, va... | <|body_start_0|>
picking_obj = self.pool.get('stock.picking')
seq_obj_name = self._name
vals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)
new_id = picking_obj.create(cr, user, vals, context)
return new_id
<|end_body_0|>
<|body_start_1|>
picking_obj ... | stock_picking_in | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_picking_in:
def create(self, cr, user, vals, context=None):
"""Override create to call create of stock.picking"""
<|body_0|>
def write(self, cr, uid, ids, vals, context=None):
"""Override write to call write of stock.picking"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_10k_train_007342 | 17,898 | no_license | [
{
"docstring": "Override create to call create of stock.picking",
"name": "create",
"signature": "def create(self, cr, user, vals, context=None)"
},
{
"docstring": "Override write to call write of stock.picking",
"name": "write",
"signature": "def write(self, cr, uid, ids, vals, context=... | 2 | stack_v2_sparse_classes_30k_train_006456 | Implement the Python class `stock_picking_in` described below.
Class description:
Implement the stock_picking_in class.
Method signatures and docstrings:
- def create(self, cr, user, vals, context=None): Override create to call create of stock.picking
- def write(self, cr, uid, ids, vals, context=None): Override writ... | Implement the Python class `stock_picking_in` described below.
Class description:
Implement the stock_picking_in class.
Method signatures and docstrings:
- def create(self, cr, user, vals, context=None): Override create to call create of stock.picking
- def write(self, cr, uid, ids, vals, context=None): Override writ... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class stock_picking_in:
def create(self, cr, user, vals, context=None):
"""Override create to call create of stock.picking"""
<|body_0|>
def write(self, cr, uid, ids, vals, context=None):
"""Override write to call write of stock.picking"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class stock_picking_in:
def create(self, cr, user, vals, context=None):
"""Override create to call create of stock.picking"""
picking_obj = self.pool.get('stock.picking')
seq_obj_name = self._name
vals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)
new_id ... | the_stack_v2_python_sparse | v_7/NISS/shamil_v3/stock_oc/model/stock.py | musabahmed/baba | train | 0 | |
8d6d0e55c271ac7df25c5791d771120863bccd2d | [
"super().__init__()\nself._config_entry = config_entry\nself._entry_id = config_entry.entry_id",
"errors = {}\nif user_input is not None:\n return self.async_create_entry(title='', data=user_input)\nreturn self.async_show_form(step_id='init', data_schema=create_schema(self._config_entry, step='init'), errors=e... | <|body_start_0|>
super().__init__()
self._config_entry = config_entry
self._entry_id = config_entry.entry_id
<|end_body_0|>
<|body_start_1|>
errors = {}
if user_input is not None:
return self.async_create_entry(title='', data=user_input)
return self.async_sho... | Changing options flow. | SleepAsAndroidOptionsFlow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SleepAsAndroidOptionsFlow:
"""Changing options flow."""
def __init__(self, config_entry):
"""Initialize options flow."""
<|body_0|>
async def async_step_init(self, user_input=None):
"""Manage the options."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_007343 | 3,504 | no_license | [
{
"docstring": "Initialize options flow.",
"name": "__init__",
"signature": "def __init__(self, config_entry)"
},
{
"docstring": "Manage the options.",
"name": "async_step_init",
"signature": "async def async_step_init(self, user_input=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003444 | Implement the Python class `SleepAsAndroidOptionsFlow` described below.
Class description:
Changing options flow.
Method signatures and docstrings:
- def __init__(self, config_entry): Initialize options flow.
- async def async_step_init(self, user_input=None): Manage the options. | Implement the Python class `SleepAsAndroidOptionsFlow` described below.
Class description:
Changing options flow.
Method signatures and docstrings:
- def __init__(self, config_entry): Initialize options flow.
- async def async_step_init(self, user_input=None): Manage the options.
<|skeleton|>
class SleepAsAndroidOpt... | 3c985391265c94c733cf333201c72010c6296900 | <|skeleton|>
class SleepAsAndroidOptionsFlow:
"""Changing options flow."""
def __init__(self, config_entry):
"""Initialize options flow."""
<|body_0|>
async def async_step_init(self, user_input=None):
"""Manage the options."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SleepAsAndroidOptionsFlow:
"""Changing options flow."""
def __init__(self, config_entry):
"""Initialize options flow."""
super().__init__()
self._config_entry = config_entry
self._entry_id = config_entry.entry_id
async def async_step_init(self, user_input=None):
... | the_stack_v2_python_sparse | custom_components/sleep_as_android/config_flow.py | SeLLeRoNe/HA-Config | train | 80 |
c5b8604ae9055f603494c1f984ff3a943eae1c98 | [
"self._header = ProgressiveHeader(request_event.request.request_id)\nself._api_endpoint = request_event.context.system.api_endpoint + '/v1/directives'\nself._api_access_token = request_event.context.system.api_access_token",
"directive = ProgressiveDirective(speech)\nresponse = ProgressiveResponse(self._header, d... | <|body_start_0|>
self._header = ProgressiveHeader(request_event.request.request_id)
self._api_endpoint = request_event.context.system.api_endpoint + '/v1/directives'
self._api_access_token = request_event.context.system.api_access_token
<|end_body_0|>
<|body_start_1|>
directive = Progre... | This class provides a simple way to create and send a progressive response to Alexa while your skill processes the complete response. | ProgressiveResponseBuilder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgressiveResponseBuilder:
"""This class provides a simple way to create and send a progressive response to Alexa while your skill processes the complete response."""
def __init__(self, request_event):
"""Create a progressive response builder. You only need to create one of these pe... | stack_v2_sparse_classes_10k_train_007344 | 3,057 | permissive | [
{
"docstring": "Create a progressive response builder. You only need to create one of these per each request and simply call the send speech each time you need to send a response. Initialize with the request event object.",
"name": "__init__",
"signature": "def __init__(self, request_event)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_002515 | Implement the Python class `ProgressiveResponseBuilder` described below.
Class description:
This class provides a simple way to create and send a progressive response to Alexa while your skill processes the complete response.
Method signatures and docstrings:
- def __init__(self, request_event): Create a progressive ... | Implement the Python class `ProgressiveResponseBuilder` described below.
Class description:
This class provides a simple way to create and send a progressive response to Alexa while your skill processes the complete response.
Method signatures and docstrings:
- def __init__(self, request_event): Create a progressive ... | aac9d8aa4d6d5d2e9dcd079e0ac516b06c8a94ba | <|skeleton|>
class ProgressiveResponseBuilder:
"""This class provides a simple way to create and send a progressive response to Alexa while your skill processes the complete response."""
def __init__(self, request_event):
"""Create a progressive response builder. You only need to create one of these pe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProgressiveResponseBuilder:
"""This class provides a simple way to create and send a progressive response to Alexa while your skill processes the complete response."""
def __init__(self, request_event):
"""Create a progressive response builder. You only need to create one of these per each reques... | the_stack_v2_python_sparse | askalexa/response/progressive.py | scottenglert/AskAlexa | train | 2 |
82474b732e0974212195a08ff9f7f3b76a871d1c | [
"analysis = Analysis.objects.get(id=self._analysis_id)\norganization = analysis.organization\nif not organization.better_analysis_api_key:\n message = f'''Organization \"{organization.name}\" is missing the required BETTER Analysis API Key. Please update your organization's settings or contact your organization ... | <|body_start_0|>
analysis = Analysis.objects.get(id=self._analysis_id)
organization = analysis.organization
if not organization.better_analysis_api_key:
message = f'''Organization "{organization.name}" is missing the required BETTER Analysis API Key. Please update your organization's... | BETTERPipeline is a class for preparing, running, and post processing BETTER analysis by implementing the AnalysisPipeline's abstract methods. | BETTERPipeline | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BETTERPipeline:
"""BETTERPipeline is a class for preparing, running, and post processing BETTER analysis by implementing the AnalysisPipeline's abstract methods."""
def _prepare_analysis(self, property_view_ids, start_analysis=False):
"""Internal implementation for preparing better a... | stack_v2_sparse_classes_10k_train_007345 | 23,144 | permissive | [
{
"docstring": "Internal implementation for preparing better analysis",
"name": "_prepare_analysis",
"signature": "def _prepare_analysis(self, property_view_ids, start_analysis=False)"
},
{
"docstring": "Internal implementation for starting the BETTER analysis",
"name": "_start_analysis",
... | 2 | null | Implement the Python class `BETTERPipeline` described below.
Class description:
BETTERPipeline is a class for preparing, running, and post processing BETTER analysis by implementing the AnalysisPipeline's abstract methods.
Method signatures and docstrings:
- def _prepare_analysis(self, property_view_ids, start_analys... | Implement the Python class `BETTERPipeline` described below.
Class description:
BETTERPipeline is a class for preparing, running, and post processing BETTER analysis by implementing the AnalysisPipeline's abstract methods.
Method signatures and docstrings:
- def _prepare_analysis(self, property_view_ids, start_analys... | 680b6a2b45f3c568d779d8ac86553a0b08c384c8 | <|skeleton|>
class BETTERPipeline:
"""BETTERPipeline is a class for preparing, running, and post processing BETTER analysis by implementing the AnalysisPipeline's abstract methods."""
def _prepare_analysis(self, property_view_ids, start_analysis=False):
"""Internal implementation for preparing better a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BETTERPipeline:
"""BETTERPipeline is a class for preparing, running, and post processing BETTER analysis by implementing the AnalysisPipeline's abstract methods."""
def _prepare_analysis(self, property_view_ids, start_analysis=False):
"""Internal implementation for preparing better analysis"""
... | the_stack_v2_python_sparse | seed/analysis_pipelines/better/pipeline.py | SEED-platform/seed | train | 108 |
f042cc6a52f31a5fdd1850f3000a4d90bf0265df | [
"def serialize_completed_analysis() -> bytes:\n return legacy_pickle.dumps(self.completed_analysis.dict())\nserialized_completed_analysis = await anyio.to_thread.run_sync(serialize_completed_analysis, cancellable=True)\nreturn {'id': self.id, 'protocol_id': self.protocol_id, 'analyzer_version': self.analyzer_ver... | <|body_start_0|>
def serialize_completed_analysis() -> bytes:
return legacy_pickle.dumps(self.completed_analysis.dict())
serialized_completed_analysis = await anyio.to_thread.run_sync(serialize_completed_analysis, cancellable=True)
return {'id': self.id, 'protocol_id': self.protocol_... | A protocol analysis that's been completed, storable in a SQL database. See `CompletedAnalysisStore`. | CompletedAnalysisResource | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompletedAnalysisResource:
"""A protocol analysis that's been completed, storable in a SQL database. See `CompletedAnalysisStore`."""
async def to_sql_values(self) -> Dict[str, object]:
"""Return this data as a dict that can be passed to a SQLALchemy insert. This potentially involves... | stack_v2_sparse_classes_10k_train_007346 | 8,687 | permissive | [
{
"docstring": "Return this data as a dict that can be passed to a SQLALchemy insert. This potentially involves heavy serialization, so it's offloaded to a worker thread. Do not modify anything while serialization is ongoing in its worker thread. Avoid calling this from inside a SQL transaction, since it might ... | 2 | stack_v2_sparse_classes_30k_train_006096 | Implement the Python class `CompletedAnalysisResource` described below.
Class description:
A protocol analysis that's been completed, storable in a SQL database. See `CompletedAnalysisStore`.
Method signatures and docstrings:
- async def to_sql_values(self) -> Dict[str, object]: Return this data as a dict that can be... | Implement the Python class `CompletedAnalysisResource` described below.
Class description:
A protocol analysis that's been completed, storable in a SQL database. See `CompletedAnalysisStore`.
Method signatures and docstrings:
- async def to_sql_values(self) -> Dict[str, object]: Return this data as a dict that can be... | 026b523c8c9e5d45910c490efb89194d72595be9 | <|skeleton|>
class CompletedAnalysisResource:
"""A protocol analysis that's been completed, storable in a SQL database. See `CompletedAnalysisStore`."""
async def to_sql_values(self) -> Dict[str, object]:
"""Return this data as a dict that can be passed to a SQLALchemy insert. This potentially involves... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CompletedAnalysisResource:
"""A protocol analysis that's been completed, storable in a SQL database. See `CompletedAnalysisStore`."""
async def to_sql_values(self) -> Dict[str, object]:
"""Return this data as a dict that can be passed to a SQLALchemy insert. This potentially involves heavy serial... | the_stack_v2_python_sparse | robot-server/robot_server/protocols/completed_analysis_store.py | Opentrons/opentrons | train | 326 |
e184dc5a56df5f6ee2125c1d378ea6fd362a1f6a | [
"a = 'sql_error.ini'\nsql_error = open(a, 'r')\nerrors = sql_error.readlines()\nsql_error.close()\nself.errors = errors\nself.link = link",
"domain = url.split('?')[0]\nparams = {}\nparam = url.split('?')[1]\nfor pm in param.split('&'):\n key, value = pm.split('=')\n try:\n int(value)\n value ... | <|body_start_0|>
a = 'sql_error.ini'
sql_error = open(a, 'r')
errors = sql_error.readlines()
sql_error.close()
self.errors = errors
self.link = link
<|end_body_0|>
<|body_start_1|>
domain = url.split('?')[0]
params = {}
param = url.split('?')[1]
... | Scan | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scan:
def __init__(self, link):
"""type errors : list param errors : sqli error that may exist type links : generate param links : all links want wo test"""
<|body_0|>
def create_link(self, url):
"""Create a link with symbol ' type url : str param url : which url to ... | stack_v2_sparse_classes_10k_train_007347 | 2,642 | no_license | [
{
"docstring": "type errors : list param errors : sqli error that may exist type links : generate param links : all links want wo test",
"name": "__init__",
"signature": "def __init__(self, link)"
},
{
"docstring": "Create a link with symbol ' type url : str param url : which url to add ' return... | 4 | stack_v2_sparse_classes_30k_train_001829 | Implement the Python class `Scan` described below.
Class description:
Implement the Scan class.
Method signatures and docstrings:
- def __init__(self, link): type errors : list param errors : sqli error that may exist type links : generate param links : all links want wo test
- def create_link(self, url): Create a li... | Implement the Python class `Scan` described below.
Class description:
Implement the Scan class.
Method signatures and docstrings:
- def __init__(self, link): type errors : list param errors : sqli error that may exist type links : generate param links : all links want wo test
- def create_link(self, url): Create a li... | 111e4fcb2e3fb8e632ffed85b7c9e53ba2ed1c14 | <|skeleton|>
class Scan:
def __init__(self, link):
"""type errors : list param errors : sqli error that may exist type links : generate param links : all links want wo test"""
<|body_0|>
def create_link(self, url):
"""Create a link with symbol ' type url : str param url : which url to ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Scan:
def __init__(self, link):
"""type errors : list param errors : sqli error that may exist type links : generate param links : all links want wo test"""
a = 'sql_error.ini'
sql_error = open(a, 'r')
errors = sql_error.readlines()
sql_error.close()
self.errors... | the_stack_v2_python_sparse | sqli/src/scan.py | ZUI520/Python | train | 2 | |
38b50ea62decdfa3a14bf6f0358ae08def1f5740 | [
"super(InceptionV3, self).__init__()\nself.resize_input = resize_input\nself.normalize_input = normalize_input\nself.output_blocks = sorted(output_blocks)\nself.last_needed_block = max(output_blocks)\nassert self.last_needed_block <= 3, 'Last possible output block index is 3'\nself.blocks = nn.ModuleList()\nincepti... | <|body_start_0|>
super(InceptionV3, self).__init__()
self.resize_input = resize_input
self.normalize_input = normalize_input
self.output_blocks = sorted(output_blocks)
self.last_needed_block = max(output_blocks)
assert self.last_needed_block <= 3, 'Last possible output bl... | Pretrained InceptionV3 network returning feature maps | InceptionV3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InceptionV3:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=False, normalize_input=True, requires_grad=False):
"""Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices o... | stack_v2_sparse_classes_10k_train_007348 | 8,851 | no_license | [
{
"docstring": "Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of blocks to return features of. Possible values are: - 0: corresponds to output of first max pooling - 1: corresponds to output of second max pooling - 2: corresponds to output which is fed to aux classifier ... | 2 | null | Implement the Python class `InceptionV3` described below.
Class description:
Pretrained InceptionV3 network returning feature maps
Method signatures and docstrings:
- def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=False, normalize_input=True, requires_grad=False): Build pretrained InceptionV3 Pa... | Implement the Python class `InceptionV3` described below.
Class description:
Pretrained InceptionV3 network returning feature maps
Method signatures and docstrings:
- def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=False, normalize_input=True, requires_grad=False): Build pretrained InceptionV3 Pa... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class InceptionV3:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=False, normalize_input=True, requires_grad=False):
"""Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InceptionV3:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=False, normalize_input=True, requires_grad=False):
"""Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of blocks to r... | the_stack_v2_python_sparse | generated/test_tamarott_SinGAN.py | jansel/pytorch-jit-paritybench | train | 35 |
9ea1c2746cd676d8a16df87e9b920ae9f6c52dd6 | [
"seq_length = 4\nnum_predictions = 2\nxlnet_base = _get_xlnet_base()\nxlnet_trainer_model = xlnet.XLNetPretrainer(network=xlnet_base)\ninputs = dict(input_word_ids=tf.keras.layers.Input(shape=(seq_length,), dtype=tf.int32, name='input_word_ids'), input_type_ids=tf.keras.layers.Input(shape=(seq_length,), dtype=tf.in... | <|body_start_0|>
seq_length = 4
num_predictions = 2
xlnet_base = _get_xlnet_base()
xlnet_trainer_model = xlnet.XLNetPretrainer(network=xlnet_base)
inputs = dict(input_word_ids=tf.keras.layers.Input(shape=(seq_length,), dtype=tf.int32, name='input_word_ids'), input_type_ids=tf.ker... | XLNetPretrainerTest | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XLNetPretrainerTest:
def test_xlnet_trainer(self):
"""Validates that the Keras object can be created."""
<|body_0|>
def test_xlnet_tensor_call(self):
"""Validates that the Keras object can be invoked."""
<|body_1|>
def test_serialize_deserialize(self):
... | stack_v2_sparse_classes_10k_train_007349 | 13,124 | permissive | [
{
"docstring": "Validates that the Keras object can be created.",
"name": "test_xlnet_trainer",
"signature": "def test_xlnet_trainer(self)"
},
{
"docstring": "Validates that the Keras object can be invoked.",
"name": "test_xlnet_tensor_call",
"signature": "def test_xlnet_tensor_call(self... | 3 | stack_v2_sparse_classes_30k_train_001820 | Implement the Python class `XLNetPretrainerTest` described below.
Class description:
Implement the XLNetPretrainerTest class.
Method signatures and docstrings:
- def test_xlnet_trainer(self): Validates that the Keras object can be created.
- def test_xlnet_tensor_call(self): Validates that the Keras object can be inv... | Implement the Python class `XLNetPretrainerTest` described below.
Class description:
Implement the XLNetPretrainerTest class.
Method signatures and docstrings:
- def test_xlnet_trainer(self): Validates that the Keras object can be created.
- def test_xlnet_tensor_call(self): Validates that the Keras object can be inv... | 6fc53292b1d3ce3c0340ce724c2c11c77e663d27 | <|skeleton|>
class XLNetPretrainerTest:
def test_xlnet_trainer(self):
"""Validates that the Keras object can be created."""
<|body_0|>
def test_xlnet_tensor_call(self):
"""Validates that the Keras object can be invoked."""
<|body_1|>
def test_serialize_deserialize(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class XLNetPretrainerTest:
def test_xlnet_trainer(self):
"""Validates that the Keras object can be created."""
seq_length = 4
num_predictions = 2
xlnet_base = _get_xlnet_base()
xlnet_trainer_model = xlnet.XLNetPretrainer(network=xlnet_base)
inputs = dict(input_word_id... | the_stack_v2_python_sparse | models/official/nlp/modeling/models/xlnet_test.py | aboerzel/German_License_Plate_Recognition | train | 34 | |
c5aa9c70754851c5259b7b9aeb8d1a06c538fa17 | [
"self._dataset = dataset\nself._split_name = split_name\nself._is_training = is_training\nself._model_variant = model_variant\nself._num_readers = 8\nself._num_threads = 64",
"data_provider = dataset_data_provider.DatasetDataProvider(self._dataset, num_readers=self._num_readers, shuffle=self._is_training, num_epo... | <|body_start_0|>
self._dataset = dataset
self._split_name = split_name
self._is_training = is_training
self._model_variant = model_variant
self._num_readers = 8
self._num_threads = 64
<|end_body_0|>
<|body_start_1|>
data_provider = dataset_data_provider.DatasetDa... | Prepares data for TPUEstimator. | InputReader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputReader:
"""Prepares data for TPUEstimator."""
def __init__(self, dataset, split_name, is_training, model_variant):
"""Initializes slim Dataset etc. Args: dataset: slim Dataset. split_name: String, the name of train/eval/test split. is_training: Boolean, whether the data is used ... | stack_v2_sparse_classes_10k_train_007350 | 4,902 | permissive | [
{
"docstring": "Initializes slim Dataset etc. Args: dataset: slim Dataset. split_name: String, the name of train/eval/test split. is_training: Boolean, whether the data is used for training. model_variant: String, model variant for choosing how to mean-subtract the images.",
"name": "__init__",
"signatu... | 2 | null | Implement the Python class `InputReader` described below.
Class description:
Prepares data for TPUEstimator.
Method signatures and docstrings:
- def __init__(self, dataset, split_name, is_training, model_variant): Initializes slim Dataset etc. Args: dataset: slim Dataset. split_name: String, the name of train/eval/te... | Implement the Python class `InputReader` described below.
Class description:
Prepares data for TPUEstimator.
Method signatures and docstrings:
- def __init__(self, dataset, split_name, is_training, model_variant): Initializes slim Dataset etc. Args: dataset: slim Dataset. split_name: String, the name of train/eval/te... | 0f7adb97a93ec3e3485c261d030c507eb16b33e4 | <|skeleton|>
class InputReader:
"""Prepares data for TPUEstimator."""
def __init__(self, dataset, split_name, is_training, model_variant):
"""Initializes slim Dataset etc. Args: dataset: slim Dataset. split_name: String, the name of train/eval/test split. is_training: Boolean, whether the data is used ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InputReader:
"""Prepares data for TPUEstimator."""
def __init__(self, dataset, split_name, is_training, model_variant):
"""Initializes slim Dataset etc. Args: dataset: slim Dataset. split_name: String, the name of train/eval/test split. is_training: Boolean, whether the data is used for training.... | the_stack_v2_python_sparse | models/experimental/deeplab/data_pipeline.py | tensorflow/tpu | train | 5,627 |
b67860fa5829925ba8b94f029d289e7b7713da6f | [
"super(afsc_bot_detector, self).__init__()\nself.search_min = search_min\nself.window_len = window_len\nself.backstep = backstep",
"if not isinstance(p_data, processed_data.processed_data):\n raise TypeError('You must pass a processed_data object to this method.')\nv_axis, v_axis_type = p_data.get_v_axis()\nbo... | <|body_start_0|>
super(afsc_bot_detector, self).__init__()
self.search_min = search_min
self.window_len = window_len
self.backstep = backstep
<|end_body_0|>
<|body_start_1|>
if not isinstance(p_data, processed_data.processed_data):
raise TypeError('You must pass a pr... | The afsc_bot_detector class implements a simple amplitude based bottom detection algorithm. It was written mainly as an example and will need to be developed further if you're looking for a robust bottom pick solution. To use, you instantiate an instance setting your bottom deteciton parameters, then call the detect me... | afsc_bot_detector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class afsc_bot_detector:
"""The afsc_bot_detector class implements a simple amplitude based bottom detection algorithm. It was written mainly as an example and will need to be developed further if you're looking for a robust bottom pick solution. To use, you instantiate an instance setting your bottom ... | stack_v2_sparse_classes_10k_train_007351 | 7,840 | permissive | [
{
"docstring": "Initializes afsc_bot_detector object and sets several internal properties.",
"name": "__init__",
"signature": "def __init__(self, search_min=10, window_len=11, backstep=35)"
},
{
"docstring": "p_data - an instance of a processed data object that contains the data to perform the b... | 3 | stack_v2_sparse_classes_30k_train_005361 | Implement the Python class `afsc_bot_detector` described below.
Class description:
The afsc_bot_detector class implements a simple amplitude based bottom detection algorithm. It was written mainly as an example and will need to be developed further if you're looking for a robust bottom pick solution. To use, you insta... | Implement the Python class `afsc_bot_detector` described below.
Class description:
The afsc_bot_detector class implements a simple amplitude based bottom detection algorithm. It was written mainly as an example and will need to be developed further if you're looking for a robust bottom pick solution. To use, you insta... | 6e165ad1a947e62fc233467631c445fe9ebcdad2 | <|skeleton|>
class afsc_bot_detector:
"""The afsc_bot_detector class implements a simple amplitude based bottom detection algorithm. It was written mainly as an example and will need to be developed further if you're looking for a robust bottom pick solution. To use, you instantiate an instance setting your bottom ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class afsc_bot_detector:
"""The afsc_bot_detector class implements a simple amplitude based bottom detection algorithm. It was written mainly as an example and will need to be developed further if you're looking for a robust bottom pick solution. To use, you instantiate an instance setting your bottom deteciton par... | the_stack_v2_python_sparse | echolab2/processing/afsc_bot_detector.py | iambaim/pyEcholab | train | 2 |
13c2070910709952904bde6c9c10bcc81d0ec81d | [
"self._mass_slice_list = []\nfor i in range(len(mass_map_list)):\n self._mass_slice_list.append(MassSlice(mass_map_list[i], grid_spacing_list[i], redshift_list[i]))\nself._mass_map_list = mass_map_list\nself._grid_spacing_list = grid_spacing_list\nself._redshift_list = redshift_list",
"lens_model = LensModel(l... | <|body_start_0|>
self._mass_slice_list = []
for i in range(len(mass_map_list)):
self._mass_slice_list.append(MassSlice(mass_map_list[i], grid_spacing_list[i], redshift_list[i]))
self._mass_map_list = mass_map_list
self._grid_spacing_list = grid_spacing_list
self._reds... | class to perform multi-plane ray-tracing from convergence maps at different redshifts From the convergence maps the deflection angles and lensing potential are computed (from different settings) and then an interpolated grid of all those quantities generate an instance of the lenstronomy LensModel multi-plane instance.... | LightCone | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LightCone:
"""class to perform multi-plane ray-tracing from convergence maps at different redshifts From the convergence maps the deflection angles and lensing potential are computed (from different settings) and then an interpolated grid of all those quantities generate an instance of the lenstr... | stack_v2_sparse_classes_10k_train_007352 | 5,293 | permissive | [
{
"docstring": ":param mass_map_list: 2d numpy array of mass map (in units physical Solar masses enclosed in each pixel/gird point of the map) :param grid_spacing_list: list of grid spacing of the individual mass maps in units of physical Mpc :param redshift_list: list of redshifts of the mass maps",
"name"... | 2 | null | Implement the Python class `LightCone` described below.
Class description:
class to perform multi-plane ray-tracing from convergence maps at different redshifts From the convergence maps the deflection angles and lensing potential are computed (from different settings) and then an interpolated grid of all those quanti... | Implement the Python class `LightCone` described below.
Class description:
class to perform multi-plane ray-tracing from convergence maps at different redshifts From the convergence maps the deflection angles and lensing potential are computed (from different settings) and then an interpolated grid of all those quanti... | 73c9645f26f6983fe7961104075ebe8bf7a4b54c | <|skeleton|>
class LightCone:
"""class to perform multi-plane ray-tracing from convergence maps at different redshifts From the convergence maps the deflection angles and lensing potential are computed (from different settings) and then an interpolated grid of all those quantities generate an instance of the lenstr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LightCone:
"""class to perform multi-plane ray-tracing from convergence maps at different redshifts From the convergence maps the deflection angles and lensing potential are computed (from different settings) and then an interpolated grid of all those quantities generate an instance of the lenstronomy LensMod... | the_stack_v2_python_sparse | lenstronomy/LensModel/LightConeSim/light_cone.py | lenstronomy/lenstronomy | train | 41 |
187eff397e6c196a407ea888f6f77a1b74ab251e | [
"mock_comment = mock.MagicMock()\nmock_comment.body = '/gcbrun trial_build.py aiohttp --sanitizer coverage address --fuzzing-engine libfuzzer'\ncomments = [mock_comment]\nexpected_command = ['aiohttp', '--sanitizer', 'coverage', 'address', '--fuzzing-engine', 'libfuzzer']\nactual_command = ci_trial_build.get_latest... | <|body_start_0|>
mock_comment = mock.MagicMock()
mock_comment.body = '/gcbrun trial_build.py aiohttp --sanitizer coverage address --fuzzing-engine libfuzzer'
comments = [mock_comment]
expected_command = ['aiohttp', '--sanitizer', 'coverage', 'address', '--fuzzing-engine', 'libfuzzer']
... | Tests for get_latest_gcbrun_command. | GetLatestGCBrunCommandTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetLatestGCBrunCommandTest:
"""Tests for get_latest_gcbrun_command."""
def test_command_parsing(self):
"""Tests that commands from GitHub comments are parsed properly."""
<|body_0|>
def test_last_comment(self):
"""Tests that the last comment from the GitHub PR is... | stack_v2_sparse_classes_10k_train_007353 | 2,218 | permissive | [
{
"docstring": "Tests that commands from GitHub comments are parsed properly.",
"name": "test_command_parsing",
"signature": "def test_command_parsing(self)"
},
{
"docstring": "Tests that the last comment from the GitHub PR is considered the command.",
"name": "test_last_comment",
"signa... | 2 | null | Implement the Python class `GetLatestGCBrunCommandTest` described below.
Class description:
Tests for get_latest_gcbrun_command.
Method signatures and docstrings:
- def test_command_parsing(self): Tests that commands from GitHub comments are parsed properly.
- def test_last_comment(self): Tests that the last comment ... | Implement the Python class `GetLatestGCBrunCommandTest` described below.
Class description:
Tests for get_latest_gcbrun_command.
Method signatures and docstrings:
- def test_command_parsing(self): Tests that commands from GitHub comments are parsed properly.
- def test_last_comment(self): Tests that the last comment ... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class GetLatestGCBrunCommandTest:
"""Tests for get_latest_gcbrun_command."""
def test_command_parsing(self):
"""Tests that commands from GitHub comments are parsed properly."""
<|body_0|>
def test_last_comment(self):
"""Tests that the last comment from the GitHub PR is... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetLatestGCBrunCommandTest:
"""Tests for get_latest_gcbrun_command."""
def test_command_parsing(self):
"""Tests that commands from GitHub comments are parsed properly."""
mock_comment = mock.MagicMock()
mock_comment.body = '/gcbrun trial_build.py aiohttp --sanitizer coverage addre... | the_stack_v2_python_sparse | infra/build/functions/ci_trial_build_test.py | google/oss-fuzz | train | 9,438 |
cf2f466d601f487ea693148c9793467a296ee6a7 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DelegatedAdminAccessAssignment()",
"from .delegated_admin_access_assignment_status import DelegatedAdminAccessAssignmentStatus\nfrom .delegated_admin_access_container import DelegatedAdminAccessContainer\nfrom .delegated_admin_access_d... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DelegatedAdminAccessAssignment()
<|end_body_0|>
<|body_start_1|>
from .delegated_admin_access_assignment_status import DelegatedAdminAccessAssignmentStatus
from .delegated_admin_access_c... | DelegatedAdminAccessAssignment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelegatedAdminAccessAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminAccessAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | stack_v2_sparse_classes_10k_train_007354 | 4,301 | 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: DelegatedAdminAccessAssignment",
"name": "create_from_discriminator_value",
"signature": "def create_from_di... | 3 | null | Implement the Python class `DelegatedAdminAccessAssignment` described below.
Class description:
Implement the DelegatedAdminAccessAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminAccessAssignment: Creates a new instance of... | Implement the Python class `DelegatedAdminAccessAssignment` described below.
Class description:
Implement the DelegatedAdminAccessAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminAccessAssignment: Creates a new instance of... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DelegatedAdminAccessAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminAccessAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DelegatedAdminAccessAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminAccessAssignment:
"""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 creat... | the_stack_v2_python_sparse | msgraph/generated/models/delegated_admin_access_assignment.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
9adef181bfce5395e5aa881bb040f1f7620e49ab | [
"config = mock.Mock()\nconfig.workspace = 'workspace'\nconfig.benchmark_method_patterns = ['new_foo.BenchmarkClass.filter:bench.*']\nbenchmark_runner = benchmark.BenchmarkRunner(config)\nmock_benchmark_class = mock.Mock()\nmock_benchmark_class.benchmark_method_1 = 'foo'\nmock_module = mock.Mock()\nsys.modules['new_... | <|body_start_0|>
config = mock.Mock()
config.workspace = 'workspace'
config.benchmark_method_patterns = ['new_foo.BenchmarkClass.filter:bench.*']
benchmark_runner = benchmark.BenchmarkRunner(config)
mock_benchmark_class = mock.Mock()
mock_benchmark_class.benchmark_method_... | TestBenchmarkRunner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBenchmarkRunner:
def test_get_benchmark_methods_filter(self):
"""Tests returning methods on a class based on a filter."""
<|body_0|>
def test_get_benchmark_methods_exact_match(self):
"""Tests returning methods on a class based on a filter."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_007355 | 2,160 | permissive | [
{
"docstring": "Tests returning methods on a class based on a filter.",
"name": "test_get_benchmark_methods_filter",
"signature": "def test_get_benchmark_methods_filter(self)"
},
{
"docstring": "Tests returning methods on a class based on a filter.",
"name": "test_get_benchmark_methods_exact... | 2 | stack_v2_sparse_classes_30k_train_006249 | Implement the Python class `TestBenchmarkRunner` described below.
Class description:
Implement the TestBenchmarkRunner class.
Method signatures and docstrings:
- def test_get_benchmark_methods_filter(self): Tests returning methods on a class based on a filter.
- def test_get_benchmark_methods_exact_match(self): Tests... | Implement the Python class `TestBenchmarkRunner` described below.
Class description:
Implement the TestBenchmarkRunner class.
Method signatures and docstrings:
- def test_get_benchmark_methods_filter(self): Tests returning methods on a class based on a filter.
- def test_get_benchmark_methods_exact_match(self): Tests... | c8e97df0d4d3d0c1020b98391c526df12371fc30 | <|skeleton|>
class TestBenchmarkRunner:
def test_get_benchmark_methods_filter(self):
"""Tests returning methods on a class based on a filter."""
<|body_0|>
def test_get_benchmark_methods_exact_match(self):
"""Tests returning methods on a class based on a filter."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestBenchmarkRunner:
def test_get_benchmark_methods_filter(self):
"""Tests returning methods on a class based on a filter."""
config = mock.Mock()
config.workspace = 'workspace'
config.benchmark_method_patterns = ['new_foo.BenchmarkClass.filter:bench.*']
benchmark_runne... | the_stack_v2_python_sparse | perfzero/lib/benchmark_test.py | tensorflow/benchmarks | train | 1,182 | |
79fd783e07972dd497efd314089114f536ced46f | [
"logger.info('Get all role')\nfilter_object = {'query_string': request.args.get('q', None), 'order_by_field': request.args.get('order_by_field', None), 'order_by': request.args.get('order_by', None), 'datefrom': request.args.get('datefrom', None), 'dateto': request.args.get('dateto', None), 'limit': request.args.ge... | <|body_start_0|>
logger.info('Get all role')
filter_object = {'query_string': request.args.get('q', None), 'order_by_field': request.args.get('order_by_field', None), 'order_by': request.args.get('order_by', None), 'datefrom': request.args.get('datefrom', None), 'dateto': request.args.get('dateto', None... | Role list functionalities | RoleList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleList:
"""Role list functionalities"""
def get(self):
"""Get all role"""
<|body_0|>
def post(self):
"""Insert a role"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
logger.info('Get all role')
filter_object = {'query_string': request.... | stack_v2_sparse_classes_10k_train_007356 | 3,667 | no_license | [
{
"docstring": "Get all role",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Insert a role",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004579 | Implement the Python class `RoleList` described below.
Class description:
Role list functionalities
Method signatures and docstrings:
- def get(self): Get all role
- def post(self): Insert a role | Implement the Python class `RoleList` described below.
Class description:
Role list functionalities
Method signatures and docstrings:
- def get(self): Get all role
- def post(self): Insert a role
<|skeleton|>
class RoleList:
"""Role list functionalities"""
def get(self):
"""Get all role"""
<... | 4dc5f5e816e3c461b8a60c5f61c7eafc08050579 | <|skeleton|>
class RoleList:
"""Role list functionalities"""
def get(self):
"""Get all role"""
<|body_0|>
def post(self):
"""Insert a role"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RoleList:
"""Role list functionalities"""
def get(self):
"""Get all role"""
logger.info('Get all role')
filter_object = {'query_string': request.args.get('q', None), 'order_by_field': request.args.get('order_by_field', None), 'order_by': request.args.get('order_by', None), 'datefr... | the_stack_v2_python_sparse | app/api/role.py | ekramulmostafa/ms-auth | train | 0 |
b8a35ff83563cd4a2bdedbbce46ace657eaa0377 | [
"super().__init__()\nself.grid = [['S', 'F', 'F', 'F'], ['F', 'H', 'F', 'H'], ['F', 'F', 'F', 'H'], ['H', 'F', 'F', 'G']]\nself.env_info = {'policy_type': 'grid', 'action_space': [0, 1, 2, 3], 'state_size': 16}\nself.max_reward_per_episode = 1.0",
"self.state = 0\nself.done = False\nreturn self.state",
"assert ... | <|body_start_0|>
super().__init__()
self.grid = [['S', 'F', 'F', 'F'], ['F', 'H', 'F', 'H'], ['F', 'F', 'F', 'H'], ['H', 'F', 'F', 'G']]
self.env_info = {'policy_type': 'grid', 'action_space': [0, 1, 2, 3], 'state_size': 16}
self.max_reward_per_episode = 1.0
<|end_body_0|>
<|body_start_... | FrozenLakeEnv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrozenLakeEnv:
def __init__(self):
"""Initialise the FrozenLake environment."""
<|body_0|>
def reset(self):
"""Resets the enviroment. Should be called after every episode of a learning procedure. Returns: - self.state: np.array, represents the current state of the en... | stack_v2_sparse_classes_10k_train_007357 | 3,043 | no_license | [
{
"docstring": "Initialise the FrozenLake environment.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Resets the enviroment. Should be called after every episode of a learning procedure. Returns: - self.state: np.array, represents the current state of the environment ... | 3 | stack_v2_sparse_classes_30k_train_006621 | Implement the Python class `FrozenLakeEnv` described below.
Class description:
Implement the FrozenLakeEnv class.
Method signatures and docstrings:
- def __init__(self): Initialise the FrozenLake environment.
- def reset(self): Resets the enviroment. Should be called after every episode of a learning procedure. Retur... | Implement the Python class `FrozenLakeEnv` described below.
Class description:
Implement the FrozenLakeEnv class.
Method signatures and docstrings:
- def __init__(self): Initialise the FrozenLake environment.
- def reset(self): Resets the enviroment. Should be called after every episode of a learning procedure. Retur... | ea6db735b432471bb0e0a1a9db063403ecc08333 | <|skeleton|>
class FrozenLakeEnv:
def __init__(self):
"""Initialise the FrozenLake environment."""
<|body_0|>
def reset(self):
"""Resets the enviroment. Should be called after every episode of a learning procedure. Returns: - self.state: np.array, represents the current state of the en... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FrozenLakeEnv:
def __init__(self):
"""Initialise the FrozenLake environment."""
super().__init__()
self.grid = [['S', 'F', 'F', 'F'], ['F', 'H', 'F', 'H'], ['F', 'F', 'F', 'H'], ['H', 'F', 'F', 'G']]
self.env_info = {'policy_type': 'grid', 'action_space': [0, 1, 2, 3], 'state_s... | the_stack_v2_python_sparse | src/reinforcement_learning/environments/frozenlake.py | Timsey/simple-machine-learning | train | 0 | |
b78075e72465eb318933fba9584ae4154540b444 | [
"if not b:\n need_seconds = a[0]\nelse:\n need_seconds = self.least_need_second(a, b)\nhours = need_seconds // 3600\nmins = (need_seconds - hours * 3600) // 60\nseconds = need_seconds % 60\nif hours + 8 >= 12:\n end = 'pm'\n hours = hours + 8 - 12\n hours_str = ('0' if hours < 10 else '') + str(hours... | <|body_start_0|>
if not b:
need_seconds = a[0]
else:
need_seconds = self.least_need_second(a, b)
hours = need_seconds // 3600
mins = (need_seconds - hours * 3600) // 60
seconds = need_seconds % 60
if hours + 8 >= 12:
end = 'pm'
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def earlest_off_time(self, a, b):
"""Args: a: list[int] b: list[int] Return: str"""
<|body_0|>
def least_need_second(self, a, b):
"""Args: a: list[int] b: list[int] Return: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not b:
... | stack_v2_sparse_classes_10k_train_007358 | 2,060 | no_license | [
{
"docstring": "Args: a: list[int] b: list[int] Return: str",
"name": "earlest_off_time",
"signature": "def earlest_off_time(self, a, b)"
},
{
"docstring": "Args: a: list[int] b: list[int] Return: int",
"name": "least_need_second",
"signature": "def least_need_second(self, a, b)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def earlest_off_time(self, a, b): Args: a: list[int] b: list[int] Return: str
- def least_need_second(self, a, b): Args: a: list[int] b: list[int] Return: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def earlest_off_time(self, a, b): Args: a: list[int] b: list[int] Return: str
- def least_need_second(self, a, b): Args: a: list[int] b: list[int] Return: int
<|skeleton|>
class... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def earlest_off_time(self, a, b):
"""Args: a: list[int] b: list[int] Return: str"""
<|body_0|>
def least_need_second(self, a, b):
"""Args: a: list[int] b: list[int] Return: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def earlest_off_time(self, a, b):
"""Args: a: list[int] b: list[int] Return: str"""
if not b:
need_seconds = a[0]
else:
need_seconds = self.least_need_second(a, b)
hours = need_seconds // 3600
mins = (need_seconds - hours * 3600) // 60
... | the_stack_v2_python_sparse | 秋招/网易/3.py | AiZhanghan/Leetcode | train | 0 | |
a9526fd2fe7b438e5c2de485bbe67a0f9b9f0d24 | [
"from pyopencl.tools import parse_arg_list\nself.arguments = parse_arg_list(arguments)\ndel arguments\nself.sort_arg_names = sort_arg_names\nself.bits = int(bits_at_a_time)\nself.index_dtype = np.dtype(index_dtype)\nself.key_dtype = np.dtype(key_dtype)\nself.options = options\nscan_ctype, scan_dtype, scan_t_cdecl =... | <|body_start_0|>
from pyopencl.tools import parse_arg_list
self.arguments = parse_arg_list(arguments)
del arguments
self.sort_arg_names = sort_arg_names
self.bits = int(bits_at_a_time)
self.index_dtype = np.dtype(index_dtype)
self.key_dtype = np.dtype(key_dtype)
... | Provides a general `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_ on the compute device. .. versionadded:: 2013.1 | RadixSort | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RadixSort:
"""Provides a general `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_ on the compute device. .. versionadded:: 2013.1"""
def __init__(self, context, arguments, key_expr, sort_arg_names, bits_at_a_time=2, index_dtype=np.int32, key_dtype=np.uint32, options=[]):
""":... | stack_v2_sparse_classes_10k_train_007359 | 40,605 | permissive | [
{
"docstring": ":arg arguments: A string of comma-separated C argument declarations. If *arguments* is specified, then *input_expr* must also be specified. All types used here must be known to PyOpenCL. (see :func:`pyopencl.tools.get_or_register_dtype`). :arg key_expr: An integer-valued C expression returning t... | 2 | stack_v2_sparse_classes_30k_val_000135 | Implement the Python class `RadixSort` described below.
Class description:
Provides a general `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_ on the compute device. .. versionadded:: 2013.1
Method signatures and docstrings:
- def __init__(self, context, arguments, key_expr, sort_arg_names, bits_at_a_time=2, ... | Implement the Python class `RadixSort` described below.
Class description:
Provides a general `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_ on the compute device. .. versionadded:: 2013.1
Method signatures and docstrings:
- def __init__(self, context, arguments, key_expr, sort_arg_names, bits_at_a_time=2, ... | 14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1 | <|skeleton|>
class RadixSort:
"""Provides a general `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_ on the compute device. .. versionadded:: 2013.1"""
def __init__(self, context, arguments, key_expr, sort_arg_names, bits_at_a_time=2, index_dtype=np.int32, key_dtype=np.uint32, options=[]):
""":... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RadixSort:
"""Provides a general `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_ on the compute device. .. versionadded:: 2013.1"""
def __init__(self, context, arguments, key_expr, sort_arg_names, bits_at_a_time=2, index_dtype=np.int32, key_dtype=np.uint32, options=[]):
""":arg arguments... | the_stack_v2_python_sparse | data/python/0b8fa53e09a4b9e50dd1bda444ca4436_algorithm.py | maxim5/code-inspector | train | 5 |
db66c9975d076099c7957f1b3acde7c65f25f5d1 | [
"if not array:\n return 0\ndp = [1]\nanswer = 1\nfor i in range(1, len(array)):\n maxLIS = 1\n for j in range(0, i):\n if array[i] > array[j] and dp[j] + 1 > maxLIS:\n maxLIS = dp[j] + 1\n dp.append(maxLIS)\n answer = max(answer, maxLIS)\nreturn answer",
"def binarySearch(nums, st... | <|body_start_0|>
if not array:
return 0
dp = [1]
answer = 1
for i in range(1, len(array)):
maxLIS = 1
for j in range(0, i):
if array[i] > array[j] and dp[j] + 1 > maxLIS:
maxLIS = dp[j] + 1
dp.append(maxL... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestIncreasingSubsequence(self, array):
""":type array: List[int] :rtype: int"""
<|body_0|>
def LIS(self, array):
""":type array: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not array:
return... | stack_v2_sparse_classes_10k_train_007360 | 1,474 | no_license | [
{
"docstring": ":type array: List[int] :rtype: int",
"name": "longestIncreasingSubsequence",
"signature": "def longestIncreasingSubsequence(self, array)"
},
{
"docstring": ":type array: List[int] :rtype: int",
"name": "LIS",
"signature": "def LIS(self, array)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000198 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestIncreasingSubsequence(self, array): :type array: List[int] :rtype: int
- def LIS(self, array): :type array: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestIncreasingSubsequence(self, array): :type array: List[int] :rtype: int
- def LIS(self, array): :type array: List[int] :rtype: int
<|skeleton|>
class Solution:
de... | fa624b702129fa3efd6997791e4cd37c420e114e | <|skeleton|>
class Solution:
def longestIncreasingSubsequence(self, array):
""":type array: List[int] :rtype: int"""
<|body_0|>
def LIS(self, array):
""":type array: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestIncreasingSubsequence(self, array):
""":type array: List[int] :rtype: int"""
if not array:
return 0
dp = [1]
answer = 1
for i in range(1, len(array)):
maxLIS = 1
for j in range(0, i):
if array[i] >... | the_stack_v2_python_sparse | p62/p62.py | zois-tasoulas/DailyInterviewPro | train | 0 | |
82b11074e5d1b48130fa4f5bd3ba0701051e8122 | [
"canned_query_views = []\nif mr.project_id:\n with mr.profiler.Phase('getting canned queries'):\n canned_queries = self.services.features.GetCannedQueriesByProjectID(mr.cnxn, mr.project_id)\n canned_query_views = [savedqueries_helpers.SavedQueryView(sq, idx + 1, None, None) for idx, sq in enumerate(can... | <|body_start_0|>
canned_query_views = []
if mr.project_id:
with mr.profiler.Phase('getting canned queries'):
canned_queries = self.services.features.GetCannedQueriesByProjectID(mr.cnxn, mr.project_id)
canned_query_views = [savedqueries_helpers.SavedQueryView(sq, i... | IssueAdvancedSearch shows a form to enter an advanced search. | IssueAdvancedSearch | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IssueAdvancedSearch:
"""IssueAdvancedSearch shows a form to enter an advanced search."""
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for... | stack_v2_sparse_classes_10k_train_007361 | 4,674 | permissive | [
{
"docstring": "Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for rendering the page.",
"name": "GatherPageData",
"signature": "def GatherPageData(self, mr)"
},
{
"docstring": "Proces... | 4 | stack_v2_sparse_classes_30k_train_001048 | Implement the Python class `IssueAdvancedSearch` described below.
Class description:
IssueAdvancedSearch shows a form to enter an advanced search.
Method signatures and docstrings:
- def GatherPageData(self, mr): Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed ... | Implement the Python class `IssueAdvancedSearch` described below.
Class description:
IssueAdvancedSearch shows a form to enter an advanced search.
Method signatures and docstrings:
- def GatherPageData(self, mr): Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed ... | b5d4783f99461438ca9e6a477535617fadab6ba3 | <|skeleton|>
class IssueAdvancedSearch:
"""IssueAdvancedSearch shows a form to enter an advanced search."""
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IssueAdvancedSearch:
"""IssueAdvancedSearch shows a form to enter an advanced search."""
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for rendering th... | the_stack_v2_python_sparse | appengine/monorail/tracker/issueadvsearch.py | xinghun61/infra | train | 2 |
01b190add20f8cce1f784c3292f2c9e8634de606 | [
"if root is None:\n return 0\nreturn 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))",
"\"\"\" Do a BFS \"\"\"\nimport collections\nq = collections.deque()\ndepth = 0\nq.append(root)\nwhile q:\n levelSize = len(q)\n depth += 1\n for i in range(levelSize):\n node = q.popleft()\n ... | <|body_start_0|>
if root is None:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
<|end_body_0|>
<|body_start_1|>
""" Do a BFS """
import collections
q = collections.deque()
depth = 0
q.append(root)
while q:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
return 0
return ... | stack_v2_sparse_classes_10k_train_007362 | 971 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003856 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def maxDepth(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def maxDepth(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def maxDepth(self, root... | 5714fdb2d8a89a68d68d07f7ffd3f6bcff5b2ccf | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
if root is None:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
""" Do a BFS """
... | the_stack_v2_python_sparse | Python/tree/104_max_depth.py | 01-Jacky/PracticeProblems | train | 0 | |
3b872b98e962a7d8064f7c645edea82fa1c72bb5 | [
"InfiniteMultinomial.__init__(self)\nself.strength = strength\nself.alpha = alpha",
"j = self.num_partitions()\nphi_j = rBeta(self.strength * self.alpha.x(j), self.strength * (1.0 - self.alpha.partition_start(j + 1)))\nassert 0.0 <= phi_j\nassert phi_j <= 1.0\ntop = self.last()\ntop = top + (1.0 - self.partition_... | <|body_start_0|>
InfiniteMultinomial.__init__(self)
self.strength = strength
self.alpha = alpha
<|end_body_0|>
<|body_start_1|>
j = self.num_partitions()
phi_j = rBeta(self.strength * self.alpha.x(j), self.strength * (1.0 - self.alpha.partition_start(j + 1)))
assert 0.0 ... | Lazy sampling from an infinite Dirchlet distribution. | InfiniteDirichlet | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfiniteDirichlet:
"""Lazy sampling from an infinite Dirchlet distribution."""
def __init__(self, strength, alpha):
"""Initialise with a strength parameter and an infinite prior. The infinite prior should be an infinite multinomial parameterisation itself."""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_007363 | 6,764 | permissive | [
{
"docstring": "Initialise with a strength parameter and an infinite prior. The infinite prior should be an infinite multinomial parameterisation itself.",
"name": "__init__",
"signature": "def __init__(self, strength, alpha)"
},
{
"docstring": "Extend the stick breaking construction by one part... | 2 | stack_v2_sparse_classes_30k_train_000799 | Implement the Python class `InfiniteDirichlet` described below.
Class description:
Lazy sampling from an infinite Dirchlet distribution.
Method signatures and docstrings:
- def __init__(self, strength, alpha): Initialise with a strength parameter and an infinite prior. The infinite prior should be an infinite multino... | Implement the Python class `InfiniteDirichlet` described below.
Class description:
Lazy sampling from an infinite Dirchlet distribution.
Method signatures and docstrings:
- def __init__(self, strength, alpha): Initialise with a strength parameter and an infinite prior. The infinite prior should be an infinite multino... | 1b825ba7a60f0a0489df5f41b273374aef628a60 | <|skeleton|>
class InfiniteDirichlet:
"""Lazy sampling from an infinite Dirchlet distribution."""
def __init__(self, strength, alpha):
"""Initialise with a strength parameter and an infinite prior. The infinite prior should be an infinite multinomial parameterisation itself."""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InfiniteDirichlet:
"""Lazy sampling from an infinite Dirchlet distribution."""
def __init__(self, strength, alpha):
"""Initialise with a strength parameter and an infinite prior. The infinite prior should be an infinite multinomial parameterisation itself."""
InfiniteMultinomial.__init__(... | the_stack_v2_python_sparse | python/infpy/dp/infinite_multinomials.py | JohnReid/infpy | train | 5 |
956f48cde8a0a5351b9aebef0bb33400c9549ac6 | [
"self.get_players()\nself.setup_player(self.player1)\nself.setup_player(self.player2)",
"clear_screen()\nprint('Welcome to the Battleship game. You need two players. \\nPlease give the name of the first player:')\nself.player1 = Player()\nprint(\"Thank you. So {} is playing.\\nNow please provide the second player... | <|body_start_0|>
self.get_players()
self.setup_player(self.player1)
self.setup_player(self.player2)
<|end_body_0|>
<|body_start_1|>
clear_screen()
print('Welcome to the Battleship game. You need two players. \nPlease give the name of the first player:')
self.player1 = Pl... | Initiation of the Game Class starts the Battleship Game | Game | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
"""Initiation of the Game Class starts the Battleship Game"""
def setup(self):
"""This methods sets up the game."""
<|body_0|>
def get_players(self):
"""This gets the names of the players and prompts them to continue into the single player setup for both pl... | stack_v2_sparse_classes_10k_train_007364 | 2,637 | no_license | [
{
"docstring": "This methods sets up the game.",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "This gets the names of the players and prompts them to continue into the single player setup for both players.",
"name": "get_players",
"signature": "def get_players(self)"... | 6 | stack_v2_sparse_classes_30k_train_002406 | Implement the Python class `Game` described below.
Class description:
Initiation of the Game Class starts the Battleship Game
Method signatures and docstrings:
- def setup(self): This methods sets up the game.
- def get_players(self): This gets the names of the players and prompts them to continue into the single pla... | Implement the Python class `Game` described below.
Class description:
Initiation of the Game Class starts the Battleship Game
Method signatures and docstrings:
- def setup(self): This methods sets up the game.
- def get_players(self): This gets the names of the players and prompts them to continue into the single pla... | 8bfbba09132b405f7c68cbfd9a0e7596223c3a53 | <|skeleton|>
class Game:
"""Initiation of the Game Class starts the Battleship Game"""
def setup(self):
"""This methods sets up the game."""
<|body_0|>
def get_players(self):
"""This gets the names of the players and prompts them to continue into the single player setup for both pl... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Game:
"""Initiation of the Game Class starts the Battleship Game"""
def setup(self):
"""This methods sets up the game."""
self.get_players()
self.setup_player(self.player1)
self.setup_player(self.player2)
def get_players(self):
"""This gets the names of the pl... | the_stack_v2_python_sparse | project02_python_battleshipgame/game.py | sabinem/treehouse-python-techdegree | train | 3 |
a184c10bc5a33f14401a45ca96bc88c0ee033b86 | [
"try:\n json_data = api.payload\n resp = Node().register(json_data)\n return masked_json_template(resp, 200)\nexcept:\n abort(400, 'Input unrecognizable.')",
"try:\n try:\n get_args = {'filter': request.args.get('filter', default='', type=str), 'range': request.args.get('range', default='', ... | <|body_start_0|>
try:
json_data = api.payload
resp = Node().register(json_data)
return masked_json_template(resp, 200)
except:
abort(400, 'Input unrecognizable.')
<|end_body_0|>
<|body_start_1|>
try:
try:
get_args = {'f... | NodeRoute | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeRoute:
def post(self):
"""Add new node"""
<|body_0|>
def get(self):
"""Get Node data"""
<|body_1|>
def delete(self):
"""Delete all existing Nodes"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
try:
json_data = a... | stack_v2_sparse_classes_10k_train_007365 | 4,218 | permissive | [
{
"docstring": "Add new node",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Get Node data",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Delete all existing Nodes",
"name": "delete",
"signature": "def delete(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_001483 | Implement the Python class `NodeRoute` described below.
Class description:
Implement the NodeRoute class.
Method signatures and docstrings:
- def post(self): Add new node
- def get(self): Get Node data
- def delete(self): Delete all existing Nodes | Implement the Python class `NodeRoute` described below.
Class description:
Implement the NodeRoute class.
Method signatures and docstrings:
- def post(self): Add new node
- def get(self): Get Node data
- def delete(self): Delete all existing Nodes
<|skeleton|>
class NodeRoute:
def post(self):
"""Add new... | 100fca0d2dd9b0b2ab2fa5974d8126af35ddcfd1 | <|skeleton|>
class NodeRoute:
def post(self):
"""Add new node"""
<|body_0|>
def get(self):
"""Get Node data"""
<|body_1|>
def delete(self):
"""Delete all existing Nodes"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NodeRoute:
def post(self):
"""Add new node"""
try:
json_data = api.payload
resp = Node().register(json_data)
return masked_json_template(resp, 200)
except:
abort(400, 'Input unrecognizable.')
def get(self):
"""Get Node data""... | the_stack_v2_python_sparse | app/controllers/api/node/node.py | ardihikaru/api-dashboard-5g-dive | train | 0 | |
5a0aa3c571a2b2c460401d7837dc71a3d28d2ad7 | [
"self.transformed_collection: list[TiTransform] = []\nfor ti_dict in self.ti_dicts:\n self.transformed_collection.append(TiTransform(ti_dict, self.transforms))",
"self.process()\nbatch = {'group': [], 'indicator': []}\nself.log.trace(f'feature=ti-transform-batch, ti-count={len(self.transformed_collection)}')\n... | <|body_start_0|>
self.transformed_collection: list[TiTransform] = []
for ti_dict in self.ti_dicts:
self.transformed_collection.append(TiTransform(ti_dict, self.transforms))
<|end_body_0|>
<|body_start_1|>
self.process()
batch = {'group': [], 'indicator': []}
self.log... | Mappings | TiTransforms | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TiTransforms:
"""Mappings"""
def process(self):
"""Process the mapping."""
<|body_0|>
def batch(self) -> dict:
"""Return the data in batch format."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.transformed_collection: list[TiTransform] = [... | stack_v2_sparse_classes_10k_train_007366 | 6,246 | permissive | [
{
"docstring": "Process the mapping.",
"name": "process",
"signature": "def process(self)"
},
{
"docstring": "Return the data in batch format.",
"name": "batch",
"signature": "def batch(self) -> dict"
}
] | 2 | null | Implement the Python class `TiTransforms` described below.
Class description:
Mappings
Method signatures and docstrings:
- def process(self): Process the mapping.
- def batch(self) -> dict: Return the data in batch format. | Implement the Python class `TiTransforms` described below.
Class description:
Mappings
Method signatures and docstrings:
- def process(self): Process the mapping.
- def batch(self) -> dict: Return the data in batch format.
<|skeleton|>
class TiTransforms:
"""Mappings"""
def process(self):
"""Process... | 30dc147e40d63d1082ec2a5e6c62005b60c29c37 | <|skeleton|>
class TiTransforms:
"""Mappings"""
def process(self):
"""Process the mapping."""
<|body_0|>
def batch(self) -> dict:
"""Return the data in batch format."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TiTransforms:
"""Mappings"""
def process(self):
"""Process the mapping."""
self.transformed_collection: list[TiTransform] = []
for ti_dict in self.ti_dicts:
self.transformed_collection.append(TiTransform(ti_dict, self.transforms))
def batch(self) -> dict:
... | the_stack_v2_python_sparse | tcex/api/tc/ti_transform/ti_transform.py | ThreatConnect-Inc/tcex | train | 24 |
aa38db5eb532ae0799f852a2b06ff8f6ea10f080 | [
"for i in range(len(matrix)):\n for j in range(len(matrix)):\n if matrix[i][j] == target:\n return True\nreturn False",
"res = []\nfor x in matrix:\n res.extend(x)\nreturn target in res",
"res = []\nfor x in matrix:\n res.extend(x)\nres.sort()\nleft, right = (0, len(res) - 1)\nwhile l... | <|body_start_0|>
for i in range(len(matrix)):
for j in range(len(matrix)):
if matrix[i][j] == target:
return True
return False
<|end_body_0|>
<|body_start_1|>
res = []
for x in matrix:
res.extend(x)
return target in res... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
"""Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)"""
<|body_0|>
def searchMatrix1(self, matrix, target):
"""Purpose: searches 2D matrix, and returns True if target is found. ... | stack_v2_sparse_classes_10k_train_007367 | 1,839 | no_license | [
{
"docstring": "Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": "Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)",... | 4 | stack_v2_sparse_classes_30k_train_007180 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)
- def searchMatrix1(self, matrix, target): Purpo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)
- def searchMatrix1(self, matrix, target): Purpo... | 95a86cbbca28d0c0f6d72d28a2f1cb5a86327934 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
"""Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)"""
<|body_0|>
def searchMatrix1(self, matrix, target):
"""Purpose: searches 2D matrix, and returns True if target is found. ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix(self, matrix, target):
"""Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)"""
for i in range(len(matrix)):
for j in range(len(matrix)):
if matrix[i][j] == target:
return True
... | the_stack_v2_python_sparse | search2dMatrix.py | tashakim/puzzles_python | train | 8 | |
9ddad8253d4a8379d70c9546a6f891b702c50c29 | [
"if self == RewardType.EVERY_STEP_ZERO_SUM:\n return (0.0, 1.0)\nelif self == RewardType.EVERY_STEP_LENGTH:\n return (0.0, 1.0)\nelif self == RewardType.ON_EAT_AND_ON_DEATH:\n return (-1.0, 1.0)\nelif self == RewardType.RANK_ON_DEATH:\n return (-1.0, 1.0)\nelse:\n raise ValueError(f'RewardType not ye... | <|body_start_0|>
if self == RewardType.EVERY_STEP_ZERO_SUM:
return (0.0, 1.0)
elif self == RewardType.EVERY_STEP_LENGTH:
return (0.0, 1.0)
elif self == RewardType.ON_EAT_AND_ON_DEATH:
return (-1.0, 1.0)
elif self == RewardType.RANK_ON_DEATH:
... | RewardType | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RewardType:
def get_cumulative_reward_spec(self) -> Tuple[Optional[float], Optional[float]]:
"""The minimum/maximum cumulative available reward"""
<|body_0|>
def get_recommended_value_activation_scale_shift_dict(self) -> Dict:
"""The recommended value activation func... | stack_v2_sparse_classes_10k_train_007368 | 49,153 | permissive | [
{
"docstring": "The minimum/maximum cumulative available reward",
"name": "get_cumulative_reward_spec",
"signature": "def get_cumulative_reward_spec(self) -> Tuple[Optional[float], Optional[float]]"
},
{
"docstring": "The recommended value activation function, value_scale, and value_shift for th... | 2 | stack_v2_sparse_classes_30k_train_005387 | Implement the Python class `RewardType` described below.
Class description:
Implement the RewardType class.
Method signatures and docstrings:
- def get_cumulative_reward_spec(self) -> Tuple[Optional[float], Optional[float]]: The minimum/maximum cumulative available reward
- def get_recommended_value_activation_scale_... | Implement the Python class `RewardType` described below.
Class description:
Implement the RewardType class.
Method signatures and docstrings:
- def get_cumulative_reward_spec(self) -> Tuple[Optional[float], Optional[float]]: The minimum/maximum cumulative available reward
- def get_recommended_value_activation_scale_... | f4d9fcb0811704bd339ad5c7ff937dd0d9e25763 | <|skeleton|>
class RewardType:
def get_cumulative_reward_spec(self) -> Tuple[Optional[float], Optional[float]]:
"""The minimum/maximum cumulative available reward"""
<|body_0|>
def get_recommended_value_activation_scale_shift_dict(self) -> Dict:
"""The recommended value activation func... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RewardType:
def get_cumulative_reward_spec(self) -> Tuple[Optional[float], Optional[float]]:
"""The minimum/maximum cumulative available reward"""
if self == RewardType.EVERY_STEP_ZERO_SUM:
return (0.0, 1.0)
elif self == RewardType.EVERY_STEP_LENGTH:
return (0.0... | the_stack_v2_python_sparse | hungry_geese/env/goose_env.py | IsaiahPressman/Kaggle_Hungry_Geese | train | 0 | |
3615569900ca4fb2800158d5453528df61c53f26 | [
"self.db_name = name\nself.data = self.extract(version)\nself.strategies = [normalize_units, drop_unspecified_subcategories, ensure_categories_are_tuples]",
"def extract_flow_data(o):\n ds = {'categories': (o.compartment.compartment.text, o.compartment.subcompartment.text), 'code': o.get('id'), 'CAS number': o... | <|body_start_0|>
self.db_name = name
self.data = self.extract(version)
self.strategies = [normalize_units, drop_unspecified_subcategories, ensure_categories_are_tuples]
<|end_body_0|>
<|body_start_1|>
def extract_flow_data(o):
ds = {'categories': (o.compartment.compartment.t... | Import elementary flows from ecoinvent xml format. Attributes ---------- format : str Format of the data: "Ecoinvent XML". db_name : str Name of the database. data : list Extracted data from the xml file. strategies : list List of functions to apply to the extracted data. See Also -------- https://github.com/brightway-... | Ecospold2BiosphereImporter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ecospold2BiosphereImporter:
"""Import elementary flows from ecoinvent xml format. Attributes ---------- format : str Format of the data: "Ecoinvent XML". db_name : str Name of the database. data : list Extracted data from the xml file. strategies : list List of functions to apply to the extracted... | stack_v2_sparse_classes_10k_train_007369 | 2,880 | permissive | [
{
"docstring": "Initialize the importer. Parameters ---------- name : str, optional Name of the database, by default \"biosphere3\". version : str, optional Version of the database, by default \"3.9\".",
"name": "__init__",
"signature": "def __init__(self, name='biosphere3', version='3.9')"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_006886 | Implement the Python class `Ecospold2BiosphereImporter` described below.
Class description:
Import elementary flows from ecoinvent xml format. Attributes ---------- format : str Format of the data: "Ecoinvent XML". db_name : str Name of the database. data : list Extracted data from the xml file. strategies : list List... | Implement the Python class `Ecospold2BiosphereImporter` described below.
Class description:
Import elementary flows from ecoinvent xml format. Attributes ---------- format : str Format of the data: "Ecoinvent XML". db_name : str Name of the database. data : list Extracted data from the xml file. strategies : list List... | 0c3c7288a897f57511ce17a6be1698e2cb9b08a1 | <|skeleton|>
class Ecospold2BiosphereImporter:
"""Import elementary flows from ecoinvent xml format. Attributes ---------- format : str Format of the data: "Ecoinvent XML". db_name : str Name of the database. data : list Extracted data from the xml file. strategies : list List of functions to apply to the extracted... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Ecospold2BiosphereImporter:
"""Import elementary flows from ecoinvent xml format. Attributes ---------- format : str Format of the data: "Ecoinvent XML". db_name : str Name of the database. data : list Extracted data from the xml file. strategies : list List of functions to apply to the extracted data. See Al... | the_stack_v2_python_sparse | bw2io/importers/ecospold2_biosphere.py | brightway-lca/brightway2-io | train | 13 |
3f0b8d03bb81763f0e1b0ba5c89e9cf5fa6efe42 | [
"self._skeleton = server.TrunkSkeleton()\nself._stub = server.TrunkStub()\nLOG.debug('RPC backend initialized for trunk plugin')\nfor event_type in (events.AFTER_CREATE, events.AFTER_DELETE):\n registry.subscribe(self.process_event, resources.TRUNK, event_type)\n registry.subscribe(self.process_event, resourc... | <|body_start_0|>
self._skeleton = server.TrunkSkeleton()
self._stub = server.TrunkStub()
LOG.debug('RPC backend initialized for trunk plugin')
for event_type in (events.AFTER_CREATE, events.AFTER_DELETE):
registry.subscribe(self.process_event, resources.TRUNK, event_type)
... | The Neutron Server RPC backend. | ServerSideRpcBackend | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerSideRpcBackend:
"""The Neutron Server RPC backend."""
def __init__(self):
"""Initialize an RPC backend for the Neutron Server."""
<|body_0|>
def process_event(self, resource, event, trunk_plugin, payload):
"""Emit RPC notifications to registered subscribers... | stack_v2_sparse_classes_10k_train_007370 | 2,676 | permissive | [
{
"docstring": "Initialize an RPC backend for the Neutron Server.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Emit RPC notifications to registered subscribers.",
"name": "process_event",
"signature": "def process_event(self, resource, event, trunk_plugin, p... | 2 | null | Implement the Python class `ServerSideRpcBackend` described below.
Class description:
The Neutron Server RPC backend.
Method signatures and docstrings:
- def __init__(self): Initialize an RPC backend for the Neutron Server.
- def process_event(self, resource, event, trunk_plugin, payload): Emit RPC notifications to r... | Implement the Python class `ServerSideRpcBackend` described below.
Class description:
The Neutron Server RPC backend.
Method signatures and docstrings:
- def __init__(self): Initialize an RPC backend for the Neutron Server.
- def process_event(self, resource, event, trunk_plugin, payload): Emit RPC notifications to r... | dde31aae392b80341f6440eb38db1583563d7d1f | <|skeleton|>
class ServerSideRpcBackend:
"""The Neutron Server RPC backend."""
def __init__(self):
"""Initialize an RPC backend for the Neutron Server."""
<|body_0|>
def process_event(self, resource, event, trunk_plugin, payload):
"""Emit RPC notifications to registered subscribers... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ServerSideRpcBackend:
"""The Neutron Server RPC backend."""
def __init__(self):
"""Initialize an RPC backend for the Neutron Server."""
self._skeleton = server.TrunkSkeleton()
self._stub = server.TrunkStub()
LOG.debug('RPC backend initialized for trunk plugin')
for... | the_stack_v2_python_sparse | neutron/services/trunk/rpc/backend.py | openstack/neutron | train | 1,174 |
8d3fbc72f95891fe45b86724380600c7616d8be8 | [
"super(Actor, self).__init__()\nself.log_std_min = log_std_min\nself.log_std_max = log_std_max\nself.hidden = nn.Linear(in_dim, 32)\nself.mu_layer = nn.Linear(32, out_dim)\nself.mu_layer = init_layer_uniform(self.mu_layer)\nself.log_std_layer = nn.Linear(32, out_dim)\nself.log_std_layer = init_layer_uniform(self.lo... | <|body_start_0|>
super(Actor, self).__init__()
self.log_std_min = log_std_min
self.log_std_max = log_std_max
self.hidden = nn.Linear(in_dim, 32)
self.mu_layer = nn.Linear(32, out_dim)
self.mu_layer = init_layer_uniform(self.mu_layer)
self.log_std_layer = nn.Linear... | Actor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Actor:
def __init__(self, in_dim: int, out_dim: int, log_std_min: int=-20, log_std_max: int=0):
"""Initialize."""
<|body_0|>
def forward(self, state: torch.Tensor) -> torch.Tensor:
"""Forward method implementation."""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_10k_train_007371 | 13,315 | no_license | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, in_dim: int, out_dim: int, log_std_min: int=-20, log_std_max: int=0)"
},
{
"docstring": "Forward method implementation.",
"name": "forward",
"signature": "def forward(self, state: torch.Tensor) -> torch.Te... | 2 | stack_v2_sparse_classes_30k_train_006925 | Implement the Python class `Actor` described below.
Class description:
Implement the Actor class.
Method signatures and docstrings:
- def __init__(self, in_dim: int, out_dim: int, log_std_min: int=-20, log_std_max: int=0): Initialize.
- def forward(self, state: torch.Tensor) -> torch.Tensor: Forward method implementa... | Implement the Python class `Actor` described below.
Class description:
Implement the Actor class.
Method signatures and docstrings:
- def __init__(self, in_dim: int, out_dim: int, log_std_min: int=-20, log_std_max: int=0): Initialize.
- def forward(self, state: torch.Tensor) -> torch.Tensor: Forward method implementa... | 14ddfb81295c349acc2ede7588ebc73c235246c0 | <|skeleton|>
class Actor:
def __init__(self, in_dim: int, out_dim: int, log_std_min: int=-20, log_std_max: int=0):
"""Initialize."""
<|body_0|>
def forward(self, state: torch.Tensor) -> torch.Tensor:
"""Forward method implementation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Actor:
def __init__(self, in_dim: int, out_dim: int, log_std_min: int=-20, log_std_max: int=0):
"""Initialize."""
super(Actor, self).__init__()
self.log_std_min = log_std_min
self.log_std_max = log_std_max
self.hidden = nn.Linear(in_dim, 32)
self.mu_layer = nn.L... | the_stack_v2_python_sparse | PPO_GAE_TEST/PPO_gae_test2.py | namjiwon1023/Reinforcement_learning | train | 2 | |
ab557a96b07a16843ce01d55c38a14c2c13d16d9 | [
"self.key = key\nself.value = value\nself.left = self.right = None",
"if key < self.key:\n if self.left:\n self.left.insert(key, value)\n else:\n self.left = Tree(key, value)\nelif key > self.key:\n if self.right:\n self.right.insert(key, value)\n else:\n self.right = Tree(... | <|body_start_0|>
self.key = key
self.value = value
self.left = self.right = None
<|end_body_0|>
<|body_start_1|>
if key < self.key:
if self.left:
self.left.insert(key, value)
else:
self.left = Tree(key, value)
elif key > se... | Tree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tree:
def __init__(self, key, value=None):
"""Create a new Tree object with empty L & R subtrees."""
<|body_0|>
def insert(self, key, value=None):
"""Insert a new element into the tree in th ecorrect position."""
<|body_1|>
def walk(self):
"""Gen... | stack_v2_sparse_classes_10k_train_007372 | 2,224 | no_license | [
{
"docstring": "Create a new Tree object with empty L & R subtrees.",
"name": "__init__",
"signature": "def __init__(self, key, value=None)"
},
{
"docstring": "Insert a new element into the tree in th ecorrect position.",
"name": "insert",
"signature": "def insert(self, key, value=None)"... | 5 | stack_v2_sparse_classes_30k_train_002459 | Implement the Python class `Tree` described below.
Class description:
Implement the Tree class.
Method signatures and docstrings:
- def __init__(self, key, value=None): Create a new Tree object with empty L & R subtrees.
- def insert(self, key, value=None): Insert a new element into the tree in th ecorrect position.
... | Implement the Python class `Tree` described below.
Class description:
Implement the Tree class.
Method signatures and docstrings:
- def __init__(self, key, value=None): Create a new Tree object with empty L & R subtrees.
- def insert(self, key, value=None): Insert a new element into the tree in th ecorrect position.
... | eff582478058db318e1b9352ce26c5afa8f21231 | <|skeleton|>
class Tree:
def __init__(self, key, value=None):
"""Create a new Tree object with empty L & R subtrees."""
<|body_0|>
def insert(self, key, value=None):
"""Insert a new element into the tree in th ecorrect position."""
<|body_1|>
def walk(self):
"""Gen... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Tree:
def __init__(self, key, value=None):
"""Create a new Tree object with empty L & R subtrees."""
self.key = key
self.value = value
self.left = self.right = None
def insert(self, key, value=None):
"""Insert a new element into the tree in th ecorrect position."""... | the_stack_v2_python_sparse | python/Python4_Homework03/src/tree.py | joelgarzatx/portfolio | train | 0 | |
c57f1160fb160f8e68a0ec2500ffeb2c7f442ab7 | [
"n = len(nums1)\nm = len(nums2)\ni = -1\nj = 0\nans = []\nwhile k:\n ch = []\n if 0 <= i + 1 < n and 0 <= j < m:\n ch.append((nums1[i + 1] + nums2[j], i + 1, 0, nums1[i + 1], nums2[j]))\n if 0 <= j + 1 < m and 0 <= i < n:\n ch.append((nums1[i] + nums2[j + 1], 0, j + 1, nums1[i], nums2[j + 1])... | <|body_start_0|>
n = len(nums1)
m = len(nums2)
i = -1
j = 0
ans = []
while k:
ch = []
if 0 <= i + 1 < n and 0 <= j < m:
ch.append((nums1[i + 1] + nums2[j], i + 1, 0, nums1[i + 1], nums2[j]))
if 0 <= j + 1 < m and 0 <= i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kSmallestPairsWA(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
<|body_0|>
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype:... | stack_v2_sparse_classes_10k_train_007373 | 2,425 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]",
"name": "kSmallestPairsWA",
"signature": "def kSmallestPairsWA(self, nums1, nums2, k)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kSmallestPairsWA(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]
- def kSmallestPairs(self, nums1, nums2, k): :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kSmallestPairsWA(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]
- def kSmallestPairs(self, nums1, nums2, k): :type... | 02ebe56cd92b9f4baeee132c5077892590018650 | <|skeleton|>
class Solution:
def kSmallestPairsWA(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
<|body_0|>
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def kSmallestPairsWA(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
n = len(nums1)
m = len(nums2)
i = -1
j = 0
ans = []
while k:
ch = []
if 0 <= i + 1 < n... | the_stack_v2_python_sparse | python/leetcode.373.py | CalvinNeo/LeetCode | train | 3 | |
df76d797c60cefe8bfb44bcbaf67ca2c5725bb74 | [
"self.name = name\nself.function = function\nself.hindcast = hindcast\nself.probabilistic = probabilistic\nself.long_name = long_name\nself.aliases = aliases",
"summary = '----- Comparison metadata -----\\n'\nsummary += f'Name: {self.name}\\n'\nif not self.probabilistic:\n summary += 'Kind: deterministic\\n'\n... | <|body_start_0|>
self.name = name
self.function = function
self.hindcast = hindcast
self.probabilistic = probabilistic
self.long_name = long_name
self.aliases = aliases
<|end_body_0|>
<|body_start_1|>
summary = '----- Comparison metadata -----\n'
summary ... | Master class for all comparisons. See :ref:`comparisons`. | Comparison | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Comparison:
"""Master class for all comparisons. See :ref:`comparisons`."""
def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Optional[str]=None, aliases: Optional[List[str]]=None) -> None:
... | stack_v2_sparse_classes_10k_train_007374 | 11,669 | permissive | [
{
"docstring": "Comparison initialization See :ref:`comparisons`. Args: name: name of comparison. function: comparison function. hindcast: Can comparison be used in :py:class:`.HindcastEnsemble`? ``False`` means only :py:class:`.PerfectModelEnsemble` probabilistic: Can this comparison be used for probabilistic ... | 2 | stack_v2_sparse_classes_30k_train_002936 | Implement the Python class `Comparison` described below.
Class description:
Master class for all comparisons. See :ref:`comparisons`.
Method signatures and docstrings:
- def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Op... | Implement the Python class `Comparison` described below.
Class description:
Master class for all comparisons. See :ref:`comparisons`.
Method signatures and docstrings:
- def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Op... | 1424e89e9bdf3eb1ae47d581be2953ede0b98996 | <|skeleton|>
class Comparison:
"""Master class for all comparisons. See :ref:`comparisons`."""
def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Optional[str]=None, aliases: Optional[List[str]]=None) -> None:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Comparison:
"""Master class for all comparisons. See :ref:`comparisons`."""
def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Optional[str]=None, aliases: Optional[List[str]]=None) -> None:
"""Comparis... | the_stack_v2_python_sparse | climpred/comparisons.py | pangeo-data/climpred | train | 164 |
c5adee643bbe9db8b815807dc9e4497a6beb0d8f | [
"address = ModelDelivereAdrressClient.query.filter_by(id=address_id).filter_by(client=client_id).first()\nif address:\n try:\n address.delete_address()\n return (jsonify({'message': 'address deleted'}), 200)\n except:\n return (jsonify({'message': 'Internal error'}), 500)\nreturn (jsonify... | <|body_start_0|>
address = ModelDelivereAdrressClient.query.filter_by(id=address_id).filter_by(client=client_id).first()
if address:
try:
address.delete_address()
return (jsonify({'message': 'address deleted'}), 200)
except:
return ... | ClientAddressApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientAddressApi:
def delete(self, client_id, address_id):
"""Deletar endereço de entrega cadastrado."""
<|body_0|>
def put(self, client_id, address_id):
"""Atualiza endereço de entrega cadastrador"""
<|body_1|>
def patch(self, client_id, address_id):
... | stack_v2_sparse_classes_10k_train_007375 | 11,080 | permissive | [
{
"docstring": "Deletar endereço de entrega cadastrado.",
"name": "delete",
"signature": "def delete(self, client_id, address_id)"
},
{
"docstring": "Atualiza endereço de entrega cadastrador",
"name": "put",
"signature": "def put(self, client_id, address_id)"
},
{
"docstring": "S... | 4 | stack_v2_sparse_classes_30k_train_005503 | Implement the Python class `ClientAddressApi` described below.
Class description:
Implement the ClientAddressApi class.
Method signatures and docstrings:
- def delete(self, client_id, address_id): Deletar endereço de entrega cadastrado.
- def put(self, client_id, address_id): Atualiza endereço de entrega cadastrador
... | Implement the Python class `ClientAddressApi` described below.
Class description:
Implement the ClientAddressApi class.
Method signatures and docstrings:
- def delete(self, client_id, address_id): Deletar endereço de entrega cadastrado.
- def put(self, client_id, address_id): Atualiza endereço de entrega cadastrador
... | d85e9eb6680e48bfa4a8ccba24c76fb8f5fbcc54 | <|skeleton|>
class ClientAddressApi:
def delete(self, client_id, address_id):
"""Deletar endereço de entrega cadastrado."""
<|body_0|>
def put(self, client_id, address_id):
"""Atualiza endereço de entrega cadastrador"""
<|body_1|>
def patch(self, client_id, address_id):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClientAddressApi:
def delete(self, client_id, address_id):
"""Deletar endereço de entrega cadastrado."""
address = ModelDelivereAdrressClient.query.filter_by(id=address_id).filter_by(client=client_id).first()
if address:
try:
address.delete_address()
... | the_stack_v2_python_sparse | Api/resources/admin/clients.py | rodrigomota01/azulerosa | train | 0 | |
8160c0212a3f5a0f67007330614cd13566ea606a | [
"figure = plt.figure()\naxes = plt.gca()\nlc_linecolors = rhessi.hsi_linecolors()\nfor lc_color, (item, frame) in zip(lc_linecolors, self.data.iteritems()):\n axes.plot_date(self.data.index, frame.values, '-', label=item, lw=2, color=lc_color)\naxes.set_yscale('log')\naxes.set_xlabel(datetime.datetime.isoformat(... | <|body_start_0|>
figure = plt.figure()
axes = plt.gca()
lc_linecolors = rhessi.hsi_linecolors()
for lc_color, (item, frame) in zip(lc_linecolors, self.data.iteritems()):
axes.plot_date(self.data.index, frame.values, '-', label=item, lw=2, color=lc_color)
axes.set_ysca... | RHESSI X-ray Summary LightCurve. The RHESSI mission consists of a single spin-stabilized spacecraft in a low-altitude orbit inclined 38 degrees to the Earth's equator. The only instrument on board is an Germaniun imaging spectrometer with the ability to obtain high fidelity solar images in X rays (down to 3 keV) to gam... | RHESSISummaryLightCurve | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RHESSISummaryLightCurve:
"""RHESSI X-ray Summary LightCurve. The RHESSI mission consists of a single spin-stabilized spacecraft in a low-altitude orbit inclined 38 degrees to the Earth's equator. The only instrument on board is an Germaniun imaging spectrometer with the ability to obtain high fid... | stack_v2_sparse_classes_10k_train_007376 | 4,180 | permissive | [
{
"docstring": "Plots RHESSI Count Rate light curve. An example is shown below. .. plot:: from sunpy import lightcurve as lc from sunpy.data.sample import RHESSI_TIMESERIES rhessi = lc.RHESSISummaryLightCurve.create(RHESSI_TIMESERIES) rhessi.peek() Returns ------- fig : `~matplotlib.Figure` A plot figure.",
... | 4 | stack_v2_sparse_classes_30k_train_003897 | Implement the Python class `RHESSISummaryLightCurve` described below.
Class description:
RHESSI X-ray Summary LightCurve. The RHESSI mission consists of a single spin-stabilized spacecraft in a low-altitude orbit inclined 38 degrees to the Earth's equator. The only instrument on board is an Germaniun imaging spectrome... | Implement the Python class `RHESSISummaryLightCurve` described below.
Class description:
RHESSI X-ray Summary LightCurve. The RHESSI mission consists of a single spin-stabilized spacecraft in a low-altitude orbit inclined 38 degrees to the Earth's equator. The only instrument on board is an Germaniun imaging spectrome... | 52fb75ece4677e554d5a6a5b43fa116a66d1fcdc | <|skeleton|>
class RHESSISummaryLightCurve:
"""RHESSI X-ray Summary LightCurve. The RHESSI mission consists of a single spin-stabilized spacecraft in a low-altitude orbit inclined 38 degrees to the Earth's equator. The only instrument on board is an Germaniun imaging spectrometer with the ability to obtain high fid... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RHESSISummaryLightCurve:
"""RHESSI X-ray Summary LightCurve. The RHESSI mission consists of a single spin-stabilized spacecraft in a low-altitude orbit inclined 38 degrees to the Earth's equator. The only instrument on board is an Germaniun imaging spectrometer with the ability to obtain high fidelity solar i... | the_stack_v2_python_sparse | sunpy/lightcurve/sources/rhessi.py | cosmologist10/sunpy | train | 1 |
3461d7e94d781666a648e1a69b346c03d863afd3 | [
"response = utility.ExecutorResponse()\nresponse._stdout = '{\"key\":\"value\"}'\nresponse._parse_raw_input()\nself.assertEqual(response._json, '{\"key\":\"value\"}')\nself.assertEqual(response._parsed_output, {'key': 'value'})",
"response = utility.ExecutorResponse()\nresponse._stdout = 'non-json string'\nrespon... | <|body_start_0|>
response = utility.ExecutorResponse()
response._stdout = '{"key":"value"}'
response._parse_raw_input()
self.assertEqual(response._json, '{"key":"value"}')
self.assertEqual(response._parsed_output, {'key': 'value'})
<|end_body_0|>
<|body_start_1|>
respons... | UtilityTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilityTest:
def test_parse_raw_input_json(self):
"""Testing json stdout is correctly parsed."""
<|body_0|>
def test_parse_raw_input_text(self):
"""Testing non-json stdout is correctly parsed."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
response... | stack_v2_sparse_classes_10k_train_007377 | 1,529 | permissive | [
{
"docstring": "Testing json stdout is correctly parsed.",
"name": "test_parse_raw_input_json",
"signature": "def test_parse_raw_input_json(self)"
},
{
"docstring": "Testing non-json stdout is correctly parsed.",
"name": "test_parse_raw_input_text",
"signature": "def test_parse_raw_input... | 2 | null | Implement the Python class `UtilityTest` described below.
Class description:
Implement the UtilityTest class.
Method signatures and docstrings:
- def test_parse_raw_input_json(self): Testing json stdout is correctly parsed.
- def test_parse_raw_input_text(self): Testing non-json stdout is correctly parsed. | Implement the Python class `UtilityTest` described below.
Class description:
Implement the UtilityTest class.
Method signatures and docstrings:
- def test_parse_raw_input_json(self): Testing json stdout is correctly parsed.
- def test_parse_raw_input_text(self): Testing non-json stdout is correctly parsed.
<|skeleto... | 3fb199658f68e7debf4906d9ce32a9a307e39243 | <|skeleton|>
class UtilityTest:
def test_parse_raw_input_json(self):
"""Testing json stdout is correctly parsed."""
<|body_0|>
def test_parse_raw_input_text(self):
"""Testing non-json stdout is correctly parsed."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UtilityTest:
def test_parse_raw_input_json(self):
"""Testing json stdout is correctly parsed."""
response = utility.ExecutorResponse()
response._stdout = '{"key":"value"}'
response._parse_raw_input()
self.assertEqual(response._json, '{"key":"value"}')
self.asser... | the_stack_v2_python_sparse | sdk/python/kfp/deprecated/cli/diagnose_me/utility_test.py | kubeflow/pipelines | train | 3,434 | |
3f50cdff9d0323d2880ddeaf534eb66b5046d6ca | [
"self.n1, self.n2 = (self.initialize_ngram(ngram_file_name1, sep), self.initialize_ngram(ngram_file_name2, sep))\nself.ngrams1, self.floor1, self.L1 = (self.n1[0], self.n1[1], self.n1[2])\nself.ngrams2, self.floor2, self.L2 = (self.n2[0], self.n2[1], self.n2[2])",
"log_score = 0\nfor i in range(len(text) - self.L... | <|body_start_0|>
self.n1, self.n2 = (self.initialize_ngram(ngram_file_name1, sep), self.initialize_ngram(ngram_file_name2, sep))
self.ngrams1, self.floor1, self.L1 = (self.n1[0], self.n1[1], self.n1[2])
self.ngrams2, self.floor2, self.L2 = (self.n2[0], self.n2[1], self.n2[2])
<|end_body_0|>
<|b... | ngram_score | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ngram_score:
def __init__(self, ngram_file_name1, ngram_file_name2, sep=' '):
"""Generally - scorer = ngram_score('english_trigrams.txt', 'english_quadgrams.txt') Initializes log10 probability dictionaries self.ngrams1 & 2, as well as corresponding self.floors1 & 2, and self.L1 & 2 (leng... | stack_v2_sparse_classes_10k_train_007378 | 12,572 | permissive | [
{
"docstring": "Generally - scorer = ngram_score('english_trigrams.txt', 'english_quadgrams.txt') Initializes log10 probability dictionaries self.ngrams1 & 2, as well as corresponding self.floors1 & 2, and self.L1 & 2 (length of ngram) . self.L1 should be of length one shorter than self.L2, e.g. trigram and qua... | 3 | stack_v2_sparse_classes_30k_train_005229 | Implement the Python class `ngram_score` described below.
Class description:
Implement the ngram_score class.
Method signatures and docstrings:
- def __init__(self, ngram_file_name1, ngram_file_name2, sep=' '): Generally - scorer = ngram_score('english_trigrams.txt', 'english_quadgrams.txt') Initializes log10 probabi... | Implement the Python class `ngram_score` described below.
Class description:
Implement the ngram_score class.
Method signatures and docstrings:
- def __init__(self, ngram_file_name1, ngram_file_name2, sep=' '): Generally - scorer = ngram_score('english_trigrams.txt', 'english_quadgrams.txt') Initializes log10 probabi... | afac5a4b3c31ec78e6c8ef211ba9dd664a4070f7 | <|skeleton|>
class ngram_score:
def __init__(self, ngram_file_name1, ngram_file_name2, sep=' '):
"""Generally - scorer = ngram_score('english_trigrams.txt', 'english_quadgrams.txt') Initializes log10 probability dictionaries self.ngrams1 & 2, as well as corresponding self.floors1 & 2, and self.L1 & 2 (leng... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ngram_score:
def __init__(self, ngram_file_name1, ngram_file_name2, sep=' '):
"""Generally - scorer = ngram_score('english_trigrams.txt', 'english_quadgrams.txt') Initializes log10 probability dictionaries self.ngrams1 & 2, as well as corresponding self.floors1 & 2, and self.L1 & 2 (length of ngram) .... | the_stack_v2_python_sparse | basics_less_old.py | BenjiDayan/national_cipher_challenge | train | 0 | |
c4ecd1600a103e129b137ec874c25f3c6b86c7d1 | [
"excluded_ports = set(['TruePort', 'FalsePort', 'TrueOutputPorts', 'FalseOutputPorts'])\nfor port_name, connector_list in self.inputPorts.iteritems():\n if port_name not in excluded_ports:\n for connector in connector_list:\n connector.obj.update()\nfor port_name, connectorList in copy.copy(sel... | <|body_start_0|>
excluded_ports = set(['TruePort', 'FalsePort', 'TrueOutputPorts', 'FalseOutputPorts'])
for port_name, connector_list in self.inputPorts.iteritems():
if port_name not in excluded_ports:
for connector in connector_list:
connector.obj.update(... | The If Module alows the user to choose the part of the workflow to be executed through the use of a condition. | If | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class If:
"""The If Module alows the user to choose the part of the workflow to be executed through the use of a condition."""
def updateUpstream(self):
"""A modified version of the updateUpstream method."""
<|body_0|>
def compute(self):
"""The compute method for the I... | stack_v2_sparse_classes_10k_train_007379 | 5,146 | permissive | [
{
"docstring": "A modified version of the updateUpstream method.",
"name": "updateUpstream",
"signature": "def updateUpstream(self)"
},
{
"docstring": "The compute method for the If module.",
"name": "compute",
"signature": "def compute(self)"
}
] | 2 | null | Implement the Python class `If` described below.
Class description:
The If Module alows the user to choose the part of the workflow to be executed through the use of a condition.
Method signatures and docstrings:
- def updateUpstream(self): A modified version of the updateUpstream method.
- def compute(self): The com... | Implement the Python class `If` described below.
Class description:
The If Module alows the user to choose the part of the workflow to be executed through the use of a condition.
Method signatures and docstrings:
- def updateUpstream(self): A modified version of the updateUpstream method.
- def compute(self): The com... | 23ef56ec24b85c82416e1437a08381635328abe5 | <|skeleton|>
class If:
"""The If Module alows the user to choose the part of the workflow to be executed through the use of a condition."""
def updateUpstream(self):
"""A modified version of the updateUpstream method."""
<|body_0|>
def compute(self):
"""The compute method for the I... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class If:
"""The If Module alows the user to choose the part of the workflow to be executed through the use of a condition."""
def updateUpstream(self):
"""A modified version of the updateUpstream method."""
excluded_ports = set(['TruePort', 'FalsePort', 'TrueOutputPorts', 'FalseOutputPorts'])
... | the_stack_v2_python_sparse | vistrails_current/vistrails/packages/controlflow/conditional.py | lumig242/VisTrailsRecommendation | train | 3 |
35f38c64fa2560d5152ce761dddaf6573982eb53 | [
"count = 0\ncnt_words = {}\nfor word in words:\n cnt_words[word] = cnt_words.get(word, 0) + 1\nfor word in cnt_words.keys():\n if self.isSubsequence(word, S):\n count += cnt_words[word]\nreturn count",
"idx = 0\nfor c in s:\n idx = t.find(c, idx)\n if idx == -1:\n return False\n idx +... | <|body_start_0|>
count = 0
cnt_words = {}
for word in words:
cnt_words[word] = cnt_words.get(word, 0) + 1
for word in cnt_words.keys():
if self.isSubsequence(word, S):
count += cnt_words[word]
return count
<|end_body_0|>
<|body_start_1|>
... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numMatchingSubseq(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
<|body_0|>
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = 0
... | stack_v2_sparse_classes_10k_train_007380 | 3,821 | permissive | [
{
"docstring": ":type S: str :type words: List[str] :rtype: int",
"name": "numMatchingSubseq",
"signature": "def numMatchingSubseq(self, S, words)"
},
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isSubsequence",
"signature": "def isSubsequence(self, s, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005622 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numMatchingSubseq(self, S, words): :type S: str :type words: List[str] :rtype: int
- def isSubsequence(self, s, t): :type s: str :type t: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numMatchingSubseq(self, S, words): :type S: str :type words: List[str] :rtype: int
- def isSubsequence(self, s, t): :type s: str :type t: str :rtype: bool
<|skeleton|>
class... | 34d34280170c991ea7a28d74a3f2338753844917 | <|skeleton|>
class Solution:
def numMatchingSubseq(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
<|body_0|>
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def numMatchingSubseq(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
count = 0
cnt_words = {}
for word in words:
cnt_words[word] = cnt_words.get(word, 0) + 1
for word in cnt_words.keys():
if self.isSubsequence(wo... | the_stack_v2_python_sparse | number_of_matching_subsequences_792.py | danielsunzhongyuan/my_leetcode_in_python | train | 0 | |
bb187ee689ddcfc19545b1920cc5882d37236f62 | [
"A = a.split('+')\nB = b.split('+')\nA[-1] = A[-1][0:-1]\nB[-1] = B[-1][0:-1]\nfirst = int(A[0]) * int(B[0])\nsecond = -int(A[-1]) * int(B[-1])\nthrid = int(A[0]) * int(B[-1]) + int(A[-1]) * int(B[0])\na = first + second\nb = str(thrid) + 'i'\nreturn str(a) + '+' + b",
"def parse(s):\n array = s.split('+')\n ... | <|body_start_0|>
A = a.split('+')
B = b.split('+')
A[-1] = A[-1][0:-1]
B[-1] = B[-1][0:-1]
first = int(A[0]) * int(B[0])
second = -int(A[-1]) * int(B[-1])
thrid = int(A[0]) * int(B[-1]) + int(A[-1]) * int(B[0])
a = first + second
b = str(thrid) + '... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def complexNumberMultiply(self, a, b):
""":type a: str :type b: str :rtype: str 36ms"""
<|body_0|>
def complexNumberMultiply_1(self, a, b):
""":type a: str :type b: str :rtype: str 33ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
A = a... | stack_v2_sparse_classes_10k_train_007381 | 1,892 | no_license | [
{
"docstring": ":type a: str :type b: str :rtype: str 36ms",
"name": "complexNumberMultiply",
"signature": "def complexNumberMultiply(self, a, b)"
},
{
"docstring": ":type a: str :type b: str :rtype: str 33ms",
"name": "complexNumberMultiply_1",
"signature": "def complexNumberMultiply_1(... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def complexNumberMultiply(self, a, b): :type a: str :type b: str :rtype: str 36ms
- def complexNumberMultiply_1(self, a, b): :type a: str :type b: str :rtype: str 33ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def complexNumberMultiply(self, a, b): :type a: str :type b: str :rtype: str 36ms
- def complexNumberMultiply_1(self, a, b): :type a: str :type b: str :rtype: str 33ms
<|skeleto... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def complexNumberMultiply(self, a, b):
""":type a: str :type b: str :rtype: str 36ms"""
<|body_0|>
def complexNumberMultiply_1(self, a, b):
""":type a: str :type b: str :rtype: str 33ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def complexNumberMultiply(self, a, b):
""":type a: str :type b: str :rtype: str 36ms"""
A = a.split('+')
B = b.split('+')
A[-1] = A[-1][0:-1]
B[-1] = B[-1][0:-1]
first = int(A[0]) * int(B[0])
second = -int(A[-1]) * int(B[-1])
thrid = in... | the_stack_v2_python_sparse | ComplexNumberMultiplication_MID_537.py | 953250587/leetcode-python | train | 2 | |
01c70a3ce64a35861398a6fded9db64d12ec285e | [
"if arch_code is None:\n warnings.warn('arch_code not provided when not searching.')\nsuper().__init__(arch_code=arch_code, channel_mul=channel_mul, cell=cell, num_blocks=num_blocks, num_depths=num_depths, spatial_dims=spatial_dims, act_name=act_name, norm_name=norm_name, use_downsample=use_downsample, device=de... | <|body_start_0|>
if arch_code is None:
warnings.warn('arch_code not provided when not searching.')
super().__init__(arch_code=arch_code, channel_mul=channel_mul, cell=cell, num_blocks=num_blocks, num_depths=num_depths, spatial_dims=spatial_dims, act_name=act_name, norm_name=norm_name, use_do... | Instance of the final searched architecture. Only used in re-training/inference stage. | TopologyInstance | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopologyInstance:
"""Instance of the final searched architecture. Only used in re-training/inference stage."""
def __init__(self, arch_code=None, channel_mul: float=1.0, cell=Cell, num_blocks: int=6, num_depths: int=3, spatial_dims: int=3, act_name: tuple | str='RELU', norm_name: tuple | str... | stack_v2_sparse_classes_10k_train_007382 | 44,771 | permissive | [
{
"docstring": "Initialize DiNTS topology search space of neural architectures.",
"name": "__init__",
"signature": "def __init__(self, arch_code=None, channel_mul: float=1.0, cell=Cell, num_blocks: int=6, num_depths: int=3, spatial_dims: int=3, act_name: tuple | str='RELU', norm_name: tuple | str=('INST... | 2 | null | Implement the Python class `TopologyInstance` described below.
Class description:
Instance of the final searched architecture. Only used in re-training/inference stage.
Method signatures and docstrings:
- def __init__(self, arch_code=None, channel_mul: float=1.0, cell=Cell, num_blocks: int=6, num_depths: int=3, spati... | Implement the Python class `TopologyInstance` described below.
Class description:
Instance of the final searched architecture. Only used in re-training/inference stage.
Method signatures and docstrings:
- def __init__(self, arch_code=None, channel_mul: float=1.0, cell=Cell, num_blocks: int=6, num_depths: int=3, spati... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class TopologyInstance:
"""Instance of the final searched architecture. Only used in re-training/inference stage."""
def __init__(self, arch_code=None, channel_mul: float=1.0, cell=Cell, num_blocks: int=6, num_depths: int=3, spatial_dims: int=3, act_name: tuple | str='RELU', norm_name: tuple | str... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TopologyInstance:
"""Instance of the final searched architecture. Only used in re-training/inference stage."""
def __init__(self, arch_code=None, channel_mul: float=1.0, cell=Cell, num_blocks: int=6, num_depths: int=3, spatial_dims: int=3, act_name: tuple | str='RELU', norm_name: tuple | str=('INSTANCE',... | the_stack_v2_python_sparse | monai/networks/nets/dints.py | Project-MONAI/MONAI | train | 4,805 |
3c4b114a9c3eed4783d30677fe874c8ddcefa2dc | [
"super().__init__(in_features, out_features, bias=bias)\nweights = torch.full((out_features, in_features), sigma_init)\nself.sigma_weight = nn.Parameter(weights)\nepsilon_weight = torch.zeros(out_features, in_features)\nself.register_buffer('epsilon_weight', epsilon_weight)\nif bias:\n bias = torch.full((out_fea... | <|body_start_0|>
super().__init__(in_features, out_features, bias=bias)
weights = torch.full((out_features, in_features), sigma_init)
self.sigma_weight = nn.Parameter(weights)
epsilon_weight = torch.zeros(out_features, in_features)
self.register_buffer('epsilon_weight', epsilon_w... | Noisy Layer using Independent Gaussian Noise. based on https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On-Second-Edition/blob/master/ Chapter08/lib/dqn_extra.py#L19 | NoisyLinear | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoisyLinear:
"""Noisy Layer using Independent Gaussian Noise. based on https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On-Second-Edition/blob/master/ Chapter08/lib/dqn_extra.py#L19"""
def __init__(self, in_features: int, out_features: int, sigma_init: float=0.017, bias: ... | stack_v2_sparse_classes_10k_train_007383 | 15,112 | permissive | [
{
"docstring": "Args: in_features: number of inputs out_features: number of outputs sigma_init: initial fill value of noisy weights bias: flag to include bias to linear layer",
"name": "__init__",
"signature": "def __init__(self, in_features: int, out_features: int, sigma_init: float=0.017, bias: bool=T... | 3 | stack_v2_sparse_classes_30k_train_005951 | Implement the Python class `NoisyLinear` described below.
Class description:
Noisy Layer using Independent Gaussian Noise. based on https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On-Second-Edition/blob/master/ Chapter08/lib/dqn_extra.py#L19
Method signatures and docstrings:
- def __init__(self, ... | Implement the Python class `NoisyLinear` described below.
Class description:
Noisy Layer using Independent Gaussian Noise. based on https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On-Second-Edition/blob/master/ Chapter08/lib/dqn_extra.py#L19
Method signatures and docstrings:
- def __init__(self, ... | bdf311369b236c1e3d0336c7ed4ba249854f8606 | <|skeleton|>
class NoisyLinear:
"""Noisy Layer using Independent Gaussian Noise. based on https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On-Second-Edition/blob/master/ Chapter08/lib/dqn_extra.py#L19"""
def __init__(self, in_features: int, out_features: int, sigma_init: float=0.017, bias: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NoisyLinear:
"""Noisy Layer using Independent Gaussian Noise. based on https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On-Second-Edition/blob/master/ Chapter08/lib/dqn_extra.py#L19"""
def __init__(self, in_features: int, out_features: int, sigma_init: float=0.017, bias: bool=True) ->... | the_stack_v2_python_sparse | src/pl_bolts/models/rl/common/networks.py | Lightning-Universe/lightning-bolts | train | 76 |
d0565f83db422e3d3436761b64934a05366ebf17 | [
"value = '<div>'\nclase = 'actions'\ncontexto = ''\nperm_mod = PoseePermiso('modificar rol')\nperm_del = PoseePermiso('eliminar rol')\nurl_cont = '/rolesplantilla/'\ntipo = obj.tipo.lower()\nif tipo.find(u'proyecto') >= 0:\n contexto = 'proyecto'\nelif tipo.find(u'fase') >= 0:\n contexto = 'fase'\nelse:\n ... | <|body_start_0|>
value = '<div>'
clase = 'actions'
contexto = ''
perm_mod = PoseePermiso('modificar rol')
perm_del = PoseePermiso('eliminar rol')
url_cont = '/rolesplantilla/'
tipo = obj.tipo.lower()
if tipo.find(u'proyecto') >= 0:
contexto = '... | RolPlantillaTableFiller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RolPlantillaTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, **kw):
"""Se muestra la lista de rol si se tiene un permiso necesario. Caso contrario le muestra sus roles."""
... | stack_v2_sparse_classes_10k_train_007384 | 31,597 | no_license | [
{
"docstring": "Links de acciones para un registro dado",
"name": "__actions__",
"signature": "def __actions__(self, obj)"
},
{
"docstring": "Se muestra la lista de rol si se tiene un permiso necesario. Caso contrario le muestra sus roles.",
"name": "_do_get_provider_count_and_objs",
"si... | 2 | stack_v2_sparse_classes_30k_train_002811 | Implement the Python class `RolPlantillaTableFiller` described below.
Class description:
Implement the RolPlantillaTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, **kw): Se muestra la lista de rol si... | Implement the Python class `RolPlantillaTableFiller` described below.
Class description:
Implement the RolPlantillaTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, **kw): Se muestra la lista de rol si... | 997531e130d1951b483f4a6a67f2df7467cd9fd1 | <|skeleton|>
class RolPlantillaTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, **kw):
"""Se muestra la lista de rol si se tiene un permiso necesario. Caso contrario le muestra sus roles."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RolPlantillaTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
value = '<div>'
clase = 'actions'
contexto = ''
perm_mod = PoseePermiso('modificar rol')
perm_del = PoseePermiso('eliminar rol')
url_cont = '/rolesplantill... | the_stack_v2_python_sparse | lpm/controllers/rol.py | jorgeramirez/LPM | train | 1 | |
bf52cdb366bf2827c2168f9a33a80c59443be497 | [
"super().__init__()\nself._momentum = momentum\nself._eps = eps",
"self.running_mean = self.add_weight(name='running_mean', shape=input_shape[1:], dtype=tf.float32, initializer=tf.keras.initializers.Zeros(), trainable=False)\nself.running_var = self.add_weight(name='running_var', shape=input_shape[1:], dtype=tf.f... | <|body_start_0|>
super().__init__()
self._momentum = momentum
self._eps = eps
<|end_body_0|>
<|body_start_1|>
self.running_mean = self.add_weight(name='running_mean', shape=input_shape[1:], dtype=tf.float32, initializer=tf.keras.initializers.Zeros(), trainable=False)
self.runnin... | Revertible batch normalization. Attributes: _momentum: _eps: | BatchNorm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchNorm:
"""Revertible batch normalization. Attributes: _momentum: _eps:"""
def __init__(self, momentum=0.9, eps=1e-05):
"""Initializes the object. Args: momentum: eps:"""
<|body_0|>
def build(self, input_shape):
"""Adds variables to the layer. Args: input_shap... | stack_v2_sparse_classes_10k_train_007385 | 12,897 | no_license | [
{
"docstring": "Initializes the object. Args: momentum: eps:",
"name": "__init__",
"signature": "def __init__(self, momentum=0.9, eps=1e-05)"
},
{
"docstring": "Adds variables to the layer. Args: input_shape: Returns:",
"name": "build",
"signature": "def build(self, input_shape)"
},
... | 3 | stack_v2_sparse_classes_30k_train_001555 | Implement the Python class `BatchNorm` described below.
Class description:
Revertible batch normalization. Attributes: _momentum: _eps:
Method signatures and docstrings:
- def __init__(self, momentum=0.9, eps=1e-05): Initializes the object. Args: momentum: eps:
- def build(self, input_shape): Adds variables to the la... | Implement the Python class `BatchNorm` described below.
Class description:
Revertible batch normalization. Attributes: _momentum: _eps:
Method signatures and docstrings:
- def __init__(self, momentum=0.9, eps=1e-05): Initializes the object. Args: momentum: eps:
- def build(self, input_shape): Adds variables to the la... | 6d04861ef87ba2ba2a4182ad36f3b322fcf47cfa | <|skeleton|>
class BatchNorm:
"""Revertible batch normalization. Attributes: _momentum: _eps:"""
def __init__(self, momentum=0.9, eps=1e-05):
"""Initializes the object. Args: momentum: eps:"""
<|body_0|>
def build(self, input_shape):
"""Adds variables to the layer. Args: input_shap... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BatchNorm:
"""Revertible batch normalization. Attributes: _momentum: _eps:"""
def __init__(self, momentum=0.9, eps=1e-05):
"""Initializes the object. Args: momentum: eps:"""
super().__init__()
self._momentum = momentum
self._eps = eps
def build(self, input_shape):
... | the_stack_v2_python_sparse | flow.py | gaotianxiang/text-to-image-synthesis | train | 0 |
4461b2eba907b9afb6292ad0ef79f692485cc5db | [
"super(LstmEncoderModel, self).__init__()\nself.padding_idx = padding_idx\nself.embedding = nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx)\nself.dropout = nn.Dropout(p=dropout_rate)\nself.lstm_encoder = nn.LSTM(emb_dim, hidden_size, num_layers=n_layers, direction='bidirectional')",
"token_embed = self... | <|body_start_0|>
super(LstmEncoderModel, self).__init__()
self.padding_idx = padding_idx
self.embedding = nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx)
self.dropout = nn.Dropout(p=dropout_rate)
self.lstm_encoder = nn.LSTM(emb_dim, hidden_size, num_layers=n_layers, di... | LstmEncoderModel | LstmEncoderModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LstmEncoderModel:
"""LstmEncoderModel"""
def __init__(self, vocab_size, emb_dim=128, hidden_size=1024, n_layers=3, padding_idx=0, epsilon=1e-05, dropout_rate=0.1):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_10k_train_007386 | 17,522 | permissive | [
{
"docstring": "__init__",
"name": "__init__",
"signature": "def __init__(self, vocab_size, emb_dim=128, hidden_size=1024, n_layers=3, padding_idx=0, epsilon=1e-05, dropout_rate=0.1)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, input, pos)"
}
] | 2 | null | Implement the Python class `LstmEncoderModel` described below.
Class description:
LstmEncoderModel
Method signatures and docstrings:
- def __init__(self, vocab_size, emb_dim=128, hidden_size=1024, n_layers=3, padding_idx=0, epsilon=1e-05, dropout_rate=0.1): __init__
- def forward(self, input, pos): forward | Implement the Python class `LstmEncoderModel` described below.
Class description:
LstmEncoderModel
Method signatures and docstrings:
- def __init__(self, vocab_size, emb_dim=128, hidden_size=1024, n_layers=3, padding_idx=0, epsilon=1e-05, dropout_rate=0.1): __init__
- def forward(self, input, pos): forward
<|skeleto... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class LstmEncoderModel:
"""LstmEncoderModel"""
def __init__(self, vocab_size, emb_dim=128, hidden_size=1024, n_layers=3, padding_idx=0, epsilon=1e-05, dropout_rate=0.1):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LstmEncoderModel:
"""LstmEncoderModel"""
def __init__(self, vocab_size, emb_dim=128, hidden_size=1024, n_layers=3, padding_idx=0, epsilon=1e-05, dropout_rate=0.1):
"""__init__"""
super(LstmEncoderModel, self).__init__()
self.padding_idx = padding_idx
self.embedding = nn.Em... | the_stack_v2_python_sparse | pahelix/model_zoo/protein_sequence_model.py | PaddlePaddle/PaddleHelix | train | 771 |
d4c0422c97195fb79950977c565e2ad2c56b54d7 | [
"size = len(prices)\nif size <= 0:\n return 0\nmemo = {}\n\ndef dp(start, k):\n if k == 0:\n return 0\n if start >= size:\n return 0\n if (start, k) in memo:\n return memo[start, k]\n minIdx = start\n maxPro = 0\n for i in range(start + 1, size):\n if prices[i] < pri... | <|body_start_0|>
size = len(prices)
if size <= 0:
return 0
memo = {}
def dp(start, k):
if k == 0:
return 0
if start >= size:
return 0
if (start, k) in memo:
return memo[start, k]
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
"""暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化"""
<|body_0|>
def maxProfit_dp(self, k: int, prices: List[int]) -> int:
"""动态规划:三个操作状态buy, sell, rest。 通用状态转移方程:s[0,1]两种(有无股票)状态的两种情况,昨天的股票持有状态和今天的操作影响今天的收益情况 dp[i][k]... | stack_v2_sparse_classes_10k_train_007387 | 5,547 | permissive | [
{
"docstring": "暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化",
"name": "maxProfit",
"signature": "def maxProfit(self, k: int, prices: List[int]) -> int"
},
{
"docstring": "动态规划:三个操作状态buy, sell, rest。 通用状态转移方程:s[0,1]两种(有无股票)状态的两种情况,昨天的股票持有状态和今天的操作影响今天的收益情况 dp[i][k][0] = max(dp[i - 1][k][0], dp[i - 1][k][1] + ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, k: int, prices: List[int]) -> int: 暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化
- def maxProfit_dp(self, k: int, prices: List[int]) -> int: 动态规划:三个操作状态buy, sell, rest。 通用状... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, k: int, prices: List[int]) -> int: 暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化
- def maxProfit_dp(self, k: int, prices: List[int]) -> int: 动态规划:三个操作状态buy, sell, rest。 通用状... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
"""暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化"""
<|body_0|>
def maxProfit_dp(self, k: int, prices: List[int]) -> int:
"""动态规划:三个操作状态buy, sell, rest。 通用状态转移方程:s[0,1]两种(有无股票)状态的两种情况,昨天的股票持有状态和今天的操作影响今天的收益情况 dp[i][k]... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
"""暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化"""
size = len(prices)
if size <= 0:
return 0
memo = {}
def dp(start, k):
if k == 0:
return 0
if start >= size:
... | the_stack_v2_python_sparse | 123-best-time-to-buy-and-sell-stock-iii.py | yuenliou/leetcode | train | 0 | |
114a26f379a54a0ca74551d5906e6c0040134bfb | [
"super().__init__()\nself.in_chans = in_chans\nself.out_chans = out_chans\nself.chans = chans\nself.num_pool_layers = num_pool_layers\nself.drop_prob = drop_prob\nself.reduction = reduction\nself.down_sample_layers = nn.ModuleList([ConvBlock(in_chans, chans, drop_prob, attention=False, attention_type=attention_type... | <|body_start_0|>
super().__init__()
self.in_chans = in_chans
self.out_chans = out_chans
self.chans = chans
self.num_pool_layers = num_pool_layers
self.drop_prob = drop_prob
self.reduction = reduction
self.down_sample_layers = nn.ModuleList([ConvBlock(in_ch... | PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. Springer, 2015. | CSEUnetModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSEUnetModel:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241... | stack_v2_sparse_classes_10k_train_007388 | 10,589 | no_license | [
{
"docstring": "Args: in_chans (int): Number of channels in the input to the U-Net model. out_chans (int): Number of channels in the output to the U-Net model. chans (int): Number of output channels of the first convolution layer. num_pool_layers (int): Number of down-sampling and up-sampling layers. drop_prob ... | 2 | stack_v2_sparse_classes_30k_train_005800 | Implement the Python class `CSEUnetModel` described below.
Class description:
PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and comput... | Implement the Python class `CSEUnetModel` described below.
Class description:
PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and comput... | 219652c8a08c4f2f682acd9f95a4e1b3fd36b70b | <|skeleton|>
class CSEUnetModel:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CSEUnetModel:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. Springer, 2... | the_stack_v2_python_sparse | lemawarersn_unet_conv_redundancy_removed_relu/chattn.py | Bala93/Holistic-MRI-Reconstruction | train | 1 |
d6f86e784f52338a15b3247df1ea7444ac07595f | [
"self.card = card\nself.fromZoneType = fromZoneType\nself.toZoneType = toZoneType",
"fromZone = context.loadZone(self.fromZoneType)\ntoZone = context.loadZone(self.toZoneType)\ncards = [self.card]\nif self.card is None:\n cards = list(fromZone)\nfor card in cards:\n if card in fromZone:\n fromZone.re... | <|body_start_0|>
self.card = card
self.fromZoneType = fromZoneType
self.toZoneType = toZoneType
<|end_body_0|>
<|body_start_1|>
fromZone = context.loadZone(self.fromZoneType)
toZone = context.loadZone(self.toZoneType)
cards = [self.card]
if self.card is None:
... | Represents an effect to Put a Card on the Bottom | PutOnBottom | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PutOnBottom:
"""Represents an effect to Put a Card on the Bottom"""
def __init__(self, fromZoneType, toZoneType, card=None):
"""Initialize the Effect"""
<|body_0|>
def perform(self, context):
"""Perform the Game Effect"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_10k_train_007389 | 750 | no_license | [
{
"docstring": "Initialize the Effect",
"name": "__init__",
"signature": "def __init__(self, fromZoneType, toZoneType, card=None)"
},
{
"docstring": "Perform the Game Effect",
"name": "perform",
"signature": "def perform(self, context)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004776 | Implement the Python class `PutOnBottom` described below.
Class description:
Represents an effect to Put a Card on the Bottom
Method signatures and docstrings:
- def __init__(self, fromZoneType, toZoneType, card=None): Initialize the Effect
- def perform(self, context): Perform the Game Effect | Implement the Python class `PutOnBottom` described below.
Class description:
Represents an effect to Put a Card on the Bottom
Method signatures and docstrings:
- def __init__(self, fromZoneType, toZoneType, card=None): Initialize the Effect
- def perform(self, context): Perform the Game Effect
<|skeleton|>
class Put... | 0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258 | <|skeleton|>
class PutOnBottom:
"""Represents an effect to Put a Card on the Bottom"""
def __init__(self, fromZoneType, toZoneType, card=None):
"""Initialize the Effect"""
<|body_0|>
def perform(self, context):
"""Perform the Game Effect"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PutOnBottom:
"""Represents an effect to Put a Card on the Bottom"""
def __init__(self, fromZoneType, toZoneType, card=None):
"""Initialize the Effect"""
self.card = card
self.fromZoneType = fromZoneType
self.toZoneType = toZoneType
def perform(self, context):
... | the_stack_v2_python_sparse | src/Game/Effects/put_on_bottom.py | dfwarden/DeckBuilding | train | 0 |
d223e3078bd71735dbae8d125303765bb890b809 | [
"team = Team.get(id_=team_id)\nif not team:\n self.error(404, 'Team not found')\nform = forms.Team()\nform.name.data = team.name\nself.render('team.html', title=u'Team: {}'.format(team.name), form=form, edit=True, users=Users.get(), team=team, members=Users_team.get(team_id=team_id))",
"team = Team.get(id_=tea... | <|body_start_0|>
team = Team.get(id_=team_id)
if not team:
self.error(404, 'Team not found')
form = forms.Team()
form.name.data = team.name
self.render('team.html', title=u'Team: {}'.format(team.name), form=form, edit=True, users=Users.get(), team=team, members=Users_... | Handles the editing of a team. | Edit_handler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Edit_handler:
"""Handles the editing of a team."""
def get(self, team_id):
"""Renders the edit team form. :param team_id: int"""
<|body_0|>
def post(self, team_id):
"""Validates and updates the team. Redirects to the new team if successful. :param team_id: int"""... | stack_v2_sparse_classes_10k_train_007390 | 3,222 | no_license | [
{
"docstring": "Renders the edit team form. :param team_id: int",
"name": "get",
"signature": "def get(self, team_id)"
},
{
"docstring": "Validates and updates the team. Redirects to the new team if successful. :param team_id: int",
"name": "post",
"signature": "def post(self, team_id)"
... | 2 | stack_v2_sparse_classes_30k_train_000289 | Implement the Python class `Edit_handler` described below.
Class description:
Handles the editing of a team.
Method signatures and docstrings:
- def get(self, team_id): Renders the edit team form. :param team_id: int
- def post(self, team_id): Validates and updates the team. Redirects to the new team if successful. :... | Implement the Python class `Edit_handler` described below.
Class description:
Handles the editing of a team.
Method signatures and docstrings:
- def get(self, team_id): Renders the edit team form. :param team_id: int
- def post(self, team_id): Validates and updates the team. Redirects to the new team if successful. :... | 3f331c7169c90d1fac0d1922b011b56eebbd086a | <|skeleton|>
class Edit_handler:
"""Handles the editing of a team."""
def get(self, team_id):
"""Renders the edit team form. :param team_id: int"""
<|body_0|>
def post(self, team_id):
"""Validates and updates the team. Redirects to the new team if successful. :param team_id: int"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Edit_handler:
"""Handles the editing of a team."""
def get(self, team_id):
"""Renders the edit team form. :param team_id: int"""
team = Team.get(id_=team_id)
if not team:
self.error(404, 'Team not found')
form = forms.Team()
form.name.data = team.name
... | the_stack_v2_python_sparse | src/tlog/web/handlers/team.py | thomaserlang/TLog | train | 2 |
4814742139003f0bdc3ecb2c7be564754abf6ffe | [
"self._type = type\nself._project = project\nself._location = location\nself._creds, _ = google.auth.default()\nself._gcp_resources = gcp_resources\nself._session = self._get_session()",
"retry = Retry(total=_CONNECTION_ERROR_RETRY_LIMIT, status_forcelist=[429, 503], backoff_factor=_CONNECTION_RETRY_BACKOFF_FACTO... | <|body_start_0|>
self._type = type
self._project = project
self._location = location
self._creds, _ = google.auth.default()
self._gcp_resources = gcp_resources
self._session = self._get_session()
<|end_body_0|>
<|body_start_1|>
retry = Retry(total=_CONNECTION_ERR... | Common module for creating Dataproc Flex Template jobs. | DataflowFlexTemplateRemoteRunner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataflowFlexTemplateRemoteRunner:
"""Common module for creating Dataproc Flex Template jobs."""
def __init__(self, type: str, project: str, location: str, gcp_resources: str):
"""Initializes a DataflowFlexTemplateRemoteRunner object."""
<|body_0|>
def _get_session(self) ... | stack_v2_sparse_classes_10k_train_007391 | 9,632 | permissive | [
{
"docstring": "Initializes a DataflowFlexTemplateRemoteRunner object.",
"name": "__init__",
"signature": "def __init__(self, type: str, project: str, location: str, gcp_resources: str)"
},
{
"docstring": "Gets a http session.",
"name": "_get_session",
"signature": "def _get_session(self... | 5 | null | Implement the Python class `DataflowFlexTemplateRemoteRunner` described below.
Class description:
Common module for creating Dataproc Flex Template jobs.
Method signatures and docstrings:
- def __init__(self, type: str, project: str, location: str, gcp_resources: str): Initializes a DataflowFlexTemplateRemoteRunner o... | Implement the Python class `DataflowFlexTemplateRemoteRunner` described below.
Class description:
Common module for creating Dataproc Flex Template jobs.
Method signatures and docstrings:
- def __init__(self, type: str, project: str, location: str, gcp_resources: str): Initializes a DataflowFlexTemplateRemoteRunner o... | 3fb199658f68e7debf4906d9ce32a9a307e39243 | <|skeleton|>
class DataflowFlexTemplateRemoteRunner:
"""Common module for creating Dataproc Flex Template jobs."""
def __init__(self, type: str, project: str, location: str, gcp_resources: str):
"""Initializes a DataflowFlexTemplateRemoteRunner object."""
<|body_0|>
def _get_session(self) ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DataflowFlexTemplateRemoteRunner:
"""Common module for creating Dataproc Flex Template jobs."""
def __init__(self, type: str, project: str, location: str, gcp_resources: str):
"""Initializes a DataflowFlexTemplateRemoteRunner object."""
self._type = type
self._project = project
... | the_stack_v2_python_sparse | components/google-cloud/google_cloud_pipeline_components/container/preview/dataflow/flex_template/remote_runner.py | kubeflow/pipelines | train | 3,434 |
503c72178d8d2931ae0e3700e7ee3a0b5478a821 | [
"result = {'result': 'NG'}\ndata = request.get_json(force=True)\nif data:\n succsee, message = CtrlQuotations().update_quotation_status(data)\n if succsee:\n result = {'result': 'OK', 'content': message}\n else:\n result['error'] = message\nelse:\n result['error'] = '请不要传空数据'\nreturn resul... | <|body_start_0|>
result = {'result': 'NG'}
data = request.get_json(force=True)
if data:
succsee, message = CtrlQuotations().update_quotation_status(data)
if succsee:
result = {'result': 'OK', 'content': message}
else:
result['er... | ApiQuotationStatue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiQuotationStatue:
def post(self):
"""修改状态 :return:"""
<|body_0|>
def get(self, quotation_id):
"""获取状态 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = {'result': 'NG'}
data = request.get_json(force=True)
if data:
... | stack_v2_sparse_classes_10k_train_007392 | 10,406 | no_license | [
{
"docstring": "修改状态 :return:",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "获取状态 :return:",
"name": "get",
"signature": "def get(self, quotation_id)"
}
] | 2 | null | Implement the Python class `ApiQuotationStatue` described below.
Class description:
Implement the ApiQuotationStatue class.
Method signatures and docstrings:
- def post(self): 修改状态 :return:
- def get(self, quotation_id): 获取状态 :return: | Implement the Python class `ApiQuotationStatue` described below.
Class description:
Implement the ApiQuotationStatue class.
Method signatures and docstrings:
- def post(self): 修改状态 :return:
- def get(self, quotation_id): 获取状态 :return:
<|skeleton|>
class ApiQuotationStatue:
def post(self):
"""修改状态 :retur... | 64b31e7bdfcb8a4c95f0a8a607f0bcff576cec11 | <|skeleton|>
class ApiQuotationStatue:
def post(self):
"""修改状态 :return:"""
<|body_0|>
def get(self, quotation_id):
"""获取状态 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ApiQuotationStatue:
def post(self):
"""修改状态 :return:"""
result = {'result': 'NG'}
data = request.get_json(force=True)
if data:
succsee, message = CtrlQuotations().update_quotation_status(data)
if succsee:
result = {'result': 'OK', 'conten... | the_stack_v2_python_sparse | koala/koala_server/app/api_1_0/api_quotations.py | lsn1183/web_project | train | 0 | |
c62aec4f31195ec2a94f985c8b7a65d59111b571 | [
"anomalies = cls._FetchUntriagedAnomalies()\nrecovered_anomalies = _FindAndUpdateRecoveredAnomalies(anomalies)\nmap(_AddLogForRecoveredAnomaly, recovered_anomalies)",
"anomalies = []\nfutures = []\nsheriff_keys = sheriff.Sheriff.query().fetch(keys_only=True)\nfor key in sheriff_keys:\n query = anomaly.Anomaly.... | <|body_start_0|>
anomalies = cls._FetchUntriagedAnomalies()
recovered_anomalies = _FindAndUpdateRecoveredAnomalies(anomalies)
map(_AddLogForRecoveredAnomaly, recovered_anomalies)
<|end_body_0|>
<|body_start_1|>
anomalies = []
futures = []
sheriff_keys = sheriff.Sheriff.q... | Class for triaging anomalies. | TriageAnomalies | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriageAnomalies:
"""Class for triaging anomalies."""
def Process(cls):
"""Processes anomalies."""
<|body_0|>
def _FetchUntriagedAnomalies(cls):
"""Fetches recent untriaged anomalies asynchronously from all sheriffs."""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_10k_train_007393 | 9,110 | permissive | [
{
"docstring": "Processes anomalies.",
"name": "Process",
"signature": "def Process(cls)"
},
{
"docstring": "Fetches recent untriaged anomalies asynchronously from all sheriffs.",
"name": "_FetchUntriagedAnomalies",
"signature": "def _FetchUntriagedAnomalies(cls)"
}
] | 2 | null | Implement the Python class `TriageAnomalies` described below.
Class description:
Class for triaging anomalies.
Method signatures and docstrings:
- def Process(cls): Processes anomalies.
- def _FetchUntriagedAnomalies(cls): Fetches recent untriaged anomalies asynchronously from all sheriffs. | Implement the Python class `TriageAnomalies` described below.
Class description:
Class for triaging anomalies.
Method signatures and docstrings:
- def Process(cls): Processes anomalies.
- def _FetchUntriagedAnomalies(cls): Fetches recent untriaged anomalies asynchronously from all sheriffs.
<|skeleton|>
class Triage... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class TriageAnomalies:
"""Class for triaging anomalies."""
def Process(cls):
"""Processes anomalies."""
<|body_0|>
def _FetchUntriagedAnomalies(cls):
"""Fetches recent untriaged anomalies asynchronously from all sheriffs."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TriageAnomalies:
"""Class for triaging anomalies."""
def Process(cls):
"""Processes anomalies."""
anomalies = cls._FetchUntriagedAnomalies()
recovered_anomalies = _FindAndUpdateRecoveredAnomalies(anomalies)
map(_AddLogForRecoveredAnomaly, recovered_anomalies)
def _Fet... | the_stack_v2_python_sparse | third_party/catapult/dashboard/dashboard/auto_triage.py | metux/chromium-suckless | train | 5 |
8c56b367b61a20a8d53d5602010377710436d5a1 | [
"super(FixupConv2D, self).__init__()\nif initialW is None:\n initialW = I.Zero()\nwith self.init_scope():\n self.conv = L.Convolution2D(in_channels, out_channels, ksize=ksize, stride=stride, pad=pad, nobias=nobias, initialW=initialW, initial_bias=initial_bias, dilate=dilate, groups=groups)\n self.bias_in =... | <|body_start_0|>
super(FixupConv2D, self).__init__()
if initialW is None:
initialW = I.Zero()
with self.init_scope():
self.conv = L.Convolution2D(in_channels, out_channels, ksize=ksize, stride=stride, pad=pad, nobias=nobias, initialW=initialW, initial_bias=initial_bias, d... | Wraps Convolution2D by Fixup. Fixup works by adding a scalar bias to the input of convolution, optionally multiplying its output by another scalar multiplier, and then adding another bias scalar term. The final result might be passed through an activation func. | FixupConv2D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixupConv2D:
"""Wraps Convolution2D by Fixup. Fixup works by adding a scalar bias to the input of convolution, optionally multiplying its output by another scalar multiplier, and then adding another bias scalar term. The final result might be passed through an activation func."""
def __init_... | stack_v2_sparse_classes_10k_train_007394 | 2,394 | permissive | [
{
"docstring": "CTOR.",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels, ksize=None, stride=1, pad=0, dilate=1, groups=1, nobias=True, initialW=None, initial_bias=None, use_scale=True, activ=F.relu)"
},
{
"docstring": "forward",
"name": "forward",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_003428 | Implement the Python class `FixupConv2D` described below.
Class description:
Wraps Convolution2D by Fixup. Fixup works by adding a scalar bias to the input of convolution, optionally multiplying its output by another scalar multiplier, and then adding another bias scalar term. The final result might be passed through ... | Implement the Python class `FixupConv2D` described below.
Class description:
Wraps Convolution2D by Fixup. Fixup works by adding a scalar bias to the input of convolution, optionally multiplying its output by another scalar multiplier, and then adding another bias scalar term. The final result might be passed through ... | 0ca435433b9953e33656173c4d60ebd61c5c5e87 | <|skeleton|>
class FixupConv2D:
"""Wraps Convolution2D by Fixup. Fixup works by adding a scalar bias to the input of convolution, optionally multiplying its output by another scalar multiplier, and then adding another bias scalar term. The final result might be passed through an activation func."""
def __init_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FixupConv2D:
"""Wraps Convolution2D by Fixup. Fixup works by adding a scalar bias to the input of convolution, optionally multiplying its output by another scalar multiplier, and then adding another bias scalar term. The final result might be passed through an activation func."""
def __init__(self, in_ch... | the_stack_v2_python_sparse | chainerlp/links/connection/fixup_conv2d.py | MetaVai/gradient-scaling | train | 0 |
cf9e6bef68f464922d94f22edb15f3ddd4077905 | [
"try:\n return super().make_context(info_name, args, parent, **extra)\nexcept Exception as e:\n telemetry_client = parent.obj['TELEMETRY_CLIENT']\n if isinstance(e, click.exceptions.Exit) and e.exit_code == 0:\n telemetry_client.send_command_telemetry(parent, extra_info_name=info_name, is_help=True)... | <|body_start_0|>
try:
return super().make_context(info_name, args, parent, **extra)
except Exception as e:
telemetry_client = parent.obj['TELEMETRY_CLIENT']
if isinstance(e, click.exceptions.Exit) and e.exit_code == 0:
telemetry_client.send_command_tel... | OctaviaCommand | [
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"Elastic-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OctaviaCommand:
def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context:
"""Wrap parent make context with telemetry sending in case of failure. Args: info_name (t.Optional[str]): The info name for this... | stack_v2_sparse_classes_10k_train_007395 | 2,019 | permissive | [
{
"docstring": "Wrap parent make context with telemetry sending in case of failure. Args: info_name (t.Optional[str]): The info name for this invocation. args (t.List[str]): The arguments to parse as list of strings. parent (t.Optional[click.Context], optional): The parent context if available.. Defaults to Non... | 2 | stack_v2_sparse_classes_30k_train_002125 | Implement the Python class `OctaviaCommand` described below.
Class description:
Implement the OctaviaCommand class.
Method signatures and docstrings:
- def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context: Wrap parent make conte... | Implement the Python class `OctaviaCommand` described below.
Class description:
Implement the OctaviaCommand class.
Method signatures and docstrings:
- def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context: Wrap parent make conte... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class OctaviaCommand:
def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context:
"""Wrap parent make context with telemetry sending in case of failure. Args: info_name (t.Optional[str]): The info name for this... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OctaviaCommand:
def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context:
"""Wrap parent make context with telemetry sending in case of failure. Args: info_name (t.Optional[str]): The info name for this invocation. a... | the_stack_v2_python_sparse | dts/airbyte/octavia-cli/octavia_cli/base_commands.py | alldatacenter/alldata | train | 774 | |
23e4b14a5f6f34cc9d5b2970f6740700684a6ec2 | [
"if 'model' in blend_coord and model_id_attr is None:\n raise ValueError('model_id_attr required to blend over {}'.format(blend_coord))\nif 'model' not in blend_coord and (model_id_attr is not None and record_run_attr is None):\n warnings.warn('model_id_attr not required for blending over {} - will be ignored... | <|body_start_0|>
if 'model' in blend_coord and model_id_attr is None:
raise ValueError('model_id_attr required to blend over {}'.format(blend_coord))
if 'model' not in blend_coord and (model_id_attr is not None and record_run_attr is None):
warnings.warn('model_id_attr not requir... | Prepares cubes for cycle and grid blending | MergeCubesForWeightedBlending | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeCubesForWeightedBlending:
"""Prepares cubes for cycle and grid blending"""
def __init__(self, blend_coord: str, weighting_coord: Optional[str]=None, model_id_attr: Optional[str]=None, record_run_attr: Optional[str]=None) -> None:
"""Initialise the class Args: blend_coord: Name o... | stack_v2_sparse_classes_10k_train_007396 | 30,444 | permissive | [
{
"docstring": "Initialise the class Args: blend_coord: Name of coordinate over which blending will be performed. For multi-model blending this is flexible to any string containing \"model\". For all other coordinates this is prescriptive: cube.coord(blend_coord) must return an iris.coords.Coord instance for al... | 5 | null | Implement the Python class `MergeCubesForWeightedBlending` described below.
Class description:
Prepares cubes for cycle and grid blending
Method signatures and docstrings:
- def __init__(self, blend_coord: str, weighting_coord: Optional[str]=None, model_id_attr: Optional[str]=None, record_run_attr: Optional[str]=None... | Implement the Python class `MergeCubesForWeightedBlending` described below.
Class description:
Prepares cubes for cycle and grid blending
Method signatures and docstrings:
- def __init__(self, blend_coord: str, weighting_coord: Optional[str]=None, model_id_attr: Optional[str]=None, record_run_attr: Optional[str]=None... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class MergeCubesForWeightedBlending:
"""Prepares cubes for cycle and grid blending"""
def __init__(self, blend_coord: str, weighting_coord: Optional[str]=None, model_id_attr: Optional[str]=None, record_run_attr: Optional[str]=None) -> None:
"""Initialise the class Args: blend_coord: Name o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MergeCubesForWeightedBlending:
"""Prepares cubes for cycle and grid blending"""
def __init__(self, blend_coord: str, weighting_coord: Optional[str]=None, model_id_attr: Optional[str]=None, record_run_attr: Optional[str]=None) -> None:
"""Initialise the class Args: blend_coord: Name of coordinate ... | the_stack_v2_python_sparse | improver/blending/weighted_blend.py | metoppv/improver | train | 101 |
041bde86e8c4db19fffd4293b9e8132d958d7768 | [
"try:\n code, resp = get_order_detail(request, sn)\n if code == RespCode.Succeed.value:\n return Response(resp)\n else:\n return error_resp(code, resp)\nexcept Exception as e:\n print(e)\n return error_resp(RespCode.Exception.value, _('Server exception, please try again'))",
"try:\n ... | <|body_start_0|>
try:
code, resp = get_order_detail(request, sn)
if code == RespCode.Succeed.value:
return Response(resp)
else:
return error_resp(code, resp)
except Exception as e:
print(e)
return error_resp(Resp... | OrderDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderDetailView:
def get(self, request, sn):
"""订单支付页面"""
<|body_0|>
def delete(self, request, sn):
"""订单删除(逻辑删除)"""
<|body_1|>
def put(self, request, sn):
"""取消订单"""
<|body_2|>
def post(self, request, sn):
"""立即支付"""
... | stack_v2_sparse_classes_10k_train_007397 | 4,027 | no_license | [
{
"docstring": "订单支付页面",
"name": "get",
"signature": "def get(self, request, sn)"
},
{
"docstring": "订单删除(逻辑删除)",
"name": "delete",
"signature": "def delete(self, request, sn)"
},
{
"docstring": "取消订单",
"name": "put",
"signature": "def put(self, request, sn)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_004074 | Implement the Python class `OrderDetailView` described below.
Class description:
Implement the OrderDetailView class.
Method signatures and docstrings:
- def get(self, request, sn): 订单支付页面
- def delete(self, request, sn): 订单删除(逻辑删除)
- def put(self, request, sn): 取消订单
- def post(self, request, sn): 立即支付 | Implement the Python class `OrderDetailView` described below.
Class description:
Implement the OrderDetailView class.
Method signatures and docstrings:
- def get(self, request, sn): 订单支付页面
- def delete(self, request, sn): 订单删除(逻辑删除)
- def put(self, request, sn): 取消订单
- def post(self, request, sn): 立即支付
<|skeleton|>
... | 14c94075094e1657b90b0bb3f94544d008255f45 | <|skeleton|>
class OrderDetailView:
def get(self, request, sn):
"""订单支付页面"""
<|body_0|>
def delete(self, request, sn):
"""订单删除(逻辑删除)"""
<|body_1|>
def put(self, request, sn):
"""取消订单"""
<|body_2|>
def post(self, request, sn):
"""立即支付"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OrderDetailView:
def get(self, request, sn):
"""订单支付页面"""
try:
code, resp = get_order_detail(request, sn)
if code == RespCode.Succeed.value:
return Response(resp)
else:
return error_resp(code, resp)
except Exception as... | the_stack_v2_python_sparse | order/views.py | Tsurol/trip-server | train | 1 | |
72986cb210f4bd98b0ccbc5360309eef8bb27b8d | [
"self._num_hard_examples = num_hard_examples\nself._iou_threshold = iou_threshold\nself._loss_type = loss_type\nself._cls_loss_weight = cls_loss_weight\nself._loc_loss_weight = loc_loss_weight\nself._max_negatives_per_positive = float(max_negatives_per_positive) if max_negatives_per_positive is not None else max_ne... | <|body_start_0|>
self._num_hard_examples = num_hard_examples
self._iou_threshold = iou_threshold
self._loss_type = loss_type
self._cls_loss_weight = cls_loss_weight
self._loc_loss_weight = loc_loss_weight
self._max_negatives_per_positive = float(max_negatives_per_positive... | Hard example mining for regions in a list of images. | HardExampleMiner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HardExampleMiner:
"""Hard example mining for regions in a list of images."""
def __init__(self, num_hard_examples=64, iou_threshold=0.7, loss_type='both', cls_loss_weight=0.05, loc_loss_weight=0.06, max_negatives_per_positive=None, min_negatives_per_image=0):
"""Constructor. Args: nu... | stack_v2_sparse_classes_10k_train_007398 | 14,833 | no_license | [
{
"docstring": "Constructor. Args: num_hard_examples: int scalar, max num of hard examples to be selected per image used in NMS. iou_threshold: float scalar, min IOU for a box to be considered as being overlapped with a previously selected box during NMS. loss_type: string scalar 'cls', 'loc', 'both', hard-mini... | 3 | stack_v2_sparse_classes_30k_train_005369 | Implement the Python class `HardExampleMiner` described below.
Class description:
Hard example mining for regions in a list of images.
Method signatures and docstrings:
- def __init__(self, num_hard_examples=64, iou_threshold=0.7, loss_type='both', cls_loss_weight=0.05, loc_loss_weight=0.06, max_negatives_per_positiv... | Implement the Python class `HardExampleMiner` described below.
Class description:
Hard example mining for regions in a list of images.
Method signatures and docstrings:
- def __init__(self, num_hard_examples=64, iou_threshold=0.7, loss_type='both', cls_loss_weight=0.05, loc_loss_weight=0.06, max_negatives_per_positiv... | 5a53e02c690632bcf140d1b17327959609aab395 | <|skeleton|>
class HardExampleMiner:
"""Hard example mining for regions in a list of images."""
def __init__(self, num_hard_examples=64, iou_threshold=0.7, loss_type='both', cls_loss_weight=0.05, loc_loss_weight=0.06, max_negatives_per_positive=None, min_negatives_per_image=0):
"""Constructor. Args: nu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HardExampleMiner:
"""Hard example mining for regions in a list of images."""
def __init__(self, num_hard_examples=64, iou_threshold=0.7, loss_type='both', cls_loss_weight=0.05, loc_loss_weight=0.06, max_negatives_per_positive=None, min_negatives_per_image=0):
"""Constructor. Args: num_hard_exampl... | the_stack_v2_python_sparse | core/losses.py | chao-ji/tf-detection | train | 2 |
c2db422cc7a9bb4ec61ea1f37c28c02e9da345ff | [
"try:\n with datastore_services.get_ndb_context():\n question_summary = question_services.get_question_summary_from_model(question_summary_model)\n question_summary.version = question_version\n question_summary.validate()\nexcept Exception as e:\n logging.exception(e)\n return result.Err((ques... | <|body_start_0|>
try:
with datastore_services.get_ndb_context():
question_summary = question_services.get_question_summary_from_model(question_summary_model)
question_summary.version = question_version
question_summary.validate()
except Exception as e:... | Job that adds a version field to QuestionSummary models. | PopulateQuestionSummaryVersionOneOffJob | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PopulateQuestionSummaryVersionOneOffJob:
"""Job that adds a version field to QuestionSummary models."""
def _update_and_validate_summary_model(question_version: int, question_summary_model: question_models.QuestionSummaryModel) -> result.Result[Tuple[str, question_models.QuestionSummaryModel... | stack_v2_sparse_classes_10k_train_007399 | 12,101 | permissive | [
{
"docstring": "Transform question summary model into question summary object, add a version field and return the populated summary model. Args: question_version: int. The version number in the corresponding question domain object. question_summary_model: QuestionSummaryModel. The question summary model to migr... | 2 | stack_v2_sparse_classes_30k_train_000208 | Implement the Python class `PopulateQuestionSummaryVersionOneOffJob` described below.
Class description:
Job that adds a version field to QuestionSummary models.
Method signatures and docstrings:
- def _update_and_validate_summary_model(question_version: int, question_summary_model: question_models.QuestionSummaryMod... | Implement the Python class `PopulateQuestionSummaryVersionOneOffJob` described below.
Class description:
Job that adds a version field to QuestionSummary models.
Method signatures and docstrings:
- def _update_and_validate_summary_model(question_version: int, question_summary_model: question_models.QuestionSummaryMod... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class PopulateQuestionSummaryVersionOneOffJob:
"""Job that adds a version field to QuestionSummary models."""
def _update_and_validate_summary_model(question_version: int, question_summary_model: question_models.QuestionSummaryModel) -> result.Result[Tuple[str, question_models.QuestionSummaryModel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PopulateQuestionSummaryVersionOneOffJob:
"""Job that adds a version field to QuestionSummary models."""
def _update_and_validate_summary_model(question_version: int, question_summary_model: question_models.QuestionSummaryModel) -> result.Result[Tuple[str, question_models.QuestionSummaryModel], Tuple[str,... | the_stack_v2_python_sparse | core/jobs/batch_jobs/question_migration_jobs.py | oppia/oppia | train | 6,172 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.