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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
af26c8fba8e103e34cf6f7981939a7d100dc9107 | [
"pos_hash = {0: 0}\nout = None\ntemp_sum = 0\nfor i in range(len(nums)):\n temp_sum += nums[i]\n remain_sum = temp_sum - k\n if remain_sum in pos_hash:\n length = i + 1 - pos_hash[remain_sum]\n if out is None or length > out:\n out = length\n if temp_sum not in pos_hash:\n ... | <|body_start_0|>
pos_hash = {0: 0}
out = None
temp_sum = 0
for i in range(len(nums)):
temp_sum += nums[i]
remain_sum = temp_sum - k
if remain_sum in pos_hash:
length = i + 1 - pos_hash[remain_sum]
if out is None or lengt... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArrayLen(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def maxSubArrayLen2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pos_ha... | stack_v2_sparse_classes_36k_train_009100 | 1,838 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "maxSubArrayLen",
"signature": "def maxSubArrayLen(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "maxSubArrayLen2",
"signature": "def maxSubArrayLen2(self, nums, k)"
}... | 2 | stack_v2_sparse_classes_30k_train_005040 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArrayLen(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def maxSubArrayLen2(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 maxSubArrayLen(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def maxSubArrayLen2(self, nums, k): :type nums: List[int] :type k: int :rtype: int
<|skeleton... | 604efd2c53c369fb262f42f7f7f31997ea4d029b | <|skeleton|>
class Solution:
def maxSubArrayLen(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def maxSubArrayLen2(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 maxSubArrayLen(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
pos_hash = {0: 0}
out = None
temp_sum = 0
for i in range(len(nums)):
temp_sum += nums[i]
remain_sum = temp_sum - k
if remain_sum in pos_... | the_stack_v2_python_sparse | 325_Maximum_Size_Subarray_Sum_Equals_k.py | fxy1018/Leetcode | train | 1 | |
12dfd81185ad5202bb50bd8cc303b1e1ce06536b | [
"if len(self.max_heap) + len(self.min_heap) & 1 == 0:\n if len(self.min_heap) and self.min_heap[0] < num:\n num = heapq.heappushpop(self.min_heap, num)\n heapq.heappush(self.max_heap, -num)\nelse:\n if len(self.max_heap) and num < -self.max_heap[0]:\n num = -heapq.heappushpop(self.max_heap, -... | <|body_start_0|>
if len(self.max_heap) + len(self.min_heap) & 1 == 0:
if len(self.min_heap) and self.min_heap[0] < num:
num = heapq.heappushpop(self.min_heap, num)
heapq.heappush(self.max_heap, -num)
else:
if len(self.max_heap) and num < -self.max_heap... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def insert(self, num):
"""获取数据流"""
<|body_0|>
def getMedian(self):
"""获取数据流中的中位数"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(self.max_heap) + len(self.min_heap) & 1 == 0:
if len(self.min_heap) and self.min_heap[0] < ... | stack_v2_sparse_classes_36k_train_009101 | 1,466 | no_license | [
{
"docstring": "获取数据流",
"name": "insert",
"signature": "def insert(self, num)"
},
{
"docstring": "获取数据流中的中位数",
"name": "getMedian",
"signature": "def getMedian(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011084 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insert(self, num): 获取数据流
- def getMedian(self): 获取数据流中的中位数 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insert(self, num): 获取数据流
- def getMedian(self): 获取数据流中的中位数
<|skeleton|>
class Solution:
def insert(self, num):
"""获取数据流"""
<|body_0|>
def getMedian... | ef6aee94c7990d734271c204034ec273b665226d | <|skeleton|>
class Solution:
def insert(self, num):
"""获取数据流"""
<|body_0|>
def getMedian(self):
"""获取数据流中的中位数"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def insert(self, num):
"""获取数据流"""
if len(self.max_heap) + len(self.min_heap) & 1 == 0:
if len(self.min_heap) and self.min_heap[0] < num:
num = heapq.heappushpop(self.min_heap, num)
heapq.heappush(self.max_heap, -num)
else:
... | the_stack_v2_python_sparse | 剑指offer/数据流中的中位数.py | godzzbboss/leetcode | train | 0 | |
da06cdba5a6c489723c3b46f073703c84540b3ac | [
"self.manager = PackageManager()\nself.packages = self.manager.list_packages(unpacked_only=True)\nif not self.packages:\n show_error('There are no packages available to be packaged')\n return\nself.window.show_quick_panel(self.packages, self.on_done)",
"destination = self.manager.settings.get('package_desti... | <|body_start_0|>
self.manager = PackageManager()
self.packages = self.manager.list_packages(unpacked_only=True)
if not self.packages:
show_error('There are no packages available to be packaged')
return
self.window.show_quick_panel(self.packages, self.on_done)
<|en... | Abstract class for commands that create .sublime-package files | PackageCreator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackageCreator:
"""Abstract class for commands that create .sublime-package files"""
def show_panel(self):
"""Shows a list of packages that can be turned into a .sublime-package file"""
<|body_0|>
def get_package_destination(self):
"""Retrieves the destination fo... | stack_v2_sparse_classes_36k_train_009102 | 1,205 | permissive | [
{
"docstring": "Shows a list of packages that can be turned into a .sublime-package file",
"name": "show_panel",
"signature": "def show_panel(self)"
},
{
"docstring": "Retrieves the destination for .sublime-package files :return: A string - the path to the folder to save .sublime-package files i... | 2 | stack_v2_sparse_classes_30k_val_000901 | Implement the Python class `PackageCreator` described below.
Class description:
Abstract class for commands that create .sublime-package files
Method signatures and docstrings:
- def show_panel(self): Shows a list of packages that can be turned into a .sublime-package file
- def get_package_destination(self): Retriev... | Implement the Python class `PackageCreator` described below.
Class description:
Abstract class for commands that create .sublime-package files
Method signatures and docstrings:
- def show_panel(self): Shows a list of packages that can be turned into a .sublime-package file
- def get_package_destination(self): Retriev... | 8c9833710577de6db6e8b1db5d9196e19e19d117 | <|skeleton|>
class PackageCreator:
"""Abstract class for commands that create .sublime-package files"""
def show_panel(self):
"""Shows a list of packages that can be turned into a .sublime-package file"""
<|body_0|>
def get_package_destination(self):
"""Retrieves the destination fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PackageCreator:
"""Abstract class for commands that create .sublime-package files"""
def show_panel(self):
"""Shows a list of packages that can be turned into a .sublime-package file"""
self.manager = PackageManager()
self.packages = self.manager.list_packages(unpacked_only=True)
... | the_stack_v2_python_sparse | EthanBrown.SublimeText2.UtilPackages/tools/PackageCache/Package Control/package_control/package_creator.py | Iristyle/ChocolateyPackages | train | 19 |
e1d7f86681d865affe9103102ce5d6ef5b63891a | [
"results = []\nfor entry in self.api_audit_entries:\n if username is not None and entry.username != username:\n continue\n if router_method_names and entry.router_method_name not in router_method_names:\n continue\n if min_timestamp is not None and entry.timestamp < min_timestamp:\n co... | <|body_start_0|>
results = []
for entry in self.api_audit_entries:
if username is not None and entry.username != username:
continue
if router_method_names and entry.router_method_name not in router_method_names:
continue
if min_timestam... | InMemoryDB mixin for event handling. | InMemoryDBEventMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InMemoryDBEventMixin:
"""InMemoryDB mixin for event handling."""
def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None):
"""Returns audit entries stored in the database."""
<|body_0|>
def CountAPIAuditEntriesByUserA... | stack_v2_sparse_classes_36k_train_009103 | 2,178 | permissive | [
{
"docstring": "Returns audit entries stored in the database.",
"name": "ReadAPIAuditEntries",
"signature": "def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None)"
},
{
"docstring": "Returns audit entry counts grouped by user and calendar ... | 3 | null | Implement the Python class `InMemoryDBEventMixin` described below.
Class description:
InMemoryDB mixin for event handling.
Method signatures and docstrings:
- def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None): Returns audit entries stored in the database.
-... | Implement the Python class `InMemoryDBEventMixin` described below.
Class description:
InMemoryDB mixin for event handling.
Method signatures and docstrings:
- def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None): Returns audit entries stored in the database.
-... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class InMemoryDBEventMixin:
"""InMemoryDB mixin for event handling."""
def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None):
"""Returns audit entries stored in the database."""
<|body_0|>
def CountAPIAuditEntriesByUserA... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InMemoryDBEventMixin:
"""InMemoryDB mixin for event handling."""
def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None):
"""Returns audit entries stored in the database."""
results = []
for entry in self.api_audit_entries:
... | the_stack_v2_python_sparse | grr/server/grr_response_server/databases/mem_events.py | google/grr | train | 4,683 |
9bd0318b8c7cb6488d0a0f286c27b140af0da0a0 | [
"FeaturewiseDatasetMeasure.__init__(self)\nself.__datameasure = datameasure\nself.__noise = noise",
"if not N.issubdtype(dataset.samples.dtype, N.float):\n dataset.setSamplesDType('float32')\nif __debug__:\n nfeatures = dataset.nfeatures\nsens_map = []\norig_measure = self.__datameasure(dataset)\nfor featur... | <|body_start_0|>
FeaturewiseDatasetMeasure.__init__(self)
self.__datameasure = datameasure
self.__noise = noise
<|end_body_0|>
<|body_start_1|>
if not N.issubdtype(dataset.samples.dtype, N.float):
dataset.setSamplesDType('float32')
if __debug__:
nfeatures... | This is a `FeaturewiseDatasetMeasure` that uses a scalar `DatasetMeasure` and selective noise perturbation to compute a sensitivity map. First the scalar `DatasetMeasure` computed using the original dataset. Next the data measure is computed multiple times each with a single feature in the dataset perturbed by noise. T... | NoisePerturbationSensitivity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoisePerturbationSensitivity:
"""This is a `FeaturewiseDatasetMeasure` that uses a scalar `DatasetMeasure` and selective noise perturbation to compute a sensitivity map. First the scalar `DatasetMeasure` computed using the original dataset. Next the data measure is computed multiple times each wi... | stack_v2_sparse_classes_36k_train_009104 | 3,784 | permissive | [
{
"docstring": "Cheap initialization. Parameters datameasure: `Datameasure` that is used to quantify the effect of noise perturbation. noise: Functor to generate noise. The noise generator has to return an 1d array of n values when called the `size=n` keyword argument. This is the default interface of the rando... | 2 | stack_v2_sparse_classes_30k_train_002763 | Implement the Python class `NoisePerturbationSensitivity` described below.
Class description:
This is a `FeaturewiseDatasetMeasure` that uses a scalar `DatasetMeasure` and selective noise perturbation to compute a sensitivity map. First the scalar `DatasetMeasure` computed using the original dataset. Next the data mea... | Implement the Python class `NoisePerturbationSensitivity` described below.
Class description:
This is a `FeaturewiseDatasetMeasure` that uses a scalar `DatasetMeasure` and selective noise perturbation to compute a sensitivity map. First the scalar `DatasetMeasure` computed using the original dataset. Next the data mea... | 2a8fcaa57457c8994455144e9e69494d167204c4 | <|skeleton|>
class NoisePerturbationSensitivity:
"""This is a `FeaturewiseDatasetMeasure` that uses a scalar `DatasetMeasure` and selective noise perturbation to compute a sensitivity map. First the scalar `DatasetMeasure` computed using the original dataset. Next the data measure is computed multiple times each wi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoisePerturbationSensitivity:
"""This is a `FeaturewiseDatasetMeasure` that uses a scalar `DatasetMeasure` and selective noise perturbation to compute a sensitivity map. First the scalar `DatasetMeasure` computed using the original dataset. Next the data measure is computed multiple times each with a single f... | the_stack_v2_python_sparse | mvpa/measures/noiseperturbation.py | gorlins/PyMVPA | train | 0 |
68fbd986055ee502f867c05d45835f5956ef2b8f | [
"self.list = []\nfor i in range(len(string)):\n if string[i] == '0':\n self.list.append('o')\n if string[i] == '1':\n self.list.append('l')\n if string[i] == '3' or string[i] == '5':\n self.list.append('e')\n if string[i] == '8':\n self.list.append('b')\n else:\n se... | <|body_start_0|>
self.list = []
for i in range(len(string)):
if string[i] == '0':
self.list.append('o')
if string[i] == '1':
self.list.append('l')
if string[i] == '3' or string[i] == '5':
self.list.append('e')
... | conversion | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class conversion:
def numbersToLetters(self, string):
"""Converts numbers to letters; returns string"""
<|body_0|>
def lettersToNumbers(self, string):
"""Converts letters to numbers; returns string"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.list... | stack_v2_sparse_classes_36k_train_009105 | 3,194 | permissive | [
{
"docstring": "Converts numbers to letters; returns string",
"name": "numbersToLetters",
"signature": "def numbersToLetters(self, string)"
},
{
"docstring": "Converts letters to numbers; returns string",
"name": "lettersToNumbers",
"signature": "def lettersToNumbers(self, string)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000759 | Implement the Python class `conversion` described below.
Class description:
Implement the conversion class.
Method signatures and docstrings:
- def numbersToLetters(self, string): Converts numbers to letters; returns string
- def lettersToNumbers(self, string): Converts letters to numbers; returns string | Implement the Python class `conversion` described below.
Class description:
Implement the conversion class.
Method signatures and docstrings:
- def numbersToLetters(self, string): Converts numbers to letters; returns string
- def lettersToNumbers(self, string): Converts letters to numbers; returns string
<|skeleton|... | af04f91e14492d0ddfe7b5ad00e0652e609ca1b5 | <|skeleton|>
class conversion:
def numbersToLetters(self, string):
"""Converts numbers to letters; returns string"""
<|body_0|>
def lettersToNumbers(self, string):
"""Converts letters to numbers; returns string"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class conversion:
def numbersToLetters(self, string):
"""Converts numbers to letters; returns string"""
self.list = []
for i in range(len(string)):
if string[i] == '0':
self.list.append('o')
if string[i] == '1':
self.list.append('l')
... | the_stack_v2_python_sparse | Code/Pygame Based/20140326/carPlateRegistrationSystem.py | creatingcrap/PythonPlate | train | 0 | |
5fa30f70e990648178b4b7d54319d16b3ca33f6e | [
"self.paths = paths\nself.recursive = recursive\nif self.paths is None:\n self.paths = []\nsuper(FilesystemCollector, self).__init__()",
"for path in self.paths:\n for base, directories, filenames in os.walk(path):\n for filename in filenames:\n _, extension = os.path.splitext(filename)\n ... | <|body_start_0|>
self.paths = paths
self.recursive = recursive
if self.paths is None:
self.paths = []
super(FilesystemCollector, self).__init__()
<|end_body_0|>
<|body_start_1|>
for path in self.paths:
for base, directories, filenames in os.walk(path):
... | FilesystemCollector | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilesystemCollector:
def __init__(self, paths=None, recursive=True):
"""Initialise with *paths* to search. If *recursive* is True then all subdirectories of *paths* will also be searched."""
<|body_0|>
def collect(self):
"""Yield collected schemas."""
<|body_... | stack_v2_sparse_classes_36k_train_009106 | 1,630 | permissive | [
{
"docstring": "Initialise with *paths* to search. If *recursive* is True then all subdirectories of *paths* will also be searched.",
"name": "__init__",
"signature": "def __init__(self, paths=None, recursive=True)"
},
{
"docstring": "Yield collected schemas.",
"name": "collect",
"signat... | 2 | stack_v2_sparse_classes_30k_train_014085 | Implement the Python class `FilesystemCollector` described below.
Class description:
Implement the FilesystemCollector class.
Method signatures and docstrings:
- def __init__(self, paths=None, recursive=True): Initialise with *paths* to search. If *recursive* is True then all subdirectories of *paths* will also be se... | Implement the Python class `FilesystemCollector` described below.
Class description:
Implement the FilesystemCollector class.
Method signatures and docstrings:
- def __init__(self, paths=None, recursive=True): Initialise with *paths* to search. If *recursive* is True then all subdirectories of *paths* will also be se... | 41039cea452860649f717358fd57a99e73202579 | <|skeleton|>
class FilesystemCollector:
def __init__(self, paths=None, recursive=True):
"""Initialise with *paths* to search. If *recursive* is True then all subdirectories of *paths* will also be searched."""
<|body_0|>
def collect(self):
"""Yield collected schemas."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilesystemCollector:
def __init__(self, paths=None, recursive=True):
"""Initialise with *paths* to search. If *recursive* is True then all subdirectories of *paths* will also be searched."""
self.paths = paths
self.recursive = recursive
if self.paths is None:
self.p... | the_stack_v2_python_sparse | source/harmony/schema/collector.py | 4degrees/harmony | train | 4 | |
7242c4aac59f4c7f68b3748249404dc1a7d2c1a1 | [
"self._suffix = suffix\nself._cache = {}\nobject.__init__(self)",
"class_name = value.__class__.__name__\nmethod = self._cache.get(class_name)\nif not method:\n type_name = class_name\n if self._suffix and type_name.endswith(self._suffix):\n type_name = type_name[:-len(self._suffix)]\n type_name =... | <|body_start_0|>
self._suffix = suffix
self._cache = {}
object.__init__(self)
<|end_body_0|>
<|body_start_1|>
class_name = value.__class__.__name__
method = self._cache.get(class_name)
if not method:
type_name = class_name
if self._suffix and type... | Convenience class for visitors used in vAPI Python runtime | VapiVisitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VapiVisitor:
"""Convenience class for visitors used in vAPI Python runtime"""
def __init__(self, suffix=None):
"""Initialize VapiVisitor :type suffix: :class:`str` :param suffix: The suffix string that should be removed from class name during the dispatch"""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_009107 | 1,397 | no_license | [
{
"docstring": "Initialize VapiVisitor :type suffix: :class:`str` :param suffix: The suffix string that should be removed from class name during the dispatch",
"name": "__init__",
"signature": "def __init__(self, suffix=None)"
},
{
"docstring": "Dispatch the call to the appropriate method based ... | 2 | stack_v2_sparse_classes_30k_train_019523 | Implement the Python class `VapiVisitor` described below.
Class description:
Convenience class for visitors used in vAPI Python runtime
Method signatures and docstrings:
- def __init__(self, suffix=None): Initialize VapiVisitor :type suffix: :class:`str` :param suffix: The suffix string that should be removed from cl... | Implement the Python class `VapiVisitor` described below.
Class description:
Convenience class for visitors used in vAPI Python runtime
Method signatures and docstrings:
- def __init__(self, suffix=None): Initialize VapiVisitor :type suffix: :class:`str` :param suffix: The suffix string that should be removed from cl... | 5d395700ab3d0d1d45b497e48beab8c366fca9f5 | <|skeleton|>
class VapiVisitor:
"""Convenience class for visitors used in vAPI Python runtime"""
def __init__(self, suffix=None):
"""Initialize VapiVisitor :type suffix: :class:`str` :param suffix: The suffix string that should be removed from class name during the dispatch"""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VapiVisitor:
"""Convenience class for visitors used in vAPI Python runtime"""
def __init__(self, suffix=None):
"""Initialize VapiVisitor :type suffix: :class:`str` :param suffix: The suffix string that should be removed from class name during the dispatch"""
self._suffix = suffix
... | the_stack_v2_python_sparse | alexa-program.bak/vmware/vapi/lib/visitor.py | taromurata/TDP2018_VMCAPI | train | 1 |
aed7681c01b5333194881195baf8fe4986db2ab9 | [
"self.seed = seed\nself.lst = []\nself.line_lst = []\nself.index = 0\nwith open('war-and-peace.txt', 'r') as file:\n for line in file.readlines():\n self.line_lst.append(line)\n file.seek(0)\n for lines in file:\n for word in lines.split():\n if word.isalpha() == True:\n ... | <|body_start_0|>
self.seed = seed
self.lst = []
self.line_lst = []
self.index = 0
with open('war-and-peace.txt', 'r') as file:
for line in file.readlines():
self.line_lst.append(line)
file.seek(0)
for lines in file:
... | Psuedo Random Generator | WarAndPeacePseudoRandomNumberGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WarAndPeacePseudoRandomNumberGenerator:
"""Psuedo Random Generator"""
def __init__(self, seed):
"""Initiate Seed Number"""
<|body_0|>
def random(self):
"""Random Number from 0-1"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.seed = seed
... | stack_v2_sparse_classes_36k_train_009108 | 2,527 | no_license | [
{
"docstring": "Initiate Seed Number",
"name": "__init__",
"signature": "def __init__(self, seed)"
},
{
"docstring": "Random Number from 0-1",
"name": "random",
"signature": "def random(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015991 | Implement the Python class `WarAndPeacePseudoRandomNumberGenerator` described below.
Class description:
Psuedo Random Generator
Method signatures and docstrings:
- def __init__(self, seed): Initiate Seed Number
- def random(self): Random Number from 0-1 | Implement the Python class `WarAndPeacePseudoRandomNumberGenerator` described below.
Class description:
Psuedo Random Generator
Method signatures and docstrings:
- def __init__(self, seed): Initiate Seed Number
- def random(self): Random Number from 0-1
<|skeleton|>
class WarAndPeacePseudoRandomNumberGenerator:
... | 3f900864ac3e85bc60988bf08eca160a408d44d7 | <|skeleton|>
class WarAndPeacePseudoRandomNumberGenerator:
"""Psuedo Random Generator"""
def __init__(self, seed):
"""Initiate Seed Number"""
<|body_0|>
def random(self):
"""Random Number from 0-1"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WarAndPeacePseudoRandomNumberGenerator:
"""Psuedo Random Generator"""
def __init__(self, seed):
"""Initiate Seed Number"""
self.seed = seed
self.lst = []
self.line_lst = []
self.index = 0
with open('war-and-peace.txt', 'r') as file:
for line in ... | the_stack_v2_python_sparse | Hw7/Hw7_1.py | paripon123/DSC-430-Python | train | 2 |
ea32cb1d053c5690dd9270b1d86c815d056c4336 | [
"self.instance = instance\nfor name, field in self.hidden_fields.items():\n self.hidden_fields[name] = getattr(self.instance, name)",
"grouping = collections.defaultdict(list)\nfor name, field in self.fields.items():\n group = getattr(field, 'group', '0. ')\n grouping[group].append((field.verbose_name, g... | <|body_start_0|>
self.instance = instance
for name, field in self.hidden_fields.items():
self.hidden_fields[name] = getattr(self.instance, name)
<|end_body_0|>
<|body_start_1|>
grouping = collections.defaultdict(list)
for name, field in self.fields.items():
group... | A base class that constructs the readonly template for a given model. This uses the same notion that Django's forms APIs use to generate forms for given models. The idea is completely inspired from Django's ModelForm APIs and tries to mimic the same names that is used there in order to provide consistency. In addition,... | ModelReadOnlyTemplate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelReadOnlyTemplate:
"""A base class that constructs the readonly template for a given model. This uses the same notion that Django's forms APIs use to generate forms for given models. The idea is completely inspired from Django's ModelForm APIs and tries to mimic the same names that is used th... | stack_v2_sparse_classes_36k_train_009109 | 9,668 | permissive | [
{
"docstring": "Constructor to initialize the model instance. The readonly template will be rendered for the data in this model instance.",
"name": "__init__",
"signature": "def __init__(self, instance=None)"
},
{
"docstring": "Iterator yielding groups of model instance's properties to be render... | 3 | stack_v2_sparse_classes_30k_train_003093 | Implement the Python class `ModelReadOnlyTemplate` described below.
Class description:
A base class that constructs the readonly template for a given model. This uses the same notion that Django's forms APIs use to generate forms for given models. The idea is completely inspired from Django's ModelForm APIs and tries ... | Implement the Python class `ModelReadOnlyTemplate` described below.
Class description:
A base class that constructs the readonly template for a given model. This uses the same notion that Django's forms APIs use to generate forms for given models. The idea is completely inspired from Django's ModelForm APIs and tries ... | f581989f168189fa3a58c028eff327a16c03e438 | <|skeleton|>
class ModelReadOnlyTemplate:
"""A base class that constructs the readonly template for a given model. This uses the same notion that Django's forms APIs use to generate forms for given models. The idea is completely inspired from Django's ModelForm APIs and tries to mimic the same names that is used th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelReadOnlyTemplate:
"""A base class that constructs the readonly template for a given model. This uses the same notion that Django's forms APIs use to generate forms for given models. The idea is completely inspired from Django's ModelForm APIs and tries to mimic the same names that is used there in order ... | the_stack_v2_python_sparse | app/soc/views/readonly_template.py | sambitgaan/nupic.son | train | 0 |
011c2c4de5f89e0f33ce9287fc819cfd630ace89 | [
"self._supersampling_factor = supersampling_factor\nif supersampling_kernel_size is None:\n kernel_low_res, kernel_high_res = (np.zeros((3, 3)), kernel_supersampled)\n self._low_res_convolution = False\nelse:\n kernel_low_res, kernel_high_res = kernel_util.split_kernel(kernel_supersampled, supersampling_ke... | <|body_start_0|>
self._supersampling_factor = supersampling_factor
if supersampling_kernel_size is None:
kernel_low_res, kernel_high_res = (np.zeros((3, 3)), kernel_supersampled)
self._low_res_convolution = False
else:
kernel_low_res, kernel_high_res = kernel_... | class to compute the convolution on a supersampled grid with partial convolution computed on the regular grid | SubgridKernelConvolution | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubgridKernelConvolution:
"""class to compute the convolution on a supersampled grid with partial convolution computed on the regular grid"""
def __init__(self, kernel_supersampled, supersampling_factor, supersampling_kernel_size=None, convolution_type='fft_static'):
""":param kernel... | stack_v2_sparse_classes_36k_train_009110 | 15,375 | permissive | [
{
"docstring": ":param kernel_supersampled: kernel in supersampled pixels :param supersampling_factor: supersampling factor relative to the image pixel grid :param supersampling_kernel_size: number of pixels (in units of the image pixels) that are convolved with the supersampled kernel",
"name": "__init__",... | 3 | null | Implement the Python class `SubgridKernelConvolution` described below.
Class description:
class to compute the convolution on a supersampled grid with partial convolution computed on the regular grid
Method signatures and docstrings:
- def __init__(self, kernel_supersampled, supersampling_factor, supersampling_kernel... | Implement the Python class `SubgridKernelConvolution` described below.
Class description:
class to compute the convolution on a supersampled grid with partial convolution computed on the regular grid
Method signatures and docstrings:
- def __init__(self, kernel_supersampled, supersampling_factor, supersampling_kernel... | 73c9645f26f6983fe7961104075ebe8bf7a4b54c | <|skeleton|>
class SubgridKernelConvolution:
"""class to compute the convolution on a supersampled grid with partial convolution computed on the regular grid"""
def __init__(self, kernel_supersampled, supersampling_factor, supersampling_kernel_size=None, convolution_type='fft_static'):
""":param kernel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubgridKernelConvolution:
"""class to compute the convolution on a supersampled grid with partial convolution computed on the regular grid"""
def __init__(self, kernel_supersampled, supersampling_factor, supersampling_kernel_size=None, convolution_type='fft_static'):
""":param kernel_supersampled... | the_stack_v2_python_sparse | lenstronomy/ImSim/Numerics/convolution.py | lenstronomy/lenstronomy | train | 41 |
720d2a07ca675ad86e8903581955833b08d1330f | [
"edgeList.sort(key=lambda x: x[2])\nself.__uf = UnionFind(n)\nself.__adj = [[] for _ in xrange(n)]\nfor index, (i, j, weight) in enumerate(edgeList):\n if not self.__uf.union_set(i, j):\n continue\n self.__adj[i].append((j, weight))\n self.__adj[j].append((i, weight))\nself.__tree_infos = TreeInfos(... | <|body_start_0|>
edgeList.sort(key=lambda x: x[2])
self.__uf = UnionFind(n)
self.__adj = [[] for _ in xrange(n)]
for index, (i, j, weight) in enumerate(edgeList):
if not self.__uf.union_set(i, j):
continue
self.__adj[i].append((j, weight))
... | DistanceLimitedPathsExist | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DistanceLimitedPathsExist:
def __init__(self, n, edgeList):
""":type n: int :type edgeList: List[List[int]]"""
<|body_0|>
def query(self, p, q, limit):
""":type p: int :type q: int :type limit: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_009111 | 7,205 | permissive | [
{
"docstring": ":type n: int :type edgeList: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, n, edgeList)"
},
{
"docstring": ":type p: int :type q: int :type limit: int :rtype: bool",
"name": "query",
"signature": "def query(self, p, q, limit)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014546 | Implement the Python class `DistanceLimitedPathsExist` described below.
Class description:
Implement the DistanceLimitedPathsExist class.
Method signatures and docstrings:
- def __init__(self, n, edgeList): :type n: int :type edgeList: List[List[int]]
- def query(self, p, q, limit): :type p: int :type q: int :type li... | Implement the Python class `DistanceLimitedPathsExist` described below.
Class description:
Implement the DistanceLimitedPathsExist class.
Method signatures and docstrings:
- def __init__(self, n, edgeList): :type n: int :type edgeList: List[List[int]]
- def query(self, p, q, limit): :type p: int :type q: int :type li... | 4dc4e6642dc92f1983c13564cc0fd99917cab358 | <|skeleton|>
class DistanceLimitedPathsExist:
def __init__(self, n, edgeList):
""":type n: int :type edgeList: List[List[int]]"""
<|body_0|>
def query(self, p, q, limit):
""":type p: int :type q: int :type limit: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DistanceLimitedPathsExist:
def __init__(self, n, edgeList):
""":type n: int :type edgeList: List[List[int]]"""
edgeList.sort(key=lambda x: x[2])
self.__uf = UnionFind(n)
self.__adj = [[] for _ in xrange(n)]
for index, (i, j, weight) in enumerate(edgeList):
i... | the_stack_v2_python_sparse | Python/checking-existence-of-edge-length-limited-paths-ii.py | kamyu104/LeetCode-Solutions | train | 4,549 | |
cadf78bb94358eb48b068269c2f229c804b7b9c6 | [
"self.locations = defaultdict(list)\nfor i, w in enumerate(words):\n self.locations[w].append(i)",
"loc1, loc2 = (self.locations[word1], self.locations[word2])\nl1, l2 = (0, 0)\nmin_diff = float('inf')\nwhile l1 < len(loc1) and l2 < len(loc2):\n min_diff = min(min_diff, abs(loc1[l1] - loc2[l2]))\n if loc... | <|body_start_0|>
self.locations = defaultdict(list)
for i, w in enumerate(words):
self.locations[w].append(i)
<|end_body_0|>
<|body_start_1|>
loc1, loc2 = (self.locations[word1], self.locations[word2])
l1, l2 = (0, 0)
min_diff = float('inf')
while l1 < len(lo... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.locations = defaultdict(list)
... | stack_v2_sparse_classes_36k_train_009112 | 1,596 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 79d4e3946309f6e37e18c1958243d63faf99861c | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.locations = defaultdict(list)
for i, w in enumerate(words):
self.locations[w].append(i)
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
loc1... | the_stack_v2_python_sparse | 201-300/244_最短单词距离II.py | ZhiyuSun/leetcode-practice | train | 6 | |
71ec09d7a1f2263c962a5263fe50894ffc22b068 | [
"if cookie == None:\n return\ncookies = {}\nfor x in cookie.split(';'):\n name, value = x.strip().split('=', 1)\n cookies[name] = value\nreturn cookies",
"if file == None:\n return\npayload = []\ntry:\n with open(file, 'rb') as f:\n encoding = chardet.detect(f.read())['encoding']\n F = op... | <|body_start_0|>
if cookie == None:
return
cookies = {}
for x in cookie.split(';'):
name, value = x.strip().split('=', 1)
cookies[name] = value
return cookies
<|end_body_0|>
<|body_start_1|>
if file == None:
return
payload ... | Check | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Check:
def checkCookies(self, cookie):
"""检查cookie并组合cookie :param cookie: :return:"""
<|body_0|>
def fileRead(self, file):
"""导入payload文件 :param file: :return:"""
<|body_1|>
def threadSetting(self, threadN, flag):
"""设置线程数 :param threadN: 线程数 :p... | stack_v2_sparse_classes_36k_train_009113 | 2,010 | no_license | [
{
"docstring": "检查cookie并组合cookie :param cookie: :return:",
"name": "checkCookies",
"signature": "def checkCookies(self, cookie)"
},
{
"docstring": "导入payload文件 :param file: :return:",
"name": "fileRead",
"signature": "def fileRead(self, file)"
},
{
"docstring": "设置线程数 :param thr... | 5 | stack_v2_sparse_classes_30k_train_012896 | Implement the Python class `Check` described below.
Class description:
Implement the Check class.
Method signatures and docstrings:
- def checkCookies(self, cookie): 检查cookie并组合cookie :param cookie: :return:
- def fileRead(self, file): 导入payload文件 :param file: :return:
- def threadSetting(self, threadN, flag): 设置线程数 ... | Implement the Python class `Check` described below.
Class description:
Implement the Check class.
Method signatures and docstrings:
- def checkCookies(self, cookie): 检查cookie并组合cookie :param cookie: :return:
- def fileRead(self, file): 导入payload文件 :param file: :return:
- def threadSetting(self, threadN, flag): 设置线程数 ... | 8103baaed6d90606befd7435b8ce8d4841d56bd3 | <|skeleton|>
class Check:
def checkCookies(self, cookie):
"""检查cookie并组合cookie :param cookie: :return:"""
<|body_0|>
def fileRead(self, file):
"""导入payload文件 :param file: :return:"""
<|body_1|>
def threadSetting(self, threadN, flag):
"""设置线程数 :param threadN: 线程数 :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Check:
def checkCookies(self, cookie):
"""检查cookie并组合cookie :param cookie: :return:"""
if cookie == None:
return
cookies = {}
for x in cookie.split(';'):
name, value = x.strip().split('=', 1)
cookies[name] = value
return cookies
... | the_stack_v2_python_sparse | modules/func/check.py | T-Jinhao/Scanner | train | 14 | |
efe9295488035c5fd21f274cc9bf5e793431fcc7 | [
"size = len(s)\nif size == 0:\n return ''\nlongest_palindrome = 1\nlongest_palindrome_str = s[0]\nfor i in range(size):\n palindrome_odd, odd_len = self.__center_spread(s, size, i, i)\n palindrome_even, even_len = self.__center_spread(s, size, i, i + 1)\n cur_max_sub = palindrome_odd if odd_len >= even_... | <|body_start_0|>
size = len(s)
if size == 0:
return ''
longest_palindrome = 1
longest_palindrome_str = s[0]
for i in range(size):
palindrome_odd, odd_len = self.__center_spread(s, size, i, i)
palindrome_even, even_len = self.__center_spread(s, ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""中心扩散的思路 时间复杂度:O(N^2) 空间复杂度:O(1)"""
<|body_0|>
def __center_spread(self, s, size, left, right):
"""left = right的时候,此时回文中心是一条线,回文串的长度是奇数 right = left + 1的时候,此时回文中心是任意一个字符,回文串的长度是偶数"""
<|body_1|>
def ... | stack_v2_sparse_classes_36k_train_009114 | 2,093 | no_license | [
{
"docstring": "中心扩散的思路 时间复杂度:O(N^2) 空间复杂度:O(1)",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s: str) -> str"
},
{
"docstring": "left = right的时候,此时回文中心是一条线,回文串的长度是奇数 right = left + 1的时候,此时回文中心是任意一个字符,回文串的长度是偶数",
"name": "__center_spread",
"signature": "def __ce... | 3 | stack_v2_sparse_classes_30k_train_010347 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: 中心扩散的思路 时间复杂度:O(N^2) 空间复杂度:O(1)
- def __center_spread(self, s, size, left, right): left = right的时候,此时回文中心是一条线,回文串的长度是奇数 right = left +... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: 中心扩散的思路 时间复杂度:O(N^2) 空间复杂度:O(1)
- def __center_spread(self, s, size, left, right): left = right的时候,此时回文中心是一条线,回文串的长度是奇数 right = left +... | 3f4284330f9771037ca59e2e6a94122e51e58540 | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""中心扩散的思路 时间复杂度:O(N^2) 空间复杂度:O(1)"""
<|body_0|>
def __center_spread(self, s, size, left, right):
"""left = right的时候,此时回文中心是一条线,回文串的长度是奇数 right = left + 1的时候,此时回文中心是任意一个字符,回文串的长度是偶数"""
<|body_1|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s: str) -> str:
"""中心扩散的思路 时间复杂度:O(N^2) 空间复杂度:O(1)"""
size = len(s)
if size == 0:
return ''
longest_palindrome = 1
longest_palindrome_str = s[0]
for i in range(size):
palindrome_odd, odd_len = self.__... | the_stack_v2_python_sparse | Leetcode/5.最长回文子串.py | myf-algorithm/Leetcode | train | 1 | |
68d0fef31cabf173e2c550d0d890103ae32e8051 | [
"tape = s\npattern = p\nm = len(tape)\nn = len(pattern)\ndp = [[False for _ in xrange(n + 1)] for _ in xrange(m + 1)]\ndp[m][n] = True\nfor j in xrange(n - 1, -1, -1):\n if pattern[j] == '*':\n dp[m][j] = dp[m][j + 1]\nfor i in xrange(m - 1, -1, -1):\n for j in xrange(n - 1, -1, -1):\n if tape[i... | <|body_start_0|>
tape = s
pattern = p
m = len(tape)
n = len(pattern)
dp = [[False for _ in xrange(n + 1)] for _ in xrange(m + 1)]
dp[m][n] = True
for j in xrange(n - 1, -1, -1):
if pattern[j] == '*':
dp[m][j] = dp[m][j + 1]
for ... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isMatch_MLE(self, s, p):
"""dp, similar to 011 Regular Expression Matching. Backward dp but Memory Limit Exceeds :param s: tape, an input string :param p: pattern, a pattern string :return: boolean"""
<|body_0|>
def isMatch_forward(self, s, p):
""""?" i... | stack_v2_sparse_classes_36k_train_009115 | 3,437 | permissive | [
{
"docstring": "dp, similar to 011 Regular Expression Matching. Backward dp but Memory Limit Exceeds :param s: tape, an input string :param p: pattern, a pattern string :return: boolean",
"name": "isMatch_MLE",
"signature": "def isMatch_MLE(self, s, p)"
},
{
"docstring": "\"?\" is not the proble... | 2 | stack_v2_sparse_classes_30k_train_008382 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch_MLE(self, s, p): dp, similar to 011 Regular Expression Matching. Backward dp but Memory Limit Exceeds :param s: tape, an input string :param p: pattern, a pattern str... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch_MLE(self, s, p): dp, similar to 011 Regular Expression Matching. Backward dp but Memory Limit Exceeds :param s: tape, an input string :param p: pattern, a pattern str... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def isMatch_MLE(self, s, p):
"""dp, similar to 011 Regular Expression Matching. Backward dp but Memory Limit Exceeds :param s: tape, an input string :param p: pattern, a pattern string :return: boolean"""
<|body_0|>
def isMatch_forward(self, s, p):
""""?" i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isMatch_MLE(self, s, p):
"""dp, similar to 011 Regular Expression Matching. Backward dp but Memory Limit Exceeds :param s: tape, an input string :param p: pattern, a pattern string :return: boolean"""
tape = s
pattern = p
m = len(tape)
n = len(pattern)
... | the_stack_v2_python_sparse | 043 Wildcard Matching.py | Aminaba123/LeetCode | train | 1 | |
1beea031d41a28a3fc1c5f5632f9a87a2ee0f3ea | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SiteCollection()",
"from .root import Root\nfrom .root import Root\nfields: Dict[str, Callable[[Any], None]] = {'dataLocationCode': lambda n: setattr(self, 'data_location_code', n.get_str_value()), 'hostname': lambda n: setattr(self, '... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SiteCollection()
<|end_body_0|>
<|body_start_1|>
from .root import Root
from .root import Root
fields: Dict[str, Callable[[Any], None]] = {'dataLocationCode': lambda n: setattr(s... | SiteCollection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiteCollection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SiteCollection:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | stack_v2_sparse_classes_36k_train_009116 | 3,131 | 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: SiteCollection",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | null | Implement the Python class `SiteCollection` described below.
Class description:
Implement the SiteCollection class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SiteCollection: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `SiteCollection` described below.
Class description:
Implement the SiteCollection class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SiteCollection: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SiteCollection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SiteCollection:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SiteCollection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SiteCollection:
"""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: SiteCollec... | the_stack_v2_python_sparse | msgraph/generated/models/site_collection.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
c863db94ef5227e48b68e93afe0b1ce404c392a8 | [
"super().__init__(data, device)\nself.entity_description = description\nself._attr_unique_id = f'{device.device_uuid}-{description.key}'\nif description.key == CONST.TEMP_STATUS_KEY:\n self._attr_native_unit_of_measurement = device.temp_unit\nelif description.key == CONST.HUMI_STATUS_KEY:\n self._attr_native_... | <|body_start_0|>
super().__init__(data, device)
self.entity_description = description
self._attr_unique_id = f'{device.device_uuid}-{description.key}'
if description.key == CONST.TEMP_STATUS_KEY:
self._attr_native_unit_of_measurement = device.temp_unit
elif descriptio... | A sensor implementation for Abode devices. | AbodeSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbodeSensor:
"""A sensor implementation for Abode devices."""
def __init__(self, data: AbodeSystem, device: AbodeSense, description: SensorEntityDescription) -> None:
"""Initialize a sensor for an Abode device."""
<|body_0|>
def native_value(self) -> float | None:
... | stack_v2_sparse_classes_36k_train_009117 | 2,873 | permissive | [
{
"docstring": "Initialize a sensor for an Abode device.",
"name": "__init__",
"signature": "def __init__(self, data: AbodeSystem, device: AbodeSense, description: SensorEntityDescription) -> None"
},
{
"docstring": "Return the state of the sensor.",
"name": "native_value",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_005573 | Implement the Python class `AbodeSensor` described below.
Class description:
A sensor implementation for Abode devices.
Method signatures and docstrings:
- def __init__(self, data: AbodeSystem, device: AbodeSense, description: SensorEntityDescription) -> None: Initialize a sensor for an Abode device.
- def native_val... | Implement the Python class `AbodeSensor` described below.
Class description:
A sensor implementation for Abode devices.
Method signatures and docstrings:
- def __init__(self, data: AbodeSystem, device: AbodeSense, description: SensorEntityDescription) -> None: Initialize a sensor for an Abode device.
- def native_val... | 2e65b77b2b5c17919939481f327963abdfdc53f0 | <|skeleton|>
class AbodeSensor:
"""A sensor implementation for Abode devices."""
def __init__(self, data: AbodeSystem, device: AbodeSense, description: SensorEntityDescription) -> None:
"""Initialize a sensor for an Abode device."""
<|body_0|>
def native_value(self) -> float | None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbodeSensor:
"""A sensor implementation for Abode devices."""
def __init__(self, data: AbodeSystem, device: AbodeSense, description: SensorEntityDescription) -> None:
"""Initialize a sensor for an Abode device."""
super().__init__(data, device)
self.entity_description = descriptio... | the_stack_v2_python_sparse | homeassistant/components/abode/sensor.py | konnected-io/home-assistant | train | 24 |
1b86360c2208d537ab4c1ffa5b47c0ea9bd70823 | [
"super().__init__(econet_device)\nself.entity_description = description\nself._attr_name = f'{econet_device.device_name}_{description.name}'\nself._attr_unique_id = f'{econet_device.device_id}_{econet_device.device_name}_{description.name}'",
"value = getattr(self._econet, self.entity_description.key)\nif self.en... | <|body_start_0|>
super().__init__(econet_device)
self.entity_description = description
self._attr_name = f'{econet_device.device_name}_{description.name}'
self._attr_unique_id = f'{econet_device.device_id}_{econet_device.device_name}_{description.name}'
<|end_body_0|>
<|body_start_1|>
... | Define a Econet sensor. | EcoNetSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EcoNetSensor:
"""Define a Econet sensor."""
def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None:
"""Initialize."""
<|body_0|>
def native_value(self):
"""Return sensors state."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_009118 | 4,025 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None"
},
{
"docstring": "Return sensors state.",
"name": "native_value",
"signature": "def native_value(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018011 | Implement the Python class `EcoNetSensor` described below.
Class description:
Define a Econet sensor.
Method signatures and docstrings:
- def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None: Initialize.
- def native_value(self): Return sensors state. | Implement the Python class `EcoNetSensor` described below.
Class description:
Define a Econet sensor.
Method signatures and docstrings:
- def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None: Initialize.
- def native_value(self): Return sensors state.
<|skeleton|>
class EcoNetSe... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EcoNetSensor:
"""Define a Econet sensor."""
def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None:
"""Initialize."""
<|body_0|>
def native_value(self):
"""Return sensors state."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EcoNetSensor:
"""Define a Econet sensor."""
def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None:
"""Initialize."""
super().__init__(econet_device)
self.entity_description = description
self._attr_name = f'{econet_device.device_name}_{... | the_stack_v2_python_sparse | homeassistant/components/econet/sensor.py | home-assistant/core | train | 35,501 |
95963e9e56d05becb1d08c18706d6738a22cbdd6 | [
"m = hashlib.md5()\n_m = hashlib.md5()\nm.update(cls.key)\n_m.update(requestid + '+' + str(m.hexdigest()).upper())\nrequesttoken = str(_m.hexdigest()).upper()\nxml = \"<?xml version='1.0' encoding='utf-8'?>\\n <REQUEST>\\n <ACTION>MeberShipRequest</ACTION>\\n ... | <|body_start_0|>
m = hashlib.md5()
_m = hashlib.md5()
m.update(cls.key)
_m.update(requestid + '+' + str(m.hexdigest()).upper())
requesttoken = str(_m.hexdigest()).upper()
xml = "<?xml version='1.0' encoding='utf-8'?>\n <REQUEST>\n ... | Traffic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Traffic:
def send_traffic(cls, requestid, phone):
""":param requestid: 唯一标识字符串,客户端生成, :param phone: 手机号码 :return:"""
<|body_0|>
def query_traffic(cls, requestid):
""":param requestid: 唯一标识字符串,客户端生成, :returns: 0=成功,-1 = 失败, 1 = 正在处理中 该接口返回含义与充值接口不同,代表提交到上游接口的状态 该接口返回成... | stack_v2_sparse_classes_36k_train_009119 | 4,315 | no_license | [
{
"docstring": ":param requestid: 唯一标识字符串,客户端生成, :param phone: 手机号码 :return:",
"name": "send_traffic",
"signature": "def send_traffic(cls, requestid, phone)"
},
{
"docstring": ":param requestid: 唯一标识字符串,客户端生成, :returns: 0=成功,-1 = 失败, 1 = 正在处理中 该接口返回含义与充值接口不同,代表提交到上游接口的状态 该接口返回成功仅代表上游接口成功处理(多数情况为... | 2 | stack_v2_sparse_classes_30k_train_007755 | Implement the Python class `Traffic` described below.
Class description:
Implement the Traffic class.
Method signatures and docstrings:
- def send_traffic(cls, requestid, phone): :param requestid: 唯一标识字符串,客户端生成, :param phone: 手机号码 :return:
- def query_traffic(cls, requestid): :param requestid: 唯一标识字符串,客户端生成, :returns... | Implement the Python class `Traffic` described below.
Class description:
Implement the Traffic class.
Method signatures and docstrings:
- def send_traffic(cls, requestid, phone): :param requestid: 唯一标识字符串,客户端生成, :param phone: 手机号码 :return:
- def query_traffic(cls, requestid): :param requestid: 唯一标识字符串,客户端生成, :returns... | 9221630f236d096487528d3e382477056c6dc76b | <|skeleton|>
class Traffic:
def send_traffic(cls, requestid, phone):
""":param requestid: 唯一标识字符串,客户端生成, :param phone: 手机号码 :return:"""
<|body_0|>
def query_traffic(cls, requestid):
""":param requestid: 唯一标识字符串,客户端生成, :returns: 0=成功,-1 = 失败, 1 = 正在处理中 该接口返回含义与充值接口不同,代表提交到上游接口的状态 该接口返回成... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Traffic:
def send_traffic(cls, requestid, phone):
""":param requestid: 唯一标识字符串,客户端生成, :param phone: 手机号码 :return:"""
m = hashlib.md5()
_m = hashlib.md5()
m.update(cls.key)
_m.update(requestid + '+' + str(m.hexdigest()).upper())
requesttoken = str(_m.hexdigest())... | the_stack_v2_python_sparse | wanx/platforms/traffic.py | LeePapa/migu_community | train | 0 | |
cc43bd908d879d665d666e88ee30e7a60b1d25b4 | [
"self.position = position\nself.num_trials = num_trials\nself.position_value = np.true_divide(1000, self.position)\nif self.position == 1:\n self.position_word = ' position '\nelse:\n self.position_word = ' positions '",
"investment_outcome = []\nfor i in range(self.position * self.num_trials):\n outcome... | <|body_start_0|>
self.position = position
self.num_trials = num_trials
self.position_value = np.true_divide(1000, self.position)
if self.position == 1:
self.position_word = ' position '
else:
self.position_word = ' positions '
<|end_body_0|>
<|body_start_... | investment_instrument | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class investment_instrument:
def __init__(self, position, num_trials):
"""Initiate an instance of the investment_instrument class. A function of an investment position"""
<|body_0|>
def generate_daily_returns(self):
"""For each position, simulate n daily returns, where n i... | stack_v2_sparse_classes_36k_train_009120 | 3,339 | no_license | [
{
"docstring": "Initiate an instance of the investment_instrument class. A function of an investment position",
"name": "__init__",
"signature": "def __init__(self, position, num_trials)"
},
{
"docstring": "For each position, simulate n daily returns, where n is num_trials",
"name": "generat... | 4 | null | Implement the Python class `investment_instrument` described below.
Class description:
Implement the investment_instrument class.
Method signatures and docstrings:
- def __init__(self, position, num_trials): Initiate an instance of the investment_instrument class. A function of an investment position
- def generate_d... | Implement the Python class `investment_instrument` described below.
Class description:
Implement the investment_instrument class.
Method signatures and docstrings:
- def __init__(self, position, num_trials): Initiate an instance of the investment_instrument class. A function of an investment position
- def generate_d... | 5b904060e8bced7f91547ad7f7819773a7450a1e | <|skeleton|>
class investment_instrument:
def __init__(self, position, num_trials):
"""Initiate an instance of the investment_instrument class. A function of an investment position"""
<|body_0|>
def generate_daily_returns(self):
"""For each position, simulate n daily returns, where n i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class investment_instrument:
def __init__(self, position, num_trials):
"""Initiate an instance of the investment_instrument class. A function of an investment position"""
self.position = position
self.num_trials = num_trials
self.position_value = np.true_divide(1000, self.position)
... | the_stack_v2_python_sparse | zvz201/investment_instrument.py | ds-ga-1007/assignment8 | train | 1 | |
646a7319cc86ef33fa426c9985e2edc83175c21f | [
"self.X = X_init\nself.Y = Y_init\nself.l = l\nself.sigma_f = sigma_f\nself.K = self.kernel(self.X, self.X)",
"first = np.sum(X1 ** 2, 1).reshape(-1, 1)\nsecond = np.sum(X2 ** 2, 1)\ndist_sq = first + second - 2 * np.dot(X1, X2.T)\nkernel = self.sigma_f ** 2 * np.exp(-0.5 / self.l ** 2 * dist_sq)\nreturn kernel"
... | <|body_start_0|>
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(self.X, self.X)
<|end_body_0|>
<|body_start_1|>
first = np.sum(X1 ** 2, 1).reshape(-1, 1)
second = np.sum(X2 ** 2, 1)
dist_sq = first + second - 2 * np... | A class that represents a gaussian process | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""A class that represents a gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""constructor for class"""
<|body_0|>
def kernel(self, X1, X2):
"""Returns the covariance matrix"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_009121 | 779 | no_license | [
{
"docstring": "constructor for class",
"name": "__init__",
"signature": "def __init__(self, X_init, Y_init, l=1, sigma_f=1)"
},
{
"docstring": "Returns the covariance matrix",
"name": "kernel",
"signature": "def kernel(self, X1, X2)"
}
] | 2 | null | Implement the Python class `GaussianProcess` described below.
Class description:
A class that represents a gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): constructor for class
- def kernel(self, X1, X2): Returns the covariance matrix | Implement the Python class `GaussianProcess` described below.
Class description:
A class that represents a gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): constructor for class
- def kernel(self, X1, X2): Returns the covariance matrix
<|skeleton|>
class Gaussi... | 91300120d38acb6440a6dbb8c408b1193c07de88 | <|skeleton|>
class GaussianProcess:
"""A class that represents a gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""constructor for class"""
<|body_0|>
def kernel(self, X1, X2):
"""Returns the covariance matrix"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianProcess:
"""A class that represents a gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""constructor for class"""
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(self.X, self.X)
def... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/0-gp.py | anaruzz/holbertonschool-machine_learning | train | 0 |
7c2cc5dba1a9bd62da60c453d6d7e2c6b9e5d188 | [
"if request.user.is_authenticated:\n return HttpResponseRedirect(reverse('OSINT_System_Core:tso-dashboard'))\nreturn render(request, 'User_Accounts_Management_Unit/login.html', {'message': ''})",
"username = request.POST.get('username', None)\npassword = request.POST.get('password', None)\nif username is not N... | <|body_start_0|>
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('OSINT_System_Core:tso-dashboard'))
return render(request, 'User_Accounts_Management_Unit/login.html', {'message': ''})
<|end_body_0|>
<|body_start_1|>
username = request.POST.get('username', None... | USER Login View | User_Login | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User_Login:
"""USER Login View"""
def get(self, request, *args):
"""get handler for login view"""
<|body_0|>
def post(self, request):
"""post handler for login view"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if request.user.is_authenticated... | stack_v2_sparse_classes_36k_train_009122 | 19,842 | no_license | [
{
"docstring": "get handler for login view",
"name": "get",
"signature": "def get(self, request, *args)"
},
{
"docstring": "post handler for login view",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | null | Implement the Python class `User_Login` described below.
Class description:
USER Login View
Method signatures and docstrings:
- def get(self, request, *args): get handler for login view
- def post(self, request): post handler for login view | Implement the Python class `User_Login` described below.
Class description:
USER Login View
Method signatures and docstrings:
- def get(self, request, *args): get handler for login view
- def post(self, request): post handler for login view
<|skeleton|>
class User_Login:
"""USER Login View"""
def get(self, ... | 79c55755509195029a01eb487b971408a724e6c8 | <|skeleton|>
class User_Login:
"""USER Login View"""
def get(self, request, *args):
"""get handler for login view"""
<|body_0|>
def post(self, request):
"""post handler for login view"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class User_Login:
"""USER Login View"""
def get(self, request, *args):
"""get handler for login view"""
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('OSINT_System_Core:tso-dashboard'))
return render(request, 'User_Accounts_Management_Unit/login.html'... | the_stack_v2_python_sparse | User_Accounts_Management_Unit/views.py | maliksblr92/v2 | train | 0 |
472abe0395a624babf2be5b4f23a1877eda808c8 | [
"start_time = time.time()\nrequest_data = {'开始时间': start_time}\nif request.GET.dict():\n request_data['query_params'] = request.GET.dict()\nif request.body:\n try:\n request_data['data'] = json.loads(request.body.decode('utf8', 'ignore'))\n except:\n request_data['data'] = request.body.decode... | <|body_start_0|>
start_time = time.time()
request_data = {'开始时间': start_time}
if request.GET.dict():
request_data['query_params'] = request.GET.dict()
if request.body:
try:
request_data['data'] = json.loads(request.body.decode('utf8', 'ignore'))
... | 自定义日志中间件 | LoggerMiddleware | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoggerMiddleware:
"""自定义日志中间件"""
def process_request(self, request):
"""请求信息"""
<|body_0|>
def process_response(self, request, response):
"""响应信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
start_time = time.time()
request_data = {'开... | stack_v2_sparse_classes_36k_train_009123 | 1,946 | no_license | [
{
"docstring": "请求信息",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "响应信息",
"name": "process_response",
"signature": "def process_response(self, request, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012863 | Implement the Python class `LoggerMiddleware` described below.
Class description:
自定义日志中间件
Method signatures and docstrings:
- def process_request(self, request): 请求信息
- def process_response(self, request, response): 响应信息 | Implement the Python class `LoggerMiddleware` described below.
Class description:
自定义日志中间件
Method signatures and docstrings:
- def process_request(self, request): 请求信息
- def process_response(self, request, response): 响应信息
<|skeleton|>
class LoggerMiddleware:
"""自定义日志中间件"""
def process_request(self, request)... | 764df78c59d6e9c2dafee65e875b29df2635d33c | <|skeleton|>
class LoggerMiddleware:
"""自定义日志中间件"""
def process_request(self, request):
"""请求信息"""
<|body_0|>
def process_response(self, request, response):
"""响应信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoggerMiddleware:
"""自定义日志中间件"""
def process_request(self, request):
"""请求信息"""
start_time = time.time()
request_data = {'开始时间': start_time}
if request.GET.dict():
request_data['query_params'] = request.GET.dict()
if request.body:
try:
... | the_stack_v2_python_sparse | utils/custom_middleware.py | shawnhuang90s/oms_test | train | 2 |
94a3f5f8134b2b1fbce90946b8067f384daa6ea7 | [
"Web3Initializer.__init__(self, url, port)\nself.contract = self.web3.eth.contract(abi=contract_abi, address=contract_address)\nself.last_block = self.web3.eth.blockNumber\nself.private_key = private_key\nself.minter = minter\nself.password = password\nself.timeout = 120\nself.ledger_type = LedgerType.ETHEREUM",
... | <|body_start_0|>
Web3Initializer.__init__(self, url, port)
self.contract = self.web3.eth.contract(abi=contract_abi, address=contract_address)
self.last_block = self.web3.eth.blockNumber
self.private_key = private_key
self.minter = minter
self.password = password
s... | Ethereum implementation of the Responder. | EthereumResponder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EthereumResponder:
"""Ethereum implementation of the Responder."""
def __init__(self, minter: str, contract_address: str, contract_abi: object, url: str, port: int=None, private_key: str=None, password: str=None):
""":param str minter: The contract minter who is in charge of data col... | stack_v2_sparse_classes_36k_train_009124 | 14,213 | permissive | [
{
"docstring": ":param str minter: The contract minter who is in charge of data collecting :param str contract_address: The address of data transfer contract implementing Interledger interface :param object contract_abi: Contract ABI :param str url: The web3 url :param int port: The web3 port, if any (default=N... | 2 | stack_v2_sparse_classes_30k_train_002950 | Implement the Python class `EthereumResponder` described below.
Class description:
Ethereum implementation of the Responder.
Method signatures and docstrings:
- def __init__(self, minter: str, contract_address: str, contract_abi: object, url: str, port: int=None, private_key: str=None, password: str=None): :param str... | Implement the Python class `EthereumResponder` described below.
Class description:
Ethereum implementation of the Responder.
Method signatures and docstrings:
- def __init__(self, minter: str, contract_address: str, contract_abi: object, url: str, port: int=None, private_key: str=None, password: str=None): :param str... | 404b6caa7c5ea58c27c20d716dffa60904fb7f46 | <|skeleton|>
class EthereumResponder:
"""Ethereum implementation of the Responder."""
def __init__(self, minter: str, contract_address: str, contract_abi: object, url: str, port: int=None, private_key: str=None, password: str=None):
""":param str minter: The contract minter who is in charge of data col... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EthereumResponder:
"""Ethereum implementation of the Responder."""
def __init__(self, minter: str, contract_address: str, contract_abi: object, url: str, port: int=None, private_key: str=None, password: str=None):
""":param str minter: The contract minter who is in charge of data collecting :para... | the_stack_v2_python_sparse | il-agent/src/data_transfer/ethereum.py | SOFIE-project/SMAUG-Marketplace | train | 1 |
0f41d718b7264f317ab9661d9e49515cae80a97a | [
"super().__init__(server, params, backend)\nself._client_write = None\nself._client_read = None\nself._master_name, self._sentinel_hosts, self._database_name = self.parse_connection_string(server)\nself.log = logging.getLogger(DJANGO_REDIS_LOGGER)",
"try:\n master_name, servers_string, database_name = connecti... | <|body_start_0|>
super().__init__(server, params, backend)
self._client_write = None
self._client_read = None
self._master_name, self._sentinel_hosts, self._database_name = self.parse_connection_string(server)
self.log = logging.getLogger(DJANGO_REDIS_LOGGER)
<|end_body_0|>
<|bo... | Sentinel client object extending django-redis DefaultClient | SentinelClient | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SentinelClient:
"""Sentinel client object extending django-redis DefaultClient"""
def __init__(self, server, params, backend):
"""Slightly different logic than connection to multiple Redis servers. Reserve only one write and one read descriptor, as they will be closed on exit anyway.... | stack_v2_sparse_classes_36k_train_009125 | 6,382 | permissive | [
{
"docstring": "Slightly different logic than connection to multiple Redis servers. Reserve only one write and one read descriptor, as they will be closed on exit anyway.",
"name": "__init__",
"signature": "def __init__(self, server, params, backend)"
},
{
"docstring": "Parse connection string i... | 5 | stack_v2_sparse_classes_30k_train_004789 | Implement the Python class `SentinelClient` described below.
Class description:
Sentinel client object extending django-redis DefaultClient
Method signatures and docstrings:
- def __init__(self, server, params, backend): Slightly different logic than connection to multiple Redis servers. Reserve only one write and on... | Implement the Python class `SentinelClient` described below.
Class description:
Sentinel client object extending django-redis DefaultClient
Method signatures and docstrings:
- def __init__(self, server, params, backend): Slightly different logic than connection to multiple Redis servers. Reserve only one write and on... | f2d46fc46b271eb3b4d565039a29c15ba15f027c | <|skeleton|>
class SentinelClient:
"""Sentinel client object extending django-redis DefaultClient"""
def __init__(self, server, params, backend):
"""Slightly different logic than connection to multiple Redis servers. Reserve only one write and one read descriptor, as they will be closed on exit anyway.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SentinelClient:
"""Sentinel client object extending django-redis DefaultClient"""
def __init__(self, server, params, backend):
"""Slightly different logic than connection to multiple Redis servers. Reserve only one write and one read descriptor, as they will be closed on exit anyway."""
s... | the_stack_v2_python_sparse | src/richie/apps/core/cache.py | openfun/richie | train | 238 |
97708158999324baa3be4855505af8b6bed94ca1 | [
"frame_size = 200\nhop_size = 180\naudio = tf.random.normal([1, 1000])\npadded_audio = spectral_ops.pad(audio, frame_size, hop_size, 'same')\ns_pad_end = tf.signal.stft(audio, frame_size, hop_size, pad_end=True)\ns_same = tf.signal.stft(padded_audio, frame_size, hop_size, pad_end=False)\nself.assertAllClose(np.abs(... | <|body_start_0|>
frame_size = 200
hop_size = 180
audio = tf.random.normal([1, 1000])
padded_audio = spectral_ops.pad(audio, frame_size, hop_size, 'same')
s_pad_end = tf.signal.stft(audio, frame_size, hop_size, pad_end=True)
s_same = tf.signal.stft(padded_audio, frame_size... | PadTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PadTest:
def test_pad_end_stft_is_consistent(self):
"""Ensure that spectral_ops.pad('same') is same as stft(pad_end=True)."""
<|body_0|>
def test_padding_shapes_are_correct(self, padding, hop_size):
"""Ensure that pad() and get_framed_lengths() have correct shapes.""... | stack_v2_sparse_classes_36k_train_009126 | 11,158 | permissive | [
{
"docstring": "Ensure that spectral_ops.pad('same') is same as stft(pad_end=True).",
"name": "test_pad_end_stft_is_consistent",
"signature": "def test_pad_end_stft_is_consistent(self)"
},
{
"docstring": "Ensure that pad() and get_framed_lengths() have correct shapes.",
"name": "test_padding... | 2 | stack_v2_sparse_classes_30k_train_004112 | Implement the Python class `PadTest` described below.
Class description:
Implement the PadTest class.
Method signatures and docstrings:
- def test_pad_end_stft_is_consistent(self): Ensure that spectral_ops.pad('same') is same as stft(pad_end=True).
- def test_padding_shapes_are_correct(self, padding, hop_size): Ensur... | Implement the Python class `PadTest` described below.
Class description:
Implement the PadTest class.
Method signatures and docstrings:
- def test_pad_end_stft_is_consistent(self): Ensure that spectral_ops.pad('same') is same as stft(pad_end=True).
- def test_padding_shapes_are_correct(self, padding, hop_size): Ensur... | 7e0a39420f3bd87d9efd54cf0d36f4e258311340 | <|skeleton|>
class PadTest:
def test_pad_end_stft_is_consistent(self):
"""Ensure that spectral_ops.pad('same') is same as stft(pad_end=True)."""
<|body_0|>
def test_padding_shapes_are_correct(self, padding, hop_size):
"""Ensure that pad() and get_framed_lengths() have correct shapes.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PadTest:
def test_pad_end_stft_is_consistent(self):
"""Ensure that spectral_ops.pad('same') is same as stft(pad_end=True)."""
frame_size = 200
hop_size = 180
audio = tf.random.normal([1, 1000])
padded_audio = spectral_ops.pad(audio, frame_size, hop_size, 'same')
... | the_stack_v2_python_sparse | ddsp/spectral_ops_test.py | magenta/ddsp | train | 2,666 | |
bd2af086ccad86af8fb117ae783e48ea5be34a38 | [
"try:\n indices = self.getArrayIndices()\nexcept TypeError:\n return self\navailable_index = 0\ntry:\n for i in range(max(indices) + 2):\n if not self[i].connections():\n available_index = i\n break\nexcept ValueError:\n available_index = 0\nreturn self[available_index]",
... | <|body_start_0|>
try:
indices = self.getArrayIndices()
except TypeError:
return self
available_index = 0
try:
for i in range(max(indices) + 2):
if not self[i].connections():
available_index = i
br... | Extension to PyMel classes | MayaExtension | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MayaExtension:
"""Extension to PyMel classes"""
def next_available(self):
"""returns the next available attr in a multi attr :return: The available index as an attribute"""
<|body_0|>
def value(self, value=None):
"""returns or set the check box value"""
<... | stack_v2_sparse_classes_36k_train_009127 | 37,214 | permissive | [
{
"docstring": "returns the next available attr in a multi attr :return: The available index as an attribute",
"name": "next_available",
"signature": "def next_available(self)"
},
{
"docstring": "returns or set the check box value",
"name": "value",
"signature": "def value(self, value=No... | 3 | stack_v2_sparse_classes_30k_val_001038 | Implement the Python class `MayaExtension` described below.
Class description:
Extension to PyMel classes
Method signatures and docstrings:
- def next_available(self): returns the next available attr in a multi attr :return: The available index as an attribute
- def value(self, value=None): returns or set the check b... | Implement the Python class `MayaExtension` described below.
Class description:
Extension to PyMel classes
Method signatures and docstrings:
- def next_available(self): returns the next available attr in a multi attr :return: The available index as an attribute
- def value(self, value=None): returns or set the check b... | 7b4cf60cb17f00435ecc3e03d573a9e2d0b44fe0 | <|skeleton|>
class MayaExtension:
"""Extension to PyMel classes"""
def next_available(self):
"""returns the next available attr in a multi attr :return: The available index as an attribute"""
<|body_0|>
def value(self, value=None):
"""returns or set the check box value"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MayaExtension:
"""Extension to PyMel classes"""
def next_available(self):
"""returns the next available attr in a multi attr :return: The available index as an attribute"""
try:
indices = self.getArrayIndices()
except TypeError:
return self
availabl... | the_stack_v2_python_sparse | anima/dcc/mayaEnv/extension.py | eoyilmaz/anima | train | 113 |
654d1d3cc6e6dc4341c4c2ae4627f6b58877500d | [
"self.psum = []\ns = 0\nfor n in w:\n s += n\n self.psum.append(s)\nself.total = s",
"target = math.floor(self.total * random.random())\ni, j = (0, len(self.psum) - 1)\nwhile i + 1 < j:\n mid = (i + j) / 2\n if self.psum[mid] > target:\n j = mid\n else:\n i = mid\nif self.psum[i] > ta... | <|body_start_0|>
self.psum = []
s = 0
for n in w:
s += n
self.psum.append(s)
self.total = s
<|end_body_0|>
<|body_start_1|>
target = math.floor(self.total * random.random())
i, j = (0, len(self.psum) - 1)
while i + 1 < j:
mid =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.psum = []
s = 0
for n in w:
s += n
self.psum.append... | stack_v2_sparse_classes_36k_train_009128 | 1,609 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 6aaf58b1e1170a994affd6330d90b89aaaf582d9 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.psum = []
s = 0
for n in w:
s += n
self.psum.append(s)
self.total = s
def pickIndex(self):
""":rtype: int"""
target = math.floor(self.total * random.random())
... | the_stack_v2_python_sparse | Python/528.py | skywhat/leetcode | train | 82 | |
92836280dd9151eb3043d2ffd9b6f10bd91f7b27 | [
"if isinstance(bing_key, str):\n self.bing_key = bing_key\nelse:\n raise TypeError(\"'bing_key' must be type of string\")\nself.access_token = self.__get_access_token()\nif language is None:\n self.language = 'germany'\nelif isinstance(language, str):\n self.language = language\nelse:\n raise TypeErr... | <|body_start_0|>
if isinstance(bing_key, str):
self.bing_key = bing_key
else:
raise TypeError("'bing_key' must be type of string")
self.access_token = self.__get_access_token()
if language is None:
self.language = 'germany'
elif isinstance(lang... | TextToSpeech | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextToSpeech:
def __init__(self, bing_key, language=None, gender=None, output_mode='riff-16khz-16bit-mono-pcm'):
"""constructor to initialize bing_key, language, gender and output mode :param bing_key: string, bing api key to get the access token :param language: string, select appropria... | stack_v2_sparse_classes_36k_train_009129 | 5,760 | permissive | [
{
"docstring": "constructor to initialize bing_key, language, gender and output mode :param bing_key: string, bing api key to get the access token :param language: string, select appropriate language for the output speech :param gender: string, gender of the speaker, can be 'Female' or 'Male' :param output_mode... | 4 | stack_v2_sparse_classes_30k_train_000518 | Implement the Python class `TextToSpeech` described below.
Class description:
Implement the TextToSpeech class.
Method signatures and docstrings:
- def __init__(self, bing_key, language=None, gender=None, output_mode='riff-16khz-16bit-mono-pcm'): constructor to initialize bing_key, language, gender and output mode :p... | Implement the Python class `TextToSpeech` described below.
Class description:
Implement the TextToSpeech class.
Method signatures and docstrings:
- def __init__(self, bing_key, language=None, gender=None, output_mode='riff-16khz-16bit-mono-pcm'): constructor to initialize bing_key, language, gender and output mode :p... | f6bd9e68365797351dfc7a4cb17ee5141ec77f97 | <|skeleton|>
class TextToSpeech:
def __init__(self, bing_key, language=None, gender=None, output_mode='riff-16khz-16bit-mono-pcm'):
"""constructor to initialize bing_key, language, gender and output mode :param bing_key: string, bing api key to get the access token :param language: string, select appropria... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextToSpeech:
def __init__(self, bing_key, language=None, gender=None, output_mode='riff-16khz-16bit-mono-pcm'):
"""constructor to initialize bing_key, language, gender and output mode :param bing_key: string, bing api key to get the access token :param language: string, select appropriate language fo... | the_stack_v2_python_sparse | speech_control/text_to_speech.py | NikoKalbitzer/speech_processing_v2 | train | 0 | |
d3285af8240246530d8b4602ebb79bdc610586f7 | [
"self.api_url = 'http://api.douban.com/labs/bubbler/user/{}'\nself.session = Session()\nself.home_page = 'http://www.douban.com/people/{}'",
"userid = user[0]\nresult = self.session.get(self.api_url.format(userid)).json()\nself.assertEqual(result.get('id'), '1832573')\nself.assertEqual(result.get('uid'), userid)\... | <|body_start_0|>
self.api_url = 'http://api.douban.com/labs/bubbler/user/{}'
self.session = Session()
self.home_page = 'http://www.douban.com/people/{}'
<|end_body_0|>
<|body_start_1|>
userid = user[0]
result = self.session.get(self.api_url.format(userid)).json()
self.as... | test dou ban apis | TestDouBanApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDouBanApi:
"""test dou ban apis"""
def setUp(self):
"""pass"""
<|body_0|>
def test_first_user_info(self):
"""pass"""
<|body_1|>
def test_second_user_info(self):
"""pass"""
<|body_2|>
def test_third_user_info(self):
""... | stack_v2_sparse_classes_36k_train_009130 | 1,986 | no_license | [
{
"docstring": "pass",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "pass",
"name": "test_first_user_info",
"signature": "def test_first_user_info(self)"
},
{
"docstring": "pass",
"name": "test_second_user_info",
"signature": "def test_second_user_inf... | 4 | stack_v2_sparse_classes_30k_train_021345 | Implement the Python class `TestDouBanApi` described below.
Class description:
test dou ban apis
Method signatures and docstrings:
- def setUp(self): pass
- def test_first_user_info(self): pass
- def test_second_user_info(self): pass
- def test_third_user_info(self): pass | Implement the Python class `TestDouBanApi` described below.
Class description:
test dou ban apis
Method signatures and docstrings:
- def setUp(self): pass
- def test_first_user_info(self): pass
- def test_second_user_info(self): pass
- def test_third_user_info(self): pass
<|skeleton|>
class TestDouBanApi:
"""tes... | b8dd4dd6dafaf9899e97bbb75a3ef80246ec427b | <|skeleton|>
class TestDouBanApi:
"""test dou ban apis"""
def setUp(self):
"""pass"""
<|body_0|>
def test_first_user_info(self):
"""pass"""
<|body_1|>
def test_second_user_info(self):
"""pass"""
<|body_2|>
def test_third_user_info(self):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDouBanApi:
"""test dou ban apis"""
def setUp(self):
"""pass"""
self.api_url = 'http://api.douban.com/labs/bubbler/user/{}'
self.session = Session()
self.home_page = 'http://www.douban.com/people/{}'
def test_first_user_info(self):
"""pass"""
userid... | the_stack_v2_python_sparse | fifth_week/second_day/test_douban_api.py | czkun1986/Let-s-go-python- | train | 0 |
115659e72ad0f9618a5da88d602ad39644ae2d6e | [
"self.org = org\nself.name = name\nself.telephone = telephone\nself.email = email",
"template = 'BEGIN:VCARD\\nORG:{}\\nFN:{}\\nTEL:{}\\nEMAIL:{}\\nEND:VCARD'.format(self.org, self.name, self.telephone, self.email)\nprint(template)\nimg = qrcode.make(template)\nimage_path = path + '%s.png' % self.name\nimg.save(i... | <|body_start_0|>
self.org = org
self.name = name
self.telephone = telephone
self.email = email
<|end_body_0|>
<|body_start_1|>
template = 'BEGIN:VCARD\nORG:{}\nFN:{}\nTEL:{}\nEMAIL:{}\nEND:VCARD'.format(self.org, self.name, self.telephone, self.email)
print(template)
... | 实现生成二维码图片功能 | Print_Image | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Print_Image:
"""实现生成二维码图片功能"""
def __init__(self, org, name, telephone, email):
"""构造函数,初始化以下参数: self.org:部门(职位) self.name:姓名 self.telephone:电话 self.email: 邮箱"""
<|body_0|>
def get_vard(self, path):
"""生成二维码图片"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_009131 | 944 | no_license | [
{
"docstring": "构造函数,初始化以下参数: self.org:部门(职位) self.name:姓名 self.telephone:电话 self.email: 邮箱",
"name": "__init__",
"signature": "def __init__(self, org, name, telephone, email)"
},
{
"docstring": "生成二维码图片",
"name": "get_vard",
"signature": "def get_vard(self, path)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007808 | Implement the Python class `Print_Image` described below.
Class description:
实现生成二维码图片功能
Method signatures and docstrings:
- def __init__(self, org, name, telephone, email): 构造函数,初始化以下参数: self.org:部门(职位) self.name:姓名 self.telephone:电话 self.email: 邮箱
- def get_vard(self, path): 生成二维码图片 | Implement the Python class `Print_Image` described below.
Class description:
实现生成二维码图片功能
Method signatures and docstrings:
- def __init__(self, org, name, telephone, email): 构造函数,初始化以下参数: self.org:部门(职位) self.name:姓名 self.telephone:电话 self.email: 邮箱
- def get_vard(self, path): 生成二维码图片
<|skeleton|>
class Print_Image:... | 588cae717d46f0dfcec41ea2c2bf4328d5d46b5c | <|skeleton|>
class Print_Image:
"""实现生成二维码图片功能"""
def __init__(self, org, name, telephone, email):
"""构造函数,初始化以下参数: self.org:部门(职位) self.name:姓名 self.telephone:电话 self.email: 邮箱"""
<|body_0|>
def get_vard(self, path):
"""生成二维码图片"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Print_Image:
"""实现生成二维码图片功能"""
def __init__(self, org, name, telephone, email):
"""构造函数,初始化以下参数: self.org:部门(职位) self.name:姓名 self.telephone:电话 self.email: 邮箱"""
self.org = org
self.name = name
self.telephone = telephone
self.email = email
def get_vard(self, p... | the_stack_v2_python_sparse | print_images/print_image.py | bai-design/my-tcs-git | train | 0 |
6e3aaee3eee289eed36819c1b0b53c39d0ead6a0 | [
"self.eula = kwargs.pop('eula', None)\nself.content_type_id = kwargs.pop('content_type_id', None)\nself.object_pk = kwargs.pop('object_pk', None)\nsuper(SignEULAForm, self).__init__(*args, **kwargs)\nself.fields['accept'].widget.attrs.update({'class': 'required'})",
"if self.content_type_id is not None and self.o... | <|body_start_0|>
self.eula = kwargs.pop('eula', None)
self.content_type_id = kwargs.pop('content_type_id', None)
self.object_pk = kwargs.pop('object_pk', None)
super(SignEULAForm, self).__init__(*args, **kwargs)
self.fields['accept'].widget.attrs.update({'class': 'required'})
<|e... | Display accept and next fields on EULA form. | SignEULAForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignEULAForm:
"""Display accept and next fields on EULA form."""
def __init__(self, *args, **kwargs):
"""Initialise variables."""
<|body_0|>
def save(self, request):
"""Save the UserEULA and return the saved object."""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_009132 | 1,601 | no_license | [
{
"docstring": "Initialise variables.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Save the UserEULA and return the saved object.",
"name": "save",
"signature": "def save(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013457 | Implement the Python class `SignEULAForm` described below.
Class description:
Display accept and next fields on EULA form.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialise variables.
- def save(self, request): Save the UserEULA and return the saved object. | Implement the Python class `SignEULAForm` described below.
Class description:
Display accept and next fields on EULA form.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialise variables.
- def save(self, request): Save the UserEULA and return the saved object.
<|skeleton|>
class SignEU... | 9219e6c5a49eecd1c66dd1b518640c5d678acab6 | <|skeleton|>
class SignEULAForm:
"""Display accept and next fields on EULA form."""
def __init__(self, *args, **kwargs):
"""Initialise variables."""
<|body_0|>
def save(self, request):
"""Save the UserEULA and return the saved object."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignEULAForm:
"""Display accept and next fields on EULA form."""
def __init__(self, *args, **kwargs):
"""Initialise variables."""
self.eula = kwargs.pop('eula', None)
self.content_type_id = kwargs.pop('content_type_id', None)
self.object_pk = kwargs.pop('object_pk', None)
... | the_stack_v2_python_sparse | tunobase/eula/forms.py | unomena/tunobase | train | 0 |
71d7dfb3db3d61c4283458518b9cb104f5b7c2fc | [
"self.argument_spec = netapp_utils.na_ontap_host_argument_spec()\nself.argument_spec.update(dict(state=dict(required=False, choices=['present'], default='present'), node=dict(required=True, type='str'), port=dict(required=True, type='str'), mtu=dict(required=False, type='str', default=None), autonegotiate_admin=dic... | <|body_start_0|>
self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
self.argument_spec.update(dict(state=dict(required=False, choices=['present'], default='present'), node=dict(required=True, type='str'), port=dict(required=True, type='str'), mtu=dict(required=False, type='str', default=Non... | Modify a Net port | NetAppOntapNetPort | [
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetAppOntapNetPort:
"""Modify a Net port"""
def __init__(self):
"""Initialize the Ontap Net Port Class"""
<|body_0|>
def get_net_port(self):
"""Return details about the net port :return: Details about the net port. None if not found. :rtype: dict"""
<|bod... | stack_v2_sparse_classes_36k_train_009133 | 8,175 | permissive | [
{
"docstring": "Initialize the Ontap Net Port Class",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Return details about the net port :return: Details about the net port. None if not found. :rtype: dict",
"name": "get_net_port",
"signature": "def get_net_port(s... | 4 | stack_v2_sparse_classes_30k_train_011677 | Implement the Python class `NetAppOntapNetPort` described below.
Class description:
Modify a Net port
Method signatures and docstrings:
- def __init__(self): Initialize the Ontap Net Port Class
- def get_net_port(self): Return details about the net port :return: Details about the net port. None if not found. :rtype: ... | Implement the Python class `NetAppOntapNetPort` described below.
Class description:
Modify a Net port
Method signatures and docstrings:
- def __init__(self): Initialize the Ontap Net Port Class
- def get_net_port(self): Return details about the net port :return: Details about the net port. None if not found. :rtype: ... | 0cd0c003884155ac922e3e301305ac202de7028c | <|skeleton|>
class NetAppOntapNetPort:
"""Modify a Net port"""
def __init__(self):
"""Initialize the Ontap Net Port Class"""
<|body_0|>
def get_net_port(self):
"""Return details about the net port :return: Details about the net port. None if not found. :rtype: dict"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetAppOntapNetPort:
"""Modify a Net port"""
def __init__(self):
"""Initialize the Ontap Net Port Class"""
self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
self.argument_spec.update(dict(state=dict(required=False, choices=['present'], default='present'), node=dict(re... | the_stack_v2_python_sparse | ansible/my_env/lib/python2.7/site-packages/ansible/modules/storage/netapp/na_ontap_net_port.py | otus-devops-2019-02/yyashkin_infra | train | 0 |
c4e849864d94b8b94dc15c79409964e27fd5d805 | [
"try:\n response = requests.get(CONF.api.github_api_capabilities_url)\n LOG.debug('Response Status: %s / Used Requests Cache: %s' % (response.status_code, getattr(response, 'from_cache', False)))\n if response.status_code == 200:\n regex = re.compile('^[0-9]{4}\\\\.[0-9]{2}\\\\.json$')\n capa... | <|body_start_0|>
try:
response = requests.get(CONF.api.github_api_capabilities_url)
LOG.debug('Response Status: %s / Used Requests Cache: %s' % (response.status_code, getattr(response, 'from_cache', False)))
if response.status_code == 200:
regex = re.compile('... | /v1/capabilities handler. This acts as a proxy for retrieving capability files from the openstack/defcore Github repository. | CapabilitiesController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CapabilitiesController:
"""/v1/capabilities handler. This acts as a proxy for retrieving capability files from the openstack/defcore Github repository."""
def get(self):
"""Get a list of all available capabilities."""
<|body_0|>
def get_one(self, file_name):
"""H... | stack_v2_sparse_classes_36k_train_009134 | 8,563 | permissive | [
{
"docstring": "Get a list of all available capabilities.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Handler for getting contents of specific capability file.",
"name": "get_one",
"signature": "def get_one(self, file_name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016661 | Implement the Python class `CapabilitiesController` described below.
Class description:
/v1/capabilities handler. This acts as a proxy for retrieving capability files from the openstack/defcore Github repository.
Method signatures and docstrings:
- def get(self): Get a list of all available capabilities.
- def get_on... | Implement the Python class `CapabilitiesController` described below.
Class description:
/v1/capabilities handler. This acts as a proxy for retrieving capability files from the openstack/defcore Github repository.
Method signatures and docstrings:
- def get(self): Get a list of all available capabilities.
- def get_on... | 711f7527c430873edbed72e4f85af916b2088014 | <|skeleton|>
class CapabilitiesController:
"""/v1/capabilities handler. This acts as a proxy for retrieving capability files from the openstack/defcore Github repository."""
def get(self):
"""Get a list of all available capabilities."""
<|body_0|>
def get_one(self, file_name):
"""H... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CapabilitiesController:
"""/v1/capabilities handler. This acts as a proxy for retrieving capability files from the openstack/defcore Github repository."""
def get(self):
"""Get a list of all available capabilities."""
try:
response = requests.get(CONF.api.github_api_capabiliti... | the_stack_v2_python_sparse | refstack/api/controllers/v1.py | russell/refstack | train | 0 |
92313e22fb0c07158720c667515969804e4e981f | [
"if not isinstance(message, Message):\n raise TypeError('`{}` is not a message'.format(str(type(message))))\nserialized_message = [encode_message(message)]\nif response_to is not None and response_to.identity != '':\n serialized_message = [response_to.identity] + serialized_message\ntry:\n await socket.sen... | <|body_start_0|>
if not isinstance(message, Message):
raise TypeError('`{}` is not a message'.format(str(type(message))))
serialized_message = [encode_message(message)]
if response_to is not None and response_to.identity != '':
serialized_message = [response_to.identity] ... | Static helper class for sending and receiving messages through zmq sockets. | Messenger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Messenger:
"""Static helper class for sending and receiving messages through zmq sockets."""
async def send(socket: zmq.asyncio.Socket, message: Message, response_to: Optional[Message]=None) -> None:
"""Encode given message and send it to the given socket. :param socket: socket to se... | stack_v2_sparse_classes_36k_train_009135 | 3,056 | permissive | [
{
"docstring": "Encode given message and send it to the given socket. :param socket: socket to send the message to :param message: message to be send :param response_to: optional message to respond to :raise MessengerError: if it fails :raise UnknownMessageTypeError: if the message to be send is of unknown type... | 2 | stack_v2_sparse_classes_30k_train_011255 | Implement the Python class `Messenger` described below.
Class description:
Static helper class for sending and receiving messages through zmq sockets.
Method signatures and docstrings:
- async def send(socket: zmq.asyncio.Socket, message: Message, response_to: Optional[Message]=None) -> None: Encode given message and... | Implement the Python class `Messenger` described below.
Class description:
Static helper class for sending and receiving messages through zmq sockets.
Method signatures and docstrings:
- async def send(socket: zmq.asyncio.Socket, message: Message, response_to: Optional[Message]=None) -> None: Encode given message and... | 0847c9885584378dd68a48c40d03f9bb02b2b57c | <|skeleton|>
class Messenger:
"""Static helper class for sending and receiving messages through zmq sockets."""
async def send(socket: zmq.asyncio.Socket, message: Message, response_to: Optional[Message]=None) -> None:
"""Encode given message and send it to the given socket. :param socket: socket to se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Messenger:
"""Static helper class for sending and receiving messages through zmq sockets."""
async def send(socket: zmq.asyncio.Socket, message: Message, response_to: Optional[Message]=None) -> None:
"""Encode given message and send it to the given socket. :param socket: socket to send the messag... | the_stack_v2_python_sparse | shepherd/comm/messenger.py | iterait/shepherd | train | 6 |
27e2db0f96453751978fe2b1455273cfe2e8b1f6 | [
"add_input_output_information(self, input_names, output_name, output_shape)\nself.bias = np.ascontiguousarray(bias, dtype=np.double)\nself.is_minuend = is_minuend",
"offset, old_length = self.abstract_information\nelement = ffn_sub_bias_zono(man, True, element, offset, self.bias, self.is_minuend, old_length)\nadd... | <|body_start_0|>
add_input_output_information(self, input_names, output_name, output_shape)
self.bias = np.ascontiguousarray(bias, dtype=np.double)
self.is_minuend = is_minuend
<|end_body_0|>
<|body_start_1|>
offset, old_length = self.abstract_information
element = ffn_sub_bias_... | DeepzonoSub | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepzonoSub:
def __init__(self, bias, is_minuend, input_names, output_name, output_shape):
"""Arguments --------- bias : numpy.ndarray the values of the first addend input_names : iterable iterable with the name of the second addend output_name : str name of this node's output output_sha... | stack_v2_sparse_classes_36k_train_009136 | 34,420 | permissive | [
{
"docstring": "Arguments --------- bias : numpy.ndarray the values of the first addend input_names : iterable iterable with the name of the second addend output_name : str name of this node's output output_shape : iterable iterable of ints with the shape of the output of this node",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_007600 | Implement the Python class `DeepzonoSub` described below.
Class description:
Implement the DeepzonoSub class.
Method signatures and docstrings:
- def __init__(self, bias, is_minuend, input_names, output_name, output_shape): Arguments --------- bias : numpy.ndarray the values of the first addend input_names : iterable... | Implement the Python class `DeepzonoSub` described below.
Class description:
Implement the DeepzonoSub class.
Method signatures and docstrings:
- def __init__(self, bias, is_minuend, input_names, output_name, output_shape): Arguments --------- bias : numpy.ndarray the values of the first addend input_names : iterable... | 8771d3158b2c64a360d5bdfd4433490863257dd6 | <|skeleton|>
class DeepzonoSub:
def __init__(self, bias, is_minuend, input_names, output_name, output_shape):
"""Arguments --------- bias : numpy.ndarray the values of the first addend input_names : iterable iterable with the name of the second addend output_name : str name of this node's output output_sha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepzonoSub:
def __init__(self, bias, is_minuend, input_names, output_name, output_shape):
"""Arguments --------- bias : numpy.ndarray the values of the first addend input_names : iterable iterable with the name of the second addend output_name : str name of this node's output output_shape : iterable ... | the_stack_v2_python_sparse | tf_verify/deepzono_nodes.py | eth-sri/eran | train | 306 | |
7206e842d94c92cdf7ea889171d61692c53c469d | [
"from models import Proyecto, User, users\nproyecto = Proyecto.query.filter(Proyecto.nombre == proyectoNombre).first_or_404()\nusuario = User.query.filter(User.name == userName).first_or_404()\nproyecto.users.append(usuario)\ndb.session.commit()",
"from models import Proyecto, User, users\nproyecto = Proyecto.que... | <|body_start_0|>
from models import Proyecto, User, users
proyecto = Proyecto.query.filter(Proyecto.nombre == proyectoNombre).first_or_404()
usuario = User.query.filter(User.name == userName).first_or_404()
proyecto.users.append(usuario)
db.session.commit()
<|end_body_0|>
<|body... | MgrProyectoXUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MgrProyectoXUser:
def guardar(self, proyectoNombre, userName):
"""asigna a un proyecto un usuario"""
<|body_0|>
def borrar(self, proyectoNombre, userName):
"""deasigna a un proyecto un usuario"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from mod... | stack_v2_sparse_classes_36k_train_009137 | 837 | no_license | [
{
"docstring": "asigna a un proyecto un usuario",
"name": "guardar",
"signature": "def guardar(self, proyectoNombre, userName)"
},
{
"docstring": "deasigna a un proyecto un usuario",
"name": "borrar",
"signature": "def borrar(self, proyectoNombre, userName)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002927 | Implement the Python class `MgrProyectoXUser` described below.
Class description:
Implement the MgrProyectoXUser class.
Method signatures and docstrings:
- def guardar(self, proyectoNombre, userName): asigna a un proyecto un usuario
- def borrar(self, proyectoNombre, userName): deasigna a un proyecto un usuario | Implement the Python class `MgrProyectoXUser` described below.
Class description:
Implement the MgrProyectoXUser class.
Method signatures and docstrings:
- def guardar(self, proyectoNombre, userName): asigna a un proyecto un usuario
- def borrar(self, proyectoNombre, userName): deasigna a un proyecto un usuario
<|sk... | da5330f318698f86af12c3c91cb3f1524540f4ca | <|skeleton|>
class MgrProyectoXUser:
def guardar(self, proyectoNombre, userName):
"""asigna a un proyecto un usuario"""
<|body_0|>
def borrar(self, proyectoNombre, userName):
"""deasigna a un proyecto un usuario"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MgrProyectoXUser:
def guardar(self, proyectoNombre, userName):
"""asigna a un proyecto un usuario"""
from models import Proyecto, User, users
proyecto = Proyecto.query.filter(Proyecto.nombre == proyectoNombre).first_or_404()
usuario = User.query.filter(User.name == userName).fi... | the_stack_v2_python_sparse | src/mgrProyectoXUser.py | frvc123/proyecto-sicp | train | 0 | |
e7fd4a0f2325d451914d8481238c7d5cef58f1e0 | [
"super(Range, self).__init__()\nif field_name:\n self.add_field(field_name, args)",
"if args is None:\n args = {}\nreturn self.set_param(field_name, args)"
] | <|body_start_0|>
super(Range, self).__init__()
if field_name:
self.add_field(field_name, args)
<|end_body_0|>
<|body_start_1|>
if args is None:
args = {}
return self.set_param(field_name, args)
<|end_body_1|>
| @see: http://www.elasticsearch.org/guide/reference/query-dsl/range-query/ | Range | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Range:
"""@see: http://www.elasticsearch.org/guide/reference/query-dsl/range-query/"""
def __init__(self, field_name=None, args=None):
"""@param field_name: @type field_name: str @param args: @type args: dict"""
<|body_0|>
def add_field(self, field_name, args=None):
... | stack_v2_sparse_classes_36k_train_009138 | 819 | permissive | [
{
"docstring": "@param field_name: @type field_name: str @param args: @type args: dict",
"name": "__init__",
"signature": "def __init__(self, field_name=None, args=None)"
},
{
"docstring": "Add a range field to the query @param field_name: @type field_name: str @param args: @type args: dict @ret... | 2 | null | Implement the Python class `Range` described below.
Class description:
@see: http://www.elasticsearch.org/guide/reference/query-dsl/range-query/
Method signatures and docstrings:
- def __init__(self, field_name=None, args=None): @param field_name: @type field_name: str @param args: @type args: dict
- def add_field(se... | Implement the Python class `Range` described below.
Class description:
@see: http://www.elasticsearch.org/guide/reference/query-dsl/range-query/
Method signatures and docstrings:
- def __init__(self, field_name=None, args=None): @param field_name: @type field_name: str @param args: @type args: dict
- def add_field(se... | 0fbf68ed3e17d665e3cdf1913444ebf1f72693dd | <|skeleton|>
class Range:
"""@see: http://www.elasticsearch.org/guide/reference/query-dsl/range-query/"""
def __init__(self, field_name=None, args=None):
"""@param field_name: @type field_name: str @param args: @type args: dict"""
<|body_0|>
def add_field(self, field_name, args=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Range:
"""@see: http://www.elasticsearch.org/guide/reference/query-dsl/range-query/"""
def __init__(self, field_name=None, args=None):
"""@param field_name: @type field_name: str @param args: @type args: dict"""
super(Range, self).__init__()
if field_name:
self.add_fie... | the_stack_v2_python_sparse | pylastica/query/range.py | jlinn/pylastica | train | 5 |
1623508708711a8ade6ef3692c872a24fe6d052d | [
"exprval = self.term()\nwhile self._accept('PLUS') or self._accept('MINUS'):\n op = self.tok.type\n right = self.term()\n if op == 'PLUS':\n exprval = ('+', exprval, right)\n elif op == 'MINUS':\n exprval = ('-', exprval, right)\nreturn exprval",
"termval = self.factor()\nwhile self._acc... | <|body_start_0|>
exprval = self.term()
while self._accept('PLUS') or self._accept('MINUS'):
op = self.tok.type
right = self.term()
if op == 'PLUS':
exprval = ('+', exprval, right)
elif op == 'MINUS':
exprval = ('-', exprval,... | ExpressionTreeBuilder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpressionTreeBuilder:
def expr(self):
"""expression ::= term { ('+'|'-') term }"""
<|body_0|>
def term(self):
"""term ::= factor { ('*'|'/') factor }*"""
<|body_1|>
def factor(self):
"""factor ::= NUM | ( expr )"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k_train_009139 | 9,547 | no_license | [
{
"docstring": "expression ::= term { ('+'|'-') term }",
"name": "expr",
"signature": "def expr(self)"
},
{
"docstring": "term ::= factor { ('*'|'/') factor }*",
"name": "term",
"signature": "def term(self)"
},
{
"docstring": "factor ::= NUM | ( expr )",
"name": "factor",
... | 3 | null | Implement the Python class `ExpressionTreeBuilder` described below.
Class description:
Implement the ExpressionTreeBuilder class.
Method signatures and docstrings:
- def expr(self): expression ::= term { ('+'|'-') term }
- def term(self): term ::= factor { ('*'|'/') factor }*
- def factor(self): factor ::= NUM | ( ex... | Implement the Python class `ExpressionTreeBuilder` described below.
Class description:
Implement the ExpressionTreeBuilder class.
Method signatures and docstrings:
- def expr(self): expression ::= term { ('+'|'-') term }
- def term(self): term ::= factor { ('*'|'/') factor }*
- def factor(self): factor ::= NUM | ( ex... | 632a54124c6a15103f6773cbb3668bf67c72993f | <|skeleton|>
class ExpressionTreeBuilder:
def expr(self):
"""expression ::= term { ('+'|'-') term }"""
<|body_0|>
def term(self):
"""term ::= factor { ('*'|'/') factor }*"""
<|body_1|>
def factor(self):
"""factor ::= NUM | ( expr )"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExpressionTreeBuilder:
def expr(self):
"""expression ::= term { ('+'|'-') term }"""
exprval = self.term()
while self._accept('PLUS') or self._accept('MINUS'):
op = self.tok.type
right = self.term()
if op == 'PLUS':
exprval = ('+', exp... | the_stack_v2_python_sparse | Chapter 2: Strings and Text/2.19.writing_a_simple_recursive_descent_parser.py | fluency03/Python-Cookbook | train | 2 | |
a6ca4fae47d954ed846d3246afef26febbf8fe90 | [
"H = self.units\nassert isinstance(input_shape, list)\nnb_inputs = len(input_shape)\nassert nb_inputs >= 2\nassert len(input_shape[0]) == 3\nB, P, H_ = input_shape[0]\nassert H_ == 2 * H\nassert len(input_shape[1]) == 3\nB, Q, H_ = input_shape[1]\nassert H_ == 2 * H\nself.input_spec = [None]\nsuper(QuestionAttnGRU,... | <|body_start_0|>
H = self.units
assert isinstance(input_shape, list)
nb_inputs = len(input_shape)
assert nb_inputs >= 2
assert len(input_shape[0]) == 3
B, P, H_ = input_shape[0]
assert H_ == 2 * H
assert len(input_shape[1]) == 3
B, Q, H_ = input_sh... | Class implementing attention mechanism, to get the relevance/importance of one tensor on other. Used to obtain question-aware representation of the passage, i.e. importance of each word in the question w.r.t passage. | QuestionAttnGRU | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionAttnGRU:
"""Class implementing attention mechanism, to get the relevance/importance of one tensor on other. Used to obtain question-aware representation of the passage, i.e. importance of each word in the question w.r.t passage."""
def build(self, input_shape):
"""Creates the... | stack_v2_sparse_classes_36k_train_009140 | 2,239 | permissive | [
{
"docstring": "Creates the layer weights. Must be implemented on all layers that have weights. # Arguments input_shape: Keras tensor (future input to layer) or list/tuple of Keras tensors to reference for weight shape computations",
"name": "build",
"signature": "def build(self, input_shape)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_001905 | Implement the Python class `QuestionAttnGRU` described below.
Class description:
Class implementing attention mechanism, to get the relevance/importance of one tensor on other. Used to obtain question-aware representation of the passage, i.e. importance of each word in the question w.r.t passage.
Method signatures an... | Implement the Python class `QuestionAttnGRU` described below.
Class description:
Class implementing attention mechanism, to get the relevance/importance of one tensor on other. Used to obtain question-aware representation of the passage, i.e. importance of each word in the question w.r.t passage.
Method signatures an... | 34dca815e9f4b7a9def0d4d9292f7a409515cac9 | <|skeleton|>
class QuestionAttnGRU:
"""Class implementing attention mechanism, to get the relevance/importance of one tensor on other. Used to obtain question-aware representation of the passage, i.e. importance of each word in the question w.r.t passage."""
def build(self, input_shape):
"""Creates the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionAttnGRU:
"""Class implementing attention mechanism, to get the relevance/importance of one tensor on other. Used to obtain question-aware representation of the passage, i.e. importance of each word in the question w.r.t passage."""
def build(self, input_shape):
"""Creates the layer weight... | the_stack_v2_python_sparse | layers/QuestionAttnGRU.py | halloTheCoder/RNet-Keras | train | 2 |
24946af70bd19f4df06148cc31a255e1e471b47b | [
"if not kwargs.get('obj_ids'):\n obj_model = facade.get_route_map_entry_by_search(self.search)\n objects = obj_model['query_set']\n only_main_property = False\nelse:\n ids = kwargs.get('obj_ids').split(';')\n objects = facade.get_route_map_entry_by_ids(ids)\n only_main_property = True\n obj_mod... | <|body_start_0|>
if not kwargs.get('obj_ids'):
obj_model = facade.get_route_map_entry_by_search(self.search)
objects = obj_model['query_set']
only_main_property = False
else:
ids = kwargs.get('obj_ids').split(';')
objects = facade.get_route_map... | RouteMapView | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RouteMapView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMapEntries by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new RouteMapEntry."""
<|body_1|>
def put(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_36k_train_009141 | 9,414 | permissive | [
{
"docstring": "Returns a list of RouteMapEntries by ids ou dict.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Create new RouteMapEntry.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Upda... | 4 | stack_v2_sparse_classes_30k_train_004713 | Implement the Python class `RouteMapView` described below.
Class description:
Implement the RouteMapView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of RouteMapEntries by ids ou dict.
- def post(self, request, *args, **kwargs): Create new RouteMapEntry.
- def put... | Implement the Python class `RouteMapView` described below.
Class description:
Implement the RouteMapView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of RouteMapEntries by ids ou dict.
- def post(self, request, *args, **kwargs): Create new RouteMapEntry.
- def put... | eb27e1d977a1c4bb1fee8fb51b8d8050c64696d9 | <|skeleton|>
class RouteMapView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMapEntries by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new RouteMapEntry."""
<|body_1|>
def put(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RouteMapView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMapEntries by ids ou dict."""
if not kwargs.get('obj_ids'):
obj_model = facade.get_route_map_entry_by_search(self.search)
objects = obj_model['query_set']
only_main_property = F... | the_stack_v2_python_sparse | networkapi/api_route_map/v4/views.py | globocom/GloboNetworkAPI | train | 86 | |
6aab3c8814403e4bc542411b40b7f20bdb7ab0bb | [
"self.login()\nresponse = self.api_response(expected_response_code=302, api_version=api_version)\nassert self.username in response['location']",
"self.login()\nself.user.refresh_from_db()\nlast_login_before = self.user.last_login\nself.api_response(expected_response_code=302, api_version=api_version)\nself.user.r... | <|body_start_0|>
self.login()
response = self.api_response(expected_response_code=302, api_version=api_version)
assert self.username in response['location']
<|end_body_0|>
<|body_start_1|>
self.login()
self.user.refresh_from_db()
last_login_before = self.user.last_login
... | Tests for /api/mobile/{api_version}/my_user_info | TestUserInfoApi | [
"MIT",
"AGPL-3.0-only",
"AGPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUserInfoApi:
"""Tests for /api/mobile/{api_version}/my_user_info"""
def test_success(self, api_version):
"""Verify the endpoint redirects to the user detail endpoint"""
<|body_0|>
def test_last_loggedin_updated(self, api_version):
"""Verify that a user's last... | stack_v2_sparse_classes_36k_train_009142 | 26,573 | permissive | [
{
"docstring": "Verify the endpoint redirects to the user detail endpoint",
"name": "test_success",
"signature": "def test_success(self, api_version)"
},
{
"docstring": "Verify that a user's last logged in value updates after hitting the my_user_info endpoint",
"name": "test_last_loggedin_up... | 2 | null | Implement the Python class `TestUserInfoApi` described below.
Class description:
Tests for /api/mobile/{api_version}/my_user_info
Method signatures and docstrings:
- def test_success(self, api_version): Verify the endpoint redirects to the user detail endpoint
- def test_last_loggedin_updated(self, api_version): Veri... | Implement the Python class `TestUserInfoApi` described below.
Class description:
Tests for /api/mobile/{api_version}/my_user_info
Method signatures and docstrings:
- def test_success(self, api_version): Verify the endpoint redirects to the user detail endpoint
- def test_last_loggedin_updated(self, api_version): Veri... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class TestUserInfoApi:
"""Tests for /api/mobile/{api_version}/my_user_info"""
def test_success(self, api_version):
"""Verify the endpoint redirects to the user detail endpoint"""
<|body_0|>
def test_last_loggedin_updated(self, api_version):
"""Verify that a user's last... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestUserInfoApi:
"""Tests for /api/mobile/{api_version}/my_user_info"""
def test_success(self, api_version):
"""Verify the endpoint redirects to the user detail endpoint"""
self.login()
response = self.api_response(expected_response_code=302, api_version=api_version)
asser... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/mobile_api/users/tests.py | luque/better-ways-of-thinking-about-software | train | 3 |
bb1908e455736d5f2dc4491ee0dcf4c856a5191d | [
"self._attribute_groep_id: int = attribute_groep_id\n'\\n Het ID van deze attribuutgroep.\\n '\nself._aantal_voorwaarden_voor_true: int = aantal_voorwaarden_voor_true\n'\\n Het minimale aantal voorwaarden waaraan moet worden voldaan om deze attribuutgroep te laten vuren.\\n '\nself._kopp... | <|body_start_0|>
self._attribute_groep_id: int = attribute_groep_id
'\n Het ID van deze attribuutgroep.\n '
self._aantal_voorwaarden_voor_true: int = aantal_voorwaarden_voor_true
'\n Het minimale aantal voorwaarden waaraan moet worden voldaan om deze attribuutgroep t... | Klasse voor attribuutgroep. | AttribuutGroep | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttribuutGroep:
"""Klasse voor attribuutgroep."""
def __init__(self, attribute_groep_id: int, aantal_voorwaarden_voor_true: int, koppelingen: List[AttribuutGroepKoppeling]):
"""Object constructor. :param int attribute_groep_id: Het ID van deze attribuutgroep. :param int aantal_voorwa... | stack_v2_sparse_classes_36k_train_009143 | 2,059 | permissive | [
{
"docstring": "Object constructor. :param int attribute_groep_id: Het ID van deze attribuutgroep. :param int aantal_voorwaarden_voor_true: Het minimale aantal voorwaarden waaraan moet worden voldaan. :param list[kerapu.boom.attribuut_groep_koppeling.AttribuutGroepKoppeling.AttribuutGroepKoppeling] koppelingen:... | 2 | stack_v2_sparse_classes_30k_val_001192 | Implement the Python class `AttribuutGroep` described below.
Class description:
Klasse voor attribuutgroep.
Method signatures and docstrings:
- def __init__(self, attribute_groep_id: int, aantal_voorwaarden_voor_true: int, koppelingen: List[AttribuutGroepKoppeling]): Object constructor. :param int attribute_groep_id:... | Implement the Python class `AttribuutGroep` described below.
Class description:
Klasse voor attribuutgroep.
Method signatures and docstrings:
- def __init__(self, attribute_groep_id: int, aantal_voorwaarden_voor_true: int, koppelingen: List[AttribuutGroepKoppeling]): Object constructor. :param int attribute_groep_id:... | fdae5ce96e9c79bf0d325c488077436fa31ad03f | <|skeleton|>
class AttribuutGroep:
"""Klasse voor attribuutgroep."""
def __init__(self, attribute_groep_id: int, aantal_voorwaarden_voor_true: int, koppelingen: List[AttribuutGroepKoppeling]):
"""Object constructor. :param int attribute_groep_id: Het ID van deze attribuutgroep. :param int aantal_voorwa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttribuutGroep:
"""Klasse voor attribuutgroep."""
def __init__(self, attribute_groep_id: int, aantal_voorwaarden_voor_true: int, koppelingen: List[AttribuutGroepKoppeling]):
"""Object constructor. :param int attribute_groep_id: Het ID van deze attribuutgroep. :param int aantal_voorwaarden_voor_tr... | the_stack_v2_python_sparse | kerapu/boom/AttribuutGroep.py | SetBased/py-kerapu | train | 5 |
9566707095fed517fb2e60767227fc540e48e93d | [
"try:\n responseData = User.fetchAll()\n if len(responseData) > 0:\n response = jsonify(responseData)\n else:\n response = jsonify()\n return make_response(response, 200)\nexcept:\n handle400error(users_ns, 'Invalid username')\nreturn handle500error(users_ns)",
"args = update_user_arg... | <|body_start_0|>
try:
responseData = User.fetchAll()
if len(responseData) > 0:
response = jsonify(responseData)
else:
response = jsonify()
return make_response(response, 200)
except:
handle400error(users_ns, 'Inv... | UserCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCollection:
def get(self, username):
"""Gets all users"""
<|body_0|>
def put(self, username):
"""Updates data and password of a user"""
<|body_1|>
def delete(self, username):
"""Deletes a user"""
<|body_2|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_009144 | 8,609 | no_license | [
{
"docstring": "Gets all users",
"name": "get",
"signature": "def get(self, username)"
},
{
"docstring": "Updates data and password of a user",
"name": "put",
"signature": "def put(self, username)"
},
{
"docstring": "Deletes a user",
"name": "delete",
"signature": "def de... | 3 | stack_v2_sparse_classes_30k_train_013009 | Implement the Python class `UserCollection` described below.
Class description:
Implement the UserCollection class.
Method signatures and docstrings:
- def get(self, username): Gets all users
- def put(self, username): Updates data and password of a user
- def delete(self, username): Deletes a user | Implement the Python class `UserCollection` described below.
Class description:
Implement the UserCollection class.
Method signatures and docstrings:
- def get(self, username): Gets all users
- def put(self, username): Updates data and password of a user
- def delete(self, username): Deletes a user
<|skeleton|>
clas... | 72ba34ce64482da23020d84a41819b889dad51f1 | <|skeleton|>
class UserCollection:
def get(self, username):
"""Gets all users"""
<|body_0|>
def put(self, username):
"""Updates data and password of a user"""
<|body_1|>
def delete(self, username):
"""Deletes a user"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserCollection:
def get(self, username):
"""Gets all users"""
try:
responseData = User.fetchAll()
if len(responseData) > 0:
response = jsonify(responseData)
else:
response = jsonify()
return make_response(response,... | the_stack_v2_python_sparse | WakeOnLan-server/flask/api/namespaces/users_ns.py | DarioGar/WakeOnLan | train | 0 | |
eefbc01f811186f60e68f1e5353594542ce281ab | [
"try:\n response = requests.get(url='http://tunnel-api.apeyun.com/q', params=ApeProxyManager.params, headers={'Content-Type': 'text/plain; charset=utf-8'})\n if response.status_code == 200:\n res = json.loads(response.text)\n if res['code'] == 200:\n data = res['data']\n cl... | <|body_start_0|>
try:
response = requests.get(url='http://tunnel-api.apeyun.com/q', params=ApeProxyManager.params, headers={'Content-Type': 'text/plain; charset=utf-8'})
if response.status_code == 200:
res = json.loads(response.text)
if res['code'] == 200:... | ApeProxyManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApeProxyManager:
def getProxiesDicts(cls):
"""一次性获取多个代理 :return:"""
<|body_0|>
def getProxy(cls):
"""获取一个代理 :return:"""
<|body_1|>
def proxyDict2String(cls, proxy):
"""将字典形式的代理转化为http://ip:port形式 :param proxy: :return:"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_009145 | 5,542 | no_license | [
{
"docstring": "一次性获取多个代理 :return:",
"name": "getProxiesDicts",
"signature": "def getProxiesDicts(cls)"
},
{
"docstring": "获取一个代理 :return:",
"name": "getProxy",
"signature": "def getProxy(cls)"
},
{
"docstring": "将字典形式的代理转化为http://ip:port形式 :param proxy: :return:",
"name": "p... | 4 | stack_v2_sparse_classes_30k_train_011762 | Implement the Python class `ApeProxyManager` described below.
Class description:
Implement the ApeProxyManager class.
Method signatures and docstrings:
- def getProxiesDicts(cls): 一次性获取多个代理 :return:
- def getProxy(cls): 获取一个代理 :return:
- def proxyDict2String(cls, proxy): 将字典形式的代理转化为http://ip:port形式 :param proxy: :ret... | Implement the Python class `ApeProxyManager` described below.
Class description:
Implement the ApeProxyManager class.
Method signatures and docstrings:
- def getProxiesDicts(cls): 一次性获取多个代理 :return:
- def getProxy(cls): 获取一个代理 :return:
- def proxyDict2String(cls, proxy): 将字典形式的代理转化为http://ip:port形式 :param proxy: :ret... | 3898125fa65ca045e7c203a18e7a1129b9ce5988 | <|skeleton|>
class ApeProxyManager:
def getProxiesDicts(cls):
"""一次性获取多个代理 :return:"""
<|body_0|>
def getProxy(cls):
"""获取一个代理 :return:"""
<|body_1|>
def proxyDict2String(cls, proxy):
"""将字典形式的代理转化为http://ip:port形式 :param proxy: :return:"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApeProxyManager:
def getProxiesDicts(cls):
"""一次性获取多个代理 :return:"""
try:
response = requests.get(url='http://tunnel-api.apeyun.com/q', params=ApeProxyManager.params, headers={'Content-Type': 'text/plain; charset=utf-8'})
if response.status_code == 200:
r... | the_stack_v2_python_sparse | CnkiSpider/proxy.py | konwa/CnkiSpider | train | 0 | |
3130044e1e2f5f797c887c854d4b545ce5427899 | [
"self.stats = stats\nself.vid_h = vid_h\nself.vid_w = vid_w",
"root_area = np.sqrt(float(det['w']) * float(det['h']))\ndist = float(det['center_x'])\ndist = min(self.vid_w - float(det['center_x']), dist)\ndist = min(float(det['center_y']), dist)\ndist = min(self.vid_h - float(det['center_y']), dist)\nprob = float... | <|body_start_0|>
self.stats = stats
self.vid_h = vid_h
self.vid_w = vid_w
<|end_body_0|>
<|body_start_1|>
root_area = np.sqrt(float(det['w']) * float(det['h']))
dist = float(det['center_x'])
dist = min(self.vid_w - float(det['center_x']), dist)
dist = min(float(d... | Functor for extracting init features from a detection. | InitFeatureExtractor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InitFeatureExtractor:
"""Functor for extracting init features from a detection."""
def __init__(self, stats, vid_h, vid_w):
"""Constructor. Inputs: stats -- Feature stats dict. vid_h -- Height of video. vid_w -- Width of video."""
<|body_0|>
def __call__(self, det):
... | stack_v2_sparse_classes_36k_train_009146 | 1,205 | permissive | [
{
"docstring": "Constructor. Inputs: stats -- Feature stats dict. vid_h -- Height of video. vid_w -- Width of video.",
"name": "__init__",
"signature": "def __init__(self, stats, vid_h, vid_w)"
},
{
"docstring": "Extracts init features from a detection. Inputs: det -- Current detection.",
"n... | 2 | stack_v2_sparse_classes_30k_train_021511 | Implement the Python class `InitFeatureExtractor` described below.
Class description:
Functor for extracting init features from a detection.
Method signatures and docstrings:
- def __init__(self, stats, vid_h, vid_w): Constructor. Inputs: stats -- Feature stats dict. vid_h -- Height of video. vid_w -- Width of video.... | Implement the Python class `InitFeatureExtractor` described below.
Class description:
Functor for extracting init features from a detection.
Method signatures and docstrings:
- def __init__(self, stats, vid_h, vid_w): Constructor. Inputs: stats -- Feature stats dict. vid_h -- Height of video. vid_w -- Width of video.... | fae655f396380dbe74413812a41b734e267faffe | <|skeleton|>
class InitFeatureExtractor:
"""Functor for extracting init features from a detection."""
def __init__(self, stats, vid_h, vid_w):
"""Constructor. Inputs: stats -- Feature stats dict. vid_h -- Height of video. vid_w -- Width of video."""
<|body_0|>
def __call__(self, det):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InitFeatureExtractor:
"""Functor for extracting init features from a detection."""
def __init__(self, stats, vid_h, vid_w):
"""Constructor. Inputs: stats -- Feature stats dict. vid_h -- Height of video. vid_w -- Width of video."""
self.stats = stats
self.vid_h = vid_h
self... | the_stack_v2_python_sparse | train/siamese/extractors/init_feature_extractor.py | openem-team/openem | train | 11 |
06c04b422eee36009c6b9c7c408104f89dca00b3 | [
"changed = False\nif options.delay is not None and 0 <= options.delay != self.delay:\n self.delay = options.delay\n changed = True\nif options.bandwidth is not None and 0 <= options.bandwidth != self.bandwidth:\n self.bandwidth = options.bandwidth\n changed = True\nif options.loss is not None and 0 <= o... | <|body_start_0|>
changed = False
if options.delay is not None and 0 <= options.delay != self.delay:
self.delay = options.delay
changed = True
if options.bandwidth is not None and 0 <= options.bandwidth != self.bandwidth:
self.bandwidth = options.bandwidth
... | Options for creating and updating links within core. | LinkOptions | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkOptions:
"""Options for creating and updating links within core."""
def update(self, options: 'LinkOptions') -> bool:
"""Updates current options with values from other options. :param options: options to update with :return: True if any value has changed, False otherwise"""
... | stack_v2_sparse_classes_36k_train_009147 | 9,883 | permissive | [
{
"docstring": "Updates current options with values from other options. :param options: options to update with :return: True if any value has changed, False otherwise",
"name": "update",
"signature": "def update(self, options: 'LinkOptions') -> bool"
},
{
"docstring": "Checks if the current opti... | 3 | stack_v2_sparse_classes_30k_train_002248 | Implement the Python class `LinkOptions` described below.
Class description:
Options for creating and updating links within core.
Method signatures and docstrings:
- def update(self, options: 'LinkOptions') -> bool: Updates current options with values from other options. :param options: options to update with :return... | Implement the Python class `LinkOptions` described below.
Class description:
Options for creating and updating links within core.
Method signatures and docstrings:
- def update(self, options: 'LinkOptions') -> bool: Updates current options with values from other options. :param options: options to update with :return... | 20071eed2e73a2287aa385698dd604f4933ae7ff | <|skeleton|>
class LinkOptions:
"""Options for creating and updating links within core."""
def update(self, options: 'LinkOptions') -> bool:
"""Updates current options with values from other options. :param options: options to update with :return: True if any value has changed, False otherwise"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkOptions:
"""Options for creating and updating links within core."""
def update(self, options: 'LinkOptions') -> bool:
"""Updates current options with values from other options. :param options: options to update with :return: True if any value has changed, False otherwise"""
changed = ... | the_stack_v2_python_sparse | daemon/core/emulator/data.py | coreemu/core | train | 606 |
8329331e3d92774f342a700b54c3c9d222a28f29 | [
"self.set_func = set_func\nself.index = index\nsuper(Pixel, self).__init__(**kwargs)",
"if key == 'color':\n self.set_func(self.index, value)\nsuper(Pixel, self).__setitem__(key, value)"
] | <|body_start_0|>
self.set_func = set_func
self.index = index
super(Pixel, self).__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
if key == 'color':
self.set_func(self.index, value)
super(Pixel, self).__setitem__(key, value)
<|end_body_1|>
| Pixel class to store information about a pixel | Pixel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pixel:
"""Pixel class to store information about a pixel"""
def __init__(self, index, set_func, **kwargs):
"""Save set function and index :param index: int, pixel index in the strip :param set_func: function, handler function to set color"""
<|body_0|>
def __setitem__(se... | stack_v2_sparse_classes_36k_train_009148 | 716 | no_license | [
{
"docstring": "Save set function and index :param index: int, pixel index in the strip :param set_func: function, handler function to set color",
"name": "__init__",
"signature": "def __init__(self, index, set_func, **kwargs)"
},
{
"docstring": "Override set item to call set function first",
... | 2 | stack_v2_sparse_classes_30k_train_004909 | Implement the Python class `Pixel` described below.
Class description:
Pixel class to store information about a pixel
Method signatures and docstrings:
- def __init__(self, index, set_func, **kwargs): Save set function and index :param index: int, pixel index in the strip :param set_func: function, handler function t... | Implement the Python class `Pixel` described below.
Class description:
Pixel class to store information about a pixel
Method signatures and docstrings:
- def __init__(self, index, set_func, **kwargs): Save set function and index :param index: int, pixel index in the strip :param set_func: function, handler function t... | 809aef0d46966e2cd761673d4556912a23f3a2a3 | <|skeleton|>
class Pixel:
"""Pixel class to store information about a pixel"""
def __init__(self, index, set_func, **kwargs):
"""Save set function and index :param index: int, pixel index in the strip :param set_func: function, handler function to set color"""
<|body_0|>
def __setitem__(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pixel:
"""Pixel class to store information about a pixel"""
def __init__(self, index, set_func, **kwargs):
"""Save set function and index :param index: int, pixel index in the strip :param set_func: function, handler function to set color"""
self.set_func = set_func
self.index = i... | the_stack_v2_python_sparse | src/utils/pixels.py | stacywebb/ledypi | train | 0 |
eefa0595bf53ce622f056160afc825d54eb74298 | [
"assert next is Node.empty or isinstance(next, Node)\nself.item = item\nself.next = next",
"if self.next:\n next_str = ', ' + repr(self.next)\nelse:\n next_str = ''\nreturn 'StackNode({0}{1})'.format(self.item, next_str)"
] | <|body_start_0|>
assert next is Node.empty or isinstance(next, Node)
self.item = item
self.next = next
<|end_body_0|>
<|body_start_1|>
if self.next:
next_str = ', ' + repr(self.next)
else:
next_str = ''
return 'StackNode({0}{1})'.format(self.item,... | Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
def __init__(self, item, next=empty):
"""init a node"""
<|body_0|>
def __repr__(self):
"""它实现Node类的repr()函数"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
assert next is Node.empty or isinstance(next, Node)
self.item = item
se... | stack_v2_sparse_classes_36k_train_009149 | 1,916 | no_license | [
{
"docstring": "init a node",
"name": "__init__",
"signature": "def __init__(self, item, next=empty)"
},
{
"docstring": "它实现Node类的repr()函数",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | null | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, item, next=empty): init a node
- def __repr__(self): 它实现Node类的repr()函数 | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, item, next=empty): init a node
- def __repr__(self): 它实现Node类的repr()函数
<|skeleton|>
class Node:
def __init__(self, item, next=empty):
"""init a node"""
... | c431569ae08fb77c67e948f5ded75c306af20ba2 | <|skeleton|>
class Node:
def __init__(self, item, next=empty):
"""init a node"""
<|body_0|>
def __repr__(self):
"""它实现Node类的repr()函数"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Node:
def __init__(self, item, next=empty):
"""init a node"""
assert next is Node.empty or isinstance(next, Node)
self.item = item
self.next = next
def __repr__(self):
"""它实现Node类的repr()函数"""
if self.next:
next_str = ', ' + repr(self.next)
... | the_stack_v2_python_sparse | algo-lib/1_basic/Python/dep/Queue-LinkedList.py | itrowa/arsenal | train | 0 | |
cc65871d127c4b6724dff20c675b187c81eb99c4 | [
"self.canvas = canvas\nself.fileName = fileName\nself.name = name\nself.suffix = suffix\nmenu.add_command(label=settings.getEachWordCapitalized(self.name), command=self.display)",
"for repositoryDialog in settings.globalRepositoryDialogListTable:\n if repositoryDialog.repository.lowerName == self.name:\n ... | <|body_start_0|>
self.canvas = canvas
self.fileName = fileName
self.name = name
self.suffix = suffix
menu.add_command(label=settings.getEachWordCapitalized(self.name), command=self.display)
<|end_body_0|>
<|body_start_1|>
for repositoryDialog in settings.globalRepository... | A class to display the export canvas repository dialog. | ExportCanvasDialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExportCanvasDialog:
"""A class to display the export canvas repository dialog."""
def addPluginToMenu(self, canvas, fileName, menu, name, suffix):
"""Add the display command to the menu."""
<|body_0|>
def display(self):
"""Display the export canvas repository dia... | stack_v2_sparse_classes_36k_train_009150 | 33,354 | no_license | [
{
"docstring": "Add the display command to the menu.",
"name": "addPluginToMenu",
"signature": "def addPluginToMenu(self, canvas, fileName, menu, name, suffix)"
},
{
"docstring": "Display the export canvas repository dialog.",
"name": "display",
"signature": "def display(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001526 | Implement the Python class `ExportCanvasDialog` described below.
Class description:
A class to display the export canvas repository dialog.
Method signatures and docstrings:
- def addPluginToMenu(self, canvas, fileName, menu, name, suffix): Add the display command to the menu.
- def display(self): Display the export ... | Implement the Python class `ExportCanvasDialog` described below.
Class description:
A class to display the export canvas repository dialog.
Method signatures and docstrings:
- def addPluginToMenu(self, canvas, fileName, menu, name, suffix): Add the display command to the menu.
- def display(self): Display the export ... | fd69d8e856780c826386dc973ceabcc03623f3e8 | <|skeleton|>
class ExportCanvasDialog:
"""A class to display the export canvas repository dialog."""
def addPluginToMenu(self, canvas, fileName, menu, name, suffix):
"""Add the display command to the menu."""
<|body_0|>
def display(self):
"""Display the export canvas repository dia... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExportCanvasDialog:
"""A class to display the export canvas repository dialog."""
def addPluginToMenu(self, canvas, fileName, menu, name, suffix):
"""Add the display command to the menu."""
self.canvas = canvas
self.fileName = fileName
self.name = name
self.suffix ... | the_stack_v2_python_sparse | skeinforge_tools/analyze_plugins/analyze_utilities/tableau.py | bmander/skeinforge | train | 34 |
6de2e8347b779445e6508c4618fd87e2338d33b4 | [
"@lru_cache(None)\ndef pmin(i, j):\n if i == j:\n return 0\n return min(pmax(i + 1, j), pmax(i, j - 1))\n\n@lru_cache(None)\ndef pmax(i, j):\n if i == j:\n return piles[i]\n return max(piles[i] + pmin(i + 1, j), pmin(i, j - 1) + piles[j])\np1 = pmax(0, len(piles) - 1)\np2 = sum(piles) - p1... | <|body_start_0|>
@lru_cache(None)
def pmin(i, j):
if i == j:
return 0
return min(pmax(i + 1, j), pmax(i, j - 1))
@lru_cache(None)
def pmax(i, j):
if i == j:
return piles[i]
return max(piles[i] + pmin(i + 1, ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def stoneGame_solution_1_minimax(self, piles: List[int]) -> bool:
""":type piles: List[int] :rtype: bool"""
<|body_0|>
def stoneGame_solution_2_minimax_DP_2D(self, piles: List[int]) -> bool:
""":type piles: List[int] :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_009151 | 4,363 | no_license | [
{
"docstring": ":type piles: List[int] :rtype: bool",
"name": "stoneGame_solution_1_minimax",
"signature": "def stoneGame_solution_1_minimax(self, piles: List[int]) -> bool"
},
{
"docstring": ":type piles: List[int] :rtype: bool",
"name": "stoneGame_solution_2_minimax_DP_2D",
"signature"... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def stoneGame_solution_1_minimax(self, piles: List[int]) -> bool: :type piles: List[int] :rtype: bool
- def stoneGame_solution_2_minimax_DP_2D(self, piles: List[int]) -> bool: :t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def stoneGame_solution_1_minimax(self, piles: List[int]) -> bool: :type piles: List[int] :rtype: bool
- def stoneGame_solution_2_minimax_DP_2D(self, piles: List[int]) -> bool: :t... | f2621cd76822a922c49b60f32931f26cce1c571d | <|skeleton|>
class Solution:
def stoneGame_solution_1_minimax(self, piles: List[int]) -> bool:
""":type piles: List[int] :rtype: bool"""
<|body_0|>
def stoneGame_solution_2_minimax_DP_2D(self, piles: List[int]) -> bool:
""":type piles: List[int] :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def stoneGame_solution_1_minimax(self, piles: List[int]) -> bool:
""":type piles: List[int] :rtype: bool"""
@lru_cache(None)
def pmin(i, j):
if i == j:
return 0
return min(pmax(i + 1, j), pmax(i, j - 1))
@lru_cache(None)
... | the_stack_v2_python_sparse | Dynamic_Programming/023_leetcode_P_877_StoneGame/Solution.py | Keshav1506/competitive_programming | train | 0 | |
00ad2569c7c6229910c2c772c714b517c0a9ad0a | [
"self.train_number = self.request.rel_url.query.get('train', None)\nif self.train_number:\n return web.HTTPMovedPermanently('/%s/train/%s' % (self.request.language, self.train_number))\nself.train_number = self.request.match_info.get('train')\nreturn await super(TrainView, self).get()",
"try:\n context = cf... | <|body_start_0|>
self.train_number = self.request.rel_url.query.get('train', None)
if self.train_number:
return web.HTTPMovedPermanently('/%s/train/%s' % (self.request.language, self.train_number))
self.train_number = self.request.match_info.get('train')
return await super(Tr... | Page that displays details about a specific train. | TrainView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainView:
"""Page that displays details about a specific train."""
async def get(self):
"""Reply to HTTP GET request."""
<|body_0|>
def context(self) -> dict:
"""Gets the context to render the template with. Returns: The context to pass to the template."""
... | stack_v2_sparse_classes_36k_train_009152 | 1,595 | no_license | [
{
"docstring": "Reply to HTTP GET request.",
"name": "get",
"signature": "async def get(self)"
},
{
"docstring": "Gets the context to render the template with. Returns: The context to pass to the template.",
"name": "context",
"signature": "def context(self) -> dict"
}
] | 2 | stack_v2_sparse_classes_30k_train_016744 | Implement the Python class `TrainView` described below.
Class description:
Page that displays details about a specific train.
Method signatures and docstrings:
- async def get(self): Reply to HTTP GET request.
- def context(self) -> dict: Gets the context to render the template with. Returns: The context to pass to t... | Implement the Python class `TrainView` described below.
Class description:
Page that displays details about a specific train.
Method signatures and docstrings:
- async def get(self): Reply to HTTP GET request.
- def context(self) -> dict: Gets the context to render the template with. Returns: The context to pass to t... | fc182e2f8bb45682361ac16befd2710f3492e65f | <|skeleton|>
class TrainView:
"""Page that displays details about a specific train."""
async def get(self):
"""Reply to HTTP GET request."""
<|body_0|>
def context(self) -> dict:
"""Gets the context to render the template with. Returns: The context to pass to the template."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainView:
"""Page that displays details about a specific train."""
async def get(self):
"""Reply to HTTP GET request."""
self.train_number = self.request.rel_url.query.get('train', None)
if self.train_number:
return web.HTTPMovedPermanently('/%s/train/%s' % (self.requ... | the_stack_v2_python_sparse | cfrweb/views/train.py | Photonios/cfr.ninja | train | 4 |
e8fd9ec03c1af09e4f3962be591d0dbc2d5aa965 | [
"self.driver = driver\nself.searchIn = searchIn\nself.SearchConfig = {'GoogleSearch': {'URL': 'https://www.google.com/', 'SearchBox_xPath': '/html/body/div/div[3]/form/div[2]/div/div[1]/div/div[1]/input', 'OpenInNewLink': 'pnnext'}, 'GoogleNewsSearch': {'URL': 'https://news.google.com/?hl=en-IN&gl=IN&ceid=IN:en', '... | <|body_start_0|>
self.driver = driver
self.searchIn = searchIn
self.SearchConfig = {'GoogleSearch': {'URL': 'https://www.google.com/', 'SearchBox_xPath': '/html/body/div/div[3]/form/div[2]/div/div[1]/div/div[1]/input', 'OpenInNewLink': 'pnnext'}, 'GoogleNewsSearch': {'URL': 'https://news.google.... | search | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class search:
def __init__(self, driver, searchIn='GoogleSearch'):
"""Search In Options: 'GoogleSearch', 'GoogleNewsSearch', 'GoogleScholarSearch', 'GoogleImageSearch'"""
<|body_0|>
def genEleMsg(self, elem=None):
"""to Generate Respeccted Msg when a element is loaded"""
... | stack_v2_sparse_classes_36k_train_009153 | 6,562 | no_license | [
{
"docstring": "Search In Options: 'GoogleSearch', 'GoogleNewsSearch', 'GoogleScholarSearch', 'GoogleImageSearch'",
"name": "__init__",
"signature": "def __init__(self, driver, searchIn='GoogleSearch')"
},
{
"docstring": "to Generate Respeccted Msg when a element is loaded",
"name": "genEleM... | 4 | stack_v2_sparse_classes_30k_train_000203 | Implement the Python class `search` described below.
Class description:
Implement the search class.
Method signatures and docstrings:
- def __init__(self, driver, searchIn='GoogleSearch'): Search In Options: 'GoogleSearch', 'GoogleNewsSearch', 'GoogleScholarSearch', 'GoogleImageSearch'
- def genEleMsg(self, elem=None... | Implement the Python class `search` described below.
Class description:
Implement the search class.
Method signatures and docstrings:
- def __init__(self, driver, searchIn='GoogleSearch'): Search In Options: 'GoogleSearch', 'GoogleNewsSearch', 'GoogleScholarSearch', 'GoogleImageSearch'
- def genEleMsg(self, elem=None... | 61b561d95113c9844119baeed25716b2565c99c4 | <|skeleton|>
class search:
def __init__(self, driver, searchIn='GoogleSearch'):
"""Search In Options: 'GoogleSearch', 'GoogleNewsSearch', 'GoogleScholarSearch', 'GoogleImageSearch'"""
<|body_0|>
def genEleMsg(self, elem=None):
"""to Generate Respeccted Msg when a element is loaded"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class search:
def __init__(self, driver, searchIn='GoogleSearch'):
"""Search In Options: 'GoogleSearch', 'GoogleNewsSearch', 'GoogleScholarSearch', 'GoogleImageSearch'"""
self.driver = driver
self.searchIn = searchIn
self.SearchConfig = {'GoogleSearch': {'URL': 'https://www.google.co... | the_stack_v2_python_sparse | bin/Sel2_InitiateSearch.py | gagangm/NewsGatheringAndSentimentAnalysis | train | 0 | |
2dc5136a3b3f296b3bbeb27f1e7060f2cc6ff730 | [
"adapter = os.environ.get('CN_SECRET_ADAPTER', 'vault')\nif adapter == 'vault':\n return VaultSecret()\nif adapter == 'kubernetes':\n return KubernetesSecret()\nif adapter == 'google':\n return GoogleSecret()\nif adapter == 'aws':\n return AwsSecret()\nraise ValueError(f'Unsupported secret adapter {adap... | <|body_start_0|>
adapter = os.environ.get('CN_SECRET_ADAPTER', 'vault')
if adapter == 'vault':
return VaultSecret()
if adapter == 'kubernetes':
return KubernetesSecret()
if adapter == 'google':
return GoogleSecret()
if adapter == 'aws':
... | This class manage secrets and act as a proxy to specific secret adapter class. | SecretManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecretManager:
"""This class manage secrets and act as a proxy to specific secret adapter class."""
def adapter(self) -> SecretAdapter:
"""Get an instance of secret adapter class. Returns: An instance of secret adapter class. Raises: ValueError: If the value of `CN_SECRET_ADAPTER` en... | stack_v2_sparse_classes_36k_train_009154 | 11,331 | permissive | [
{
"docstring": "Get an instance of secret adapter class. Returns: An instance of secret adapter class. Raises: ValueError: If the value of `CN_SECRET_ADAPTER` environment variable is not supported. Examples: ```py os.environ[\"CN_SECRET_ADAPTER\"] = \"vault\" SecretManager().adapter # returns an instance of ada... | 3 | null | Implement the Python class `SecretManager` described below.
Class description:
This class manage secrets and act as a proxy to specific secret adapter class.
Method signatures and docstrings:
- def adapter(self) -> SecretAdapter: Get an instance of secret adapter class. Returns: An instance of secret adapter class. R... | Implement the Python class `SecretManager` described below.
Class description:
This class manage secrets and act as a proxy to specific secret adapter class.
Method signatures and docstrings:
- def adapter(self) -> SecretAdapter: Get an instance of secret adapter class. Returns: An instance of secret adapter class. R... | 66c4ef766a62788437cce88974357a9a2b20de21 | <|skeleton|>
class SecretManager:
"""This class manage secrets and act as a proxy to specific secret adapter class."""
def adapter(self) -> SecretAdapter:
"""Get an instance of secret adapter class. Returns: An instance of secret adapter class. Raises: ValueError: If the value of `CN_SECRET_ADAPTER` en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SecretManager:
"""This class manage secrets and act as a proxy to specific secret adapter class."""
def adapter(self) -> SecretAdapter:
"""Get an instance of secret adapter class. Returns: An instance of secret adapter class. Raises: ValueError: If the value of `CN_SECRET_ADAPTER` environment var... | the_stack_v2_python_sparse | jans-pycloudlib/jans/pycloudlib/manager.py | JanssenProject/jans | train | 400 |
df9419e46b70d5cddc679791a31024bf39c4fb01 | [
"if self.call_args is None:\n expected = self._format_mock_call_signature(args, kwargs)\n raise AssertionError('Expected call: %s\\nNot called' % (expected,))\n\ndef _error_message(cause):\n msg = self._format_mock_failure_message(args, kwargs)\n if six.PY2 and cause is not None:\n msg = '%s\\n%s... | <|body_start_0|>
if self.call_args is None:
expected = self._format_mock_call_signature(args, kwargs)
raise AssertionError('Expected call: %s\nNot called' % (expected,))
def _error_message(cause):
msg = self._format_mock_failure_message(args, kwargs)
if s... | AlteredMagicMock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlteredMagicMock:
def assert_called_with(self, *args, **kwargs):
"""Assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock."""
<|body_0|>
def assert_any_call(sel... | stack_v2_sparse_classes_36k_train_009155 | 22,331 | no_license | [
{
"docstring": "Assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.",
"name": "assert_called_with",
"signature": "def assert_called_with(self, *args, **kwargs)"
},
{
"docstring":... | 3 | null | Implement the Python class `AlteredMagicMock` described below.
Class description:
Implement the AlteredMagicMock class.
Method signatures and docstrings:
- def assert_called_with(self, *args, **kwargs): Assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args... | Implement the Python class `AlteredMagicMock` described below.
Class description:
Implement the AlteredMagicMock class.
Method signatures and docstrings:
- def assert_called_with(self, *args, **kwargs): Assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args... | 092a354315b9b2c08e32cdc049791d82dfd47745 | <|skeleton|>
class AlteredMagicMock:
def assert_called_with(self, *args, **kwargs):
"""Assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock."""
<|body_0|>
def assert_any_call(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlteredMagicMock:
def assert_called_with(self, *args, **kwargs):
"""Assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock."""
if self.call_args is None:
expected = sel... | the_stack_v2_python_sparse | robot_skills/src/robot_skills/mockbot.py | tue-robotics/tue_robocup | train | 39 | |
2874baaa24f1c2cdafe8577cd7b68d50be0329b1 | [
"t = tabulate(lambda x: x)\nf = tuple([next(t) for _ in range(3)])\neq_(f, (0, 1, 2))",
"t = tabulate(lambda x: 2 * x, -1)\nf = (next(t), next(t), next(t))\neq_(f, (-2, 0, 2))"
] | <|body_start_0|>
t = tabulate(lambda x: x)
f = tuple([next(t) for _ in range(3)])
eq_(f, (0, 1, 2))
<|end_body_0|>
<|body_start_1|>
t = tabulate(lambda x: 2 * x, -1)
f = (next(t), next(t), next(t))
eq_(f, (-2, 0, 2))
<|end_body_1|>
| Tests for ``tabulate()`` | TabulateTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TabulateTests:
"""Tests for ``tabulate()``"""
def test_simple_tabulate(self):
"""Test the happy path"""
<|body_0|>
def test_count(self):
"""Ensure tabulate accepts specific count"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
t = tabulate(lambd... | stack_v2_sparse_classes_36k_train_009156 | 47,145 | no_license | [
{
"docstring": "Test the happy path",
"name": "test_simple_tabulate",
"signature": "def test_simple_tabulate(self)"
},
{
"docstring": "Ensure tabulate accepts specific count",
"name": "test_count",
"signature": "def test_count(self)"
}
] | 2 | null | Implement the Python class `TabulateTests` described below.
Class description:
Tests for ``tabulate()``
Method signatures and docstrings:
- def test_simple_tabulate(self): Test the happy path
- def test_count(self): Ensure tabulate accepts specific count | Implement the Python class `TabulateTests` described below.
Class description:
Tests for ``tabulate()``
Method signatures and docstrings:
- def test_simple_tabulate(self): Test the happy path
- def test_count(self): Ensure tabulate accepts specific count
<|skeleton|>
class TabulateTests:
"""Tests for ``tabulate(... | 0ac6653219c2701c13c508c5c4fc9bc3437eea06 | <|skeleton|>
class TabulateTests:
"""Tests for ``tabulate()``"""
def test_simple_tabulate(self):
"""Test the happy path"""
<|body_0|>
def test_count(self):
"""Ensure tabulate accepts specific count"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TabulateTests:
"""Tests for ``tabulate()``"""
def test_simple_tabulate(self):
"""Test the happy path"""
t = tabulate(lambda x: x)
f = tuple([next(t) for _ in range(3)])
eq_(f, (0, 1, 2))
def test_count(self):
"""Ensure tabulate accepts specific count"""
... | the_stack_v2_python_sparse | repoData/erikrose-more-itertools/allPythonContent.py | aCoffeeYin/pyreco | train | 0 |
00a759b38e7eee3d6d5df66ac84c6db793a32d03 | [
"if request.method != 'POST':\n return True\nif request.user.is_government:\n return request.user.has_perm('SIGN_SALES') or request.user.has_perm('RECOMMEND_SALES') or request.user.has_perm('DECLINE_SALES') or request.user.has_perm('VALIDATE_SALES')\nreturn request.user.has_perm('CREATE_SALES') or request.use... | <|body_start_0|>
if request.method != 'POST':
return True
if request.user.is_government:
return request.user.has_perm('SIGN_SALES') or request.user.has_perm('RECOMMEND_SALES') or request.user.has_perm('DECLINE_SALES') or request.user.has_perm('VALIDATE_SALES')
return requ... | Used by Viewset to check permissions for API requests | CreditRequestPermissions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreditRequestPermissions:
"""Used by Viewset to check permissions for API requests"""
def has_permission(self, request, view):
"""Check permissions When an object does not yet exist (POST)"""
<|body_0|>
def has_object_permission(self, request, view, obj):
"""Chec... | stack_v2_sparse_classes_36k_train_009157 | 1,730 | permissive | [
{
"docstring": "Check permissions When an object does not yet exist (POST)",
"name": "has_permission",
"signature": "def has_permission(self, request, view)"
},
{
"docstring": "Check permissions When an object does exist (PUT, GET)",
"name": "has_object_permission",
"signature": "def has... | 2 | null | Implement the Python class `CreditRequestPermissions` described below.
Class description:
Used by Viewset to check permissions for API requests
Method signatures and docstrings:
- def has_permission(self, request, view): Check permissions When an object does not yet exist (POST)
- def has_object_permission(self, requ... | Implement the Python class `CreditRequestPermissions` described below.
Class description:
Used by Viewset to check permissions for API requests
Method signatures and docstrings:
- def has_permission(self, request, view): Check permissions When an object does not yet exist (POST)
- def has_object_permission(self, requ... | b395efe620a1b82c2ecee2004cca358d8407397e | <|skeleton|>
class CreditRequestPermissions:
"""Used by Viewset to check permissions for API requests"""
def has_permission(self, request, view):
"""Check permissions When an object does not yet exist (POST)"""
<|body_0|>
def has_object_permission(self, request, view, obj):
"""Chec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreditRequestPermissions:
"""Used by Viewset to check permissions for API requests"""
def has_permission(self, request, view):
"""Check permissions When an object does not yet exist (POST)"""
if request.method != 'POST':
return True
if request.user.is_government:
... | the_stack_v2_python_sparse | backend/api/permissions/credit_request.py | emi-hi/zeva | train | 0 |
27cb6ab4cfafb605725380bbd8cb76b0ea921ff8 | [
"self.name = name\nself.propIdx = propIdx\nself.minValue = minValue\nself.maxValue = maxValue\nself.offset = scaffoldoffset",
"product = self.offset\npropIdx = self.propIdx\nfor s in sidechains:\n product += s.props[propIdx]\nreturn self.minValue <= product <= self.maxValue"
] | <|body_start_0|>
self.name = name
self.propIdx = propIdx
self.minValue = minValue
self.maxValue = maxValue
self.offset = scaffoldoffset
<|end_body_0|>
<|body_start_1|>
product = self.offset
propIdx = self.propIdx
for s in sidechains:
product +... | Property | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Property:
def __init__(self, name, propIdx, minValue, maxValue, scaffoldoffset=0.0):
"""name, propIdx, minValue, maxValue, scaffoldoffset -> initial a Property name is the name of the property. propIdx: the index of the property in the property vector minValue: the minimum acceptable val... | stack_v2_sparse_classes_36k_train_009158 | 17,205 | permissive | [
{
"docstring": "name, propIdx, minValue, maxValue, scaffoldoffset -> initial a Property name is the name of the property. propIdx: the index of the property in the property vector minValue: the minimum acceptable value for the property maxValue: the maximum acceptable value for the property scaffoldoffset: any ... | 2 | null | Implement the Python class `Property` described below.
Class description:
Implement the Property class.
Method signatures and docstrings:
- def __init__(self, name, propIdx, minValue, maxValue, scaffoldoffset=0.0): name, propIdx, minValue, maxValue, scaffoldoffset -> initial a Property name is the name of the propert... | Implement the Python class `Property` described below.
Class description:
Implement the Property class.
Method signatures and docstrings:
- def __init__(self, name, propIdx, minValue, maxValue, scaffoldoffset=0.0): name, propIdx, minValue, maxValue, scaffoldoffset -> initial a Property name is the name of the propert... | 650141ece7b68f054ed14813e1585436ad57d3df | <|skeleton|>
class Property:
def __init__(self, name, propIdx, minValue, maxValue, scaffoldoffset=0.0):
"""name, propIdx, minValue, maxValue, scaffoldoffset -> initial a Property name is the name of the property. propIdx: the index of the property in the property vector minValue: the minimum acceptable val... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Property:
def __init__(self, name, propIdx, minValue, maxValue, scaffoldoffset=0.0):
"""name, propIdx, minValue, maxValue, scaffoldoffset -> initial a Property name is the name of the property. propIdx: the index of the property in the property vector minValue: the minimum acceptable value for the pro... | the_stack_v2_python_sparse | Contrib/Glare/glare.py | biolearning-stadius/rdkit | train | 6 | |
7cf88e1645d8accf7097a420974ba659944b7549 | [
"self.g = g\nself.user_type = user_type\nself.item_type = item_type\nself.user_to_item_etype = list(g.metagraph()[user_type][item_type])[0]\nself.item_to_user_etype = list(g.metagraph()[item_type][user_type])[0]\nself.batch_size = batch_size",
"while True:\n heads = torch.randint(0, self.g.number_of_nodes(self... | <|body_start_0|>
self.g = g
self.user_type = user_type
self.item_type = item_type
self.user_to_item_etype = list(g.metagraph()[user_type][item_type])[0]
self.item_to_user_etype = list(g.metagraph()[item_type][user_type])[0]
self.batch_size = batch_size
<|end_body_0|>
<|b... | Item to Item Batch Sampler class. | ItemToItemBatchSampler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemToItemBatchSampler:
"""Item to Item Batch Sampler class."""
def __init__(self, g, user_type, item_type, batch_size):
"""Constructor for ItemToItemBatchSampler class. Args: g (dgl.DGLGraph): graph of training dataset user_type (str): user node name item_type (str): item node name ... | stack_v2_sparse_classes_36k_train_009159 | 12,447 | no_license | [
{
"docstring": "Constructor for ItemToItemBatchSampler class. Args: g (dgl.DGLGraph): graph of training dataset user_type (str): user node name item_type (str): item node name batch_size (int): batch size",
"name": "__init__",
"signature": "def __init__(self, g, user_type, item_type, batch_size)"
},
... | 2 | stack_v2_sparse_classes_30k_train_020410 | Implement the Python class `ItemToItemBatchSampler` described below.
Class description:
Item to Item Batch Sampler class.
Method signatures and docstrings:
- def __init__(self, g, user_type, item_type, batch_size): Constructor for ItemToItemBatchSampler class. Args: g (dgl.DGLGraph): graph of training dataset user_ty... | Implement the Python class `ItemToItemBatchSampler` described below.
Class description:
Item to Item Batch Sampler class.
Method signatures and docstrings:
- def __init__(self, g, user_type, item_type, batch_size): Constructor for ItemToItemBatchSampler class. Args: g (dgl.DGLGraph): graph of training dataset user_ty... | f1c385e46d2d5475b28dec91b57a933ac81c23c5 | <|skeleton|>
class ItemToItemBatchSampler:
"""Item to Item Batch Sampler class."""
def __init__(self, g, user_type, item_type, batch_size):
"""Constructor for ItemToItemBatchSampler class. Args: g (dgl.DGLGraph): graph of training dataset user_type (str): user node name item_type (str): item node name ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ItemToItemBatchSampler:
"""Item to Item Batch Sampler class."""
def __init__(self, g, user_type, item_type, batch_size):
"""Constructor for ItemToItemBatchSampler class. Args: g (dgl.DGLGraph): graph of training dataset user_type (str): user node name item_type (str): item node name batch_size (i... | the_stack_v2_python_sparse | projects/project_19/src/pinsage/sampler.py | amuamushu/projects-2020-2021 | train | 0 |
40edf3ebd7bec0481aec670733635b4ac996d706 | [
"n = len(A)\ni = 0\nwhile i + 1 < n and A[i] < A[i + 1]:\n i += 1\nreturn i",
"n = len(A)\nleft, right = (1, n - 2)\nwhile left <= right:\n mid = left + (right - left) // 2\n if A[mid - 1] < A[mid] > A[mid + 1]:\n return mid\n elif A[mid] < A[mid + 1]:\n left = mid + 1\n elif A[mid - ... | <|body_start_0|>
n = len(A)
i = 0
while i + 1 < n and A[i] < A[i + 1]:
i += 1
return i
<|end_body_0|>
<|body_start_1|>
n = len(A)
left, right = (1, n - 2)
while left <= right:
mid = left + (right - left) // 2
if A[mid - 1] < A[... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def xpeakIndexInMountainArray(self, A: List[int]) -> int:
"""Time complexity = O(n)"""
<|body_0|>
def peakIndexInMountainArray(self, A: List[int]) -> int:
"""Time complexity = O(log n) Your runtime beats 98.91 % of python3 submissions."""
<|body_1|>... | stack_v2_sparse_classes_36k_train_009160 | 788 | permissive | [
{
"docstring": "Time complexity = O(n)",
"name": "xpeakIndexInMountainArray",
"signature": "def xpeakIndexInMountainArray(self, A: List[int]) -> int"
},
{
"docstring": "Time complexity = O(log n) Your runtime beats 98.91 % of python3 submissions.",
"name": "peakIndexInMountainArray",
"si... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def xpeakIndexInMountainArray(self, A: List[int]) -> int: Time complexity = O(n)
- def peakIndexInMountainArray(self, A: List[int]) -> int: Time complexity = O(log n) Your runtim... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def xpeakIndexInMountainArray(self, A: List[int]) -> int: Time complexity = O(n)
- def peakIndexInMountainArray(self, A: List[int]) -> int: Time complexity = O(log n) Your runtim... | 9d7759bea1f44673c2de4f25a94b27368928a59f | <|skeleton|>
class Solution:
def xpeakIndexInMountainArray(self, A: List[int]) -> int:
"""Time complexity = O(n)"""
<|body_0|>
def peakIndexInMountainArray(self, A: List[int]) -> int:
"""Time complexity = O(log n) Your runtime beats 98.91 % of python3 submissions."""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def xpeakIndexInMountainArray(self, A: List[int]) -> int:
"""Time complexity = O(n)"""
n = len(A)
i = 0
while i + 1 < n and A[i] < A[i + 1]:
i += 1
return i
def peakIndexInMountainArray(self, A: List[int]) -> int:
"""Time complexity = ... | the_stack_v2_python_sparse | leetcode/google/tagged/peak_index_in_mountain_array.py | pagsamo/google-tech-dev-guide | train | 0 | |
7d81971b3cc33cf292b8f01c9cb50b434ffe2a20 | [
"def backtrack(pos: int, target: int) -> List[List[int]]:\n if target == 0:\n return [[]]\n if pos >= len(nums) or nums[pos] > target:\n return []\n return [[nums[pos]] + sub_sol for sub_sol in backtrack(pos, target - nums[pos])] + backtrack(pos + 1, target)\nnums.sort()\nreturn backtrack(0, ... | <|body_start_0|>
def backtrack(pos: int, target: int) -> List[List[int]]:
if target == 0:
return [[]]
if pos >= len(nums) or nums[pos] > target:
return []
return [[nums[pos]] + sub_sol for sub_sol in backtrack(pos, target - nums[pos])] + backtr... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum_1(self, nums: List[int], target: int) -> List[List[int]]:
"""If we select the number at 'i', then we have another sub-problem to solve at 'i+1' with 'target-nums[i]'. If we sort the numbers, we can cut the exploration when nums[i] > target. There might be ove... | stack_v2_sparse_classes_36k_train_009161 | 2,540 | no_license | [
{
"docstring": "If we select the number at 'i', then we have another sub-problem to solve at 'i+1' with 'target-nums[i]'. If we sort the numbers, we can cut the exploration when nums[i] > target. There might be overlapping problems (select 2 then 3, or select 5), but it might not be worth memoizing them because... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum_1(self, nums: List[int], target: int) -> List[List[int]]: If we select the number at 'i', then we have another sub-problem to solve at 'i+1' with 'target-nums[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum_1(self, nums: List[int], target: int) -> List[List[int]]: If we select the number at 'i', then we have another sub-problem to solve at 'i+1' with 'target-nums[... | 3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8 | <|skeleton|>
class Solution:
def combinationSum_1(self, nums: List[int], target: int) -> List[List[int]]:
"""If we select the number at 'i', then we have another sub-problem to solve at 'i+1' with 'target-nums[i]'. If we sort the numbers, we can cut the exploration when nums[i] > target. There might be ove... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSum_1(self, nums: List[int], target: int) -> List[List[int]]:
"""If we select the number at 'i', then we have another sub-problem to solve at 'i+1' with 'target-nums[i]'. If we sort the numbers, we can cut the exploration when nums[i] > target. There might be overlapping probl... | the_stack_v2_python_sparse | backtrack/CombinationSum.py | QuentinDuval/PythonExperiments | train | 3 | |
35db5a3db506d34cba4fb78ae0fd15ce29c7f519 | [
"if self.app.pargs.download is None:\n download_type = []\nelse:\n download_type = self.app.pargs.download.split(',')\n download_type = list(filter(lambda x: x in all_download_type, download_type))\nreturn download_type",
"help = None\nfun = getattr(self, func_name, None)\nif fun and getattr(fun, '__ceme... | <|body_start_0|>
if self.app.pargs.download is None:
download_type = []
else:
download_type = self.app.pargs.download.split(',')
download_type = list(filter(lambda x: x in all_download_type, download_type))
return download_type
<|end_body_0|>
<|body_start_1|>... | NXSpiderBaseController | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NXSpiderBaseController:
def parse_download(self):
"""lost of spider function will parse -dw param, this will do it :return:"""
<|body_0|>
def param_check(self, params, func_name):
"""this will check param inputted and require is complete or not, and print help help w... | stack_v2_sparse_classes_36k_train_009162 | 1,707 | permissive | [
{
"docstring": "lost of spider function will parse -dw param, this will do it :return:",
"name": "parse_download",
"signature": "def parse_download(self)"
},
{
"docstring": "this will check param inputted and require is complete or not, and print help help will be in expose(help='...'), and got ... | 2 | stack_v2_sparse_classes_30k_train_007285 | Implement the Python class `NXSpiderBaseController` described below.
Class description:
Implement the NXSpiderBaseController class.
Method signatures and docstrings:
- def parse_download(self): lost of spider function will parse -dw param, this will do it :return:
- def param_check(self, params, func_name): this will... | Implement the Python class `NXSpiderBaseController` described below.
Class description:
Implement the NXSpiderBaseController class.
Method signatures and docstrings:
- def parse_download(self): lost of spider function will parse -dw param, this will do it :return:
- def param_check(self, params, func_name): this will... | 68e588c0612d0ab2af3a820ff88ca24d698ceeb7 | <|skeleton|>
class NXSpiderBaseController:
def parse_download(self):
"""lost of spider function will parse -dw param, this will do it :return:"""
<|body_0|>
def param_check(self, params, func_name):
"""this will check param inputted and require is complete or not, and print help help w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NXSpiderBaseController:
def parse_download(self):
"""lost of spider function will parse -dw param, this will do it :return:"""
if self.app.pargs.download is None:
download_type = []
else:
download_type = self.app.pargs.download.split(',')
download_ty... | the_stack_v2_python_sparse | NXSpider/bin/base_ctrl.py | Z-Shuming/NXSpider | train | 0 | |
39a350c094dc6dfa2cc94d925aedccaa2cea19e7 | [
"quadrado = Quadrado()\nquadrado.lado = 4\nself.assertEquals(4, quadrado.RetornaLado())",
"quadrado = Quadrado()\nquadrado.lado = 3\nself.assertEquals(9, quadrado.CalcularArea())"
] | <|body_start_0|>
quadrado = Quadrado()
quadrado.lado = 4
self.assertEquals(4, quadrado.RetornaLado())
<|end_body_0|>
<|body_start_1|>
quadrado = Quadrado()
quadrado.lado = 3
self.assertEquals(9, quadrado.CalcularArea())
<|end_body_1|>
| MyQuadradoTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyQuadradoTest:
def testRetornaLado(self):
"""Função que testa o método 'Retorna Lado' da classe Quadrado :return: sem retornos."""
<|body_0|>
def testeCalcularArea(self):
"""Função que testa o método 'CalculaArea' da classe Quadrado :return: sem retornos."""
... | stack_v2_sparse_classes_36k_train_009163 | 784 | no_license | [
{
"docstring": "Função que testa o método 'Retorna Lado' da classe Quadrado :return: sem retornos.",
"name": "testRetornaLado",
"signature": "def testRetornaLado(self)"
},
{
"docstring": "Função que testa o método 'CalculaArea' da classe Quadrado :return: sem retornos.",
"name": "testeCalcul... | 2 | stack_v2_sparse_classes_30k_train_019546 | Implement the Python class `MyQuadradoTest` described below.
Class description:
Implement the MyQuadradoTest class.
Method signatures and docstrings:
- def testRetornaLado(self): Função que testa o método 'Retorna Lado' da classe Quadrado :return: sem retornos.
- def testeCalcularArea(self): Função que testa o método... | Implement the Python class `MyQuadradoTest` described below.
Class description:
Implement the MyQuadradoTest class.
Method signatures and docstrings:
- def testRetornaLado(self): Função que testa o método 'Retorna Lado' da classe Quadrado :return: sem retornos.
- def testeCalcularArea(self): Função que testa o método... | 0ebcb2da872fcd5c101826455710634a3e6e69cb | <|skeleton|>
class MyQuadradoTest:
def testRetornaLado(self):
"""Função que testa o método 'Retorna Lado' da classe Quadrado :return: sem retornos."""
<|body_0|>
def testeCalcularArea(self):
"""Função que testa o método 'CalculaArea' da classe Quadrado :return: sem retornos."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyQuadradoTest:
def testRetornaLado(self):
"""Função que testa o método 'Retorna Lado' da classe Quadrado :return: sem retornos."""
quadrado = Quadrado()
quadrado.lado = 4
self.assertEquals(4, quadrado.RetornaLado())
def testeCalcularArea(self):
"""Função que testa... | the_stack_v2_python_sparse | Projeto_Testes/First_TDD_File.py | gnfandrade/Projetos_Python | train | 0 | |
1968a46a67377fed112b685c22fb731f81742e33 | [
"base_url = 'https://github.com/IATI/IATI-Guidance/commits/main/en/'\nfile_path = '/'.join(self.ssot_path.split('/')[1:]) + '.rst'\nreturn base_url + file_path",
"related = []\nsoup = BeautifulSoup(self.data, 'html.parser')\nanchors = soup.findAll('a')\nfor anchor in anchors:\n anchor_href = anchor['href']\n ... | <|body_start_0|>
base_url = 'https://github.com/IATI/IATI-Guidance/commits/main/en/'
file_path = '/'.join(self.ssot_path.split('/')[1:]) + '.rst'
return base_url + file_path
<|end_body_0|>
<|body_start_1|>
related = []
soup = BeautifulSoup(self.data, 'html.parser')
ancho... | A model for the Standard Guidance Page, an IATI reference page. | StandardGuidancePage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StandardGuidancePage:
"""A model for the Standard Guidance Page, an IATI reference page."""
def github_url(self):
"""Calculate a Github changelog url."""
<|body_0|>
def related_guidance(self):
"""Extract related_guidance."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_009164 | 14,810 | permissive | [
{
"docstring": "Calculate a Github changelog url.",
"name": "github_url",
"signature": "def github_url(self)"
},
{
"docstring": "Extract related_guidance.",
"name": "related_guidance",
"signature": "def related_guidance(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006941 | Implement the Python class `StandardGuidancePage` described below.
Class description:
A model for the Standard Guidance Page, an IATI reference page.
Method signatures and docstrings:
- def github_url(self): Calculate a Github changelog url.
- def related_guidance(self): Extract related_guidance. | Implement the Python class `StandardGuidancePage` described below.
Class description:
A model for the Standard Guidance Page, an IATI reference page.
Method signatures and docstrings:
- def github_url(self): Calculate a Github changelog url.
- def related_guidance(self): Extract related_guidance.
<|skeleton|>
class ... | 4cf7be72b6b3d0c46dcadcc9d9904b471215ea81 | <|skeleton|>
class StandardGuidancePage:
"""A model for the Standard Guidance Page, an IATI reference page."""
def github_url(self):
"""Calculate a Github changelog url."""
<|body_0|>
def related_guidance(self):
"""Extract related_guidance."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StandardGuidancePage:
"""A model for the Standard Guidance Page, an IATI reference page."""
def github_url(self):
"""Calculate a Github changelog url."""
base_url = 'https://github.com/IATI/IATI-Guidance/commits/main/en/'
file_path = '/'.join(self.ssot_path.split('/')[1:]) + '.rst... | the_stack_v2_python_sparse | iati_standard/models.py | IATI/IATI-Standard-Website | train | 4 |
bdeeae3d262cf069d26a89adb49b3094b82d7944 | [
"http_auth = request.META['HTTP_AUTHORIZATION']\nparts = http_auth.split(' ')\nif parts[0] != 'token':\n return None\nif len(parts) != 2:\n logger.warning('WebAPITokenAuthBackend: Missing token in HTTP_AUTHORIZATION header %s', http_auth, extra={'request': request})\n return None\nreturn {'token': parts[1]... | <|body_start_0|>
http_auth = request.META['HTTP_AUTHORIZATION']
parts = http_auth.split(' ')
if parts[0] != 'token':
return None
if len(parts) != 2:
logger.warning('WebAPITokenAuthBackend: Missing token in HTTP_AUTHORIZATION header %s', http_auth, extra={'request'... | Authenticates users using their generated API token. This will check the ``HTTP_AUTHORIZATION`` header for a ``token <token>`` value. If found, it will attempt to find the user that owns the token, and authenticate that user. | WebAPITokenAuthBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebAPITokenAuthBackend:
"""Authenticates users using their generated API token. This will check the ``HTTP_AUTHORIZATION`` header for a ``token <token>`` value. If found, it will attempt to find the user that owns the token, and authenticate that user."""
def get_credentials(self, request: H... | stack_v2_sparse_classes_36k_train_009165 | 12,956 | no_license | [
{
"docstring": "Return credentials for the token. If the request is attempting to authenticate with a token, this will return a dictionary containing the token in a ``token`` key. Args: request (HttpRequest): The HTTP request from the client. Returns: dict: A dictionary containing the token in a ``token`` key, ... | 3 | stack_v2_sparse_classes_30k_val_000840 | Implement the Python class `WebAPITokenAuthBackend` described below.
Class description:
Authenticates users using their generated API token. This will check the ``HTTP_AUTHORIZATION`` header for a ``token <token>`` value. If found, it will attempt to find the user that owns the token, and authenticate that user.
Meth... | Implement the Python class `WebAPITokenAuthBackend` described below.
Class description:
Authenticates users using their generated API token. This will check the ``HTTP_AUTHORIZATION`` header for a ``token <token>`` value. If found, it will attempt to find the user that owns the token, and authenticate that user.
Meth... | 99ea69d80a3a393b0da4da3152ef26e808dd8487 | <|skeleton|>
class WebAPITokenAuthBackend:
"""Authenticates users using their generated API token. This will check the ``HTTP_AUTHORIZATION`` header for a ``token <token>`` value. If found, it will attempt to find the user that owns the token, and authenticate that user."""
def get_credentials(self, request: H... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WebAPITokenAuthBackend:
"""Authenticates users using their generated API token. This will check the ``HTTP_AUTHORIZATION`` header for a ``token <token>`` value. If found, it will attempt to find the user that owns the token, and authenticate that user."""
def get_credentials(self, request: HttpRequest) -... | the_stack_v2_python_sparse | djblets/webapi/auth/backends/api_tokens.py | chipx86/djblets | train | 2 |
8bfd94e6af41e7261260066d704758ca4723903f | [
"target_part_flat = list(target_part.recurse(classFilter=('Note', 'Rest')))\nout_stream = stream.Stream()\nout_flat = []\nskip_flag = False\nfor idx in np.arange(len(target_part_flat)):\n if embellisher.fermata_layer[idx] == 1 and (not skip_flag) and (not target_part_flat[idx].isRest):\n end_idx = self.ge... | <|body_start_0|>
target_part_flat = list(target_part.recurse(classFilter=('Note', 'Rest')))
out_stream = stream.Stream()
out_flat = []
skip_flag = False
for idx in np.arange(len(target_part_flat)):
if embellisher.fermata_layer[idx] == 1 and (not skip_flag) and (not ta... | FermataFill | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FermataFill:
def embellish(self, embellisher, target_part, target_part_name):
"""Fill in consecutive quarter notes if they both fave fermatas"""
<|body_0|>
def get_fermata_end_index(self, start_index, fermata_layer):
"""Function to return the end index of a string of... | stack_v2_sparse_classes_36k_train_009166 | 11,313 | no_license | [
{
"docstring": "Fill in consecutive quarter notes if they both fave fermatas",
"name": "embellish",
"signature": "def embellish(self, embellisher, target_part, target_part_name)"
},
{
"docstring": "Function to return the end index of a string of fermatas Parameters ---------- start_index : int i... | 2 | stack_v2_sparse_classes_30k_train_003274 | Implement the Python class `FermataFill` described below.
Class description:
Implement the FermataFill class.
Method signatures and docstrings:
- def embellish(self, embellisher, target_part, target_part_name): Fill in consecutive quarter notes if they both fave fermatas
- def get_fermata_end_index(self, start_index,... | Implement the Python class `FermataFill` described below.
Class description:
Implement the FermataFill class.
Method signatures and docstrings:
- def embellish(self, embellisher, target_part, target_part_name): Fill in consecutive quarter notes if they both fave fermatas
- def get_fermata_end_index(self, start_index,... | 64baba9d90c25fea2687eed56b54b862eb3c89c9 | <|skeleton|>
class FermataFill:
def embellish(self, embellisher, target_part, target_part_name):
"""Fill in consecutive quarter notes if they both fave fermatas"""
<|body_0|>
def get_fermata_end_index(self, start_index, fermata_layer):
"""Function to return the end index of a string of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FermataFill:
def embellish(self, embellisher, target_part, target_part_name):
"""Fill in consecutive quarter notes if they both fave fermatas"""
target_part_flat = list(target_part.recurse(classFilter=('Note', 'Rest')))
out_stream = stream.Stream()
out_flat = []
skip_fl... | the_stack_v2_python_sparse | bachmarkov/embellish/embellish.py | thewassermann/bachmarkov | train | 0 | |
ba46b2f01f4abecdb95c16af0c9daf99f98fa17d | [
"super(MLBFusion, self).__init__()\nself.linear_I = nn.Linear(I_input_hidden, mm_hidden_size)\nself.linear_T = nn.Linear(T_input_hidden, mm_hidden_size)\nself.I_activate_func = I_activate_func\nself.T_activate_func = T_activate_func\nself.dropout_I = dropout_I\nself.dropout_T = dropout_T",
"x_I = F.dropout(input_... | <|body_start_0|>
super(MLBFusion, self).__init__()
self.linear_I = nn.Linear(I_input_hidden, mm_hidden_size)
self.linear_T = nn.Linear(T_input_hidden, mm_hidden_size)
self.I_activate_func = I_activate_func
self.T_activate_func = T_activate_func
self.dropout_I = dropout_I
... | MLBFusion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLBFusion:
def __init__(self, T_input_hidden, I_input_hidden, mm_hidden_size=1200, T_activate_func=gelu, I_activate_func=gelu, dropout_T=0.5, dropout_I=0.5):
""":param T_input_hidden: Text feature size :param I_input_hidden: Image feature size :param mm_hidden_size: multimodal hidden siz... | stack_v2_sparse_classes_36k_train_009167 | 5,761 | no_license | [
{
"docstring": ":param T_input_hidden: Text feature size :param I_input_hidden: Image feature size :param mm_hidden_size: multimodal hidden size :param T_activate_func: Text activate function, must be a callable object :param I_activate_func: Image activate function, must be a callable object :param dropout_T: ... | 2 | stack_v2_sparse_classes_30k_train_002842 | Implement the Python class `MLBFusion` described below.
Class description:
Implement the MLBFusion class.
Method signatures and docstrings:
- def __init__(self, T_input_hidden, I_input_hidden, mm_hidden_size=1200, T_activate_func=gelu, I_activate_func=gelu, dropout_T=0.5, dropout_I=0.5): :param T_input_hidden: Text f... | Implement the Python class `MLBFusion` described below.
Class description:
Implement the MLBFusion class.
Method signatures and docstrings:
- def __init__(self, T_input_hidden, I_input_hidden, mm_hidden_size=1200, T_activate_func=gelu, I_activate_func=gelu, dropout_T=0.5, dropout_I=0.5): :param T_input_hidden: Text f... | 6209dc7a9f17e52dd570bbcbd1c9829a2b14f52c | <|skeleton|>
class MLBFusion:
def __init__(self, T_input_hidden, I_input_hidden, mm_hidden_size=1200, T_activate_func=gelu, I_activate_func=gelu, dropout_T=0.5, dropout_I=0.5):
""":param T_input_hidden: Text feature size :param I_input_hidden: Image feature size :param mm_hidden_size: multimodal hidden siz... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MLBFusion:
def __init__(self, T_input_hidden, I_input_hidden, mm_hidden_size=1200, T_activate_func=gelu, I_activate_func=gelu, dropout_T=0.5, dropout_I=0.5):
""":param T_input_hidden: Text feature size :param I_input_hidden: Image feature size :param mm_hidden_size: multimodal hidden size :param T_act... | the_stack_v2_python_sparse | models/base/modal_fusion.py | yiranyyu/Phrase-Grounding | train | 2 | |
0edde025936976aa089bd6cf642279cdd08c7033 | [
"self.chess_game = chess_game\nself.pieces = []\nself._load_pieces()",
"filename = 'images/chess_pieces.bmp'\npiece_ss = SpriteSheet(filename)\npiece_images = piece_ss.load_grid_images(2, 6, x_margin=64, x_padding=72, y_margin=68, y_padding=48)\ncolors = ['black', 'white']\nnames = ['king', 'queen', 'rook', 'bish... | <|body_start_0|>
self.chess_game = chess_game
self.pieces = []
self._load_pieces()
<|end_body_0|>
<|body_start_1|>
filename = 'images/chess_pieces.bmp'
piece_ss = SpriteSheet(filename)
piece_images = piece_ss.load_grid_images(2, 6, x_margin=64, x_padding=72, y_margin=68,... | Represents a set of chess pieces. Each piece is an object of the Piece class. | ChessSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChessSet:
"""Represents a set of chess pieces. Each piece is an object of the Piece class."""
def __init__(self, chess_game):
"""Initialize attributes to represent the overall set of pieces."""
<|body_0|>
def _load_pieces(self):
"""Builds the overall set: - Loads... | stack_v2_sparse_classes_36k_train_009168 | 2,009 | permissive | [
{
"docstring": "Initialize attributes to represent the overall set of pieces.",
"name": "__init__",
"signature": "def __init__(self, chess_game)"
},
{
"docstring": "Builds the overall set: - Loads images from the sprite sheet. - Creates a Piece object, and sets appropriate attributes for that pi... | 2 | stack_v2_sparse_classes_30k_train_017876 | Implement the Python class `ChessSet` described below.
Class description:
Represents a set of chess pieces. Each piece is an object of the Piece class.
Method signatures and docstrings:
- def __init__(self, chess_game): Initialize attributes to represent the overall set of pieces.
- def _load_pieces(self): Builds the... | Implement the Python class `ChessSet` described below.
Class description:
Represents a set of chess pieces. Each piece is an object of the Piece class.
Method signatures and docstrings:
- def __init__(self, chess_game): Initialize attributes to represent the overall set of pieces.
- def _load_pieces(self): Builds the... | 2cb4b45dd14a230aa0e800042e893f8dfb23beda | <|skeleton|>
class ChessSet:
"""Represents a set of chess pieces. Each piece is an object of the Piece class."""
def __init__(self, chess_game):
"""Initialize attributes to represent the overall set of pieces."""
<|body_0|>
def _load_pieces(self):
"""Builds the overall set: - Loads... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChessSet:
"""Represents a set of chess pieces. Each piece is an object of the Piece class."""
def __init__(self, chess_game):
"""Initialize attributes to represent the overall set of pieces."""
self.chess_game = chess_game
self.pieces = []
self._load_pieces()
def _loa... | the_stack_v2_python_sparse | MY_REPOS/Lambda-Resource-Static-Assets/2-resources/BLOG/Python/pcc_2e-master/beyond_pcc/chess_game/chess_set.py | bgoonz/UsefulResourceRepo2.0 | train | 10 |
ac72b15d3753c8c6976750c0b7350b07a8053b2f | [
"func = self.client.getCommandFunc('undo')\nif func is not None:\n func(('/undo', 'all', username), 'user', False)\nelse:\n self.client.sendServerMessage('Error: Could not find Undo command.')\nfunc = self.client.getCommandFunc('spec')\nif func is not None:\n func(('/spec', username), 'user', False)\nelse:... | <|body_start_0|>
func = self.client.getCommandFunc('undo')
if func is not None:
func(('/undo', 'all', username), 'user', False)
else:
self.client.sendServerMessage('Error: Could not find Undo command.')
func = self.client.getCommandFunc('spec')
if func is ... | xspec | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class xspec:
def commandXSpec(self, username, fromloc, overriderank):
"""/xspec username - Mod Undoes all builds by the user, specs them, and then kicks them."""
<|body_0|>
def commandUSpec(self, username, fromloc, overriderank):
"""/uspec username - Mod Undoes all builds ... | stack_v2_sparse_classes_36k_train_009169 | 2,046 | permissive | [
{
"docstring": "/xspec username - Mod Undoes all builds by the user, specs them, and then kicks them.",
"name": "commandXSpec",
"signature": "def commandXSpec(self, username, fromloc, overriderank)"
},
{
"docstring": "/uspec username - Mod Undoes all builds by the user and specs them.",
"nam... | 2 | stack_v2_sparse_classes_30k_train_014644 | Implement the Python class `xspec` described below.
Class description:
Implement the xspec class.
Method signatures and docstrings:
- def commandXSpec(self, username, fromloc, overriderank): /xspec username - Mod Undoes all builds by the user, specs them, and then kicks them.
- def commandUSpec(self, username, fromlo... | Implement the Python class `xspec` described below.
Class description:
Implement the xspec class.
Method signatures and docstrings:
- def commandXSpec(self, username, fromloc, overriderank): /xspec username - Mod Undoes all builds by the user, specs them, and then kicks them.
- def commandUSpec(self, username, fromlo... | 5482def8b50562fdbae980cda9b1708bfad8bffb | <|skeleton|>
class xspec:
def commandXSpec(self, username, fromloc, overriderank):
"""/xspec username - Mod Undoes all builds by the user, specs them, and then kicks them."""
<|body_0|>
def commandUSpec(self, username, fromloc, overriderank):
"""/uspec username - Mod Undoes all builds ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class xspec:
def commandXSpec(self, username, fromloc, overriderank):
"""/xspec username - Mod Undoes all builds by the user, specs them, and then kicks them."""
func = self.client.getCommandFunc('undo')
if func is not None:
func(('/undo', 'all', username), 'user', False)
... | the_stack_v2_python_sparse | core/plugins/xspec.py | TheArchives/Nexus | train | 1 | |
dc56a997b4bf8fd7b7792a023b8b2c720d61dab6 | [
"self.help_headers_color = help_headers_color or {}\nself.help_options_color = help_options_color or {}\nself.help_options_custom_colors = help_options_custom_colors or {}\nsuper().__init__(*args, **kwargs)",
"formatter = HelpColorsFormatter(width=ctx.terminal_width, max_width=ctx.max_content_width, headers_color... | <|body_start_0|>
self.help_headers_color = help_headers_color or {}
self.help_options_color = help_options_color or {}
self.help_options_custom_colors = help_options_custom_colors or {}
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
formatter = HelpColorsForma... | Click help formatting plugin. See file docstring for license. Modified from original copy to support click.style() instead of direct ANSII string formatting. | HelpColorsMixin | [
"BSD-3-Clause-Clear"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HelpColorsMixin:
"""Click help formatting plugin. See file docstring for license. Modified from original copy to support click.style() instead of direct ANSII string formatting."""
def __init__(self, help_headers_color=None, help_options_color=None, help_options_custom_colors=None, *args, **... | stack_v2_sparse_classes_36k_train_009170 | 6,420 | permissive | [
{
"docstring": "Initialize help mixin.",
"name": "__init__",
"signature": "def __init__(self, help_headers_color=None, help_options_color=None, help_options_custom_colors=None, *args, **kwargs)"
},
{
"docstring": "Format help.",
"name": "get_help",
"signature": "def get_help(self, ctx)"
... | 2 | stack_v2_sparse_classes_30k_train_016598 | Implement the Python class `HelpColorsMixin` described below.
Class description:
Click help formatting plugin. See file docstring for license. Modified from original copy to support click.style() instead of direct ANSII string formatting.
Method signatures and docstrings:
- def __init__(self, help_headers_color=None,... | Implement the Python class `HelpColorsMixin` described below.
Class description:
Click help formatting plugin. See file docstring for license. Modified from original copy to support click.style() instead of direct ANSII string formatting.
Method signatures and docstrings:
- def __init__(self, help_headers_color=None,... | 90c179f46ecc58562dbcd9ec6d761075a8699f79 | <|skeleton|>
class HelpColorsMixin:
"""Click help formatting plugin. See file docstring for license. Modified from original copy to support click.style() instead of direct ANSII string formatting."""
def __init__(self, help_headers_color=None, help_options_color=None, help_options_custom_colors=None, *args, **... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HelpColorsMixin:
"""Click help formatting plugin. See file docstring for license. Modified from original copy to support click.style() instead of direct ANSII string formatting."""
def __init__(self, help_headers_color=None, help_options_color=None, help_options_custom_colors=None, *args, **kwargs):
... | the_stack_v2_python_sparse | hyperglass/cli/formatting.py | GeeZeeS/hyperglass | train | 0 |
aa890a4d28c88cd8ecfe4c96d080df2bb08a7085 | [
"self.dense1 = Dense(self.n_hidden)\nself.dense2 = Dense(self.n_hidden)\nself.dense3 = Dense(self.n_latent)\nself.dense4 = Dense(self.n_latent)\nself.batchnorm1 = nn.BatchNorm(momentum=0.99, epsilon=0.001)\nself.batchnorm2 = nn.BatchNorm(momentum=0.99, epsilon=0.001)\nself.dropout1 = nn.Dropout(self.dropout_rate)\n... | <|body_start_0|>
self.dense1 = Dense(self.n_hidden)
self.dense2 = Dense(self.n_hidden)
self.dense3 = Dense(self.n_latent)
self.dense4 = Dense(self.n_latent)
self.batchnorm1 = nn.BatchNorm(momentum=0.99, epsilon=0.001)
self.batchnorm2 = nn.BatchNorm(momentum=0.99, epsilon=... | Encoder for Jax VAE. | FlaxEncoder | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlaxEncoder:
"""Encoder for Jax VAE."""
def setup(self):
"""Setup encoder."""
<|body_0|>
def __call__(self, x: jnp.ndarray, training: Optional[bool]=None):
"""Forward pass."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dense1 = Dense(self... | stack_v2_sparse_classes_36k_train_009171 | 7,000 | permissive | [
{
"docstring": "Setup encoder.",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Forward pass.",
"name": "__call__",
"signature": "def __call__(self, x: jnp.ndarray, training: Optional[bool]=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014674 | Implement the Python class `FlaxEncoder` described below.
Class description:
Encoder for Jax VAE.
Method signatures and docstrings:
- def setup(self): Setup encoder.
- def __call__(self, x: jnp.ndarray, training: Optional[bool]=None): Forward pass. | Implement the Python class `FlaxEncoder` described below.
Class description:
Encoder for Jax VAE.
Method signatures and docstrings:
- def setup(self): Setup encoder.
- def __call__(self, x: jnp.ndarray, training: Optional[bool]=None): Forward pass.
<|skeleton|>
class FlaxEncoder:
"""Encoder for Jax VAE."""
... | 2cf00ecef4a04dfa2d35fb0fd3cb3aa0eb101330 | <|skeleton|>
class FlaxEncoder:
"""Encoder for Jax VAE."""
def setup(self):
"""Setup encoder."""
<|body_0|>
def __call__(self, x: jnp.ndarray, training: Optional[bool]=None):
"""Forward pass."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlaxEncoder:
"""Encoder for Jax VAE."""
def setup(self):
"""Setup encoder."""
self.dense1 = Dense(self.n_hidden)
self.dense2 = Dense(self.n_hidden)
self.dense3 = Dense(self.n_latent)
self.dense4 = Dense(self.n_latent)
self.batchnorm1 = nn.BatchNorm(momentum... | the_stack_v2_python_sparse | scvi/module/_jaxvae.py | jacobkimmel/scVI | train | 0 |
3f55621c031b8444134a82c02601f0f41b772268 | [
"def dfs(node, s):\n \"\"\"\n :ret: true, false\n \"\"\"\n if not node:\n return False\n if not node.left and (not node.right) and (s == node.val):\n return True\n lv = rv = False\n if node.left:\n lv = dfs(node.left, s - node.val)\n if node.right:\n ... | <|body_start_0|>
def dfs(node, s):
"""
:ret: true, false
"""
if not node:
return False
if not node.left and (not node.right) and (s == node.val):
return True
lv = rv = False
if nod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasPathSum(self, root, s):
""":type root: TreeNode :type sum: int :rtype: bool using minus"""
<|body_0|>
def rewrite(self, root, s):
""":type root: TreeNode :type sum: int :rtype: bool using minus!"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_009172 | 2,306 | no_license | [
{
"docstring": ":type root: TreeNode :type sum: int :rtype: bool using minus",
"name": "hasPathSum",
"signature": "def hasPathSum(self, root, s)"
},
{
"docstring": ":type root: TreeNode :type sum: int :rtype: bool using minus!",
"name": "rewrite",
"signature": "def rewrite(self, root, s)... | 2 | stack_v2_sparse_classes_30k_train_021523 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum(self, root, s): :type root: TreeNode :type sum: int :rtype: bool using minus
- def rewrite(self, root, s): :type root: TreeNode :type sum: int :rtype: bool using m... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum(self, root, s): :type root: TreeNode :type sum: int :rtype: bool using minus
- def rewrite(self, root, s): :type root: TreeNode :type sum: int :rtype: bool using m... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def hasPathSum(self, root, s):
""":type root: TreeNode :type sum: int :rtype: bool using minus"""
<|body_0|>
def rewrite(self, root, s):
""":type root: TreeNode :type sum: int :rtype: bool using minus!"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hasPathSum(self, root, s):
""":type root: TreeNode :type sum: int :rtype: bool using minus"""
def dfs(node, s):
"""
:ret: true, false
"""
if not node:
return False
if not node.left and (no... | the_stack_v2_python_sparse | depth-first-search/112_Path_Sum.py | vsdrun/lc_public | train | 6 | |
ff57d5d6f3ce7ceb296e76aee369d25fa082b2b7 | [
"dir_path = dir_path.rstrip('/')\nlog.i('- start merge: [%s]' % dir_path)\nlines = [self.Parsed(dt.min, b'')]\nfiles = list(self.__files(dir_path))\nif len(files) == 0:\n return False\nfor l in list(fileinput.input(files, mode='rb')):\n p = self.__parse(l)\n if p.time is None:\n lines[-1].line = lin... | <|body_start_0|>
dir_path = dir_path.rstrip('/')
log.i('- start merge: [%s]' % dir_path)
lines = [self.Parsed(dt.min, b'')]
files = list(self.__files(dir_path))
if len(files) == 0:
return False
for l in list(fileinput.input(files, mode='rb')):
p = ... | Merge multiple log files. | Merge | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Merge:
"""Merge multiple log files."""
def exec(self, dir_path):
"""Exec merge files and sort by timestamp. :param str dir_path: Directory path which contains log files. :return: Merge result. :rtype bool"""
<|body_0|>
def __files(self, dir_path):
"""Find files. ... | stack_v2_sparse_classes_36k_train_009173 | 2,373 | permissive | [
{
"docstring": "Exec merge files and sort by timestamp. :param str dir_path: Directory path which contains log files. :return: Merge result. :rtype bool",
"name": "exec",
"signature": "def exec(self, dir_path)"
},
{
"docstring": "Find files. :return: Iterator[str]",
"name": "__files",
"s... | 3 | stack_v2_sparse_classes_30k_train_005799 | Implement the Python class `Merge` described below.
Class description:
Merge multiple log files.
Method signatures and docstrings:
- def exec(self, dir_path): Exec merge files and sort by timestamp. :param str dir_path: Directory path which contains log files. :return: Merge result. :rtype bool
- def __files(self, di... | Implement the Python class `Merge` described below.
Class description:
Merge multiple log files.
Method signatures and docstrings:
- def exec(self, dir_path): Exec merge files and sort by timestamp. :param str dir_path: Directory path which contains log files. :return: Merge result. :rtype bool
- def __files(self, di... | 3d2675e784fb535023ad8b12933c27fd65c2fe2e | <|skeleton|>
class Merge:
"""Merge multiple log files."""
def exec(self, dir_path):
"""Exec merge files and sort by timestamp. :param str dir_path: Directory path which contains log files. :return: Merge result. :rtype bool"""
<|body_0|>
def __files(self, dir_path):
"""Find files. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Merge:
"""Merge multiple log files."""
def exec(self, dir_path):
"""Exec merge files and sort by timestamp. :param str dir_path: Directory path which contains log files. :return: Merge result. :rtype bool"""
dir_path = dir_path.rstrip('/')
log.i('- start merge: [%s]' % dir_path)
... | the_stack_v2_python_sparse | logger/merge.py | ujiro99/auto_logger | train | 0 |
2e4376f7331777b5521feda55dd6f9bcc1b75dff | [
"step = 0\nfor num in chips:\n if num % 2 == 1:\n step += 1\nreturn min(step, len(chips) - step)",
"step1, step2 = (0, 0)\nfor num in chips:\n if num % 2 == 1:\n step1 += 1\n else:\n step2 += 1\nreturn min(step1, step2)"
] | <|body_start_0|>
step = 0
for num in chips:
if num % 2 == 1:
step += 1
return min(step, len(chips) - step)
<|end_body_0|>
<|body_start_1|>
step1, step2 = (0, 0)
for num in chips:
if num % 2 == 1:
step1 += 1
else... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def min_cost_to_move_chips(self, chips: List[int]) -> int:
"""摆筹码代价最小 Args: chips: 数组 Returns: 摆筹码"""
<|body_0|>
def min_cost_to_move_chips2(self, chips: List[int]) -> int:
"""摆筹码代价最小 Args: chips: 数组 Returns: 摆筹码"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_009174 | 2,366 | permissive | [
{
"docstring": "摆筹码代价最小 Args: chips: 数组 Returns: 摆筹码",
"name": "min_cost_to_move_chips",
"signature": "def min_cost_to_move_chips(self, chips: List[int]) -> int"
},
{
"docstring": "摆筹码代价最小 Args: chips: 数组 Returns: 摆筹码",
"name": "min_cost_to_move_chips2",
"signature": "def min_cost_to_mov... | 2 | stack_v2_sparse_classes_30k_train_016671 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def min_cost_to_move_chips(self, chips: List[int]) -> int: 摆筹码代价最小 Args: chips: 数组 Returns: 摆筹码
- def min_cost_to_move_chips2(self, chips: List[int]) -> int: 摆筹码代价最小 Args: chips:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def min_cost_to_move_chips(self, chips: List[int]) -> int: 摆筹码代价最小 Args: chips: 数组 Returns: 摆筹码
- def min_cost_to_move_chips2(self, chips: List[int]) -> int: 摆筹码代价最小 Args: chips:... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def min_cost_to_move_chips(self, chips: List[int]) -> int:
"""摆筹码代价最小 Args: chips: 数组 Returns: 摆筹码"""
<|body_0|>
def min_cost_to_move_chips2(self, chips: List[int]) -> int:
"""摆筹码代价最小 Args: chips: 数组 Returns: 摆筹码"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def min_cost_to_move_chips(self, chips: List[int]) -> int:
"""摆筹码代价最小 Args: chips: 数组 Returns: 摆筹码"""
step = 0
for num in chips:
if num % 2 == 1:
step += 1
return min(step, len(chips) - step)
def min_cost_to_move_chips2(self, chips: Li... | the_stack_v2_python_sparse | src/leetcodepython/array/play_with_chips_1217.py | zhangyu345293721/leetcode | train | 101 | |
533ae1e65676f3bed6656686bfaae22f1b4e042a | [
"self.db = db\nself.config = config\nself.slides = self.db[self.config['db_collection']]",
"if not ObjectId.is_valid(id):\n resp = {'status': 404, 'message': 'Invalid slide Id ' + id}\n return Response(dumps(resp), status=404, mimetype='application/json')\nimage = self.slides.find_one({'_id': ObjectId(id)},... | <|body_start_0|>
self.db = db
self.config = config
self.slides = self.db[self.config['db_collection']]
<|end_body_0|>
<|body_start_1|>
if not ObjectId.is_valid(id):
resp = {'status': 404, 'message': 'Invalid slide Id ' + id}
return Response(dumps(resp), status=40... | Slide | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Slide:
def __init__(self, db, config):
"""initialize Slide resource Args: db: mongo db connection config: application configurations opt: deep zoom configurations Returns: None"""
<|body_0|>
def get(self, id):
"""Get slide information --- tags: - Slide parameters: - ... | stack_v2_sparse_classes_36k_train_009175 | 2,541 | permissive | [
{
"docstring": "initialize Slide resource Args: db: mongo db connection config: application configurations opt: deep zoom configurations Returns: None",
"name": "__init__",
"signature": "def __init__(self, db, config)"
},
{
"docstring": "Get slide information --- tags: - Slide parameters: - in: ... | 3 | stack_v2_sparse_classes_30k_train_013271 | Implement the Python class `Slide` described below.
Class description:
Implement the Slide class.
Method signatures and docstrings:
- def __init__(self, db, config): initialize Slide resource Args: db: mongo db connection config: application configurations opt: deep zoom configurations Returns: None
- def get(self, i... | Implement the Python class `Slide` described below.
Class description:
Implement the Slide class.
Method signatures and docstrings:
- def __init__(self, db, config): initialize Slide resource Args: db: mongo db connection config: application configurations opt: deep zoom configurations Returns: None
- def get(self, i... | 86f89f08dcfdab00ca295a6009820c02d84f7074 | <|skeleton|>
class Slide:
def __init__(self, db, config):
"""initialize Slide resource Args: db: mongo db connection config: application configurations opt: deep zoom configurations Returns: None"""
<|body_0|>
def get(self, id):
"""Get slide information --- tags: - Slide parameters: - ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Slide:
def __init__(self, db, config):
"""initialize Slide resource Args: db: mongo db connection config: application configurations opt: deep zoom configurations Returns: None"""
self.db = db
self.config = config
self.slides = self.db[self.config['db_collection']]
def get... | the_stack_v2_python_sparse | api/routes/v1/Slide.py | dgutman/ADRCPathViewer | train | 1 | |
14bf3295d4b8eb60dfc5643d85db80b743727066 | [
"stats = kwargs['stats']\nif day == 0 or not stats:\n return '<td class=\"noday\"> </td>'\nstat = next((stat for stat in stats if stat.date == dt.date(kwargs['theyear'], kwargs['themonth'], day)), None)\nif not stat:\n return '<td class=\"noday\"> </td>'\nparams = dict(defaults.units, **stat.dict)\n... | <|body_start_0|>
stats = kwargs['stats']
if day == 0 or not stats:
return '<td class="noday"> </td>'
stat = next((stat for stat in stats if stat.date == dt.date(kwargs['theyear'], kwargs['themonth'], day)), None)
if not stat:
return '<td class="noday"> <... | Генератор html-календаря с погодой | CalendarMaker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalendarMaker:
"""Генератор html-календаря с погодой"""
def formatday(self, day, weekday, **kwargs):
"""Возвращает HTML код ячейки календаря :param day: день месяца :param weekday: день недели :param kwargs: в кваргах передаётся stats - список объектов класса Stats :return: str Html ... | stack_v2_sparse_classes_36k_train_009176 | 11,050 | no_license | [
{
"docstring": "Возвращает HTML код ячейки календаря :param day: день месяца :param weekday: день недели :param kwargs: в кваргах передаётся stats - список объектов класса Stats :return: str Html код ячейки календаря с прогнозом",
"name": "formatday",
"signature": "def formatday(self, day, weekday, **kw... | 5 | null | Implement the Python class `CalendarMaker` described below.
Class description:
Генератор html-календаря с погодой
Method signatures and docstrings:
- def formatday(self, day, weekday, **kwargs): Возвращает HTML код ячейки календаря :param day: день месяца :param weekday: день недели :param kwargs: в кваргах передаётс... | Implement the Python class `CalendarMaker` described below.
Class description:
Генератор html-календаря с погодой
Method signatures and docstrings:
- def formatday(self, day, weekday, **kwargs): Возвращает HTML код ячейки календаря :param day: день месяца :param weekday: день недели :param kwargs: в кваргах передаётс... | d2c0014dffccadb8232a1034e4ea9b427016a1d1 | <|skeleton|>
class CalendarMaker:
"""Генератор html-календаря с погодой"""
def formatday(self, day, weekday, **kwargs):
"""Возвращает HTML код ячейки календаря :param day: день месяца :param weekday: день недели :param kwargs: в кваргах передаётся stats - список объектов класса Stats :return: str Html ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CalendarMaker:
"""Генератор html-календаря с погодой"""
def formatday(self, day, weekday, **kwargs):
"""Возвращает HTML код ячейки календаря :param day: день месяца :param weekday: день недели :param kwargs: в кваргах передаётся stats - список объектов класса Stats :return: str Html код ячейки ка... | the_stack_v2_python_sparse | lesson_016/engine/image_maker.py | glotyuids/skillbox_learning | train | 0 |
a57de99f40ac58259136f3d63db1aa7f0d3d1c2a | [
"result = []\nfor i in range(len(temperatures)):\n for j in range(i + 1, len(temperatures)):\n if temperatures[j] > temperatures[i]:\n result.append(j - i)\n break\n if j == len(temperatures) - 1 and temperatures[j] <= temperatures[i]:\n result.append(0)\nresult.app... | <|body_start_0|>
result = []
for i in range(len(temperatures)):
for j in range(i + 1, len(temperatures)):
if temperatures[j] > temperatures[i]:
result.append(j - i)
break
if j == len(temperatures) - 1 and temperatures[j]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dailyTemperatures1(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_009177 | 1,544 | no_license | [
{
"docstring": ":type temperatures: List[int] :rtype: List[int]",
"name": "dailyTemperatures1",
"signature": "def dailyTemperatures1(self, temperatures)"
},
{
"docstring": ":type temperatures: List[int] :rtype: List[int]",
"name": "dailyTemperatures",
"signature": "def dailyTemperatures(... | 2 | stack_v2_sparse_classes_30k_train_010693 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures1(self, temperatures): :type temperatures: List[int] :rtype: List[int]
- def dailyTemperatures(self, temperatures): :type temperatures: List[int] :rtype: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures1(self, temperatures): :type temperatures: List[int] :rtype: List[int]
- def dailyTemperatures(self, temperatures): :type temperatures: List[int] :rtype: Lis... | 96e847591aa6ea7ea285dbcfc1c9bcfc32026de5 | <|skeleton|>
class Solution:
def dailyTemperatures1(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def dailyTemperatures1(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
result = []
for i in range(len(temperatures)):
for j in range(i + 1, len(temperatures)):
if temperatures[j] > temperatures[i]:
res... | the_stack_v2_python_sparse | DueueStack/L739_daily-temperatures.py | lihujun101/LeetCode | train | 0 | |
ce2be1f9aaeb877660e30745892967dae1848032 | [
"params = super().get_default_params()\nparams.add(engine.param.Param(name='num_dense_units', value=512, hyper_space=engine.hyper_spaces.quniform(low=32, high=1024), validator=lambda x: 0 < x < 2048))\nreturn params",
"x_in = [keras.layers.Input(shape) for shape in self._params['input_shapes']]\nx = keras.layers.... | <|body_start_0|>
params = super().get_default_params()
params.add(engine.param.Param(name='num_dense_units', value=512, hyper_space=engine.hyper_spaces.quniform(low=32, high=1024), validator=lambda x: 0 < x < 2048))
return params
<|end_body_0|>
<|body_start_1|>
x_in = [keras.layers.Inpu... | A simple densely connected baseline model. Examples: >>> model = DenseBaselineModel() >>> model.params['input_shapes'] = [(30,), (30,)] >>> model.params['num_dense_units'] = 1024 >>> model.guess_and_fill_missing_params() >>> model.build() | DenseBaselineModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DenseBaselineModel:
"""A simple densely connected baseline model. Examples: >>> model = DenseBaselineModel() >>> model.params['input_shapes'] = [(30,), (30,)] >>> model.params['num_dense_units'] = 1024 >>> model.guess_and_fill_missing_params() >>> model.build()"""
def get_default_params(cls)... | stack_v2_sparse_classes_36k_train_009178 | 1,299 | permissive | [
{
"docstring": ":return: model default parameters.",
"name": "get_default_params",
"signature": "def get_default_params(cls) -> engine.ParamTable"
},
{
"docstring": "Model structure.",
"name": "build",
"signature": "def build(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012311 | Implement the Python class `DenseBaselineModel` described below.
Class description:
A simple densely connected baseline model. Examples: >>> model = DenseBaselineModel() >>> model.params['input_shapes'] = [(30,), (30,)] >>> model.params['num_dense_units'] = 1024 >>> model.guess_and_fill_missing_params() >>> model.buil... | Implement the Python class `DenseBaselineModel` described below.
Class description:
A simple densely connected baseline model. Examples: >>> model = DenseBaselineModel() >>> model.params['input_shapes'] = [(30,), (30,)] >>> model.params['num_dense_units'] = 1024 >>> model.guess_and_fill_missing_params() >>> model.buil... | e49d619a52b2e96b6f0e8e76164d76f623210198 | <|skeleton|>
class DenseBaselineModel:
"""A simple densely connected baseline model. Examples: >>> model = DenseBaselineModel() >>> model.params['input_shapes'] = [(30,), (30,)] >>> model.params['num_dense_units'] = 1024 >>> model.guess_and_fill_missing_params() >>> model.build()"""
def get_default_params(cls)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DenseBaselineModel:
"""A simple densely connected baseline model. Examples: >>> model = DenseBaselineModel() >>> model.params['input_shapes'] = [(30,), (30,)] >>> model.params['num_dense_units'] = 1024 >>> model.guess_and_fill_missing_params() >>> model.build()"""
def get_default_params(cls) -> engine.Pa... | the_stack_v2_python_sparse | matchzoo/models/dense_baseline_model.py | JacobPolloreno/MatchZoo | train | 0 |
de4e5aea3ea7a3c3985041a7146e4182c0628b12 | [
"if not fs.is_valid_project_root(root_dir):\n raise TrestleError(f'Provided root directory {str(root_dir)} is not a valid Trestle root directory.')\nself.root_dir = root_dir\nself.model_type = model_type\nself.model_name = name\nself.model_alias = classname_to_alias(self.model_type.__name__, 'json')\nif parser.t... | <|body_start_0|>
if not fs.is_valid_project_root(root_dir):
raise TrestleError(f'Provided root directory {str(root_dir)} is not a valid Trestle root directory.')
self.root_dir = root_dir
self.model_type = model_type
self.model_name = name
self.model_alias = classname_... | Object representing OSCAL models in repository for programmatic manipulation. | ManagedOSCAL | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManagedOSCAL:
"""Object representing OSCAL models in repository for programmatic manipulation."""
def __init__(self, root_dir: pathlib.Path, model_type: Type[OscalBaseModel], name: str) -> None:
"""Initialize repository OSCAL model object."""
<|body_0|>
def read(self) ->... | stack_v2_sparse_classes_36k_train_009179 | 16,368 | permissive | [
{
"docstring": "Initialize repository OSCAL model object.",
"name": "__init__",
"signature": "def __init__(self, root_dir: pathlib.Path, model_type: Type[OscalBaseModel], name: str) -> None"
},
{
"docstring": "Read OSCAL model from repository.",
"name": "read",
"signature": "def read(sel... | 6 | stack_v2_sparse_classes_30k_train_007142 | Implement the Python class `ManagedOSCAL` described below.
Class description:
Object representing OSCAL models in repository for programmatic manipulation.
Method signatures and docstrings:
- def __init__(self, root_dir: pathlib.Path, model_type: Type[OscalBaseModel], name: str) -> None: Initialize repository OSCAL m... | Implement the Python class `ManagedOSCAL` described below.
Class description:
Object representing OSCAL models in repository for programmatic manipulation.
Method signatures and docstrings:
- def __init__(self, root_dir: pathlib.Path, model_type: Type[OscalBaseModel], name: str) -> None: Initialize repository OSCAL m... | 969c10eceb73202d2b7856bac598f9b11afc696e | <|skeleton|>
class ManagedOSCAL:
"""Object representing OSCAL models in repository for programmatic manipulation."""
def __init__(self, root_dir: pathlib.Path, model_type: Type[OscalBaseModel], name: str) -> None:
"""Initialize repository OSCAL model object."""
<|body_0|>
def read(self) ->... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManagedOSCAL:
"""Object representing OSCAL models in repository for programmatic manipulation."""
def __init__(self, root_dir: pathlib.Path, model_type: Type[OscalBaseModel], name: str) -> None:
"""Initialize repository OSCAL model object."""
if not fs.is_valid_project_root(root_dir):
... | the_stack_v2_python_sparse | trestle/core/repository.py | xee5ch/compliance-trestle | train | 0 |
70a48bbff8040b7574bf27c5d3a333ad7490989e | [
"exc_infos = []\nfor _ in xrange(num):\n exc_infos.extend(failures_lib.CreateExceptInfo(cls(message), traceback))\nreturn exc_infos",
"self.assertTrue(failures_lib.CompoundFailure().HasEmptyList())\nexc_infos = self._CreateExceptInfos(KeyError)\nself.assertFalse(failures_lib.CompoundFailure(exc_infos=exc_infos... | <|body_start_0|>
exc_infos = []
for _ in xrange(num):
exc_infos.extend(failures_lib.CreateExceptInfo(cls(message), traceback))
return exc_infos
<|end_body_0|>
<|body_start_1|>
self.assertTrue(failures_lib.CompoundFailure().HasEmptyList())
exc_infos = self._CreateExce... | Test the CompoundFailure class. | CompoundFailureTest | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompoundFailureTest:
"""Test the CompoundFailure class."""
def _CreateExceptInfos(self, cls, message='', traceback='', num=1):
"""A helper function to create a list of ExceptInfo objects."""
<|body_0|>
def testHasEmptyList(self):
"""Tests the HasEmptyList method.... | stack_v2_sparse_classes_36k_train_009180 | 9,373 | permissive | [
{
"docstring": "A helper function to create a list of ExceptInfo objects.",
"name": "_CreateExceptInfos",
"signature": "def _CreateExceptInfos(self, cls, message='', traceback='', num=1)"
},
{
"docstring": "Tests the HasEmptyList method.",
"name": "testHasEmptyList",
"signature": "def te... | 6 | null | Implement the Python class `CompoundFailureTest` described below.
Class description:
Test the CompoundFailure class.
Method signatures and docstrings:
- def _CreateExceptInfos(self, cls, message='', traceback='', num=1): A helper function to create a list of ExceptInfo objects.
- def testHasEmptyList(self): Tests the... | Implement the Python class `CompoundFailureTest` described below.
Class description:
Test the CompoundFailure class.
Method signatures and docstrings:
- def _CreateExceptInfos(self, cls, message='', traceback='', num=1): A helper function to create a list of ExceptInfo objects.
- def testHasEmptyList(self): Tests the... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class CompoundFailureTest:
"""Test the CompoundFailure class."""
def _CreateExceptInfos(self, cls, message='', traceback='', num=1):
"""A helper function to create a list of ExceptInfo objects."""
<|body_0|>
def testHasEmptyList(self):
"""Tests the HasEmptyList method.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompoundFailureTest:
"""Test the CompoundFailure class."""
def _CreateExceptInfos(self, cls, message='', traceback='', num=1):
"""A helper function to create a list of ExceptInfo objects."""
exc_infos = []
for _ in xrange(num):
exc_infos.extend(failures_lib.CreateExcep... | the_stack_v2_python_sparse | third_party/chromite/cbuildbot/failures_lib_unittest.py | metux/chromium-suckless | train | 5 |
aa3e5ba23c0ac42486b030cd4d6a66b466ff0d1e | [
"self.cache_size = 0\nself.cache_capacity = capacity\nself.cache = dict()\nself.list = List()",
"if key not in self.cache:\n return -1\nreturn_value = self.cache[key].value\nself.list.move_node_to_front(self.cache[key])\nreturn return_value",
"if key not in self.cache:\n if self.cache_size == self.cache_c... | <|body_start_0|>
self.cache_size = 0
self.cache_capacity = capacity
self.cache = dict()
self.list = List()
<|end_body_0|>
<|body_start_1|>
if key not in self.cache:
return -1
return_value = self.cache[key].value
self.list.move_node_to_front(self.cache... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_009181 | 4,037 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 1dec441f1975d402d093031569cfd301eb71d465 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.cache_size = 0
self.cache_capacity = capacity
self.cache = dict()
self.list = List()
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.cache:
re... | the_stack_v2_python_sparse | 146-lru-cache.py | franktank/py-practice | train | 1 | |
e1419476106d719fc42ec0c79667826f79301a57 | [
"if node.op == 'call_function':\n if node.target in (len, operator.is_, operator.is_not, operator.contains):\n return True\nelif node.op == 'call_method':\n if isinstance(node.args[0], Node) and isinstance(model_speedup.node_infos[node.args[0]].output_origin, torch.Tensor):\n if node.target in (... | <|body_start_0|>
if node.op == 'call_function':
if node.target in (len, operator.is_, operator.is_not, operator.contains):
return True
elif node.op == 'call_method':
if isinstance(node.args[0], Node) and isinstance(model_speedup.node_infos[node.args[0]].output_ori... | For some ops that will not produce masks. | NoMaskUpdater | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoMaskUpdater:
"""For some ops that will not produce masks."""
def detect(self, model_speedup: 'ModelSpeedup', node: Node) -> bool:
"""the default MaskUpdater for operators that will not change mask value"""
<|body_0|>
def direct_update_process(self, model_speedup: 'Mode... | stack_v2_sparse_classes_36k_train_009182 | 20,408 | permissive | [
{
"docstring": "the default MaskUpdater for operators that will not change mask value",
"name": "detect",
"signature": "def detect(self, model_speedup: 'ModelSpeedup', node: Node) -> bool"
},
{
"docstring": "get all input from node_info.output_randomize and execute the node calc the out_mask and... | 2 | null | Implement the Python class `NoMaskUpdater` described below.
Class description:
For some ops that will not produce masks.
Method signatures and docstrings:
- def detect(self, model_speedup: 'ModelSpeedup', node: Node) -> bool: the default MaskUpdater for operators that will not change mask value
- def direct_update_pr... | Implement the Python class `NoMaskUpdater` described below.
Class description:
For some ops that will not produce masks.
Method signatures and docstrings:
- def detect(self, model_speedup: 'ModelSpeedup', node: Node) -> bool: the default MaskUpdater for operators that will not change mask value
- def direct_update_pr... | b84d25bec15ece54bf1703b1acb15d9f8919f656 | <|skeleton|>
class NoMaskUpdater:
"""For some ops that will not produce masks."""
def detect(self, model_speedup: 'ModelSpeedup', node: Node) -> bool:
"""the default MaskUpdater for operators that will not change mask value"""
<|body_0|>
def direct_update_process(self, model_speedup: 'Mode... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoMaskUpdater:
"""For some ops that will not produce masks."""
def detect(self, model_speedup: 'ModelSpeedup', node: Node) -> bool:
"""the default MaskUpdater for operators that will not change mask value"""
if node.op == 'call_function':
if node.target in (len, operator.is_, ... | the_stack_v2_python_sparse | nni/compression/speedup/mask_updater.py | Eurus-Holmes/nni | train | 3 |
7378ae5ad74753ba51e41a50533d20e75802c923 | [
"if not api_url:\n raise ValueError('Invalid URL')\nself.url = api_url\nself.auth = NewsApiAuth(api_key=api_key)",
"if not keyword:\n raise ValueError('Invalid keyword')\nurl_params = {'q': keyword, 'language': _DEFAULT_LANGUAGE, 'sortBy': _RELEVANCY, 'from': date_from.strftime('%Y-%m-%d'), 'pageSize': page... | <|body_start_0|>
if not api_url:
raise ValueError('Invalid URL')
self.url = api_url
self.auth = NewsApiAuth(api_key=api_key)
<|end_body_0|>
<|body_start_1|>
if not keyword:
raise ValueError('Invalid keyword')
url_params = {'q': keyword, 'language': _DEFAU... | Defines new object to collect News APi information. Attributes: url: (str) HTTP URL to contact API. auth: (requests) Corresponds to key to authenticate News Api. | NewsApiClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewsApiClient:
"""Defines new object to collect News APi information. Attributes: url: (str) HTTP URL to contact API. auth: (requests) Corresponds to key to authenticate News Api."""
def __init__(self, api_key, api_url):
"""Constructor to define API key and URL. Args: api_key: (str) ... | stack_v2_sparse_classes_36k_train_009183 | 14,300 | permissive | [
{
"docstring": "Constructor to define API key and URL. Args: api_key: (str) Corresponds to key to authenticate News Api. api_url: (str) URL to contact API. Raises: ValueError: Invalid URL.",
"name": "__init__",
"signature": "def __init__(self, api_key, api_url)"
},
{
"docstring": ":param keyword... | 3 | stack_v2_sparse_classes_30k_train_011862 | Implement the Python class `NewsApiClient` described below.
Class description:
Defines new object to collect News APi information. Attributes: url: (str) HTTP URL to contact API. auth: (requests) Corresponds to key to authenticate News Api.
Method signatures and docstrings:
- def __init__(self, api_key, api_url): Con... | Implement the Python class `NewsApiClient` described below.
Class description:
Defines new object to collect News APi information. Attributes: url: (str) HTTP URL to contact API. auth: (requests) Corresponds to key to authenticate News Api.
Method signatures and docstrings:
- def __init__(self, api_key, api_url): Con... | c27812e6b846eb1e28ec0c6e8508e18886e37617 | <|skeleton|>
class NewsApiClient:
"""Defines new object to collect News APi information. Attributes: url: (str) HTTP URL to contact API. auth: (requests) Corresponds to key to authenticate News Api."""
def __init__(self, api_key, api_url):
"""Constructor to define API key and URL. Args: api_key: (str) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewsApiClient:
"""Defines new object to collect News APi information. Attributes: url: (str) HTTP URL to contact API. auth: (requests) Corresponds to key to authenticate News Api."""
def __init__(self, api_key, api_url):
"""Constructor to define API key and URL. Args: api_key: (str) Corresponds t... | the_stack_v2_python_sparse | mini/app.py | gogasca/news_ml | train | 4 |
db986b3bb32571e73fc853dc8e92970869a72dd2 | [
"super().__init__()\nself.property_set_list = property_set_list\nself.backtrack_name = f'{prefix}_minimum_point_state'\nself.minimum_reached = f'{prefix}_minimum_point'\nself.backtrack_depth = backtrack_depth",
"score = tuple((self.property_set[x] for x in self.property_set_list))\nstate = self.property_set[self.... | <|body_start_0|>
super().__init__()
self.property_set_list = property_set_list
self.backtrack_name = f'{prefix}_minimum_point_state'
self.minimum_reached = f'{prefix}_minimum_point'
self.backtrack_depth = backtrack_depth
<|end_body_0|>
<|body_start_1|>
score = tuple((sel... | Check if the DAG has reached a relative semi-stable point over previous runs This pass is similar to the :class:`~.FixedPoint` transpiler pass and is intended primarily to be used to set a loop break condition in the property set. However, unlike the :class:`~.FixedPoint` class which only sets the condition if 2 consec... | MinimumPoint | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinimumPoint:
"""Check if the DAG has reached a relative semi-stable point over previous runs This pass is similar to the :class:`~.FixedPoint` transpiler pass and is intended primarily to be used to set a loop break condition in the property set. However, unlike the :class:`~.FixedPoint` class w... | stack_v2_sparse_classes_36k_train_009184 | 5,409 | permissive | [
{
"docstring": "Initialize an instance of this pass Args: property_set_list (list): A list of property set keys that will be used to evaluate the local minimum. The values of these property set keys will be used as a tuple for comparison prefix (str): The prefix to use for the property set key that is used for ... | 2 | null | Implement the Python class `MinimumPoint` described below.
Class description:
Check if the DAG has reached a relative semi-stable point over previous runs This pass is similar to the :class:`~.FixedPoint` transpiler pass and is intended primarily to be used to set a loop break condition in the property set. However, u... | Implement the Python class `MinimumPoint` described below.
Class description:
Check if the DAG has reached a relative semi-stable point over previous runs This pass is similar to the :class:`~.FixedPoint` transpiler pass and is intended primarily to be used to set a loop break condition in the property set. However, u... | 0b51250e219ca303654fc28a318c21366584ccd3 | <|skeleton|>
class MinimumPoint:
"""Check if the DAG has reached a relative semi-stable point over previous runs This pass is similar to the :class:`~.FixedPoint` transpiler pass and is intended primarily to be used to set a loop break condition in the property set. However, unlike the :class:`~.FixedPoint` class w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MinimumPoint:
"""Check if the DAG has reached a relative semi-stable point over previous runs This pass is similar to the :class:`~.FixedPoint` transpiler pass and is intended primarily to be used to set a loop break condition in the property set. However, unlike the :class:`~.FixedPoint` class which only set... | the_stack_v2_python_sparse | qiskit/transpiler/passes/utils/minimum_point.py | 1ucian0/qiskit-terra | train | 6 |
e05c94385259b4a27a8898fd11c194dd761a9f6f | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SharedInsight()",
"from .entity import Entity\nfrom .resource_reference import ResourceReference\nfrom .resource_visualization import ResourceVisualization\nfrom .sharing_detail import SharingDetail\nfrom .entity import Entity\nfrom .r... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SharedInsight()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .resource_reference import ResourceReference
from .resource_visualization import ResourceVisualiza... | SharedInsight | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SharedInsight:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedInsight:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k_train_009185 | 4,000 | 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: SharedInsight",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | stack_v2_sparse_classes_30k_train_004603 | Implement the Python class `SharedInsight` described below.
Class description:
Implement the SharedInsight class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedInsight: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `SharedInsight` described below.
Class description:
Implement the SharedInsight class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedInsight: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SharedInsight:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedInsight:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SharedInsight:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedInsight:
"""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: SharedInsigh... | the_stack_v2_python_sparse | msgraph/generated/models/shared_insight.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
0401ca140f9554023f67c5f495962b8d88356057 | [
"import collections\ncounter = collections.Counter(nums)\nn_2 = len(nums) // 2\nfor key in counter.keys():\n value = counter.get(key)\n if value > n_2:\n return key",
"temp = nums[0]\ncount = 1\nfor i in range(1, len(nums)):\n if count == 0:\n count += 1\n temp = nums[i]\n elif te... | <|body_start_0|>
import collections
counter = collections.Counter(nums)
n_2 = len(nums) // 2
for key in counter.keys():
value = counter.get(key)
if value > n_2:
return key
<|end_body_0|>
<|body_start_1|>
temp = nums[0]
count = 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def majorityElement2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import collections
counter =... | stack_v2_sparse_classes_36k_train_009186 | 3,022 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "majorityElement",
"signature": "def majorityElement(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "majorityElement2",
"signature": "def majorityElement2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement2(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 majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def ma... | e3fa905ea46f03b56cde662d1d7a03c4af82773a | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def majorityElement2(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 majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
import collections
counter = collections.Counter(nums)
n_2 = len(nums) // 2
for key in counter.keys():
value = counter.get(key)
if value > n_2:
ret... | the_stack_v2_python_sparse | pyPractice/algoproblem/MajorityElement_169.py | bing1zhi2/algorithmPractice | train | 0 | |
1c6c69e12eccccc3287fa81fdd1566bbcab1641a | [
"if columns is not None:\n if isinstance(columns, list) or isinstance(columns, tuple):\n self.columns = columns\n else:\n raise NameError('Invalid type {}'.format(type(columns)))\nelse:\n self.columns = columns\nself.random_state = random_state",
"if not isinstance(X, pd.core.frame.DataFram... | <|body_start_0|>
if columns is not None:
if isinstance(columns, list) or isinstance(columns, tuple):
self.columns = columns
else:
raise NameError('Invalid type {}'.format(type(columns)))
else:
self.columns = columns
self.random_... | This transformer select features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FeatureSelector/ | FeatureSelector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureSelector:
"""This transformer select features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FeatureSelector/"""
def __init__(self, columns=None... | stack_v2_sparse_classes_36k_train_009187 | 6,690 | permissive | [
{
"docstring": "Init replace missing values.",
"name": "__init__",
"signature": "def __init__(self, columns=None, random_state=99)"
},
{
"docstring": "Gets the columns to make a replace missing values. Parameters ---------- X : {Dataframe}, shape = [n_samples, n_features] Dataframe, where n_samp... | 3 | stack_v2_sparse_classes_30k_train_005248 | Implement the Python class `FeatureSelector` described below.
Class description:
This transformer select features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FeatureSelector/
... | Implement the Python class `FeatureSelector` described below.
Class description:
This transformer select features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FeatureSelector/
... | e768a4cad150b35fb5bf543ab28aa23764af51d9 | <|skeleton|>
class FeatureSelector:
"""This transformer select features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FeatureSelector/"""
def __init__(self, columns=None... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureSelector:
"""This transformer select features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FeatureSelector/"""
def __init__(self, columns=None, random_stat... | the_stack_v2_python_sparse | mlearner/preprocessing/feature_selector.py | jaisenbe58r/MLearner | train | 9 |
3f5f61093ff089e84bcf992944928bf871f43e26 | [
"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... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
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_sum: D... | stack_v2_sparse_classes_36k_train_009188 | 1,573 | permissive | [
{
"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 `Solution` described below.
Class description:
Implement the Solution 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(self, root, sum... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution 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(self, root, sum... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
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_sum: D... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
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, prefix_s... | the_stack_v2_python_sparse | 437 Path Sum III.py | Aminaba123/LeetCode | train | 1 | |
636de2deb80c00a9eb846a12d37770d6653bccc8 | [
"query = '\\n INSERT IGNORE INTO yara_signature_references\\n VALUES (%(blob_id)s, %(username_hash)s, NOW(6))\\n '\nargs = {'blob_id': blob_id.AsBytes(), 'username_hash': mysql_utils.Hash(username)}\ntry:\n cursor.execute(query, args)\nexcept MySQLdb.IntegrityError:\n raise db.UnknownGRRUserError(use... | <|body_start_0|>
query = '\n INSERT IGNORE INTO yara_signature_references\n VALUES (%(blob_id)s, %(username_hash)s, NOW(6))\n '
args = {'blob_id': blob_id.AsBytes(), 'username_hash': mysql_utils.Hash(username)}
try:
cursor.execute(query, args)
except MySQLdb.Integrit... | A MySQL database mixin class with YARA-related methods. | MySQLDBYaraMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySQLDBYaraMixin:
"""A MySQL database mixin class with YARA-related methods."""
def WriteYaraSignatureReference(self, blob_id: rdf_objects.BlobID, username: Text, cursor: MySQLdb.cursors.Cursor) -> None:
"""Marks specified blob id as a YARA signature."""
<|body_0|>
def V... | stack_v2_sparse_classes_36k_train_009189 | 1,462 | permissive | [
{
"docstring": "Marks specified blob id as a YARA signature.",
"name": "WriteYaraSignatureReference",
"signature": "def WriteYaraSignatureReference(self, blob_id: rdf_objects.BlobID, username: Text, cursor: MySQLdb.cursors.Cursor) -> None"
},
{
"docstring": "Verifies whether specified blob is a ... | 2 | stack_v2_sparse_classes_30k_train_007960 | Implement the Python class `MySQLDBYaraMixin` described below.
Class description:
A MySQL database mixin class with YARA-related methods.
Method signatures and docstrings:
- def WriteYaraSignatureReference(self, blob_id: rdf_objects.BlobID, username: Text, cursor: MySQLdb.cursors.Cursor) -> None: Marks specified blob... | Implement the Python class `MySQLDBYaraMixin` described below.
Class description:
A MySQL database mixin class with YARA-related methods.
Method signatures and docstrings:
- def WriteYaraSignatureReference(self, blob_id: rdf_objects.BlobID, username: Text, cursor: MySQLdb.cursors.Cursor) -> None: Marks specified blob... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class MySQLDBYaraMixin:
"""A MySQL database mixin class with YARA-related methods."""
def WriteYaraSignatureReference(self, blob_id: rdf_objects.BlobID, username: Text, cursor: MySQLdb.cursors.Cursor) -> None:
"""Marks specified blob id as a YARA signature."""
<|body_0|>
def V... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MySQLDBYaraMixin:
"""A MySQL database mixin class with YARA-related methods."""
def WriteYaraSignatureReference(self, blob_id: rdf_objects.BlobID, username: Text, cursor: MySQLdb.cursors.Cursor) -> None:
"""Marks specified blob id as a YARA signature."""
query = '\n INSERT IGNORE INTO ... | the_stack_v2_python_sparse | grr/server/grr_response_server/databases/mysql_yara.py | google/grr | train | 4,683 |
86a57d39d6c54d2fc56428001b7912a1c554b6e4 | [
"def parse_string(pattern):\n d = {}\n count = 0\n digits_pattern = ''\n for p in pattern:\n if p in d:\n digits_pattern += d[p]\n else:\n digits_pattern += str(count)\n d[p] = str(count)\n count += 1\n return digits_pattern\nreturn parse_stri... | <|body_start_0|>
def parse_string(pattern):
d = {}
count = 0
digits_pattern = ''
for p in pattern:
if p in d:
digits_pattern += d[p]
else:
digits_pattern += str(count)
d[p]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordPattern(self, pattern, strs):
""":type pattern: str :type str: str :rtype: bool"""
<|body_0|>
def wordPattern1(self, pattern, str):
""":type pattern: str :type str: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d... | stack_v2_sparse_classes_36k_train_009190 | 1,713 | no_license | [
{
"docstring": ":type pattern: str :type str: str :rtype: bool",
"name": "wordPattern",
"signature": "def wordPattern(self, pattern, strs)"
},
{
"docstring": ":type pattern: str :type str: str :rtype: bool",
"name": "wordPattern1",
"signature": "def wordPattern1(self, pattern, str)"
}
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordPattern(self, pattern, strs): :type pattern: str :type str: str :rtype: bool
- def wordPattern1(self, pattern, str): :type pattern: str :type str: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordPattern(self, pattern, strs): :type pattern: str :type str: str :rtype: bool
- def wordPattern1(self, pattern, str): :type pattern: str :type str: str :rtype: bool
<|ske... | 857b8c7fccfe8216da59228c1cf3675444855673 | <|skeleton|>
class Solution:
def wordPattern(self, pattern, strs):
""":type pattern: str :type str: str :rtype: bool"""
<|body_0|>
def wordPattern1(self, pattern, str):
""":type pattern: str :type str: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordPattern(self, pattern, strs):
""":type pattern: str :type str: str :rtype: bool"""
def parse_string(pattern):
d = {}
count = 0
digits_pattern = ''
for p in pattern:
if p in d:
digits_pattern +... | the_stack_v2_python_sparse | algorithm/Word-Pattern.py | atashi/LLL | train | 0 | |
c47ffbcd8a6e1bfa57fed31ba19d1a05585ef46c | [
"if isinstance(db_value, (int, long, float)):\n return datetime.datetime.fromtimestamp(db_value)\nelse:\n return super(TimestampColumn, self).dbRestore(db_value, context=context)",
"if isinstance(py_value, datetime.datetime):\n return time.mktime(py_value.timetuple())\nelse:\n return super(TimestampCo... | <|body_start_0|>
if isinstance(db_value, (int, long, float)):
return datetime.datetime.fromtimestamp(db_value)
else:
return super(TimestampColumn, self).dbRestore(db_value, context=context)
<|end_body_0|>
<|body_start_1|>
if isinstance(py_value, datetime.datetime):
... | TimestampColumn | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimestampColumn:
def dbRestore(self, db_value, context=None):
"""Restores the value from a table cache for usage. :param value | <variant> context | <orb.Context> || None"""
<|body_0|>
def dbStore(self, typ, py_value):
"""Converts the value to one that is safe to sto... | stack_v2_sparse_classes_36k_train_009191 | 16,562 | permissive | [
{
"docstring": "Restores the value from a table cache for usage. :param value | <variant> context | <orb.Context> || None",
"name": "dbRestore",
"signature": "def dbRestore(self, db_value, context=None)"
},
{
"docstring": "Converts the value to one that is safe to store on a record within the re... | 3 | null | Implement the Python class `TimestampColumn` described below.
Class description:
Implement the TimestampColumn class.
Method signatures and docstrings:
- def dbRestore(self, db_value, context=None): Restores the value from a table cache for usage. :param value | <variant> context | <orb.Context> || None
- def dbStore... | Implement the Python class `TimestampColumn` described below.
Class description:
Implement the TimestampColumn class.
Method signatures and docstrings:
- def dbRestore(self, db_value, context=None): Restores the value from a table cache for usage. :param value | <variant> context | <orb.Context> || None
- def dbStore... | 575be2689cb269e65a0a2678232ff940acc19e5a | <|skeleton|>
class TimestampColumn:
def dbRestore(self, db_value, context=None):
"""Restores the value from a table cache for usage. :param value | <variant> context | <orb.Context> || None"""
<|body_0|>
def dbStore(self, typ, py_value):
"""Converts the value to one that is safe to sto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimestampColumn:
def dbRestore(self, db_value, context=None):
"""Restores the value from a table cache for usage. :param value | <variant> context | <orb.Context> || None"""
if isinstance(db_value, (int, long, float)):
return datetime.datetime.fromtimestamp(db_value)
else:
... | the_stack_v2_python_sparse | orb/core/column_types/dtime.py | orb-framework/orb | train | 7 | |
81a9aaa7e895b7392578d1482bbb04eb88afae05 | [
"users = User.objects.filter(username__iexact=self.cleaned_data['username'])\nif not users:\n return self.cleaned_data['username']\nraise forms.ValidationError(_(u'该用户名已经注册'))",
"emails = User.objects.filter(email__iexact=self.cleaned_data['email'])\nif not emails:\n return self.cleaned_data['email']\nraise... | <|body_start_0|>
users = User.objects.filter(username__iexact=self.cleaned_data['username'])
if not users:
return self.cleaned_data['username']
raise forms.ValidationError(_(u'该用户名已经注册'))
<|end_body_0|>
<|body_start_1|>
emails = User.objects.filter(email__iexact=self.cleaned... | RegisterForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterForm:
def clean_username(self):
"""验证重复昵称"""
<|body_0|>
def clean_email(self):
"""验证重复email"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
users = User.objects.filter(username__iexact=self.cleaned_data['username'])
if not users:
... | stack_v2_sparse_classes_36k_train_009192 | 5,159 | no_license | [
{
"docstring": "验证重复昵称",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "验证重复email",
"name": "clean_email",
"signature": "def clean_email(self)"
}
] | 2 | null | Implement the Python class `RegisterForm` described below.
Class description:
Implement the RegisterForm class.
Method signatures and docstrings:
- def clean_username(self): 验证重复昵称
- def clean_email(self): 验证重复email | Implement the Python class `RegisterForm` described below.
Class description:
Implement the RegisterForm class.
Method signatures and docstrings:
- def clean_username(self): 验证重复昵称
- def clean_email(self): 验证重复email
<|skeleton|>
class RegisterForm:
def clean_username(self):
"""验证重复昵称"""
<|body_0... | f5877567b6d7a0e3ab9895416ea95d02f3b572a4 | <|skeleton|>
class RegisterForm:
def clean_username(self):
"""验证重复昵称"""
<|body_0|>
def clean_email(self):
"""验证重复email"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisterForm:
def clean_username(self):
"""验证重复昵称"""
users = User.objects.filter(username__iexact=self.cleaned_data['username'])
if not users:
return self.cleaned_data['username']
raise forms.ValidationError(_(u'该用户名已经注册'))
def clean_email(self):
"""验证重... | the_stack_v2_python_sparse | accounts/forms.py | sj741231/stockstar-vsa | train | 0 | |
ec0b4f55127dd62f571acb7541b3adabe5bbad49 | [
"super().__init__(name=name)\nself._embedding_dim = embedding_dim\nif number_of_dom_encoder_layers < 0:\n raise ValueError('Number of DOM encoder layers should be > 0 but got %d' % number_of_dom_encoder_layers)\nif number_of_profile_encoder_layers < 0:\n raise ValueError('Number of profile encoder layers shou... | <|body_start_0|>
super().__init__(name=name)
self._embedding_dim = embedding_dim
if number_of_dom_encoder_layers < 0:
raise ValueError('Number of DOM encoder layers should be > 0 but got %d' % number_of_dom_encoder_layers)
if number_of_profile_encoder_layers < 0:
... | Feed forward DQN for web navigation. | DQNWebFF | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DQNWebFF:
"""Feed forward DQN for web navigation."""
def __init__(self, vocab_size, embedding_dim, latent_dim, number_of_dom_encoder_layers=1, number_of_profile_encoder_layers=1, embedding_initializer=None, profile_value_dropout=0.0, use_select_option_dim=False, name=None, return_state_value... | stack_v2_sparse_classes_36k_train_009193 | 21,865 | permissive | [
{
"docstring": "DQN with feed forward DOM encoder. Profile and DOM are independently encoded into tensors where profile tensor represents field encodings while DOM tensor represents element encodings. These two tensors are used score every element and field pairs. Scores correspond to Q values in DQN or logits ... | 2 | stack_v2_sparse_classes_30k_train_013868 | Implement the Python class `DQNWebFF` described below.
Class description:
Feed forward DQN for web navigation.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, latent_dim, number_of_dom_encoder_layers=1, number_of_profile_encoder_layers=1, embedding_initializer=None, profile_value_dro... | Implement the Python class `DQNWebFF` described below.
Class description:
Feed forward DQN for web navigation.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, latent_dim, number_of_dom_encoder_layers=1, number_of_profile_encoder_layers=1, embedding_initializer=None, profile_value_dro... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class DQNWebFF:
"""Feed forward DQN for web navigation."""
def __init__(self, vocab_size, embedding_dim, latent_dim, number_of_dom_encoder_layers=1, number_of_profile_encoder_layers=1, embedding_initializer=None, profile_value_dropout=0.0, use_select_option_dim=False, name=None, return_state_value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DQNWebFF:
"""Feed forward DQN for web navigation."""
def __init__(self, vocab_size, embedding_dim, latent_dim, number_of_dom_encoder_layers=1, number_of_profile_encoder_layers=1, embedding_initializer=None, profile_value_dropout=0.0, use_select_option_dim=False, name=None, return_state_value=False):
... | the_stack_v2_python_sparse | compositional_rl/gwob/CoDE/q_networks.py | Jimmy-INL/google-research | train | 1 |
210c1f1df88fd0a9dca4f1280da90594e3d6ff93 | [
"Init.__init__(self, *args, **kwargs)\nself._negative = negative\nself._parameter = parameter\nself._scale = scale\nself._obs = EarthLocation.of_site(obs)\nself._kind = kind",
"if not os.path.exists(filename):\n self.log.error('Give file %s for extracting coordinates does not exist, skipping.', filename)\n ... | <|body_start_0|>
Init.__init__(self, *args, **kwargs)
self._negative = negative
self._parameter = parameter
self._scale = scale
self._obs = EarthLocation.of_site(obs)
self._kind = kind
<|end_body_0|>
<|body_start_1|>
if not os.path.exists(filename):
s... | Initializes a component from the heliocentric correction calculated for RA/Dec given in the FITS headers. This class, when called, initializes a single parameter (the radial velocity, default to "v") of the given component with the heliocentric correction calculated from RA/DEC/DATE-OBS in the given file. | InitFromVhelio | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InitFromVhelio:
"""Initializes a component from the heliocentric correction calculated for RA/Dec given in the FITS headers. This class, when called, initializes a single parameter (the radial velocity, default to "v") of the given component with the heliocentric correction calculated from RA/DEC... | stack_v2_sparse_classes_36k_train_009194 | 2,738 | permissive | [
{
"docstring": "Initializes a new Init object. Args: negative: If True, uses the negative of the calculated correction. parameter: Name of the parameter in the component to set. scale: Time scale to use for DATE-OBS. obs: Observatory to use for calculating correction. kind: Either barycentric or heliocentric.",... | 2 | stack_v2_sparse_classes_30k_train_006879 | Implement the Python class `InitFromVhelio` described below.
Class description:
Initializes a component from the heliocentric correction calculated for RA/Dec given in the FITS headers. This class, when called, initializes a single parameter (the radial velocity, default to "v") of the given component with the helioce... | Implement the Python class `InitFromVhelio` described below.
Class description:
Initializes a component from the heliocentric correction calculated for RA/Dec given in the FITS headers. This class, when called, initializes a single parameter (the radial velocity, default to "v") of the given component with the helioce... | 648eb1758e3744d9e3d6669edc4a0c4753559f17 | <|skeleton|>
class InitFromVhelio:
"""Initializes a component from the heliocentric correction calculated for RA/Dec given in the FITS headers. This class, when called, initializes a single parameter (the radial velocity, default to "v") of the given component with the heliocentric correction calculated from RA/DEC... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InitFromVhelio:
"""Initializes a component from the heliocentric correction calculated for RA/Dec given in the FITS headers. This class, when called, initializes a single parameter (the radial velocity, default to "v") of the given component with the heliocentric correction calculated from RA/DEC/DATE-OBS in ... | the_stack_v2_python_sparse | spexxy/init/fromvhelio.py | thusser/spexxy | train | 4 |
5635f44223ddf0dac7eb1f44481d61c83fb4294e | [
"super().__init__(s3_client)\nself.big_query_instance = big_query_instance or MavenBigQuery()\nself.big_query_content = list()\nself.counter = Counter()\nself.bucket_name = self.s3_client.bucket_name if self.s3_client else 'developer-analytics-audit-report'\nself.filename = '{}/big-query-data/{}'.format(os.getenv('... | <|body_start_0|>
super().__init__(s3_client)
self.big_query_instance = big_query_instance or MavenBigQuery()
self.big_query_content = list()
self.counter = Counter()
self.bucket_name = self.s3_client.bucket_name if self.s3_client else 'developer-analytics-audit-report'
se... | Implementation data processing for maven bigquery. | MavenBQDataProcessing | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MavenBQDataProcessing:
"""Implementation data processing for maven bigquery."""
def __init__(self, big_query_instance=None, s3_client=None, file_name='collated.json'):
"""Initialize the BigQueryDataProcessing object."""
<|body_0|>
def process(self):
"""Process Ma... | stack_v2_sparse_classes_36k_train_009195 | 3,782 | permissive | [
{
"docstring": "Initialize the BigQueryDataProcessing object.",
"name": "__init__",
"signature": "def __init__(self, big_query_instance=None, s3_client=None, file_name='collated.json')"
},
{
"docstring": "Process Maven Bigquery response data.",
"name": "process",
"signature": "def proces... | 3 | stack_v2_sparse_classes_30k_train_000766 | Implement the Python class `MavenBQDataProcessing` described below.
Class description:
Implementation data processing for maven bigquery.
Method signatures and docstrings:
- def __init__(self, big_query_instance=None, s3_client=None, file_name='collated.json'): Initialize the BigQueryDataProcessing object.
- def proc... | Implement the Python class `MavenBQDataProcessing` described below.
Class description:
Implementation data processing for maven bigquery.
Method signatures and docstrings:
- def __init__(self, big_query_instance=None, s3_client=None, file_name='collated.json'): Initialize the BigQueryDataProcessing object.
- def proc... | 98f5d8f6e402dfed3b9ba9385040eacbb0a12bc3 | <|skeleton|>
class MavenBQDataProcessing:
"""Implementation data processing for maven bigquery."""
def __init__(self, big_query_instance=None, s3_client=None, file_name='collated.json'):
"""Initialize the BigQueryDataProcessing object."""
<|body_0|>
def process(self):
"""Process Ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MavenBQDataProcessing:
"""Implementation data processing for maven bigquery."""
def __init__(self, big_query_instance=None, s3_client=None, file_name='collated.json'):
"""Initialize the BigQueryDataProcessing object."""
super().__init__(s3_client)
self.big_query_instance = big_que... | the_stack_v2_python_sparse | rudra/data_store/bigquery/maven_bigquery.py | fabric8-analytics/fabric8-analytics-rudra | train | 3 |
fdccf5112edf9abfcad0f0fc6171f4a2c249851b | [
"self._env = env\nself._epsilon = kwargs['epsilon']\nself._mu_plus = kwargs['mu_plus']\nself._mu_minus = kwargs['mu_minus']\nself._action_tolerance = kwargs['action_tolerance']\nself._environment = None",
"expert_action = self._env.expert()\nif self._env.action_space.discrete:\n is_correct = expert_action == a... | <|body_start_0|>
self._env = env
self._epsilon = kwargs['epsilon']
self._mu_plus = kwargs['mu_plus']
self._mu_minus = kwargs['mu_minus']
self._action_tolerance = kwargs['action_tolerance']
self._environment = None
<|end_body_0|>
<|body_start_1|>
expert_action = s... | A multi-task teacher which gives feedback according to the SABL model. Actions are considered correct if they match the expert's sampled action for the current state. | Teacher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Teacher:
"""A multi-task teacher which gives feedback according to the SABL model. Actions are considered correct if they match the expert's sampled action for the current state."""
def __init__(self, env, **kwargs):
"""Initializes the teacher, but does not assign it to a specific en... | stack_v2_sparse_classes_36k_train_009196 | 3,072 | no_license | [
{
"docstring": "Initializes the teacher, but does not assign it to a specific environment. :param kwargs: the configuration parameters",
"name": "__init__",
"signature": "def __init__(self, env, **kwargs)"
},
{
"docstring": "Gets feedback for the given action. Feedback depends on the current sta... | 2 | stack_v2_sparse_classes_30k_train_000094 | Implement the Python class `Teacher` described below.
Class description:
A multi-task teacher which gives feedback according to the SABL model. Actions are considered correct if they match the expert's sampled action for the current state.
Method signatures and docstrings:
- def __init__(self, env, **kwargs): Initial... | Implement the Python class `Teacher` described below.
Class description:
A multi-task teacher which gives feedback according to the SABL model. Actions are considered correct if they match the expert's sampled action for the current state.
Method signatures and docstrings:
- def __init__(self, env, **kwargs): Initial... | 381c019a3c930d943672a65ae651e5a4f52686f8 | <|skeleton|>
class Teacher:
"""A multi-task teacher which gives feedback according to the SABL model. Actions are considered correct if they match the expert's sampled action for the current state."""
def __init__(self, env, **kwargs):
"""Initializes the teacher, but does not assign it to a specific en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Teacher:
"""A multi-task teacher which gives feedback according to the SABL model. Actions are considered correct if they match the expert's sampled action for the current state."""
def __init__(self, env, **kwargs):
"""Initializes the teacher, but does not assign it to a specific environment. :p... | the_stack_v2_python_sparse | feedback/teachers/sabl.py | rtloftin/HAL | train | 0 |
8c71fcca09d6bee9c8df0998162ccbaf03d788c3 | [
"errors = []\nif not HAS_TEXTFSM:\n errors.append(missing_required_lib('textfsm'))\nreturn {'errors': errors}",
"cli_output = self._task_args.get('text')\nres = self._check_reqs()\nif res.get('errors'):\n return {'errors': res.get('errors')}\ntemplate_path = self._task_args.get('parser').get('template_path'... | <|body_start_0|>
errors = []
if not HAS_TEXTFSM:
errors.append(missing_required_lib('textfsm'))
return {'errors': errors}
<|end_body_0|>
<|body_start_1|>
cli_output = self._task_args.get('text')
res = self._check_reqs()
if res.get('errors'):
retur... | The textfsm parser class Convert raw text to structured data using textfsm | CliParser | [
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CliParser:
"""The textfsm parser class Convert raw text to structured data using textfsm"""
def _check_reqs():
"""Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path"""
<|body_0|>
def parse(self, *_args, **_kwargs):
... | stack_v2_sparse_classes_36k_train_009197 | 3,264 | permissive | [
{
"docstring": "Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path",
"name": "_check_reqs",
"signature": "def _check_reqs()"
},
{
"docstring": "Std entry point for a cli_parse parse execution :return: Errors or parsed text as structured data :rtype... | 2 | stack_v2_sparse_classes_30k_train_010566 | Implement the Python class `CliParser` described below.
Class description:
The textfsm parser class Convert raw text to structured data using textfsm
Method signatures and docstrings:
- def _check_reqs(): Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path
- def parse(se... | Implement the Python class `CliParser` described below.
Class description:
The textfsm parser class Convert raw text to structured data using textfsm
Method signatures and docstrings:
- def _check_reqs(): Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path
- def parse(se... | 2ea7d4f00212f502bc684ac257371ada73da1ca9 | <|skeleton|>
class CliParser:
"""The textfsm parser class Convert raw text to structured data using textfsm"""
def _check_reqs():
"""Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path"""
<|body_0|>
def parse(self, *_args, **_kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CliParser:
"""The textfsm parser class Convert raw text to structured data using textfsm"""
def _check_reqs():
"""Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path"""
errors = []
if not HAS_TEXTFSM:
errors.append(missing... | the_stack_v2_python_sparse | intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/ansible/utils/plugins/sub_plugins/cli_parser/textfsm_parser.py | SimonFangCisco/dne-dna-code | train | 0 |
29666ceeb7ad8b049896dac71ecf612edb5778d0 | [
"data = db.Db()\nresult = data.getCartridgesByState(state_id)\nresp.status = falcon.HTTP_200\nresp.content_type = falcon.MEDIA_TEXT\nresp.text = result",
"param = req.media\naction = int(param['action'])\ndata = db.Db()\nif action == 0:\n result = data.changeCartridgeState(param)\n resp.status = falcon.HTTP... | <|body_start_0|>
data = db.Db()
result = data.getCartridgesByState(state_id)
resp.status = falcon.HTTP_200
resp.content_type = falcon.MEDIA_TEXT
resp.text = result
<|end_body_0|>
<|body_start_1|>
param = req.media
action = int(param['action'])
data = db.D... | CartridgeState | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartridgeState:
def on_get(self, req, resp, state_id):
"""handle get request"""
<|body_0|>
def on_post(self, req, resp):
"""handle post"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = db.Db()
result = data.getCartridgesByState(state_i... | stack_v2_sparse_classes_36k_train_009198 | 850 | no_license | [
{
"docstring": "handle get request",
"name": "on_get",
"signature": "def on_get(self, req, resp, state_id)"
},
{
"docstring": "handle post",
"name": "on_post",
"signature": "def on_post(self, req, resp)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000660 | Implement the Python class `CartridgeState` described below.
Class description:
Implement the CartridgeState class.
Method signatures and docstrings:
- def on_get(self, req, resp, state_id): handle get request
- def on_post(self, req, resp): handle post | Implement the Python class `CartridgeState` described below.
Class description:
Implement the CartridgeState class.
Method signatures and docstrings:
- def on_get(self, req, resp, state_id): handle get request
- def on_post(self, req, resp): handle post
<|skeleton|>
class CartridgeState:
def on_get(self, req, r... | 529e9a0c66a6c7021224a2daf60f378f01164ca5 | <|skeleton|>
class CartridgeState:
def on_get(self, req, resp, state_id):
"""handle get request"""
<|body_0|>
def on_post(self, req, resp):
"""handle post"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CartridgeState:
def on_get(self, req, resp, state_id):
"""handle get request"""
data = db.Db()
result = data.getCartridgesByState(state_id)
resp.status = falcon.HTTP_200
resp.content_type = falcon.MEDIA_TEXT
resp.text = result
def on_post(self, req, resp):
... | the_stack_v2_python_sparse | answers/cartridge_state.py | Logsod/noti_rest_server | train | 0 | |
e2e4ca18f119d1ffacd8311ccd815d3137dec97f | [
"n = len(nums)\n_sum = sum(nums)\nif _sum % 2 != 0:\n return False\ntarget = _sum // 2\ndp = [[False] * (target + 1) for _ in range(n)]\nfor i in range(0, n):\n if nums[i] > target:\n continue\n dp[i][nums[i]] = True\n if i == 0:\n continue\n for j in range(target + 1):\n if j >=... | <|body_start_0|>
n = len(nums)
_sum = sum(nums)
if _sum % 2 != 0:
return False
target = _sum // 2
dp = [[False] * (target + 1) for _ in range(n)]
for i in range(0, n):
if nums[i] > target:
continue
dp[i][nums[i]] = True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canPartition(self, nums: List[int]) -> bool:
"""LC 416 Partition Equal Subset Sum Tim complexity: O(N * max(nums)) difficulty: medium Args: nums (List[int]): [description] Returns: bool: [description]"""
<|body_0|>
def canPartition(self, nums: List[int]) -> boo... | stack_v2_sparse_classes_36k_train_009199 | 1,505 | no_license | [
{
"docstring": "LC 416 Partition Equal Subset Sum Tim complexity: O(N * max(nums)) difficulty: medium Args: nums (List[int]): [description] Returns: bool: [description]",
"name": "canPartition",
"signature": "def canPartition(self, nums: List[int]) -> bool"
},
{
"docstring": "Space optimization ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition(self, nums: List[int]) -> bool: LC 416 Partition Equal Subset Sum Tim complexity: O(N * max(nums)) difficulty: medium Args: nums (List[int]): [description] Retur... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition(self, nums: List[int]) -> bool: LC 416 Partition Equal Subset Sum Tim complexity: O(N * max(nums)) difficulty: medium Args: nums (List[int]): [description] Retur... | 89b6c180bb772978b6646131f9734b122e745f9c | <|skeleton|>
class Solution:
def canPartition(self, nums: List[int]) -> bool:
"""LC 416 Partition Equal Subset Sum Tim complexity: O(N * max(nums)) difficulty: medium Args: nums (List[int]): [description] Returns: bool: [description]"""
<|body_0|>
def canPartition(self, nums: List[int]) -> boo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canPartition(self, nums: List[int]) -> bool:
"""LC 416 Partition Equal Subset Sum Tim complexity: O(N * max(nums)) difficulty: medium Args: nums (List[int]): [description] Returns: bool: [description]"""
n = len(nums)
_sum = sum(nums)
if _sum % 2 != 0:
... | the_stack_v2_python_sparse | dp/python/partition-equal-subset-sum.py | dyf102/LC-daily | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.