blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b8f7b6633430512ff60337ce3a4275c3d76f5ddd | [
"nums.sort()\nprint(nums)\nprint(nums[len(nums) - k])\nreturn nums[len(nums) - k]",
"pivot = nums[0]\nleft = [l for l in nums if l < pivot]\nequal = [e for e in nums if e == pivot]\nright = [r for r in nums if r > pivot]\nif k <= len(right):\n return self.findKthLargest2(right, k)\nelif k - len(right) <= len(e... | <|body_start_0|>
nums.sort()
print(nums)
print(nums[len(nums) - k])
return nums[len(nums) - k]
<|end_body_0|>
<|body_start_1|>
pivot = nums[0]
left = [l for l in nums if l < pivot]
equal = [e for e in nums if e == pivot]
right = [r for r in nums if r > pi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findKthLargest2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums.s... | stack_v2_sparse_classes_36k_train_005700 | 780 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findKthLargest",
"signature": "def findKthLargest(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findKthLargest2",
"signature": "def findKthLargest2(self, nums, k)"
}... | 2 | stack_v2_sparse_classes_30k_train_004958 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findKthLargest2(self, nums, k): :type nums: List[int] :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findKthLargest2(self, nums, k): :type nums: List[int] :type k: int :rtype: int
<|skeleton... | eb5f6488c875c107743f84a44cbbf55ff7ed3296 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findKthLargest2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
nums.sort()
print(nums)
print(nums[len(nums) - k])
return nums[len(nums) - k]
def findKthLargest2(self, nums, k):
""":type nums: List[int] :type k: int :rtype:... | the_stack_v2_python_sparse | 215__Kth Largest Element.py | chengcheng8632/lovely-nuts | train | 0 | |
bf7c13bd1efc3652598178d879a9cc30b5957b73 | [
"lyrName = lyrComboBox.currentText()\nlyr = QgsMapLayerRegistry.instance().mapLayersByName(lyrName)[0]\nlyrFeats = lyr.getFeatures()\nfeatureArray = self.createFeatureArray(lyrFeats)\nshape = featureArray.shape\nrows = shape[0]\ncols = shape[1]\nmodel = QStandardItemModel(rows, cols)\nself.setFieldNames(model, lyr)... | <|body_start_0|>
lyrName = lyrComboBox.currentText()
lyr = QgsMapLayerRegistry.instance().mapLayersByName(lyrName)[0]
lyrFeats = lyr.getFeatures()
featureArray = self.createFeatureArray(lyrFeats)
shape = featureArray.shape
rows = shape[0]
cols = shape[1]
m... | Class that creates attribute tables for table views | AttributeTable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeTable:
"""Class that creates attribute tables for table views"""
def attributeTable(self, lyrComboBox, tableView, sorting=False):
"""populate the attribute table with data based on the layer chosen in the lyrcomboBox"""
<|body_0|>
def createFeatureArray(self, ly... | stack_v2_sparse_classes_36k_train_005701 | 3,343 | no_license | [
{
"docstring": "populate the attribute table with data based on the layer chosen in the lyrcomboBox",
"name": "attributeTable",
"signature": "def attributeTable(self, lyrComboBox, tableView, sorting=False)"
},
{
"docstring": "puts all of the attributes of the layer features into a 2d array, read... | 3 | stack_v2_sparse_classes_30k_train_011713 | Implement the Python class `AttributeTable` described below.
Class description:
Class that creates attribute tables for table views
Method signatures and docstrings:
- def attributeTable(self, lyrComboBox, tableView, sorting=False): populate the attribute table with data based on the layer chosen in the lyrcomboBox
-... | Implement the Python class `AttributeTable` described below.
Class description:
Class that creates attribute tables for table views
Method signatures and docstrings:
- def attributeTable(self, lyrComboBox, tableView, sorting=False): populate the attribute table with data based on the layer chosen in the lyrcomboBox
-... | ba1fd3a139580e00eca4aa87ad8e49f46718d58a | <|skeleton|>
class AttributeTable:
"""Class that creates attribute tables for table views"""
def attributeTable(self, lyrComboBox, tableView, sorting=False):
"""populate the attribute table with data based on the layer chosen in the lyrcomboBox"""
<|body_0|>
def createFeatureArray(self, ly... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttributeTable:
"""Class that creates attribute tables for table views"""
def attributeTable(self, lyrComboBox, tableView, sorting=False):
"""populate the attribute table with data based on the layer chosen in the lyrcomboBox"""
lyrName = lyrComboBox.currentText()
lyr = QgsMapLaye... | the_stack_v2_python_sparse | attributeTable.py | Charlotteg/QGISforSchools | train | 1 |
ffe3893e42bfeaeb09ac05a53c172d701d8ef3cc | [
"def decorated_view(request: HttpRequest, course_id: int, post_id: int, *args, **kwargs):\n post = Post.objects.get(id=post_id)\n user = request.user\n is_student = user in post.course.students.all()\n is_instructor = user in post.course.instructors.all()\n if request.method in ['GET', 'PATCH'] and (... | <|body_start_0|>
def decorated_view(request: HttpRequest, course_id: int, post_id: int, *args, **kwargs):
post = Post.objects.get(id=post_id)
user = request.user
is_student = user in post.course.students.all()
is_instructor = user in post.course.instructors.all()
... | View class for a given post. | PostView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostView:
"""View class for a given post."""
def permissioned(view):
"""View decorator that checks if a user has permission to access/edit the post specified in the url."""
<|body_0|>
def get(self, request: HttpRequest, course_id: int, post_id: int) -> HttpResponse:
... | stack_v2_sparse_classes_36k_train_005702 | 5,470 | permissive | [
{
"docstring": "View decorator that checks if a user has permission to access/edit the post specified in the url.",
"name": "permissioned",
"signature": "def permissioned(view)"
},
{
"docstring": "Return post data.",
"name": "get",
"signature": "def get(self, request: HttpRequest, course... | 5 | stack_v2_sparse_classes_30k_train_009834 | Implement the Python class `PostView` described below.
Class description:
View class for a given post.
Method signatures and docstrings:
- def permissioned(view): View decorator that checks if a user has permission to access/edit the post specified in the url.
- def get(self, request: HttpRequest, course_id: int, pos... | Implement the Python class `PostView` described below.
Class description:
View class for a given post.
Method signatures and docstrings:
- def permissioned(view): View decorator that checks if a user has permission to access/edit the post specified in the url.
- def get(self, request: HttpRequest, course_id: int, pos... | 6b688c28c79e56df5cc667d704db72ba30141f7a | <|skeleton|>
class PostView:
"""View class for a given post."""
def permissioned(view):
"""View decorator that checks if a user has permission to access/edit the post specified in the url."""
<|body_0|>
def get(self, request: HttpRequest, course_id: int, post_id: int) -> HttpResponse:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostView:
"""View class for a given post."""
def permissioned(view):
"""View decorator that checks if a user has permission to access/edit the post specified in the url."""
def decorated_view(request: HttpRequest, course_id: int, post_id: int, *args, **kwargs):
post = Post.obj... | the_stack_v2_python_sparse | backend/api/views/PostView.py | CaoRuiming/CS1320-Final-Project | train | 0 |
1456f0a454731e47776e98d47bcd2c7403dbd3a0 | [
"protos = []\nif not isinstance(x, Iterable):\n protos.append(x.proto_with_data)\nelse:\n protos = [r.proto_with_data for r in x]\nreturn jina_pb2.DataRequestListProto(requests=protos).SerializeToString()",
"rlp = jina_pb2.DataRequestListProto()\nrlp.ParseFromString(x)\nreturn [DataRequest.from_proto(reques... | <|body_start_0|>
protos = []
if not isinstance(x, Iterable):
protos.append(x.proto_with_data)
else:
protos = [r.proto_with_data for r in x]
return jina_pb2.DataRequestListProto(requests=protos).SerializeToString()
<|end_body_0|>
<|body_start_1|>
rlp = jin... | This class is a drop-in replacement for gRPC default serializer. It replaces default serializer to make sure the message sending interface is convenient. It can handle sending single messages or a list of messages. It also returns a list of messages. Effectively this is hiding MessageListProto from the consumer | DataRequestListProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataRequestListProto:
"""This class is a drop-in replacement for gRPC default serializer. It replaces default serializer to make sure the message sending interface is convenient. It can handle sending single messages or a list of messages. It also returns a list of messages. Effectively this is h... | stack_v2_sparse_classes_36k_train_005703 | 7,917 | permissive | [
{
"docstring": "# noqa: DAR101 # noqa: DAR102 # noqa: DAR201",
"name": "SerializeToString",
"signature": "def SerializeToString(x: 'Union[List[DataRequest], DataRequest]')"
},
{
"docstring": "# noqa: DAR101 # noqa: DAR102 # noqa: DAR201",
"name": "FromString",
"signature": "def FromStrin... | 2 | null | Implement the Python class `DataRequestListProto` described below.
Class description:
This class is a drop-in replacement for gRPC default serializer. It replaces default serializer to make sure the message sending interface is convenient. It can handle sending single messages or a list of messages. It also returns a ... | Implement the Python class `DataRequestListProto` described below.
Class description:
This class is a drop-in replacement for gRPC default serializer. It replaces default serializer to make sure the message sending interface is convenient. It can handle sending single messages or a list of messages. It also returns a ... | 23c7b8c78fc4ad67d16d83fc0c9f0eae9e935e71 | <|skeleton|>
class DataRequestListProto:
"""This class is a drop-in replacement for gRPC default serializer. It replaces default serializer to make sure the message sending interface is convenient. It can handle sending single messages or a list of messages. It also returns a list of messages. Effectively this is h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataRequestListProto:
"""This class is a drop-in replacement for gRPC default serializer. It replaces default serializer to make sure the message sending interface is convenient. It can handle sending single messages or a list of messages. It also returns a list of messages. Effectively this is hiding Message... | the_stack_v2_python_sparse | jina/proto/serializer.py | jina-ai/jina | train | 20,687 |
269e36f882c4f92b2c70d159147c56dc7299b2d3 | [
"if not root:\n return []\nnode_stack = [[root]]\nval_list = []\nwhile node_stack:\n node = node_stack.pop(0)\n node_list = []\n for i in node:\n if not i:\n val_list.append(None)\n else:\n val_list.append(i.val)\n if i.left:\n node_list.appe... | <|body_start_0|>
if not root:
return []
node_stack = [[root]]
val_list = []
while node_stack:
node = node_stack.pop(0)
node_list = []
for i in node:
if not i:
val_list.append(None)
else:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_005704 | 3,243 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_015647 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 2866df7587ee867a958a2b4fc02345bc3ef56999 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
node_stack = [[root]]
val_list = []
while node_stack:
node = node_stack.pop(0)
node_list = []
... | the_stack_v2_python_sparse | 中级算法/serialize.py | OrangeJessie/Fighting_Leetcode | train | 1 | |
4b34d4fdbf315181bd2dad599f5c6445659aa7a7 | [
"self.language = self.language.casefold()\nif self.region is not None:\n self.region = self.region.upper()",
"if not is_language_match(self.language, dialect.language):\n return (-1, 0)\nis_exact_language = self.language == dialect.language\nif self.region is None and dialect.region is None:\n return (2 ... | <|body_start_0|>
self.language = self.language.casefold()
if self.region is not None:
self.region = self.region.upper()
<|end_body_0|>
<|body_start_1|>
if not is_language_match(self.language, dialect.language):
return (-1, 0)
is_exact_language = self.language == ... | Language with optional region and script/code. | Dialect | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dialect:
"""Language with optional region and script/code."""
def __post_init__(self) -> None:
"""Fix casing of language/region."""
<|body_0|>
def score(self, dialect: Dialect, country: str | None=None) -> tuple[float, float]:
"""Return score for match with anoth... | stack_v2_sparse_classes_36k_train_005705 | 5,648 | permissive | [
{
"docstring": "Fix casing of language/region.",
"name": "__post_init__",
"signature": "def __post_init__(self) -> None"
},
{
"docstring": "Return score for match with another dialect where higher is better. Score < 0 indicates a failure to match.",
"name": "score",
"signature": "def sco... | 3 | stack_v2_sparse_classes_30k_train_010186 | Implement the Python class `Dialect` described below.
Class description:
Language with optional region and script/code.
Method signatures and docstrings:
- def __post_init__(self) -> None: Fix casing of language/region.
- def score(self, dialect: Dialect, country: str | None=None) -> tuple[float, float]: Return score... | Implement the Python class `Dialect` described below.
Class description:
Language with optional region and script/code.
Method signatures and docstrings:
- def __post_init__(self) -> None: Fix casing of language/region.
- def score(self, dialect: Dialect, country: str | None=None) -> tuple[float, float]: Return score... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class Dialect:
"""Language with optional region and script/code."""
def __post_init__(self) -> None:
"""Fix casing of language/region."""
<|body_0|>
def score(self, dialect: Dialect, country: str | None=None) -> tuple[float, float]:
"""Return score for match with anoth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dialect:
"""Language with optional region and script/code."""
def __post_init__(self) -> None:
"""Fix casing of language/region."""
self.language = self.language.casefold()
if self.region is not None:
self.region = self.region.upper()
def score(self, dialect: Dial... | the_stack_v2_python_sparse | homeassistant/util/language.py | home-assistant/core | train | 35,501 |
82534e2bf363f46d0d34803fc31659e2af877780 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn PassiveDnsRecord()",
"from .artifact import Artifact\nfrom .host import Host\nfrom .artifact import Artifact\nfrom .host import Host\nfields: Dict[str, Callable[[Any], None]] = {'artifact': lambda n: setattr(self, 'artifact', n.get_obj... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return PassiveDnsRecord()
<|end_body_0|>
<|body_start_1|>
from .artifact import Artifact
from .host import Host
from .artifact import Artifact
from .host import Host
fie... | PassiveDnsRecord | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PassiveDnsRecord:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PassiveDnsRecord:
"""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... | stack_v2_sparse_classes_36k_train_005706 | 4,107 | 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: PassiveDnsRecord",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | null | Implement the Python class `PassiveDnsRecord` described below.
Class description:
Implement the PassiveDnsRecord class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PassiveDnsRecord: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `PassiveDnsRecord` described below.
Class description:
Implement the PassiveDnsRecord class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PassiveDnsRecord: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class PassiveDnsRecord:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PassiveDnsRecord:
"""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... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PassiveDnsRecord:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PassiveDnsRecord:
"""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: Passiv... | the_stack_v2_python_sparse | msgraph/generated/models/security/passive_dns_record.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
f52badb15efc934adca638833ffe362d63e9f398 | [
"dataSet = mode.context.cache.getData(self)\nif not dataSet:\n dataSet = self.compile(mode=mode)\nprovider, font, lines = dataSet\nif provider and font and lines:\n return font.render(lines, fontStyle=self.fontStyle, mode=mode)\nelse:\n return 0",
"value = '\\n'.join(self.string)\nprovider, font = fontpr... | <|body_start_0|>
dataSet = mode.context.cache.getData(self)
if not dataSet:
dataSet = self.compile(mode=mode)
provider, font, lines = dataSet
if provider and font and lines:
return font.render(lines, fontStyle=self.fontStyle, mode=mode)
else:
r... | VRML97-like Text node for displaying text Note that the OpenGLContext Text node provides a number of enhancements to the VRML97 text node, the most pronounced of which is the ability to specify different "geometry formats" as attributes of the fontStyle node. Each text node acquires a pointer to a "font" object from an... | Text | [
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Text:
"""VRML97-like Text node for displaying text Note that the OpenGLContext Text node provides a number of enhancements to the VRML97 text node, the most pronounced of which is the ability to specify different "geometry formats" as attributes of the fontStyle node. Each text node acquires a po... | stack_v2_sparse_classes_36k_train_005707 | 2,590 | permissive | [
{
"docstring": "Render a text-node Depending on the geometry format of the text, the resulting text may be bitmaps blitted directly to the screen, polygonal text rendered in 3-D, or line-set text outlines rendered in 3-D.",
"name": "render",
"signature": "def render(self, visible=1, lit=1, textured=1, m... | 2 | null | Implement the Python class `Text` described below.
Class description:
VRML97-like Text node for displaying text Note that the OpenGLContext Text node provides a number of enhancements to the VRML97 text node, the most pronounced of which is the ability to specify different "geometry formats" as attributes of the fontS... | Implement the Python class `Text` described below.
Class description:
VRML97-like Text node for displaying text Note that the OpenGLContext Text node provides a number of enhancements to the VRML97 text node, the most pronounced of which is the ability to specify different "geometry formats" as attributes of the fontS... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class Text:
"""VRML97-like Text node for displaying text Note that the OpenGLContext Text node provides a number of enhancements to the VRML97 text node, the most pronounced of which is the ability to specify different "geometry formats" as attributes of the fontStyle node. Each text node acquires a po... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Text:
"""VRML97-like Text node for displaying text Note that the OpenGLContext Text node provides a number of enhancements to the VRML97 text node, the most pronounced of which is the ability to specify different "geometry formats" as attributes of the fontStyle node. Each text node acquires a pointer to a "f... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/scenegraph/text/text.py | alexus37/AugmentedRealityChess | train | 1 |
ac49592ab5d0a19a774eb94418af4683d0fcc9a0 | [
"if canAppAccessDatabase():\n self.create_default_test_reports()\n self.create_default_build_reports()",
"src_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', 'report')\ndst_dir = os.path.join(settings.MEDIA_ROOT, 'report', 'inventree', model.getSubdir())\nif not os.path.exists(d... | <|body_start_0|>
if canAppAccessDatabase():
self.create_default_test_reports()
self.create_default_build_reports()
<|end_body_0|>
<|body_start_1|>
src_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', 'report')
dst_dir = os.path.join(settings.M... | ReportConfig | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportConfig:
def ready(self):
"""This function is called whenever the report app is loaded"""
<|body_0|>
def create_default_reports(self, model, reports):
"""Copy defualt report files across to the media directory."""
<|body_1|>
def create_default_test_... | stack_v2_sparse_classes_36k_train_005708 | 3,578 | permissive | [
{
"docstring": "This function is called whenever the report app is loaded",
"name": "ready",
"signature": "def ready(self)"
},
{
"docstring": "Copy defualt report files across to the media directory.",
"name": "create_default_reports",
"signature": "def create_default_reports(self, model... | 4 | null | Implement the Python class `ReportConfig` described below.
Class description:
Implement the ReportConfig class.
Method signatures and docstrings:
- def ready(self): This function is called whenever the report app is loaded
- def create_default_reports(self, model, reports): Copy defualt report files across to the med... | Implement the Python class `ReportConfig` described below.
Class description:
Implement the ReportConfig class.
Method signatures and docstrings:
- def ready(self): This function is called whenever the report app is loaded
- def create_default_reports(self, model, reports): Copy defualt report files across to the med... | 2a0ea66f6591756eeb62da28d24daec3ad4209e8 | <|skeleton|>
class ReportConfig:
def ready(self):
"""This function is called whenever the report app is loaded"""
<|body_0|>
def create_default_reports(self, model, reports):
"""Copy defualt report files across to the media directory."""
<|body_1|>
def create_default_test_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReportConfig:
def ready(self):
"""This function is called whenever the report app is loaded"""
if canAppAccessDatabase():
self.create_default_test_reports()
self.create_default_build_reports()
def create_default_reports(self, model, reports):
"""Copy defual... | the_stack_v2_python_sparse | InvenTree/report/apps.py | MedShift/InvenTree | train | 0 | |
861b7761560f515ea622702bf5094957313ced07 | [
"self.index = 0\nself.twitters = dict()\nself.followers = dict()",
"if userId in self.twitters:\n self.twitters[userId].append((tweetId, self.index))\nelse:\n self.twitters.setdefault(userId, [(tweetId, self.index)])\nself.index += 1",
"tweets = []\nif userId in self.twitters:\n tweets += self.twitters... | <|body_start_0|>
self.index = 0
self.twitters = dict()
self.followers = dict()
<|end_body_0|>
<|body_start_1|>
if userId in self.twitters:
self.twitters[userId].append((tweetId, self.index))
else:
self.twitters.setdefault(userId, [(tweetId, self.index)])
... | Twitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
<|body_1|>
def getNewsFeed(self, userId: int) -> list:
"""Retrieve the 10 most r... | stack_v2_sparse_classes_36k_train_005709 | 2,372 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compose a new tweet.",
"name": "postTweet",
"signature": "def postTweet(self, userId: int, tweetId: int) -> None"
},
{
"docstring": "Retrieve the 10 mos... | 5 | stack_v2_sparse_classes_30k_train_002434 | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet.
- def getNewsFeed(self, userId: int) -> list... | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet.
- def getNewsFeed(self, userId: int) -> list... | 4416d0c711b8978f12de960c29d00a9d9792b9e0 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
<|body_1|>
def getNewsFeed(self, userId: int) -> list:
"""Retrieve the 10 most r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Twitter:
def __init__(self):
"""Initialize your data structure here."""
self.index = 0
self.twitters = dict()
self.followers = dict()
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
if userId in self.twitters:
... | the_stack_v2_python_sparse | 301-400/355. Design Twitter.py | Ys-Zhou/leetcode-medi-p3 | train | 0 | |
4b32221dfa2b66dee5fc2d2a8c86501d22d7ed04 | [
"if sociallogin.is_existing:\n return\nif 'email' not in sociallogin.account.extra_data:\n return\ntry:\n email = sociallogin.account.extra_data['email'].lower()\n email_address = EmailAddress.objects.get(email__iexact=email)\nexcept EmailAddress.DoesNotExist:\n return\nuser = email_address.user\nsoc... | <|body_start_0|>
if sociallogin.is_existing:
return
if 'email' not in sociallogin.account.extra_data:
return
try:
email = sociallogin.account.extra_data['email'].lower()
email_address = EmailAddress.objects.get(email__iexact=email)
except E... | SocialAccountAdapter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SocialAccountAdapter:
def pre_social_login(self, request, sociallogin):
"""Invoked just after a user successfully authenticates via a social provider, but before the login is actually processed (and before the pre_social_login signal is emitted). We're trying to solve different use cases... | stack_v2_sparse_classes_36k_train_005710 | 2,719 | permissive | [
{
"docstring": "Invoked just after a user successfully authenticates via a social provider, but before the login is actually processed (and before the pre_social_login signal is emitted). We're trying to solve different use cases: - social account already exists, just go on - social account has no email or emai... | 2 | stack_v2_sparse_classes_30k_val_000731 | Implement the Python class `SocialAccountAdapter` described below.
Class description:
Implement the SocialAccountAdapter class.
Method signatures and docstrings:
- def pre_social_login(self, request, sociallogin): Invoked just after a user successfully authenticates via a social provider, but before the login is actu... | Implement the Python class `SocialAccountAdapter` described below.
Class description:
Implement the SocialAccountAdapter class.
Method signatures and docstrings:
- def pre_social_login(self, request, sociallogin): Invoked just after a user successfully authenticates via a social provider, but before the login is actu... | bfb335d70733130eaecb026d38e23a5ac01e50ea | <|skeleton|>
class SocialAccountAdapter:
def pre_social_login(self, request, sociallogin):
"""Invoked just after a user successfully authenticates via a social provider, but before the login is actually processed (and before the pre_social_login signal is emitted). We're trying to solve different use cases... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SocialAccountAdapter:
def pre_social_login(self, request, sociallogin):
"""Invoked just after a user successfully authenticates via a social provider, but before the login is actually processed (and before the pre_social_login signal is emitted). We're trying to solve different use cases: - social acc... | the_stack_v2_python_sparse | server/comidaimigrante/account/adapter.py | LabHackerSP/comidaimigrante | train | 1 | |
c324a0bf7ea81d8cc2050306cca56a53ae4dde2d | [
"msg: Message = copy(ctx.message)\nmsg.content = f'{ctx.prefix}{command}'\nreturn await ctx.bot.get_context(msg)",
"new_ctx = await self.create_execution_context(ctx, command)\nctx.subcontext = new_ctx\nif not ctx.subcontext.command:\n help_command = f'{ctx.prefix}help'\n error = f\"The command you are tryi... | <|body_start_0|>
msg: Message = copy(ctx.message)
msg.content = f'{ctx.prefix}{command}'
return await ctx.bot.get_context(msg)
<|end_body_0|>
<|body_start_1|>
new_ctx = await self.create_execution_context(ctx, command)
ctx.subcontext = new_ctx
if not ctx.subcontext.comma... | Time the command execution of a command. | TimedCommands | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimedCommands:
"""Time the command execution of a command."""
async def create_execution_context(ctx: commands.Context, command: str) -> commands.Context:
"""Get a new execution context for a command."""
<|body_0|>
async def timed(self, ctx: commands.Context, *, command:... | stack_v2_sparse_classes_36k_train_005711 | 1,576 | permissive | [
{
"docstring": "Get a new execution context for a command.",
"name": "create_execution_context",
"signature": "async def create_execution_context(ctx: commands.Context, command: str) -> commands.Context"
},
{
"docstring": "Time the command execution of a command.",
"name": "timed",
"sign... | 2 | stack_v2_sparse_classes_30k_train_009189 | Implement the Python class `TimedCommands` described below.
Class description:
Time the command execution of a command.
Method signatures and docstrings:
- async def create_execution_context(ctx: commands.Context, command: str) -> commands.Context: Get a new execution context for a command.
- async def timed(self, ct... | Implement the Python class `TimedCommands` described below.
Class description:
Time the command execution of a command.
Method signatures and docstrings:
- async def create_execution_context(ctx: commands.Context, command: str) -> commands.Context: Get a new execution context for a command.
- async def timed(self, ct... | 7aaf8f406fcb6cbe89e4b6742eff6c3efa754993 | <|skeleton|>
class TimedCommands:
"""Time the command execution of a command."""
async def create_execution_context(ctx: commands.Context, command: str) -> commands.Context:
"""Get a new execution context for a command."""
<|body_0|>
async def timed(self, ctx: commands.Context, *, command:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimedCommands:
"""Time the command execution of a command."""
async def create_execution_context(ctx: commands.Context, command: str) -> commands.Context:
"""Get a new execution context for a command."""
msg: Message = copy(ctx.message)
msg.content = f'{ctx.prefix}{command}'
... | the_stack_v2_python_sparse | bot/exts/evergreen/timed.py | Lynchly/sir-lancebot | train | 1 |
bfaeac640db9fdebd01ddbdaeb2712f3ed3cace9 | [
"if len(strs) == 0:\n return chr(258)\nreturn chr(257).join((x for x in strs))",
"if s == chr(258):\n return []\nreturn s.split(chr(257))"
] | <|body_start_0|>
if len(strs) == 0:
return chr(258)
return chr(257).join((x for x in strs))
<|end_body_0|>
<|body_start_1|>
if s == chr(258):
return []
return s.split(chr(257))
<|end_body_1|>
| Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_005712 | 4,315 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | 59f70dc4466e15df591ba285317e4a1fe808ed60 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
if len(strs) == 0:
return chr(258)
return chr(257).join((x for x in strs))
def decode(self, s):
"""Decodes a single string to a list of strings.... | the_stack_v2_python_sparse | leet/Design/encode_and_decode_strings.py | arsamigullin/problem_solving_python | train | 0 | |
fe26dba95d683ca4ddcb2189a13253f1e448fb99 | [
"if prompt_from_serial_number and (not expected_prompt):\n if not prompt_after_login:\n prompt_after_login = self._re_default_prompt\n if serial_number and (not set_prompt):\n set_prompt = 'export PS1=\"adb_shell@{} \\\\$ \"'.format(serial_number)\n expected_prompt = re.compile(self.re_ge... | <|body_start_0|>
if prompt_from_serial_number and (not expected_prompt):
if not prompt_after_login:
prompt_after_login = self._re_default_prompt
if serial_number and (not set_prompt):
set_prompt = 'export PS1="adb_shell@{} \\$ "'.format(serial_number)
... | AdbShell | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdbShell:
def __init__(self, connection, serial_number=None, prompt=None, expected_prompt=None, newline_chars=None, target_newline='\n', runner=None, set_timeout=None, allowed_newline_after_prompt=False, set_prompt=None, prompt_after_login=None, prompt_from_serial_number=False):
"""Moler... | stack_v2_sparse_classes_36k_train_005713 | 5,676 | permissive | [
{
"docstring": "Moler class of Unix command adb shell. It is intended to enter shell and not run commands via shell like 'adb shell ls -l' # TODO: AdbShellExecute ? :param connection: moler connection to device, terminal when command is executed. :param serial_number: SN of selected device as seen on 'adb devic... | 5 | null | Implement the Python class `AdbShell` described below.
Class description:
Implement the AdbShell class.
Method signatures and docstrings:
- def __init__(self, connection, serial_number=None, prompt=None, expected_prompt=None, newline_chars=None, target_newline='\n', runner=None, set_timeout=None, allowed_newline_afte... | Implement the Python class `AdbShell` described below.
Class description:
Implement the AdbShell class.
Method signatures and docstrings:
- def __init__(self, connection, serial_number=None, prompt=None, expected_prompt=None, newline_chars=None, target_newline='\n', runner=None, set_timeout=None, allowed_newline_afte... | 5a7bb06807b6e0124c77040367d0c20f42849a4c | <|skeleton|>
class AdbShell:
def __init__(self, connection, serial_number=None, prompt=None, expected_prompt=None, newline_chars=None, target_newline='\n', runner=None, set_timeout=None, allowed_newline_after_prompt=False, set_prompt=None, prompt_after_login=None, prompt_from_serial_number=False):
"""Moler... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdbShell:
def __init__(self, connection, serial_number=None, prompt=None, expected_prompt=None, newline_chars=None, target_newline='\n', runner=None, set_timeout=None, allowed_newline_after_prompt=False, set_prompt=None, prompt_after_login=None, prompt_from_serial_number=False):
"""Moler class of Unix... | the_stack_v2_python_sparse | moler/cmd/adb/adb_shell.py | nokia/moler | train | 60 | |
3e0025a984f7d1e981e92aeb78dd2acafa7ec7e0 | [
"with DBConnectionHandler() as db_connection:\n try:\n select = db_connection.get_select()\n statement = select(UserSchema.id, UserSchema.username, UserSchema.password).order_by(UserSchema.id)\n results = db_connection.session.execute(statement).all()\n if len(results) == 0:\n ... | <|body_start_0|>
with DBConnectionHandler() as db_connection:
try:
select = db_connection.get_select()
statement = select(UserSchema.id, UserSchema.username, UserSchema.password).order_by(UserSchema.id)
results = db_connection.session.execute(statement... | Class to manage User Repository | UserRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRepository:
"""Class to manage User Repository"""
def fetch(cls) -> List[User]:
"""Fetch all users from database. :return - return a list of users"""
<|body_0|>
def find(cls, user_id: int=None) -> User:
"""Find a specific user on database. :params - user_id: ... | stack_v2_sparse_classes_36k_train_005714 | 3,805 | no_license | [
{
"docstring": "Fetch all users from database. :return - return a list of users",
"name": "fetch",
"signature": "def fetch(cls) -> List[User]"
},
{
"docstring": "Find a specific user on database. :params - user_id: User's id - username: User's username :return - return a specific User",
"nam... | 4 | stack_v2_sparse_classes_30k_train_001577 | Implement the Python class `UserRepository` described below.
Class description:
Class to manage User Repository
Method signatures and docstrings:
- def fetch(cls) -> List[User]: Fetch all users from database. :return - return a list of users
- def find(cls, user_id: int=None) -> User: Find a specific user on database... | Implement the Python class `UserRepository` described below.
Class description:
Class to manage User Repository
Method signatures and docstrings:
- def fetch(cls) -> List[User]: Fetch all users from database. :return - return a list of users
- def find(cls, user_id: int=None) -> User: Find a specific user on database... | c5896f3e7b8c85b76ebd365a6862b391bb14dcc3 | <|skeleton|>
class UserRepository:
"""Class to manage User Repository"""
def fetch(cls) -> List[User]:
"""Fetch all users from database. :return - return a list of users"""
<|body_0|>
def find(cls, user_id: int=None) -> User:
"""Find a specific user on database. :params - user_id: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserRepository:
"""Class to manage User Repository"""
def fetch(cls) -> List[User]:
"""Fetch all users from database. :return - return a list of users"""
with DBConnectionHandler() as db_connection:
try:
select = db_connection.get_select()
state... | the_stack_v2_python_sparse | src/repositories/implementations/user/user_repository.py | devtorello/py-clean-arch | train | 0 |
1348db50d53e3faa6dfe277a5ec27b53d1ae6e97 | [
"queue = Queue()\nfor i in range(1000):\n queue.enqueue(i)\n self.assertEqual(queue.front.info, 0)\n self.assertEqual(queue.rear.info, i)\n self.assertEqual(len(queue), i + 1)",
"queue = Queue(list(range(1, 1001)))\nfor i in range(1, 1001):\n self.assertEqual(queue.dequeue().info, i)\n self.asse... | <|body_start_0|>
queue = Queue()
for i in range(1000):
queue.enqueue(i)
self.assertEqual(queue.front.info, 0)
self.assertEqual(queue.rear.info, i)
self.assertEqual(len(queue), i + 1)
<|end_body_0|>
<|body_start_1|>
queue = Queue(list(range(1, 1001... | Test the `chapter5.Queue` data structure | TestQueue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestQueue:
"""Test the `chapter5.Queue` data structure"""
def test_enqueue(self):
"""Test enqueueing"""
<|body_0|>
def test_dequeue(self):
"""Test dequeueing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
queue = Queue()
for i in range(... | stack_v2_sparse_classes_36k_train_005715 | 1,656 | no_license | [
{
"docstring": "Test enqueueing",
"name": "test_enqueue",
"signature": "def test_enqueue(self)"
},
{
"docstring": "Test dequeueing",
"name": "test_dequeue",
"signature": "def test_dequeue(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004309 | Implement the Python class `TestQueue` described below.
Class description:
Test the `chapter5.Queue` data structure
Method signatures and docstrings:
- def test_enqueue(self): Test enqueueing
- def test_dequeue(self): Test dequeueing | Implement the Python class `TestQueue` described below.
Class description:
Test the `chapter5.Queue` data structure
Method signatures and docstrings:
- def test_enqueue(self): Test enqueueing
- def test_dequeue(self): Test dequeueing
<|skeleton|>
class TestQueue:
"""Test the `chapter5.Queue` data structure"""
... | b73f0596d7e4a52a284dd1a072f37a65257dc357 | <|skeleton|>
class TestQueue:
"""Test the `chapter5.Queue` data structure"""
def test_enqueue(self):
"""Test enqueueing"""
<|body_0|>
def test_dequeue(self):
"""Test dequeueing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestQueue:
"""Test the `chapter5.Queue` data structure"""
def test_enqueue(self):
"""Test enqueueing"""
queue = Queue()
for i in range(1000):
queue.enqueue(i)
self.assertEqual(queue.front.info, 0)
self.assertEqual(queue.rear.info, i)
... | the_stack_v2_python_sparse | chapter5/tests.py | lptorres/data-structures-exercises | train | 0 |
fdfb16032d63dccfe736757871f28ac55b96b3da | [
"self._filename = filename\nself._filelayout = filelayout\nself._data = self._parse()",
"output = pd.read_csv(self._filename, comment='#', delim_whitespace=True, names=self._filelayout)\noutput_dict = output.to_dict()\nreturn output_dict",
"try:\n selected_data = np.array(list(self._data[name].values()))\nex... | <|body_start_0|>
self._filename = filename
self._filelayout = filelayout
self._data = self._parse()
<|end_body_0|>
<|body_start_1|>
output = pd.read_csv(self._filename, comment='#', delim_whitespace=True, names=self._filelayout)
output_dict = output.to_dict()
return outp... | Parses information for known data files in txt format. | RawData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RawData:
"""Parses information for known data files in txt format."""
def __init__(self, filename, filelayout):
"""Parses information for known data files in txt format. :filename: name of the file to parse :filelayout: list of column names in file"""
<|body_0|>
def _par... | stack_v2_sparse_classes_36k_train_005716 | 15,467 | no_license | [
{
"docstring": "Parses information for known data files in txt format. :filename: name of the file to parse :filelayout: list of column names in file",
"name": "__init__",
"signature": "def __init__(self, filename, filelayout)"
},
{
"docstring": "Parse the data form the object's file. :return: a... | 3 | stack_v2_sparse_classes_30k_train_019721 | Implement the Python class `RawData` described below.
Class description:
Parses information for known data files in txt format.
Method signatures and docstrings:
- def __init__(self, filename, filelayout): Parses information for known data files in txt format. :filename: name of the file to parse :filelayout: list of... | Implement the Python class `RawData` described below.
Class description:
Parses information for known data files in txt format.
Method signatures and docstrings:
- def __init__(self, filename, filelayout): Parses information for known data files in txt format. :filename: name of the file to parse :filelayout: list of... | 0c1894ce8d9f5daed539240d3ac86e645d6de44c | <|skeleton|>
class RawData:
"""Parses information for known data files in txt format."""
def __init__(self, filename, filelayout):
"""Parses information for known data files in txt format. :filename: name of the file to parse :filelayout: list of column names in file"""
<|body_0|>
def _par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RawData:
"""Parses information for known data files in txt format."""
def __init__(self, filename, filelayout):
"""Parses information for known data files in txt format. :filename: name of the file to parse :filelayout: list of column names in file"""
self._filename = filename
sel... | the_stack_v2_python_sparse | stan_implementation/analysis_interface/interfaces/data.py | cescalara/soiaporn_model | train | 1 |
ede5a4cfa5bca266ff6aea338da80690ca3f5893 | [
"super(WotView, self).__init__(parent)\nself.setScene(Scene(self))\nself.setCacheMode(QGraphicsView.CacheBackground)\nself.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate)\nself.setRenderHint(QPainter.Antialiasing)\nself.setRenderHint(QPainter.SmoothPixmapTransform)",
"if event.modifiers() & Qt.Con... | <|body_start_0|>
super(WotView, self).__init__(parent)
self.setScene(Scene(self))
self.setCacheMode(QGraphicsView.CacheBackground)
self.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate)
self.setRenderHint(QPainter.Antialiasing)
self.setRenderHint(QPainter.Sm... | WotView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WotView:
def __init__(self, parent=None):
"""Create View to display scene :param parent: [Optional, default=None] Parent widget"""
<|body_0|>
def wheelEvent(self, event: QWheelEvent):
"""Zoom in/out on the mouse cursor"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_005717 | 16,818 | permissive | [
{
"docstring": "Create View to display scene :param parent: [Optional, default=None] Parent widget",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Zoom in/out on the mouse cursor",
"name": "wheelEvent",
"signature": "def wheelEvent(self, event: QWh... | 2 | stack_v2_sparse_classes_30k_train_008540 | Implement the Python class `WotView` described below.
Class description:
Implement the WotView class.
Method signatures and docstrings:
- def __init__(self, parent=None): Create View to display scene :param parent: [Optional, default=None] Parent widget
- def wheelEvent(self, event: QWheelEvent): Zoom in/out on the m... | Implement the Python class `WotView` described below.
Class description:
Implement the WotView class.
Method signatures and docstrings:
- def __init__(self, parent=None): Create View to display scene :param parent: [Optional, default=None] Parent widget
- def wheelEvent(self, event: QWheelEvent): Zoom in/out on the m... | 25699bae35ce9e46e0999f38548cb9d3c1ef7f3c | <|skeleton|>
class WotView:
def __init__(self, parent=None):
"""Create View to display scene :param parent: [Optional, default=None] Parent widget"""
<|body_0|>
def wheelEvent(self, event: QWheelEvent):
"""Zoom in/out on the mouse cursor"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WotView:
def __init__(self, parent=None):
"""Create View to display scene :param parent: [Optional, default=None] Parent widget"""
super(WotView, self).__init__(parent)
self.setScene(Scene(self))
self.setCacheMode(QGraphicsView.CacheBackground)
self.setViewportUpdateMod... | the_stack_v2_python_sparse | src/cutecoin/gui/views/wot.py | sethkontny/cutecoin | train | 0 | |
a64e7210b5ff743d9436c637ae933bc1ca56e0eb | [
"super().__init__(raster_mode, dwell_time, total_time, dwell_time_live)\nself.step_count_x = step_count_x\nself.step_count_y = step_count_y\nself.step_count_z = step_count_z\nself.step_size_x = step_size_x\nself.step_size_y = step_size_y\nself.step_size_z = step_size_z\nself.position = position\nself.raster_mode_z ... | <|body_start_0|>
super().__init__(raster_mode, dwell_time, total_time, dwell_time_live)
self.step_count_x = step_count_x
self.step_count_y = step_count_y
self.step_count_z = step_count_z
self.step_size_x = step_size_x
self.step_size_y = step_size_y
self.step_size_... | AcquisitionRasterXYZ | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AcquisitionRasterXYZ:
def __init__(self, step_count_x, step_count_y, step_count_z, step_size_x=None, step_size_y=None, step_size_z=None, position=None, raster_mode_z=None, raster_mode=None, dwell_time=None, total_time=None, dwell_time_live=None):
"""Defines the position and duration of a... | stack_v2_sparse_classes_36k_train_005718 | 15,189 | permissive | [
{
"docstring": "Defines the position and duration of a three-dimensional X/Y/Z raster over the specimen. :arg step_count_x: number of steps in x direction (required) :arg step_count_y: number of steps in y direction (required) :arg step_count_z: number of steps in z direction (required) :arg step_size_x: dimens... | 3 | null | Implement the Python class `AcquisitionRasterXYZ` described below.
Class description:
Implement the AcquisitionRasterXYZ class.
Method signatures and docstrings:
- def __init__(self, step_count_x, step_count_y, step_count_z, step_size_x=None, step_size_y=None, step_size_z=None, position=None, raster_mode_z=None, rast... | Implement the Python class `AcquisitionRasterXYZ` described below.
Class description:
Implement the AcquisitionRasterXYZ class.
Method signatures and docstrings:
- def __init__(self, step_count_x, step_count_y, step_count_z, step_size_x=None, step_size_y=None, step_size_z=None, position=None, raster_mode_z=None, rast... | 0081ea29127c72e8a0511a9f8fc58d0fe098b801 | <|skeleton|>
class AcquisitionRasterXYZ:
def __init__(self, step_count_x, step_count_y, step_count_z, step_size_x=None, step_size_y=None, step_size_z=None, position=None, raster_mode_z=None, raster_mode=None, dwell_time=None, total_time=None, dwell_time_live=None):
"""Defines the position and duration of a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AcquisitionRasterXYZ:
def __init__(self, step_count_x, step_count_y, step_count_z, step_size_x=None, step_size_y=None, step_size_z=None, position=None, raster_mode_z=None, raster_mode=None, dwell_time=None, total_time=None, dwell_time_live=None):
"""Defines the position and duration of a three-dimensi... | the_stack_v2_python_sparse | pyhmsa/spec/condition/acquisition.py | pyhmsa/pyhmsa | train | 2 | |
0732a42c608cc5359d3494754ff4caca76ce0240 | [
"self._index = esm.Index()\nfor item in in_list:\n if isinstance(item, tuple):\n in_str = item[0]\n in_str = in_str.encode(DEFAULT_ENCODING)\n self._index.enter(in_str, item)\n elif isinstance(item, basestring):\n item = item.encode(DEFAULT_ENCODING)\n self._index.enter(item... | <|body_start_0|>
self._index = esm.Index()
for item in in_list:
if isinstance(item, tuple):
in_str = item[0]
in_str = in_str.encode(DEFAULT_ENCODING)
self._index.enter(in_str, item)
elif isinstance(item, basestring):
... | This is a wrapper around esm that provides the plugins (users) with an easy to use API to esm for doing various "in" statements with better algorithms. | esm_multi_in | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class esm_multi_in:
"""This is a wrapper around esm that provides the plugins (users) with an easy to use API to esm for doing various "in" statements with better algorithms."""
def __init__(self, in_list):
""":param in_list: A list with all the strings that we want to match against one or... | stack_v2_sparse_classes_36k_train_005719 | 2,771 | no_license | [
{
"docstring": ":param in_list: A list with all the strings that we want to match against one or more strings using the \"query\" function. This list might be [str_1, str_2 ... , str_N] or something like [ (str_1, obj1) , (str_2, obj2) ... , (str_N, objN)]. In the first case, if a match is found this class will... | 2 | null | Implement the Python class `esm_multi_in` described below.
Class description:
This is a wrapper around esm that provides the plugins (users) with an easy to use API to esm for doing various "in" statements with better algorithms.
Method signatures and docstrings:
- def __init__(self, in_list): :param in_list: A list ... | Implement the Python class `esm_multi_in` described below.
Class description:
This is a wrapper around esm that provides the plugins (users) with an easy to use API to esm for doing various "in" statements with better algorithms.
Method signatures and docstrings:
- def __init__(self, in_list): :param in_list: A list ... | 13967bffaa211fe7f793204796802f1a5967f1d7 | <|skeleton|>
class esm_multi_in:
"""This is a wrapper around esm that provides the plugins (users) with an easy to use API to esm for doing various "in" statements with better algorithms."""
def __init__(self, in_list):
""":param in_list: A list with all the strings that we want to match against one or... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class esm_multi_in:
"""This is a wrapper around esm that provides the plugins (users) with an easy to use API to esm for doing various "in" statements with better algorithms."""
def __init__(self, in_list):
""":param in_list: A list with all the strings that we want to match against one or more strings... | the_stack_v2_python_sparse | w3af-repo/w3af/core/data/esmre/esm_multi_in.py | ZenSecurity/w3af-module | train | 2 |
dc2d6b4697dc3f5cd3f5cedd307052254563004a | [
"self.approach = approach\nself.axis = axis\nself.top = top\nself.bottom = bottom\nself.height = height\nself.width = width\nself.offsets = offsets\nself.binormal = cross(approach, axis) if binormal is None else binormal\nself.center = 0.5 * bottom + 0.5 * top\nself.fingerNormals = (self.binormal, -self.binormal)\n... | <|body_start_0|>
self.approach = approach
self.axis = axis
self.top = top
self.bottom = bottom
self.height = height
self.width = width
self.offsets = offsets
self.binormal = cross(approach, axis) if binormal is None else binormal
self.center = 0.5 ... | Grasp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grasp:
def __init__(self, approach, axis, top, bottom, height, width, offsets, binormal=None, score=None, image=None):
"""Creates a Grasp object with everything needed."""
<|body_0|>
def Flip(self):
"""Creates a new grasp flipped 180 degrees about the approach direct... | stack_v2_sparse_classes_36k_train_005720 | 1,492 | permissive | [
{
"docstring": "Creates a Grasp object with everything needed.",
"name": "__init__",
"signature": "def __init__(self, approach, axis, top, bottom, height, width, offsets, binormal=None, score=None, image=None)"
},
{
"docstring": "Creates a new grasp flipped 180 degrees about the approach directi... | 2 | stack_v2_sparse_classes_30k_train_007086 | Implement the Python class `Grasp` described below.
Class description:
Implement the Grasp class.
Method signatures and docstrings:
- def __init__(self, approach, axis, top, bottom, height, width, offsets, binormal=None, score=None, image=None): Creates a Grasp object with everything needed.
- def Flip(self): Creates... | Implement the Python class `Grasp` described below.
Class description:
Implement the Grasp class.
Method signatures and docstrings:
- def __init__(self, approach, axis, top, bottom, height, width, offsets, binormal=None, score=None, image=None): Creates a Grasp object with everything needed.
- def Flip(self): Creates... | 15cdf2a6d5a255ecb78488ca75657af559d0c2da | <|skeleton|>
class Grasp:
def __init__(self, approach, axis, top, bottom, height, width, offsets, binormal=None, score=None, image=None):
"""Creates a Grasp object with everything needed."""
<|body_0|>
def Flip(self):
"""Creates a new grasp flipped 180 degrees about the approach direct... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Grasp:
def __init__(self, approach, axis, top, bottom, height, width, offsets, binormal=None, score=None, image=None):
"""Creates a Grasp object with everything needed."""
self.approach = approach
self.axis = axis
self.top = top
self.bottom = bottom
self.height ... | the_stack_v2_python_sparse | simulation/python2/grasp.py | mgualti/PickAndPlace | train | 14 | |
7ffa00cacaf8d5bdc37e95fea7f1e7d324064936 | [
"self.table = DBFetcher(dot_t_system_dir, 'db', 'admin').fetch()\nself.ssid_hash = None\nself.password_hash = None\nself.private_key = None\nself.__get_keys()",
"ssid_hash = hashlib.sha256(ssid.encode()).hexdigest()\npassword_hash = hashlib.sha256(password.encode()).hexdigest()\npublic_key = hashlib.sha256((ssid ... | <|body_start_0|>
self.table = DBFetcher(dot_t_system_dir, 'db', 'admin').fetch()
self.ssid_hash = None
self.password_hash = None
self.private_key = None
self.__get_keys()
<|end_body_0|>
<|body_start_1|>
ssid_hash = hashlib.sha256(ssid.encode()).hexdigest()
passwo... | Class to define an administrator for managing admin authentication keys of tracking system. This class provides necessary initiations and functions named :func:`t_system.administration.Administrator.change_keys` for changing admin entry keys. | Administrator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Administrator:
"""Class to define an administrator for managing admin authentication keys of tracking system. This class provides necessary initiations and functions named :func:`t_system.administration.Administrator.change_keys` for changing admin entry keys."""
def __init__(self):
... | stack_v2_sparse_classes_36k_train_005721 | 8,320 | permissive | [
{
"docstring": "Initialization method of :class:`t_system.administration.Administrator` class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to change keys of secret entry point for root authorized. 2 key(ssid and password) authentication uses sha256 encryptio... | 5 | stack_v2_sparse_classes_30k_val_000924 | Implement the Python class `Administrator` described below.
Class description:
Class to define an administrator for managing admin authentication keys of tracking system. This class provides necessary initiations and functions named :func:`t_system.administration.Administrator.change_keys` for changing admin entry key... | Implement the Python class `Administrator` described below.
Class description:
Class to define an administrator for managing admin authentication keys of tracking system. This class provides necessary initiations and functions named :func:`t_system.administration.Administrator.change_keys` for changing admin entry key... | 4cf34572b8f8eac54d6c339f37aa72b6a13d8934 | <|skeleton|>
class Administrator:
"""Class to define an administrator for managing admin authentication keys of tracking system. This class provides necessary initiations and functions named :func:`t_system.administration.Administrator.change_keys` for changing admin entry keys."""
def __init__(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Administrator:
"""Class to define an administrator for managing admin authentication keys of tracking system. This class provides necessary initiations and functions named :func:`t_system.administration.Administrator.change_keys` for changing admin entry keys."""
def __init__(self):
"""Initializa... | the_stack_v2_python_sparse | t_system/administration.py | LookAtMe-Genius-Cameraman/T_System | train | 9 |
8da7f8a42b07cb657c235fa38af23f70d203b439 | [
"super(SwarmStatistics, self).__init__()\nself.internalDict = {'bestFitMax': 0.0, 'bestFitMin': 0.0, 'bestFitAvg': 0.0, 'bestFitDev': 0.0, 'bestFitVar': 0.0, 'fitMin': 0.0, 'fitMax': 0.0, 'fitAvg': 0.0}\nself.descriptions = {'bestFitMax': 'Maximum best Fitness', 'bestFitMin': 'Minimum best Fitness', 'bestFitAvg': '... | <|body_start_0|>
super(SwarmStatistics, self).__init__()
self.internalDict = {'bestFitMax': 0.0, 'bestFitMin': 0.0, 'bestFitAvg': 0.0, 'bestFitDev': 0.0, 'bestFitVar': 0.0, 'fitMin': 0.0, 'fitMax': 0.0, 'fitAvg': 0.0}
self.descriptions = {'bestFitMax': 'Maximum best Fitness', 'bestFitMin': 'Mini... | Swarm Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitMax, bestFitMin** The maximum and minimum fitness scores of the swarm **bestFitAvg,bestFitDev** The Average and Standard Deviation of the best fitness of the swarm **fitMin, fitMax, fitAvg** Minimum fitnes... | SwarmStatistics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwarmStatistics:
"""Swarm Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitMax, bestFitMin** The maximum and minimum fitness scores of the swarm **bestFitAvg,bestFitDev** The Average and Standard Deviation of the best fitness of the swar... | stack_v2_sparse_classes_36k_train_005722 | 5,204 | no_license | [
{
"docstring": "The Statistics Class Creator",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns a string representation of the statistics",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010342 | Implement the Python class `SwarmStatistics` described below.
Class description:
Swarm Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitMax, bestFitMin** The maximum and minimum fitness scores of the swarm **bestFitAvg,bestFitDev** The Average and Standard De... | Implement the Python class `SwarmStatistics` described below.
Class description:
Swarm Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitMax, bestFitMin** The maximum and minimum fitness scores of the swarm **bestFitAvg,bestFitDev** The Average and Standard De... | ea1ef4cba0b5bddf1b7bf858e53c32aeb859655d | <|skeleton|>
class SwarmStatistics:
"""Swarm Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitMax, bestFitMin** The maximum and minimum fitness scores of the swarm **bestFitAvg,bestFitDev** The Average and Standard Deviation of the best fitness of the swar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwarmStatistics:
"""Swarm Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitMax, bestFitMin** The maximum and minimum fitness scores of the swarm **bestFitAvg,bestFitDev** The Average and Standard Deviation of the best fitness of the swarm **fitMin, f... | the_stack_v2_python_sparse | 0.12/FloatStatistics.py | ItaloAP/pypso | train | 0 |
7d284d419762d29019091319b619bc68450fe829 | [
"data = self.get_json()\ngroup_ids = data.get('groupIds')\nif group_ids is None:\n return self.error('Missing required parameter: `groupIds`')\ntry:\n group_ids = [int(gid) for gid in data['groupIds']]\nexcept ValueError:\n return self.error('Invalid value provided for `groupIDs`; unable to parse all list ... | <|body_start_0|>
data = self.get_json()
group_ids = data.get('groupIds')
if group_ids is None:
return self.error('Missing required parameter: `groupIds`')
try:
group_ids = [int(gid) for gid in data['groupIds']]
except ValueError:
return self.er... | SourceLabelsHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceLabelsHandler:
def post(self, obj_id):
"""--- description: Note that a source has been labelled. tags: - sources - source_scans parameters: - in: path name: obj_id required: true schema: type: string description: | ID of object to indicate source labelling for requestBody: content:... | stack_v2_sparse_classes_36k_train_005723 | 4,944 | permissive | [
{
"docstring": "--- description: Note that a source has been labelled. tags: - sources - source_scans parameters: - in: path name: obj_id required: true schema: type: string description: | ID of object to indicate source labelling for requestBody: content: application/json: schema: type: object properties: grou... | 2 | null | Implement the Python class `SourceLabelsHandler` described below.
Class description:
Implement the SourceLabelsHandler class.
Method signatures and docstrings:
- def post(self, obj_id): --- description: Note that a source has been labelled. tags: - sources - source_scans parameters: - in: path name: obj_id required: ... | Implement the Python class `SourceLabelsHandler` described below.
Class description:
Implement the SourceLabelsHandler class.
Method signatures and docstrings:
- def post(self, obj_id): --- description: Note that a source has been labelled. tags: - sources - source_scans parameters: - in: path name: obj_id required: ... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class SourceLabelsHandler:
def post(self, obj_id):
"""--- description: Note that a source has been labelled. tags: - sources - source_scans parameters: - in: path name: obj_id required: true schema: type: string description: | ID of object to indicate source labelling for requestBody: content:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SourceLabelsHandler:
def post(self, obj_id):
"""--- description: Note that a source has been labelled. tags: - sources - source_scans parameters: - in: path name: obj_id required: true schema: type: string description: | ID of object to indicate source labelling for requestBody: content: application/j... | the_stack_v2_python_sparse | skyportal/handlers/api/source_labels.py | skyportal/skyportal | train | 80 | |
07bd23cfcefc6f488fb40bcd1acd3b735fd93412 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn RiskyServicePrincipalHistoryItem()",
"from .risk_service_principal_activity import RiskServicePrincipalActivity\nfrom .risky_service_principal import RiskyServicePrincipal\nfrom .risk_service_principal_activity import RiskServicePrinci... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return RiskyServicePrincipalHistoryItem()
<|end_body_0|>
<|body_start_1|>
from .risk_service_principal_activity import RiskServicePrincipalActivity
from .risky_service_principal import RiskySer... | RiskyServicePrincipalHistoryItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RiskyServicePrincipalHistoryItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskyServicePrincipalHistoryItem:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminat... | stack_v2_sparse_classes_36k_train_005724 | 2,742 | 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: RiskyServicePrincipalHistoryItem",
"name": "create_from_discriminator_value",
"signature": "def create_from_... | 3 | null | Implement the Python class `RiskyServicePrincipalHistoryItem` described below.
Class description:
Implement the RiskyServicePrincipalHistoryItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskyServicePrincipalHistoryItem: Creates a new insta... | Implement the Python class `RiskyServicePrincipalHistoryItem` described below.
Class description:
Implement the RiskyServicePrincipalHistoryItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskyServicePrincipalHistoryItem: Creates a new insta... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class RiskyServicePrincipalHistoryItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskyServicePrincipalHistoryItem:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RiskyServicePrincipalHistoryItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskyServicePrincipalHistoryItem:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and c... | the_stack_v2_python_sparse | msgraph/generated/models/risky_service_principal_history_item.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
3a56af78b21b83b75d8f573ed0f772507b219461 | [
"if not root:\n return '[]'\nqueue = collections.deque([root])\nans = []\nwhile queue:\n node = queue.popleft()\n if not node:\n ans.append('null')\n continue\n ans.append(str(node.val))\n queue.extend([node.left, node.right])\nreturn '[' + ','.join(ans) + ']'",
"vals = collections.de... | <|body_start_0|>
if not root:
return '[]'
queue = collections.deque([root])
ans = []
while queue:
node = queue.popleft()
if not node:
ans.append('null')
continue
ans.append(str(node.val))
queue.ex... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_005725 | 1,565 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_019974 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 35cc05c763b4622aacd9d1166ded2fa320b7ceaf | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '[]'
queue = collections.deque([root])
ans = []
while queue:
node = queue.popleft()
if not node:
... | the_stack_v2_python_sparse | 297.Serialize_and_Deserialize_Binary_Tree(BFS).py | simonzg/leetcode-solutions | train | 0 | |
5aec9db14569e309175b32a02b06b72e3c1c92b4 | [
"if warmup_type is not None:\n if not isinstance(warmup_iters, int) or warmup_iters <= 0:\n raise ValueError('\"warmup_iters\" must be a positive integer')\n if not isinstance(warmup_ratio, float) or warmup_ratio <= 0 or warmup_ratio > 1.0:\n raise ValueError('\"warmup_ratio\" must be in range (... | <|body_start_0|>
if warmup_type is not None:
if not isinstance(warmup_iters, int) or warmup_iters <= 0:
raise ValueError('"warmup_iters" must be a positive integer')
if not isinstance(warmup_ratio, float) or warmup_ratio <= 0 or warmup_ratio > 1.0:
raise V... | Multiple Step learning rate with warm up. :param milestones: list of decay epochs :type milestones: list of int :param decay_rates: list of decay rates :type decay_rates: list of float :param warmup: whether to warm up :type warmup: bool :param epoch_steps: steps in one epoch :type epoch_steps: int | WarmupScheduler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WarmupScheduler:
"""Multiple Step learning rate with warm up. :param milestones: list of decay epochs :type milestones: list of int :param decay_rates: list of decay rates :type decay_rates: list of float :param warmup: whether to warm up :type warmup: bool :param epoch_steps: steps in one epoch ... | stack_v2_sparse_classes_36k_train_005726 | 3,827 | permissive | [
{
"docstring": "Init WarmupScheduler.",
"name": "__init__",
"signature": "def __init__(self, optimizer, warmup_type='linear', warmup_iters=0, warmup_ratio=0.1, after_scheduler_config=None, **kwargs)"
},
{
"docstring": "Get lr.",
"name": "get_lr",
"signature": "def get_lr(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_016520 | Implement the Python class `WarmupScheduler` described below.
Class description:
Multiple Step learning rate with warm up. :param milestones: list of decay epochs :type milestones: list of int :param decay_rates: list of decay rates :type decay_rates: list of float :param warmup: whether to warm up :type warmup: bool ... | Implement the Python class `WarmupScheduler` described below.
Class description:
Multiple Step learning rate with warm up. :param milestones: list of decay epochs :type milestones: list of int :param decay_rates: list of decay rates :type decay_rates: list of float :param warmup: whether to warm up :type warmup: bool ... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class WarmupScheduler:
"""Multiple Step learning rate with warm up. :param milestones: list of decay epochs :type milestones: list of int :param decay_rates: list of decay rates :type decay_rates: list of float :param warmup: whether to warm up :type warmup: bool :param epoch_steps: steps in one epoch ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WarmupScheduler:
"""Multiple Step learning rate with warm up. :param milestones: list of decay epochs :type milestones: list of int :param decay_rates: list of decay rates :type decay_rates: list of float :param warmup: whether to warm up :type warmup: bool :param epoch_steps: steps in one epoch :type epoch_s... | the_stack_v2_python_sparse | zeus/trainer/modules/lr_schedulers/warmup_scheduler_torch.py | huawei-noah/xingtian | train | 308 |
597d7e6d95ae2fc71a6538f2edb728236aae1488 | [
"self.page_id = page_id\nself.form_classes = form_classes\npage_class = AccountPage.registry.get('page_id', page_id)\nassert page_class is not None\nfor form_class in form_classes:\n page_class.add_form(form_class)",
"page_class = AccountPage.registry.get('page_id', self.page_id)\nassert page_class is not None... | <|body_start_0|>
self.page_id = page_id
self.form_classes = form_classes
page_class = AccountPage.registry.get('page_id', page_id)
assert page_class is not None
for form_class in form_classes:
page_class.add_form(form_class)
<|end_body_0|>
<|body_start_1|>
pa... | A hook for adding new forms to a page in the My Account page. This is used to add custom forms to a page in the My Account page. The form can be used to provide user-level customization of an extension, through a traditional form-based approach or even through custom JavaScript. This hook takes the ID of a registered p... | AccountPageFormsHook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountPageFormsHook:
"""A hook for adding new forms to a page in the My Account page. This is used to add custom forms to a page in the My Account page. The form can be used to provide user-level customization of an extension, through a traditional form-based approach or even through custom Java... | stack_v2_sparse_classes_36k_train_005727 | 3,261 | permissive | [
{
"docstring": "Initialize the hook. This will register each of the provided page form classes on the account page matching the provided ID. Args: page_id (unicode): The page ID corresponding to a registered :py:class:`~reviewboard.accounts.pages.AccountPage`. form_classes (list of type): The list of form class... | 2 | null | Implement the Python class `AccountPageFormsHook` described below.
Class description:
A hook for adding new forms to a page in the My Account page. This is used to add custom forms to a page in the My Account page. The form can be used to provide user-level customization of an extension, through a traditional form-bas... | Implement the Python class `AccountPageFormsHook` described below.
Class description:
A hook for adding new forms to a page in the My Account page. This is used to add custom forms to a page in the My Account page. The form can be used to provide user-level customization of an extension, through a traditional form-bas... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class AccountPageFormsHook:
"""A hook for adding new forms to a page in the My Account page. This is used to add custom forms to a page in the My Account page. The form can be used to provide user-level customization of an extension, through a traditional form-based approach or even through custom Java... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountPageFormsHook:
"""A hook for adding new forms to a page in the My Account page. This is used to add custom forms to a page in the My Account page. The form can be used to provide user-level customization of an extension, through a traditional form-based approach or even through custom JavaScript. This ... | the_stack_v2_python_sparse | reviewboard/extensions/hooks/account_page.py | reviewboard/reviewboard | train | 1,141 |
09bda41fa073c3e9ecdc3e92343d94b8c2a3172b | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center. | MerchantCenterLinkServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MerchantCenterLinkServiceServicer:
"""Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center."""
def ListMerchantCenterLinks(self, request, context):
"""Returns Merchant Center links available for th... | stack_v2_sparse_classes_36k_train_005728 | 4,994 | permissive | [
{
"docstring": "Returns Merchant Center links available for this customer.",
"name": "ListMerchantCenterLinks",
"signature": "def ListMerchantCenterLinks(self, request, context)"
},
{
"docstring": "Returns the Merchant Center link in full detail.",
"name": "GetMerchantCenterLink",
"signa... | 3 | stack_v2_sparse_classes_30k_train_007687 | Implement the Python class `MerchantCenterLinkServiceServicer` described below.
Class description:
Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center.
Method signatures and docstrings:
- def ListMerchantCenterLinks(self, request,... | Implement the Python class `MerchantCenterLinkServiceServicer` described below.
Class description:
Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center.
Method signatures and docstrings:
- def ListMerchantCenterLinks(self, request,... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class MerchantCenterLinkServiceServicer:
"""Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center."""
def ListMerchantCenterLinks(self, request, context):
"""Returns Merchant Center links available for th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MerchantCenterLinkServiceServicer:
"""Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center."""
def ListMerchantCenterLinks(self, request, context):
"""Returns Merchant Center links available for this customer."... | the_stack_v2_python_sparse | google/ads/google_ads/v3/proto/services/merchant_center_link_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
9d0311eee66d247c2e9b7f04a8f3221b3a29d538 | [
"if num_rows == 1 or num_rows >= len(s):\n return s\nresult = []\ncycle = 2 * num_rows - 2\nfor row in range(num_rows):\n for curr in range(row, len(s), cycle):\n result.append(s[curr])\n mid_row_index = curr + cycle - 2 * row\n if row != 0 and row != num_rows - 1 and (mid_row_index < len... | <|body_start_0|>
if num_rows == 1 or num_rows >= len(s):
return s
result = []
cycle = 2 * num_rows - 2
for row in range(num_rows):
for curr in range(row, len(s), cycle):
result.append(s[curr])
mid_row_index = curr + cycle - 2 * row
... | ZigZag | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigZag:
def convert_(self, s: str, num_rows: int) -> str:
"""Approach: Visit By Row Time Complexity: O(N) Space Complexity: O(N) :param s: :param num_rows: :return:"""
<|body_0|>
def convert(self, s: str, num_rows: int) -> str:
"""Approach: Sort by Row Time Complexit... | stack_v2_sparse_classes_36k_train_005729 | 1,651 | no_license | [
{
"docstring": "Approach: Visit By Row Time Complexity: O(N) Space Complexity: O(N) :param s: :param num_rows: :return:",
"name": "convert_",
"signature": "def convert_(self, s: str, num_rows: int) -> str"
},
{
"docstring": "Approach: Sort by Row Time Complexity: O(N) Space Complexity: O(N) :par... | 2 | null | Implement the Python class `ZigZag` described below.
Class description:
Implement the ZigZag class.
Method signatures and docstrings:
- def convert_(self, s: str, num_rows: int) -> str: Approach: Visit By Row Time Complexity: O(N) Space Complexity: O(N) :param s: :param num_rows: :return:
- def convert(self, s: str, ... | Implement the Python class `ZigZag` described below.
Class description:
Implement the ZigZag class.
Method signatures and docstrings:
- def convert_(self, s: str, num_rows: int) -> str: Approach: Visit By Row Time Complexity: O(N) Space Complexity: O(N) :param s: :param num_rows: :return:
- def convert(self, s: str, ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class ZigZag:
def convert_(self, s: str, num_rows: int) -> str:
"""Approach: Visit By Row Time Complexity: O(N) Space Complexity: O(N) :param s: :param num_rows: :return:"""
<|body_0|>
def convert(self, s: str, num_rows: int) -> str:
"""Approach: Sort by Row Time Complexit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZigZag:
def convert_(self, s: str, num_rows: int) -> str:
"""Approach: Visit By Row Time Complexity: O(N) Space Complexity: O(N) :param s: :param num_rows: :return:"""
if num_rows == 1 or num_rows >= len(s):
return s
result = []
cycle = 2 * num_rows - 2
for ... | the_stack_v2_python_sparse | revisited__2021/math_and_string/zig_zag_conversion.py | Shiv2157k/leet_code | train | 1 | |
549a62c3978d203bf422081bad0566a6af0bd3bc | [
"results = []\n\ndef strSerialize(node):\n if node:\n results.append(str(node.val))\n strSerialize(node.left)\n strSerialize(node.right)\n else:\n results.append('None')\nstrSerialize(root)\nresultStr = ' '.join(results)\nreturn resultStr",
"def strDeserialize(nodes):\n if nod... | <|body_start_0|>
results = []
def strSerialize(node):
if node:
results.append(str(node.val))
strSerialize(node.left)
strSerialize(node.right)
else:
results.append('None')
strSerialize(root)
resultStr... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_005730 | 2,652 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_009154 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 453e92109494c962c36280cd0d32fb28aa771615 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
results = []
def strSerialize(node):
if node:
results.append(str(node.val))
strSerialize(node.left)
strSerialize(node... | the_stack_v2_python_sparse | Python/leetcode_297_serialize_and_deserialize_binary_tree.py | bakker4444/Algorithms | train | 1 | |
311a75d990d50170b1aa6a228895890966cf193a | [
"import yfinance as yf\nif start is not None:\n start = to_tzaware_datetime(start, tz=get_local_tz())\nif end is not None:\n end = to_tzaware_datetime(end, tz=get_local_tz())\nreturn yf.Ticker(symbol).history(period=period, start=start, end=end, **kwargs)",
"download_kwargs = self.select_symbol_kwargs(symbo... | <|body_start_0|>
import yfinance as yf
if start is not None:
start = to_tzaware_datetime(start, tz=get_local_tz())
if end is not None:
end = to_tzaware_datetime(end, tz=get_local_tz())
return yf.Ticker(symbol).history(period=period, start=start, end=end, **kwargs)... | `Data` for data coming from `yfinance`. Stocks are usually in the timezone "+0500" and cryptocurrencies in UTC. !!! warning Data coming from Yahoo is not the most stable data out there. Yahoo may manipulate data how they want, add noise, return missing data points (see volume in the example below), etc. It's only used ... | YFData | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YFData:
"""`Data` for data coming from `yfinance`. Stocks are usually in the timezone "+0500" and cryptocurrencies in UTC. !!! warning Data coming from Yahoo is not the most stable data out there. Yahoo may manipulate data how they want, add noise, return missing data points (see volume in the ex... | stack_v2_sparse_classes_36k_train_005731 | 30,831 | permissive | [
{
"docstring": "Download the symbol. Args: symbol (str): Symbol. period (str): Period. start (any): Start datetime. See `vectorbt.utils.datetime.to_tzaware_datetime`. end (any): End datetime. See `vectorbt.utils.datetime.to_tzaware_datetime`. **kwargs: Keyword arguments passed to `yfinance.base.TickerBase.histo... | 2 | stack_v2_sparse_classes_30k_train_019486 | Implement the Python class `YFData` described below.
Class description:
`Data` for data coming from `yfinance`. Stocks are usually in the timezone "+0500" and cryptocurrencies in UTC. !!! warning Data coming from Yahoo is not the most stable data out there. Yahoo may manipulate data how they want, add noise, return mi... | Implement the Python class `YFData` described below.
Class description:
`Data` for data coming from `yfinance`. Stocks are usually in the timezone "+0500" and cryptocurrencies in UTC. !!! warning Data coming from Yahoo is not the most stable data out there. Yahoo may manipulate data how they want, add noise, return mi... | 0cd596e1be975d4af6379d883090ffb5b7375d08 | <|skeleton|>
class YFData:
"""`Data` for data coming from `yfinance`. Stocks are usually in the timezone "+0500" and cryptocurrencies in UTC. !!! warning Data coming from Yahoo is not the most stable data out there. Yahoo may manipulate data how they want, add noise, return missing data points (see volume in the ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YFData:
"""`Data` for data coming from `yfinance`. Stocks are usually in the timezone "+0500" and cryptocurrencies in UTC. !!! warning Data coming from Yahoo is not the most stable data out there. Yahoo may manipulate data how they want, add noise, return missing data points (see volume in the example below),... | the_stack_v2_python_sparse | vectorbt/data/custom.py | davidandreoletti/vectorbt | train | 0 |
84dd5d6faa6bffacc1ac1f1c3e58d183bb5f4719 | [
"letters = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\nresult = 0\nfor pos in range(len(s)):\n if pos < len(s) - 1 and letters[s[pos]] < letters[s[pos + 1]]:\n result -= letters[s[pos]]\n else:\n result += letters[s[pos]]\nreturn result",
"import re\nletters = {'I': 1, '... | <|body_start_0|>
letters = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = 0
for pos in range(len(s)):
if pos < len(s) - 1 and letters[s[pos]] < letters[s[pos + 1]]:
result -= letters[s[pos]]
else:
result += lette... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def romanToInt(self, s: str) -> int:
"""普通循环解法 :param s: :return:"""
<|body_0|>
def romanToIntByRE(self, s: str) -> int:
"""使用正则表达式的解法 :param s: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
letters = {'I': 1, 'V': 5, 'X': 10, '... | stack_v2_sparse_classes_36k_train_005732 | 1,373 | no_license | [
{
"docstring": "普通循环解法 :param s: :return:",
"name": "romanToInt",
"signature": "def romanToInt(self, s: str) -> int"
},
{
"docstring": "使用正则表达式的解法 :param s: :return:",
"name": "romanToIntByRE",
"signature": "def romanToIntByRE(self, s: str) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_017134 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def romanToInt(self, s: str) -> int: 普通循环解法 :param s: :return:
- def romanToIntByRE(self, s: str) -> int: 使用正则表达式的解法 :param s: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def romanToInt(self, s: str) -> int: 普通循环解法 :param s: :return:
- def romanToIntByRE(self, s: str) -> int: 使用正则表达式的解法 :param s: :return:
<|skeleton|>
class Solution:
def rom... | 976d9185eca401587000dab56b6330542bc8437c | <|skeleton|>
class Solution:
def romanToInt(self, s: str) -> int:
"""普通循环解法 :param s: :return:"""
<|body_0|>
def romanToIntByRE(self, s: str) -> int:
"""使用正则表达式的解法 :param s: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def romanToInt(self, s: str) -> int:
"""普通循环解法 :param s: :return:"""
letters = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = 0
for pos in range(len(s)):
if pos < len(s) - 1 and letters[s[pos]] < letters[s[pos + 1]]:
... | the_stack_v2_python_sparse | leetcode/algorithm/13.py | baiasuka/PyhtonStudy | train | 0 | |
5f938d7858cd85b5b4c68d2639ff06f084747f35 | [
"self.rows = []\nself.variables_places = {}\ni = 0\nfor var in variables:\n self.variables_places[var] = i\n i += 1",
"if len(values) != len(self.variables_places.keys()):\n raise ValueError('Invalid number of values. Should be equal to a number of variables')\nself.rows.append(self.Row(probability, valu... | <|body_start_0|>
self.rows = []
self.variables_places = {}
i = 0
for var in variables:
self.variables_places[var] = i
i += 1
<|end_body_0|>
<|body_start_1|>
if len(values) != len(self.variables_places.keys()):
raise ValueError('Invalid number ... | ProbabilityDistribution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProbabilityDistribution:
def __init__(self, variables):
""":param variables iterable(str): names of all variables in this probability distribution"""
<|body_0|>
def set(self, probability, values):
"""Add probability of variables in probability distribution to have sp... | stack_v2_sparse_classes_36k_train_005733 | 20,140 | no_license | [
{
"docstring": ":param variables iterable(str): names of all variables in this probability distribution",
"name": "__init__",
"signature": "def __init__(self, variables)"
},
{
"docstring": "Add probability of variables in probability distribution to have specified values. :param probability: pro... | 3 | stack_v2_sparse_classes_30k_train_018242 | Implement the Python class `ProbabilityDistribution` described below.
Class description:
Implement the ProbabilityDistribution class.
Method signatures and docstrings:
- def __init__(self, variables): :param variables iterable(str): names of all variables in this probability distribution
- def set(self, probability, ... | Implement the Python class `ProbabilityDistribution` described below.
Class description:
Implement the ProbabilityDistribution class.
Method signatures and docstrings:
- def __init__(self, variables): :param variables iterable(str): names of all variables in this probability distribution
- def set(self, probability, ... | 32a9b9158d73dc80b355993a5a5f8fc49ae25334 | <|skeleton|>
class ProbabilityDistribution:
def __init__(self, variables):
""":param variables iterable(str): names of all variables in this probability distribution"""
<|body_0|>
def set(self, probability, values):
"""Add probability of variables in probability distribution to have sp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProbabilityDistribution:
def __init__(self, variables):
""":param variables iterable(str): names of all variables in this probability distribution"""
self.rows = []
self.variables_places = {}
i = 0
for var in variables:
self.variables_places[var] = i
... | the_stack_v2_python_sparse | aima/core/probability/algorithms.py | afcarl/aima-python-mushketyk | train | 1 | |
50839c32e3b143a425efe2b0520147c345546c82 | [
"hash_map = {}\nfor v in s:\n hash_map[v] = hash_map.get(v, 0) + 1\nfor v in t:\n if hash_map.get(v, 'Null') == 'Null' or hash_map.get(v, 'Null') == 0:\n return v\n hash_map[v] -= 1",
"res = 0\nfor v in s:\n res = res ^ ord(v)\nfor v in t:\n res = res ^ ord(v)\nreturn chr(res)"
] | <|body_start_0|>
hash_map = {}
for v in s:
hash_map[v] = hash_map.get(v, 0) + 1
for v in t:
if hash_map.get(v, 'Null') == 'Null' or hash_map.get(v, 'Null') == 0:
return v
hash_map[v] -= 1
<|end_body_0|>
<|body_start_1|>
res = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTheDifference(self, s, t):
""":type s: str :type t: str :rtype: str"""
<|body_0|>
def findTheDifference1(self, s, t):
""":type s: str :type t: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
hash_map = {}
fo... | stack_v2_sparse_classes_36k_train_005734 | 713 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: str",
"name": "findTheDifference",
"signature": "def findTheDifference(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: str",
"name": "findTheDifference1",
"signature": "def findTheDifference1(self, s, t)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTheDifference(self, s, t): :type s: str :type t: str :rtype: str
- def findTheDifference1(self, s, t): :type s: str :type t: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTheDifference(self, s, t): :type s: str :type t: str :rtype: str
- def findTheDifference1(self, s, t): :type s: str :type t: str :rtype: str
<|skeleton|>
class Solution:... | 472f780c3214aab5c713612812d834ccbe589434 | <|skeleton|>
class Solution:
def findTheDifference(self, s, t):
""":type s: str :type t: str :rtype: str"""
<|body_0|>
def findTheDifference1(self, s, t):
""":type s: str :type t: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findTheDifference(self, s, t):
""":type s: str :type t: str :rtype: str"""
hash_map = {}
for v in s:
hash_map[v] = hash_map.get(v, 0) + 1
for v in t:
if hash_map.get(v, 'Null') == 'Null' or hash_map.get(v, 'Null') == 0:
retu... | the_stack_v2_python_sparse | 2/389-Find_the_Difference.py | ChangXiaodong/Leetcode-solutions | train | 4 | |
fe6ffdfdcd95bc4f3eb8154aa51fac8cbf0eb985 | [
"parent = request.GET.get('id', '')\nif not parent:\n return Response([])\nobj = ModuleTree.objects.filter(parent=parent)\ndata = ModuleTreeSer(obj, many=True).data\nreturn Response(data)",
"data = request.data\nobj = ModuleTree.objects.filter(id=data['id']).first()\nserializer = ModuleTreeSer(obj, data=data)\... | <|body_start_0|>
parent = request.GET.get('id', '')
if not parent:
return Response([])
obj = ModuleTree.objects.filter(parent=parent)
data = ModuleTreeSer(obj, many=True).data
return Response(data)
<|end_body_0|>
<|body_start_1|>
data = request.data
o... | ModuleCaseTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleCaseTree:
def get(self, request, *args, **kwargs):
"""模块列表"""
<|body_0|>
def put(self, request, *args, **kwargs):
"""编辑模块"""
<|body_1|>
def post(self, request, *args, **kwargs):
"""创建模块"""
<|body_2|>
def delete(self, request, *... | stack_v2_sparse_classes_36k_train_005735 | 9,587 | no_license | [
{
"docstring": "模块列表",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "编辑模块",
"name": "put",
"signature": "def put(self, request, *args, **kwargs)"
},
{
"docstring": "创建模块",
"name": "post",
"signature": "def post(self, request, *ar... | 4 | stack_v2_sparse_classes_30k_train_021521 | Implement the Python class `ModuleCaseTree` described below.
Class description:
Implement the ModuleCaseTree class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 模块列表
- def put(self, request, *args, **kwargs): 编辑模块
- def post(self, request, *args, **kwargs): 创建模块
- def delete(self, requ... | Implement the Python class `ModuleCaseTree` described below.
Class description:
Implement the ModuleCaseTree class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 模块列表
- def put(self, request, *args, **kwargs): 编辑模块
- def post(self, request, *args, **kwargs): 创建模块
- def delete(self, requ... | f2523d6e51cde1b53ac6f453f8066b4b90c523b9 | <|skeleton|>
class ModuleCaseTree:
def get(self, request, *args, **kwargs):
"""模块列表"""
<|body_0|>
def put(self, request, *args, **kwargs):
"""编辑模块"""
<|body_1|>
def post(self, request, *args, **kwargs):
"""创建模块"""
<|body_2|>
def delete(self, request, *... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModuleCaseTree:
def get(self, request, *args, **kwargs):
"""模块列表"""
parent = request.GET.get('id', '')
if not parent:
return Response([])
obj = ModuleTree.objects.filter(parent=parent)
data = ModuleTreeSer(obj, many=True).data
return Response(data)
... | the_stack_v2_python_sparse | api/interface/rest/interfaceManage.py | zhuzhanhao1/backend | train | 0 | |
0476ae4a3911cdb57dddab65f194e3502cdc11ad | [
"content = '\\n Hi {{ taster_first_name }},\\n\\n {% if verification_code %}\\n To allow you to enjoy all that Vinely has to offer, we have created a new account for you. Follow the following steps to activate your account.\\n <h3>Activate Account:</h3>\\n <table>\\n <tr>\\... | <|body_start_0|>
content = '\n Hi {{ taster_first_name }},\n\n {% if verification_code %}\n To allow you to enjoy all that Vinely has to offer, we have created a new account for you. Follow the following steps to activate your account.\n <h3>Activate Account:</h3>\n <table>\n ... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
content = '\n Hi {{ taster_first_name }},\n... | stack_v2_sparse_classes_36k_train_005736 | 4,199 | no_license | [
{
"docstring": "Write your forwards methods here.",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Write your backwards methods here.",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021006 | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here. | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here.
<|skeleton|>
class Migration:
def forwards(self,... | c5c7d8a0b1a297e07302870017d3fb03c5dbb009 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
content = '\n Hi {{ taster_first_name }},\n\n {% if verification_code %}\n To allow you to enjoy all that Vinely has to offer, we have created a new account for you. Follow the following steps to a... | the_stack_v2_python_sparse | cms/migrations/0016_add_welcome_email_template.py | RSV3/nuvine | train | 0 | |
9321b297db24abbafe12bf8e629a626aae4868fb | [
"if not nums:\n return [[]]\nres = []\nself.helper(res, [], nums)\nreturn res",
"total.append(part)\nif len(nums) == 1:\n total.append(part + [nums[0]])\n return\nfor i, e in enumerate(nums):\n self.helper(total, part + [e], nums[i + 1:])"
] | <|body_start_0|>
if not nums:
return [[]]
res = []
self.helper(res, [], nums)
return res
<|end_body_0|>
<|body_start_1|>
total.append(part)
if len(nums) == 1:
total.append(part + [nums[0]])
return
for i, e in enumerate(nums):
... | Solution description | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Solution description"""
def func(self, nums):
"""Solution function description"""
<|body_0|>
def helper(self, total, part, nums):
"""Solution function description"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
... | stack_v2_sparse_classes_36k_train_005737 | 795 | permissive | [
{
"docstring": "Solution function description",
"name": "func",
"signature": "def func(self, nums)"
},
{
"docstring": "Solution function description",
"name": "helper",
"signature": "def helper(self, total, part, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004108 | Implement the Python class `Solution` described below.
Class description:
Solution description
Method signatures and docstrings:
- def func(self, nums): Solution function description
- def helper(self, total, part, nums): Solution function description | Implement the Python class `Solution` described below.
Class description:
Solution description
Method signatures and docstrings:
- def func(self, nums): Solution function description
- def helper(self, total, part, nums): Solution function description
<|skeleton|>
class Solution:
"""Solution description"""
... | 869ee24c50c08403b170e8f7868699185e9dfdd1 | <|skeleton|>
class Solution:
"""Solution description"""
def func(self, nums):
"""Solution function description"""
<|body_0|>
def helper(self, total, part, nums):
"""Solution function description"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Solution description"""
def func(self, nums):
"""Solution function description"""
if not nums:
return [[]]
res = []
self.helper(res, [], nums)
return res
def helper(self, total, part, nums):
"""Solution function description"""
... | the_stack_v2_python_sparse | 78.Subsets/2.py | cerebrumaize/leetcode | train | 0 |
fd12abdcc467a7188572d9f5194d1fbecf3e7513 | [
"self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]",
"while len(self.x_values) < self.num_points:\n x_dir = choice([1, -1])\n x_dist = choice([0, 1, 2, 3, 4])\n x_step = x_dir * x_dist\n y_dir = choice([1, -1])\n y_dist = choice([0, 1, 2, 3, 4])\n y_step = y_dir * y_dist\n ... | <|body_start_0|>
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
while len(self.x_values) < self.num_points:
x_dir = choice([1, -1])
x_dist = choice([0, 1, 2, 3, 4])
x_step = x_dir * x_dist
... | A class to generate random walks. | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
"""A class to generate random walks."""
def __init__(self, num_points=5000):
"""Initialise attributes of a walk."""
<|body_0|>
def fill_walk(self):
"""Calculate all the points in the walk."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_005738 | 4,560 | no_license | [
{
"docstring": "Initialise attributes of a walk.",
"name": "__init__",
"signature": "def __init__(self, num_points=5000)"
},
{
"docstring": "Calculate all the points in the walk.",
"name": "fill_walk",
"signature": "def fill_walk(self)"
}
] | 2 | null | Implement the Python class `RandomWalk` described below.
Class description:
A class to generate random walks.
Method signatures and docstrings:
- def __init__(self, num_points=5000): Initialise attributes of a walk.
- def fill_walk(self): Calculate all the points in the walk. | Implement the Python class `RandomWalk` described below.
Class description:
A class to generate random walks.
Method signatures and docstrings:
- def __init__(self, num_points=5000): Initialise attributes of a walk.
- def fill_walk(self): Calculate all the points in the walk.
<|skeleton|>
class RandomWalk:
"""A ... | 8b55775c9f0ed49444becb35b8d529620537fa54 | <|skeleton|>
class RandomWalk:
"""A class to generate random walks."""
def __init__(self, num_points=5000):
"""Initialise attributes of a walk."""
<|body_0|>
def fill_walk(self):
"""Calculate all the points in the walk."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomWalk:
"""A class to generate random walks."""
def __init__(self, num_points=5000):
"""Initialise attributes of a walk."""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""Calculate all the points in the walk.""... | the_stack_v2_python_sparse | project2_data_visualisation/chapter15_generating_data/c15_examples.py | barcern/python-crash-course | train | 2 |
14d0405cae111922181435dc2ea901a3844e2a87 | [
"max_or = 0\nfor i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n xor = nums[i] ^ nums[j]\n if xor > max_or:\n max_or = xor\nreturn max_or",
"mx, mask = (0, 0)\nfor i in range(31, -1, -1):\n possible_mx = mx | 1 << i\n mask = mask | 1 << i\n bits = set()\n for n... | <|body_start_0|>
max_or = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
xor = nums[i] ^ nums[j]
if xor > max_or:
max_or = xor
return max_or
<|end_body_0|>
<|body_start_1|>
mx, mask = (0, 0)
for i in... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMaximumXOR(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMaximumXOR2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
max_or = 0
for i in range(len(... | stack_v2_sparse_classes_36k_train_005739 | 1,284 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMaximumXOR",
"signature": "def findMaximumXOR(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMaximumXOR2",
"signature": "def findMaximumXOR2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001380 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaximumXOR(self, nums): :type nums: List[int] :rtype: int
- def findMaximumXOR2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaximumXOR(self, nums): :type nums: List[int] :rtype: int
- def findMaximumXOR2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def find... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def findMaximumXOR(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMaximumXOR2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMaximumXOR(self, nums):
""":type nums: List[int] :rtype: int"""
max_or = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
xor = nums[i] ^ nums[j]
if xor > max_or:
max_or = xor
return... | the_stack_v2_python_sparse | 421. Maximum XOR of Two Numbers in an Array/maxOr.py | Macielyoung/LeetCode | train | 1 | |
c68673dc26d8cd9e067fd8dfeeeadf4269c7f239 | [
"len_list = 0\np = head\nwhile p:\n len_list = len_list + 1\n p = p.next\nif len_list == 0:\n return head\nfrom_front = len_list - n + 1\nif from_front == 1:\n return head.next\ncurr = head\nprev = head\nx = 1\nwhile x != from_front:\n prev = curr\n curr = curr.next\n x = x + 1\nprev.next = cur... | <|body_start_0|>
len_list = 0
p = head
while p:
len_list = len_list + 1
p = p.next
if len_list == 0:
return head
from_front = len_list - n + 1
if from_front == 1:
return head.next
curr = head
prev = head
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd2(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_005740 | 1,363 | no_license | [
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(self, head, n)"
},
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd2",
"signature": "def removeNthFromEnd2(sel... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd2(self, head, n): :type head: ListNode :type n: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd2(self, head, n): :type head: ListNode :type n: int :rtype: ListNode... | cd8470b4a7ee47b872b590b3682d0f3c59aa2199 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd2(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
len_list = 0
p = head
while p:
len_list = len_list + 1
p = p.next
if len_list == 0:
return head
from_front = len_list - n ... | the_stack_v2_python_sparse | delete_nth_node_from_end.py | manika1511/interview_prep | train | 0 | |
14d5768a422c980e5e409be1e2cc56efe52f5aea | [
"prefix_function = [0] * len(pattern)\nborder = 0\nfor i in range(1, len(pattern)):\n while border > 0 and pattern[i] != pattern[border]:\n border = prefix_function[border - 1]\n if pattern[i] == pattern[border]:\n border += 1\n else:\n border = 0\n prefix_function[i] = border\nretu... | <|body_start_0|>
prefix_function = [0] * len(pattern)
border = 0
for i in range(1, len(pattern)):
while border > 0 and pattern[i] != pattern[border]:
border = prefix_function[border - 1]
if pattern[i] == pattern[border]:
border += 1
... | Util | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Util:
def _compute_prefix_function(pattern):
"""Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the whole S. Examples: 'a' is a border of 'arba' 'ab' is a border of 'abcdab' 'abab' is a border ... | stack_v2_sparse_classes_36k_train_005741 | 2,665 | no_license | [
{
"docstring": "Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the whole S. Examples: 'a' is a border of 'arba' 'ab' is a border of 'abcdab' 'abab' is a border of 'ababab' 'ab' is not a border of 'ab' Definition: The... | 3 | stack_v2_sparse_classes_30k_train_013353 | Implement the Python class `Util` described below.
Class description:
Implement the Util class.
Method signatures and docstrings:
- def _compute_prefix_function(pattern): Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the ... | Implement the Python class `Util` described below.
Class description:
Implement the Util class.
Method signatures and docstrings:
- def _compute_prefix_function(pattern): Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the ... | 01dd6f0dadf62a520bcafafddf7bf2b79e8e2603 | <|skeleton|>
class Util:
def _compute_prefix_function(pattern):
"""Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the whole S. Examples: 'a' is a border of 'arba' 'ab' is a border of 'abcdab' 'abab' is a border ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Util:
def _compute_prefix_function(pattern):
"""Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the whole S. Examples: 'a' is a border of 'arba' 'ab' is a border of 'abcdab' 'abab' is a border of 'ababab' 'a... | the_stack_v2_python_sparse | course4-strings/practice/knuth_morris_pratt/knuth_morris_pratt.py | dmitri-mamrukov/coursera-data-structures-and-algorithms | train | 1 | |
3fd0f8a80e2687472efde5a91ec8037e95c57006 | [
"data = self.data\nid_ = data['entity']['id']\nreturn f'{PLATFORM_URL}assignments/{id_}'",
"available = super().available\ndata = self.data\nto_role = data['to_role']\nreturn to_role == 'professional_user' and available"
] | <|body_start_0|>
data = self.data
id_ = data['entity']['id']
return f'{PLATFORM_URL}assignments/{id_}'
<|end_body_0|>
<|body_start_1|>
available = super().available
data = self.data
to_role = data['to_role']
return to_role == 'professional_user' and available
<|e... | Email to creative on new comment created. | CommentCreatedToCreative | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentCreatedToCreative:
"""Email to creative on new comment created."""
def action_url(self) -> str:
"""Action URL."""
<|body_0|>
def available(self) -> bool:
"""Check if this action is available."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_005742 | 5,020 | no_license | [
{
"docstring": "Action URL.",
"name": "action_url",
"signature": "def action_url(self) -> str"
},
{
"docstring": "Check if this action is available.",
"name": "available",
"signature": "def available(self) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_val_001062 | Implement the Python class `CommentCreatedToCreative` described below.
Class description:
Email to creative on new comment created.
Method signatures and docstrings:
- def action_url(self) -> str: Action URL.
- def available(self) -> bool: Check if this action is available. | Implement the Python class `CommentCreatedToCreative` described below.
Class description:
Email to creative on new comment created.
Method signatures and docstrings:
- def action_url(self) -> str: Action URL.
- def available(self) -> bool: Check if this action is available.
<|skeleton|>
class CommentCreatedToCreativ... | cca179f55ebc3c420426eff59b23d7c8963ca9a3 | <|skeleton|>
class CommentCreatedToCreative:
"""Email to creative on new comment created."""
def action_url(self) -> str:
"""Action URL."""
<|body_0|>
def available(self) -> bool:
"""Check if this action is available."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentCreatedToCreative:
"""Email to creative on new comment created."""
def action_url(self) -> str:
"""Action URL."""
data = self.data
id_ = data['entity']['id']
return f'{PLATFORM_URL}assignments/{id_}'
def available(self) -> bool:
"""Check if this action ... | the_stack_v2_python_sparse | src/briefy/choreographer/actions/mail/leica/comment.py | BriefyHQ/briefy.choreographer | train | 0 |
26fd4fa80efe8df3f9ebc1ca3b6d82df6c6c10a6 | [
"super(VSFD, self).__init__()\nself.char_num = char_num\nself.fc0 = paddle.nn.Linear(in_features=in_channels * 2, out_features=pvam_ch)\nself.fc1 = paddle.nn.Linear(in_features=pvam_ch, out_features=self.char_num)",
"b, t, c1 = pvam_feature.shape\nb, t, c2 = gsrm_feature.shape\ncombine_feature_ = paddle.concat([p... | <|body_start_0|>
super(VSFD, self).__init__()
self.char_num = char_num
self.fc0 = paddle.nn.Linear(in_features=in_channels * 2, out_features=pvam_ch)
self.fc1 = paddle.nn.Linear(in_features=pvam_ch, out_features=self.char_num)
<|end_body_0|>
<|body_start_1|>
b, t, c1 = pvam_feat... | VSFD | VSFD | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VSFD:
"""VSFD"""
def __init__(self, in_channels=512, pvam_ch=512, char_num=38):
"""init"""
<|body_0|>
def forward(self, pvam_feature, gsrm_feature):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(VSFD, self).__init__()
... | stack_v2_sparse_classes_36k_train_005743 | 1,291 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, in_channels=512, pvam_ch=512, char_num=38)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, pvam_feature, gsrm_feature)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006391 | Implement the Python class `VSFD` described below.
Class description:
VSFD
Method signatures and docstrings:
- def __init__(self, in_channels=512, pvam_ch=512, char_num=38): init
- def forward(self, pvam_feature, gsrm_feature): forward | Implement the Python class `VSFD` described below.
Class description:
VSFD
Method signatures and docstrings:
- def __init__(self, in_channels=512, pvam_ch=512, char_num=38): init
- def forward(self, pvam_feature, gsrm_feature): forward
<|skeleton|>
class VSFD:
"""VSFD"""
def __init__(self, in_channels=512, ... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class VSFD:
"""VSFD"""
def __init__(self, in_channels=512, pvam_ch=512, char_num=38):
"""init"""
<|body_0|>
def forward(self, pvam_feature, gsrm_feature):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VSFD:
"""VSFD"""
def __init__(self, in_channels=512, pvam_ch=512, char_num=38):
"""init"""
super(VSFD, self).__init__()
self.char_num = char_num
self.fc0 = paddle.nn.Linear(in_features=in_channels * 2, out_features=pvam_ch)
self.fc1 = paddle.nn.Linear(in_features=p... | the_stack_v2_python_sparse | framework/e2e/moduletrans/diy/layer/VSFD.py | PaddlePaddle/PaddleTest | train | 42 |
6544b630174ec46621b87b7fff5e3fddeef21266 | [
"url = self.trimUrlPrefix(urlTrait.url)\nif url and self.isTnsStyle(url):\n EMPTY = OracleTnsRecordParser.EMPTY\n obj = OracleTnsRecordParser().parse(url)\n uniqueHostCount = self._countUniqueHosts(obj)\n description = self._getDescription(obj)\n serviceName = description.connect_data.service_name\n ... | <|body_start_0|>
url = self.trimUrlPrefix(urlTrait.url)
if url and self.isTnsStyle(url):
EMPTY = OracleTnsRecordParser.EMPTY
obj = OracleTnsRecordParser().parse(url)
uniqueHostCount = self._countUniqueHosts(obj)
description = self._getDescription(obj)
... | OracleThinNoSidCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OracleThinNoSidCase:
def isApplicableUrlTrait(self, urlTrait):
"""@types: jdbc_url_parser.Trait -> bool"""
<|body_0|>
def parse(self, url):
"""@types: str -> tuple[db.DatabaseServer]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
url = self.trimUrl... | stack_v2_sparse_classes_36k_train_005744 | 40,819 | no_license | [
{
"docstring": "@types: jdbc_url_parser.Trait -> bool",
"name": "isApplicableUrlTrait",
"signature": "def isApplicableUrlTrait(self, urlTrait)"
},
{
"docstring": "@types: str -> tuple[db.DatabaseServer]",
"name": "parse",
"signature": "def parse(self, url)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017681 | Implement the Python class `OracleThinNoSidCase` described below.
Class description:
Implement the OracleThinNoSidCase class.
Method signatures and docstrings:
- def isApplicableUrlTrait(self, urlTrait): @types: jdbc_url_parser.Trait -> bool
- def parse(self, url): @types: str -> tuple[db.DatabaseServer] | Implement the Python class `OracleThinNoSidCase` described below.
Class description:
Implement the OracleThinNoSidCase class.
Method signatures and docstrings:
- def isApplicableUrlTrait(self, urlTrait): @types: jdbc_url_parser.Trait -> bool
- def parse(self, url): @types: str -> tuple[db.DatabaseServer]
<|skeleton|... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class OracleThinNoSidCase:
def isApplicableUrlTrait(self, urlTrait):
"""@types: jdbc_url_parser.Trait -> bool"""
<|body_0|>
def parse(self, url):
"""@types: str -> tuple[db.DatabaseServer]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OracleThinNoSidCase:
def isApplicableUrlTrait(self, urlTrait):
"""@types: jdbc_url_parser.Trait -> bool"""
url = self.trimUrlPrefix(urlTrait.url)
if url and self.isTnsStyle(url):
EMPTY = OracleTnsRecordParser.EMPTY
obj = OracleTnsRecordParser().parse(url)
... | the_stack_v2_python_sparse | reference/ucmdb/discovery/jdbc_url_parser.py | madmonkyang/cda-record | train | 0 | |
1ca4406cb1e89827421dbbc75cb67129c45a324b | [
"self.tableid = tableid\nself.min_intersect = min_intersect\nself.max_intersect = max_intersect",
"image = dict(creator='MOL/com.google.earthengine.examples.mol.CountPolygonIntersect', args=[dict(type='FeatureCollection', table_id=self.tableid)])\nquery = dict(image=simplejson.dumps(image), bands='intersectionCou... | <|body_start_0|>
self.tableid = tableid
self.min_intersect = min_intersect
self.max_intersect = max_intersect
<|end_body_0|>
<|body_start_1|>
image = dict(creator='MOL/com.google.earthengine.examples.mol.CountPolygonIntersect', args=[dict(type='FeatureCollection', table_id=self.tableid)... | This class encapsulates a /mapid request to Earth Engine. When executed, this request returns a mapid and token that can be used to create tile URLs for tiling a Fusion Table table on a Google Map. | MapIdRequest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MapIdRequest:
"""This class encapsulates a /mapid request to Earth Engine. When executed, this request returns a mapid and token that can be used to create tile URLs for tiling a Fusion Table table on a Google Map."""
def __init__(self, tableid, min_intersect=1, max_intersect=32):
""... | stack_v2_sparse_classes_36k_train_005745 | 13,900 | permissive | [
{
"docstring": "Creates a new MapIdRequest object. Args: tableid - The Fusion Table table id. min_intersect - The min number of polygons to intersect. max_intersect - The max number of polygons to intersect.",
"name": "__init__",
"signature": "def __init__(self, tableid, min_intersect=1, max_intersect=3... | 2 | null | Implement the Python class `MapIdRequest` described below.
Class description:
This class encapsulates a /mapid request to Earth Engine. When executed, this request returns a mapid and token that can be used to create tile URLs for tiling a Fusion Table table on a Google Map.
Method signatures and docstrings:
- def __... | Implement the Python class `MapIdRequest` described below.
Class description:
This class encapsulates a /mapid request to Earth Engine. When executed, this request returns a mapid and token that can be used to create tile URLs for tiling a Fusion Table table on a Google Map.
Method signatures and docstrings:
- def __... | e3c50ee4ec8364c61cfff3ea68ece1098674f4d6 | <|skeleton|>
class MapIdRequest:
"""This class encapsulates a /mapid request to Earth Engine. When executed, this request returns a mapid and token that can be used to create tile URLs for tiling a Fusion Table table on a Google Map."""
def __init__(self, tableid, min_intersect=1, max_intersect=32):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MapIdRequest:
"""This class encapsulates a /mapid request to Earth Engine. When executed, this request returns a mapid and token that can be used to create tile URLs for tiling a Fusion Table table on a Google Map."""
def __init__(self, tableid, min_intersect=1, max_intersect=32):
"""Creates a ne... | the_stack_v2_python_sparse | earthengine/frontend.py | MapofLife/MOL | train | 19 |
b73cfe03513586c7e61535f4ead89d8d2deae389 | [
"def decorator(func):\n\n @api.expect((model, description))\n @api.response(ValidationError)\n @wraps(func)\n def wrapper(*args, **kwargs):\n payload = request.json\n try:\n schema = schema_override if schema_override else model.__schema__\n errors = process_config(co... | <|body_start_0|>
def decorator(func):
@api.expect((model, description))
@api.response(ValidationError)
@wraps(func)
def wrapper(*args, **kwargs):
payload = request.json
try:
schema = schema_override if schema_ov... | Extends a flask restx :class:`flask_restx.Api` with: - methods to make using json schemas easier - methods to auto document and handle :class:`ApiError` responses | API | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class API:
"""Extends a flask restx :class:`flask_restx.Api` with: - methods to make using json schemas easier - methods to auto document and handle :class:`ApiError` responses"""
def validate(self, model: Model, schema_override: Optional[Dict[str, List[Dict[str, str]]]]=None, description=None):
... | stack_v2_sparse_classes_36k_train_005746 | 15,675 | permissive | [
{
"docstring": "When a method is decorated with this, json data submitted to the endpoint will be validated with the given `model`. This also auto-documents the expected model, as well as the possible :class:`ValidationError` response.",
"name": "validate",
"signature": "def validate(self, model: Model,... | 3 | stack_v2_sparse_classes_30k_train_019615 | Implement the Python class `API` described below.
Class description:
Extends a flask restx :class:`flask_restx.Api` with: - methods to make using json schemas easier - methods to auto document and handle :class:`ApiError` responses
Method signatures and docstrings:
- def validate(self, model: Model, schema_override: ... | Implement the Python class `API` described below.
Class description:
Extends a flask restx :class:`flask_restx.Api` with: - methods to make using json schemas easier - methods to auto document and handle :class:`ApiError` responses
Method signatures and docstrings:
- def validate(self, model: Model, schema_override: ... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class API:
"""Extends a flask restx :class:`flask_restx.Api` with: - methods to make using json schemas easier - methods to auto document and handle :class:`ApiError` responses"""
def validate(self, model: Model, schema_override: Optional[Dict[str, List[Dict[str, str]]]]=None, description=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class API:
"""Extends a flask restx :class:`flask_restx.Api` with: - methods to make using json schemas easier - methods to auto document and handle :class:`ApiError` responses"""
def validate(self, model: Model, schema_override: Optional[Dict[str, List[Dict[str, str]]]]=None, description=None):
"""Whe... | the_stack_v2_python_sparse | flexget/api/app.py | BrutuZ/Flexget | train | 1 |
3e568022653bc773ad5f765681c8705fb8619820 | [
"file_name_to_id = {}\nsource_files = ScaleFile.objects.filter(id__in=input_file_ids, file_type='SOURCE')\nfor source_file in source_files:\n file_name_to_id[source_file.file_name] = source_file.id\nfor file_name in parse_results:\n if file_name not in file_name_to_id:\n continue\n src_file_id = fil... | <|body_start_0|>
file_name_to_id = {}
source_files = ScaleFile.objects.filter(id__in=input_file_ids, file_type='SOURCE')
for source_file in source_files:
file_name_to_id[source_file.file_name] = source_file.id
for file_name in parse_results:
if file_name not in fi... | Implements the data file parse saver to provide a way to save parse results for source files. | SourceDataFileParseSaver | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceDataFileParseSaver:
"""Implements the data file parse saver to provide a way to save parse results for source files."""
def save_parse_results(self, parse_results, input_file_ids):
"""See :meth:`job.configuration.data.data_file.AbstractDataFileParseSaver.save_parse_results`"""
... | stack_v2_sparse_classes_36k_train_005747 | 3,460 | permissive | [
{
"docstring": "See :meth:`job.configuration.data.data_file.AbstractDataFileParseSaver.save_parse_results`",
"name": "save_parse_results",
"signature": "def save_parse_results(self, parse_results, input_file_ids)"
},
{
"docstring": "Saves the given parse results to the source file for the given ... | 2 | stack_v2_sparse_classes_30k_train_008060 | Implement the Python class `SourceDataFileParseSaver` described below.
Class description:
Implements the data file parse saver to provide a way to save parse results for source files.
Method signatures and docstrings:
- def save_parse_results(self, parse_results, input_file_ids): See :meth:`job.configuration.data.dat... | Implement the Python class `SourceDataFileParseSaver` described below.
Class description:
Implements the data file parse saver to provide a way to save parse results for source files.
Method signatures and docstrings:
- def save_parse_results(self, parse_results, input_file_ids): See :meth:`job.configuration.data.dat... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class SourceDataFileParseSaver:
"""Implements the data file parse saver to provide a way to save parse results for source files."""
def save_parse_results(self, parse_results, input_file_ids):
"""See :meth:`job.configuration.data.data_file.AbstractDataFileParseSaver.save_parse_results`"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SourceDataFileParseSaver:
"""Implements the data file parse saver to provide a way to save parse results for source files."""
def save_parse_results(self, parse_results, input_file_ids):
"""See :meth:`job.configuration.data.data_file.AbstractDataFileParseSaver.save_parse_results`"""
file_... | the_stack_v2_python_sparse | scale/source/configuration/source_data_file.py | kfconsultant/scale | train | 0 |
73a4d3ad76877d05c40b2405b19c9bb27d39b183 | [
"if 0 <= amount <= 99999999:\n self.summary.record_deposit(account, amount)\nelse:\n raise ValueError('Invalid transaction value for agent mode')",
"if 0 <= amount <= 99999999:\n self.summary.record_withdraw(account, amount)\nelse:\n raise ValueError('Invalid transaction value for agent mode')",
"if... | <|body_start_0|>
if 0 <= amount <= 99999999:
self.summary.record_deposit(account, amount)
else:
raise ValueError('Invalid transaction value for agent mode')
<|end_body_0|>
<|body_start_1|>
if 0 <= amount <= 99999999:
self.summary.record_withdraw(account, amou... | AgentSession class is a child class of the abstract class "Session" It allows the user to perform privileged bank transactions - deposit, withdraw, transfer, create account and delete account It also verfies input looking for constraints and value error (invalid amount) | AgentSession | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgentSession:
"""AgentSession class is a child class of the abstract class "Session" It allows the user to perform privileged bank transactions - deposit, withdraw, transfer, create account and delete account It also verfies input looking for constraints and value error (invalid amount)"""
d... | stack_v2_sparse_classes_36k_train_005748 | 2,247 | no_license | [
{
"docstring": "Checks amount and makes deposit to account",
"name": "deposit",
"signature": "def deposit(self, account, amount)"
},
{
"docstring": "Checks amount and withdraws from account",
"name": "withdraw",
"signature": "def withdraw(self, account, amount)"
},
{
"docstring":... | 6 | stack_v2_sparse_classes_30k_train_016836 | Implement the Python class `AgentSession` described below.
Class description:
AgentSession class is a child class of the abstract class "Session" It allows the user to perform privileged bank transactions - deposit, withdraw, transfer, create account and delete account It also verfies input looking for constraints and... | Implement the Python class `AgentSession` described below.
Class description:
AgentSession class is a child class of the abstract class "Session" It allows the user to perform privileged bank transactions - deposit, withdraw, transfer, create account and delete account It also verfies input looking for constraints and... | 05d7e84158c162cdaa638d3856e07e6f93288863 | <|skeleton|>
class AgentSession:
"""AgentSession class is a child class of the abstract class "Session" It allows the user to perform privileged bank transactions - deposit, withdraw, transfer, create account and delete account It also verfies input looking for constraints and value error (invalid amount)"""
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgentSession:
"""AgentSession class is a child class of the abstract class "Session" It allows the user to perform privileged bank transactions - deposit, withdraw, transfer, create account and delete account It also verfies input looking for constraints and value error (invalid amount)"""
def deposit(se... | the_stack_v2_python_sparse | lib/frontend/agent_session.py | nine2k/simbank | train | 0 |
54c270469b8a3fc0c44ac3708de82357f003640b | [
"urls = ['https://data.unicef.org/resources/resource-type/publications/', 'https://data.unicef.org/resources/resource-type/guidance/']\nfor url in urls:\n self.logger.info('Initial url: %s', url)\n yield scrapy.Request(url=url, callback=self.parse, errback=self.on_error)",
"for href in response.css('.block-... | <|body_start_0|>
urls = ['https://data.unicef.org/resources/resource-type/publications/', 'https://data.unicef.org/resources/resource-type/guidance/']
for url in urls:
self.logger.info('Initial url: %s', url)
yield scrapy.Request(url=url, callback=self.parse, errback=self.on_erro... | UnicefSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnicefSpider:
def start_requests(self):
"""This sets up the urls to scrape for each years."""
<|body_0|>
def parse(self, response):
"""Parse the articles listing page and go to the next one. @url https://data.unicef.org/resources/resource-type/publications/ @returns ... | stack_v2_sparse_classes_36k_train_005749 | 2,668 | permissive | [
{
"docstring": "This sets up the urls to scrape for each years.",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "Parse the articles listing page and go to the next one. @url https://data.unicef.org/resources/resource-type/publications/ @returns items 0 0 @re... | 3 | null | Implement the Python class `UnicefSpider` described below.
Class description:
Implement the UnicefSpider class.
Method signatures and docstrings:
- def start_requests(self): This sets up the urls to scrape for each years.
- def parse(self, response): Parse the articles listing page and go to the next one. @url https:... | Implement the Python class `UnicefSpider` described below.
Class description:
Implement the UnicefSpider class.
Method signatures and docstrings:
- def start_requests(self): This sets up the urls to scrape for each years.
- def parse(self, response): Parse the articles listing page and go to the next one. @url https:... | 1aa42c7d8aaf0a91d033af8448a33f37563b0365 | <|skeleton|>
class UnicefSpider:
def start_requests(self):
"""This sets up the urls to scrape for each years."""
<|body_0|>
def parse(self, response):
"""Parse the articles listing page and go to the next one. @url https://data.unicef.org/resources/resource-type/publications/ @returns ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnicefSpider:
def start_requests(self):
"""This sets up the urls to scrape for each years."""
urls = ['https://data.unicef.org/resources/resource-type/publications/', 'https://data.unicef.org/resources/resource-type/guidance/']
for url in urls:
self.logger.info('Initial url... | the_stack_v2_python_sparse | pipeline/reach-scraper/wsf_scraping/spiders/unicef_spider.py | wellcometrust/reach | train | 12 | |
ad172e5a3e540aefdba0482081d3aa7db0343e33 | [
"capa = crear_capa()\nself.assertEqual(capa.metadatos is not None, True)\nself.assertEqual(capa.mapserverlayer is not None, True)",
"c = Client()\nresponse = c.get(reverse('layers:detalle_capa_por_id', args=(1,)))\nself.assertEqual(response.status_code, 404)\ncapa = crear_capa(nombre='prueba333')\nresponse = c.ge... | <|body_start_0|>
capa = crear_capa()
self.assertEqual(capa.metadatos is not None, True)
self.assertEqual(capa.mapserverlayer is not None, True)
<|end_body_0|>
<|body_start_1|>
c = Client()
response = c.get(reverse('layers:detalle_capa_por_id', args=(1,)))
self.assertEqua... | CapaMethodTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CapaMethodTests:
def test_crear_capa_crea_dependencias_1a1(self):
"""Toda Capa debe tener un Metadatos y un MapServerLayer"""
<|body_0|>
def test_detalle_capa_por_id(self):
"""Detalle Capa por id"""
<|body_1|>
def test_ultimas(self):
"""Test de u... | stack_v2_sparse_classes_36k_train_005750 | 2,901 | permissive | [
{
"docstring": "Toda Capa debe tener un Metadatos y un MapServerLayer",
"name": "test_crear_capa_crea_dependencias_1a1",
"signature": "def test_crear_capa_crea_dependencias_1a1(self)"
},
{
"docstring": "Detalle Capa por id",
"name": "test_detalle_capa_por_id",
"signature": "def test_deta... | 4 | stack_v2_sparse_classes_30k_val_000684 | Implement the Python class `CapaMethodTests` described below.
Class description:
Implement the CapaMethodTests class.
Method signatures and docstrings:
- def test_crear_capa_crea_dependencias_1a1(self): Toda Capa debe tener un Metadatos y un MapServerLayer
- def test_detalle_capa_por_id(self): Detalle Capa por id
- d... | Implement the Python class `CapaMethodTests` described below.
Class description:
Implement the CapaMethodTests class.
Method signatures and docstrings:
- def test_crear_capa_crea_dependencias_1a1(self): Toda Capa debe tener un Metadatos y un MapServerLayer
- def test_detalle_capa_por_id(self): Detalle Capa por id
- d... | e0f345ec137fe31f51ebf28b77e38fb8037fb978 | <|skeleton|>
class CapaMethodTests:
def test_crear_capa_crea_dependencias_1a1(self):
"""Toda Capa debe tener un Metadatos y un MapServerLayer"""
<|body_0|>
def test_detalle_capa_por_id(self):
"""Detalle Capa por id"""
<|body_1|>
def test_ultimas(self):
"""Test de u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CapaMethodTests:
def test_crear_capa_crea_dependencias_1a1(self):
"""Toda Capa debe tener un Metadatos y un MapServerLayer"""
capa = crear_capa()
self.assertEqual(capa.metadatos is not None, True)
self.assertEqual(capa.mapserverlayer is not None, True)
def test_detalle_cap... | the_stack_v2_python_sparse | layers/tests.py | pcecconi/mapground | train | 0 | |
8ca3bb7d0a77b2616ee8c42fcef8170fba3a01ea | [
"self._API_GETTERS['id', 'name', 'description'] = events.get_event if version.parse(connection.web_version) >= version.parse('11.3.0200') else objects.get_object_info\nif id is None and name is None:\n raise AttributeError(\"Please specify either 'name' or 'id' parameter in the constructor.\")\nif id is None:\n ... | <|body_start_0|>
self._API_GETTERS['id', 'name', 'description'] = events.get_event if version.parse(connection.web_version) >= version.parse('11.3.0200') else objects.get_object_info
if id is None and name is None:
raise AttributeError("Please specify either 'name' or 'id' parameter in the c... | Class representation of MicroStrategy Event object. Attributes: connection: A MicroStrategy connection object name: Event name id: Event ID description: Event descriptions | Event | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Event:
"""Class representation of MicroStrategy Event object. Attributes: connection: A MicroStrategy connection object name: Event name id: Event ID description: Event descriptions"""
def __init__(self, connection: Connection, id: str | None=None, name: str | None=None) -> None:
"""... | stack_v2_sparse_classes_36k_train_005751 | 5,223 | permissive | [
{
"docstring": "Initialize the Event object, populates it with I-Server data. Specify either `id` or `name`. When `id` is provided (not `None`), `name` is omitted. Args: connection: MicroStrategy connection object returned by `connection.Connection()`. id: Event ID name: Event name",
"name": "__init__",
... | 4 | null | Implement the Python class `Event` described below.
Class description:
Class representation of MicroStrategy Event object. Attributes: connection: A MicroStrategy connection object name: Event name id: Event ID description: Event descriptions
Method signatures and docstrings:
- def __init__(self, connection: Connecti... | Implement the Python class `Event` described below.
Class description:
Class representation of MicroStrategy Event object. Attributes: connection: A MicroStrategy connection object name: Event name id: Event ID description: Event descriptions
Method signatures and docstrings:
- def __init__(self, connection: Connecti... | c6cea33b15bcd876ded4de25138b3f5e5165cd6d | <|skeleton|>
class Event:
"""Class representation of MicroStrategy Event object. Attributes: connection: A MicroStrategy connection object name: Event name id: Event ID description: Event descriptions"""
def __init__(self, connection: Connection, id: str | None=None, name: str | None=None) -> None:
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Event:
"""Class representation of MicroStrategy Event object. Attributes: connection: A MicroStrategy connection object name: Event name id: Event ID description: Event descriptions"""
def __init__(self, connection: Connection, id: str | None=None, name: str | None=None) -> None:
"""Initialize th... | the_stack_v2_python_sparse | mstrio/distribution_services/event.py | MicroStrategy/mstrio-py | train | 84 |
c6cfc99ccce79f02271345604ef996051b94d76f | [
"super().__init__(name=metric.name, metric=metric, model_selection_operator=model_selection_operator, logdir=logdir)\nif processing_predictions is None:\n processing_predictions = {'fn': tf.argmax, 'kwargs': {'axis': -1}}\nself._processing_predictions = processing_predictions",
"for features, labels in context... | <|body_start_0|>
super().__init__(name=metric.name, metric=metric, model_selection_operator=model_selection_operator, logdir=logdir)
if processing_predictions is None:
processing_predictions = {'fn': tf.argmax, 'kwargs': {'axis': -1}}
self._processing_predictions = processing_predict... | Wrap a metric using `argmax` to extract predictions out of a classifier's output. | ClassifierMetric | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassifierMetric:
"""Wrap a metric using `argmax` to extract predictions out of a classifier's output."""
def __init__(self, metric: tf.keras.metrics.Metric, model_selection_operator: Callable=None, logdir: Union[Path, str]=Path().cwd() / 'log', processing_predictions=None) -> None:
... | stack_v2_sparse_classes_36k_train_005752 | 5,720 | permissive | [
{
"docstring": "Initialize the Metric. Args: metric (:py:class:`tf.keras.metrics.Metric`): The Keras Metric to use with the classifier (e.g.: Accuracy()). model_selection_operator (:py:obj:`typing.Callable`): The operation that will be used when `model_selection` is triggered to compare the metrics, used by the... | 2 | stack_v2_sparse_classes_30k_train_010766 | Implement the Python class `ClassifierMetric` described below.
Class description:
Wrap a metric using `argmax` to extract predictions out of a classifier's output.
Method signatures and docstrings:
- def __init__(self, metric: tf.keras.metrics.Metric, model_selection_operator: Callable=None, logdir: Union[Path, str]=... | Implement the Python class `ClassifierMetric` described below.
Class description:
Wrap a metric using `argmax` to extract predictions out of a classifier's output.
Method signatures and docstrings:
- def __init__(self, metric: tf.keras.metrics.Metric, model_selection_operator: Callable=None, logdir: Union[Path, str]=... | 92ac86fb0c962854e0d80c44165e0e7ff126b3c1 | <|skeleton|>
class ClassifierMetric:
"""Wrap a metric using `argmax` to extract predictions out of a classifier's output."""
def __init__(self, metric: tf.keras.metrics.Metric, model_selection_operator: Callable=None, logdir: Union[Path, str]=Path().cwd() / 'log', processing_predictions=None) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassifierMetric:
"""Wrap a metric using `argmax` to extract predictions out of a classifier's output."""
def __init__(self, metric: tf.keras.metrics.Metric, model_selection_operator: Callable=None, logdir: Union[Path, str]=Path().cwd() / 'log', processing_predictions=None) -> None:
"""Initialize... | the_stack_v2_python_sparse | src/ashpy/metrics/classifier.py | zurutech/ashpy | train | 89 |
2ca9c6a58e4e67f55f0e2a558466108e7481c789 | [
"course = handler.get_course()\nunits = course.get_units()\nprogramming_assignments = [unit for unit in units if unit.custom_unit_type == base.ProgAssignment.UNIT_TYPE_ID]\ntemplate_value = {'programming_assignments': programming_assignments}\nreturn jinja2.utils.Markup(handler.get_template('templates/prog_assignme... | <|body_start_0|>
course = handler.get_course()
units = course.get_units()
programming_assignments = [unit for unit in units if unit.custom_unit_type == base.ProgAssignment.UNIT_TYPE_ID]
template_value = {'programming_assignments': programming_assignments}
return jinja2.utils.Mark... | Handler for prog assignment test runs | ProgAssignmentTestRunHandler | [
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgAssignmentTestRunHandler:
"""Handler for prog assignment test runs"""
def display_html(cls, handler):
"""Landing page for viewing programming assignment test runs"""
<|body_0|>
def get_show_results(cls, handler):
"""GET endpoint to show the details of the lat... | stack_v2_sparse_classes_36k_train_005753 | 10,246 | permissive | [
{
"docstring": "Landing page for viewing programming assignment test runs",
"name": "display_html",
"signature": "def display_html(cls, handler)"
},
{
"docstring": "GET endpoint to show the details of the latest run of a programming assignment",
"name": "get_show_results",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_015373 | Implement the Python class `ProgAssignmentTestRunHandler` described below.
Class description:
Handler for prog assignment test runs
Method signatures and docstrings:
- def display_html(cls, handler): Landing page for viewing programming assignment test runs
- def get_show_results(cls, handler): GET endpoint to show t... | Implement the Python class `ProgAssignmentTestRunHandler` described below.
Class description:
Handler for prog assignment test runs
Method signatures and docstrings:
- def display_html(cls, handler): Landing page for viewing programming assignment test runs
- def get_show_results(cls, handler): GET endpoint to show t... | 2bca9d64499e160b2da9bed6e97fcda712feec72 | <|skeleton|>
class ProgAssignmentTestRunHandler:
"""Handler for prog assignment test runs"""
def display_html(cls, handler):
"""Landing page for viewing programming assignment test runs"""
<|body_0|>
def get_show_results(cls, handler):
"""GET endpoint to show the details of the lat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProgAssignmentTestRunHandler:
"""Handler for prog assignment test runs"""
def display_html(cls, handler):
"""Landing page for viewing programming assignment test runs"""
course = handler.get_course()
units = course.get_units()
programming_assignments = [unit for unit in un... | the_stack_v2_python_sparse | coursebuilder/modules/programming_assignments/dashboard.py | RavinderSinghPB/seek | train | 0 |
6ee5f055653976c1718c60519fcbaa73012dff60 | [
"result = []\nfor column in mapping.get_children():\n if excluded_keys is None or column.key not in excluded_keys:\n result.append(column.name)\nreturn result",
"for column in mapping.get_children():\n if column.key == key:\n return column.name\nreturn None",
"def get_column_description(colu... | <|body_start_0|>
result = []
for column in mapping.get_children():
if excluded_keys is None or column.key not in excluded_keys:
result.append(column.name)
return result
<|end_body_0|>
<|body_start_1|>
for column in mapping.get_children():
if colum... | QueryHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueryHelper:
def get_columns_list(cls, mapping: Table, excluded_keys=None) -> List[str]:
"""Returns list of columns's names from given SQLAlchemy Table object :param excluded_keys: Keys, which will be excluded from the list :param mapping: SQLAlchemy table :return: List of names"""
... | stack_v2_sparse_classes_36k_train_005754 | 6,307 | no_license | [
{
"docstring": "Returns list of columns's names from given SQLAlchemy Table object :param excluded_keys: Keys, which will be excluded from the list :param mapping: SQLAlchemy table :return: List of names",
"name": "get_columns_list",
"signature": "def get_columns_list(cls, mapping: Table, excluded_keys=... | 6 | stack_v2_sparse_classes_30k_train_016235 | Implement the Python class `QueryHelper` described below.
Class description:
Implement the QueryHelper class.
Method signatures and docstrings:
- def get_columns_list(cls, mapping: Table, excluded_keys=None) -> List[str]: Returns list of columns's names from given SQLAlchemy Table object :param excluded_keys: Keys, w... | Implement the Python class `QueryHelper` described below.
Class description:
Implement the QueryHelper class.
Method signatures and docstrings:
- def get_columns_list(cls, mapping: Table, excluded_keys=None) -> List[str]: Returns list of columns's names from given SQLAlchemy Table object :param excluded_keys: Keys, w... | d5e383a3a703c973d038627f35d405e716cfd25c | <|skeleton|>
class QueryHelper:
def get_columns_list(cls, mapping: Table, excluded_keys=None) -> List[str]:
"""Returns list of columns's names from given SQLAlchemy Table object :param excluded_keys: Keys, which will be excluded from the list :param mapping: SQLAlchemy table :return: List of names"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QueryHelper:
def get_columns_list(cls, mapping: Table, excluded_keys=None) -> List[str]:
"""Returns list of columns's names from given SQLAlchemy Table object :param excluded_keys: Keys, which will be excluded from the list :param mapping: SQLAlchemy table :return: List of names"""
result = []... | the_stack_v2_python_sparse | app/utils/helpers.py | Innodogs/Innodogs | train | 0 | |
44de0935ca52542716b1d09f355ccacc243141d3 | [
"m, n = (len(matrix), len(matrix[0]))\nself.sum = [[0] * n for _ in range(m)]\nself.sum[0][0] = matrix[0][0]\nfor i in range(1, n, 1):\n self.sum[0][i] = self.sum[0][i - 1] + matrix[0][i]\nfor j in range(1, m, 1):\n self.sum[j][0] = self.sum[j - 1][0] + matrix[j][0]\nfor i in range(1, m):\n for j in range(... | <|body_start_0|>
m, n = (len(matrix), len(matrix[0]))
self.sum = [[0] * n for _ in range(m)]
self.sum[0][0] = matrix[0][0]
for i in range(1, n, 1):
self.sum[0][i] = self.sum[0][i - 1] + matrix[0][i]
for j in range(1, m, 1):
self.sum[j][0] = self.sum[j - 1]... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_005755 | 1,584 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_005794 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | ad1eabfa27dda65b743d7d93524f1ec8f1e0ebfc | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
m, n = (len(matrix), len(matrix[0]))
self.sum = [[0] * n for _ in range(m)]
self.sum[0][0] = matrix[0][0]
for i in range(1, n, 1):
self.sum[0][i] = self.sum[0][i - 1] + matrix[0][i]
... | the_stack_v2_python_sparse | code/leetcode-304.py | kiyoxi2020/leetcode | train | 3 | |
bcf1b9c13fa954c345b9ae9778b1cea8e402d049 | [
"super(Logmap0, self).__init__()\nself.min_norm = min_norm\nself.norm_k = Norm(axis=-1, keep_dims=True)\nself.artanh = Artanh()\nself.norm_k = Norm(axis=-1, keep_dims=True)\nself.clamp_min = ClampMin()",
"sqrt_c = c ** 0.5\np_norm = self.clamp_min(self.norm_k(p), self.min_norm)\nscale = 1.0 / sqrt_c * self.artanh... | <|body_start_0|>
super(Logmap0, self).__init__()
self.min_norm = min_norm
self.norm_k = Norm(axis=-1, keep_dims=True)
self.artanh = Artanh()
self.norm_k = Norm(axis=-1, keep_dims=True)
self.clamp_min = ClampMin()
<|end_body_0|>
<|body_start_1|>
sqrt_c = c ** 0.5
... | logmap0 class | Logmap0 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logmap0:
"""logmap0 class"""
def __init__(self, min_norm):
"""init fun"""
<|body_0|>
def construct(self, p, c):
"""class construction"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Logmap0, self).__init__()
self.min_norm = min_nor... | stack_v2_sparse_classes_36k_train_005756 | 8,596 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, min_norm)"
},
{
"docstring": "class construction",
"name": "construct",
"signature": "def construct(self, p, c)"
}
] | 2 | null | Implement the Python class `Logmap0` described below.
Class description:
logmap0 class
Method signatures and docstrings:
- def __init__(self, min_norm): init fun
- def construct(self, p, c): class construction | Implement the Python class `Logmap0` described below.
Class description:
logmap0 class
Method signatures and docstrings:
- def __init__(self, min_norm): init fun
- def construct(self, p, c): class construction
<|skeleton|>
class Logmap0:
"""logmap0 class"""
def __init__(self, min_norm):
"""init fun"... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class Logmap0:
"""logmap0 class"""
def __init__(self, min_norm):
"""init fun"""
<|body_0|>
def construct(self, p, c):
"""class construction"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Logmap0:
"""logmap0 class"""
def __init__(self, min_norm):
"""init fun"""
super(Logmap0, self).__init__()
self.min_norm = min_norm
self.norm_k = Norm(axis=-1, keep_dims=True)
self.artanh = Artanh()
self.norm_k = Norm(axis=-1, keep_dims=True)
self.cl... | the_stack_v2_python_sparse | research/nlp/hypertext/src/poincare.py | mindspore-ai/models | train | 301 |
a9085eaf7a446c54f2a7226b5c8e7ae9a6661930 | [
"super(RelPositionalEncoding, self).__init__()\nself.d_model = d_model\nself.xscale = math.sqrt(self.d_model)\nself.dropout = torch.nn.Dropout(p=dropout_rate)\nself.pe = None\nself.extend_pe(torch.tensor(0.0).expand(1, max_len))",
"if self.pe is not None:\n if self.pe.size(1) >= x.size(1) * 2 - 1:\n if ... | <|body_start_0|>
super(RelPositionalEncoding, self).__init__()
self.d_model = d_model
self.xscale = math.sqrt(self.d_model)
self.dropout = torch.nn.Dropout(p=dropout_rate)
self.pe = None
self.extend_pe(torch.tensor(0.0).expand(1, max_len))
<|end_body_0|>
<|body_start_1|>... | Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. | RelPositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int):... | stack_v2_sparse_classes_36k_train_005757 | 12,758 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model, dropout_rate, max_len=5000)"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, x)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_000042 | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rat... | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rat... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum inpu... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transformer/embedding.py | espnet/espnet | train | 7,242 |
2e338003a48935ec5d5790485ec3500560a3b728 | [
"field = self.getPrimaryField()\nif isinstance(field.get(self), File):\n return field.get(self).index_html(REQUEST, RESPONSE)\nreturn field.index_html(self, REQUEST, RESPONSE)",
"if key is None:\n return self.getId()\nelse:\n field = self.getField(key) or getattr(self, key, None)\n if field and shasat... | <|body_start_0|>
field = self.getPrimaryField()
if isinstance(field.get(self), File):
return field.get(self).index_html(REQUEST, RESPONSE)
return field.index_html(self, REQUEST, RESPONSE)
<|end_body_0|>
<|body_start_1|>
if key is None:
return self.getId()
... | An image attachment | ImageAttachment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageAttachment:
"""An image attachment"""
def index_html(self, REQUEST, RESPONSE):
"""download the file inline or as an attachment"""
<|body_0|>
def getFilename(self, key=None):
"""Returns the filename from a field."""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_005758 | 1,189 | no_license | [
{
"docstring": "download the file inline or as an attachment",
"name": "index_html",
"signature": "def index_html(self, REQUEST, RESPONSE)"
},
{
"docstring": "Returns the filename from a field.",
"name": "getFilename",
"signature": "def getFilename(self, key=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020957 | Implement the Python class `ImageAttachment` described below.
Class description:
An image attachment
Method signatures and docstrings:
- def index_html(self, REQUEST, RESPONSE): download the file inline or as an attachment
- def getFilename(self, key=None): Returns the filename from a field. | Implement the Python class `ImageAttachment` described below.
Class description:
An image attachment
Method signatures and docstrings:
- def index_html(self, REQUEST, RESPONSE): download the file inline or as an attachment
- def getFilename(self, key=None): Returns the filename from a field.
<|skeleton|>
class Image... | 8a7bdbdb98c3f9fc1073c6061cd2d3a0ec80caf5 | <|skeleton|>
class ImageAttachment:
"""An image attachment"""
def index_html(self, REQUEST, RESPONSE):
"""download the file inline or as an attachment"""
<|body_0|>
def getFilename(self, key=None):
"""Returns the filename from a field."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageAttachment:
"""An image attachment"""
def index_html(self, REQUEST, RESPONSE):
"""download the file inline or as an attachment"""
field = self.getPrimaryField()
if isinstance(field.get(self), File):
return field.get(self).index_html(REQUEST, RESPONSE)
retu... | the_stack_v2_python_sparse | buildout-cache/eggs/Products.SimpleAttachment-5.0.0-py2.7.egg/Products/SimpleAttachment/content/image.py | renansfs/Plone_SP | train | 0 |
3d3b8f1148bacc4bd4655a16fdd88249c0236dc6 | [
"ans = lastIdx = 0\nfor i, x in enumerate(A + [10 ** 10]):\n if x > R:\n ans += self.numSubarrayMinimumMax(A[lastIdx:i], L)\n lastIdx = i + 1\nreturn ans",
"ans = lastIdx = 0\nfor i, x in enumerate(A):\n if x >= L:\n ans += (i - lastIdx + 1) * (len(A) - i)\n lastIdx = i + 1\nretu... | <|body_start_0|>
ans = lastIdx = 0
for i, x in enumerate(A + [10 ** 10]):
if x > R:
ans += self.numSubarrayMinimumMax(A[lastIdx:i], L)
lastIdx = i + 1
return ans
<|end_body_0|>
<|body_start_1|>
ans = lastIdx = 0
for i, x in enumerate(A... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubarrayBoundedMax(self, A, L, R):
""":type A: List[int] :type L: int :type R: int :rtype: int"""
<|body_0|>
def numSubarrayMinimumMax(self, A, L):
""":type A: List[int] :type L: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_005759 | 2,471 | no_license | [
{
"docstring": ":type A: List[int] :type L: int :type R: int :rtype: int",
"name": "numSubarrayBoundedMax",
"signature": "def numSubarrayBoundedMax(self, A, L, R)"
},
{
"docstring": ":type A: List[int] :type L: int :rtype: int",
"name": "numSubarrayMinimumMax",
"signature": "def numSubar... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayBoundedMax(self, A, L, R): :type A: List[int] :type L: int :type R: int :rtype: int
- def numSubarrayMinimumMax(self, A, L): :type A: List[int] :type L: int :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayBoundedMax(self, A, L, R): :type A: List[int] :type L: int :type R: int :rtype: int
- def numSubarrayMinimumMax(self, A, L): :type A: List[int] :type L: int :rtype... | 035ef08434fa1ca781a6fb2f9eed3538b7d20c02 | <|skeleton|>
class Solution:
def numSubarrayBoundedMax(self, A, L, R):
""":type A: List[int] :type L: int :type R: int :rtype: int"""
<|body_0|>
def numSubarrayMinimumMax(self, A, L):
""":type A: List[int] :type L: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSubarrayBoundedMax(self, A, L, R):
""":type A: List[int] :type L: int :type R: int :rtype: int"""
ans = lastIdx = 0
for i, x in enumerate(A + [10 ** 10]):
if x > R:
ans += self.numSubarrayMinimumMax(A[lastIdx:i], L)
lastIdx =... | the_stack_v2_python_sparse | leetcode_python/Array/number-of-subarrays-with-bounded-maximum.py | yennanliu/CS_basics | train | 64 | |
16d2159a79e1bf886a49d7db52e067aa0a2b22f3 | [
"self._caffe = kwargs.pop('caffe')\nkwargs.setdefault('label_suffix', '')\nsuper(CategoryForm, self).__init__(*args, **kwargs)\nself.fields['name'].label = 'Nazwa'",
"name = self.cleaned_data['name']\nquery = Category.objects.filter(name=name, caffe=self._caffe)\nif self.instance.pk:\n query = query.exclude(pk... | <|body_start_0|>
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(CategoryForm, self).__init__(*args, **kwargs)
self.fields['name'].label = 'Nazwa'
<|end_body_0|>
<|body_start_1|>
name = self.cleaned_data['name']
query = Category.objects.filt... | Responsible for setting up a Category. | CategoryForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryForm:
"""Responsible for setting up a Category."""
def __init__(self, *args, **kwargs):
"""Initialize all Category's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commit=True):
"""Overri... | stack_v2_sparse_classes_36k_train_005760 | 5,569 | permissive | [
{
"docstring": "Initialize all Category's fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Check name field.",
"name": "clean_name",
"signature": "def clean_name(self)"
},
{
"docstring": "Override of save method, to add Caffe rel... | 3 | stack_v2_sparse_classes_30k_train_004193 | Implement the Python class `CategoryForm` described below.
Class description:
Responsible for setting up a Category.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Category's fields.
- def clean_name(self): Check name field.
- def save(self, commit=True): Override of save meth... | Implement the Python class `CategoryForm` described below.
Class description:
Responsible for setting up a Category.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Category's fields.
- def clean_name(self): Check name field.
- def save(self, commit=True): Override of save meth... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class CategoryForm:
"""Responsible for setting up a Category."""
def __init__(self, *args, **kwargs):
"""Initialize all Category's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commit=True):
"""Overri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoryForm:
"""Responsible for setting up a Category."""
def __init__(self, *args, **kwargs):
"""Initialize all Category's fields."""
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(CategoryForm, self).__init__(*args, **kwargs)
self.... | the_stack_v2_python_sparse | caffe/reports/forms.py | VirrageS/io-kawiarnie | train | 3 |
4a566a17a251ee6f7b954408180f6f00046edef1 | [
"try:\n space = await get_data_from_req(self.request).spaces.get(space_id)\nexcept ResourceNotFoundError:\n raise NotFound\nreturn json_response(space)",
"try:\n space = await get_data_from_req(self.request).spaces.update(space_id, data)\nexcept ResourceNotFoundError:\n raise NotFound\nexcept Resource... | <|body_start_0|>
try:
space = await get_data_from_req(self.request).spaces.get(space_id)
except ResourceNotFoundError:
raise NotFound
return json_response(space)
<|end_body_0|>
<|body_start_1|>
try:
space = await get_data_from_req(self.request).spaces... | SpaceView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpaceView:
async def get(self, space_id: int, /) -> Union[r200[GetSpaceResponse], r404]:
"""Get a space. Fetches the complete representation of a space. Status Codes: 200: Successful operation 404: User not found"""
<|body_0|>
async def patch(self, space_id: int, /, data: Up... | stack_v2_sparse_classes_36k_train_005761 | 4,595 | permissive | [
{
"docstring": "Get a space. Fetches the complete representation of a space. Status Codes: 200: Successful operation 404: User not found",
"name": "get",
"signature": "async def get(self, space_id: int, /) -> Union[r200[GetSpaceResponse], r404]"
},
{
"docstring": "Update a space. Changes the nam... | 2 | null | Implement the Python class `SpaceView` described below.
Class description:
Implement the SpaceView class.
Method signatures and docstrings:
- async def get(self, space_id: int, /) -> Union[r200[GetSpaceResponse], r404]: Get a space. Fetches the complete representation of a space. Status Codes: 200: Successful operati... | Implement the Python class `SpaceView` described below.
Class description:
Implement the SpaceView class.
Method signatures and docstrings:
- async def get(self, space_id: int, /) -> Union[r200[GetSpaceResponse], r404]: Get a space. Fetches the complete representation of a space. Status Codes: 200: Successful operati... | 1d17d2ba570cf5487e7514bec29250a5b368bb0a | <|skeleton|>
class SpaceView:
async def get(self, space_id: int, /) -> Union[r200[GetSpaceResponse], r404]:
"""Get a space. Fetches the complete representation of a space. Status Codes: 200: Successful operation 404: User not found"""
<|body_0|>
async def patch(self, space_id: int, /, data: Up... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpaceView:
async def get(self, space_id: int, /) -> Union[r200[GetSpaceResponse], r404]:
"""Get a space. Fetches the complete representation of a space. Status Codes: 200: Successful operation 404: User not found"""
try:
space = await get_data_from_req(self.request).spaces.get(spac... | the_stack_v2_python_sparse | virtool/spaces/api.py | virtool/virtool | train | 45 | |
4c9e1f0c609c848d0664973663ff472f13af2aa2 | [
"if max_row == -1:\n max_row = len(self.r)\nclean = True\nlimit = int(ceil((1 + params['c']) * params.block_size))\nfor kappa in range(min_row, max_row - limit):\n assert max_row - kappa >= params.block_size\n clean &= self.svp_reduction(kappa, params.block_size, params, tracer=tracer)\ncost_ceil = log(par... | <|body_start_0|>
if max_row == -1:
max_row = len(self.r)
clean = True
limit = int(ceil((1 + params['c']) * params.block_size))
for kappa in range(min_row, max_row - limit):
assert max_row - kappa >= params.block_size
clean &= self.svp_reduction(kappa, ... | A simulator simulating both quality and time. | ProcrastinatingBKZSimulation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcrastinatingBKZSimulation:
"""A simulator simulating both quality and time."""
def tour(self, params, min_row=0, max_row=-1, tracer=dummy_tracer):
""":param params: BKZ parameters :param min_row: start processing at min_row (inclusive) :param max_row: stop processing at max_row (e... | stack_v2_sparse_classes_36k_train_005762 | 24,318 | no_license | [
{
"docstring": ":param params: BKZ parameters :param min_row: start processing at min_row (inclusive) :param max_row: stop processing at max_row (exclusive) :returns: whether the basis remained untouched or not",
"name": "tour",
"signature": "def tour(self, params, min_row=0, max_row=-1, tracer=dummy_tr... | 2 | stack_v2_sparse_classes_30k_train_000331 | Implement the Python class `ProcrastinatingBKZSimulation` described below.
Class description:
A simulator simulating both quality and time.
Method signatures and docstrings:
- def tour(self, params, min_row=0, max_row=-1, tracer=dummy_tracer): :param params: BKZ parameters :param min_row: start processing at min_row ... | Implement the Python class `ProcrastinatingBKZSimulation` described below.
Class description:
A simulator simulating both quality and time.
Method signatures and docstrings:
- def tour(self, params, min_row=0, max_row=-1, tracer=dummy_tracer): :param params: BKZ parameters :param min_row: start processing at min_row ... | d5bfc4e75ebec65d645853041ae548c5bfc066c8 | <|skeleton|>
class ProcrastinatingBKZSimulation:
"""A simulator simulating both quality and time."""
def tour(self, params, min_row=0, max_row=-1, tracer=dummy_tracer):
""":param params: BKZ parameters :param min_row: start processing at min_row (inclusive) :param max_row: stop processing at max_row (e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProcrastinatingBKZSimulation:
"""A simulator simulating both quality and time."""
def tour(self, params, min_row=0, max_row=-1, tracer=dummy_tracer):
""":param params: BKZ parameters :param min_row: start processing at min_row (inclusive) :param max_row: stop processing at max_row (exclusive) :re... | the_stack_v2_python_sparse | simu.py | fasterBKZ/simulation | train | 0 |
4cc7dbdcf717aed82fa1c769725d8ca33c5ff495 | [
"self.latitude = latitude\nself.longitude = longitude\nself.calc_method = calc_method\nself.prayer_times_info = None",
"from prayer_times_calculator import PrayerTimesCalculator\ntoday = datetime.today().strftime('%Y-%m-%d')\ncalc = PrayerTimesCalculator(latitude=self.latitude, longitude=self.longitude, calculati... | <|body_start_0|>
self.latitude = latitude
self.longitude = longitude
self.calc_method = calc_method
self.prayer_times_info = None
<|end_body_0|>
<|body_start_1|>
from prayer_times_calculator import PrayerTimesCalculator
today = datetime.today().strftime('%Y-%m-%d')
... | Data object for Islamic prayer times. | IslamicPrayerTimesData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IslamicPrayerTimesData:
"""Data object for Islamic prayer times."""
def __init__(self, latitude, longitude, calc_method):
"""Create object to hold data."""
<|body_0|>
def get_new_prayer_times(self):
"""Fetch prayer times for today."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_005763 | 7,529 | permissive | [
{
"docstring": "Create object to hold data.",
"name": "__init__",
"signature": "def __init__(self, latitude, longitude, calc_method)"
},
{
"docstring": "Fetch prayer times for today.",
"name": "get_new_prayer_times",
"signature": "def get_new_prayer_times(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017267 | Implement the Python class `IslamicPrayerTimesData` described below.
Class description:
Data object for Islamic prayer times.
Method signatures and docstrings:
- def __init__(self, latitude, longitude, calc_method): Create object to hold data.
- def get_new_prayer_times(self): Fetch prayer times for today. | Implement the Python class `IslamicPrayerTimesData` described below.
Class description:
Data object for Islamic prayer times.
Method signatures and docstrings:
- def __init__(self, latitude, longitude, calc_method): Create object to hold data.
- def get_new_prayer_times(self): Fetch prayer times for today.
<|skeleto... | 6e414983738d9495eb9e4f858e3e98e9e38869db | <|skeleton|>
class IslamicPrayerTimesData:
"""Data object for Islamic prayer times."""
def __init__(self, latitude, longitude, calc_method):
"""Create object to hold data."""
<|body_0|>
def get_new_prayer_times(self):
"""Fetch prayer times for today."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IslamicPrayerTimesData:
"""Data object for Islamic prayer times."""
def __init__(self, latitude, longitude, calc_method):
"""Create object to hold data."""
self.latitude = latitude
self.longitude = longitude
self.calc_method = calc_method
self.prayer_times_info = N... | the_stack_v2_python_sparse | homeassistant/components/islamic_prayer_times/sensor.py | Watemlifts/home-assistant | train | 4 |
9f1073553733a94bc7326e07459ca0811eb98d9e | [
"count = [0]\nself.dfs(root, sum, 0, {}, count)\nreturn count[0]",
"if not root:\n return\ncur_sum += root.val\ndiff = cur_sum - sum\nif diff in prefix_sum:\n count[0] += prefix_sum[diff]\nif diff == 0:\n count[0] += 1\nprefix_sum[cur_sum] = prefix_sum.get(cur_sum, 0) + 1\nself.dfs(root.left, sum, cur_su... | <|body_start_0|>
count = [0]
self.dfs(root, sum, 0, {}, count)
return count[0]
<|end_body_0|>
<|body_start_1|>
if not root:
return
cur_sum += root.val
diff = cur_sum - sum
if diff in prefix_sum:
count[0] += prefix_sum[diff]
if diff... | SolutionComplex | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionComplex:
def pathSum(self, root, sum):
"""Brute force: two dfs, O(n^2) Prefix sum in Tree, starting from root - O(n) :type root: TreeNode :type sum: int :rtype: int"""
<|body_0|>
def dfs(self, root, sum, cur_sum, prefix_sum, count):
"""Root to node sum prefix... | stack_v2_sparse_classes_36k_train_005764 | 2,552 | no_license | [
{
"docstring": "Brute force: two dfs, O(n^2) Prefix sum in Tree, starting from root - O(n) :type root: TreeNode :type sum: int :rtype: int",
"name": "pathSum",
"signature": "def pathSum(self, root, sum)"
},
{
"docstring": "Root to node sum prefix_sum: Dict[int, int], sum -> count",
"name": "... | 2 | null | Implement the Python class `SolutionComplex` described below.
Class description:
Implement the SolutionComplex class.
Method signatures and docstrings:
- def pathSum(self, root, sum): Brute force: two dfs, O(n^2) Prefix sum in Tree, starting from root - O(n) :type root: TreeNode :type sum: int :rtype: int
- def dfs(s... | Implement the Python class `SolutionComplex` described below.
Class description:
Implement the SolutionComplex class.
Method signatures and docstrings:
- def pathSum(self, root, sum): Brute force: two dfs, O(n^2) Prefix sum in Tree, starting from root - O(n) :type root: TreeNode :type sum: int :rtype: int
- def dfs(s... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class SolutionComplex:
def pathSum(self, root, sum):
"""Brute force: two dfs, O(n^2) Prefix sum in Tree, starting from root - O(n) :type root: TreeNode :type sum: int :rtype: int"""
<|body_0|>
def dfs(self, root, sum, cur_sum, prefix_sum, count):
"""Root to node sum prefix... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolutionComplex:
def pathSum(self, root, sum):
"""Brute force: two dfs, O(n^2) Prefix sum in Tree, starting from root - O(n) :type root: TreeNode :type sum: int :rtype: int"""
count = [0]
self.dfs(root, sum, 0, {}, count)
return count[0]
def dfs(self, root, sum, cur_sum, p... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/437 Path Sum III.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
06e9f4077f61656b975c39cb5c9ca4e53048f417 | [
"cherrypy.response.headers['Content-Type'] = 'text/html; charset=utf-8'\ncherrypy.response.headers['Content-Language'] = 'en'\ns = '<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=... | <|body_start_0|>
cherrypy.response.headers['Content-Type'] = 'text/html; charset=utf-8'
cherrypy.response.headers['Content-Language'] = 'en'
s = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html xmlns="http://www.w3.org/1999/xh... | Output a gallery of cover pages. | CoverPages | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoverPages:
"""Output a gallery of cover pages."""
def serve(rows, size):
"""Output a gallery of coverpages."""
<|body_0|>
def index(self, count, size, order, **kwargs):
"""Internal help function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_005765 | 3,091 | no_license | [
{
"docstring": "Output a gallery of coverpages.",
"name": "serve",
"signature": "def serve(rows, size)"
},
{
"docstring": "Internal help function.",
"name": "index",
"signature": "def index(self, count, size, order, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007750 | Implement the Python class `CoverPages` described below.
Class description:
Output a gallery of cover pages.
Method signatures and docstrings:
- def serve(rows, size): Output a gallery of coverpages.
- def index(self, count, size, order, **kwargs): Internal help function. | Implement the Python class `CoverPages` described below.
Class description:
Output a gallery of cover pages.
Method signatures and docstrings:
- def serve(rows, size): Output a gallery of coverpages.
- def index(self, count, size, order, **kwargs): Internal help function.
<|skeleton|>
class CoverPages:
"""Output... | 62ead004375ef24ac13f6bf80f48742cf0b40625 | <|skeleton|>
class CoverPages:
"""Output a gallery of cover pages."""
def serve(rows, size):
"""Output a gallery of coverpages."""
<|body_0|>
def index(self, count, size, order, **kwargs):
"""Internal help function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CoverPages:
"""Output a gallery of cover pages."""
def serve(rows, size):
"""Output a gallery of coverpages."""
cherrypy.response.headers['Content-Type'] = 'text/html; charset=utf-8'
cherrypy.response.headers['Content-Language'] = 'en'
s = '<!DOCTYPE html PUBLIC "-//W3C//D... | the_stack_v2_python_sparse | CoverPages.py | eshellman/autocat3_gutenberg1 | train | 1 |
0c7f7be82182c2e44099fb963a1813dd6eb33718 | [
"generated_module = f'{self.name}.generated_module'\ngenerated_table_name = f'{self.name}.generated_table'\ntable_name = self.getconfig(generated_table_name, section=CC.READER)\ngenerated_module = das_utils.class_from_config(self.config, generated_module, CC.READER)\nself.generated_class = getattr(generated_module,... | <|body_start_0|>
generated_module = f'{self.name}.generated_module'
generated_table_name = f'{self.name}.generated_table'
table_name = self.getconfig(generated_table_name, section=CC.READER)
generated_module = das_utils.class_from_config(self.config, generated_module, CC.READER)
... | FixedWidthFormatTable | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixedWidthFormatTable:
def make_variables(self) -> typing.List[FWFTableVariable]:
"""Dynamically create variables based on the generated specification file"""
<|body_0|>
def load(self, filter=None):
"""Load the fixed-width formatted file, using the generated specific... | stack_v2_sparse_classes_36k_train_005766 | 2,639 | permissive | [
{
"docstring": "Dynamically create variables based on the generated specification file",
"name": "make_variables",
"signature": "def make_variables(self) -> typing.List[FWFTableVariable]"
},
{
"docstring": "Load the fixed-width formatted file, using the generated specification file to parse rows... | 2 | stack_v2_sparse_classes_30k_train_005310 | Implement the Python class `FixedWidthFormatTable` described below.
Class description:
Implement the FixedWidthFormatTable class.
Method signatures and docstrings:
- def make_variables(self) -> typing.List[FWFTableVariable]: Dynamically create variables based on the generated specification file
- def load(self, filte... | Implement the Python class `FixedWidthFormatTable` described below.
Class description:
Implement the FixedWidthFormatTable class.
Method signatures and docstrings:
- def make_variables(self) -> typing.List[FWFTableVariable]: Dynamically create variables based on the generated specification file
- def load(self, filte... | 7f7ba44055da15d13b191180249e656e1bd398c6 | <|skeleton|>
class FixedWidthFormatTable:
def make_variables(self) -> typing.List[FWFTableVariable]:
"""Dynamically create variables based on the generated specification file"""
<|body_0|>
def load(self, filter=None):
"""Load the fixed-width formatted file, using the generated specific... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FixedWidthFormatTable:
def make_variables(self) -> typing.List[FWFTableVariable]:
"""Dynamically create variables based on the generated specification file"""
generated_module = f'{self.name}.generated_module'
generated_table_name = f'{self.name}.generated_table'
table_name = s... | the_stack_v2_python_sparse | das_decennial/programs/reader/fwf_reader.py | p-b-j/uscb-das-container-public | train | 1 | |
3be32a078629544eb473ce51e66c5afc84139bbe | [
"self.rotation_angle = angle\nself.args = args\nif kwargs is None:\n self.kwargs = {'preserve_range': True}\nelse:\n if 'preserve_range' in kwargs and (not kwargs['preserve_range']):\n msg = 'preserve_range cannot be set to False!'\n logger.error(msg)\n raise ValueError(msg)\n self.kwa... | <|body_start_0|>
self.rotation_angle = angle
self.args = args
if kwargs is None:
self.kwargs = {'preserve_range': True}
else:
if 'preserve_range' in kwargs and (not kwargs['preserve_range']):
msg = 'preserve_range cannot be set to False!'
... | Implements a rotation of an Entity by a specified angle amount. | RotateXForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RotateXForm:
"""Implements a rotation of an Entity by a specified angle amount."""
def __init__(self, angle: int=90, args: tuple=(), kwargs: dict=None) -> None:
"""Creates a Rotator Transform object :param angle: The degree amount to rotate (in degrees, not radians!) :param args: any... | stack_v2_sparse_classes_36k_train_005767 | 4,028 | permissive | [
{
"docstring": "Creates a Rotator Transform object :param angle: The degree amount to rotate (in degrees, not radians!) :param args: any additional arguments to pass to skimage.transform.rotate :param kwargs: any keyword arguments to pass to skimage.transform.rotate",
"name": "__init__",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_004171 | Implement the Python class `RotateXForm` described below.
Class description:
Implements a rotation of an Entity by a specified angle amount.
Method signatures and docstrings:
- def __init__(self, angle: int=90, args: tuple=(), kwargs: dict=None) -> None: Creates a Rotator Transform object :param angle: The degree amo... | Implement the Python class `RotateXForm` described below.
Class description:
Implements a rotation of an Entity by a specified angle amount.
Method signatures and docstrings:
- def __init__(self, angle: int=90, args: tuple=(), kwargs: dict=None) -> None: Creates a Rotator Transform object :param angle: The degree amo... | 6ee5912f1fa57f49a4dd4feeeaf7862153bb6a9f | <|skeleton|>
class RotateXForm:
"""Implements a rotation of an Entity by a specified angle amount."""
def __init__(self, angle: int=90, args: tuple=(), kwargs: dict=None) -> None:
"""Creates a Rotator Transform object :param angle: The degree amount to rotate (in degrees, not radians!) :param args: any... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RotateXForm:
"""Implements a rotation of an Entity by a specified angle amount."""
def __init__(self, angle: int=90, args: tuple=(), kwargs: dict=None) -> None:
"""Creates a Rotator Transform object :param angle: The degree amount to rotate (in degrees, not radians!) :param args: any additional a... | the_stack_v2_python_sparse | trojai/trojai/datagen/image_affine_xforms.py | ionutmodo/TrojAI-UMD | train | 1 |
ae17169d3e4afa2aa0d10711afd7a6ff9b3024f1 | [
"self._num_key = 0\nself._num_value = num_output_qubits\nself._measurement = measurement\nself._logger = logging.getLogger(__name__)",
"linear_dict = problem.objective.get_linear()\nlinear_coeff = np.zeros(problem.variables.get_num())\nfor i, v in linear_dict.items():\n linear_coeff[i] = v\nquadratic_dict = pr... | <|body_start_0|>
self._num_key = 0
self._num_value = num_output_qubits
self._measurement = measurement
self._logger = logging.getLogger(__name__)
<|end_body_0|>
<|body_start_1|>
linear_dict = problem.objective.get_linear()
linear_coeff = np.zeros(problem.variables.get_nu... | Converts an optimization problem (QUBO) to a negative value oracle. In addition, a state preparation operator is generated from the coefficients and constant of a QUBO, which can be used to encode the function into a quantum state. In conjuction, this oracle and operator can be used to flag the negative values of a QUB... | OptimizationProblemToNegativeValueOracle | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizationProblemToNegativeValueOracle:
"""Converts an optimization problem (QUBO) to a negative value oracle. In addition, a state preparation operator is generated from the coefficients and constant of a QUBO, which can be used to encode the function into a quantum state. In conjuction, this ... | stack_v2_sparse_classes_36k_train_005768 | 7,561 | permissive | [
{
"docstring": "Args: num_output_qubits: The number of qubits required to represent the output. measurement: Whether the A operator contains measurements.",
"name": "__init__",
"signature": "def __init__(self, num_output_qubits: int, measurement: bool=False) -> None"
},
{
"docstring": "A helper ... | 5 | stack_v2_sparse_classes_30k_train_013716 | Implement the Python class `OptimizationProblemToNegativeValueOracle` described below.
Class description:
Converts an optimization problem (QUBO) to a negative value oracle. In addition, a state preparation operator is generated from the coefficients and constant of a QUBO, which can be used to encode the function int... | Implement the Python class `OptimizationProblemToNegativeValueOracle` described below.
Class description:
Converts an optimization problem (QUBO) to a negative value oracle. In addition, a state preparation operator is generated from the coefficients and constant of a QUBO, which can be used to encode the function int... | f252d3e20f3513c4d6de8188e02231676a3fa35e | <|skeleton|>
class OptimizationProblemToNegativeValueOracle:
"""Converts an optimization problem (QUBO) to a negative value oracle. In addition, a state preparation operator is generated from the coefficients and constant of a QUBO, which can be used to encode the function into a quantum state. In conjuction, this ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptimizationProblemToNegativeValueOracle:
"""Converts an optimization problem (QUBO) to a negative value oracle. In addition, a state preparation operator is generated from the coefficients and constant of a QUBO, which can be used to encode the function into a quantum state. In conjuction, this oracle and op... | the_stack_v2_python_sparse | qiskit/optimization/converters/optimization_problem_to_negative_value_oracle.py | andrea-simonetto/qiskit-aqua | train | 0 |
8222ee10530059ccded7f986ea4c63fb69073a46 | [
"if layers < 0:\n raise ValueError('Number of layers must be at least 0.')\nelse:\n self.layers = layers\nif not isinstance(nodes, int):\n raise ValueError('Nodes must be a positive integer.')\nelse:\n self.nodes = nodes\nif epochs < 1:\n raise ValueError('The number of epochs must be at least 1.')\n... | <|body_start_0|>
if layers < 0:
raise ValueError('Number of layers must be at least 0.')
else:
self.layers = layers
if not isinstance(nodes, int):
raise ValueError('Nodes must be a positive integer.')
else:
self.nodes = nodes
if epo... | Class to build, fit, and predict using a feed-forward neural network. | Network | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Network:
"""Class to build, fit, and predict using a feed-forward neural network."""
def __init__(self, layers=2, nodes=25, epochs=50, batch=256, rate=0.001, optimizer='rmsprop'):
"""Parameters: - - - - - layers : number of layers in the network nodes : (int,list) specifies the numbe... | stack_v2_sparse_classes_36k_train_005769 | 7,075 | permissive | [
{
"docstring": "Parameters: - - - - - layers : number of layers in the network nodes : (int,list) specifies the number of nodes per layer if integer is provided, will generate same number of nodes per layer. If a list is provided, will compare length of list to number of layers. If they match, will add number o... | 5 | stack_v2_sparse_classes_30k_train_010422 | Implement the Python class `Network` described below.
Class description:
Class to build, fit, and predict using a feed-forward neural network.
Method signatures and docstrings:
- def __init__(self, layers=2, nodes=25, epochs=50, batch=256, rate=0.001, optimizer='rmsprop'): Parameters: - - - - - layers : number of lay... | Implement the Python class `Network` described below.
Class description:
Class to build, fit, and predict using a feed-forward neural network.
Method signatures and docstrings:
- def __init__(self, layers=2, nodes=25, epochs=50, batch=256, rate=0.001, optimizer='rmsprop'): Parameters: - - - - - layers : number of lay... | 328a2b6d541675017346837e439696e7d3eaeb69 | <|skeleton|>
class Network:
"""Class to build, fit, and predict using a feed-forward neural network."""
def __init__(self, layers=2, nodes=25, epochs=50, batch=256, rate=0.001, optimizer='rmsprop'):
"""Parameters: - - - - - layers : number of layers in the network nodes : (int,list) specifies the numbe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Network:
"""Class to build, fit, and predict using a feed-forward neural network."""
def __init__(self, layers=2, nodes=25, epochs=50, batch=256, rate=0.001, optimizer='rmsprop'):
"""Parameters: - - - - - layers : number of layers in the network nodes : (int,list) specifies the number of nodes pe... | the_stack_v2_python_sparse | parcellearning/NeuralNetwork.py | briceran/parcellearning | train | 0 |
7730af6fc733fdf98d564d81dd57ed7cb5d0231b | [
"super(ConnectionThread, self).__init__(parent)\nself.g = g\nself.sig = sig\nself.parent = parent",
"repo_list = []\ntry:\n for repo in self.g.get_user().get_repos():\n repo_list.append(repo)\n if self.parent is not None:\n self.parent.parent.statusBar().showMessage('Done.')\n sys_tray ... | <|body_start_0|>
super(ConnectionThread, self).__init__(parent)
self.g = g
self.sig = sig
self.parent = parent
<|end_body_0|>
<|body_start_1|>
repo_list = []
try:
for repo in self.g.get_user().get_repos():
repo_list.append(repo)
if... | Thread used to connect to github. | ConnectionThread | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectionThread:
"""Thread used to connect to github."""
def __init__(self, parent, g=None, sig=None):
"""Init thread."""
<|body_0|>
def run(self):
"""Run thread."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ConnectionThread, self).__i... | stack_v2_sparse_classes_36k_train_005770 | 11,571 | permissive | [
{
"docstring": "Init thread.",
"name": "__init__",
"signature": "def __init__(self, parent, g=None, sig=None)"
},
{
"docstring": "Run thread.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007729 | Implement the Python class `ConnectionThread` described below.
Class description:
Thread used to connect to github.
Method signatures and docstrings:
- def __init__(self, parent, g=None, sig=None): Init thread.
- def run(self): Run thread. | Implement the Python class `ConnectionThread` described below.
Class description:
Thread used to connect to github.
Method signatures and docstrings:
- def __init__(self, parent, g=None, sig=None): Init thread.
- def run(self): Run thread.
<|skeleton|>
class ConnectionThread:
"""Thread used to connect to github.... | 93dd7abb03d27cf3490d8b2514365260d67ab15b | <|skeleton|>
class ConnectionThread:
"""Thread used to connect to github."""
def __init__(self, parent, g=None, sig=None):
"""Init thread."""
<|body_0|>
def run(self):
"""Run thread."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConnectionThread:
"""Thread used to connect to github."""
def __init__(self, parent, g=None, sig=None):
"""Init thread."""
super(ConnectionThread, self).__init__(parent)
self.g = g
self.sig = sig
self.parent = parent
def run(self):
"""Run thread."""
... | the_stack_v2_python_sparse | Work_Log_Generator/work_log.py | hastagAB/Awesome-Python-Scripts | train | 1,757 |
7e9dd062e6d7e42b0750e5a136f692cc5a065e49 | [
"if from_user_id == 0 or message_id == 0:\n return self._response(Pyobject(Error.param_error))\nsql = 'select user_id from message where id = %s' % message_id\nresult = mysql_conn.query(sql)\nif len(result) > 0:\n to_user_id = result[0]['user_id']\n sql = 'insert into pushing(from_user_id,to_user_id,messag... | <|body_start_0|>
if from_user_id == 0 or message_id == 0:
return self._response(Pyobject(Error.param_error))
sql = 'select user_id from message where id = %s' % message_id
result = mysql_conn.query(sql)
if len(result) > 0:
to_user_id = result[0]['user_id']
... | 资源相关接口 | pushing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pushing:
"""资源相关接口"""
def push(self, from_user_id={'atype': int, 'adef': 0}, message_id={'atype': int, 'adef': 0}):
"""推送message阅读消息"""
<|body_0|>
def get(self, user_id={'atype': int, 'adef': 0}):
"""查询用户是否具有推送"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_005771 | 2,103 | no_license | [
{
"docstring": "推送message阅读消息",
"name": "push",
"signature": "def push(self, from_user_id={'atype': int, 'adef': 0}, message_id={'atype': int, 'adef': 0})"
},
{
"docstring": "查询用户是否具有推送",
"name": "get",
"signature": "def get(self, user_id={'atype': int, 'adef': 0})"
}
] | 2 | stack_v2_sparse_classes_30k_train_008580 | Implement the Python class `pushing` described below.
Class description:
资源相关接口
Method signatures and docstrings:
- def push(self, from_user_id={'atype': int, 'adef': 0}, message_id={'atype': int, 'adef': 0}): 推送message阅读消息
- def get(self, user_id={'atype': int, 'adef': 0}): 查询用户是否具有推送 | Implement the Python class `pushing` described below.
Class description:
资源相关接口
Method signatures and docstrings:
- def push(self, from_user_id={'atype': int, 'adef': 0}, message_id={'atype': int, 'adef': 0}): 推送message阅读消息
- def get(self, user_id={'atype': int, 'adef': 0}): 查询用户是否具有推送
<|skeleton|>
class pushing:
... | 78cc5e0d90d7c424932edf6ea6312a21643d29f0 | <|skeleton|>
class pushing:
"""资源相关接口"""
def push(self, from_user_id={'atype': int, 'adef': 0}, message_id={'atype': int, 'adef': 0}):
"""推送message阅读消息"""
<|body_0|>
def get(self, user_id={'atype': int, 'adef': 0}):
"""查询用户是否具有推送"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class pushing:
"""资源相关接口"""
def push(self, from_user_id={'atype': int, 'adef': 0}, message_id={'atype': int, 'adef': 0}):
"""推送message阅读消息"""
if from_user_id == 0 or message_id == 0:
return self._response(Pyobject(Error.param_error))
sql = 'select user_id from message where ... | the_stack_v2_python_sparse | api/pushing.py | BurningAzzzi/thack | train | 1 |
8a6f0d52d714f803465af4612c27800394cb413d | [
"super(GoogLeNet, self).__init__()\nif global_params.blocks is None:\n blocks = [BasicConv2d, Inception, InceptionAux]\nassert len(blocks) == 3\nconv_block = blocks[0]\ninception_block = blocks[1]\ninception_aux_block = blocks[2]\nself.aux_logits = global_params.aux_logits\nself.conv1 = conv_block(global_params.... | <|body_start_0|>
super(GoogLeNet, self).__init__()
if global_params.blocks is None:
blocks = [BasicConv2d, Inception, InceptionAux]
assert len(blocks) == 3
conv_block = blocks[0]
inception_block = blocks[1]
inception_aux_block = blocks[2]
self.aux_logi... | Neural network structure : (conv1): (0): Conv2d(in_channels, ch1x1, kernel_size=1) (1): BatchNorm2d(out_channels, eps=1e-03) (2): ReLU(inplace=True) (branch2): (0): Conv2d(in_channels, ch1x1, kernel_size=1) (1): BatchNorm2d(out_channels, eps=1e-03) (2): ReLU(inplace=True) (3): Conv2d(in_channels, ch1x1, kernel_size=3, ... | GoogLeNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogLeNet:
"""Neural network structure : (conv1): (0): Conv2d(in_channels, ch1x1, kernel_size=1) (1): BatchNorm2d(out_channels, eps=1e-03) (2): ReLU(inplace=True) (branch2): (0): Conv2d(in_channels, ch1x1, kernel_size=1) (1): BatchNorm2d(out_channels, eps=1e-03) (2): ReLU(inplace=True) (3): Conv2... | stack_v2_sparse_classes_36k_train_005772 | 13,487 | no_license | [
{
"docstring": ":param global_params : tuple subclass, a tuple subclass that contain parameters for the entire model (stem, all blocks, and head) - default : None",
"name": "__init__",
"signature": "def __init__(self, global_params=None)"
},
{
"docstring": ":param x : torch.Tensor, image tensor ... | 2 | stack_v2_sparse_classes_30k_train_010216 | Implement the Python class `GoogLeNet` described below.
Class description:
Neural network structure : (conv1): (0): Conv2d(in_channels, ch1x1, kernel_size=1) (1): BatchNorm2d(out_channels, eps=1e-03) (2): ReLU(inplace=True) (branch2): (0): Conv2d(in_channels, ch1x1, kernel_size=1) (1): BatchNorm2d(out_channels, eps=1e... | Implement the Python class `GoogLeNet` described below.
Class description:
Neural network structure : (conv1): (0): Conv2d(in_channels, ch1x1, kernel_size=1) (1): BatchNorm2d(out_channels, eps=1e-03) (2): ReLU(inplace=True) (branch2): (0): Conv2d(in_channels, ch1x1, kernel_size=1) (1): BatchNorm2d(out_channels, eps=1e... | 9189d2eeb748b1e539a1062a09a06b38a09780de | <|skeleton|>
class GoogLeNet:
"""Neural network structure : (conv1): (0): Conv2d(in_channels, ch1x1, kernel_size=1) (1): BatchNorm2d(out_channels, eps=1e-03) (2): ReLU(inplace=True) (branch2): (0): Conv2d(in_channels, ch1x1, kernel_size=1) (1): BatchNorm2d(out_channels, eps=1e-03) (2): ReLU(inplace=True) (3): Conv2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoogLeNet:
"""Neural network structure : (conv1): (0): Conv2d(in_channels, ch1x1, kernel_size=1) (1): BatchNorm2d(out_channels, eps=1e-03) (2): ReLU(inplace=True) (branch2): (0): Conv2d(in_channels, ch1x1, kernel_size=1) (1): BatchNorm2d(out_channels, eps=1e-03) (2): ReLU(inplace=True) (3): Conv2d(in_channels... | the_stack_v2_python_sparse | Simulations/helpers/model/googLeNet.py | emmahoggett/Error_class_lenstronomy | train | 1 |
3fc39d49c1cf53e84dc7db75aa10a107fe560679 | [
"res = []\n\ndef helper(node):\n if not node:\n return 0\n val = helper(node.next)\n if val == 0:\n res.append(0)\n return node.val\n elif node.val > val:\n res.append(0)\n return node.val\n else:\n res.append(val)\n return val\nhelper(head)\nreturn re... | <|body_start_0|>
res = []
def helper(node):
if not node:
return 0
val = helper(node.next)
if val == 0:
res.append(0)
return node.val
elif node.val > val:
res.append(0)
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextLargerNodesWrong(self, head):
""":type head: ListNode :rtype: List[int]"""
<|body_0|>
def nextLargerNodes(self, head):
""":type head: ListNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
def ... | stack_v2_sparse_classes_36k_train_005773 | 2,757 | no_license | [
{
"docstring": ":type head: ListNode :rtype: List[int]",
"name": "nextLargerNodesWrong",
"signature": "def nextLargerNodesWrong(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: List[int]",
"name": "nextLargerNodes",
"signature": "def nextLargerNodes(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005356 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextLargerNodesWrong(self, head): :type head: ListNode :rtype: List[int]
- def nextLargerNodes(self, head): :type head: ListNode :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextLargerNodesWrong(self, head): :type head: ListNode :rtype: List[int]
- def nextLargerNodes(self, head): :type head: ListNode :rtype: List[int]
<|skeleton|>
class Solutio... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def nextLargerNodesWrong(self, head):
""":type head: ListNode :rtype: List[int]"""
<|body_0|>
def nextLargerNodes(self, head):
""":type head: ListNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nextLargerNodesWrong(self, head):
""":type head: ListNode :rtype: List[int]"""
res = []
def helper(node):
if not node:
return 0
val = helper(node.next)
if val == 0:
res.append(0)
return n... | the_stack_v2_python_sparse | N/NextGreaterNodeInLinkedList.py | bssrdf/pyleet | train | 2 | |
67fb9fd2257009e2539a7aeaa6656eba81e9866f | [
"n = len(nums)\nif n < 2:\n return 0\nright, left = (0, n - 1)\ntmp = []\nfor i in range(n):\n while tmp and nums[tmp[-1]] > nums[i]:\n left = min(left, tmp.pop())\n tmp.append(i)\ntmp = []\nfor i in range(n - 1, -1, -1):\n while tmp and nums[tmp[-1]] < nums[i]:\n right = max(right, tmp.po... | <|body_start_0|>
n = len(nums)
if n < 2:
return 0
right, left = (0, n - 1)
tmp = []
for i in range(n):
while tmp and nums[tmp[-1]] > nums[i]:
left = min(left, tmp.pop())
tmp.append(i)
tmp = []
for i in range(n - ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findUnsortedSubarray(self, nums):
"""monotonic stack ref : https://www.youtube.com/watch?v=8wHH9txAK34 :type nums: List[int] :rtype: int"""
<|body_0|>
def findUnsortedSubarrayAmazing(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|... | stack_v2_sparse_classes_36k_train_005774 | 3,329 | no_license | [
{
"docstring": "monotonic stack ref : https://www.youtube.com/watch?v=8wHH9txAK34 :type nums: List[int] :rtype: int",
"name": "findUnsortedSubarray",
"signature": "def findUnsortedSubarray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findUnsortedSubarrayAmazin... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray(self, nums): monotonic stack ref : https://www.youtube.com/watch?v=8wHH9txAK34 :type nums: List[int] :rtype: int
- def findUnsortedSubarrayAmazing(self, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray(self, nums): monotonic stack ref : https://www.youtube.com/watch?v=8wHH9txAK34 :type nums: List[int] :rtype: int
- def findUnsortedSubarrayAmazing(self, ... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def findUnsortedSubarray(self, nums):
"""monotonic stack ref : https://www.youtube.com/watch?v=8wHH9txAK34 :type nums: List[int] :rtype: int"""
<|body_0|>
def findUnsortedSubarrayAmazing(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findUnsortedSubarray(self, nums):
"""monotonic stack ref : https://www.youtube.com/watch?v=8wHH9txAK34 :type nums: List[int] :rtype: int"""
n = len(nums)
if n < 2:
return 0
right, left = (0, n - 1)
tmp = []
for i in range(n):
... | the_stack_v2_python_sparse | random/shortest_unsorted_continuous_subarray.py | hwc1824/LeetCodeSolution | train | 0 | |
5a9b0798d7c7ffb85babad224f395cc8b4bfb9ec | [
"self.full_path = search_path\nself.directory_contents = listdir(self.full_path)\nself.config_filenames = []\nself.comp_filenames = []\nself.vi_list = []\nself._extract_config_filenames()",
"for filename in self.directory_contents:\n if fnmatch(filename, '*.conf'):\n self.config_filenames.append(filenam... | <|body_start_0|>
self.full_path = search_path
self.directory_contents = listdir(self.full_path)
self.config_filenames = []
self.comp_filenames = []
self.vi_list = []
self._extract_config_filenames()
<|end_body_0|>
<|body_start_1|>
for filename in self.directory_c... | Reads SECI configuration files and extracts VI names | ReadConfigFiles | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadConfigFiles:
"""Reads SECI configuration files and extracts VI names"""
def __init__(self, search_path):
"""create lists for filenames and initialise to empty lists call methods for reading directory contents and searching for config filenames :param search_path: the search path ... | stack_v2_sparse_classes_36k_train_005775 | 3,583 | no_license | [
{
"docstring": "create lists for filenames and initialise to empty lists call methods for reading directory contents and searching for config filenames :param search_path: the search path for files",
"name": "__init__",
"signature": "def __init__(self, search_path)"
},
{
"docstring": "extract SE... | 6 | stack_v2_sparse_classes_30k_train_021042 | Implement the Python class `ReadConfigFiles` described below.
Class description:
Reads SECI configuration files and extracts VI names
Method signatures and docstrings:
- def __init__(self, search_path): create lists for filenames and initialise to empty lists call methods for reading directory contents and searching ... | Implement the Python class `ReadConfigFiles` described below.
Class description:
Reads SECI configuration files and extracts VI names
Method signatures and docstrings:
- def __init__(self, search_path): create lists for filenames and initialise to empty lists call methods for reading directory contents and searching ... | bcc5cf19773731979f3e3123a4f585a0bf723c1b | <|skeleton|>
class ReadConfigFiles:
"""Reads SECI configuration files and extracts VI names"""
def __init__(self, search_path):
"""create lists for filenames and initialise to empty lists call methods for reading directory contents and searching for config filenames :param search_path: the search path ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReadConfigFiles:
"""Reads SECI configuration files and extracts VI names"""
def __init__(self, search_path):
"""create lists for filenames and initialise to empty lists call methods for reading directory contents and searching for config filenames :param search_path: the search path for files"""
... | the_stack_v2_python_sparse | SECI_Config_Analyser/Directory_Operations.py | ISISComputingGroup/ibex_utils | train | 0 |
cf54d9bf5a263143aaa8bcd2b00dc7d57e3b251a | [
"if self.request.version == 'v6':\n return BatchSerializerV6\nelif self.request.version == 'v7':\n return BatchSerializerV6",
"if request.version == 'v6':\n return self._list_v6(request)\nelif request.version == 'v7':\n return self._list_v6(request)\nraise Http404()",
"if request.version == 'v6':\n ... | <|body_start_0|>
if self.request.version == 'v6':
return BatchSerializerV6
elif self.request.version == 'v7':
return BatchSerializerV6
<|end_body_0|>
<|body_start_1|>
if request.version == 'v6':
return self._list_v6(request)
elif request.version == 'v... | This view is the endpoint for the list of batches | BatchesView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchesView:
"""This view is the endpoint for the list of batches"""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
<|body_0|>
def list(self, request):
"""Retrieves the batches and returns t... | stack_v2_sparse_classes_36k_train_005776 | 14,601 | permissive | [
{
"docstring": "Returns the appropriate serializer based off the requests version of the REST API",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Retrieves the batches and returns them in JSON form :param request: the HTTP GET request :type requ... | 5 | null | Implement the Python class `BatchesView` described below.
Class description:
This view is the endpoint for the list of batches
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def list(self, request): Retrieves the ... | Implement the Python class `BatchesView` described below.
Class description:
This view is the endpoint for the list of batches
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def list(self, request): Retrieves the ... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class BatchesView:
"""This view is the endpoint for the list of batches"""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
<|body_0|>
def list(self, request):
"""Retrieves the batches and returns t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchesView:
"""This view is the endpoint for the list of batches"""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
if self.request.version == 'v6':
return BatchSerializerV6
elif self.request.vers... | the_stack_v2_python_sparse | scale/batch/views.py | kfconsultant/scale | train | 0 |
0b39cc5d0b2c60e4d840a9c69fd40dc32372be15 | [
"res.append(partial)\nn = len(nums)\nif start >= n:\n return\nfor i in range(start, n):\n self._subsets(nums, i + 1, partial + [nums[i]], res)",
"res = []\npartial = []\nself._subsets(nums, 0, partial, res)\nreturn res"
] | <|body_start_0|>
res.append(partial)
n = len(nums)
if start >= n:
return
for i in range(start, n):
self._subsets(nums, i + 1, partial + [nums[i]], res)
<|end_body_0|>
<|body_start_1|>
res = []
partial = []
self._subsets(nums, 0, partial, r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _subsets(self, nums, start, partial, res):
""":type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]]"""
<|body_0|>
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_005777 | 1,073 | no_license | [
{
"docstring": ":type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]]",
"name": "_subsets",
"signature": "def _subsets(self, nums, start, partial, res)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsets",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_010445 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _subsets(self, nums, start, partial, res): :type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]]
- def subsets(self, nums): :type nums: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _subsets(self, nums, start, partial, res): :type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]]
- def subsets(self, nums): :type nums: L... | cd3900a7d91d1d94d308bc7a65533b8262781ee9 | <|skeleton|>
class Solution:
def _subsets(self, nums, start, partial, res):
""":type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]]"""
<|body_0|>
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _subsets(self, nums, start, partial, res):
""":type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]]"""
res.append(partial)
n = len(nums)
if start >= n:
return
for i in range(start, n):
self._subs... | the_stack_v2_python_sparse | lc0078_Subsets/lc0078.py | cgi0911/LeetCodePractice | train | 0 | |
d8ebff542419c09ec465f9825c3417ca679f6116 | [
"self.TBill_rate = pd.read_csv('../data/3m_TBillRate.csv').set_index('Date')\nself.Inflation = pd.read_csv('../data/AnnualizeInflation.csv').set_index('Date')\nself.CCI = pd.read_csv('../data/CCI.csv').set_index('Date')\nself.ChinaCPI = pd.read_csv('../data/ChinaCPI.csv').set_index('Date')\nself.ChinaM2 = pd.read_c... | <|body_start_0|>
self.TBill_rate = pd.read_csv('../data/3m_TBillRate.csv').set_index('Date')
self.Inflation = pd.read_csv('../data/AnnualizeInflation.csv').set_index('Date')
self.CCI = pd.read_csv('../data/CCI.csv').set_index('Date')
self.ChinaCPI = pd.read_csv('../data/ChinaCPI.csv').se... | macro | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class macro:
def __init__(self):
"""Read macro indicators"""
<|body_0|>
def add_a_macro_feature(self, price_df: pd.DataFrame, feature_df: pd.DataFrame, name: str, is_ex_rate=False) -> pd.DataFrame:
"""Make a new column for the feature in price_df. Match the date."""
... | stack_v2_sparse_classes_36k_train_005778 | 14,372 | no_license | [
{
"docstring": "Read macro indicators",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Make a new column for the feature in price_df. Match the date.",
"name": "add_a_macro_feature",
"signature": "def add_a_macro_feature(self, price_df: pd.DataFrame, feature_df:... | 3 | stack_v2_sparse_classes_30k_train_000184 | Implement the Python class `macro` described below.
Class description:
Implement the macro class.
Method signatures and docstrings:
- def __init__(self): Read macro indicators
- def add_a_macro_feature(self, price_df: pd.DataFrame, feature_df: pd.DataFrame, name: str, is_ex_rate=False) -> pd.DataFrame: Make a new col... | Implement the Python class `macro` described below.
Class description:
Implement the macro class.
Method signatures and docstrings:
- def __init__(self): Read macro indicators
- def add_a_macro_feature(self, price_df: pd.DataFrame, feature_df: pd.DataFrame, name: str, is_ex_rate=False) -> pd.DataFrame: Make a new col... | f261d111e28cae96097bf965948bb8c32c770f62 | <|skeleton|>
class macro:
def __init__(self):
"""Read macro indicators"""
<|body_0|>
def add_a_macro_feature(self, price_df: pd.DataFrame, feature_df: pd.DataFrame, name: str, is_ex_rate=False) -> pd.DataFrame:
"""Make a new column for the feature in price_df. Match the date."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class macro:
def __init__(self):
"""Read macro indicators"""
self.TBill_rate = pd.read_csv('../data/3m_TBillRate.csv').set_index('Date')
self.Inflation = pd.read_csv('../data/AnnualizeInflation.csv').set_index('Date')
self.CCI = pd.read_csv('../data/CCI.csv').set_index('Date')
... | the_stack_v2_python_sparse | src/get_data.py | hanktsai404/EE5183-Final-project-G4 | train | 0 | |
03175f29f9dfd3d4985bbb83ef6bd2c6c93db9af | [
"logger.info('Overriding class: Optimizer -> PVS.')\nsuper(PVS, self).__init__()\nself.build(params)\nlogger.info('Class overrided.')",
"space.agents.sort(key=lambda x: x.fit)\nfor i, agent in enumerate(space.agents):\n a = copy.deepcopy(agent)\n R = [0, 0]\n while R[0] == R[1]:\n R = r.generate_i... | <|body_start_0|>
logger.info('Overriding class: Optimizer -> PVS.')
super(PVS, self).__init__()
self.build(params)
logger.info('Class overrided.')
<|end_body_0|>
<|body_start_1|>
space.agents.sort(key=lambda x: x.fit)
for i, agent in enumerate(space.agents):
... | A PVS class, inherited from Optimizer. This is the designed class to define PVS-related variables and methods. References: P. Savsani and V. Savsani. Passing vehicle search (PVS): A novel metaheuristic algorithm. Applied Mathematical Modelling (2016). | PVS | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PVS:
"""A PVS class, inherited from Optimizer. This is the designed class to define PVS-related variables and methods. References: P. Savsani and V. Savsani. Passing vehicle search (PVS): A novel metaheuristic algorithm. Applied Mathematical Modelling (2016)."""
def __init__(self, params: Op... | stack_v2_sparse_classes_36k_train_005779 | 3,450 | permissive | [
{
"docstring": "Initialization method. Args: params: Contains key-value parameters to the meta-heuristics.",
"name": "__init__",
"signature": "def __init__(self, params: Optional[Dict[str, Any]]=None) -> None"
},
{
"docstring": "Wraps Passing Vehicle Search over all agents and variables. Args: s... | 2 | null | Implement the Python class `PVS` described below.
Class description:
A PVS class, inherited from Optimizer. This is the designed class to define PVS-related variables and methods. References: P. Savsani and V. Savsani. Passing vehicle search (PVS): A novel metaheuristic algorithm. Applied Mathematical Modelling (2016)... | Implement the Python class `PVS` described below.
Class description:
A PVS class, inherited from Optimizer. This is the designed class to define PVS-related variables and methods. References: P. Savsani and V. Savsani. Passing vehicle search (PVS): A novel metaheuristic algorithm. Applied Mathematical Modelling (2016)... | 7326a887ed8e3858bc99c8815048d56d02edf88c | <|skeleton|>
class PVS:
"""A PVS class, inherited from Optimizer. This is the designed class to define PVS-related variables and methods. References: P. Savsani and V. Savsani. Passing vehicle search (PVS): A novel metaheuristic algorithm. Applied Mathematical Modelling (2016)."""
def __init__(self, params: Op... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PVS:
"""A PVS class, inherited from Optimizer. This is the designed class to define PVS-related variables and methods. References: P. Savsani and V. Savsani. Passing vehicle search (PVS): A novel metaheuristic algorithm. Applied Mathematical Modelling (2016)."""
def __init__(self, params: Optional[Dict[s... | the_stack_v2_python_sparse | opytimizer/optimizers/population/pvs.py | gugarosa/opytimizer | train | 602 |
f8e08dd6d52334332dcaaee8fca3fe55309bf68c | [
"self._task_list = []\nwhile True:\n try:\n self._Start(in_path, in_file)\n break\n except actions.ServerChangeEvent:\n in_path = ''\ntry:\n files.Dump(out_file, self._task_list, mode='a')\nexcept files.Error as e:\n raise ConfigBuilderError() from e",
"self._build_info.ActiveConf... | <|body_start_0|>
self._task_list = []
while True:
try:
self._Start(in_path, in_file)
break
except actions.ServerChangeEvent:
in_path = ''
try:
files.Dump(out_file, self._task_list, mode='a')
except files.... | Builds the complete task list for the installation. | ConfigBuilder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigBuilder:
"""Builds the complete task list for the installation."""
def Start(self, out_file, in_path, in_file='build.yaml'):
"""Start parsing configuration files. Args: out_file: The location to store the compiled config data. in_path: The path to the root configuration file. i... | stack_v2_sparse_classes_36k_train_005780 | 7,079 | permissive | [
{
"docstring": "Start parsing configuration files. Args: out_file: The location to store the compiled config data. in_path: The path to the root configuration file. in_file: The root configuration file name.",
"name": "Start",
"signature": "def Start(self, out_file, in_path, in_file='build.yaml')"
},
... | 4 | stack_v2_sparse_classes_30k_train_000065 | Implement the Python class `ConfigBuilder` described below.
Class description:
Builds the complete task list for the installation.
Method signatures and docstrings:
- def Start(self, out_file, in_path, in_file='build.yaml'): Start parsing configuration files. Args: out_file: The location to store the compiled config ... | Implement the Python class `ConfigBuilder` described below.
Class description:
Builds the complete task list for the installation.
Method signatures and docstrings:
- def Start(self, out_file, in_path, in_file='build.yaml'): Start parsing configuration files. Args: out_file: The location to store the compiled config ... | ec44cb163f54d1393b0a2c2730d5d0d9d0fc8515 | <|skeleton|>
class ConfigBuilder:
"""Builds the complete task list for the installation."""
def Start(self, out_file, in_path, in_file='build.yaml'):
"""Start parsing configuration files. Args: out_file: The location to store the compiled config data. in_path: The path to the root configuration file. i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigBuilder:
"""Builds the complete task list for the installation."""
def Start(self, out_file, in_path, in_file='build.yaml'):
"""Start parsing configuration files. Args: out_file: The location to store the compiled config data. in_path: The path to the root configuration file. in_file: The r... | the_stack_v2_python_sparse | glazier/lib/config/builder.py | google/glazier | train | 1,311 |
e78cc8fbf109fe6cfc8124cdf3901ff09107a538 | [
"INF = 2147483647\n\ndef shortestDistance(row, col):\n visited = []\n r_queue = [(row + 1, col), (row - 1, col), (row, col + 1), (row, col - 1)]\n distance = 0\n while r_queue:\n len_q = len(r_queue)\n for k in range(len_q):\n i, j = r_queue.pop(0)\n visited += [(i, j... | <|body_start_0|>
INF = 2147483647
def shortestDistance(row, col):
visited = []
r_queue = [(row + 1, col), (row - 1, col), (row, col + 1), (row, col - 1)]
distance = 0
while r_queue:
len_q = len(r_queue)
for k in range(len_q... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wallsAndGates_I(self, rooms):
"""Do not return anything, modify rooms in-place instead."""
<|body_0|>
def wallsAndGates_II(self, rooms):
"""Do not return anything, modify rooms in-place instead."""
<|body_1|>
def wallsAndGates_III(self, roo... | stack_v2_sparse_classes_36k_train_005781 | 3,736 | no_license | [
{
"docstring": "Do not return anything, modify rooms in-place instead.",
"name": "wallsAndGates_I",
"signature": "def wallsAndGates_I(self, rooms)"
},
{
"docstring": "Do not return anything, modify rooms in-place instead.",
"name": "wallsAndGates_II",
"signature": "def wallsAndGates_II(s... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wallsAndGates_I(self, rooms): Do not return anything, modify rooms in-place instead.
- def wallsAndGates_II(self, rooms): Do not return anything, modify rooms in-place instea... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wallsAndGates_I(self, rooms): Do not return anything, modify rooms in-place instead.
- def wallsAndGates_II(self, rooms): Do not return anything, modify rooms in-place instea... | 1461b10b8910fa90a311939c6df9082a8526f9b1 | <|skeleton|>
class Solution:
def wallsAndGates_I(self, rooms):
"""Do not return anything, modify rooms in-place instead."""
<|body_0|>
def wallsAndGates_II(self, rooms):
"""Do not return anything, modify rooms in-place instead."""
<|body_1|>
def wallsAndGates_III(self, roo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wallsAndGates_I(self, rooms):
"""Do not return anything, modify rooms in-place instead."""
INF = 2147483647
def shortestDistance(row, col):
visited = []
r_queue = [(row + 1, col), (row - 1, col), (row, col + 1), (row, col - 1)]
distanc... | the_stack_v2_python_sparse | Medium/286_wallsAndGates.py | Yucheng7713/CodingPracticeByYuch | train | 0 | |
1f6b729890d6f9a21f299c53809fa45d9cffa2ca | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('alanbur_aquan_erj826_jcaluag', 'alanbur_aquan_erj826_jcaluag')\nurl = 'https://data.sfgov.org/resource/vv57-2fgy.json'\nresponse = requests.get(url).text\nr = json.loads(response)\nrepo.dropCollection('S... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('alanbur_aquan_erj826_jcaluag', 'alanbur_aquan_erj826_jcaluag')
url = 'https://data.sfgov.org/resource/vv57-2fgy.json'
response = requests.get(url)... | getSFAccidents | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getSFAccidents:
def execute(trial=False):
"""Retrieve crime incident report information from Boston."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this s... | stack_v2_sparse_classes_36k_train_005782 | 4,217 | no_license | [
{
"docstring": "Retrieve crime incident report information from Boston.",
"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 document describing th... | 2 | null | Implement the Python class `getSFAccidents` described below.
Class description:
Implement the getSFAccidents class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve crime incident report information from Boston.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Creat... | Implement the Python class `getSFAccidents` described below.
Class description:
Implement the getSFAccidents class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve crime incident report information from Boston.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Creat... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class getSFAccidents:
def execute(trial=False):
"""Retrieve crime incident report information from Boston."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class getSFAccidents:
def execute(trial=False):
"""Retrieve crime incident report information from Boston."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('alanbur_aquan_erj826_jcaluag', 'alanbur_aquan_erj826_jcal... | the_stack_v2_python_sparse | alanbur_aquan_erj826_jcaluag/getSFAccidents.py | ROODAY/course-2017-fal-proj | train | 3 | |
cf9ec76dac9fbe5f467fb8b66415d108fe7eb25e | [
"filter_dict.update({'status': {'$ne': -1}})\npipeline = list()\nproduct_cond = {'$lookup': {'from': 'product_info', 'let': {'pid': '$product_id'}, 'pipeline': [{'$match': {'$expr': {'$eq': ['$_id', '$$pid']}}}, {'$project': {'_id': 0}}], 'as': 'product_item'}}\npipeline.append(product_cond)\nrep1 = {'$replaceRoot'... | <|body_start_0|>
filter_dict.update({'status': {'$ne': -1}})
pipeline = list()
product_cond = {'$lookup': {'from': 'product_info', 'let': {'pid': '$product_id'}, 'pipeline': [{'$match': {'$expr': {'$eq': ['$_id', '$$pid']}}}, {'$project': {'_id': 0}}], 'as': 'product_item'}}
pipeline.app... | 生产任务 | ProduceTask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProduceTask:
"""生产任务"""
def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: int=10) -> dict:
"""分页查看生产任务信息.由于涉及的关系复杂,这里使用了cls.aggregate函数 :param filter_dict: 过滤器,由用户的权限生成 :param page_index: 页码(当前页码) :param page_size: 每页多少条记录 :return:"""
<|body_0|>
def d... | stack_v2_sparse_classes_36k_train_005783 | 27,644 | no_license | [
{
"docstring": "分页查看生产任务信息.由于涉及的关系复杂,这里使用了cls.aggregate函数 :param filter_dict: 过滤器,由用户的权限生成 :param page_index: 页码(当前页码) :param page_size: 每页多少条记录 :return:",
"name": "paging_info",
"signature": "def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: int=10) -> dict"
},
{
"docstring"... | 3 | null | Implement the Python class `ProduceTask` described below.
Class description:
生产任务
Method signatures and docstrings:
- def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: int=10) -> dict: 分页查看生产任务信息.由于涉及的关系复杂,这里使用了cls.aggregate函数 :param filter_dict: 过滤器,由用户的权限生成 :param page_index: 页码(当前页码) :param pag... | Implement the Python class `ProduceTask` described below.
Class description:
生产任务
Method signatures and docstrings:
- def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: int=10) -> dict: 分页查看生产任务信息.由于涉及的关系复杂,这里使用了cls.aggregate函数 :param filter_dict: 过滤器,由用户的权限生成 :param page_index: 页码(当前页码) :param pag... | 3a2bdfd1598bfcdfe56386ec0c46fcede772cbfe | <|skeleton|>
class ProduceTask:
"""生产任务"""
def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: int=10) -> dict:
"""分页查看生产任务信息.由于涉及的关系复杂,这里使用了cls.aggregate函数 :param filter_dict: 过滤器,由用户的权限生成 :param page_index: 页码(当前页码) :param page_size: 每页多少条记录 :return:"""
<|body_0|>
def d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProduceTask:
"""生产任务"""
def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: int=10) -> dict:
"""分页查看生产任务信息.由于涉及的关系复杂,这里使用了cls.aggregate函数 :param filter_dict: 过滤器,由用户的权限生成 :param page_index: 页码(当前页码) :param page_size: 每页多少条记录 :return:"""
filter_dict.update({'status': {'$n... | the_stack_v2_python_sparse | query_server/module/system_module.py | SYYDSN/py_projects | train | 0 |
d5eef808db9fe0a0f47171e4bf4e4a1da8122d36 | [
"def inOrder(node):\n if node is None:\n return\n inOrder(node.left)\n arr.append(node)\n inOrder(node.right)\narr = []\ninOrder(root)\nsize = len(arr)\nif size == 0:\n return root\nfor i in range(size):\n if i == 0:\n arr[i].left = arr[size - 1]\n arr[i].right = arr[0] if i +... | <|body_start_0|>
def inOrder(node):
if node is None:
return
inOrder(node.left)
arr.append(node)
inOrder(node.right)
arr = []
inOrder(root)
size = len(arr)
if size == 0:
return root
for i in range(... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def treeToDoublyList(self, root: TreeNode) -> TreeNode:
"""模拟"""
<|body_0|>
def treeToDoublyList1(self, root: TreeNode) -> TreeNode:
"""递归:根据以上分析,考虑使用[中序遍历]访问树的各节点 cur ;并在访问每个节点时构建 cur 和前驱节点 pre 的引用指向;中序遍历完成后,最后构建头节点和尾节点的引用指向即可。"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_005784 | 3,706 | permissive | [
{
"docstring": "模拟",
"name": "treeToDoublyList",
"signature": "def treeToDoublyList(self, root: TreeNode) -> TreeNode"
},
{
"docstring": "递归:根据以上分析,考虑使用[中序遍历]访问树的各节点 cur ;并在访问每个节点时构建 cur 和前驱节点 pre 的引用指向;中序遍历完成后,最后构建头节点和尾节点的引用指向即可。",
"name": "treeToDoublyList1",
"signature": "def treeToDo... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def treeToDoublyList(self, root: TreeNode) -> TreeNode: 模拟
- def treeToDoublyList1(self, root: TreeNode) -> TreeNode: 递归:根据以上分析,考虑使用[中序遍历]访问树的各节点 cur ;并在访问每个节点时构建 cur 和前驱节点 pre 的... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def treeToDoublyList(self, root: TreeNode) -> TreeNode: 模拟
- def treeToDoublyList1(self, root: TreeNode) -> TreeNode: 递归:根据以上分析,考虑使用[中序遍历]访问树的各节点 cur ;并在访问每个节点时构建 cur 和前驱节点 pre 的... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def treeToDoublyList(self, root: TreeNode) -> TreeNode:
"""模拟"""
<|body_0|>
def treeToDoublyList1(self, root: TreeNode) -> TreeNode:
"""递归:根据以上分析,考虑使用[中序遍历]访问树的各节点 cur ;并在访问每个节点时构建 cur 和前驱节点 pre 的引用指向;中序遍历完成后,最后构建头节点和尾节点的引用指向即可。"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def treeToDoublyList(self, root: TreeNode) -> TreeNode:
"""模拟"""
def inOrder(node):
if node is None:
return
inOrder(node.left)
arr.append(node)
inOrder(node.right)
arr = []
inOrder(root)
size = le... | the_stack_v2_python_sparse | lcof/36-er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof.py | yuenliou/leetcode | train | 0 | |
5cab765f46877ded7ecabf8e8b5e9c27a6ac88b9 | [
"self.product_code = product_code\nself.description = description\nself.market_price = market_price\nself.rental_price = rental_price",
"output_dict = {}\noutput_dict['product_code'] = self.product_code\noutput_dict['description'] = self.description\noutput_dict['market_price'] = self.market_price\noutput_dict['r... | <|body_start_0|>
self.product_code = product_code
self.description = description
self.market_price = market_price
self.rental_price = rental_price
<|end_body_0|>
<|body_start_1|>
output_dict = {}
output_dict['product_code'] = self.product_code
output_dict['descri... | contains all information about each item in the inventory | Inventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Inventory:
"""contains all information about each item in the inventory"""
def __init__(self, product_code, description, market_price, rental_price):
"""initializes class"""
<|body_0|>
def return_as_dictionary(self):
"""returns Inventory information as a dictiona... | stack_v2_sparse_classes_36k_train_005785 | 1,378 | no_license | [
{
"docstring": "initializes class",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price)"
},
{
"docstring": "returns Inventory information as a dictionary",
"name": "return_as_dictionary",
"signature": "def return_as_dictionary(self)... | 2 | stack_v2_sparse_classes_30k_train_006734 | Implement the Python class `Inventory` described below.
Class description:
contains all information about each item in the inventory
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price): initializes class
- def return_as_dictionary(self): returns Inventory info... | Implement the Python class `Inventory` described below.
Class description:
contains all information about each item in the inventory
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price): initializes class
- def return_as_dictionary(self): returns Inventory info... | 99271cd60485bd2e54f8d133c9057a2ccd6c91c2 | <|skeleton|>
class Inventory:
"""contains all information about each item in the inventory"""
def __init__(self, product_code, description, market_price, rental_price):
"""initializes class"""
<|body_0|>
def return_as_dictionary(self):
"""returns Inventory information as a dictiona... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Inventory:
"""contains all information about each item in the inventory"""
def __init__(self, product_code, description, market_price, rental_price):
"""initializes class"""
self.product_code = product_code
self.description = description
self.market_price = market_price
... | the_stack_v2_python_sparse | students/Zach Cooper/lesson01/inventory_management/inventoryClass.py | zconn/PythonCert220Assign | train | 2 |
3a24db1801f12f60cb7b3ea086f9f1d60870abd9 | [
"josep = list(range(n))\nindex = 0\nwhile josep:\n temp = josep.pop(0)\n index += 1\n if index == m:\n index = 0\n if len(josep) == 1:\n return josep[0]\n continue\n josep.append(temp)\n if len(josep) == 1:\n return josep[0]",
"if m < 1 or n < 1:\n return -... | <|body_start_0|>
josep = list(range(n))
index = 0
while josep:
temp = josep.pop(0)
index += 1
if index == m:
index = 0
if len(josep) == 1:
return josep[0]
continue
josep.append(tem... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lastRemaining(self, n, m):
""":type n: int :type m: int :rtype: int"""
<|body_0|>
def lastRemaining(self, n, m):
""":type n: int :type m: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
josep = list(range(n))
in... | stack_v2_sparse_classes_36k_train_005786 | 944 | no_license | [
{
"docstring": ":type n: int :type m: int :rtype: int",
"name": "lastRemaining",
"signature": "def lastRemaining(self, n, m)"
},
{
"docstring": ":type n: int :type m: int :rtype: int",
"name": "lastRemaining",
"signature": "def lastRemaining(self, n, m)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001048 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lastRemaining(self, n, m): :type n: int :type m: int :rtype: int
- def lastRemaining(self, n, m): :type n: int :type m: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lastRemaining(self, n, m): :type n: int :type m: int :rtype: int
- def lastRemaining(self, n, m): :type n: int :type m: int :rtype: int
<|skeleton|>
class Solution:
def... | e7fb78b30750cff774518a8d77463b7f3dba36de | <|skeleton|>
class Solution:
def lastRemaining(self, n, m):
""":type n: int :type m: int :rtype: int"""
<|body_0|>
def lastRemaining(self, n, m):
""":type n: int :type m: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lastRemaining(self, n, m):
""":type n: int :type m: int :rtype: int"""
josep = list(range(n))
index = 0
while josep:
temp = josep.pop(0)
index += 1
if index == m:
index = 0
if len(josep) == 1:
... | the_stack_v2_python_sparse | 45圆圈中最后剩下的数字.py | HuangZengPei/Sword-Offer-python | train | 0 | |
94598160a74a07fe6b126573f8719daab6775348 | [
"self.model = model\nself.dataset = dataset\nself.output_transformers = [transformer for transformer in transformers if transformer.transform_y]",
"logger.warning('Evaluator.output_statistics is deprecated.Please use dc.utils.evaluate.output_statistics instead.This method will be removed in a future version of De... | <|body_start_0|>
self.model = model
self.dataset = dataset
self.output_transformers = [transformer for transformer in transformers if transformer.transform_y]
<|end_body_0|>
<|body_start_1|>
logger.warning('Evaluator.output_statistics is deprecated.Please use dc.utils.evaluate.output_st... | Class that evaluates a model on a given dataset. The evaluator class is used to evaluate a `dc.models.Model` class on a given `dc.data.Dataset` object. The evaluator is aware of `dc.trans.Transformer` objects so will automatically undo any transformations which have been applied. Examples -------- Evaluators allow for ... | Evaluator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Evaluator:
"""Class that evaluates a model on a given dataset. The evaluator class is used to evaluate a `dc.models.Model` class on a given `dc.data.Dataset` object. The evaluator is aware of `dc.trans.Transformer` objects so will automatically undo any transformations which have been applied. Ex... | stack_v2_sparse_classes_36k_train_005787 | 19,454 | permissive | [
{
"docstring": "Initialize this evaluator Parameters ---------- model: Model Model to evaluate. Note that this must be a regression or classification model and not a generative model. dataset: Dataset Dataset object to evaluate `model` on. transformers: List[Transformer] List of `dc.trans.Transformer` objects. ... | 4 | null | Implement the Python class `Evaluator` described below.
Class description:
Class that evaluates a model on a given dataset. The evaluator class is used to evaluate a `dc.models.Model` class on a given `dc.data.Dataset` object. The evaluator is aware of `dc.trans.Transformer` objects so will automatically undo any tran... | Implement the Python class `Evaluator` described below.
Class description:
Class that evaluates a model on a given dataset. The evaluator class is used to evaluate a `dc.models.Model` class on a given `dc.data.Dataset` object. The evaluator is aware of `dc.trans.Transformer` objects so will automatically undo any tran... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class Evaluator:
"""Class that evaluates a model on a given dataset. The evaluator class is used to evaluate a `dc.models.Model` class on a given `dc.data.Dataset` object. The evaluator is aware of `dc.trans.Transformer` objects so will automatically undo any transformations which have been applied. Ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Evaluator:
"""Class that evaluates a model on a given dataset. The evaluator class is used to evaluate a `dc.models.Model` class on a given `dc.data.Dataset` object. The evaluator is aware of `dc.trans.Transformer` objects so will automatically undo any transformations which have been applied. Examples ------... | the_stack_v2_python_sparse | deepchem/utils/evaluate.py | deepchem/deepchem | train | 4,876 |
b6c40b5f482b828508acac2ccb8f8a7e9e1bdf21 | [
"if game_object is None:\n return False\nreturn game_object.has_any_tag(tuple(tags))",
"if game_object is None:\n return set()\nreturn game_object.get_tags()",
"if game_object is None:\n return False\ngame_object.append_tags(set(tags), persist=persist)\nreturn True"
] | <|body_start_0|>
if game_object is None:
return False
return game_object.has_any_tag(tuple(tags))
<|end_body_0|>
<|body_start_1|>
if game_object is None:
return set()
return game_object.get_tags()
<|end_body_1|>
<|body_start_2|>
if game_object is None:
... | Utilities for manipulating the tags of objects. | CommonObjectTagUtils | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonObjectTagUtils:
"""Utilities for manipulating the tags of objects."""
def has_game_tags(game_object: GameObject, tags: Iterator[Union[int, CommonGameTag]]) -> bool:
"""has_game_tags(game_object, tags) Determine if an Object has any of the specified tags. :param game_object: An ... | stack_v2_sparse_classes_36k_train_005788 | 2,429 | permissive | [
{
"docstring": "has_game_tags(game_object, tags) Determine if an Object has any of the specified tags. :param game_object: An instance of an Object. :type game_object: GameObject :param tags: A collection of tags to locate. :type tags: Iterator[Union[int, CommonGameTag]] :return: True, if the Object has any of ... | 3 | null | Implement the Python class `CommonObjectTagUtils` described below.
Class description:
Utilities for manipulating the tags of objects.
Method signatures and docstrings:
- def has_game_tags(game_object: GameObject, tags: Iterator[Union[int, CommonGameTag]]) -> bool: has_game_tags(game_object, tags) Determine if an Obje... | Implement the Python class `CommonObjectTagUtils` described below.
Class description:
Utilities for manipulating the tags of objects.
Method signatures and docstrings:
- def has_game_tags(game_object: GameObject, tags: Iterator[Union[int, CommonGameTag]]) -> bool: has_game_tags(game_object, tags) Determine if an Obje... | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | <|skeleton|>
class CommonObjectTagUtils:
"""Utilities for manipulating the tags of objects."""
def has_game_tags(game_object: GameObject, tags: Iterator[Union[int, CommonGameTag]]) -> bool:
"""has_game_tags(game_object, tags) Determine if an Object has any of the specified tags. :param game_object: An ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommonObjectTagUtils:
"""Utilities for manipulating the tags of objects."""
def has_game_tags(game_object: GameObject, tags: Iterator[Union[int, CommonGameTag]]) -> bool:
"""has_game_tags(game_object, tags) Determine if an Object has any of the specified tags. :param game_object: An instance of a... | the_stack_v2_python_sparse | src/sims4communitylib/utils/objects/common_object_tag_utils.py | velocist/TS4CheatsInfo | train | 1 |
d5a7bfb45084a93ac09df2891a9b69dec3f068d5 | [
"self.auth = auth\nif isinstance(aid, FaceUAccount):\n self.account = aid\nelse:\n self.account = self.get_account_model(aid)",
"if not aid:\n return None\naccount = FaceUAccount.objects.get_once(pk=aid)\nif not account:\n raise FaceUAccountInfoExcept.account_is_not_exists()\nreturn account",
"if no... | <|body_start_0|>
self.auth = auth
if isinstance(aid, FaceUAccount):
self.account = aid
else:
self.account = self.get_account_model(aid)
<|end_body_0|>
<|body_start_1|>
if not aid:
return None
account = FaceUAccount.objects.get_once(pk=aid)
... | FaceUAccountLogic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaceUAccountLogic:
def __init__(self, auth, aid=''):
"""INIT :param auth: :param aid:"""
<|body_0|>
def get_account_model(self, aid):
"""获取用户model :param aid: :return:"""
<|body_1|>
def get_account_info(self):
"""获取用户信息 :return:"""
<|body... | stack_v2_sparse_classes_36k_train_005789 | 1,363 | no_license | [
{
"docstring": "INIT :param auth: :param aid:",
"name": "__init__",
"signature": "def __init__(self, auth, aid='')"
},
{
"docstring": "获取用户model :param aid: :return:",
"name": "get_account_model",
"signature": "def get_account_model(self, aid)"
},
{
"docstring": "获取用户信息 :return:"... | 3 | null | Implement the Python class `FaceUAccountLogic` described below.
Class description:
Implement the FaceUAccountLogic class.
Method signatures and docstrings:
- def __init__(self, auth, aid=''): INIT :param auth: :param aid:
- def get_account_model(self, aid): 获取用户model :param aid: :return:
- def get_account_info(self):... | Implement the Python class `FaceUAccountLogic` described below.
Class description:
Implement the FaceUAccountLogic class.
Method signatures and docstrings:
- def __init__(self, auth, aid=''): INIT :param auth: :param aid:
- def get_account_model(self, aid): 获取用户model :param aid: :return:
- def get_account_info(self):... | 7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b | <|skeleton|>
class FaceUAccountLogic:
def __init__(self, auth, aid=''):
"""INIT :param auth: :param aid:"""
<|body_0|>
def get_account_model(self, aid):
"""获取用户model :param aid: :return:"""
<|body_1|>
def get_account_info(self):
"""获取用户信息 :return:"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FaceUAccountLogic:
def __init__(self, auth, aid=''):
"""INIT :param auth: :param aid:"""
self.auth = auth
if isinstance(aid, FaceUAccount):
self.account = aid
else:
self.account = self.get_account_model(aid)
def get_account_model(self, aid):
... | the_stack_v2_python_sparse | FireHydrant/server/faceU/logic/account.py | shoogoome/FireHydrant | train | 4 | |
105c1c27dcf773e0cabd22e4dddd089532be9663 | [
"super(ZWaveTriggerSensor, self).__init__(sensor_value)\nself._hass = hass\nself.invalidate_after = dt_util.utcnow()\nself.re_arm_sec = re_arm_sec",
"if self._value.value_id == value.value_id:\n self.update_ha_state()\n if value.data:\n self.invalidate_after = dt_util.utcnow() + datetime.timedelta(se... | <|body_start_0|>
super(ZWaveTriggerSensor, self).__init__(sensor_value)
self._hass = hass
self.invalidate_after = dt_util.utcnow()
self.re_arm_sec = re_arm_sec
<|end_body_0|>
<|body_start_1|>
if self._value.value_id == value.value_id:
self.update_ha_state()
... | Represents a stateless sensor which triggers events just 'On' within Z-Wave. | ZWaveTriggerSensor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZWaveTriggerSensor:
"""Represents a stateless sensor which triggers events just 'On' within Z-Wave."""
def __init__(self, sensor_value, hass, re_arm_sec=60):
""":param sensor_value: The z-wave node :param hass: :param re_arm_sec: Set state to Off re_arm_sec after the last On event :r... | stack_v2_sparse_classes_36k_train_005790 | 6,826 | permissive | [
{
"docstring": ":param sensor_value: The z-wave node :param hass: :param re_arm_sec: Set state to Off re_arm_sec after the last On event :return:",
"name": "__init__",
"signature": "def __init__(self, sensor_value, hass, re_arm_sec=60)"
},
{
"docstring": "Called when a value has changed on the n... | 3 | null | Implement the Python class `ZWaveTriggerSensor` described below.
Class description:
Represents a stateless sensor which triggers events just 'On' within Z-Wave.
Method signatures and docstrings:
- def __init__(self, sensor_value, hass, re_arm_sec=60): :param sensor_value: The z-wave node :param hass: :param re_arm_se... | Implement the Python class `ZWaveTriggerSensor` described below.
Class description:
Represents a stateless sensor which triggers events just 'On' within Z-Wave.
Method signatures and docstrings:
- def __init__(self, sensor_value, hass, re_arm_sec=60): :param sensor_value: The z-wave node :param hass: :param re_arm_se... | 5a808d4e7df4d8d0f12cc5b7e6cff0ddf42b1d40 | <|skeleton|>
class ZWaveTriggerSensor:
"""Represents a stateless sensor which triggers events just 'On' within Z-Wave."""
def __init__(self, sensor_value, hass, re_arm_sec=60):
""":param sensor_value: The z-wave node :param hass: :param re_arm_sec: Set state to Off re_arm_sec after the last On event :r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZWaveTriggerSensor:
"""Represents a stateless sensor which triggers events just 'On' within Z-Wave."""
def __init__(self, sensor_value, hass, re_arm_sec=60):
""":param sensor_value: The z-wave node :param hass: :param re_arm_sec: Set state to Off re_arm_sec after the last On event :return:"""
... | the_stack_v2_python_sparse | out/production/home-assistant/components/sensor/zwave.py | LaurentTrk/home-assistant | train | 2 |
8d8fffdc351023aa2ebd3667b1db3d381da4a3a2 | [
"encoded_str = []\nfor word in strs:\n encoded_str.append(str(len(word)))\n encoded_str.append('/')\n encoded_str.append(word)\nreturn ''.join(encoded_str)",
"words = []\ni = 0\nwhile i < len(s):\n slash_index = s.find('/', i)\n size = int(s[i:slash_index])\n words.append(s[slash_index + 1:slash... | <|body_start_0|>
encoded_str = []
for word in strs:
encoded_str.append(str(len(word)))
encoded_str.append('/')
encoded_str.append(word)
return ''.join(encoded_str)
<|end_body_0|>
<|body_start_1|>
words = []
i = 0
while i < len(s):
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_005791 | 1,009 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_001278 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | 9d0ff0f8705451947a6605ab5ef92bb3e27a7147 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
encoded_str = []
for word in strs:
encoded_str.append(str(len(word)))
encoded_str.append('/')
encoded_str.append(word)
return... | the_stack_v2_python_sparse | string/encode_and_decode_strings.py | rayt579/leetcode | train | 0 | |
58e2d5f1dbf8fde503afe39f8d6e66594cc3aed0 | [
"super(MultiBoxLoss, self).__init__()\nself.neg_pos_ratio = neg_pos_ratio\nself.focalloss = FocalLoss()",
"num_classes = 2\nwith torch.no_grad():\n loss = -F.log_softmax(confidence, dim=2)[:, :, 0]\nmask = box_utils.hard_negative_mining(loss, labels, self.neg_pos_ratio)\nconfidence = confidence[mask, :]\nclass... | <|body_start_0|>
super(MultiBoxLoss, self).__init__()
self.neg_pos_ratio = neg_pos_ratio
self.focalloss = FocalLoss()
<|end_body_0|>
<|body_start_1|>
num_classes = 2
with torch.no_grad():
loss = -F.log_softmax(confidence, dim=2)[:, :, 0]
mask = box_utils.hard... | MultiBoxLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiBoxLoss:
def __init__(self, neg_pos_ratio):
"""Implement SSD MultiBox Loss. Basically, MultiBox loss combines classification loss and Smooth L1 regression loss."""
<|body_0|>
def forward(self, confidence, predicted_locations, labels, gt_locations):
"""Compute cl... | stack_v2_sparse_classes_36k_train_005792 | 3,998 | permissive | [
{
"docstring": "Implement SSD MultiBox Loss. Basically, MultiBox loss combines classification loss and Smooth L1 regression loss.",
"name": "__init__",
"signature": "def __init__(self, neg_pos_ratio)"
},
{
"docstring": "Compute classification loss and smooth l1 loss. Args: confidence (batch_size... | 2 | stack_v2_sparse_classes_30k_train_003732 | Implement the Python class `MultiBoxLoss` described below.
Class description:
Implement the MultiBoxLoss class.
Method signatures and docstrings:
- def __init__(self, neg_pos_ratio): Implement SSD MultiBox Loss. Basically, MultiBox loss combines classification loss and Smooth L1 regression loss.
- def forward(self, c... | Implement the Python class `MultiBoxLoss` described below.
Class description:
Implement the MultiBoxLoss class.
Method signatures and docstrings:
- def __init__(self, neg_pos_ratio): Implement SSD MultiBox Loss. Basically, MultiBox loss combines classification loss and Smooth L1 regression loss.
- def forward(self, c... | 0e3aaed47b2e8335ae4bba92d589ca8b45af9c37 | <|skeleton|>
class MultiBoxLoss:
def __init__(self, neg_pos_ratio):
"""Implement SSD MultiBox Loss. Basically, MultiBox loss combines classification loss and Smooth L1 regression loss."""
<|body_0|>
def forward(self, confidence, predicted_locations, labels, gt_locations):
"""Compute cl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiBoxLoss:
def __init__(self, neg_pos_ratio):
"""Implement SSD MultiBox Loss. Basically, MultiBox loss combines classification loss and Smooth L1 regression loss."""
super(MultiBoxLoss, self).__init__()
self.neg_pos_ratio = neg_pos_ratio
self.focalloss = FocalLoss()
def... | the_stack_v2_python_sparse | ssd/modeling/multibox_loss.py | kapitsa2811/ssd_fcn_multitask_text_detection_pytorch1.0 | train | 0 | |
01900c1d14a04ee43553c8602a07e0c6ecfabded | [
"request = self.context['request']\ndata.setdefault('user', request.user)\ndata.setdefault('device_user_token', None)\nif not request.user.is_authenticated():\n raise serializers.ValidationError('user is not logged in.')\ntry:\n self.instance = DeviceUser.objects.get(**data)\nexcept DeviceUser.DoesNotExist:\n... | <|body_start_0|>
request = self.context['request']
data.setdefault('user', request.user)
data.setdefault('device_user_token', None)
if not request.user.is_authenticated():
raise serializers.ValidationError('user is not logged in.')
try:
self.instance = Dev... | Serializer for log users out. | LogoutSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogoutSerializer:
"""Serializer for log users out."""
def validate(self, data):
"""Validate that the requesting user owns the given device."""
<|body_0|>
def update(self):
"""Mark the given device as inactive."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_005793 | 4,186 | permissive | [
{
"docstring": "Validate that the requesting user owns the given device.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Mark the given device as inactive.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007210 | Implement the Python class `LogoutSerializer` described below.
Class description:
Serializer for log users out.
Method signatures and docstrings:
- def validate(self, data): Validate that the requesting user owns the given device.
- def update(self): Mark the given device as inactive. | Implement the Python class `LogoutSerializer` described below.
Class description:
Serializer for log users out.
Method signatures and docstrings:
- def validate(self, data): Validate that the requesting user owns the given device.
- def update(self): Mark the given device as inactive.
<|skeleton|>
class LogoutSerial... | 7349ce18f56658d67daedf5e1abb352b5c15a029 | <|skeleton|>
class LogoutSerializer:
"""Serializer for log users out."""
def validate(self, data):
"""Validate that the requesting user owns the given device."""
<|body_0|>
def update(self):
"""Mark the given device as inactive."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogoutSerializer:
"""Serializer for log users out."""
def validate(self, data):
"""Validate that the requesting user owns the given device."""
request = self.context['request']
data.setdefault('user', request.user)
data.setdefault('device_user_token', None)
if not ... | the_stack_v2_python_sparse | src/tandlr/authentication/serializers.py | shrmoud/schoolapp | train | 0 |
2a1ffefb9cbca521e658bdbaa5e4842aab16f96b | [
"self.char_cnn_layers = hyper_parameters['model'].get('char_cnn_layers', [[256, 7, 3], [256, 7, 3], [256, 3, -1], [256, 3, -1], [256, 3, -1], [256, 3, 3]])\nself.full_connect_layers = hyper_parameters['model'].get('full_connect_layers', [1024, 1024])\nself.threshold = hyper_parameters['model'].get('threshold', 1e-0... | <|body_start_0|>
self.char_cnn_layers = hyper_parameters['model'].get('char_cnn_layers', [[256, 7, 3], [256, 7, 3], [256, 3, -1], [256, 3, -1], [256, 3, -1], [256, 3, 3]])
self.full_connect_layers = hyper_parameters['model'].get('full_connect_layers', [1024, 1024])
self.threshold = hyper_paramet... | CharCNNGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CharCNNGraph:
def __init__(self, hyper_parameters):
"""初始化 :param hyper_parameters: json,超参"""
<|body_0|>
def create_model(self, hyper_parameters):
"""构建神经网络 :param hyper_parameters:json, hyper parameters of network :return: tensor, moedl"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_005794 | 2,306 | permissive | [
{
"docstring": "初始化 :param hyper_parameters: json,超参",
"name": "__init__",
"signature": "def __init__(self, hyper_parameters)"
},
{
"docstring": "构建神经网络 :param hyper_parameters:json, hyper parameters of network :return: tensor, moedl",
"name": "create_model",
"signature": "def create_mod... | 2 | stack_v2_sparse_classes_30k_train_005227 | Implement the Python class `CharCNNGraph` described below.
Class description:
Implement the CharCNNGraph class.
Method signatures and docstrings:
- def __init__(self, hyper_parameters): 初始化 :param hyper_parameters: json,超参
- def create_model(self, hyper_parameters): 构建神经网络 :param hyper_parameters:json, hyper paramete... | Implement the Python class `CharCNNGraph` described below.
Class description:
Implement the CharCNNGraph class.
Method signatures and docstrings:
- def __init__(self, hyper_parameters): 初始化 :param hyper_parameters: json,超参
- def create_model(self, hyper_parameters): 构建神经网络 :param hyper_parameters:json, hyper paramete... | 640e3f44f90d9d8046546f7e1a93a29ebe5c8d30 | <|skeleton|>
class CharCNNGraph:
def __init__(self, hyper_parameters):
"""初始化 :param hyper_parameters: json,超参"""
<|body_0|>
def create_model(self, hyper_parameters):
"""构建神经网络 :param hyper_parameters:json, hyper parameters of network :return: tensor, moedl"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CharCNNGraph:
def __init__(self, hyper_parameters):
"""初始化 :param hyper_parameters: json,超参"""
self.char_cnn_layers = hyper_parameters['model'].get('char_cnn_layers', [[256, 7, 3], [256, 7, 3], [256, 3, -1], [256, 3, -1], [256, 3, -1], [256, 3, 3]])
self.full_connect_layers = hyper_par... | the_stack_v2_python_sparse | keras_textclassification/m03_CharCNN/graph_zhang.py | wzjames/Keras-TextClassification | train | 1 | |
1480a8b6ed72711a0ba32cf235a299a605d61d6d | [
"res = 0\nif x < 0:\n symbol = -1\n x = -x\nelse:\n symbol = 1\nwhile x:\n pop = x % 10\n x = x // 10\n res = res * 10 + pop\nreturn 0 if res > pow(2, 31) else res * symbol",
"temp = str(x)\nif temp[0] != '-':\n temp = temp[::-1]\nelse:\n temp2 = temp[1:]\n temp2 = temp2[::-1]\n temp... | <|body_start_0|>
res = 0
if x < 0:
symbol = -1
x = -x
else:
symbol = 1
while x:
pop = x % 10
x = x // 10
res = res * 10 + pop
return 0 if res > pow(2, 31) else res * symbol
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 0
if x < 0:
symbol = -1
x = -x
... | stack_v2_sparse_classes_36k_train_005795 | 856 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse2",
"signature": "def reverse2(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019762 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse2(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse2(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int ... | 1a3c1f4d6e9d3444039f087763b93241f4ba7892 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
res = 0
if x < 0:
symbol = -1
x = -x
else:
symbol = 1
while x:
pop = x % 10
x = x // 10
res = res * 10 + pop
return 0 if res > ... | the_stack_v2_python_sparse | Algorithm/007_Reverse_Integer.py | Gi1ia/TechNoteBook | train | 7 | |
f409297d507889b9b9e7c61c629a7a89d5635962 | [
"new_head = curr = ListNode(0)\nq = PriorityQueue(maxsize=len(lists))\nfor index, node in enumerate(lists):\n if node:\n q.put((node.val, index, node))\nwhile not q.empty():\n _, index, node = q.get()\n curr.next = node\n curr = curr.next\n if node.next:\n q.put((node.next.val, index, n... | <|body_start_0|>
new_head = curr = ListNode(0)
q = PriorityQueue(maxsize=len(lists))
for index, node in enumerate(lists):
if node:
q.put((node.val, index, node))
while not q.empty():
_, index, node = q.get()
curr.next = node
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge_k_list_with_queue(self, lists):
"""Put the current head into priority queue"""
<|body_0|>
def merge_k_linked_lists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode NOTE: this fails for big list. e.g n = 10,000"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_005796 | 3,763 | permissive | [
{
"docstring": "Put the current head into priority queue",
"name": "merge_k_list_with_queue",
"signature": "def merge_k_list_with_queue(self, lists)"
},
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode NOTE: this fails for big list. e.g n = 10,000",
"name": "merge_k_linked_lists"... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge_k_list_with_queue(self, lists): Put the current head into priority queue
- def merge_k_linked_lists(self, lists): :type lists: List[ListNode] :rtype: ListNode NOTE: thi... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge_k_list_with_queue(self, lists): Put the current head into priority queue
- def merge_k_linked_lists(self, lists): :type lists: List[ListNode] :rtype: ListNode NOTE: thi... | 547c200b627c774535bc22880b16d5390183aeba | <|skeleton|>
class Solution:
def merge_k_list_with_queue(self, lists):
"""Put the current head into priority queue"""
<|body_0|>
def merge_k_linked_lists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode NOTE: this fails for big list. e.g n = 10,000"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def merge_k_list_with_queue(self, lists):
"""Put the current head into priority queue"""
new_head = curr = ListNode(0)
q = PriorityQueue(maxsize=len(lists))
for index, node in enumerate(lists):
if node:
q.put((node.val, index, node))
... | the_stack_v2_python_sparse | hard/23_merge_k_sorted_list.py | Sukhrobjon/leetcode | train | 0 | |
fcd3284416a2295e21e7cc8130db674ea3dd7b09 | [
"self.problem = problem\nself.initializer = initializer\nself.evaporator = evaporator\nself.intensifier = intensifier\nself.solution_generator = solution_gen\nself.terminator = terminator\nself.num_solutions = num_solutions\nself.quality_dependence = quality_dependence\nself.verbose = verbose\nself.pheromone_matrix... | <|body_start_0|>
self.problem = problem
self.initializer = initializer
self.evaporator = evaporator
self.intensifier = intensifier
self.solution_generator = solution_gen
self.terminator = terminator
self.num_solutions = num_solutions
self.quality_dependenc... | Main class of the ant colony optimizer | AntColonyOptimizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AntColonyOptimizer:
"""Main class of the ant colony optimizer"""
def __init__(self, problem: VehicleRoutingProblem, initializer: AbstractInitializer, evaporator: Evaporator, intensifier: Intensifier, solution_gen: AbstractSolutionGenerator, terminator: Terminator, num_solutions: int=1, quali... | stack_v2_sparse_classes_36k_train_005797 | 4,165 | no_license | [
{
"docstring": ":param problem: the vehicle routing problem to solve :param initializer: Initializer object for initializing the pheromon matrix :param evaporator: Evaporation strategy for the pheromone matrix :param intensifier: Intensifier strategy for the peromone matrix :param solution_gen: Solution Generat... | 2 | stack_v2_sparse_classes_30k_train_014430 | Implement the Python class `AntColonyOptimizer` described below.
Class description:
Main class of the ant colony optimizer
Method signatures and docstrings:
- def __init__(self, problem: VehicleRoutingProblem, initializer: AbstractInitializer, evaporator: Evaporator, intensifier: Intensifier, solution_gen: AbstractSo... | Implement the Python class `AntColonyOptimizer` described below.
Class description:
Main class of the ant colony optimizer
Method signatures and docstrings:
- def __init__(self, problem: VehicleRoutingProblem, initializer: AbstractInitializer, evaporator: Evaporator, intensifier: Intensifier, solution_gen: AbstractSo... | 0524c053b6d49395017fda4d8654d4e261e19b38 | <|skeleton|>
class AntColonyOptimizer:
"""Main class of the ant colony optimizer"""
def __init__(self, problem: VehicleRoutingProblem, initializer: AbstractInitializer, evaporator: Evaporator, intensifier: Intensifier, solution_gen: AbstractSolutionGenerator, terminator: Terminator, num_solutions: int=1, quali... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AntColonyOptimizer:
"""Main class of the ant colony optimizer"""
def __init__(self, problem: VehicleRoutingProblem, initializer: AbstractInitializer, evaporator: Evaporator, intensifier: Intensifier, solution_gen: AbstractSolutionGenerator, terminator: Terminator, num_solutions: int=1, quality_dependence... | the_stack_v2_python_sparse | Final_Task_ACO_full/ACO.py | hwuebben/NatureInspiredAlgorithms | train | 0 |
8e4d26ae43fcf03ee4b84e35a944842645709c66 | [
"Block.__init__(self, scenario, args)\nif self.language is None:\n raise LoadingException('Language must be defined!')",
"if tnode.voice != 'passive' and tnode.gram_diathesis != 'pas':\n if tnode.lex_anode and tnode.lex_anode.morphcat_pos == 'V':\n tnode.set_deref_attr('wild/conjugated', tnode.lex_an... | <|body_start_0|>
Block.__init__(self, scenario, args)
if self.language is None:
raise LoadingException('Language must be defined!')
<|end_body_0|>
<|body_start_1|>
if tnode.voice != 'passive' and tnode.gram_diathesis != 'pas':
if tnode.lex_anode and tnode.lex_anode.morph... | Add compound passive auxiliary 'být'. Arguments: language: the language of the target tree selector: the selector of the target tree | AddAuxVerbCompoundPassive | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddAuxVerbCompoundPassive:
"""Add compound passive auxiliary 'být'. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
<|body_0|>
def p... | stack_v2_sparse_classes_36k_train_005798 | 1,843 | permissive | [
{
"docstring": "Constructor, just checking the argument values",
"name": "__init__",
"signature": "def __init__(self, scenario, args)"
},
{
"docstring": "Add compound passive auxiliary to a node, where appropriate.",
"name": "process_tnode",
"signature": "def process_tnode(self, tnode)"
... | 2 | stack_v2_sparse_classes_30k_train_015935 | Implement the Python class `AddAuxVerbCompoundPassive` described below.
Class description:
Add compound passive auxiliary 'být'. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario, args): Constructor, just chec... | Implement the Python class `AddAuxVerbCompoundPassive` described below.
Class description:
Add compound passive auxiliary 'být'. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario, args): Constructor, just chec... | 73af644ec35c8a1cd0c37cd478c2afc1db717e0b | <|skeleton|>
class AddAuxVerbCompoundPassive:
"""Add compound passive auxiliary 'být'. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
<|body_0|>
def p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddAuxVerbCompoundPassive:
"""Add compound passive auxiliary 'být'. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
Block.__init__(self, scenario, arg... | the_stack_v2_python_sparse | alex/components/nlg/tectotpl/block/t2a/cs/addauxverbcompoundpassive.py | oplatek/alex | train | 0 |
639a3fa148c31ef2c6d05d59a76c6c4f2d9c2a95 | [
"self.hostname = host\nself.translation = Translator(config, self.hostname)\nself.ifindexes = ifindexes\nself.lookup = lookup\nself.config = config",
"port_data = self.translation.ethernet_data()\ndata = Port(port_data, self.hostname, self.config, self.lookup, ifindexes=self.ifindexes).data()\ntable = PortTable(d... | <|body_start_0|>
self.hostname = host
self.translation = Translator(config, self.hostname)
self.ifindexes = ifindexes
self.lookup = lookup
self.config = config
<|end_body_0|>
<|body_start_1|>
port_data = self.translation.ethernet_data()
data = Port(port_data, sel... | Class that creates the device's various HTML tables. | Device | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Device:
"""Class that creates the device's various HTML tables."""
def __init__(self, host, config, lookup, ifindexes=None):
"""Initialize the class. Args: config: Configuration object lookup: Lookup object host: Hostname to process ifindexes: List of ifindexes to retrieve. If None, ... | stack_v2_sparse_classes_36k_train_005799 | 18,522 | permissive | [
{
"docstring": "Initialize the class. Args: config: Configuration object lookup: Lookup object host: Hostname to process ifindexes: List of ifindexes to retrieve. If None, then do all. Returns: None",
"name": "__init__",
"signature": "def __init__(self, host, config, lookup, ifindexes=None)"
},
{
... | 3 | null | Implement the Python class `Device` described below.
Class description:
Class that creates the device's various HTML tables.
Method signatures and docstrings:
- def __init__(self, host, config, lookup, ifindexes=None): Initialize the class. Args: config: Configuration object lookup: Lookup object host: Hostname to pr... | Implement the Python class `Device` described below.
Class description:
Class that creates the device's various HTML tables.
Method signatures and docstrings:
- def __init__(self, host, config, lookup, ifindexes=None): Initialize the class. Args: config: Configuration object lookup: Lookup object host: Hostname to pr... | ae82589fbbab77fef6d6be09c1fcca5846f595a8 | <|skeleton|>
class Device:
"""Class that creates the device's various HTML tables."""
def __init__(self, host, config, lookup, ifindexes=None):
"""Initialize the class. Args: config: Configuration object lookup: Lookup object host: Hostname to process ifindexes: List of ifindexes to retrieve. If None, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Device:
"""Class that creates the device's various HTML tables."""
def __init__(self, host, config, lookup, ifindexes=None):
"""Initialize the class. Args: config: Configuration object lookup: Lookup object host: Hostname to process ifindexes: List of ifindexes to retrieve. If None, then do all. ... | the_stack_v2_python_sparse | switchmap/www/pages/device.py | PalisadoesFoundation/switchmap-ng | train | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.