blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
877deaa58e425f3416696b848b891be29749cef0 | [
"super().__init__(coordinator, vehicle)\nself.entity_description = description\nself._unit_system = unit_system\nself._attr_unique_id = f'{vehicle.vin}-{description.key}'",
"_LOGGER.debug(\"Updating binary sensor '%s' of %s\", self.entity_description.key, self.vehicle.name)\nself._attr_is_on = self.entity_descrip... | <|body_start_0|>
super().__init__(coordinator, vehicle)
self.entity_description = description
self._unit_system = unit_system
self._attr_unique_id = f'{vehicle.vin}-{description.key}'
<|end_body_0|>
<|body_start_1|>
_LOGGER.debug("Updating binary sensor '%s' of %s", self.entity_... | Representation of a BMW vehicle binary sensor. | BMWBinarySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BMWBinarySensor:
"""Representation of a BMW vehicle binary sensor."""
def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWBinarySensorEntityDescription, unit_system: UnitSystem) -> None:
"""Initialize sensor."""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_005900 | 9,144 | permissive | [
{
"docstring": "Initialize sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWBinarySensorEntityDescription, unit_system: UnitSystem) -> None"
},
{
"docstring": "Handle updated data from the coordinator.",
... | 2 | stack_v2_sparse_classes_30k_train_025866 | Implement the Python class `BMWBinarySensor` described below.
Class description:
Representation of a BMW vehicle binary sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWBinarySensorEntityDescription, unit_system: UnitSystem) -... | Implement the Python class `BMWBinarySensor` described below.
Class description:
Representation of a BMW vehicle binary sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWBinarySensorEntityDescription, unit_system: UnitSystem) -... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class BMWBinarySensor:
"""Representation of a BMW vehicle binary sensor."""
def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWBinarySensorEntityDescription, unit_system: UnitSystem) -> None:
"""Initialize sensor."""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BMWBinarySensor:
"""Representation of a BMW vehicle binary sensor."""
def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWBinarySensorEntityDescription, unit_system: UnitSystem) -> None:
"""Initialize sensor."""
super().__init__(coordinator, ve... | the_stack_v2_python_sparse | homeassistant/components/bmw_connected_drive/binary_sensor.py | home-assistant/core | train | 35,501 |
c2dad5c69981fc815e3c0878c4b852f0c3da5a04 | [
"assert da.getDim() == 2\nself.da = da\nself.prob = prob\nself.factor = factor\nself.localX = da.createLocalVec()",
"self.da.globalToLocal(X, self.localX)\nx = self.da.getVecArray(self.localX)\nf = self.da.getVecArray(F)\n(xs, xe), (ys, ye) = self.da.getRanges()\nfor j in range(ys, ye):\n for i in range(xs, xe... | <|body_start_0|>
assert da.getDim() == 2
self.da = da
self.prob = prob
self.factor = factor
self.localX = da.createLocalVec()
<|end_body_0|>
<|body_start_1|>
self.da.globalToLocal(X, self.localX)
x = self.da.getVecArray(self.localX)
f = self.da.getVecArra... | Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES | GS_reaction | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GS_reaction:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, prob, factor):
"""Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd)"""
<|body_0|>
def formF... | stack_v2_sparse_classes_75kplus_train_005901 | 20,605 | permissive | [
{
"docstring": "Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd)",
"name": "__init__",
"signature": "def __init__(self, da, prob, factor)"
},
{
"docstring": "Function to evaluate the residual for the Newton solver This function should be equal t... | 3 | stack_v2_sparse_classes_30k_train_047799 | Implement the Python class `GS_reaction` described below.
Class description:
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
Method signatures and docstrings:
- def __init__(self, da, prob, factor): Initialization routine Args: da: DMDA object prob: problem instance factor: tem... | Implement the Python class `GS_reaction` described below.
Class description:
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
Method signatures and docstrings:
- def __init__(self, da, prob, factor): Initialization routine Args: da: DMDA object prob: problem instance factor: tem... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class GS_reaction:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, prob, factor):
"""Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd)"""
<|body_0|>
def formF... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GS_reaction:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, prob, factor):
"""Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd)"""
assert da.getDim() == 2
self.d... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/GrayScott_2D_PETSc_periodic.py | Parallel-in-Time/pySDC | train | 30 |
3248bc01a5073f0461e373189667c78517fa1153 | [
"self.rate = rate\nself.period = 1.0 / rate if rate > 0.0 else 0.0\nself.recorded_time = time.time()",
"current_time = time.time()\nelapsed = current_time - self.recorded_time\nif self.period - elapsed > 0:\n rospy.rostime.wallsleep(self.period - elapsed)\nself.recorded_time = time.time()"
] | <|body_start_0|>
self.rate = rate
self.period = 1.0 / rate if rate > 0.0 else 0.0
self.recorded_time = time.time()
<|end_body_0|>
<|body_start_1|>
current_time = time.time()
elapsed = current_time - self.recorded_time
if self.period - elapsed > 0:
rospy.rosti... | A wall time implementation of ros' rospy.time.Rate class. Usage: .. code-block:: python from rocon_python_comms import WallRate rate = WallRate(10) # 10Hz = 0.1s period while True: # do something rate.sleep() | WallRate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WallRate:
"""A wall time implementation of ros' rospy.time.Rate class. Usage: .. code-block:: python from rocon_python_comms import WallRate rate = WallRate(10) # 10Hz = 0.1s period while True: # do something rate.sleep()"""
def __init__(self, rate):
""":param float rate: rate in her... | stack_v2_sparse_classes_75kplus_train_005902 | 1,718 | no_license | [
{
"docstring": ":param float rate: rate in hertz, if rate = 0, then won't sleep",
"name": "__init__",
"signature": "def __init__(self, rate)"
},
{
"docstring": "Sleep until the rate period is exceeded.",
"name": "sleep",
"signature": "def sleep(self)"
}
] | 2 | null | Implement the Python class `WallRate` described below.
Class description:
A wall time implementation of ros' rospy.time.Rate class. Usage: .. code-block:: python from rocon_python_comms import WallRate rate = WallRate(10) # 10Hz = 0.1s period while True: # do something rate.sleep()
Method signatures and docstrings:
-... | Implement the Python class `WallRate` described below.
Class description:
A wall time implementation of ros' rospy.time.Rate class. Usage: .. code-block:: python from rocon_python_comms import WallRate rate = WallRate(10) # 10Hz = 0.1s period while True: # do something rate.sleep()
Method signatures and docstrings:
-... | 1f182537b26e8622eefaf6737d3b3d18b1741ca6 | <|skeleton|>
class WallRate:
"""A wall time implementation of ros' rospy.time.Rate class. Usage: .. code-block:: python from rocon_python_comms import WallRate rate = WallRate(10) # 10Hz = 0.1s period while True: # do something rate.sleep()"""
def __init__(self, rate):
""":param float rate: rate in her... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WallRate:
"""A wall time implementation of ros' rospy.time.Rate class. Usage: .. code-block:: python from rocon_python_comms import WallRate rate = WallRate(10) # 10Hz = 0.1s period while True: # do something rate.sleep()"""
def __init__(self, rate):
""":param float rate: rate in hertz, if rate =... | the_stack_v2_python_sparse | rocon_python_comms/src/rocon_python_comms/wall_rate.py | robotics-in-concert/rocon_tools | train | 7 |
639f990371bf20341eeb8b78734bac7be8cf8876 | [
"oper = {'and': 'intersection', 'or': 'union', 'not': 'complement'}\nif len(item) < 2 or len(item) > 3:\n raise TypeError('{} must be exactly 1 operator and 1-2 items'.format(item))\nself._check('operator', item[0], str, choices=oper.keys())\nself._check('operand1', item[1], (int, tuple))\nif len(item) == 3:\n ... | <|body_start_0|>
oper = {'and': 'intersection', 'or': 'union', 'not': 'complement'}
if len(item) < 2 or len(item) > 3:
raise TypeError('{} must be exactly 1 operator and 1-2 items'.format(item))
self._check('operator', item[0], str, choices=oper.keys())
self._check('operand1'... | SCEndpoint | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SCEndpoint:
def _combo_expansion(self, item):
"""Expands the asset combination expressions from nested tuples to the nested dictionary structure that's expected. Args: item Returns: :obj:`dict`: The dictionary structure of the expanded asset list combinations."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_005903 | 12,037 | permissive | [
{
"docstring": "Expands the asset combination expressions from nested tuples to the nested dictionary structure that's expected. Args: item Returns: :obj:`dict`: The dictionary structure of the expanded asset list combinations.",
"name": "_combo_expansion",
"signature": "def _combo_expansion(self, item)... | 3 | stack_v2_sparse_classes_30k_train_038947 | Implement the Python class `SCEndpoint` described below.
Class description:
Implement the SCEndpoint class.
Method signatures and docstrings:
- def _combo_expansion(self, item): Expands the asset combination expressions from nested tuples to the nested dictionary structure that's expected. Args: item Returns: :obj:`d... | Implement the Python class `SCEndpoint` described below.
Class description:
Implement the SCEndpoint class.
Method signatures and docstrings:
- def _combo_expansion(self, item): Expands the asset combination expressions from nested tuples to the nested dictionary structure that's expected. Args: item Returns: :obj:`d... | 4e31049891f55016168b14ae30d332a965523640 | <|skeleton|>
class SCEndpoint:
def _combo_expansion(self, item):
"""Expands the asset combination expressions from nested tuples to the nested dictionary structure that's expected. Args: item Returns: :obj:`dict`: The dictionary structure of the expanded asset list combinations."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SCEndpoint:
def _combo_expansion(self, item):
"""Expands the asset combination expressions from nested tuples to the nested dictionary structure that's expected. Args: item Returns: :obj:`dict`: The dictionary structure of the expanded asset list combinations."""
oper = {'and': 'intersection',... | the_stack_v2_python_sparse | tenable/sc/base.py | tenable/pyTenable | train | 300 | |
b289f0a3d517c609fbe02915776e0326c7eb3d4f | [
"super().__init__()\nself.doSpotOscillation = False\nself.xAmplitude = 10\nself.xFrequency = 5.0\nself.yAmplitude = 5\nself.yFrequency = 10.0",
"super().fromDict(config)\nself.doSpotOscillation = config['spotOscillation']['do']\nself.xAmplitude = config['spotOscillation']['x']['amplitude']\nself.xFrequency = conf... | <|body_start_0|>
super().__init__()
self.doSpotOscillation = False
self.xAmplitude = 10
self.xFrequency = 5.0
self.yAmplitude = 5
self.yFrequency = 10.0
<|end_body_0|>
<|body_start_1|>
super().fromDict(config)
self.doSpotOscillation = config['spotOscillat... | Class that handles the configuration of the Gaussian camera. Attributes ---------- doSpotOscillation : bool Flag tp make the generated spot oscillate. xAmplitude : int The amplitude of the x component of the spot oscillation. xFrequency : float The frequency of the x component of the spot oscillation. yAmplitude : int ... | GaussianCameraConfig | [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianCameraConfig:
"""Class that handles the configuration of the Gaussian camera. Attributes ---------- doSpotOscillation : bool Flag tp make the generated spot oscillate. xAmplitude : int The amplitude of the x component of the spot oscillation. xFrequency : float The frequency of the x comp... | stack_v2_sparse_classes_75kplus_train_005904 | 2,590 | permissive | [
{
"docstring": "Summary",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Translate config to class attributes. Parameters ---------- config : dict The configuration to translate.",
"name": "fromDict",
"signature": "def fromDict(self, config)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_039393 | Implement the Python class `GaussianCameraConfig` described below.
Class description:
Class that handles the configuration of the Gaussian camera. Attributes ---------- doSpotOscillation : bool Flag tp make the generated spot oscillate. xAmplitude : int The amplitude of the x component of the spot oscillation. xFreque... | Implement the Python class `GaussianCameraConfig` described below.
Class description:
Class that handles the configuration of the Gaussian camera. Attributes ---------- doSpotOscillation : bool Flag tp make the generated spot oscillate. xAmplitude : int The amplitude of the x component of the spot oscillation. xFreque... | 3d0242276198126240667ba13e95b7bdf901d053 | <|skeleton|>
class GaussianCameraConfig:
"""Class that handles the configuration of the Gaussian camera. Attributes ---------- doSpotOscillation : bool Flag tp make the generated spot oscillate. xAmplitude : int The amplitude of the x component of the spot oscillation. xFrequency : float The frequency of the x comp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaussianCameraConfig:
"""Class that handles the configuration of the Gaussian camera. Attributes ---------- doSpotOscillation : bool Flag tp make the generated spot oscillate. xAmplitude : int The amplitude of the x component of the spot oscillation. xFrequency : float The frequency of the x component of the ... | the_stack_v2_python_sparse | spot_motion_monitor/config/gaussian_camera_config.py | lsst-sitcom/spot_motion_monitor | train | 0 |
036f1f9e00655f6435e9a6a801ddc847f96adbdb | [
"if k < 0:\n return 0\nfrom collections import defaultdict\nm = defaultdict(int)\nfor i in nums:\n m[i] += 1\nresult = set()\nfor i in nums:\n m[i] -= 1\n m[i - k] -= 1\n if m[i] >= 0 and m[i - k] >= 0:\n result.add((i - k, i))\n m[i] += 1\n m[i - k] += 1\n m[i] -= 1\n m[i + k] -= ... | <|body_start_0|>
if k < 0:
return 0
from collections import defaultdict
m = defaultdict(int)
for i in nums:
m[i] += 1
result = set()
for i in nums:
m[i] -= 1
m[i - k] -= 1
if m[i] >= 0 and m[i - k] >= 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findPairs1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findPairs(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if k < 0:
... | stack_v2_sparse_classes_75kplus_train_005905 | 1,170 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findPairs1",
"signature": "def findPairs1(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findPairs",
"signature": "def findPairs(self, nums, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPairs1(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findPairs(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 findPairs1(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findPairs(self, nums, k): :type nums: List[int] :type k: int :rtype: int
<|skeleton|>
class S... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class Solution:
def findPairs1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findPairs(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findPairs1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
if k < 0:
return 0
from collections import defaultdict
m = defaultdict(int)
for i in nums:
m[i] += 1
result = set()
for i in nums:
... | the_stack_v2_python_sparse | k-diff-pairs-in-an-array/solution.py | uxlsl/leetcode_practice | train | 0 | |
bc50770617a43eea38b2721d1f11732920f73153 | [
"self.bed_line = {}\nself.strand = {}\nself.score = {}\nself.chr_start_end = {}\n'Read filebed into a bed dict'\nwith open(filebed) as fh:\n for line in fh:\n mylist = line.rstrip('\\n').split('\\t')\n if len(mylist) < 6:\n short = 6 - len(mylist)\n mylist += ['.'] * short\n ... | <|body_start_0|>
self.bed_line = {}
self.strand = {}
self.score = {}
self.chr_start_end = {}
'Read filebed into a bed dict'
with open(filebed) as fh:
for line in fh:
mylist = line.rstrip('\n').split('\t')
if len(mylist) < 6:
... | format the following line into bed information of two sides | BedIO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BedIO:
"""format the following line into bed information of two sides"""
def __init__(self, filebed):
"""Initialize the values"""
<|body_0|>
def rename(self, re_tobesub, re_subto):
"""Change the keys with re.sub(re_tobesub, re_subto)"""
<|body_1|>
de... | stack_v2_sparse_classes_75kplus_train_005906 | 4,962 | no_license | [
{
"docstring": "Initialize the values",
"name": "__init__",
"signature": "def __init__(self, filebed)"
},
{
"docstring": "Change the keys with re.sub(re_tobesub, re_subto)",
"name": "rename",
"signature": "def rename(self, re_tobesub, re_subto)"
},
{
"docstring": "Print entire be... | 3 | stack_v2_sparse_classes_30k_train_039023 | Implement the Python class `BedIO` described below.
Class description:
format the following line into bed information of two sides
Method signatures and docstrings:
- def __init__(self, filebed): Initialize the values
- def rename(self, re_tobesub, re_subto): Change the keys with re.sub(re_tobesub, re_subto)
- def pr... | Implement the Python class `BedIO` described below.
Class description:
format the following line into bed information of two sides
Method signatures and docstrings:
- def __init__(self, filebed): Initialize the values
- def rename(self, re_tobesub, re_subto): Change the keys with re.sub(re_tobesub, re_subto)
- def pr... | e31c8f2f65260ceff110d07b530b67e465e41800 | <|skeleton|>
class BedIO:
"""format the following line into bed information of two sides"""
def __init__(self, filebed):
"""Initialize the values"""
<|body_0|>
def rename(self, re_tobesub, re_subto):
"""Change the keys with re.sub(re_tobesub, re_subto)"""
<|body_1|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BedIO:
"""format the following line into bed information of two sides"""
def __init__(self, filebed):
"""Initialize the values"""
self.bed_line = {}
self.strand = {}
self.score = {}
self.chr_start_end = {}
'Read filebed into a bed dict'
with open(fi... | the_stack_v2_python_sparse | curate_orthogene/scripts/merge_bed_to_bedpe.py | lhui2010/bundle | train | 6 |
b0f75b030c230e6dbe07d7671fbaaab28866d249 | [
"if not isinstance(opts, models.param_sets.VisorEngineProcessOpts):\n raise ValueError('opts must be of type models.param_sets.VisorEngineProcessOpts')\nif not isinstance(compdata_cache, compdata_cache_module.CompDataCache):\n raise ValueError('compdata_cache must be of type managers.CompDataCache')\nself.que... | <|body_start_0|>
if not isinstance(opts, models.param_sets.VisorEngineProcessOpts):
raise ValueError('opts must be of type models.param_sets.VisorEngineProcessOpts')
if not isinstance(compdata_cache, compdata_cache_module.CompDataCache):
raise ValueError('compdata_cache must be o... | Class for performing curated (text) queries. Curated queries are the same as text queries, but the query string starts with the '#' character. The training images are taken from a subdirectory within the 'curatedtrainimgs' folder, which must be pre-populated with the images to be processed. | CuratedQuery | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CuratedQuery:
"""Class for performing curated (text) queries. Curated queries are the same as text queries, but the query string starts with the '#' character. The training images are taken from a subdirectory within the 'curatedtrainimgs' folder, which must be pre-populated with the images to be... | stack_v2_sparse_classes_75kplus_train_005907 | 5,708 | permissive | [
{
"docstring": "Initializes the class. Arguments: query_id: id of the query being executed. query: query in dictionary form backend_port: Communication port with the backend compdata_cache: Computational data cache manager. opts: current configuration of options for the visor engine Returns: It raises ValueErro... | 2 | null | Implement the Python class `CuratedQuery` described below.
Class description:
Class for performing curated (text) queries. Curated queries are the same as text queries, but the query string starts with the '#' character. The training images are taken from a subdirectory within the 'curatedtrainimgs' folder, which must... | Implement the Python class `CuratedQuery` described below.
Class description:
Class for performing curated (text) queries. Curated queries are the same as text queries, but the query string starts with the '#' character. The training images are taken from a subdirectory within the 'curatedtrainimgs' folder, which must... | f79b1a3661534b78b991810303aa6db4bb24a14f | <|skeleton|>
class CuratedQuery:
"""Class for performing curated (text) queries. Curated queries are the same as text queries, but the query string starts with the '#' character. The training images are taken from a subdirectory within the 'curatedtrainimgs' folder, which must be pre-populated with the images to be... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CuratedQuery:
"""Class for performing curated (text) queries. Curated queries are the same as text queries, but the query string starts with the '#' character. The training images are taken from a subdirectory within the 'curatedtrainimgs' folder, which must be pre-populated with the images to be processed.""... | the_stack_v2_python_sparse | siteroot/controllers/retengine/engine/qtypes/engines/curated_query.py | danigunawan/vgg_frontend | train | 0 |
3d901bc2937037aee347194dee7cb810dd866ae5 | [
"ps = []\nself.dfs(ps, '', n, 0)\nreturn ps",
"if lbn == 0 and rbn == 0:\n prts.append(s)\nif lbn > 0:\n self.dfs(prts, s + '(', lbn - 1, rbn + 1)\nif rbn > 0:\n self.dfs(prts, s + ')', lbn, rbn - 1)"
] | <|body_start_0|>
ps = []
self.dfs(ps, '', n, 0)
return ps
<|end_body_0|>
<|body_start_1|>
if lbn == 0 and rbn == 0:
prts.append(s)
if lbn > 0:
self.dfs(prts, s + '(', lbn - 1, rbn + 1)
if rbn > 0:
self.dfs(prts, s + ')', lbn, rbn - 1)
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def dfs(self, prts, s, lbn, rbn):
""":type prts: List[str] :type s: str :type lbn: int :type rbn: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ps = []... | stack_v2_sparse_classes_75kplus_train_005908 | 619 | permissive | [
{
"docstring": ":type n: int :rtype: List[str]",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n)"
},
{
"docstring": ":type prts: List[str] :type s: str :type lbn: int :type rbn: int",
"name": "dfs",
"signature": "def dfs(self, prts, s, lbn, rbn)"
}
] | 2 | stack_v2_sparse_classes_30k_val_002424 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
- def dfs(self, prts, s, lbn, rbn): :type prts: List[str] :type s: str :type lbn: int :type rbn: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
- def dfs(self, prts, s, lbn, rbn): :type prts: List[str] :type s: str :type lbn: int :type rbn: int
<|skeleton|... | cb70ca87aa4604d1aec83d4224b3489eacebba75 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def dfs(self, prts, s, lbn, rbn):
""":type prts: List[str] :type s: str :type lbn: int :type rbn: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
ps = []
self.dfs(ps, '', n, 0)
return ps
def dfs(self, prts, s, lbn, rbn):
""":type prts: List[str] :type s: str :type lbn: int :type rbn: int"""
if lbn == 0 and rbn == 0:
... | the_stack_v2_python_sparse | LeetCode/Python3/0022._Generate_Parentheses.py | icgw/practice | train | 1 | |
843dfce0a9e3c8260f3a5129a7ac7e749e6c5543 | [
"letter = 'abcdefghijklmnopqrstuvwxyz'\ns = list(S)\ni, j = (0, len(s) - 1)\nwhile i < j:\n if s[i].lower() not in letter:\n i = i + 1\n elif s[j].lower() not in letter:\n j = j - 1\n else:\n s[i], s[j] = (s[j], s[i])\n i = i + 1\n j = j - 1\nreturn ''.join(s)",
"def ge... | <|body_start_0|>
letter = 'abcdefghijklmnopqrstuvwxyz'
s = list(S)
i, j = (0, len(s) - 1)
while i < j:
if s[i].lower() not in letter:
i = i + 1
elif s[j].lower() not in letter:
j = j - 1
else:
s[i], s[j] ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseOnlyLetters(self, S):
""":type S: str :rtype: str"""
<|body_0|>
def reverseOnlyLetters2(self, S):
""":type S: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
letter = 'abcdefghijklmnopqrstuvwxyz'
s = list... | stack_v2_sparse_classes_75kplus_train_005909 | 1,112 | no_license | [
{
"docstring": ":type S: str :rtype: str",
"name": "reverseOnlyLetters",
"signature": "def reverseOnlyLetters(self, S)"
},
{
"docstring": ":type S: str :rtype: str",
"name": "reverseOnlyLetters2",
"signature": "def reverseOnlyLetters2(self, S)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042168 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseOnlyLetters(self, S): :type S: str :rtype: str
- def reverseOnlyLetters2(self, S): :type S: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseOnlyLetters(self, S): :type S: str :rtype: str
- def reverseOnlyLetters2(self, S): :type S: str :rtype: str
<|skeleton|>
class Solution:
def reverseOnlyLetters(s... | b149d1e8a83b0dfc724bd9dc129a1cad407dd91f | <|skeleton|>
class Solution:
def reverseOnlyLetters(self, S):
""":type S: str :rtype: str"""
<|body_0|>
def reverseOnlyLetters2(self, S):
""":type S: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseOnlyLetters(self, S):
""":type S: str :rtype: str"""
letter = 'abcdefghijklmnopqrstuvwxyz'
s = list(S)
i, j = (0, len(s) - 1)
while i < j:
if s[i].lower() not in letter:
i = i + 1
elif s[j].lower() not in lett... | the_stack_v2_python_sparse | string/0917_reverse_only_letters/0917_reverse_only_letters.py | zdyxry/LeetCode | train | 6 | |
e2a27801a69639eba679dbdfe56715e4c90b2beb | [
"logger.info('Overriding class: Optimizer -> SSA.')\nsuper(SSA, self).__init__()\nself.build(params)\nlogger.info('Class overrided.')",
"c1 = 2 * np.exp(-(4 * iteration / n_iterations) ** 2)\nfor i, _ in enumerate(space.agents):\n if i == 0:\n for j, (lb, ub) in enumerate(zip(space.agents[i].lb, space.a... | <|body_start_0|>
logger.info('Overriding class: Optimizer -> SSA.')
super(SSA, self).__init__()
self.build(params)
logger.info('Class overrided.')
<|end_body_0|>
<|body_start_1|>
c1 = 2 * np.exp(-(4 * iteration / n_iterations) ** 2)
for i, _ in enumerate(space.agents):
... | A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software (2017). | SSA | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSA:
"""A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software (2017)."""
def __init__(self... | stack_v2_sparse_classes_75kplus_train_005910 | 2,711 | permissive | [
{
"docstring": "Initialization method. Args: params (dict): Contains key-value parameters to the meta-heuristics.",
"name": "__init__",
"signature": "def __init__(self, params=None)"
},
{
"docstring": "Wraps Salp Swarm Algorithm over all agents and variables. Args: space (Space): Space containin... | 2 | stack_v2_sparse_classes_30k_test_001073 | Implement the Python class `SSA` described below.
Class description:
A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Sof... | Implement the Python class `SSA` described below.
Class description:
A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Sof... | 09e5485b9e30eca622ad404e85c22de0c42c8abd | <|skeleton|>
class SSA:
"""A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software (2017)."""
def __init__(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SSA:
"""A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software (2017)."""
def __init__(self, params=None... | the_stack_v2_python_sparse | opytimizer/optimizers/swarm/ssa.py | himanshuRepo/opytimizer | train | 0 |
e51d738c5faa90db62ec31384385f4cc533cc8d2 | [
"self.config = config\nself.engine: VizierEngine\nself.datasets: VizierDatastoreApi\nself.files: VizierFilestoreApi\nself.tasks: VizierContainerTaskApi\nself.urls: ContainerApiUrlFactory\nself.service_descriptor: Dict[str, Any]\nself.views: VizierDatasetViewApi\nif init:\n self.init()",
"self.urls = ContainerA... | <|body_start_0|>
self.config = config
self.engine: VizierEngine
self.datasets: VizierDatastoreApi
self.files: VizierFilestoreApi
self.tasks: VizierContainerTaskApi
self.urls: ContainerApiUrlFactory
self.service_descriptor: Dict[str, Any]
self.views: Vizier... | VizierContainerApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VizierContainerApi:
def __init__(self, config: ContainerConfig, init: bool=False):
"""Initialize the API components. Parameters ---------- config: vizier.config.app.ContainerAppConfig Container application configuration object init: bool, optional Defer initialization if False"""
... | stack_v2_sparse_classes_75kplus_train_005911 | 7,425 | permissive | [
{
"docstring": "Initialize the API components. Parameters ---------- config: vizier.config.app.ContainerAppConfig Container application configuration object init: bool, optional Defer initialization if False",
"name": "__init__",
"signature": "def __init__(self, config: ContainerConfig, init: bool=False... | 2 | null | Implement the Python class `VizierContainerApi` described below.
Class description:
Implement the VizierContainerApi class.
Method signatures and docstrings:
- def __init__(self, config: ContainerConfig, init: bool=False): Initialize the API components. Parameters ---------- config: vizier.config.app.ContainerAppConf... | Implement the Python class `VizierContainerApi` described below.
Class description:
Implement the VizierContainerApi class.
Method signatures and docstrings:
- def __init__(self, config: ContainerConfig, init: bool=False): Initialize the API components. Parameters ---------- config: vizier.config.app.ContainerAppConf... | e99f43df3df80ad5647f57d805c339257336ac73 | <|skeleton|>
class VizierContainerApi:
def __init__(self, config: ContainerConfig, init: bool=False):
"""Initialize the API components. Parameters ---------- config: vizier.config.app.ContainerAppConfig Container application configuration object init: bool, optional Defer initialization if False"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VizierContainerApi:
def __init__(self, config: ContainerConfig, init: bool=False):
"""Initialize the API components. Parameters ---------- config: vizier.config.app.ContainerAppConfig Container application configuration object init: bool, optional Defer initialization if False"""
self.config =... | the_stack_v2_python_sparse | vizier/api/webservice/container/base.py | VizierDB/web-api-async | train | 2 | |
5ce4be5d62d95514daf62a6c938f17b54211723c | [
"self.window = window\nif self.window is None:\n self.window = sublime.active_window()\nself.on_done = on_done\nself.on_cancel = on_cancel",
"self.post_remove = post_remove\nself.view = self.window.open_file(file_name)\nEventHandler().register_handler(self, EventHandler().ON_CLOSE | EventHandler().ON_POST_SAVE... | <|body_start_0|>
self.window = window
if self.window is None:
self.window = sublime.active_window()
self.on_done = on_done
self.on_cancel = on_cancel
<|end_body_0|>
<|body_start_1|>
self.post_remove = post_remove
self.view = self.window.open_file(file_name)
... | A custom buffer for JSON editing which its data will be used on save Useful when configure multiple/complex settings | JSONPanel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSONPanel:
"""A custom buffer for JSON editing which its data will be used on save Useful when configure multiple/complex settings"""
def __init__(self, window=None, on_done=None, on_cancel=None):
"""@param window: window to open panel @param on_done: a callback function which will r... | stack_v2_sparse_classes_75kplus_train_005912 | 2,264 | permissive | [
{
"docstring": "@param window: window to open panel @param on_done: a callback function which will receive Python object converted from JSON data when panel is saved @param on_cancel: a callback function which will be called when panel is closed",
"name": "__init__",
"signature": "def __init__(self, win... | 5 | null | Implement the Python class `JSONPanel` described below.
Class description:
A custom buffer for JSON editing which its data will be used on save Useful when configure multiple/complex settings
Method signatures and docstrings:
- def __init__(self, window=None, on_done=None, on_cancel=None): @param window: window to op... | Implement the Python class `JSONPanel` described below.
Class description:
A custom buffer for JSON editing which its data will be used on save Useful when configure multiple/complex settings
Method signatures and docstrings:
- def __init__(self, window=None, on_done=None, on_cancel=None): @param window: window to op... | b38d4f9d852565d6dcecb236386628b4e56d9d09 | <|skeleton|>
class JSONPanel:
"""A custom buffer for JSON editing which its data will be used on save Useful when configure multiple/complex settings"""
def __init__(self, window=None, on_done=None, on_cancel=None):
"""@param window: window to open panel @param on_done: a callback function which will r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JSONPanel:
"""A custom buffer for JSON editing which its data will be used on save Useful when configure multiple/complex settings"""
def __init__(self, window=None, on_done=None, on_cancel=None):
"""@param window: window to open panel @param on_done: a callback function which will receive Python... | the_stack_v2_python_sparse | core/json_panel.py | evandroforks/Javatar | train | 1 |
cd1387f2eb99a31bb79f9dfd6f41c07a24f04f13 | [
"if w is None:\n w = self.w\nreturn w[s] if o is None else w[s, o]",
"phi = np.zeros(self.feature_dim)\nif o is None:\n phi[s] = 1\nelse:\n phi[s, o] = 1\nreturn phi"
] | <|body_start_0|>
if w is None:
w = self.w
return w[s] if o is None else w[s, o]
<|end_body_0|>
<|body_start_1|>
phi = np.zeros(self.feature_dim)
if o is None:
phi[s] = 1
else:
phi[s, o] = 1
return phi
<|end_body_1|>
| A special case of a linear GVF for estimating option-value functions. The weight matrix shape is (n_states, n_options). Assumes that states and options are categorical. | TabularQ | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TabularQ:
"""A special case of a linear GVF for estimating option-value functions. The weight matrix shape is (n_states, n_options). Assumes that states and options are categorical."""
def predict(self, s: int=slice(None), o: int=None, w: np.array=None, *args, **kwargs) -> Union[np.float, np... | stack_v2_sparse_classes_75kplus_train_005913 | 4,672 | no_license | [
{
"docstring": "Preforms a table lookup to find a value of a state-option tuple",
"name": "predict",
"signature": "def predict(self, s: int=slice(None), o: int=None, w: np.array=None, *args, **kwargs) -> Union[np.float, np.array]"
},
{
"docstring": "Constructs a binary matrix of size (n_states, ... | 2 | stack_v2_sparse_classes_30k_train_033427 | Implement the Python class `TabularQ` described below.
Class description:
A special case of a linear GVF for estimating option-value functions. The weight matrix shape is (n_states, n_options). Assumes that states and options are categorical.
Method signatures and docstrings:
- def predict(self, s: int=slice(None), o... | Implement the Python class `TabularQ` described below.
Class description:
A special case of a linear GVF for estimating option-value functions. The weight matrix shape is (n_states, n_options). Assumes that states and options are categorical.
Method signatures and docstrings:
- def predict(self, s: int=slice(None), o... | c654c91a9cfe5d34c778723977794dfa3e213776 | <|skeleton|>
class TabularQ:
"""A special case of a linear GVF for estimating option-value functions. The weight matrix shape is (n_states, n_options). Assumes that states and options are categorical."""
def predict(self, s: int=slice(None), o: int=None, w: np.array=None, *args, **kwargs) -> Union[np.float, np... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TabularQ:
"""A special case of a linear GVF for estimating option-value functions. The weight matrix shape is (n_states, n_options). Assumes that states and options are categorical."""
def predict(self, s: int=slice(None), o: int=None, w: np.array=None, *args, **kwargs) -> Union[np.float, np.array]:
... | the_stack_v2_python_sparse | hrl/frameworks/gvf/gvf.py | konichuvak/hrl | train | 0 |
0324656c9741ec0f61a2b4bed99e73f056088bda | [
"reader = SourceStringReader(NORMAL_TEST_CASE)\nsource = FortranSource(reader)\nunit_under_test = stylist.fortran.AutoCharArrayIntent()\nissues = unit_under_test.examine(source)\nstrings = [str(issue) for issue in issues]\nassert strings == NORMAL_TEST_EXPECTATION",
"reader = SourceStringReader(SINGLE_CHAR_CASE)\... | <|body_start_0|>
reader = SourceStringReader(NORMAL_TEST_CASE)
source = FortranSource(reader)
unit_under_test = stylist.fortran.AutoCharArrayIntent()
issues = unit_under_test.examine(source)
strings = [str(issue) for issue in issues]
assert strings == NORMAL_TEST_EXPECTAT... | Tests the rule that variable length character arguments should have intent(in) | TestAutoCharArrayIntent | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAutoCharArrayIntent:
"""Tests the rule that variable length character arguments should have intent(in)"""
def test_normal_behaviour(self):
"""Ensures the test case produces exactly the issues in expectation"""
<|body_0|>
def test_single_char(self):
"""Ensures... | stack_v2_sparse_classes_75kplus_train_005914 | 2,767 | permissive | [
{
"docstring": "Ensures the test case produces exactly the issues in expectation",
"name": "test_normal_behaviour",
"signature": "def test_normal_behaviour(self)"
},
{
"docstring": "Ensures the test can handle no length being specified.",
"name": "test_single_char",
"signature": "def tes... | 2 | null | Implement the Python class `TestAutoCharArrayIntent` described below.
Class description:
Tests the rule that variable length character arguments should have intent(in)
Method signatures and docstrings:
- def test_normal_behaviour(self): Ensures the test case produces exactly the issues in expectation
- def test_singl... | Implement the Python class `TestAutoCharArrayIntent` described below.
Class description:
Tests the rule that variable length character arguments should have intent(in)
Method signatures and docstrings:
- def test_normal_behaviour(self): Ensures the test case produces exactly the issues in expectation
- def test_singl... | c01def9b5eeb2885e45b5097ea0bbf3297da2eed | <|skeleton|>
class TestAutoCharArrayIntent:
"""Tests the rule that variable length character arguments should have intent(in)"""
def test_normal_behaviour(self):
"""Ensures the test case produces exactly the issues in expectation"""
<|body_0|>
def test_single_char(self):
"""Ensures... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAutoCharArrayIntent:
"""Tests the rule that variable length character arguments should have intent(in)"""
def test_normal_behaviour(self):
"""Ensures the test case produces exactly the issues in expectation"""
reader = SourceStringReader(NORMAL_TEST_CASE)
source = FortranSourc... | the_stack_v2_python_sparse | unit-tests/fortran_auto_char_array_intent_test.py | MetOffice/stylist | train | 23 |
83e7b5ea96d2055230bd4991b646d80868ea9620 | [
"super().__init__(call=call)\nself._dtype: type = dtype\nself._subtype: bool = subtype\nself._cast: bool = cast",
"ok_type: bool = True\nif self._subtype:\n if not isinstance(event.data, self._dtype):\n ok_type = False\nelif not type(event.data) == self._dtype:\n ok_type = False\nif not ok_type:\n ... | <|body_start_0|>
super().__init__(call=call)
self._dtype: type = dtype
self._subtype: bool = subtype
self._cast: bool = cast
<|end_body_0|>
<|body_start_1|>
ok_type: bool = True
if self._subtype:
if not isinstance(event.data, self._dtype):
ok_... | A predicate that evaluates using a custom function or method after first checking whether the event data is an instance of a given type. If it is not, then a cast to the type can be attempted and a **copy of the event** is passed with its data cast to the type. **Note**: the copy is only used **within the predicate cal... | BoboPredicateCallType | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BoboPredicateCallType:
"""A predicate that evaluates using a custom function or method after first checking whether the event data is an instance of a given type. If it is not, then a cast to the type can be attempted and a **copy of the event** is passed with its data cast to the type. **Note**:... | stack_v2_sparse_classes_75kplus_train_005915 | 4,611 | permissive | [
{
"docstring": ":param call: The callable to use for evaluating the predicate. :param dtype: The data type to use for evaluation. :param subtype: If `True`, the event's data can be a subtype of the type specified in `dtype`. If `False`, it must be exactly the type in `dtype`. :param cast: If `True`, and if the ... | 2 | stack_v2_sparse_classes_30k_train_047551 | Implement the Python class `BoboPredicateCallType` described below.
Class description:
A predicate that evaluates using a custom function or method after first checking whether the event data is an instance of a given type. If it is not, then a cast to the type can be attempted and a **copy of the event** is passed wi... | Implement the Python class `BoboPredicateCallType` described below.
Class description:
A predicate that evaluates using a custom function or method after first checking whether the event data is an instance of a given type. If it is not, then a cast to the type can be attempted and a **copy of the event** is passed wi... | 7035feece42ae3494d4471e90f8ce818ed5ab670 | <|skeleton|>
class BoboPredicateCallType:
"""A predicate that evaluates using a custom function or method after first checking whether the event data is an instance of a given type. If it is not, then a cast to the type can be attempted and a **copy of the event** is passed with its data cast to the type. **Note**:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BoboPredicateCallType:
"""A predicate that evaluates using a custom function or method after first checking whether the event data is an instance of a given type. If it is not, then a cast to the type can be attempted and a **copy of the event** is passed with its data cast to the type. **Note**: the copy is ... | the_stack_v2_python_sparse | bobocep/cep/phenom/pattern/predicate.py | r3w0p/bobocep | train | 10 |
646a4472c7b7854f7b7535e3468135850692b274 | [
"Polynomial.__init__(self, coefficients)\nif self.getDegree() != 2:\n raise PolynomialError('Not a quadratic polynomial.')",
"a, b, c = (self.getCoefficients()[2], self.getCoefficients()[1], self.getCoefficients()[0])\ndelta = b ** 2 - 4 * a * c\nif delta >= 0:\n roots = sorted([(-b - math.sqrt(delta)) / (2... | <|body_start_0|>
Polynomial.__init__(self, coefficients)
if self.getDegree() != 2:
raise PolynomialError('Not a quadratic polynomial.')
<|end_body_0|>
<|body_start_1|>
a, b, c = (self.getCoefficients()[2], self.getCoefficients()[1], self.getCoefficients()[0])
delta = b ** 2 ... | QuadraticPolynomial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuadraticPolynomial:
def __init__(self, coefficients):
"""Exercise 10"""
<|body_0|>
def getRoots(self):
"""Exercise 11 Get roots of a quadratic polynomial"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Polynomial.__init__(self, coefficients)
... | stack_v2_sparse_classes_75kplus_train_005916 | 12,688 | no_license | [
{
"docstring": "Exercise 10",
"name": "__init__",
"signature": "def __init__(self, coefficients)"
},
{
"docstring": "Exercise 11 Get roots of a quadratic polynomial",
"name": "getRoots",
"signature": "def getRoots(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033009 | Implement the Python class `QuadraticPolynomial` described below.
Class description:
Implement the QuadraticPolynomial class.
Method signatures and docstrings:
- def __init__(self, coefficients): Exercise 10
- def getRoots(self): Exercise 11 Get roots of a quadratic polynomial | Implement the Python class `QuadraticPolynomial` described below.
Class description:
Implement the QuadraticPolynomial class.
Method signatures and docstrings:
- def __init__(self, coefficients): Exercise 10
- def getRoots(self): Exercise 11 Get roots of a quadratic polynomial
<|skeleton|>
class QuadraticPolynomial:... | a47c529a7085233ba7d7f484316d1cdd3b542df4 | <|skeleton|>
class QuadraticPolynomial:
def __init__(self, coefficients):
"""Exercise 10"""
<|body_0|>
def getRoots(self):
"""Exercise 11 Get roots of a quadratic polynomial"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuadraticPolynomial:
def __init__(self, coefficients):
"""Exercise 10"""
Polynomial.__init__(self, coefficients)
if self.getDegree() != 2:
raise PolynomialError('Not a quadratic polynomial.')
def getRoots(self):
"""Exercise 11 Get roots of a quadratic polynomia... | the_stack_v2_python_sparse | Lesson2/TD/Polynomial_Solutions.py | riduan91/DSC101 | train | 0 | |
1dd48ae16cfd18d68946ba13f39451adfbf21745 | [
"input_json = request.data['APIParams']\noutput_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'Payload'], [request.data['AvailabilityDetails'], request.data['AuthenticationDetails'], None]))\nfetch_all_city = self.fetch_cities(input_json)\npayload_details = {'cities_details': fetch_all_city}\nout... | <|body_start_0|>
input_json = request.data['APIParams']
output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'Payload'], [request.data['AvailabilityDetails'], request.data['AuthenticationDetails'], None]))
fetch_all_city = self.fetch_cities(input_json)
payload_details ... | This api fetch all cities | GetAllCitiesByStateAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetAllCitiesByStateAPI:
"""This api fetch all cities"""
def post(self, request):
"""This API cover for fetch all cities."""
<|body_0|>
def fetch_cities(self, request):
"""Function to add country into database."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_75kplus_train_005917 | 1,541 | no_license | [
{
"docstring": "This API cover for fetch all cities.",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Function to add country into database.",
"name": "fetch_cities",
"signature": "def fetch_cities(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042774 | Implement the Python class `GetAllCitiesByStateAPI` described below.
Class description:
This api fetch all cities
Method signatures and docstrings:
- def post(self, request): This API cover for fetch all cities.
- def fetch_cities(self, request): Function to add country into database. | Implement the Python class `GetAllCitiesByStateAPI` described below.
Class description:
This api fetch all cities
Method signatures and docstrings:
- def post(self, request): This API cover for fetch all cities.
- def fetch_cities(self, request): Function to add country into database.
<|skeleton|>
class GetAllCities... | 36eb9931f330e64902354c6fc471be2adf4b7049 | <|skeleton|>
class GetAllCitiesByStateAPI:
"""This api fetch all cities"""
def post(self, request):
"""This API cover for fetch all cities."""
<|body_0|>
def fetch_cities(self, request):
"""Function to add country into database."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetAllCitiesByStateAPI:
"""This api fetch all cities"""
def post(self, request):
"""This API cover for fetch all cities."""
input_json = request.data['APIParams']
output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'Payload'], [request.data['AvailabilityDetails... | the_stack_v2_python_sparse | Generic/common/location/api/getallcitiesdetailsbystate/views_getallcitiesdetailsbystate.py | archiemb303/common_backend_django | train | 0 |
b0fc600dd72db7e28f9c7753728b9688e1d8d958 | [
"if maxsize <= 0:\n maxsize = _multiprocessing.SemLock.SEM_VALUE_MAX\nself._maxsize = maxsize\nself._reader, self._writer = Pipe(duplex=False)\nself._rlock = Lock()\nself._opid = os.getpid()\nif sys.platform == 'win32':\n self._wlock = None\nelse:\n self._wlock = Lock()\nself._sem = BoundedSemaphore(maxsiz... | <|body_start_0|>
if maxsize <= 0:
maxsize = _multiprocessing.SemLock.SEM_VALUE_MAX
self._maxsize = maxsize
self._reader, self._writer = Pipe(duplex=False)
self._rlock = Lock()
self._opid = os.getpid()
if sys.platform == 'win32':
self._wlock = None
... | RawQueue makes a single change to Queue: instead of using the underlying ``send`` and ``recv`` functions of the pipe, it uses ``send_bytes`` and ``recv_bytes`` to provide a "safe" transport mechanism | _RawQueue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _RawQueue:
"""RawQueue makes a single change to Queue: instead of using the underlying ``send`` and ``recv`` functions of the pipe, it uses ``send_bytes`` and ``recv_bytes`` to provide a "safe" transport mechanism"""
def __init__(self, maxsize=0):
"""Override the __init__ function so... | stack_v2_sparse_classes_75kplus_train_005918 | 2,139 | no_license | [
{
"docstring": "Override the __init__ function so that *our* _after_fork function gets registered, rather than Queue's.",
"name": "__init__",
"signature": "def __init__(self, maxsize=0)"
},
{
"docstring": "Override the default :meth:`multiprocessing.Queue._after_fork` method to use the ``send_by... | 2 | stack_v2_sparse_classes_30k_train_013373 | Implement the Python class `_RawQueue` described below.
Class description:
RawQueue makes a single change to Queue: instead of using the underlying ``send`` and ``recv`` functions of the pipe, it uses ``send_bytes`` and ``recv_bytes`` to provide a "safe" transport mechanism
Method signatures and docstrings:
- def __i... | Implement the Python class `_RawQueue` described below.
Class description:
RawQueue makes a single change to Queue: instead of using the underlying ``send`` and ``recv`` functions of the pipe, it uses ``send_bytes`` and ``recv_bytes`` to provide a "safe" transport mechanism
Method signatures and docstrings:
- def __i... | d07819bc7fa7ff0665ec14f2ebc24ed3263ac72f | <|skeleton|>
class _RawQueue:
"""RawQueue makes a single change to Queue: instead of using the underlying ``send`` and ``recv`` functions of the pipe, it uses ``send_bytes`` and ``recv_bytes`` to provide a "safe" transport mechanism"""
def __init__(self, maxsize=0):
"""Override the __init__ function so... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _RawQueue:
"""RawQueue makes a single change to Queue: instead of using the underlying ``send`` and ``recv`` functions of the pipe, it uses ``send_bytes`` and ``recv_bytes`` to provide a "safe" transport mechanism"""
def __init__(self, maxsize=0):
"""Override the __init__ function so that *our* _... | the_stack_v2_python_sparse | raw_queue.py | kramer314/sagecell | train | 0 |
80b2c664bf95039f3f1c8abb460ba7dc04c81b88 | [
"angle_limit = _check_and_convert_limit_value(angle_limit, None, 0)\nself.angle_uniform = ops.Uniform(range=angle_limit)\nself.rotate = ops.Rotate(device='gpu', fill_value=0.0, keep_size=True)\nself.rng = ops.CoinFlip(probability=p)\nself.bool = ops.Cast(dtype=types.DALIDataType.BOOL)",
"data = EasyDict(data)\nan... | <|body_start_0|>
angle_limit = _check_and_convert_limit_value(angle_limit, None, 0)
self.angle_uniform = ops.Uniform(range=angle_limit)
self.rotate = ops.Rotate(device='gpu', fill_value=0.0, keep_size=True)
self.rng = ops.CoinFlip(probability=p)
self.bool = ops.Cast(dtype=types.D... | Random rotate the image, currently not support coordinates sensitive labels | RandomRotate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomRotate:
"""Random rotate the image, currently not support coordinates sensitive labels"""
def __init__(self, p: float=0.5, angle_limit: Union[List, float]=45.0, fill_value: float=0.0):
"""Initialization Args: p (float, optional): Probability to apply this transformation.. Defau... | stack_v2_sparse_classes_75kplus_train_005919 | 22,608 | no_license | [
{
"docstring": "Initialization Args: p (float, optional): Probability to apply this transformation.. Defaults to .5. angle_limit (Union[List,float], optional): Range for changing angle in [min,max] value format. If provided as a single float, the range will be (-limit, limit). Defaults to 45.. fill_value (float... | 2 | stack_v2_sparse_classes_30k_train_010240 | Implement the Python class `RandomRotate` described below.
Class description:
Random rotate the image, currently not support coordinates sensitive labels
Method signatures and docstrings:
- def __init__(self, p: float=0.5, angle_limit: Union[List, float]=45.0, fill_value: float=0.0): Initialization Args: p (float, op... | Implement the Python class `RandomRotate` described below.
Class description:
Random rotate the image, currently not support coordinates sensitive labels
Method signatures and docstrings:
- def __init__(self, p: float=0.5, angle_limit: Union[List, float]=45.0, fill_value: float=0.0): Initialization Args: p (float, op... | 1532db8447d03e75d5ec26f93111270a4ccb7a7e | <|skeleton|>
class RandomRotate:
"""Random rotate the image, currently not support coordinates sensitive labels"""
def __init__(self, p: float=0.5, angle_limit: Union[List, float]=45.0, fill_value: float=0.0):
"""Initialization Args: p (float, optional): Probability to apply this transformation.. Defau... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomRotate:
"""Random rotate the image, currently not support coordinates sensitive labels"""
def __init__(self, p: float=0.5, angle_limit: Union[List, float]=45.0, fill_value: float=0.0):
"""Initialization Args: p (float, optional): Probability to apply this transformation.. Defaults to .5. an... | the_stack_v2_python_sparse | src/development/vortex/development/utils/data/augment/modules/nvidia_dali/modules.py | jesslynsepthiaa/vortex | train | 0 |
3f9034bea459ef6a7774ada1ec7908ea3685705a | [
"WeatherStation.__init__(self, *args, **kwargs)\nself.filename = filename\nself.time = time\nself.timezone = None if timezone is None else pytz.timezone(timezone)\nself.columns = columns\nself.separator = separator",
"for field, typ in self.columns.items():\n if 'name' in typ and 'unit' in typ:\n sensor... | <|body_start_0|>
WeatherStation.__init__(self, *args, **kwargs)
self.filename = filename
self.time = time
self.timezone = None if timezone is None else pytz.timezone(timezone)
self.columns = columns
self.separator = separator
<|end_body_0|>
<|body_start_1|>
for f... | The CSV weather station reads current weather information from a CSV file. | CSV | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSV:
"""The CSV weather station reads current weather information from a CSV file."""
def __init__(self, filename: str, columns: dict, time: int=0, timezone: str=None, separator: str=',', *args, **kwargs):
"""Creates a new weather station that reads its data from a CSV file. A typica... | stack_v2_sparse_classes_75kplus_train_005920 | 4,995 | no_license | [
{
"docstring": "Creates a new weather station that reads its data from a CSV file. A typical JSON configuration for this weather station might look like this: | { | \"filename\": \"/wetter/wento/wento_log.txt\", | \"time\": 0, | \"columns\": { | \"2\": {\"code\": \"temp\", \"name\": \"Temperature\", \"unit\": \... | 4 | stack_v2_sparse_classes_30k_train_026571 | Implement the Python class `CSV` described below.
Class description:
The CSV weather station reads current weather information from a CSV file.
Method signatures and docstrings:
- def __init__(self, filename: str, columns: dict, time: int=0, timezone: str=None, separator: str=',', *args, **kwargs): Creates a new weat... | Implement the Python class `CSV` described below.
Class description:
The CSV weather station reads current weather information from a CSV file.
Method signatures and docstrings:
- def __init__(self, filename: str, columns: dict, time: int=0, timezone: str=None, separator: str=',', *args, **kwargs): Creates a new weat... | f375dc77878ab7c6ee306401c6501237d1521610 | <|skeleton|>
class CSV:
"""The CSV weather station reads current weather information from a CSV file."""
def __init__(self, filename: str, columns: dict, time: int=0, timezone: str=None, separator: str=',', *args, **kwargs):
"""Creates a new weather station that reads its data from a CSV file. A typica... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CSV:
"""The CSV weather station reads current weather information from a CSV file."""
def __init__(self, filename: str, columns: dict, time: int=0, timezone: str=None, separator: str=',', *args, **kwargs):
"""Creates a new weather station that reads its data from a CSV file. A typical JSON config... | the_stack_v2_python_sparse | pyobs_weather/weather/stations/csv.py | pyobs/pyobs-weather | train | 0 |
0351c1df8e5dbfc83301bfbd7b156c96da4a43f1 | [
"try:\n f = open('clients.json', 'r')\n data = []\n for line in f.readlines():\n data.append(json.loads(line))\n f.close()\n return data\nexcept:\n return []",
"try:\n f = open('movies.json', 'r')\n data = []\n for line in f.readlines():\n data.append(json.loads(line))\n ... | <|body_start_0|>
try:
f = open('clients.json', 'r')
data = []
for line in f.readlines():
data.append(json.loads(line))
f.close()
return data
except:
return []
<|end_body_0|>
<|body_start_1|>
try:
... | JSON_IO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSON_IO:
def readClients(self):
""":return: A list of lists, each sublist containing the info of a client"""
<|body_0|>
def readMovies(self):
""":return: A list of lists, each sublist containing the info of a movie"""
<|body_1|>
def readRentals(self):
... | stack_v2_sparse_classes_75kplus_train_005921 | 2,481 | no_license | [
{
"docstring": ":return: A list of lists, each sublist containing the info of a client",
"name": "readClients",
"signature": "def readClients(self)"
},
{
"docstring": ":return: A list of lists, each sublist containing the info of a movie",
"name": "readMovies",
"signature": "def readMovi... | 6 | stack_v2_sparse_classes_30k_train_021507 | Implement the Python class `JSON_IO` described below.
Class description:
Implement the JSON_IO class.
Method signatures and docstrings:
- def readClients(self): :return: A list of lists, each sublist containing the info of a client
- def readMovies(self): :return: A list of lists, each sublist containing the info of ... | Implement the Python class `JSON_IO` described below.
Class description:
Implement the JSON_IO class.
Method signatures and docstrings:
- def readClients(self): :return: A list of lists, each sublist containing the info of a client
- def readMovies(self): :return: A list of lists, each sublist containing the info of ... | 4ebd70c857fac2565b44f6e40904cba209a138a1 | <|skeleton|>
class JSON_IO:
def readClients(self):
""":return: A list of lists, each sublist containing the info of a client"""
<|body_0|>
def readMovies(self):
""":return: A list of lists, each sublist containing the info of a movie"""
<|body_1|>
def readRentals(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JSON_IO:
def readClients(self):
""":return: A list of lists, each sublist containing the info of a client"""
try:
f = open('clients.json', 'r')
data = []
for line in f.readlines():
data.append(json.loads(line))
f.close()
... | the_stack_v2_python_sparse | 1st year/1st semester/FPLab/Assignment.09/external_input_output/json_io.py | arazi47/university-projects | train | 0 | |
553aa3e8e2e8bf366ec80caf2dfa415dc5e4c5e0 | [
"super(Bottleneck, self).__init__()\nself.downsample = downsample\nself._make_midout = nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, kernel_size=(3, 1), stride=(stride, 1)... | <|body_start_0|>
super(Bottleneck, self).__init__()
self.downsample = downsample
self._make_midout = nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, kern... | 用于ResNet50,101和152的残差块,1x1 + 3x3 + 1x1的卷积优化为1x1 + 3x1 + 1*3 + 1x1 | Bottleneck | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bottleneck:
"""用于ResNet50,101和152的残差块,1x1 + 3x3 + 1x1的卷积优化为1x1 + 3x1 + 1*3 + 1x1"""
def __init__(self, in_channels, out_channels, stride=1, downsample=None):
"""小残差块初始化 :param: in_channels 卷积层输入通道数 :param: out_channels 卷积层输出通道数 :param: stride 卷积层步长 :param: downsample 是否要调整, 为下采样网络结构"... | stack_v2_sparse_classes_75kplus_train_005922 | 36,979 | no_license | [
{
"docstring": "小残差块初始化 :param: in_channels 卷积层输入通道数 :param: out_channels 卷积层输出通道数 :param: stride 卷积层步长 :param: downsample 是否要调整, 为下采样网络结构",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels, stride=1, downsample=None)"
},
{
"docstring": "前向传播 :param: x 图片变量 return o... | 2 | stack_v2_sparse_classes_30k_train_048482 | Implement the Python class `Bottleneck` described below.
Class description:
用于ResNet50,101和152的残差块,1x1 + 3x3 + 1x1的卷积优化为1x1 + 3x1 + 1*3 + 1x1
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, stride=1, downsample=None): 小残差块初始化 :param: in_channels 卷积层输入通道数 :param: out_channels 卷积层输出通道数... | Implement the Python class `Bottleneck` described below.
Class description:
用于ResNet50,101和152的残差块,1x1 + 3x3 + 1x1的卷积优化为1x1 + 3x1 + 1*3 + 1x1
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, stride=1, downsample=None): 小残差块初始化 :param: in_channels 卷积层输入通道数 :param: out_channels 卷积层输出通道数... | 2a68fd854bc5b1806319dfc40e36e084f9c4c5d0 | <|skeleton|>
class Bottleneck:
"""用于ResNet50,101和152的残差块,1x1 + 3x3 + 1x1的卷积优化为1x1 + 3x1 + 1*3 + 1x1"""
def __init__(self, in_channels, out_channels, stride=1, downsample=None):
"""小残差块初始化 :param: in_channels 卷积层输入通道数 :param: out_channels 卷积层输出通道数 :param: stride 卷积层步长 :param: downsample 是否要调整, 为下采样网络结构"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Bottleneck:
"""用于ResNet50,101和152的残差块,1x1 + 3x3 + 1x1的卷积优化为1x1 + 3x1 + 1*3 + 1x1"""
def __init__(self, in_channels, out_channels, stride=1, downsample=None):
"""小残差块初始化 :param: in_channels 卷积层输入通道数 :param: out_channels 卷积层输出通道数 :param: stride 卷积层步长 :param: downsample 是否要调整, 为下采样网络结构"""
su... | the_stack_v2_python_sparse | code_keh/2d/Pytorch_nets_channel1.py | ruichen9/3DCTLungDiseaseDiagnosis | train | 0 |
c7544799df93a546885034bb95724cca97fee997 | [
"self._username_ = username\nself._cfg_ = ConfigObj('ipall.cfg')\nself._db_host_ = self._cfg_['Database']['db_host']\nself._db_user_ = self._cfg_['Database']['db_user']\nself._db_pw_ = self._cfg_['Database']['db_pw']\nself._db_ = self._cfg_['Database']['db']\nself._conn_ = DBmy.db(self._db_host_, self._db_user_, se... | <|body_start_0|>
self._username_ = username
self._cfg_ = ConfigObj('ipall.cfg')
self._db_host_ = self._cfg_['Database']['db_host']
self._db_user_ = self._cfg_['Database']['db_user']
self._db_pw_ = self._cfg_['Database']['db_pw']
self._db_ = self._cfg_['Database']['db']
... | User | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
def __init__(self, username):
"""IpallUser username ... must be unique in database"""
<|body_0|>
def get_group_id(self):
"""read the group_id from current user return: group_id -> success return: -1 -> error"""
<|body_1|>
def get_rights(self, vrf='... | stack_v2_sparse_classes_75kplus_train_005923 | 2,965 | no_license | [
{
"docstring": "IpallUser username ... must be unique in database",
"name": "__init__",
"signature": "def __init__(self, username)"
},
{
"docstring": "read the group_id from current user return: group_id -> success return: -1 -> error",
"name": "get_group_id",
"signature": "def get_group... | 5 | null | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def __init__(self, username): IpallUser username ... must be unique in database
- def get_group_id(self): read the group_id from current user return: group_id -> success return: -1 -> er... | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def __init__(self, username): IpallUser username ... must be unique in database
- def get_group_id(self): read the group_id from current user return: group_id -> success return: -1 -> er... | 8e3c9e203a0572d865f1dfb9f69596f5b6450ff7 | <|skeleton|>
class User:
def __init__(self, username):
"""IpallUser username ... must be unique in database"""
<|body_0|>
def get_group_id(self):
"""read the group_id from current user return: group_id -> success return: -1 -> error"""
<|body_1|>
def get_rights(self, vrf='... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class User:
def __init__(self, username):
"""IpallUser username ... must be unique in database"""
self._username_ = username
self._cfg_ = ConfigObj('ipall.cfg')
self._db_host_ = self._cfg_['Database']['db_host']
self._db_user_ = self._cfg_['Database']['db_user']
self.... | the_stack_v2_python_sparse | cgi-bin/.svn/text-base/IpallUser.py.svn-base | Cloudxtreme/ipall | train | 0 | |
1bb39d0527726bbab2b79a96b63c677b6f88e5e1 | [
"data = {'token': self.token, 'project_id': project_id}\ndata.update(kwargs)\nfiles = {'file': open(filename, 'r')}\nreturn self.api._post('templates/import_into_project', data=data, files=files)",
"data = {'token': self.token, 'project_id': project_id}\ndata.update(kwargs)\nreturn self.api._post('templates/expor... | <|body_start_0|>
data = {'token': self.token, 'project_id': project_id}
data.update(kwargs)
files = {'file': open(filename, 'r')}
return self.api._post('templates/import_into_project', data=data, files=files)
<|end_body_0|>
<|body_start_1|>
data = {'token': self.token, 'project_... | TemplatesManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplatesManager:
def import_into_project(self, project_id, filename, **kwargs):
"""Imports a template into a project."""
<|body_0|>
def export_as_file(self, project_id, **kwargs):
"""Exports a template as a file."""
<|body_1|>
def export_as_url(self, pr... | stack_v2_sparse_classes_75kplus_train_005924 | 993 | permissive | [
{
"docstring": "Imports a template into a project.",
"name": "import_into_project",
"signature": "def import_into_project(self, project_id, filename, **kwargs)"
},
{
"docstring": "Exports a template as a file.",
"name": "export_as_file",
"signature": "def export_as_file(self, project_id,... | 3 | stack_v2_sparse_classes_30k_test_002413 | Implement the Python class `TemplatesManager` described below.
Class description:
Implement the TemplatesManager class.
Method signatures and docstrings:
- def import_into_project(self, project_id, filename, **kwargs): Imports a template into a project.
- def export_as_file(self, project_id, **kwargs): Exports a temp... | Implement the Python class `TemplatesManager` described below.
Class description:
Implement the TemplatesManager class.
Method signatures and docstrings:
- def import_into_project(self, project_id, filename, **kwargs): Imports a template into a project.
- def export_as_file(self, project_id, **kwargs): Exports a temp... | 7b85de81619146d3d54fececda068010ae73775b | <|skeleton|>
class TemplatesManager:
def import_into_project(self, project_id, filename, **kwargs):
"""Imports a template into a project."""
<|body_0|>
def export_as_file(self, project_id, **kwargs):
"""Exports a template as a file."""
<|body_1|>
def export_as_url(self, pr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TemplatesManager:
def import_into_project(self, project_id, filename, **kwargs):
"""Imports a template into a project."""
data = {'token': self.token, 'project_id': project_id}
data.update(kwargs)
files = {'file': open(filename, 'r')}
return self.api._post('templates/im... | the_stack_v2_python_sparse | todoist/managers/templates.py | Doist/todoist-python | train | 627 | |
cf5c73a6ada2e212d01ac21e5f13166de7ce32cf | [
"negatives = soft_mask < 1e-06\nlogits_exp = logits.exp()\ntarget_pos_factor = 1 / (1 + logits_exp)\nsigmoid = logits_exp * target_pos_factor\nloss = -(soft_mask * torch.log(sigmoid) + negatives * torch.log(target_pos_factor) * hyperparameter)\nctx.save_for_backward(soft_mask, negatives, target_pos_factor, sigmoid,... | <|body_start_0|>
negatives = soft_mask < 1e-06
logits_exp = logits.exp()
target_pos_factor = 1 / (1 + logits_exp)
sigmoid = logits_exp * target_pos_factor
loss = -(soft_mask * torch.log(sigmoid) + negatives * torch.log(target_pos_factor) * hyperparameter)
ctx.save_for_bac... | WeightedKLLoss | [
"Apache-2.0",
"BSD-2-Clause-Views"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightedKLLoss:
def forward(ctx, logits, soft_mask):
""":param logits: Any shape, dtype float :param positives: Same shape as logits, dtype float :param negatives: Same shape as logits, dtype float :return: scalar, an IoU type quantity Note that the output is only for collecting statisti... | stack_v2_sparse_classes_75kplus_train_005925 | 12,587 | permissive | [
{
"docstring": ":param logits: Any shape, dtype float :param positives: Same shape as logits, dtype float :param negatives: Same shape as logits, dtype float :return: scalar, an IoU type quantity Note that the output is only for collecting statistic. It is not differentiable, and the backward pass is independen... | 2 | stack_v2_sparse_classes_30k_train_037438 | Implement the Python class `WeightedKLLoss` described below.
Class description:
Implement the WeightedKLLoss class.
Method signatures and docstrings:
- def forward(ctx, logits, soft_mask): :param logits: Any shape, dtype float :param positives: Same shape as logits, dtype float :param negatives: Same shape as logits,... | Implement the Python class `WeightedKLLoss` described below.
Class description:
Implement the WeightedKLLoss class.
Method signatures and docstrings:
- def forward(ctx, logits, soft_mask): :param logits: Any shape, dtype float :param positives: Same shape as logits, dtype float :param negatives: Same shape as logits,... | a266bc16d682832aa854348fa557a30d86b84674 | <|skeleton|>
class WeightedKLLoss:
def forward(ctx, logits, soft_mask):
""":param logits: Any shape, dtype float :param positives: Same shape as logits, dtype float :param negatives: Same shape as logits, dtype float :return: scalar, an IoU type quantity Note that the output is only for collecting statisti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WeightedKLLoss:
def forward(ctx, logits, soft_mask):
""":param logits: Any shape, dtype float :param positives: Same shape as logits, dtype float :param negatives: Same shape as logits, dtype float :return: scalar, an IoU type quantity Note that the output is only for collecting statistic. It is not d... | the_stack_v2_python_sparse | source/losses/loss_utils.py | allenai/learning_from_interaction | train | 12 | |
75311273a651dde81ca60dfcfeca1fbdadb8b75a | [
"r1 = _make_round_directly(db)\n_make_round_directly(db)\nassert game.get_current_round_id() == r1.id",
"r = _make_round_directly(db)\n_make_round_directly(db)\ngame.complete_round(r)\nwith pytest.raises(LookupError):\n game.get_current_round_id()"
] | <|body_start_0|>
r1 = _make_round_directly(db)
_make_round_directly(db)
assert game.get_current_round_id() == r1.id
<|end_body_0|>
<|body_start_1|>
r = _make_round_directly(db)
_make_round_directly(db)
game.complete_round(r)
with pytest.raises(LookupError):
... | Tests related to having multiple active rounds. It is an invalid state for the game. This might happen however in practice. Tests here are related to handling the anomaly if present. | Test_data_anomaly | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_data_anomaly:
"""Tests related to having multiple active rounds. It is an invalid state for the game. This might happen however in practice. Tests here are related to handling the anomaly if present."""
def test_get_current_round_id(self, db):
"""Select the one with the smallest... | stack_v2_sparse_classes_75kplus_train_005926 | 3,537 | no_license | [
{
"docstring": "Select the one with the smallest id.",
"name": "test_get_current_round_id",
"signature": "def test_get_current_round_id(self, db)"
},
{
"docstring": "Close all other open rounds as well.",
"name": "test_complete_round",
"signature": "def test_complete_round(self, db)"
}... | 2 | stack_v2_sparse_classes_30k_train_039087 | Implement the Python class `Test_data_anomaly` described below.
Class description:
Tests related to having multiple active rounds. It is an invalid state for the game. This might happen however in practice. Tests here are related to handling the anomaly if present.
Method signatures and docstrings:
- def test_get_cur... | Implement the Python class `Test_data_anomaly` described below.
Class description:
Tests related to having multiple active rounds. It is an invalid state for the game. This might happen however in practice. Tests here are related to handling the anomaly if present.
Method signatures and docstrings:
- def test_get_cur... | f36f1db8a2ae486987779e0753ff227bb374042f | <|skeleton|>
class Test_data_anomaly:
"""Tests related to having multiple active rounds. It is an invalid state for the game. This might happen however in practice. Tests here are related to handling the anomaly if present."""
def test_get_current_round_id(self, db):
"""Select the one with the smallest... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_data_anomaly:
"""Tests related to having multiple active rounds. It is an invalid state for the game. This might happen however in practice. Tests here are related to handling the anomaly if present."""
def test_get_current_round_id(self, db):
"""Select the one with the smallest id."""
... | the_stack_v2_python_sparse | lupi_game_server/test_game.py | e3krisztian/lupi | train | 0 |
cfd582fc34675d6830c177de810364b48cce8455 | [
"super(LanguageModel, self).__init__()\nself.vocab = Vocab(EN)\nself.emb = torch.nn.Embedding(len(self.vocab), self.emb_size)\nself.gru = torch.nn.GRU(input_size=self.emb.embedding_dim, hidden_size=self.hidden_size, num_layers=1, dropout=self.dropout_rate, batch_first=True)\nself.init_state = torch.nn.Parameter(tor... | <|body_start_0|>
super(LanguageModel, self).__init__()
self.vocab = Vocab(EN)
self.emb = torch.nn.Embedding(len(self.vocab), self.emb_size)
self.gru = torch.nn.GRU(input_size=self.emb.embedding_dim, hidden_size=self.hidden_size, num_layers=1, dropout=self.dropout_rate, batch_first=True)
... | interface of language model | LanguageModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageModel:
"""interface of language model"""
def __init__(self):
"""constructor"""
<|body_0|>
def forward(self, en, en_lengths=None):
"""Given a batch of en, doing teacher forcing on it :param en: [bsz, len] :param en_lengths: [bsz] :return logprobs, targets,... | stack_v2_sparse_classes_75kplus_train_005927 | 8,968 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Given a batch of en, doing teacher forcing on it :param en: [bsz, len] :param en_lengths: [bsz] :return logprobs, targets, masks",
"name": "forward",
"signature": "def forward(self, en,... | 3 | stack_v2_sparse_classes_30k_train_036022 | Implement the Python class `LanguageModel` described below.
Class description:
interface of language model
Method signatures and docstrings:
- def __init__(self): constructor
- def forward(self, en, en_lengths=None): Given a batch of en, doing teacher forcing on it :param en: [bsz, len] :param en_lengths: [bsz] :retu... | Implement the Python class `LanguageModel` described below.
Class description:
interface of language model
Method signatures and docstrings:
- def __init__(self): constructor
- def forward(self, en, en_lengths=None): Given a batch of en, doing teacher forcing on it :param en: [bsz, len] :param en_lengths: [bsz] :retu... | 858559c7e39ad82a87ac2546162c7dbadf7d4de8 | <|skeleton|>
class LanguageModel:
"""interface of language model"""
def __init__(self):
"""constructor"""
<|body_0|>
def forward(self, en, en_lengths=None):
"""Given a batch of en, doing teacher forcing on it :param en: [bsz, len] :param en_lengths: [bsz] :return logprobs, targets,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LanguageModel:
"""interface of language model"""
def __init__(self):
"""constructor"""
super(LanguageModel, self).__init__()
self.vocab = Vocab(EN)
self.emb = torch.nn.Embedding(len(self.vocab), self.emb_size)
self.gru = torch.nn.GRU(input_size=self.emb.embedding_d... | the_stack_v2_python_sparse | ld_research/model/agent.py | JACKHAHA363/translation_game_drift | train | 2 |
2f6ba4cc20176528312b371586d926ac57a78300 | [
"iter1 = iter(tt)\niter2 = iter(tt)\nself.assertEquals(lines[0], iter1.next())\nself.assertEquals(lines[0], iter2.next())\nself.assertEquals(lines[1], iter2.next())\nfor ix, line in enumerate(tt):\n self.assertEquals(lines[ix], line)\nfor i in xrange(len(tt)):\n self.assertEquals(lines[i], tt.GetInputs(i))\ns... | <|body_start_0|>
iter1 = iter(tt)
iter2 = iter(tt)
self.assertEquals(lines[0], iter1.next())
self.assertEquals(lines[0], iter2.next())
self.assertEquals(lines[1], iter2.next())
for ix, line in enumerate(tt):
self.assertEquals(lines[ix], line)
for i in ... | Test TruthTable functionality. | TruthTableTest | [
"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 TruthTableTest:
"""Test TruthTable functionality."""
def _TestTableSanity(self, tt, lines):
"""Run the given truth table through basic sanity checks. Args: tt: A TruthTable object. lines: The expect input lines, in order (list of tuples)."""
<|body_0|>
def testTwoDimensi... | stack_v2_sparse_classes_75kplus_train_005928 | 9,390 | permissive | [
{
"docstring": "Run the given truth table through basic sanity checks. Args: tt: A TruthTable object. lines: The expect input lines, in order (list of tuples).",
"name": "_TestTableSanity",
"signature": "def _TestTableSanity(self, tt, lines)"
},
{
"docstring": "Test TruthTable behavior for two b... | 3 | stack_v2_sparse_classes_30k_train_029935 | Implement the Python class `TruthTableTest` described below.
Class description:
Test TruthTable functionality.
Method signatures and docstrings:
- def _TestTableSanity(self, tt, lines): Run the given truth table through basic sanity checks. Args: tt: A TruthTable object. lines: The expect input lines, in order (list ... | Implement the Python class `TruthTableTest` described below.
Class description:
Test TruthTable functionality.
Method signatures and docstrings:
- def _TestTableSanity(self, tt, lines): Run the given truth table through basic sanity checks. Args: tt: A TruthTable object. lines: The expect input lines, in order (list ... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class TruthTableTest:
"""Test TruthTable functionality."""
def _TestTableSanity(self, tt, lines):
"""Run the given truth table through basic sanity checks. Args: tt: A TruthTable object. lines: The expect input lines, in order (list of tuples)."""
<|body_0|>
def testTwoDimensi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TruthTableTest:
"""Test TruthTable functionality."""
def _TestTableSanity(self, tt, lines):
"""Run the given truth table through basic sanity checks. Args: tt: A TruthTable object. lines: The expect input lines, in order (list of tuples)."""
iter1 = iter(tt)
iter2 = iter(tt)
... | the_stack_v2_python_sparse | third_party/chromite/lib/cros_test_lib_unittest.py | metux/chromium-suckless | train | 5 |
80e40081905c1e571740b3c3bcadc49418c112a2 | [
"processor = cls.processors.get(dnn_cfg.processor)\ndownload_model(dnn_cfg, opt_verbose=False)\nreturn processor(dnn_cfg)",
"name = enum_obj.name.lower()\ndnn_cfg = modelzoo_cfg.modelzoo.get(name)\nreturn cls.from_dnn_cfg(dnn_cfg)"
] | <|body_start_0|>
processor = cls.processors.get(dnn_cfg.processor)
download_model(dnn_cfg, opt_verbose=False)
return processor(dnn_cfg)
<|end_body_0|>
<|body_start_1|>
name = enum_obj.name.lower()
dnn_cfg = modelzoo_cfg.modelzoo.get(name)
return cls.from_dnn_cfg(dnn_cfg)... | DNNFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DNNFactory:
def from_dnn_cfg(cls, dnn_cfg):
"""Creates DNN model based on configuration from ModelZoo :param dnn_cfg: DNN object for the model :returns (NetProc):"""
<|body_0|>
def from_enum(cls, enum_obj):
"""Loads DNN model based on enum name. Use from_dnn_cfg for ... | stack_v2_sparse_classes_75kplus_train_005929 | 1,836 | permissive | [
{
"docstring": "Creates DNN model based on configuration from ModelZoo :param dnn_cfg: DNN object for the model :returns (NetProc):",
"name": "from_dnn_cfg",
"signature": "def from_dnn_cfg(cls, dnn_cfg)"
},
{
"docstring": "Loads DNN model based on enum name. Use from_dnn_cfg for custom props. :p... | 2 | stack_v2_sparse_classes_30k_train_014138 | Implement the Python class `DNNFactory` described below.
Class description:
Implement the DNNFactory class.
Method signatures and docstrings:
- def from_dnn_cfg(cls, dnn_cfg): Creates DNN model based on configuration from ModelZoo :param dnn_cfg: DNN object for the model :returns (NetProc):
- def from_enum(cls, enum_... | Implement the Python class `DNNFactory` described below.
Class description:
Implement the DNNFactory class.
Method signatures and docstrings:
- def from_dnn_cfg(cls, dnn_cfg): Creates DNN model based on configuration from ModelZoo :param dnn_cfg: DNN object for the model :returns (NetProc):
- def from_enum(cls, enum_... | 5c490cb72607f60e33467a9a0f412d23024e5963 | <|skeleton|>
class DNNFactory:
def from_dnn_cfg(cls, dnn_cfg):
"""Creates DNN model based on configuration from ModelZoo :param dnn_cfg: DNN object for the model :returns (NetProc):"""
<|body_0|>
def from_enum(cls, enum_obj):
"""Loads DNN model based on enum name. Use from_dnn_cfg for ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DNNFactory:
def from_dnn_cfg(cls, dnn_cfg):
"""Creates DNN model based on configuration from ModelZoo :param dnn_cfg: DNN object for the model :returns (NetProc):"""
processor = cls.processors.get(dnn_cfg.processor)
download_model(dnn_cfg, opt_verbose=False)
return processor(dn... | the_stack_v2_python_sparse | src/vframe/image/dnn_factory.py | vframeio/vframe | train | 50 | |
2fe714f0d5f031224ad4833853eb0a4584c4e254 | [
"self.dim_input = dim_input\nself.dim_output = dim_output\nself.layer_sizes = layer_sizes\nself.activation_fn = activation_fn",
"weights = {}\nwith tf.variable_scope(scope):\n weights['w_0'] = tf.Variable(tf.truncated_normal([self.dim_input, self.layer_sizes[0]], stddev=0.1), name='w_0')\n weights['b_0'] = ... | <|body_start_0|>
self.dim_input = dim_input
self.dim_output = dim_output
self.layer_sizes = layer_sizes
self.activation_fn = activation_fn
<|end_body_0|>
<|body_start_1|>
weights = {}
with tf.variable_scope(scope):
weights['w_0'] = tf.Variable(tf.truncated_no... | Generator for fully connected networks. | FullyConnectedNetworkGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullyConnectedNetworkGenerator:
"""Generator for fully connected networks."""
def __init__(self, dim_input=1, dim_output=1, layer_sizes=(64,), activation_fn=tf.nn.tanh):
"""Creates fully connected neural networks. Args: dim_input: Dimensionality of input (integer > 0). dim_output: Di... | stack_v2_sparse_classes_75kplus_train_005930 | 6,936 | permissive | [
{
"docstring": "Creates fully connected neural networks. Args: dim_input: Dimensionality of input (integer > 0). dim_output: Dimensionality of output (integer > 0). layer_sizes: non-empty list with number of neurons per internal layer. activation_fn: activation function for hidden layers",
"name": "__init__... | 3 | stack_v2_sparse_classes_30k_test_000811 | Implement the Python class `FullyConnectedNetworkGenerator` described below.
Class description:
Generator for fully connected networks.
Method signatures and docstrings:
- def __init__(self, dim_input=1, dim_output=1, layer_sizes=(64,), activation_fn=tf.nn.tanh): Creates fully connected neural networks. Args: dim_inp... | Implement the Python class `FullyConnectedNetworkGenerator` described below.
Class description:
Generator for fully connected networks.
Method signatures and docstrings:
- def __init__(self, dim_input=1, dim_output=1, layer_sizes=(64,), activation_fn=tf.nn.tanh): Creates fully connected neural networks. Args: dim_inp... | dea327aa9e7ef7f7bca5a6c225dbdca1077a06e9 | <|skeleton|>
class FullyConnectedNetworkGenerator:
"""Generator for fully connected networks."""
def __init__(self, dim_input=1, dim_output=1, layer_sizes=(64,), activation_fn=tf.nn.tanh):
"""Creates fully connected neural networks. Args: dim_input: Dimensionality of input (integer > 0). dim_output: Di... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FullyConnectedNetworkGenerator:
"""Generator for fully connected networks."""
def __init__(self, dim_input=1, dim_output=1, layer_sizes=(64,), activation_fn=tf.nn.tanh):
"""Creates fully connected neural networks. Args: dim_input: Dimensionality of input (integer > 0). dim_output: Dimensionality ... | the_stack_v2_python_sparse | norml/networks.py | Tarkiyah/googleResearch | train | 11 |
b4fd9bffee583db8cc45237db4c0604fa3a2c574 | [
"super(AddNoiseToVehicle, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._control = carla.VehicleControl()\nself._actor = actor\nself._steer_value = steer_value\nself._throttle_value = throttle_value",
"self._control = self._actor.get_control()\nself._control.steer = self... | <|body_start_0|>
super(AddNoiseToVehicle, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._control = carla.VehicleControl()
self._actor = actor
self._steer_value = steer_value
self._throttle_value = throttle_value
<|end_body_0|>
<|b... | This class contains an atomic jitter behavior. To add noise to steer as well as throttle of the vehicle. Important parameters: - actor: CARLA actor to execute the behavior - steer_value: Applied steering noise in [0,1] - throttle_value: Applied throttle noise in [0,1] The behavior terminates after setting the new actor... | AddNoiseToVehicle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddNoiseToVehicle:
"""This class contains an atomic jitter behavior. To add noise to steer as well as throttle of the vehicle. Important parameters: - actor: CARLA actor to execute the behavior - steer_value: Applied steering noise in [0,1] - throttle_value: Applied throttle noise in [0,1] The be... | stack_v2_sparse_classes_75kplus_train_005931 | 39,839 | permissive | [
{
"docstring": "Setup actor , maximum steer value and throttle value",
"name": "__init__",
"signature": "def __init__(self, actor, steer_value, throttle_value, name='Jittering')"
},
{
"docstring": "Set steer to steer_value and throttle to throttle_value until reaching full stop",
"name": "up... | 2 | stack_v2_sparse_classes_30k_train_037669 | Implement the Python class `AddNoiseToVehicle` described below.
Class description:
This class contains an atomic jitter behavior. To add noise to steer as well as throttle of the vehicle. Important parameters: - actor: CARLA actor to execute the behavior - steer_value: Applied steering noise in [0,1] - throttle_value:... | Implement the Python class `AddNoiseToVehicle` described below.
Class description:
This class contains an atomic jitter behavior. To add noise to steer as well as throttle of the vehicle. Important parameters: - actor: CARLA actor to execute the behavior - steer_value: Applied steering noise in [0,1] - throttle_value:... | 8ab0894b92e1f994802a218002021ee075c405bf | <|skeleton|>
class AddNoiseToVehicle:
"""This class contains an atomic jitter behavior. To add noise to steer as well as throttle of the vehicle. Important parameters: - actor: CARLA actor to execute the behavior - steer_value: Applied steering noise in [0,1] - throttle_value: Applied throttle noise in [0,1] The be... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddNoiseToVehicle:
"""This class contains an atomic jitter behavior. To add noise to steer as well as throttle of the vehicle. Important parameters: - actor: CARLA actor to execute the behavior - steer_value: Applied steering noise in [0,1] - throttle_value: Applied throttle noise in [0,1] The behavior termin... | the_stack_v2_python_sparse | carla_rllib/carla_rllib-prak_evaluator-carla_rllib-prak_evaluator/carla_rllib/prak_evaluator/srunner/scenarioconfigs/scenariomanager/scenarioatomics/atomic_behaviors.py | TinaMenke/Deep-Reinforcement-Learning | train | 9 |
b66122c1cdb94e43317cbf1907c93488c08410f5 | [
"self.context = context\n'*object* A `control.context.Context` singleton.\\n '\ndone = set()\nfor tp, TypeClass in ALL_TYPES.items():\n self.make(tp, TypeClass)\n done.add(tp)\nfor tp in VALUE_TABLES + USER_TABLES + USER_ENTRY_TABLES + SYSTEM_TABLES:\n if tp in done:\n continue\n TypeName ... | <|body_start_0|>
self.context = context
'*object* A `control.context.Context` singleton.\n '
done = set()
for tp, TypeClass in ALL_TYPES.items():
self.make(tp, TypeClass)
done.add(tp)
for tp in VALUE_TABLES + USER_TABLES + USER_ENTRY_TABLES + SYSTEM... | Provides access to all data types. There are kinds of data types: * scalar types, such as `control.typ.numeric.Int`, `control.typ.datetime.Datetime`, ... * master types: values are ids of master records (e.g. criteria, assessment), see `control.typ.master.Master` * value types values are ids in value tables, see `contr... | Types | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Types:
"""Provides access to all data types. There are kinds of data types: * scalar types, such as `control.typ.numeric.Int`, `control.typ.datetime.Datetime`, ... * master types: values are ids of master records (e.g. criteria, assessment), see `control.typ.master.Master` * value types values ar... | stack_v2_sparse_classes_75kplus_train_005932 | 4,487 | permissive | [
{
"docstring": "## Initialization Creates type singletons for all data types. Some types define operations that need access to `control.db.Db`, or `control.auth.Auth`. The objects for these types will be passed the type singletons that need it, so that they can in turn pass that to their methods. The type singl... | 3 | stack_v2_sparse_classes_30k_train_045879 | Implement the Python class `Types` described below.
Class description:
Provides access to all data types. There are kinds of data types: * scalar types, such as `control.typ.numeric.Int`, `control.typ.datetime.Datetime`, ... * master types: values are ids of master records (e.g. criteria, assessment), see `control.typ... | Implement the Python class `Types` described below.
Class description:
Provides access to all data types. There are kinds of data types: * scalar types, such as `control.typ.numeric.Int`, `control.typ.datetime.Datetime`, ... * master types: values are ids of master records (e.g. criteria, assessment), see `control.typ... | 4c9bec1b74716947ae822c468de1cd0d963cc377 | <|skeleton|>
class Types:
"""Provides access to all data types. There are kinds of data types: * scalar types, such as `control.typ.numeric.Int`, `control.typ.datetime.Datetime`, ... * master types: values are ids of master records (e.g. criteria, assessment), see `control.typ.master.Master` * value types values ar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Types:
"""Provides access to all data types. There are kinds of data types: * scalar types, such as `control.typ.numeric.Int`, `control.typ.datetime.Datetime`, ... * master types: values are ids of master records (e.g. criteria, assessment), see `control.typ.master.Master` * value types values are ids in valu... | the_stack_v2_python_sparse | server/control/typ/types.py | Dans-labs/dariah-contrib | train | 1 |
cb63526c5c18b5e8428849e5279755824bdf2861 | [
"super(PinyinEmbedding, self).__init__()\nwith open(os.path.join(config_path, 'pinyin_map.json')) as fin:\n pinyin_dict = json.load(fin)\nself.pinyin_out_dim = pinyin_out_dim\nself.embedding = nn.Embedding(len(pinyin_dict['idx2char']), embedding_size)\nself.conv = nn.Conv1d(in_channels=embedding_size, out_channe... | <|body_start_0|>
super(PinyinEmbedding, self).__init__()
with open(os.path.join(config_path, 'pinyin_map.json')) as fin:
pinyin_dict = json.load(fin)
self.pinyin_out_dim = pinyin_out_dim
self.embedding = nn.Embedding(len(pinyin_dict['idx2char']), embedding_size)
self.... | PinyinEmbedding | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PinyinEmbedding:
def __init__(self, embedding_size: int, pinyin_out_dim: int, config_path):
"""Pinyin Embedding Module Args: embedding_size: the size of each embedding vector pinyin_out_dim: kernel number of conv"""
<|body_0|>
def forward(self, pinyin_ids):
"""Args: ... | stack_v2_sparse_classes_75kplus_train_005933 | 1,983 | permissive | [
{
"docstring": "Pinyin Embedding Module Args: embedding_size: the size of each embedding vector pinyin_out_dim: kernel number of conv",
"name": "__init__",
"signature": "def __init__(self, embedding_size: int, pinyin_out_dim: int, config_path)"
},
{
"docstring": "Args: pinyin_ids: (bs*sentence_l... | 2 | null | Implement the Python class `PinyinEmbedding` described below.
Class description:
Implement the PinyinEmbedding class.
Method signatures and docstrings:
- def __init__(self, embedding_size: int, pinyin_out_dim: int, config_path): Pinyin Embedding Module Args: embedding_size: the size of each embedding vector pinyin_ou... | Implement the Python class `PinyinEmbedding` described below.
Class description:
Implement the PinyinEmbedding class.
Method signatures and docstrings:
- def __init__(self, embedding_size: int, pinyin_out_dim: int, config_path): Pinyin Embedding Module Args: embedding_size: the size of each embedding vector pinyin_ou... | 9bcb12ba585de8c3232b2ff50eea962fe486f80c | <|skeleton|>
class PinyinEmbedding:
def __init__(self, embedding_size: int, pinyin_out_dim: int, config_path):
"""Pinyin Embedding Module Args: embedding_size: the size of each embedding vector pinyin_out_dim: kernel number of conv"""
<|body_0|>
def forward(self, pinyin_ids):
"""Args: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PinyinEmbedding:
def __init__(self, embedding_size: int, pinyin_out_dim: int, config_path):
"""Pinyin Embedding Module Args: embedding_size: the size of each embedding vector pinyin_out_dim: kernel number of conv"""
super(PinyinEmbedding, self).__init__()
with open(os.path.join(config_... | the_stack_v2_python_sparse | models/pinyin_embedding.py | SnailDM/ChineseBert | train | 1 | |
b5e535ea31f8b3683829e49dfeb1a5c0523f8206 | [
"manager = multiprocessing.Manager()\nhelper_queue = manager.Queue()\nresult_queue = manager.Queue()\ncompleted_queue = manager.Queue()\nhelper_process = multiprocessing.Process(target=pipeline_worker.Helper, args=(TEST_STAGE, {}, helper_queue, completed_queue, result_queue))\nhelper_process.start()\nmock_result = ... | <|body_start_0|>
manager = multiprocessing.Manager()
helper_queue = manager.Queue()
result_queue = manager.Queue()
completed_queue = manager.Queue()
helper_process = multiprocessing.Process(target=pipeline_worker.Helper, args=(TEST_STAGE, {}, helper_queue, completed_queue, result... | This class tests the pipeline_worker functions. Given the same identifier, the cost should result the same from the pipeline_worker functions. | PipelineWorkerTest | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelineWorkerTest:
"""This class tests the pipeline_worker functions. Given the same identifier, the cost should result the same from the pipeline_worker functions."""
def testHelper(self):
""""Test the helper. Call the helper method twice, and test the results. The results should b... | stack_v2_sparse_classes_75kplus_train_005934 | 4,118 | permissive | [
{
"docstring": "\"Test the helper. Call the helper method twice, and test the results. The results should be the same, i.e., the cost should be the same.",
"name": "testHelper",
"signature": "def testHelper(self)"
},
{
"docstring": "\"Test the worker method. The worker should process all the inp... | 2 | stack_v2_sparse_classes_30k_train_045072 | Implement the Python class `PipelineWorkerTest` described below.
Class description:
This class tests the pipeline_worker functions. Given the same identifier, the cost should result the same from the pipeline_worker functions.
Method signatures and docstrings:
- def testHelper(self): "Test the helper. Call the helper... | Implement the Python class `PipelineWorkerTest` described below.
Class description:
This class tests the pipeline_worker functions. Given the same identifier, the cost should result the same from the pipeline_worker functions.
Method signatures and docstrings:
- def testHelper(self): "Test the helper. Call the helper... | e2745b756317aac3c7a27a4c10bdfe0921a82a1c | <|skeleton|>
class PipelineWorkerTest:
"""This class tests the pipeline_worker functions. Given the same identifier, the cost should result the same from the pipeline_worker functions."""
def testHelper(self):
""""Test the helper. Call the helper method twice, and test the results. The results should b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PipelineWorkerTest:
"""This class tests the pipeline_worker functions. Given the same identifier, the cost should result the same from the pipeline_worker functions."""
def testHelper(self):
""""Test the helper. Call the helper method twice, and test the results. The results should be the same, i... | the_stack_v2_python_sparse | app/src/main/java/com/syd/source/aosp/external/toolchain-utils/bestflags/pipeline_worker_test.py | lz-purple/Source | train | 4 |
6f18163324dc410bfc230996742340b1134952c5 | [
"super().__init__(interval, by_epoch, save_optimizer, out_dir, max_keep_ckpts, save_last, sync_buffer, **kwargs)\nself.iter_interval = iter_interval\nself.by_iter = by_iter\nassert save_mode in ['general', 'lightweight'], 'save mode should be general and lightweight, but found' + save_mode\nself.save_mode = save_mo... | <|body_start_0|>
super().__init__(interval, by_epoch, save_optimizer, out_dir, max_keep_ckpts, save_last, sync_buffer, **kwargs)
self.iter_interval = iter_interval
self.by_iter = by_iter
assert save_mode in ['general', 'lightweight'], 'save mode should be general and lightweight, but fou... | Customized Checkpoint Hook, support to only save nearest and best checkpoints | DavarCheckpointHook | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DavarCheckpointHook:
"""Customized Checkpoint Hook, support to only save nearest and best checkpoints"""
def __init__(self, interval=1, iter_interval=-1, by_epoch=True, by_iter=False, metric='accuracy', rule='greater', init_metric=0, save_optimizer=True, out_dir=None, save_mode='general', mo... | stack_v2_sparse_classes_75kplus_train_005935 | 11,737 | permissive | [
{
"docstring": "Args: interval (int): The epoch saving period. iter_interval (int): The iteration saving period. by_epoch (bool): Saving checkpoints by epoch by_iter (bool): Saving checkpoints by iteration epoch_metric (str): the epoch metric compare during save best checkpoint iter_metric (str): the iteration ... | 5 | null | Implement the Python class `DavarCheckpointHook` described below.
Class description:
Customized Checkpoint Hook, support to only save nearest and best checkpoints
Method signatures and docstrings:
- def __init__(self, interval=1, iter_interval=-1, by_epoch=True, by_iter=False, metric='accuracy', rule='greater', init_... | Implement the Python class `DavarCheckpointHook` described below.
Class description:
Customized Checkpoint Hook, support to only save nearest and best checkpoints
Method signatures and docstrings:
- def __init__(self, interval=1, iter_interval=-1, by_epoch=True, by_iter=False, metric='accuracy', rule='greater', init_... | fb47a96d1a38f5ce634c6f12d710ed5300cc89fc | <|skeleton|>
class DavarCheckpointHook:
"""Customized Checkpoint Hook, support to only save nearest and best checkpoints"""
def __init__(self, interval=1, iter_interval=-1, by_epoch=True, by_iter=False, metric='accuracy', rule='greater', init_metric=0, save_optimizer=True, out_dir=None, save_mode='general', mo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DavarCheckpointHook:
"""Customized Checkpoint Hook, support to only save nearest and best checkpoints"""
def __init__(self, interval=1, iter_interval=-1, by_epoch=True, by_iter=False, metric='accuracy', rule='greater', init_metric=0, save_optimizer=True, out_dir=None, save_mode='general', model_milestone... | the_stack_v2_python_sparse | davarocr/davarocr/mmcv/runner/hooks/davar_checkpoint.py | OCRWorld/DAVAR-Lab-OCR | train | 0 |
263e5959b31cfd1fd36b06df83e75abccae02e17 | [
"assumptions = [set(preorder) == set(inorder), len(preorder) == len(set(preorder)), len(inorder) == len(set(inorder))]\nif not all(assumptions):\n raise ValueError('both traversals must have same length, and no duplicates')\nreturn self.build_tree_recursive(preorder, inorder)",
"if len(preorder) == len(inorder... | <|body_start_0|>
assumptions = [set(preorder) == set(inorder), len(preorder) == len(set(preorder)), len(inorder) == len(set(inorder))]
if not all(assumptions):
raise ValueError('both traversals must have same length, and no duplicates')
return self.build_tree_recursive(preorder, inor... | Solution for Leetcode problem 105: Bin Tree from Inorder & Preorder. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Solution for Leetcode problem 105: Bin Tree from Inorder & Preorder."""
def build_tree(self, preorder, inorder):
"""Build a binary tree from inorder and postorder traversals. :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus_train_005936 | 1,780 | no_license | [
{
"docstring": "Build a binary tree from inorder and postorder traversals. :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode",
"name": "build_tree",
"signature": "def build_tree(self, preorder, inorder)"
},
{
"docstring": "Bin Tree from Inorder-Preorder: recursive solution.",
... | 2 | stack_v2_sparse_classes_30k_val_001889 | Implement the Python class `Solution` described below.
Class description:
Solution for Leetcode problem 105: Bin Tree from Inorder & Preorder.
Method signatures and docstrings:
- def build_tree(self, preorder, inorder): Build a binary tree from inorder and postorder traversals. :type preorder: List[int] :type inorder... | Implement the Python class `Solution` described below.
Class description:
Solution for Leetcode problem 105: Bin Tree from Inorder & Preorder.
Method signatures and docstrings:
- def build_tree(self, preorder, inorder): Build a binary tree from inorder and postorder traversals. :type preorder: List[int] :type inorder... | e11bfc454789e716055b80873af0817ec8588aea | <|skeleton|>
class Solution:
"""Solution for Leetcode problem 105: Bin Tree from Inorder & Preorder."""
def build_tree(self, preorder, inorder):
"""Build a binary tree from inorder and postorder traversals. :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""Solution for Leetcode problem 105: Bin Tree from Inorder & Preorder."""
def build_tree(self, preorder, inorder):
"""Build a binary tree from inorder and postorder traversals. :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
assumptions = [set(preorder) =... | the_stack_v2_python_sparse | p105/problem105.py | stanl3y/leetcode | train | 0 |
6dbbf34b08a0889690a98890dfe0b9a8ce610b0b | [
"self.context_length = self.config.context_path.num_blocks\nself.double_channel = self.config.context_path.num_double_channel\nself.context_num_stage = self.config.context_path.num_stage\nself.spatial_length = self.config.spatial_path.num_blocks\nself.spatial_num_stages = self.config.spatial_path.num_stages",
"ar... | <|body_start_0|>
self.context_length = self.config.context_path.num_blocks
self.double_channel = self.config.context_path.num_double_channel
self.context_num_stage = self.config.context_path.num_stage
self.spatial_length = self.config.spatial_path.num_blocks
self.spatial_num_stag... | Random algorithm of SegmentationNas. | SegmentationRandom | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegmentationRandom:
"""Random algorithm of SegmentationNas."""
def __init__(self, search_space=None):
"""Construct the SegmentationRandom class. :param search_space: Config of the search space"""
<|body_0|>
def random_context_generator(self, length=10, num_reduction=3, n... | stack_v2_sparse_classes_75kplus_train_005937 | 3,505 | permissive | [
{
"docstring": "Construct the SegmentationRandom class. :param search_space: Config of the search space",
"name": "__init__",
"signature": "def __init__(self, search_space=None)"
},
{
"docstring": "Generate a random code of BiSeNet's context path. :param length: Length of the BiSeNet's context p... | 4 | stack_v2_sparse_classes_30k_train_011427 | Implement the Python class `SegmentationRandom` described below.
Class description:
Random algorithm of SegmentationNas.
Method signatures and docstrings:
- def __init__(self, search_space=None): Construct the SegmentationRandom class. :param search_space: Config of the search space
- def random_context_generator(sel... | Implement the Python class `SegmentationRandom` described below.
Class description:
Random algorithm of SegmentationNas.
Method signatures and docstrings:
- def __init__(self, search_space=None): Construct the SegmentationRandom class. :param search_space: Config of the search space
- def random_context_generator(sel... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class SegmentationRandom:
"""Random algorithm of SegmentationNas."""
def __init__(self, search_space=None):
"""Construct the SegmentationRandom class. :param search_space: Config of the search space"""
<|body_0|>
def random_context_generator(self, length=10, num_reduction=3, n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SegmentationRandom:
"""Random algorithm of SegmentationNas."""
def __init__(self, search_space=None):
"""Construct the SegmentationRandom class. :param search_space: Config of the search space"""
self.context_length = self.config.context_path.num_blocks
self.double_channel = self.... | the_stack_v2_python_sparse | vega/algorithms/nas/segmentation_ea/segmentation_random.py | huawei-noah/vega | train | 850 |
12badb9d737392f06581d18a659f78f5bd292b99 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | MinesweeperServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinesweeperServicer:
"""Missing associated documentation comment in .proto file."""
def NewGame(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def StartLevel(self, request, context):
"""Missing associated docume... | stack_v2_sparse_classes_75kplus_train_005938 | 6,985 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "NewGame",
"signature": "def NewGame(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "StartLevel",
"signature": "def StartLevel(self, request,... | 4 | stack_v2_sparse_classes_30k_train_032260 | Implement the Python class `MinesweeperServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def NewGame(self, request, context): Missing associated documentation comment in .proto file.
- def StartLevel(self, request, context): Miss... | Implement the Python class `MinesweeperServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def NewGame(self, request, context): Missing associated documentation comment in .proto file.
- def StartLevel(self, request, context): Miss... | 9dc8bcd4b64a72252b0002ae387479d1bb372d44 | <|skeleton|>
class MinesweeperServicer:
"""Missing associated documentation comment in .proto file."""
def NewGame(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def StartLevel(self, request, context):
"""Missing associated docume... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MinesweeperServicer:
"""Missing associated documentation comment in .proto file."""
def NewGame(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | 2020/etterretningstjenesten/cybertalent-winter/3_utfordringer/2_middels/minesweeper/minesweeper_pb2_grpc.py | mklarz/ctf-writeups | train | 2 |
511f999fb628e26e60b6c6f258549e5bffd307d8 | [
"self.iscsi_access = iscsi_access\nself.nfs_4_access = nfs_4_access\nself.nfs_access = nfs_access\nself.s3_access = s3_access\nself.smb_access = smb_access\nself.swift_access = swift_access",
"if dictionary is None:\n return None\niscsi_access = dictionary.get('iscsiAccess')\nnfs_4_access = dictionary.get('nfs... | <|body_start_0|>
self.iscsi_access = iscsi_access
self.nfs_4_access = nfs_4_access
self.nfs_access = nfs_access
self.s3_access = s3_access
self.smb_access = smb_access
self.swift_access = swift_access
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'ViewIdMappingProto_ProtocolAccessInfo' model. TODO: type description here. Attributes: iscsi_access (int): Access control for iSCSI protocol for this view. nfs_4_access (int): Access control for NFSv4.1 protocol for this view. NFSv4.1 will be disabled by default in all configurations. nfs_access ... | ViewIdMappingProto_ProtocolAccessInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewIdMappingProto_ProtocolAccessInfo:
"""Implementation of the 'ViewIdMappingProto_ProtocolAccessInfo' model. TODO: type description here. Attributes: iscsi_access (int): Access control for iSCSI protocol for this view. nfs_4_access (int): Access control for NFSv4.1 protocol for this view. NFSv4... | stack_v2_sparse_classes_75kplus_train_005939 | 2,769 | permissive | [
{
"docstring": "Constructor for the ViewIdMappingProto_ProtocolAccessInfo class",
"name": "__init__",
"signature": "def __init__(self, iscsi_access=None, nfs_4_access=None, nfs_access=None, s3_access=None, smb_access=None, swift_access=None)"
},
{
"docstring": "Creates an instance of this model ... | 2 | stack_v2_sparse_classes_30k_train_015345 | Implement the Python class `ViewIdMappingProto_ProtocolAccessInfo` described below.
Class description:
Implementation of the 'ViewIdMappingProto_ProtocolAccessInfo' model. TODO: type description here. Attributes: iscsi_access (int): Access control for iSCSI protocol for this view. nfs_4_access (int): Access control fo... | Implement the Python class `ViewIdMappingProto_ProtocolAccessInfo` described below.
Class description:
Implementation of the 'ViewIdMappingProto_ProtocolAccessInfo' model. TODO: type description here. Attributes: iscsi_access (int): Access control for iSCSI protocol for this view. nfs_4_access (int): Access control fo... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ViewIdMappingProto_ProtocolAccessInfo:
"""Implementation of the 'ViewIdMappingProto_ProtocolAccessInfo' model. TODO: type description here. Attributes: iscsi_access (int): Access control for iSCSI protocol for this view. nfs_4_access (int): Access control for NFSv4.1 protocol for this view. NFSv4... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ViewIdMappingProto_ProtocolAccessInfo:
"""Implementation of the 'ViewIdMappingProto_ProtocolAccessInfo' model. TODO: type description here. Attributes: iscsi_access (int): Access control for iSCSI protocol for this view. nfs_4_access (int): Access control for NFSv4.1 protocol for this view. NFSv4.1 will be di... | the_stack_v2_python_sparse | cohesity_management_sdk/models/view_id_mapping_proto_protocol_access_info.py | cohesity/management-sdk-python | train | 24 |
07c302659613dc86989e223d825f21a08768065f | [
"payload = request.get_json(silent=True)\nif not payload:\n return response_builder(dict(message='Redemption request must have data.', status='fail'), 400)\nresult, errors = redemption_request_schema.load(payload)\nif errors:\n return response_builder(errors, 400)\nif result.get('value') > g.current_user.soci... | <|body_start_0|>
payload = request.get_json(silent=True)
if not payload:
return response_builder(dict(message='Redemption request must have data.', status='fail'), 400)
result, errors = redemption_request_schema.load(payload)
if errors:
return response_builder(err... | Resource handling all point redemption requests. Only made by society presidents. | PointRedemptionAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointRedemptionAPI:
"""Resource handling all point redemption requests. Only made by society presidents."""
def post(cls):
"""Create Redemption Request."""
<|body_0|>
def put(cls, redeem_id=None):
"""Edit Redemption Requests."""
<|body_1|>
def get(cl... | stack_v2_sparse_classes_75kplus_train_005940 | 14,043 | permissive | [
{
"docstring": "Create Redemption Request.",
"name": "post",
"signature": "def post(cls)"
},
{
"docstring": "Edit Redemption Requests.",
"name": "put",
"signature": "def put(cls, redeem_id=None)"
},
{
"docstring": "Get Redemption Requests.",
"name": "get",
"signature": "d... | 4 | null | Implement the Python class `PointRedemptionAPI` described below.
Class description:
Resource handling all point redemption requests. Only made by society presidents.
Method signatures and docstrings:
- def post(cls): Create Redemption Request.
- def put(cls, redeem_id=None): Edit Redemption Requests.
- def get(cls, r... | Implement the Python class `PointRedemptionAPI` described below.
Class description:
Resource handling all point redemption requests. Only made by society presidents.
Method signatures and docstrings:
- def post(cls): Create Redemption Request.
- def put(cls, redeem_id=None): Edit Redemption Requests.
- def get(cls, r... | 69842100d8d7c0b946fb328ddc6c8f88d777606d | <|skeleton|>
class PointRedemptionAPI:
"""Resource handling all point redemption requests. Only made by society presidents."""
def post(cls):
"""Create Redemption Request."""
<|body_0|>
def put(cls, redeem_id=None):
"""Edit Redemption Requests."""
<|body_1|>
def get(cl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PointRedemptionAPI:
"""Resource handling all point redemption requests. Only made by society presidents."""
def post(cls):
"""Create Redemption Request."""
payload = request.get_json(silent=True)
if not payload:
return response_builder(dict(message='Redemption request ... | the_stack_v2_python_sparse | src/api/endpoints/redemption_requests.py | Gfreedoms/andela-societies-backend | train | 0 |
358afdd8b06306e4e43aed50c6931e93204a894b | [
"super().__init__(**kwargs)\nself._djvu = djvu\nself._index = index\nself._prefix = self._index.title(with_ns=False)\nself._page_ns = self.site._proofread_page_ns.custom_name\nif not pages:\n self._pages = (1, self._djvu.number_of_images())\nelse:\n self._pages = pages\nif not self.opt.summary:\n self.opt.... | <|body_start_0|>
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
el... | A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot | DjVuTextBot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DjVuTextBot:
"""A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot"""
def __init__(self, djvu, index, pages: Optional[tuple]=None, **kwargs) -> None:
"""... | stack_v2_sparse_classes_75kplus_train_005941 | 6,604 | permissive | [
{
"docstring": "Initializer. :param djvu: djvu from where to fetch the text layer :type djvu: DjVuFile object :param index: index page in the Index: namespace :type index: Page object :param pages: page interval to upload (start, end)",
"name": "__init__",
"signature": "def __init__(self, djvu, index, p... | 4 | stack_v2_sparse_classes_30k_train_020588 | Implement the Python class `DjVuTextBot` described below.
Class description:
A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot
Method signatures and docstrings:
- def __init__(self, djvu... | Implement the Python class `DjVuTextBot` described below.
Class description:
A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot
Method signatures and docstrings:
- def __init__(self, djvu... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class DjVuTextBot:
"""A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot"""
def __init__(self, djvu, index, pages: Optional[tuple]=None, **kwargs) -> None:
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DjVuTextBot:
"""A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot"""
def __init__(self, djvu, index, pages: Optional[tuple]=None, **kwargs) -> None:
"""Initializer. ... | the_stack_v2_python_sparse | scripts/djvutext.py | wikimedia/pywikibot | train | 432 |
a22185544a7f253e95967705f19161dccf18d4ae | [
"super(MADF, self).__init__()\nself.in_channels_m = in_channels_m\nself.out_channels_m = out_channels_m\nself.in_channels_e = in_channels_e\nself.out_channels_e = out_channels_e\nself.kernel_size_e = kernel_size_e\nself.kernel_size_m = kernel_size_m\nself.padding_e = padding_e\nself.padding_m = padding_m\nself.stri... | <|body_start_0|>
super(MADF, self).__init__()
self.in_channels_m = in_channels_m
self.out_channels_m = out_channels_m
self.in_channels_e = in_channels_e
self.out_channels_e = out_channels_e
self.kernel_size_e = kernel_size_e
self.kernel_size_m = kernel_size_m
... | MADF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MADF:
def __init__(self, in_channels_m, out_channels_m, in_channels_e, out_channels_e, kernel_size_m, kernel_size_e, stride_m, stride_e, padding_m, padding_e, activation_m='relu', activation_e='relu', norm_m='none', norm_e='bn', device=torch.device('cpu')):
""":param in_channels_m: input... | stack_v2_sparse_classes_75kplus_train_005942 | 14,232 | no_license | [
{
"docstring": ":param in_channels_m: input channels of mask layer - m {l-1} :param out_channels_m: output channels of mask layer - m {l} :param in_channels_e: input chanels of image layer - e {l-1} :param out_channels_e: output channels of image layer - e {l} :param kernel_size_m: kernel size for transformatio... | 2 | stack_v2_sparse_classes_30k_train_020581 | Implement the Python class `MADF` described below.
Class description:
Implement the MADF class.
Method signatures and docstrings:
- def __init__(self, in_channels_m, out_channels_m, in_channels_e, out_channels_e, kernel_size_m, kernel_size_e, stride_m, stride_e, padding_m, padding_e, activation_m='relu', activation_e... | Implement the Python class `MADF` described below.
Class description:
Implement the MADF class.
Method signatures and docstrings:
- def __init__(self, in_channels_m, out_channels_m, in_channels_e, out_channels_e, kernel_size_m, kernel_size_e, stride_m, stride_e, padding_m, padding_e, activation_m='relu', activation_e... | eb9325edb73208ea992eda4be2a92119be867d10 | <|skeleton|>
class MADF:
def __init__(self, in_channels_m, out_channels_m, in_channels_e, out_channels_e, kernel_size_m, kernel_size_e, stride_m, stride_e, padding_m, padding_e, activation_m='relu', activation_e='relu', norm_m='none', norm_e='bn', device=torch.device('cpu')):
""":param in_channels_m: input... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MADF:
def __init__(self, in_channels_m, out_channels_m, in_channels_e, out_channels_e, kernel_size_m, kernel_size_e, stride_m, stride_e, padding_m, padding_e, activation_m='relu', activation_e='relu', norm_m='none', norm_e='bn', device=torch.device('cpu')):
""":param in_channels_m: input channels of m... | the_stack_v2_python_sparse | models/MadfGAN/model/blocks.py | Oorgien/Scene-Inpainting | train | 1 | |
1b19863ef40dd60b7fd4adccea061d33ed5dd887 | [
"user = User(username='Keith', email='no@no.com')\nuser.save()\nself.user = user\nself.client = Client()",
"\"\"\"Deletes users made for testing purposes.\"\"\"\nUser.objects.all().delete()\nsuper(TestCase, self)",
"self.client.force_login(self.user)\nresponse = self.client.get(reverse_lazy('home'))\nself.clien... | <|body_start_0|>
user = User(username='Keith', email='no@no.com')
user.save()
self.user = user
self.client = Client()
<|end_body_0|>
<|body_start_1|>
"""Deletes users made for testing purposes."""
User.objects.all().delete()
super(TestCase, self)
<|end_body_1|>
... | Test views related to staff (Profile, ProfileEdit, and StaffList). | TestStaffViews | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStaffViews:
"""Test views related to staff (Profile, ProfileEdit, and StaffList)."""
def setUp(self):
"""Set up."""
<|body_0|>
def tearDown(self):
"""Tear down."""
<|body_1|>
def test_200_status_on_authenticated_request_to_profile(self):
... | stack_v2_sparse_classes_75kplus_train_005943 | 1,850 | permissive | [
{
"docstring": "Set up.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tear down.",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "Check that an authenticated request returns 200 status.",
"name": "test_200_status_on_authenticat... | 4 | stack_v2_sparse_classes_30k_train_054541 | Implement the Python class `TestStaffViews` described below.
Class description:
Test views related to staff (Profile, ProfileEdit, and StaffList).
Method signatures and docstrings:
- def setUp(self): Set up.
- def tearDown(self): Tear down.
- def test_200_status_on_authenticated_request_to_profile(self): Check that a... | Implement the Python class `TestStaffViews` described below.
Class description:
Test views related to staff (Profile, ProfileEdit, and StaffList).
Method signatures and docstrings:
- def setUp(self): Set up.
- def tearDown(self): Tear down.
- def test_200_status_on_authenticated_request_to_profile(self): Check that a... | 6d9b594f317107cd26932485dd8d063e226970fa | <|skeleton|>
class TestStaffViews:
"""Test views related to staff (Profile, ProfileEdit, and StaffList)."""
def setUp(self):
"""Set up."""
<|body_0|>
def tearDown(self):
"""Tear down."""
<|body_1|>
def test_200_status_on_authenticated_request_to_profile(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestStaffViews:
"""Test views related to staff (Profile, ProfileEdit, and StaffList)."""
def setUp(self):
"""Set up."""
user = User(username='Keith', email='no@no.com')
user.save()
self.user = user
self.client = Client()
def tearDown(self):
"""Tear dow... | the_stack_v2_python_sparse | lwb_heartbeat/lwb_heartbeat/tests.py | lwb-connect/lwb_heartbeat | train | 1 |
9aae7500ab1b7763f71f27faf8cb934c7d9e29b7 | [
"self.observerSubjects = {}\nself.lock = threading.Lock()\nfor notifMethod in notificationMethods:\n self.add_notification_method(notifMethod)",
"with self.lock:\n if notifMethod in self.observerSubjects.keys():\n return\n self.observerSubjects[notifMethod] = ObserverSubject(notifMethod)\n seta... | <|body_start_0|>
self.observerSubjects = {}
self.lock = threading.Lock()
for notifMethod in notificationMethods:
self.add_notification_method(notifMethod)
<|end_body_0|>
<|body_start_1|>
with self.lock:
if notifMethod in self.observerSubjects.keys():
... | MultiObserverSubject ObserverSubject with multiple distinct notification methods. Works essentially the same way as ObserverSubject. The rational is to be able to notify different objects for different types of updates. Attributes ---------- observerSubjects : dict({str:ObserverSubject}) Dictionary of ObserverSubject i... | MultiObserverSubject | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiObserverSubject:
"""MultiObserverSubject ObserverSubject with multiple distinct notification methods. Works essentially the same way as ObserverSubject. The rational is to be able to notify different objects for different types of updates. Attributes ---------- observerSubjects : dict({str:O... | stack_v2_sparse_classes_75kplus_train_005944 | 11,424 | permissive | [
{
"docstring": "Parameters ---------- notificationMethods : list(str) list of nofication method names to be handled. A new alias method for this instance will be created with each of these names. See ObserverSubject.__init__() for details.",
"name": "__init__",
"signature": "def __init__(self, notificat... | 4 | null | Implement the Python class `MultiObserverSubject` described below.
Class description:
MultiObserverSubject ObserverSubject with multiple distinct notification methods. Works essentially the same way as ObserverSubject. The rational is to be able to notify different objects for different types of updates. Attributes --... | Implement the Python class `MultiObserverSubject` described below.
Class description:
MultiObserverSubject ObserverSubject with multiple distinct notification methods. Works essentially the same way as ObserverSubject. The rational is to be able to notify different objects for different types of updates. Attributes --... | d5f1abeae0b0473b895b4735f182ddae0516a1bd | <|skeleton|>
class MultiObserverSubject:
"""MultiObserverSubject ObserverSubject with multiple distinct notification methods. Works essentially the same way as ObserverSubject. The rational is to be able to notify different objects for different types of updates. Attributes ---------- observerSubjects : dict({str:O... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiObserverSubject:
"""MultiObserverSubject ObserverSubject with multiple distinct notification methods. Works essentially the same way as ObserverSubject. The rational is to be able to notify different objects for different types of updates. Attributes ---------- observerSubjects : dict({str:ObserverSubjec... | the_stack_v2_python_sparse | nephelae/types/ObserverPattern.py | pnarvor/nephelae_base | train | 0 |
3a5334ae9c7d1beee66ddbd6c858fbd0619b185f | [
"super(RPNHead, self).__init__()\nanchor_genarator = DefaultAnchorGenerator(cfg, input_shape)\nassert len(set((shape[0] for shape in input_shape))) == 1, 'Each level must have the same in_channel!'\nin_channels = input_shape[0][0]\nnum_anchors = anchor_genarator.num_anchors\nself.conv = nn.Conv2d(in_channels, in_ch... | <|body_start_0|>
super(RPNHead, self).__init__()
anchor_genarator = DefaultAnchorGenerator(cfg, input_shape)
assert len(set((shape[0] for shape in input_shape))) == 1, 'Each level must have the same in_channel!'
in_channels = input_shape[0][0]
num_anchors = anchor_genarator.num_a... | RPNHead | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RPNHead:
def __init__(self, cfg, input_shape, box_dim: int=4):
""":param cfg: :param input_shape: (list[list[int]]) list of (channels, height, width, stride) :param box_dim:"""
<|body_0|>
def forward(self, features):
""":param features: (list[tensor]) could use fpn :... | stack_v2_sparse_classes_75kplus_train_005945 | 3,458 | no_license | [
{
"docstring": ":param cfg: :param input_shape: (list[list[int]]) list of (channels, height, width, stride) :param box_dim:",
"name": "__init__",
"signature": "def __init__(self, cfg, input_shape, box_dim: int=4)"
},
{
"docstring": ":param features: (list[tensor]) could use fpn :return: rpn_cls_... | 2 | stack_v2_sparse_classes_30k_train_009309 | Implement the Python class `RPNHead` described below.
Class description:
Implement the RPNHead class.
Method signatures and docstrings:
- def __init__(self, cfg, input_shape, box_dim: int=4): :param cfg: :param input_shape: (list[list[int]]) list of (channels, height, width, stride) :param box_dim:
- def forward(self... | Implement the Python class `RPNHead` described below.
Class description:
Implement the RPNHead class.
Method signatures and docstrings:
- def __init__(self, cfg, input_shape, box_dim: int=4): :param cfg: :param input_shape: (list[list[int]]) list of (channels, height, width, stride) :param box_dim:
- def forward(self... | 1b4fb1e5c38ea8989aa57e2dd53e9b867036faaf | <|skeleton|>
class RPNHead:
def __init__(self, cfg, input_shape, box_dim: int=4):
""":param cfg: :param input_shape: (list[list[int]]) list of (channels, height, width, stride) :param box_dim:"""
<|body_0|>
def forward(self, features):
""":param features: (list[tensor]) could use fpn :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RPNHead:
def __init__(self, cfg, input_shape, box_dim: int=4):
""":param cfg: :param input_shape: (list[list[int]]) list of (channels, height, width, stride) :param box_dim:"""
super(RPNHead, self).__init__()
anchor_genarator = DefaultAnchorGenerator(cfg, input_shape)
assert le... | the_stack_v2_python_sparse | rpn/RPN.py | zjjszj/accumulation | train | 0 | |
3de7e65d8aff5eeabe000b15a93114d834d21ec2 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | The CAS (content-addressable storage) is used to store the inputs to and outputs from the execution service. Each piece of content is addressed by the digest of its binary data. Most of the binary data stored in the CAS is opaque to the execution engine, and is only used as a communication medium. In order to build an ... | ContentAddressableStorageServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContentAddressableStorageServicer:
"""The CAS (content-addressable storage) is used to store the inputs to and outputs from the execution service. Each piece of content is addressed by the digest of its binary data. Most of the binary data stored in the CAS is opaque to the execution engine, and ... | stack_v2_sparse_classes_75kplus_train_005946 | 24,490 | no_license | [
{
"docstring": "Determine if blobs are present in the CAS. Clients can use this API before uploading blobs to determine which ones are already present in the CAS and do not need to be uploaded again. There are no method-specific errors.",
"name": "FindMissingBlobs",
"signature": "def FindMissingBlobs(se... | 3 | stack_v2_sparse_classes_30k_train_022221 | Implement the Python class `ContentAddressableStorageServicer` described below.
Class description:
The CAS (content-addressable storage) is used to store the inputs to and outputs from the execution service. Each piece of content is addressed by the digest of its binary data. Most of the binary data stored in the CAS ... | Implement the Python class `ContentAddressableStorageServicer` described below.
Class description:
The CAS (content-addressable storage) is used to store the inputs to and outputs from the execution service. Each piece of content is addressed by the digest of its binary data. Most of the binary data stored in the CAS ... | d7424d21aa0dc121acc4d64b427ba365a3581a20 | <|skeleton|>
class ContentAddressableStorageServicer:
"""The CAS (content-addressable storage) is used to store the inputs to and outputs from the execution service. Each piece of content is addressed by the digest of its binary data. Most of the binary data stored in the CAS is opaque to the execution engine, and ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContentAddressableStorageServicer:
"""The CAS (content-addressable storage) is used to store the inputs to and outputs from the execution service. Each piece of content is addressed by the digest of its binary data. Most of the binary data stored in the CAS is opaque to the execution engine, and is only used ... | the_stack_v2_python_sparse | google/devtools/remoteexecution/v1test/remote_execution_pb2_grpc.py | msachtler/bazel-event-protocol-parser | train | 1 |
046ad089503cf0997d47a497883f642cd811841d | [
"super(Spectrogram, self).__init__()\nself.fl = fl\nself.fs = fs\nself.fn = fn\nself.sr = sr\nself.with_emphasis = with_emphasis\nself.with_delta = with_delta\nreturn",
"if self.with_emphasis:\n x[:, 1:] = x[:, 1:] - 0.97 * x[:, 0:-1]\nx_stft = torch.stft(x, self.fn, self.fs, self.fl, window=torch.hamming_wind... | <|body_start_0|>
super(Spectrogram, self).__init__()
self.fl = fl
self.fs = fs
self.fn = fn
self.sr = sr
self.with_emphasis = with_emphasis
self.with_delta = with_delta
return
<|end_body_0|>
<|body_start_1|>
if self.with_emphasis:
x[:,... | Spectrogram front-end | Spectrogram | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Spectrogram:
"""Spectrogram front-end"""
def __init__(self, fl, fs, fn, sr, with_emphasis=True, with_delta=False):
"""Initialize LFCC Para: ----- fl: int, frame length, (number of waveform points) fs: int, frame shift, (number of waveform points) fn: int, FFT points sr: int, sampling... | stack_v2_sparse_classes_75kplus_train_005947 | 11,719 | permissive | [
{
"docstring": "Initialize LFCC Para: ----- fl: int, frame length, (number of waveform points) fs: int, frame shift, (number of waveform points) fn: int, FFT points sr: int, sampling rate (Hz) with_emphasis: bool, (default True), whether pre-emphaze input wav with_delta: bool, (default False), whether use delta... | 2 | null | Implement the Python class `Spectrogram` described below.
Class description:
Spectrogram front-end
Method signatures and docstrings:
- def __init__(self, fl, fs, fn, sr, with_emphasis=True, with_delta=False): Initialize LFCC Para: ----- fl: int, frame length, (number of waveform points) fs: int, frame shift, (number ... | Implement the Python class `Spectrogram` described below.
Class description:
Spectrogram front-end
Method signatures and docstrings:
- def __init__(self, fl, fs, fn, sr, with_emphasis=True, with_delta=False): Initialize LFCC Para: ----- fl: int, frame length, (number of waveform points) fs: int, frame shift, (number ... | 55da4137149df297ed656ede9c3e4f75a7eaf552 | <|skeleton|>
class Spectrogram:
"""Spectrogram front-end"""
def __init__(self, fl, fs, fn, sr, with_emphasis=True, with_delta=False):
"""Initialize LFCC Para: ----- fl: int, frame length, (number of waveform points) fs: int, frame shift, (number of waveform points) fn: int, FFT points sr: int, sampling... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Spectrogram:
"""Spectrogram front-end"""
def __init__(self, fl, fs, fn, sr, with_emphasis=True, with_delta=False):
"""Initialize LFCC Para: ----- fl: int, frame length, (number of waveform points) fs: int, frame shift, (number of waveform points) fn: int, FFT points sr: int, sampling rate (Hz) wi... | the_stack_v2_python_sparse | LA/Baseline-LFCC-LCNN/sandbox/util_frontend.py | Jungjee/2021 | train | 0 |
6a2cbf381116c650ca27b2edec36989e5f3ede63 | [
"if 'table' not in k:\n k['table'] = self.table\nif 'engine' not in k:\n k['engine'] = k['table'].bind\nreturn alter_column(self, *p, **k)",
"table = _normalize_table(self, table)\nengine = table.bind\nvisitorcallable = get_engine_visitor(engine, 'columngenerator')\nengine._run_visitor(visitorcallable, self... | <|body_start_0|>
if 'table' not in k:
k['table'] = self.table
if 'engine' not in k:
k['engine'] = k['table'].bind
return alter_column(self, *p, **k)
<|end_body_0|>
<|body_start_1|>
table = _normalize_table(self, table)
engine = table.bind
visitorc... | Changeset extensions to SQLAlchemy columns | ChangesetColumn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangesetColumn:
"""Changeset extensions to SQLAlchemy columns"""
def alter(self, *p, **k):
"""Alter a column's definition: ALTER TABLE ALTER COLUMN May supply a new column object, or a list of properties to change. For example; the following are equivalent: col.alter(Column('myint',... | stack_v2_sparse_classes_75kplus_train_005948 | 13,328 | no_license | [
{
"docstring": "Alter a column's definition: ALTER TABLE ALTER COLUMN May supply a new column object, or a list of properties to change. For example; the following are equivalent: col.alter(Column('myint',Integer,nullable=False)) col.alter('myint',Integer,nullable=False) col.alter(name='myint',type=Integer,null... | 3 | stack_v2_sparse_classes_30k_train_028501 | Implement the Python class `ChangesetColumn` described below.
Class description:
Changeset extensions to SQLAlchemy columns
Method signatures and docstrings:
- def alter(self, *p, **k): Alter a column's definition: ALTER TABLE ALTER COLUMN May supply a new column object, or a list of properties to change. For example... | Implement the Python class `ChangesetColumn` described below.
Class description:
Changeset extensions to SQLAlchemy columns
Method signatures and docstrings:
- def alter(self, *p, **k): Alter a column's definition: ALTER TABLE ALTER COLUMN May supply a new column object, or a list of properties to change. For example... | 971b9c3eb8ca941d1797bb4b458f275bdca5a2cb | <|skeleton|>
class ChangesetColumn:
"""Changeset extensions to SQLAlchemy columns"""
def alter(self, *p, **k):
"""Alter a column's definition: ALTER TABLE ALTER COLUMN May supply a new column object, or a list of properties to change. For example; the following are equivalent: col.alter(Column('myint',... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChangesetColumn:
"""Changeset extensions to SQLAlchemy columns"""
def alter(self, *p, **k):
"""Alter a column's definition: ALTER TABLE ALTER COLUMN May supply a new column object, or a list of properties to change. For example; the following are equivalent: col.alter(Column('myint',Integer,nulla... | the_stack_v2_python_sparse | sqlalchemy-migrate/migrate/changeset/schema.py | arianepaola/tg2jython | train | 1 |
e8bb21eeb9f858c7d70128e2855fb45f4db612de | [
"payments = Payment.objects.filter(order=self)\namount = 0\nfor payment in payments:\n amount += payment.item.price * payment.quantity\nself.required_usd_amount = amount\nself.save()",
"if self.status not in ('WAITING_FOR_PAYMENT',):\n return False\nreturn now() - self.created_date < timedelta(seconds=self.... | <|body_start_0|>
payments = Payment.objects.filter(order=self)
amount = 0
for payment in payments:
amount += payment.item.price * payment.quantity
self.required_usd_amount = amount
self.save()
<|end_body_0|>
<|body_start_1|>
if self.status not in ('WAITING_FO... | Main model for orders, their rates calculations and so on | Order | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Order:
"""Main model for orders, their rates calculations and so on"""
def get_required_amount(self):
"""get sum amount for order."""
<|body_0|>
def is_active(self):
"""Return True if: * status is 'WAITING_FOR_PAYMENT' * time_to_live is more than time passed from... | stack_v2_sparse_classes_75kplus_train_005949 | 2,641 | no_license | [
{
"docstring": "get sum amount for order.",
"name": "get_required_amount",
"signature": "def get_required_amount(self)"
},
{
"docstring": "Return True if: * status is 'WAITING_FOR_PAYMENT' * time_to_live is more than time passed from model creation",
"name": "is_active",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_004023 | Implement the Python class `Order` described below.
Class description:
Main model for orders, their rates calculations and so on
Method signatures and docstrings:
- def get_required_amount(self): get sum amount for order.
- def is_active(self): Return True if: * status is 'WAITING_FOR_PAYMENT' * time_to_live is more ... | Implement the Python class `Order` described below.
Class description:
Main model for orders, their rates calculations and so on
Method signatures and docstrings:
- def get_required_amount(self): get sum amount for order.
- def is_active(self): Return True if: * status is 'WAITING_FOR_PAYMENT' * time_to_live is more ... | d3db5bae8d04a6ff2be0a5fe5da11148cce29080 | <|skeleton|>
class Order:
"""Main model for orders, their rates calculations and so on"""
def get_required_amount(self):
"""get sum amount for order."""
<|body_0|>
def is_active(self):
"""Return True if: * status is 'WAITING_FOR_PAYMENT' * time_to_live is more than time passed from... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Order:
"""Main model for orders, their rates calculations and so on"""
def get_required_amount(self):
"""get sum amount for order."""
payments = Payment.objects.filter(order=self)
amount = 0
for payment in payments:
amount += payment.item.price * payment.quanti... | the_stack_v2_python_sparse | remusgold/payments/models.py | MyWishPlatform/proof_of_gold | train | 2 |
3374a531aa2cfe6ed74982eddff281bc7f23fbfe | [
"super().__init__(name, env, location)\nself.classical_routing_table = {}\nself.quantum_routing_table = {}\nrouting = QKDRouting(f'QKDRouting_{self.name}')\nself.protocol_stack.build(routing)\nself.load_protocol(self.protocol_stack)",
"key_gen_proto = super().set_key_generation(peer, **kwargs)\nif key_gen_proto i... | <|body_start_0|>
super().__init__(name, env, location)
self.classical_routing_table = {}
self.quantum_routing_table = {}
routing = QKDRouting(f'QKDRouting_{self.name}')
self.protocol_stack.build(routing)
self.load_protocol(self.protocol_stack)
<|end_body_0|>
<|body_start... | Class for the simulation of a trusted repeater node. Attributes: classical_routing_table (Dict[Node, Node]): classical routing table the trusted repeater holds quantum_routing_table (Dict[Node, Node]): quantum routing table the trusted repeater holds | TrustedRepeaterNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrustedRepeaterNode:
"""Class for the simulation of a trusted repeater node. Attributes: classical_routing_table (Dict[Node, Node]): classical routing table the trusted repeater holds quantum_routing_table (Dict[Node, Node]): quantum routing table the trusted repeater holds"""
def __init__(s... | stack_v2_sparse_classes_75kplus_train_005950 | 13,868 | permissive | [
{
"docstring": "Constructor for TrustedRepeaterNode class. Args: name (str): name of the trusted repeater env (DESEnv): related discrete-event simulation environment location (Tuple): geographical location of the trusted repeater",
"name": "__init__",
"signature": "def __init__(self, name: str, env=None... | 2 | stack_v2_sparse_classes_30k_train_048984 | Implement the Python class `TrustedRepeaterNode` described below.
Class description:
Class for the simulation of a trusted repeater node. Attributes: classical_routing_table (Dict[Node, Node]): classical routing table the trusted repeater holds quantum_routing_table (Dict[Node, Node]): quantum routing table the truste... | Implement the Python class `TrustedRepeaterNode` described below.
Class description:
Class for the simulation of a trusted repeater node. Attributes: classical_routing_table (Dict[Node, Node]): classical routing table the trusted repeater holds quantum_routing_table (Dict[Node, Node]): quantum routing table the truste... | 8bc3c7238b5b6825eb63ded8d65afb08b389941f | <|skeleton|>
class TrustedRepeaterNode:
"""Class for the simulation of a trusted repeater node. Attributes: classical_routing_table (Dict[Node, Node]): classical routing table the trusted repeater holds quantum_routing_table (Dict[Node, Node]): quantum routing table the trusted repeater holds"""
def __init__(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrustedRepeaterNode:
"""Class for the simulation of a trusted repeater node. Attributes: classical_routing_table (Dict[Node, Node]): classical routing table the trusted repeater holds quantum_routing_table (Dict[Node, Node]): quantum routing table the trusted repeater holds"""
def __init__(self, name: st... | the_stack_v2_python_sparse | Extensions/QuantumNetwork/qcompute_qnet/models/qkd/node.py | baidu/QCompute | train | 86 |
a5453690d8b7effd231cd61fa80600e8d431960e | [
"self.unique_identifier = unique_identifier\nself.enduses = enduses\nself.shape_yd = shape_yd\nself.shape_yh = shape_yh\nself.enduse_peak_yd_factor = enduse_peak_yd_factor\nself.shape_y_dh = self.calc_y_dh_shape_from_yh()\nself.shape_peak_dh = shape_peak_dh",
"sum_every_day_p = 1 / np.sum(self.shape_yh, axis=1)\n... | <|body_start_0|>
self.unique_identifier = unique_identifier
self.enduses = enduses
self.shape_yd = shape_yd
self.shape_yh = shape_yh
self.enduse_peak_yd_factor = enduse_peak_yd_factor
self.shape_y_dh = self.calc_y_dh_shape_from_yh()
self.shape_peak_dh = shape_peak... | Load profile container to store different shapes Parameters ---------- unique_identifier : string Unique identifer for LoadProfile object shape_yd : array Shape yd (from year to day) shape_yh : array Shape yh (from year to hour) enduse_peak_yd_factor : float Factor to calculate daily demand from yearly demand Standard ... | LoadProfile | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadProfile:
"""Load profile container to store different shapes Parameters ---------- unique_identifier : string Unique identifer for LoadProfile object shape_yd : array Shape yd (from year to day) shape_yh : array Shape yh (from year to hour) enduse_peak_yd_factor : float Factor to calculate da... | stack_v2_sparse_classes_75kplus_train_005951 | 11,374 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, enduses, unique_identifier, shape_yd, shape_yh, enduse_peak_yd_factor, shape_peak_dh)"
},
{
"docstring": "Calculate shape for every day Returns ------- shape_y_dh : array Shape for every day Note ---- The output g... | 2 | stack_v2_sparse_classes_30k_test_000660 | Implement the Python class `LoadProfile` described below.
Class description:
Load profile container to store different shapes Parameters ---------- unique_identifier : string Unique identifer for LoadProfile object shape_yd : array Shape yd (from year to day) shape_yh : array Shape yh (from year to hour) enduse_peak_y... | Implement the Python class `LoadProfile` described below.
Class description:
Load profile container to store different shapes Parameters ---------- unique_identifier : string Unique identifer for LoadProfile object shape_yd : array Shape yd (from year to day) shape_yh : array Shape yh (from year to hour) enduse_peak_y... | 59a2712f353f47e3dc237479cc6cc46666b7d0f1 | <|skeleton|>
class LoadProfile:
"""Load profile container to store different shapes Parameters ---------- unique_identifier : string Unique identifer for LoadProfile object shape_yd : array Shape yd (from year to day) shape_yh : array Shape yh (from year to hour) enduse_peak_yd_factor : float Factor to calculate da... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoadProfile:
"""Load profile container to store different shapes Parameters ---------- unique_identifier : string Unique identifer for LoadProfile object shape_yd : array Shape yd (from year to day) shape_yh : array Shape yh (from year to hour) enduse_peak_yd_factor : float Factor to calculate daily demand fr... | the_stack_v2_python_sparse | energy_demand/profiles/load_profile.py | willu47/energy_demand | train | 0 |
7b417e98ac1fc919dd3b5144129a027e4cb4ec55 | [
"super(MDSSClassificationMetric, self).__init__(dataset, classified_dataset, unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups)\nself.scoring = scoring\nself.kwargs = kwargs",
"groups = self.privileged_groups if privileged else self.unprivileged_groups\nsubset = dict()\nfor g in groups:... | <|body_start_0|>
super(MDSSClassificationMetric, self).__init__(dataset, classified_dataset, unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups)
self.scoring = scoring
self.kwargs = kwargs
<|end_body_0|>
<|body_start_1|>
groups = self.privileged_groups if privi... | Bias subset scanning is proposed as a technique to identify bias in predictive models using subset scanning [#zhang16]_. This class is a wrapper for the bias scan scoring and scanning methods that uses the ClassificationMetric abstraction. References: .. [#zhang16] `Zhang, Z. and Neill, D. B., "Identifying significant ... | MDSSClassificationMetric | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MDSSClassificationMetric:
"""Bias subset scanning is proposed as a technique to identify bias in predictive models using subset scanning [#zhang16]_. This class is a wrapper for the bias scan scoring and scanning methods that uses the ClassificationMetric abstraction. References: .. [#zhang16] `Z... | stack_v2_sparse_classes_75kplus_train_005952 | 7,590 | permissive | [
{
"docstring": "Args: dataset (BinaryLabelDataset): Dataset containing ground-truth labels. classified_dataset (BinaryLabelDataset): Dataset containing predictions. scoring (str or ScoringFunction): One of 'Bernoulli' (parametric), or 'BerkJones' (non-parametric) or subclass of :class:`aif360.metrics.mdss.Scori... | 3 | stack_v2_sparse_classes_30k_train_045060 | Implement the Python class `MDSSClassificationMetric` described below.
Class description:
Bias subset scanning is proposed as a technique to identify bias in predictive models using subset scanning [#zhang16]_. This class is a wrapper for the bias scan scoring and scanning methods that uses the ClassificationMetric ab... | Implement the Python class `MDSSClassificationMetric` described below.
Class description:
Bias subset scanning is proposed as a technique to identify bias in predictive models using subset scanning [#zhang16]_. This class is a wrapper for the bias scan scoring and scanning methods that uses the ClassificationMetric ab... | 6f9972e4a7dbca2402f29b86ea67889143dbeb3e | <|skeleton|>
class MDSSClassificationMetric:
"""Bias subset scanning is proposed as a technique to identify bias in predictive models using subset scanning [#zhang16]_. This class is a wrapper for the bias scan scoring and scanning methods that uses the ClassificationMetric abstraction. References: .. [#zhang16] `Z... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MDSSClassificationMetric:
"""Bias subset scanning is proposed as a technique to identify bias in predictive models using subset scanning [#zhang16]_. This class is a wrapper for the bias scan scoring and scanning methods that uses the ClassificationMetric abstraction. References: .. [#zhang16] `Zhang, Z. and ... | the_stack_v2_python_sparse | aif360/metrics/mdss_classification_metric.py | Trusted-AI/AIF360 | train | 1,157 |
8a9451623368ddd5659f55ce7599328bb6060a28 | [
"char_set = set()\nrtn_cal = 0\nfor each_ in s:\n if each_ in char_set:\n rtn_cal += 2\n char_set.remove(each_)\n else:\n char_set.add(each_)\nif len(char_set) > 0:\n return rtn_cal + 1\nreturn rtn_cal",
"char_map = {}\nfor char_ in s:\n if char_ in char_map:\n char_map[cha... | <|body_start_0|>
char_set = set()
rtn_cal = 0
for each_ in s:
if each_ in char_set:
rtn_cal += 2
char_set.remove(each_)
else:
char_set.add(each_)
if len(char_set) > 0:
return rtn_cal + 1
return rt... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestPalindromeOld(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
char_set = set()
rtn_cal = 0
for each_... | stack_v2_sparse_classes_75kplus_train_005953 | 2,203 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "longestPalindromeOld",
"signature": "def longestPalindromeOld(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051839 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: int
- def longestPalindromeOld(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: int
- def longestPalindromeOld(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def longestPalindrome(se... | 196e58cd38db846653fb074cfd0363997121a7cf | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestPalindromeOld(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: int"""
char_set = set()
rtn_cal = 0
for each_ in s:
if each_ in char_set:
rtn_cal += 2
char_set.remove(each_)
else:
char_set.add(each_)
... | the_stack_v2_python_sparse | Longest Palindrome.py | nithinveer/leetcode-solutions | train | 0 | |
9f3bcc7e3d06add3f3037968964eb83b1a65dfda | [
"self.d = {}\nfor w in dictionary:\n if not w:\n continue\n if len(w) <= 2:\n self.d.setdefault(w, set()).add(w)\n else:\n ab = w[0] + str(len(w) - 2) + w[-1]\n self.d.setdefault(ab, set()).add(w)",
"if not word:\n return True\nif len(word) <= 2:\n ab = word\nelse:\n ... | <|body_start_0|>
self.d = {}
for w in dictionary:
if not w:
continue
if len(w) <= 2:
self.d.setdefault(w, set()).add(w)
else:
ab = w[0] + str(len(w) - 2) + w[-1]
self.d.setdefault(ab, set()).add(w)
<|end_... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str] self.d = { "d2r" : set(door, deer....) }"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.d = {... | stack_v2_sparse_classes_75kplus_train_005954 | 1,069 | no_license | [
{
"docstring": ":type dictionary: List[str] self.d = { \"d2r\" : set(door, deer....) }",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": ":type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001829 | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str] self.d = { "d2r" : set(door, deer....) }
- def isUnique(self, word): :type word: str :rtype: bool | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str] self.d = { "d2r" : set(door, deer....) }
- def isUnique(self, word): :type word: str :rtype: bool
<|skeleto... | d6a4b68227dde82ec4d41805e22a999d526d9688 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str] self.d = { "d2r" : set(door, deer....) }"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str] self.d = { "d2r" : set(door, deer....) }"""
self.d = {}
for w in dictionary:
if not w:
continue
if len(w) <= 2:
self.d.setdefault(w, set()).add(w)
... | the_stack_v2_python_sparse | 288. Word Abbreviations.py | coder-rush/LeetCode | train | 0 | |
6907e0c2364ed3be942df852b3b9afd7d78e9680 | [
"client = Client()\nresponse = client.get('/this_page_does_not_exist')\nself.assertContains(response, '404 message', status_code=404)",
"client = Client()\nresponse = client.post('/foobar', data={'q': 'Python'})\nself.assertContains(response, '404 message', status_code=404)"
] | <|body_start_0|>
client = Client()
response = client.get('/this_page_does_not_exist')
self.assertContains(response, '404 message', status_code=404)
<|end_body_0|>
<|body_start_1|>
client = Client()
response = client.post('/foobar', data={'q': 'Python'})
self.assertContai... | Test the Http Error pages. | HttpErrorHandling | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpErrorHandling:
"""Test the Http Error pages."""
def test404(self):
"""Test the 404 response."""
<|body_0|>
def test404_bis(self):
"""Test the 404 response."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
client = Client()
response = ... | stack_v2_sparse_classes_75kplus_train_005955 | 6,545 | permissive | [
{
"docstring": "Test the 404 response.",
"name": "test404",
"signature": "def test404(self)"
},
{
"docstring": "Test the 404 response.",
"name": "test404_bis",
"signature": "def test404_bis(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042367 | Implement the Python class `HttpErrorHandling` described below.
Class description:
Test the Http Error pages.
Method signatures and docstrings:
- def test404(self): Test the 404 response.
- def test404_bis(self): Test the 404 response. | Implement the Python class `HttpErrorHandling` described below.
Class description:
Test the Http Error pages.
Method signatures and docstrings:
- def test404(self): Test the 404 response.
- def test404_bis(self): Test the 404 response.
<|skeleton|>
class HttpErrorHandling:
"""Test the Http Error pages."""
d... | 497eed7a65ffff3ce4406081892b258d8c62427b | <|skeleton|>
class HttpErrorHandling:
"""Test the Http Error pages."""
def test404(self):
"""Test the 404 response."""
<|body_0|>
def test404_bis(self):
"""Test the 404 response."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HttpErrorHandling:
"""Test the Http Error pages."""
def test404(self):
"""Test the 404 response."""
client = Client()
response = client.get('/this_page_does_not_exist')
self.assertContains(response, '404 message', status_code=404)
def test404_bis(self):
"""Tes... | the_stack_v2_python_sparse | blog/tests.py | todokku/zink | train | 0 |
e8f5f83d0decce308c64fc03be1410deab912a39 | [
"super().__init__()\nself.models: dict[str, Any] = {}\nself.node_models: dict[int, str] = {}",
"model_class = self.models.get(model_name)\nif not model_class:\n raise ValueError(f'{model_name} is an invalid model')\nmodel_config = self.get_model_config(node_id, model_name)\nif not config:\n config = {}\nfor... | <|body_start_0|>
super().__init__()
self.models: dict[str, Any] = {}
self.node_models: dict[int, str] = {}
<|end_body_0|>
<|body_start_1|>
model_class = self.models.get(model_name)
if not model_class:
raise ValueError(f'{model_name} is an invalid model')
mode... | Helps handle setting models for nodes and managing their model configurations. | ModelManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelManager:
"""Helps handle setting models for nodes and managing their model configurations."""
def __init__(self) -> None:
"""Creates a ModelManager object."""
<|body_0|>
def set_model_config(self, node_id: int, model_name: str, config: dict[str, str]=None) -> None:
... | stack_v2_sparse_classes_75kplus_train_005956 | 11,690 | permissive | [
{
"docstring": "Creates a ModelManager object.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Set configuration data for a model. :param node_id: node id to set model configuration for :param model_name: model to set configuration for :param config: configurat... | 5 | stack_v2_sparse_classes_30k_train_026605 | Implement the Python class `ModelManager` described below.
Class description:
Helps handle setting models for nodes and managing their model configurations.
Method signatures and docstrings:
- def __init__(self) -> None: Creates a ModelManager object.
- def set_model_config(self, node_id: int, model_name: str, config... | Implement the Python class `ModelManager` described below.
Class description:
Helps handle setting models for nodes and managing their model configurations.
Method signatures and docstrings:
- def __init__(self) -> None: Creates a ModelManager object.
- def set_model_config(self, node_id: int, model_name: str, config... | 20071eed2e73a2287aa385698dd604f4933ae7ff | <|skeleton|>
class ModelManager:
"""Helps handle setting models for nodes and managing their model configurations."""
def __init__(self) -> None:
"""Creates a ModelManager object."""
<|body_0|>
def set_model_config(self, node_id: int, model_name: str, config: dict[str, str]=None) -> None:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelManager:
"""Helps handle setting models for nodes and managing their model configurations."""
def __init__(self) -> None:
"""Creates a ModelManager object."""
super().__init__()
self.models: dict[str, Any] = {}
self.node_models: dict[int, str] = {}
def set_model_... | the_stack_v2_python_sparse | daemon/core/config.py | coreemu/core | train | 606 |
cd46006ce73c8e211d25c066e48fbe241d6f708a | [
"if left == right == n:\n self.res_lst.append(res)\n return res\nif left < n:\n self.generate(left + 1, right, n, res + '(')\nif left > right:\n self.generate(left, right + 1, n, res + ')')",
"self.res_lst = list()\nself.generate(left=0, right=0, n=n, res='')\nreturn self.res_lst"
] | <|body_start_0|>
if left == right == n:
self.res_lst.append(res)
return res
if left < n:
self.generate(left + 1, right, n, res + '(')
if left > right:
self.generate(left, right + 1, n, res + ')')
<|end_body_0|>
<|body_start_1|>
self.res_ls... | 思路与算法 任何一个括号序列都一定是由 ( 开头,并且第一个 ( 一定有一个唯一与之对应的 )。这样一来,每一个括号序列可以用 (a)b 来表示,其中 a 与 b 分别是一个合法的括号序列(可以为空)。 那么,要生成所有长度为 2 * n 的括号序列,我们定义一个函数 generate(n) 来返回所有可能的括号序列。那么在函数 generate(n) 的过程中: 我们需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1; 递归调用 generate(i) 即可计算 a 的所有可能性; 递归调用 generate(n - i - 1) 即可计算 b 的所有可能性; 遍历 a 与 b 的所有可能性并拼接,即可得到所有长度为 2... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""思路与算法 任何一个括号序列都一定是由 ( 开头,并且第一个 ( 一定有一个唯一与之对应的 )。这样一来,每一个括号序列可以用 (a)b 来表示,其中 a 与 b 分别是一个合法的括号序列(可以为空)。 那么,要生成所有长度为 2 * n 的括号序列,我们定义一个函数 generate(n) 来返回所有可能的括号序列。那么在函数 generate(n) 的过程中: 我们需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1; 递归调用 generate(i) 即可计算 a 的所有可能性; 递归调用 generate(n - i - 1) 即可计算 b 的所... | stack_v2_sparse_classes_75kplus_train_005957 | 2,063 | no_license | [
{
"docstring": ":param left: :param right: :param n: 配额总数 :param res: :return:",
"name": "generate",
"signature": "def generate(self, left, right, n, res)"
},
{
"docstring": ":param n: :return:",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053158 | Implement the Python class `Solution` described below.
Class description:
思路与算法 任何一个括号序列都一定是由 ( 开头,并且第一个 ( 一定有一个唯一与之对应的 )。这样一来,每一个括号序列可以用 (a)b 来表示,其中 a 与 b 分别是一个合法的括号序列(可以为空)。 那么,要生成所有长度为 2 * n 的括号序列,我们定义一个函数 generate(n) 来返回所有可能的括号序列。那么在函数 generate(n) 的过程中: 我们需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1; 递归调用 generate(i) 即可计算 a 的所有... | Implement the Python class `Solution` described below.
Class description:
思路与算法 任何一个括号序列都一定是由 ( 开头,并且第一个 ( 一定有一个唯一与之对应的 )。这样一来,每一个括号序列可以用 (a)b 来表示,其中 a 与 b 分别是一个合法的括号序列(可以为空)。 那么,要生成所有长度为 2 * n 的括号序列,我们定义一个函数 generate(n) 来返回所有可能的括号序列。那么在函数 generate(n) 的过程中: 我们需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1; 递归调用 generate(i) 即可计算 a 的所有... | 47d5eaef3cf1adccaf42eb463a5c4548e003cb59 | <|skeleton|>
class Solution:
"""思路与算法 任何一个括号序列都一定是由 ( 开头,并且第一个 ( 一定有一个唯一与之对应的 )。这样一来,每一个括号序列可以用 (a)b 来表示,其中 a 与 b 分别是一个合法的括号序列(可以为空)。 那么,要生成所有长度为 2 * n 的括号序列,我们定义一个函数 generate(n) 来返回所有可能的括号序列。那么在函数 generate(n) 的过程中: 我们需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1; 递归调用 generate(i) 即可计算 a 的所有可能性; 递归调用 generate(n - i - 1) 即可计算 b 的所... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""思路与算法 任何一个括号序列都一定是由 ( 开头,并且第一个 ( 一定有一个唯一与之对应的 )。这样一来,每一个括号序列可以用 (a)b 来表示,其中 a 与 b 分别是一个合法的括号序列(可以为空)。 那么,要生成所有长度为 2 * n 的括号序列,我们定义一个函数 generate(n) 来返回所有可能的括号序列。那么在函数 generate(n) 的过程中: 我们需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1; 递归调用 generate(i) 即可计算 a 的所有可能性; 递归调用 generate(n - i - 1) 即可计算 b 的所有可能性; 遍历 a 与 ... | the_stack_v2_python_sparse | Week_03/22_括号生成.py | wffeige/algorithm015 | train | 0 |
26514f4c8854fec576c9c5cd8cd57bdc8bf9433d | [
"super(CombiBeamDecoder, self).__init__(decoder_args)\nif decoder_args.combination_scheme == 'length_norm':\n self.breakdown2score = core.breakdown2score_length_norm\nif decoder_args.combination_scheme == 'bayesian_loglin':\n self.breakdown2score = core.breakdown2score_bayesian_loglin\nif decoder_args.combina... | <|body_start_0|>
super(CombiBeamDecoder, self).__init__(decoder_args)
if decoder_args.combination_scheme == 'length_norm':
self.breakdown2score = core.breakdown2score_length_norm
if decoder_args.combination_scheme == 'bayesian_loglin':
self.breakdown2score = core.breakdow... | This beam search implementation is a modification to the hypo expansion strategy. Rather than selecting hypotheses based on the sum of the previous hypo scores and the current one, we apply combination_scheme in each time step. This makes it possible to use schemes like Bayesian combination on the word rather than the ... | CombiBeamDecoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CombiBeamDecoder:
"""This beam search implementation is a modification to the hypo expansion strategy. Rather than selecting hypotheses based on the sum of the previous hypo scores and the current one, we apply combination_scheme in each time step. This makes it possible to use schemes like Bayes... | stack_v2_sparse_classes_75kplus_train_005958 | 2,705 | permissive | [
{
"docstring": "Creates a new beam decoder instance. In addition to the constructor of `BeamDecoder`, the following values are fetched from `decoder_args`: combination_scheme (string): breakdown2score strategy",
"name": "__init__",
"signature": "def __init__(self, decoder_args)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_008933 | Implement the Python class `CombiBeamDecoder` described below.
Class description:
This beam search implementation is a modification to the hypo expansion strategy. Rather than selecting hypotheses based on the sum of the previous hypo scores and the current one, we apply combination_scheme in each time step. This make... | Implement the Python class `CombiBeamDecoder` described below.
Class description:
This beam search implementation is a modification to the hypo expansion strategy. Rather than selecting hypotheses based on the sum of the previous hypo scores and the current one, we apply combination_scheme in each time step. This make... | e7cac78676326ec4b2f219fc13e1de0e899975b0 | <|skeleton|>
class CombiBeamDecoder:
"""This beam search implementation is a modification to the hypo expansion strategy. Rather than selecting hypotheses based on the sum of the previous hypo scores and the current one, we apply combination_scheme in each time step. This makes it possible to use schemes like Bayes... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CombiBeamDecoder:
"""This beam search implementation is a modification to the hypo expansion strategy. Rather than selecting hypotheses based on the sum of the previous hypo scores and the current one, we apply combination_scheme in each time step. This makes it possible to use schemes like Bayesian combinati... | the_stack_v2_python_sparse | cam/sgnmt/decoding/combibeam.py | Jack44Wang/sgnmt | train | 0 |
e38000c26d4dc2fe8124f557220a23bf35120d03 | [
"if not email:\n raise ValueError('User must be have a valid Email Address')\nif not kwargs.get('username'):\n raise ValueError('User must have a valid Username')\nif not kwargs.get('teaching_institution'):\n raise ValueError('User must have a valid Teaching Institution')\nif not kwargs.get('first_name'):\... | <|body_start_0|>
if not email:
raise ValueError('User must be have a valid Email Address')
if not kwargs.get('username'):
raise ValueError('User must have a valid Username')
if not kwargs.get('teaching_institution'):
raise ValueError('User must have a valid Te... | AccountManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountManager:
def create_user(self, email, password=None, **kwargs):
"""Create an user, with email, username, teaching institution, first name, last name and password"""
<|body_0|>
def create_superuser(self, email, password, **kwargs):
"""Create a superuser, with e... | stack_v2_sparse_classes_75kplus_train_005959 | 4,255 | no_license | [
{
"docstring": "Create an user, with email, username, teaching institution, first name, last name and password",
"name": "create_user",
"signature": "def create_user(self, email, password=None, **kwargs)"
},
{
"docstring": "Create a superuser, with email, username, teaching institution, first na... | 2 | stack_v2_sparse_classes_30k_train_034142 | Implement the Python class `AccountManager` described below.
Class description:
Implement the AccountManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None, **kwargs): Create an user, with email, username, teaching institution, first name, last name and password
- def create_sup... | Implement the Python class `AccountManager` described below.
Class description:
Implement the AccountManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None, **kwargs): Create an user, with email, username, teaching institution, first name, last name and password
- def create_sup... | 8f296850eeab1df4c52bb7b9df0681884449e761 | <|skeleton|>
class AccountManager:
def create_user(self, email, password=None, **kwargs):
"""Create an user, with email, username, teaching institution, first name, last name and password"""
<|body_0|>
def create_superuser(self, email, password, **kwargs):
"""Create a superuser, with e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountManager:
def create_user(self, email, password=None, **kwargs):
"""Create an user, with email, username, teaching institution, first name, last name and password"""
if not email:
raise ValueError('User must be have a valid Email Address')
if not kwargs.get('username'... | the_stack_v2_python_sparse | src/web/authentication/models.py | CiberRato/pei2015-ciberrato | train | 0 | |
7832225e48e1e4f5c0d50cfc54300dcc2910dfef | [
"self.read_data(filename)\nself.prep_dataset()\nself.standardize()\nself.apply_PCA()",
"with open(filename) as infile:\n next(infile)\n for line in infile:\n line = line.strip().split(',')\n features = line[:-2]\n features = list(map(float, features))\n self.targets.append(line[-... | <|body_start_0|>
self.read_data(filename)
self.prep_dataset()
self.standardize()
self.apply_PCA()
<|end_body_0|>
<|body_start_1|>
with open(filename) as infile:
next(infile)
for line in infile:
line = line.strip().split(',')
... | At this stage we initialize the variables needed in the various methods below. | PCA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PCA:
"""At this stage we initialize the variables needed in the various methods below."""
def __init__(self, filename):
"""Initialization method - acts as a controller Args: filename (string): path to the file to process"""
<|body_0|>
def read_data(self, filename):
... | stack_v2_sparse_classes_75kplus_train_005960 | 4,762 | no_license | [
{
"docstring": "Initialization method - acts as a controller Args: filename (string): path to the file to process",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Loads in the specified file. Creates features vector and targets vector Args: filename (string): ... | 5 | stack_v2_sparse_classes_30k_train_043809 | Implement the Python class `PCA` described below.
Class description:
At this stage we initialize the variables needed in the various methods below.
Method signatures and docstrings:
- def __init__(self, filename): Initialization method - acts as a controller Args: filename (string): path to the file to process
- def ... | Implement the Python class `PCA` described below.
Class description:
At this stage we initialize the variables needed in the various methods below.
Method signatures and docstrings:
- def __init__(self, filename): Initialization method - acts as a controller Args: filename (string): path to the file to process
- def ... | 1106cf0dbc88490fd925f1c7c8e27dc088f29de9 | <|skeleton|>
class PCA:
"""At this stage we initialize the variables needed in the various methods below."""
def __init__(self, filename):
"""Initialization method - acts as a controller Args: filename (string): path to the file to process"""
<|body_0|>
def read_data(self, filename):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PCA:
"""At this stage we initialize the variables needed in the various methods below."""
def __init__(self, filename):
"""Initialization method - acts as a controller Args: filename (string): path to the file to process"""
self.read_data(filename)
self.prep_dataset()
self... | the_stack_v2_python_sparse | src/PCA/dim_red.py | flight505/Shared_Intro_ML | train | 0 |
570b83ef88f4cbe3562c4a7c7beb977671e8fec7 | [
"try:\n args = parser.parse_args()\n data = control.roles_users.role_user_list(args['user_name'], args['role_name'])\nexcept Exception as e:\n return (set_return_val(False, {}, str(e), 1234), 400)\nreturn set_return_val(True, data, '获取列表成功', 1234)",
"try:\n args = parser.parse_args()\n user_id = ar... | <|body_start_0|>
try:
args = parser.parse_args()
data = control.roles_users.role_user_list(args['user_name'], args['role_name'])
except Exception as e:
return (set_return_val(False, {}, str(e), 1234), 400)
return set_return_val(True, data, '获取列表成功', 1234)
<|en... | RolesUsersManage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RolesUsersManage:
def get(self):
"""获取用户角色列表 --- tags: - user_role parameters: - in: query type: string name: user_name description: 用户名 - in: query name: role_name type: string description: 角色名 responses: 200: description: 获取用户角色信息 schema: properties: ok: type: boolean default: 200 desc... | stack_v2_sparse_classes_75kplus_train_005961 | 8,276 | no_license | [
{
"docstring": "获取用户角色列表 --- tags: - user_role parameters: - in: query type: string name: user_name description: 用户名 - in: query name: role_name type: string description: 角色名 responses: 200: description: 获取用户角色信息 schema: properties: ok: type: boolean default: 200 description: 状态 code: type: string msg: type: st... | 4 | stack_v2_sparse_classes_30k_train_045425 | Implement the Python class `RolesUsersManage` described below.
Class description:
Implement the RolesUsersManage class.
Method signatures and docstrings:
- def get(self): 获取用户角色列表 --- tags: - user_role parameters: - in: query type: string name: user_name description: 用户名 - in: query name: role_name type: string descr... | Implement the Python class `RolesUsersManage` described below.
Class description:
Implement the RolesUsersManage class.
Method signatures and docstrings:
- def get(self): 获取用户角色列表 --- tags: - user_role parameters: - in: query type: string name: user_name description: 用户名 - in: query name: role_name type: string descr... | d25871dc66dfbd9f04e3d4d95843e39de286cfc8 | <|skeleton|>
class RolesUsersManage:
def get(self):
"""获取用户角色列表 --- tags: - user_role parameters: - in: query type: string name: user_name description: 用户名 - in: query name: role_name type: string description: 角色名 responses: 200: description: 获取用户角色信息 schema: properties: ok: type: boolean default: 200 desc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RolesUsersManage:
def get(self):
"""获取用户角色列表 --- tags: - user_role parameters: - in: query type: string name: user_name description: 用户名 - in: query name: role_name type: string description: 角色名 responses: 200: description: 获取用户角色信息 schema: properties: ok: type: boolean default: 200 description: 状态 co... | the_stack_v2_python_sparse | app/main/base/apis/roles_users.py | zcl-organization/naguan | train | 0 | |
c03030ead085a1096c6b2ab0e72eedd4f0398641 | [
"if root is None:\n return 0\nreturn self.__findNode(root, 1)",
"if node.left is None and node.right is None:\n return depth\nleftDepth = -1\nrightDepth = -1\nif node.left is not None:\n leftDepth = self.__findNode(node.left, depth + 1)\nif node.right is not None:\n rightDepth = self.__findNode(node.r... | <|body_start_0|>
if root is None:
return 0
return self.__findNode(root, 1)
<|end_body_0|>
<|body_start_1|>
if node.left is None and node.right is None:
return depth
leftDepth = -1
rightDepth = -1
if node.left is not None:
leftDepth = s... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def __findNode(self, node, depth):
""":type node: TreeNode :type depth: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
... | stack_v2_sparse_classes_75kplus_train_005962 | 1,352 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
},
{
"docstring": ":type node: TreeNode :type depth: int :rtype: int",
"name": "__findNode",
"signature": "def __findNode(self, node, depth)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def __findNode(self, node, depth): :type node: TreeNode :type depth: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def __findNode(self, node, depth): :type node: TreeNode :type depth: int :rtype: int
<|skeleton|>
class Solution:
... | c60b332866caa28e1ae5e216cbfc2c6f869a751a | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def __findNode(self, node, depth):
""":type node: TreeNode :type depth: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
if root is None:
return 0
return self.__findNode(root, 1)
def __findNode(self, node, depth):
""":type node: TreeNode :type depth: int :rtype: int"""
if node.left is None and node... | the_stack_v2_python_sparse | leetcode/easy/tree/test_maximum_depth_of_binary_tree.py | yenbohuang/online-contest-python | train | 0 | |
b9aeb83e1bb3d3b7427e1265a40e024ff4e13ac7 | [
"genbank.download([accession_number])\nself.parsed_genbank = genbank.parse([accession_number])[0]\nself.genes = []\nself._parse_genes()",
"for feature in self.parsed_genbank.features:\n if feature.type == 'CDS':\n locations = []\n if len(feature.sub_features):\n for sf in feature.sub_f... | <|body_start_0|>
genbank.download([accession_number])
self.parsed_genbank = genbank.parse([accession_number])[0]
self.genes = []
self._parse_genes()
<|end_body_0|>
<|body_start_1|>
for feature in self.parsed_genbank.features:
if feature.type == 'CDS':
... | Genome - representing a genomic DNA sequence with genes Genome.genes[i] returns the CDS sequences for each gene i. | Genome | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Genome:
"""Genome - representing a genomic DNA sequence with genes Genome.genes[i] returns the CDS sequences for each gene i."""
def __init__(self, accession_number):
"""Initialize by downloading from GenBank."""
<|body_0|>
def _parse_genes(self):
"""Parse out th... | stack_v2_sparse_classes_75kplus_train_005963 | 2,414 | no_license | [
{
"docstring": "Initialize by downloading from GenBank.",
"name": "__init__",
"signature": "def __init__(self, accession_number)"
},
{
"docstring": "Parse out the CDS sequence for each gene.",
"name": "_parse_genes",
"signature": "def _parse_genes(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001062 | Implement the Python class `Genome` described below.
Class description:
Genome - representing a genomic DNA sequence with genes Genome.genes[i] returns the CDS sequences for each gene i.
Method signatures and docstrings:
- def __init__(self, accession_number): Initialize by downloading from GenBank.
- def _parse_gene... | Implement the Python class `Genome` described below.
Class description:
Genome - representing a genomic DNA sequence with genes Genome.genes[i] returns the CDS sequences for each gene i.
Method signatures and docstrings:
- def __init__(self, accession_number): Initialize by downloading from GenBank.
- def _parse_gene... | ff77118fe81d82c835f71a41e70e3f7f303028bf | <|skeleton|>
class Genome:
"""Genome - representing a genomic DNA sequence with genes Genome.genes[i] returns the CDS sequences for each gene i."""
def __init__(self, accession_number):
"""Initialize by downloading from GenBank."""
<|body_0|>
def _parse_genes(self):
"""Parse out th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Genome:
"""Genome - representing a genomic DNA sequence with genes Genome.genes[i] returns the CDS sequences for each gene i."""
def __init__(self, accession_number):
"""Initialize by downloading from GenBank."""
genbank.download([accession_number])
self.parsed_genbank = genbank.p... | the_stack_v2_python_sparse | genomics/bio/genome.py | HussainAther/biology | train | 11 |
a31882dd8f130bfb3400c107e040f0083a607276 | [
"self.follow_dict = {}\nself.user_tweet = {}\nself.tweet_time = {}",
"if userId not in self.user_tweet:\n self.user_tweet[userId] = {tweetId}\nelse:\n self.user_tweet[userId].add(tweetId)\nn = len(self.tweet_time)\nself.tweet_time[tweetId] = n + 1",
"all_user = [userId]\nall_tweet = []\nif userId in self.... | <|body_start_0|>
self.follow_dict = {}
self.user_tweet = {}
self.tweet_time = {}
<|end_body_0|>
<|body_start_1|>
if userId not in self.user_tweet:
self.user_tweet[userId] = {tweetId}
else:
self.user_tweet[userId].add(tweetId)
n = len(self.tweet_ti... | Twitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
<|body_1|>
def getNewsFeed(self, userId):
"""Retrieve the 10 most recent tweet i... | stack_v2_sparse_classes_75kplus_train_005964 | 3,603 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compose a new tweet.",
"name": "postTweet",
"signature": "def postTweet(self, userId: int, tweetId: int) -> None"
},
{
"docstring": "Retrieve the 10 mos... | 5 | stack_v2_sparse_classes_30k_train_052367 | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet.
- def getNewsFeed(self, userId): Retrieve th... | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet.
- def getNewsFeed(self, userId): Retrieve th... | 971ecea441ce4624accb416136e09f1b797330ad | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
<|body_1|>
def getNewsFeed(self, userId):
"""Retrieve the 10 most recent tweet i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Twitter:
def __init__(self):
"""Initialize your data structure here."""
self.follow_dict = {}
self.user_tweet = {}
self.tweet_time = {}
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
if userId not in self.user_tweet:
... | the_stack_v2_python_sparse | leetcode/other/Twitter.py | huangqiank/Algorithm | train | 0 | |
b904de1bbda8fd5640b337ff04fb528cc3f2ec38 | [
"self.id = id\nself.value = value\nself.discount_type = discount_type\nself.status = status\nself.created_at = APIHelper.RFC3339DateTime(created_at) if created_at else None\nself.cycles = cycles\nself.deleted_at = APIHelper.RFC3339DateTime(deleted_at) if deleted_at else None\nself.description = description\nself.su... | <|body_start_0|>
self.id = id
self.value = value
self.discount_type = discount_type
self.status = status
self.created_at = APIHelper.RFC3339DateTime(created_at) if created_at else None
self.cycles = cycles
self.deleted_at = APIHelper.RFC3339DateTime(deleted_at) if... | Implementation of the 'Subscriptions Discounts Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. value (float): TODO: type description here. discount_type (string): TODO: type description here. status (string): TODO: type description here. created_at (datetime): T... | SubscriptionsDiscountsResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscriptionsDiscountsResponse:
"""Implementation of the 'Subscriptions Discounts Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. value (float): TODO: type description here. discount_type (string): TODO: type description here. status (stri... | stack_v2_sparse_classes_75kplus_train_005965 | 4,408 | permissive | [
{
"docstring": "Constructor for the SubscriptionsDiscountsResponse class",
"name": "__init__",
"signature": "def __init__(self, id=None, value=None, discount_type=None, status=None, created_at=None, cycles=None, deleted_at=None, description=None, subscription=None, subscription_item=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_040184 | Implement the Python class `SubscriptionsDiscountsResponse` described below.
Class description:
Implementation of the 'Subscriptions Discounts Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. value (float): TODO: type description here. discount_type (string): TO... | Implement the Python class `SubscriptionsDiscountsResponse` described below.
Class description:
Implementation of the 'Subscriptions Discounts Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. value (float): TODO: type description here. discount_type (string): TO... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class SubscriptionsDiscountsResponse:
"""Implementation of the 'Subscriptions Discounts Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. value (float): TODO: type description here. discount_type (string): TODO: type description here. status (stri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubscriptionsDiscountsResponse:
"""Implementation of the 'Subscriptions Discounts Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. value (float): TODO: type description here. discount_type (string): TODO: type description here. status (string): TODO: ty... | the_stack_v2_python_sparse | mundiapi/models/subscriptions_discounts_response.py | mundipagg/MundiAPI-PYTHON | train | 10 |
9b9d2e92cd91c45f67e6eb750aa266f7d56476ba | [
"n = len(arr)\nids = list(range(n))\nids.sort(key=lambda i: (arr[i], i))\nnextBigger = [-1] * n\nstack = []\nfor id in ids:\n while stack and stack[-1] < id:\n nextBigger[stack.pop()] = id\n stack.append(id)\nids.sort(key=lambda i: (-arr[i], i))\nnextSmaller = [-1] * n\nstack = []\nfor id in ids:\n ... | <|body_start_0|>
n = len(arr)
ids = list(range(n))
ids.sort(key=lambda i: (arr[i], i))
nextBigger = [-1] * n
stack = []
for id in ids:
while stack and stack[-1] < id:
nextBigger[stack.pop()] = id
stack.append(id)
ids.sort(ke... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def helper1(self, arr: List[int]) -> Tuple[List[int], List[int]]:
"""寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 如果有多个符合题意,取右侧第一个"""
<|body_0|>
def helper2(self, nums: List[int]) -> Tuple[List[int], List[int]]:
"""有序集合寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 相同大的,取index小的"""
... | stack_v2_sparse_classes_75kplus_train_005966 | 2,829 | no_license | [
{
"docstring": "寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 如果有多个符合题意,取右侧第一个",
"name": "helper1",
"signature": "def helper1(self, arr: List[int]) -> Tuple[List[int], List[int]]"
},
{
"docstring": "有序集合寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 相同大的,取index小的",
"name": "helper2",
"signature": "def helper2(self, nums... | 2 | stack_v2_sparse_classes_30k_train_049285 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper1(self, arr: List[int]) -> Tuple[List[int], List[int]]: 寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 如果有多个符合题意,取右侧第一个
- def helper2(self, nums: List[int]) -> Tuple[List[int], List[int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper1(self, arr: List[int]) -> Tuple[List[int], List[int]]: 寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 如果有多个符合题意,取右侧第一个
- def helper2(self, nums: List[int]) -> Tuple[List[int], List[int... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def helper1(self, arr: List[int]) -> Tuple[List[int], List[int]]:
"""寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 如果有多个符合题意,取右侧第一个"""
<|body_0|>
def helper2(self, nums: List[int]) -> Tuple[List[int], List[int]]:
"""有序集合寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 相同大的,取index小的"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def helper1(self, arr: List[int]) -> Tuple[List[int], List[int]]:
"""寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 如果有多个符合题意,取右侧第一个"""
n = len(arr)
ids = list(range(n))
ids.sort(key=lambda i: (arr[i], i))
nextBigger = [-1] * n
stack = []
for id in ids:
... | the_stack_v2_python_sparse | 1_stack/单调栈/对每个数,寻找右侧比自己大的数里最小的那个 copy.py | 981377660LMT/algorithm-study | train | 225 | |
4387853629c3b69b71269aeb1f7fdc141c0b5751 | [
"if not size:\n size = 1024\nif not hash_function:\n hash_function = 'complex'\nif type(size) not in (float, int):\n raise TypeError('Size of hash must be positive integer >= 512.')\nelif size < 512:\n raise ValueError('Size must be >= 512.')\nelse:\n self.table = [None] * size\nif hash_function == '... | <|body_start_0|>
if not size:
size = 1024
if not hash_function:
hash_function = 'complex'
if type(size) not in (float, int):
raise TypeError('Size of hash must be positive integer >= 512.')
elif size < 512:
raise ValueError('Size must be >=... | Define a hash table and it's methods. | HashTable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HashTable:
"""Define a hash table and it's methods."""
def __init__(self, size=None, hash_function=None):
"""Initialize a hash table."""
<|body_0|>
def _naive_hash(self, key):
"""Additive hash function."""
<|body_1|>
def _complex_hash(self, key):
... | stack_v2_sparse_classes_75kplus_train_005967 | 2,633 | permissive | [
{
"docstring": "Initialize a hash table.",
"name": "__init__",
"signature": "def __init__(self, size=None, hash_function=None)"
},
{
"docstring": "Additive hash function.",
"name": "_naive_hash",
"signature": "def _naive_hash(self, key)"
},
{
"docstring": "One-at-a-time hash func... | 6 | null | Implement the Python class `HashTable` described below.
Class description:
Define a hash table and it's methods.
Method signatures and docstrings:
- def __init__(self, size=None, hash_function=None): Initialize a hash table.
- def _naive_hash(self, key): Additive hash function.
- def _complex_hash(self, key): One-at-... | Implement the Python class `HashTable` described below.
Class description:
Define a hash table and it's methods.
Method signatures and docstrings:
- def __init__(self, size=None, hash_function=None): Initialize a hash table.
- def _naive_hash(self, key): Additive hash function.
- def _complex_hash(self, key): One-at-... | d579ed7b4aba3c5ead7e83bb681261c9c5e60c13 | <|skeleton|>
class HashTable:
"""Define a hash table and it's methods."""
def __init__(self, size=None, hash_function=None):
"""Initialize a hash table."""
<|body_0|>
def _naive_hash(self, key):
"""Additive hash function."""
<|body_1|>
def _complex_hash(self, key):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HashTable:
"""Define a hash table and it's methods."""
def __init__(self, size=None, hash_function=None):
"""Initialize a hash table."""
if not size:
size = 1024
if not hash_function:
hash_function = 'complex'
if type(size) not in (float, int):
... | the_stack_v2_python_sparse | DS/hash_table.py | ADL175/Data-Structures-and-Sorting | train | 1 |
b1b1bcbe87db7590dd2c458be6efb4c38a3a7667 | [
"super(INCEPTION_V3_FID, self).__init__()\nself.resize_input = resize_input\nself.output_blocks = sorted(output_blocks)\nself.last_needed_block = max(output_blocks)\nassert self.last_needed_block <= 3, 'Last possible output block index is 3'\nself.blocks = nn.ModuleList()\ninception = models.inception_v3()\nmodel_p... | <|body_start_0|>
super(INCEPTION_V3_FID, self).__init__()
self.resize_input = resize_input
self.output_blocks = sorted(output_blocks)
self.last_needed_block = max(output_blocks)
assert self.last_needed_block <= 3, 'Last possible output block index is 3'
self.blocks = nn.M... | Pretrained InceptionV3 network returning feature maps | INCEPTION_V3_FID | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class INCEPTION_V3_FID:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True):
"""Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of blocks to return features of. Possibl... | stack_v2_sparse_classes_75kplus_train_005968 | 49,823 | no_license | [
{
"docstring": "Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of blocks to return features of. Possible values are: - 0: corresponds to output of first max pooling - 1: corresponds to output of second max pooling - 2: corresponds to output which is fed to aux classifier ... | 2 | stack_v2_sparse_classes_30k_train_053670 | Implement the Python class `INCEPTION_V3_FID` described below.
Class description:
Pretrained InceptionV3 network returning feature maps
Method signatures and docstrings:
- def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True): Build pretrained InceptionV3 Parameters ---------- output_blocks : lis... | Implement the Python class `INCEPTION_V3_FID` described below.
Class description:
Pretrained InceptionV3 network returning feature maps
Method signatures and docstrings:
- def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True): Build pretrained InceptionV3 Parameters ---------- output_blocks : lis... | 2862124dca40daebb0aee79c5c36b17b3266a7f6 | <|skeleton|>
class INCEPTION_V3_FID:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True):
"""Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of blocks to return features of. Possibl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class INCEPTION_V3_FID:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True):
"""Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of blocks to return features of. Possible values are:... | the_stack_v2_python_sparse | image_generation/model.py | azadis/Obj-GAN | train | 2 |
7d040af16ce6617886ee53ed0a37b7a4d06baf9f | [
"super(RelPositionalEncoding, self).__init__()\nself.d_model = d_model\nself.xscale = math.sqrt(self.d_model)\nself.dropout = torch.nn.Dropout(p=dropout_rate)\nself.pe = None\nself.extend_pe(torch.tensor(0.0).expand(1, max_len))",
"self.max_len = x.size(1)\nself.pe = torch.zeros(self.max_len, self.d_model)\nposit... | <|body_start_0|>
super(RelPositionalEncoding, self).__init__()
self.d_model = d_model
self.xscale = math.sqrt(self.d_model)
self.dropout = torch.nn.Dropout(p=dropout_rate)
self.pe = None
self.extend_pe(torch.tensor(0.0).expand(1, max_len))
<|end_body_0|>
<|body_start_1|>... | Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. | RelPositionalEncoding | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int):... | stack_v2_sparse_classes_75kplus_train_005969 | 5,260 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model, dropout_rate, max_len=5000)"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, x)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_test_002627 | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rat... | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rat... | e2f834dd60e7939672c1795b4ac62e89ad0bca49 | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum inpu... | the_stack_v2_python_sparse | speech/conformer/pytorch/src/layers/embedding.py | graphcore/examples | train | 311 |
47a3047af5163b39d387bc307425cd0236ce6312 | [
"super(IBMCNN, self).__init__()\nself.params = params\nif params.train_embeddings:\n self.embedding = nn.Embedding(num_embeddings=params.num_embeddings, embedding_dim=params.embedding_dim)\nself.convs = nn.ModuleList([nn.Conv2d(in_channels=1, out_channels=params.num_filters, kernel_size=(fs, params.embedding_dim... | <|body_start_0|>
super(IBMCNN, self).__init__()
self.params = params
if params.train_embeddings:
self.embedding = nn.Embedding(num_embeddings=params.num_embeddings, embedding_dim=params.embedding_dim)
self.convs = nn.ModuleList([nn.Conv2d(in_channels=1, out_channels=params.nu... | CNN Model from IBM paper. | IBMCNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IBMCNN:
"""CNN Model from IBM paper."""
def __init__(self, params):
"""params: hyperparameters / settings of the model train_embeddings: train new embeddings? num_embeddings: number of embeddings (i.e. # of tokens) embedding dim: word embedding dimension (200) positional_embedding di... | stack_v2_sparse_classes_75kplus_train_005970 | 9,205 | no_license | [
{
"docstring": "params: hyperparameters / settings of the model train_embeddings: train new embeddings? num_embeddings: number of embeddings (i.e. # of tokens) embedding dim: word embedding dimension (200) positional_embedding dim (50) (optional) TODO: what is this? POS embedding dim (20) (optional) TODO: what ... | 2 | stack_v2_sparse_classes_30k_train_053355 | Implement the Python class `IBMCNN` described below.
Class description:
CNN Model from IBM paper.
Method signatures and docstrings:
- def __init__(self, params): params: hyperparameters / settings of the model train_embeddings: train new embeddings? num_embeddings: number of embeddings (i.e. # of tokens) embedding di... | Implement the Python class `IBMCNN` described below.
Class description:
CNN Model from IBM paper.
Method signatures and docstrings:
- def __init__(self, params): params: hyperparameters / settings of the model train_embeddings: train new embeddings? num_embeddings: number of embeddings (i.e. # of tokens) embedding di... | 5440470024a080e77f29374569f9d09f913280e7 | <|skeleton|>
class IBMCNN:
"""CNN Model from IBM paper."""
def __init__(self, params):
"""params: hyperparameters / settings of the model train_embeddings: train new embeddings? num_embeddings: number of embeddings (i.e. # of tokens) embedding dim: word embedding dimension (200) positional_embedding di... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IBMCNN:
"""CNN Model from IBM paper."""
def __init__(self, params):
"""params: hyperparameters / settings of the model train_embeddings: train new embeddings? num_embeddings: number of embeddings (i.e. # of tokens) embedding dim: word embedding dimension (200) positional_embedding dim (50) (optio... | the_stack_v2_python_sparse | train_model/cnn_model.py | jacobjinkelly/clinical-ad | train | 3 |
471a359c46eab69edca216ab38c298288531f99c | [
"name = 'FactorialDesign'\nsuper(FactorialDesign, self).__init__(name, xmin, xmax, use_logger)\nself.levels = levels\nif self.use_logger:\n self.logger = ml.SciopeLogger().get_logger()\n self.logger.info('Factorial design in {0} dimensions initialized'.format(len(self.xmin)))",
"if hasattr(self, 'random_idx... | <|body_start_0|>
name = 'FactorialDesign'
super(FactorialDesign, self).__init__(name, xmin, xmax, use_logger)
self.levels = levels
if self.use_logger:
self.logger = ml.SciopeLogger().get_logger()
self.logger.info('Factorial design in {0} dimensions initialized'.fo... | Class definition for Factorial design Properties/variables: * name (FactorialDesign) * levels (the number of levels in the factorial design) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated points) * outlier_column_indice... | FactorialDesign | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactorialDesign:
"""Class definition for Factorial design Properties/variables: * name (FactorialDesign) * levels (the number of levels in the factorial design) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassin... | stack_v2_sparse_classes_75kplus_train_005971 | 5,431 | permissive | [
{
"docstring": "Initialize a factorial design with specified parameters Parameters ---------- levels : integer The number of levels of the factorial design. Number of generated points will be levels^dimensionality xmin : vector or 1D array Specifies the lower bound of the hypercube within which the design is ge... | 3 | stack_v2_sparse_classes_30k_train_020196 | Implement the Python class `FactorialDesign` described below.
Class description:
Class definition for Factorial design Properties/variables: * name (FactorialDesign) * levels (the number of levels in the factorial design) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound... | Implement the Python class `FactorialDesign` described below.
Class description:
Class definition for Factorial design Properties/variables: * name (FactorialDesign) * levels (the number of levels in the factorial design) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound... | 5122107dedcee9c39458e83d853ec35f91268780 | <|skeleton|>
class FactorialDesign:
"""Class definition for Factorial design Properties/variables: * name (FactorialDesign) * levels (the number of levels in the factorial design) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FactorialDesign:
"""Class definition for Factorial design Properties/variables: * name (FactorialDesign) * levels (the number of levels in the factorial design) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated p... | the_stack_v2_python_sparse | sciope/designs/factorial_design.py | rmjiang7/sciope | train | 0 |
f7644841b6b3379a8769cc7fc2b286298441475f | [
"self.sleft = Block()\nself.sright = Block(left=self.sleft)\nself.sleft.right = self.sright\nself.keyblock = {}",
"preb = self.sleft\nif key in self.keyblock:\n preb = self.keyblock[key]\n preb.kids.remove(key)\nval = preb.val + 1\nif preb.right.val == val:\n curb = preb.right\nelse:\n curb = Block(va... | <|body_start_0|>
self.sleft = Block()
self.sright = Block(left=self.sleft)
self.sleft.right = self.sright
self.keyblock = {}
<|end_body_0|>
<|body_start_1|>
preb = self.sleft
if key in self.keyblock:
preb = self.keyblock[key]
preb.kids.remove(key)... | AllOne | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key: str) -> None:
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1."""
<|body_1|>
def dec(self, key: str) -> None:
"""Decr... | stack_v2_sparse_classes_75kplus_train_005972 | 2,418 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1.",
"name": "inc",
"signature": "def inc(self, key: str) -> None"
},
{
"docstrin... | 5 | stack_v2_sparse_classes_30k_val_001717 | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1.
- def dec(self, ... | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1.
- def dec(self, ... | 498308e6a065af444a1d5570341231e4c51dfa3f | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key: str) -> None:
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1."""
<|body_1|>
def dec(self, key: str) -> None:
"""Decr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AllOne:
def __init__(self):
"""Initialize your data structure here."""
self.sleft = Block()
self.sright = Block(left=self.sleft)
self.sleft.right = self.sright
self.keyblock = {}
def inc(self, key: str) -> None:
"""Inserts a new key <Key> with value 1. Or i... | the_stack_v2_python_sparse | lc432_ood.py | Mela2014/lc_punch | train | 0 | |
9b8eeb5c92964259eaa481abfbb71b7808653243 | [
"self.w = w\nfor i in range(1, len(self.w)):\n self.w[i] += self.w[i - 1]",
"index = randint(1, self.w[-1])\nstart = 0\nend = len(self.w) - 1\nif index < self.w[0]:\n return 0\nwhile start < end:\n mid = (start + end) // 2\n if index > self.w[mid]:\n start = mid + 1\n else:\n end = mi... | <|body_start_0|>
self.w = w
for i in range(1, len(self.w)):
self.w[i] += self.w[i - 1]
<|end_body_0|>
<|body_start_1|>
index = randint(1, self.w[-1])
start = 0
end = len(self.w) - 1
if index < self.w[0]:
return 0
while start < end:
... | 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.w = w
for i in range(1, len(self.w)):
self.w[i] += self.w[i - 1]
<|end_... | stack_v2_sparse_classes_75kplus_train_005973 | 650 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035135 | 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]"""
<|... | 16e8a7935811fa71ce71998da8549e29ba68f847 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.w = w
for i in range(1, len(self.w)):
self.w[i] += self.w[i - 1]
def pickIndex(self):
""":rtype: int"""
index = randint(1, self.w[-1])
start = 0
end = len(self.w) - 1
... | the_stack_v2_python_sparse | leetcode6/pickIndex.py | lizyang95/leetcode | train | 0 | |
f510a158315fe81dcd5bfad78ec13616ed82604c | [
"if not user_id or type(user_id) != str:\n return None\nsessionId = str(uuid4())\nself.user_id_by_session_id[sessionId] = user_id\nreturn sessionId",
"if not session_id or type(session_id) != str:\n return None\nsession = self.user_id_by_session_id.get(session_id)\nif not session:\n return None\nreturn s... | <|body_start_0|>
if not user_id or type(user_id) != str:
return None
sessionId = str(uuid4())
self.user_id_by_session_id[sessionId] = user_id
return sessionId
<|end_body_0|>
<|body_start_1|>
if not session_id or type(session_id) != str:
return None
... | SessionAuth class | SessionAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionAuth:
"""SessionAuth class"""
def create_session(self, user_id: str=None) -> str:
"""Creates a Session ID for a user"""
<|body_0|>
def user_id_for_session_id(self, session_id: str=None) -> str:
"""Returns a User ID based on a Session ID"""
<|body_1... | stack_v2_sparse_classes_75kplus_train_005974 | 1,538 | no_license | [
{
"docstring": "Creates a Session ID for a user",
"name": "create_session",
"signature": "def create_session(self, user_id: str=None) -> str"
},
{
"docstring": "Returns a User ID based on a Session ID",
"name": "user_id_for_session_id",
"signature": "def user_id_for_session_id(self, sess... | 4 | null | Implement the Python class `SessionAuth` described below.
Class description:
SessionAuth class
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: Creates a Session ID for a user
- def user_id_for_session_id(self, session_id: str=None) -> str: Returns a User ID based on a Session I... | Implement the Python class `SessionAuth` described below.
Class description:
SessionAuth class
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: Creates a Session ID for a user
- def user_id_for_session_id(self, session_id: str=None) -> str: Returns a User ID based on a Session I... | dfb69fff81fca7bccfc2cb9e3bbbdb222d318f92 | <|skeleton|>
class SessionAuth:
"""SessionAuth class"""
def create_session(self, user_id: str=None) -> str:
"""Creates a Session ID for a user"""
<|body_0|>
def user_id_for_session_id(self, session_id: str=None) -> str:
"""Returns a User ID based on a Session ID"""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SessionAuth:
"""SessionAuth class"""
def create_session(self, user_id: str=None) -> str:
"""Creates a Session ID for a user"""
if not user_id or type(user_id) != str:
return None
sessionId = str(uuid4())
self.user_id_by_session_id[sessionId] = user_id
r... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_auth.py | hunterxx0/holbertonschool-web_back_end | train | 0 |
0597a2d0a0628f71426bdb55db6f9bd717e65c30 | [
"if not (filename is None) ^ (maskobject is None):\n raise ValueError('You have to provide either a file name or a Mask object')\nelif not maskobject is None:\n if not isinstance(maskobject, Mask):\n raise ValueError('maskobject must be an instance of Mask')\n base_mask = maskobject.mask\n self._... | <|body_start_0|>
if not (filename is None) ^ (maskobject is None):
raise ValueError('You have to provide either a file name or a Mask object')
elif not maskobject is None:
if not isinstance(maskobject, Mask):
raise ValueError('maskobject must be an instance of Mas... | Defines a submask starting from a ComposedBasin object and a NetCDF file or a Mask object | ComposedSubMask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComposedSubMask:
"""Defines a submask starting from a ComposedBasin object and a NetCDF file or a Mask object"""
def __init__(self, basin, filename=None, maskobject=None, maskvarname='tmask', zlevelsvar='nav_lev', ylevelsmatvar='nav_lat', xlevelsmatvar='nav_lon', dzvarname='e3t'):
""... | stack_v2_sparse_classes_75kplus_train_005975 | 4,524 | no_license | [
{
"docstring": "ComposedSubMask constructor Args: - *basin*: a ComposedBasin object. - *filename*: the path to a NetCDF file. - *maskobject*: a Mask object. Caveats: - *filename* and *maskobject* are mutually exclusive.",
"name": "__init__",
"signature": "def __init__(self, basin, filename=None, maskobj... | 2 | stack_v2_sparse_classes_30k_train_051211 | Implement the Python class `ComposedSubMask` described below.
Class description:
Defines a submask starting from a ComposedBasin object and a NetCDF file or a Mask object
Method signatures and docstrings:
- def __init__(self, basin, filename=None, maskobject=None, maskvarname='tmask', zlevelsvar='nav_lev', ylevelsmat... | Implement the Python class `ComposedSubMask` described below.
Class description:
Defines a submask starting from a ComposedBasin object and a NetCDF file or a Mask object
Method signatures and docstrings:
- def __init__(self, basin, filename=None, maskobject=None, maskvarname='tmask', zlevelsvar='nav_lev', ylevelsmat... | 985f34c2214ea55cd4d324704847d5a0d2a9de1e | <|skeleton|>
class ComposedSubMask:
"""Defines a submask starting from a ComposedBasin object and a NetCDF file or a Mask object"""
def __init__(self, basin, filename=None, maskobject=None, maskvarname='tmask', zlevelsvar='nav_lev', ylevelsmatvar='nav_lat', xlevelsmatvar='nav_lon', dzvarname='e3t'):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComposedSubMask:
"""Defines a submask starting from a ComposedBasin object and a NetCDF file or a Mask object"""
def __init__(self, basin, filename=None, maskobject=None, maskvarname='tmask', zlevelsvar='nav_lev', ylevelsmatvar='nav_lat', xlevelsmatvar='nav_lon', dzvarname='e3t'):
"""ComposedSubM... | the_stack_v2_python_sparse | commons/composedsubmask.py | inogs/bit.sea | train | 4 |
875a72a2c22d7bc6fd2e7f349c39c292a84fe3e2 | [
"super().__init__()\nself.content_analyzer = content_analyzer\nself.recommendation_count = recommendation_count\nself.filtering_component = NearestNeighbors(n_neighbors=recommendation_count + 1, metric='cosine')",
"self._book_data = book_data\nresult = self.content_analyzer.build_features(self._book_data)\nself.f... | <|body_start_0|>
super().__init__()
self.content_analyzer = content_analyzer
self.recommendation_count = recommendation_count
self.filtering_component = NearestNeighbors(n_neighbors=recommendation_count + 1, metric='cosine')
<|end_body_0|>
<|body_start_1|>
self._book_data = book... | Recommendation model using text features. Later uses the cosine similarity in order to select the most similar books. Attributes: content_analyzer: Component used for feature extraction from the data. filtering_component: Component used for calculating most similar books based on the features calculated by the content_... | ContentBasedRecommendationModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContentBasedRecommendationModel:
"""Recommendation model using text features. Later uses the cosine similarity in order to select the most similar books. Attributes: content_analyzer: Component used for feature extraction from the data. filtering_component: Component used for calculating most sim... | stack_v2_sparse_classes_75kplus_train_005976 | 3,733 | permissive | [
{
"docstring": "Initializes an instance of the ContentBasedRecommendationModel class. Args: input_filepath: Filepath containing book data. recommendation_count: How many recommendations should be returned for a single book.",
"name": "__init__",
"signature": "def __init__(self, content_analyzer: IConten... | 3 | stack_v2_sparse_classes_30k_train_002621 | Implement the Python class `ContentBasedRecommendationModel` described below.
Class description:
Recommendation model using text features. Later uses the cosine similarity in order to select the most similar books. Attributes: content_analyzer: Component used for feature extraction from the data. filtering_component: ... | Implement the Python class `ContentBasedRecommendationModel` described below.
Class description:
Recommendation model using text features. Later uses the cosine similarity in order to select the most similar books. Attributes: content_analyzer: Component used for feature extraction from the data. filtering_component: ... | d346e7b52410dd211b42142b420abac92748b91d | <|skeleton|>
class ContentBasedRecommendationModel:
"""Recommendation model using text features. Later uses the cosine similarity in order to select the most similar books. Attributes: content_analyzer: Component used for feature extraction from the data. filtering_component: Component used for calculating most sim... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContentBasedRecommendationModel:
"""Recommendation model using text features. Later uses the cosine similarity in order to select the most similar books. Attributes: content_analyzer: Component used for feature extraction from the data. filtering_component: Component used for calculating most similar books ba... | the_stack_v2_python_sparse | booksuggest/models/cb_recommend_models.py | szymanskir/booksuggest | train | 1 |
1ff5cf19221fcaf3017c0cc3f48325da8afe2ce5 | [
"try:\n db.show_by_id(show_id, session=session)\nexcept NoResultFound:\n raise NotFoundError('show with ID %s not found' % show_id)\ntry:\n episode = db.episode_by_id(ep_id, session)\nexcept NoResultFound:\n raise NotFoundError('episode with ID %s not found' % ep_id)\nif not db.episode_in_show(show_id, ... | <|body_start_0|>
try:
db.show_by_id(show_id, session=session)
except NoResultFound:
raise NotFoundError('show with ID %s not found' % show_id)
try:
episode = db.episode_by_id(ep_id, session)
except NoResultFound:
raise NotFoundError('episod... | SeriesEpisodeAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeriesEpisodeAPI:
def get(self, show_id, ep_id, session):
"""Get episode by show ID and episode ID"""
<|body_0|>
def delete(self, show_id, ep_id, session):
"""Forgets episode by show ID and episode ID"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_005977 | 47,001 | permissive | [
{
"docstring": "Get episode by show ID and episode ID",
"name": "get",
"signature": "def get(self, show_id, ep_id, session)"
},
{
"docstring": "Forgets episode by show ID and episode ID",
"name": "delete",
"signature": "def delete(self, show_id, ep_id, session)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053544 | Implement the Python class `SeriesEpisodeAPI` described below.
Class description:
Implement the SeriesEpisodeAPI class.
Method signatures and docstrings:
- def get(self, show_id, ep_id, session): Get episode by show ID and episode ID
- def delete(self, show_id, ep_id, session): Forgets episode by show ID and episode ... | Implement the Python class `SeriesEpisodeAPI` described below.
Class description:
Implement the SeriesEpisodeAPI class.
Method signatures and docstrings:
- def get(self, show_id, ep_id, session): Get episode by show ID and episode ID
- def delete(self, show_id, ep_id, session): Forgets episode by show ID and episode ... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class SeriesEpisodeAPI:
def get(self, show_id, ep_id, session):
"""Get episode by show ID and episode ID"""
<|body_0|>
def delete(self, show_id, ep_id, session):
"""Forgets episode by show ID and episode ID"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SeriesEpisodeAPI:
def get(self, show_id, ep_id, session):
"""Get episode by show ID and episode ID"""
try:
db.show_by_id(show_id, session=session)
except NoResultFound:
raise NotFoundError('show with ID %s not found' % show_id)
try:
episode =... | the_stack_v2_python_sparse | flexget/components/series/api.py | BrutuZ/Flexget | train | 1 | |
d6145be0c820f5f8d139a7f819ad35a9e212e5a0 | [
"super().__init__(area, algorithm)\nself.originalArea = copy.deepcopy(area)\nself.originalAlgorithm = copy.copy(algorithm)\nself.runs = 0\nself.allTimeHigh = 0\nself.dataHelper = DataHelper()\nself.maxRuns = runs",
"while self.runs < self.maxRuns:\n super().on_render()\n if self.area.price > self.allTimeHig... | <|body_start_0|>
super().__init__(area, algorithm)
self.originalArea = copy.deepcopy(area)
self.originalAlgorithm = copy.copy(algorithm)
self.runs = 0
self.allTimeHigh = 0
self.dataHelper = DataHelper()
self.maxRuns = runs
<|end_body_0|>
<|body_start_1|>
... | Draws consecutive visualisations for consecuetively created areas | BulkVisualizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BulkVisualizer:
"""Draws consecutive visualisations for consecuetively created areas"""
def __init__(self, area, algorithm, runs):
"""Initiate all elements necessary to run an algorithm consecutively and create consecutive visualizations for them. Keyword arguments: area -- the area ... | stack_v2_sparse_classes_75kplus_train_005978 | 1,986 | no_license | [
{
"docstring": "Initiate all elements necessary to run an algorithm consecutively and create consecutive visualizations for them. Keyword arguments: area -- the area that should be visualised algorithm -- the algorithm by which the given area is filled runs -- the amount of times the algorithm should be run and... | 2 | stack_v2_sparse_classes_30k_train_048925 | Implement the Python class `BulkVisualizer` described below.
Class description:
Draws consecutive visualisations for consecuetively created areas
Method signatures and docstrings:
- def __init__(self, area, algorithm, runs): Initiate all elements necessary to run an algorithm consecutively and create consecutive visu... | Implement the Python class `BulkVisualizer` described below.
Class description:
Draws consecutive visualisations for consecuetively created areas
Method signatures and docstrings:
- def __init__(self, area, algorithm, runs): Initiate all elements necessary to run an algorithm consecutively and create consecutive visu... | 7e377e6e4e4f1e196181be58dee6468b9c81cda3 | <|skeleton|>
class BulkVisualizer:
"""Draws consecutive visualisations for consecuetively created areas"""
def __init__(self, area, algorithm, runs):
"""Initiate all elements necessary to run an algorithm consecutively and create consecutive visualizations for them. Keyword arguments: area -- the area ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BulkVisualizer:
"""Draws consecutive visualisations for consecuetively created areas"""
def __init__(self, area, algorithm, runs):
"""Initiate all elements necessary to run an algorithm consecutively and create consecutive visualizations for them. Keyword arguments: area -- the area that should b... | the_stack_v2_python_sparse | visualizers/bulkvisualizer.py | tommyh1234/minor.programmeren | train | 0 |
c70a497fa0a9db39e3f4546fd96775912458e71d | [
"i = 0\nwhile i < len(nums):\n if nums[i] == val:\n del nums[i]\n else:\n i += 1\nreturn len(nums)",
"tmp = list(filter(lambda x: x != val, nums))\nnums[:len(tmp)] = tmp\ndel nums[len(tmp):]\nreturn len(nums)"
] | <|body_start_0|>
i = 0
while i < len(nums):
if nums[i] == val:
del nums[i]
else:
i += 1
return len(nums)
<|end_body_0|>
<|body_start_1|>
tmp = list(filter(lambda x: x != val, nums))
nums[:len(tmp)] = tmp
del nums[le... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElement(self, nums, val):
"""direct solution"""
<|body_0|>
def removeElement2(self, nums, val):
"""use filter"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i = 0
while i < len(nums):
if nums[i] == val:
... | stack_v2_sparse_classes_75kplus_train_005979 | 1,988 | permissive | [
{
"docstring": "direct solution",
"name": "removeElement",
"signature": "def removeElement(self, nums, val)"
},
{
"docstring": "use filter",
"name": "removeElement2",
"signature": "def removeElement2(self, nums, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035874 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums, val): direct solution
- def removeElement2(self, nums, val): use filter | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums, val): direct solution
- def removeElement2(self, nums, val): use filter
<|skeleton|>
class Solution:
def removeElement(self, nums, val):
... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def removeElement(self, nums, val):
"""direct solution"""
<|body_0|>
def removeElement2(self, nums, val):
"""use filter"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def removeElement(self, nums, val):
"""direct solution"""
i = 0
while i < len(nums):
if nums[i] == val:
del nums[i]
else:
i += 1
return len(nums)
def removeElement2(self, nums, val):
"""use filter"""... | the_stack_v2_python_sparse | leetcode/0027_remove_element.py | chaosWsF/Python-Practice | train | 1 | |
606233ec6306fdf0dcb4eaaaf85464e5fab004c6 | [
"request_data = request.json\ntag_name = request_data.pop('tag_name')\ncntr = dr.RTContainer()\ntry:\n if 'tag_type' in request_data.keys():\n if len(request_data['tag_type']) <= 0:\n request_data['tag_type'] = 'generic'\n success, result = cntr.create_tag_point(tag_name, request_data['t... | <|body_start_0|>
request_data = request.json
tag_name = request_data.pop('tag_name')
cntr = dr.RTContainer()
try:
if 'tag_type' in request_data.keys():
if len(request_data['tag_type']) <= 0:
request_data['tag_type'] = 'generic'
... | Tag | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tag:
def post(self):
"""Creates a new TagPoint"""
<|body_0|>
def delete(self):
"""Deletes a TagPoint For security reasons the tag_type should match, otherwise the TagPoint cannot be deleted"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
request_dat... | stack_v2_sparse_classes_75kplus_train_005980 | 6,812 | permissive | [
{
"docstring": "Creates a new TagPoint",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Deletes a TagPoint For security reasons the tag_type should match, otherwise the TagPoint cannot be deleted",
"name": "delete",
"signature": "def delete(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012459 | Implement the Python class `Tag` described below.
Class description:
Implement the Tag class.
Method signatures and docstrings:
- def post(self): Creates a new TagPoint
- def delete(self): Deletes a TagPoint For security reasons the tag_type should match, otherwise the TagPoint cannot be deleted | Implement the Python class `Tag` described below.
Class description:
Implement the Tag class.
Method signatures and docstrings:
- def post(self): Creates a new TagPoint
- def delete(self): Deletes a TagPoint For security reasons the tag_type should match, otherwise the TagPoint cannot be deleted
<|skeleton|>
class T... | 86613ac955d70614bbb658dc6c474705b8ed5b65 | <|skeleton|>
class Tag:
def post(self):
"""Creates a new TagPoint"""
<|body_0|>
def delete(self):
"""Deletes a TagPoint For security reasons the tag_type should match, otherwise the TagPoint cannot be deleted"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tag:
def post(self):
"""Creates a new TagPoint"""
request_data = request.json
tag_name = request_data.pop('tag_name')
cntr = dr.RTContainer()
try:
if 'tag_type' in request_data.keys():
if len(request_data['tag_type']) <= 0:
... | the_stack_v2_python_sparse | api/historian/endpoints/api_admin_services.py | Borreguin/F.R.E.D.A-Zero | train | 0 | |
e51fe33231fa32c8eb804eedd0e2ddebe14c80ca | [
"self._maxsize = maxsize\nself._queue = collections.deque()\nself._closed = False\nself._mutex = threading.Lock()\nself._not_empty = threading.Condition(self._mutex)\nself._not_full = threading.Condition(self._mutex)",
"with self._not_empty:\n while not self._queue:\n self._not_empty.wait()\n item = ... | <|body_start_0|>
self._maxsize = maxsize
self._queue = collections.deque()
self._closed = False
self._mutex = threading.Lock()
self._not_empty = threading.Condition(self._mutex)
self._not_full = threading.Condition(self._mutex)
<|end_body_0|>
<|body_start_1|>
wit... | Stripped-down fork of the standard library Queue that is closeable. | CloseableQueue | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloseableQueue:
"""Stripped-down fork of the standard library Queue that is closeable."""
def __init__(self, maxsize=0):
"""Create a queue object with a given maximum size. Args: maxsize: int size of queue. If <= 0, the queue size is infinite."""
<|body_0|>
def get(self)... | stack_v2_sparse_classes_75kplus_train_005981 | 10,399 | permissive | [
{
"docstring": "Create a queue object with a given maximum size. Args: maxsize: int size of queue. If <= 0, the queue size is infinite.",
"name": "__init__",
"signature": "def __init__(self, maxsize=0)"
},
{
"docstring": "Remove and return an item from the queue. If the queue is empty, blocks un... | 4 | stack_v2_sparse_classes_30k_train_044256 | Implement the Python class `CloseableQueue` described below.
Class description:
Stripped-down fork of the standard library Queue that is closeable.
Method signatures and docstrings:
- def __init__(self, maxsize=0): Create a queue object with a given maximum size. Args: maxsize: int size of queue. If <= 0, the queue s... | Implement the Python class `CloseableQueue` described below.
Class description:
Stripped-down fork of the standard library Queue that is closeable.
Method signatures and docstrings:
- def __init__(self, maxsize=0): Create a queue object with a given maximum size. Args: maxsize: int size of queue. If <= 0, the queue s... | a7f3934a67900720af3d3b15389551483bee50b8 | <|skeleton|>
class CloseableQueue:
"""Stripped-down fork of the standard library Queue that is closeable."""
def __init__(self, maxsize=0):
"""Create a queue object with a given maximum size. Args: maxsize: int size of queue. If <= 0, the queue size is infinite."""
<|body_0|>
def get(self)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CloseableQueue:
"""Stripped-down fork of the standard library Queue that is closeable."""
def __init__(self, maxsize=0):
"""Create a queue object with a given maximum size. Args: maxsize: int size of queue. If <= 0, the queue size is infinite."""
self._maxsize = maxsize
self._queu... | the_stack_v2_python_sparse | tensorflow/python/summary/writer/event_file_writer.py | tensorflow/tensorflow | train | 208,740 |
3ebfe4033fbcb39319fc94840f1278009029e981 | [
"for token, data in USER_INFO.items():\n with self.subTest(token=token), mocked(self.mock_url):\n resp = self.try_token(token)\n self.assertEqual(self.status_head(resp), 2)\n self.assertIn('token', resp.data)\n self.assertNotEqual(resp.data['token'], token)\n self.assertEqual(U... | <|body_start_0|>
for token, data in USER_INFO.items():
with self.subTest(token=token), mocked(self.mock_url):
resp = self.try_token(token)
self.assertEqual(self.status_head(resp), 2)
self.assertIn('token', resp.data)
self.assertNotEqual... | Social auth tests. Note that this isn't actually a descendent of APITestCase, which it would need to be to run directly. Instead, we have to create subclasses which mix in this, TestFacebook, TestGoogle, etc., with APITestCase, so that setup gets run appropriately. | SocialAuthTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SocialAuthTests:
"""Social auth tests. Note that this isn't actually a descendent of APITestCase, which it would need to be to run directly. Instead, we have to create subclasses which mix in this, TestFacebook, TestGoogle, etc., with APITestCase, so that setup gets run appropriately."""
def... | stack_v2_sparse_classes_75kplus_train_005982 | 7,467 | no_license | [
{
"docstring": "Ensure that we can correctly create a new user for someone with a valid token.",
"name": "test_new_user_creation",
"signature": "def test_new_user_creation(self)"
},
{
"docstring": "Ensure that users with existing accounts and a valid social token can log in.",
"name": "test_... | 3 | null | Implement the Python class `SocialAuthTests` described below.
Class description:
Social auth tests. Note that this isn't actually a descendent of APITestCase, which it would need to be to run directly. Instead, we have to create subclasses which mix in this, TestFacebook, TestGoogle, etc., with APITestCase, so that se... | Implement the Python class `SocialAuthTests` described below.
Class description:
Social auth tests. Note that this isn't actually a descendent of APITestCase, which it would need to be to run directly. Instead, we have to create subclasses which mix in this, TestFacebook, TestGoogle, etc., with APITestCase, so that se... | b81099a84eedbe3a4f93bd13ff0cd12e5c1fe7ba | <|skeleton|>
class SocialAuthTests:
"""Social auth tests. Note that this isn't actually a descendent of APITestCase, which it would need to be to run directly. Instead, we have to create subclasses which mix in this, TestFacebook, TestGoogle, etc., with APITestCase, so that setup gets run appropriately."""
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SocialAuthTests:
"""Social auth tests. Note that this isn't actually a descendent of APITestCase, which it would need to be to run directly. Instead, we have to create subclasses which mix in this, TestFacebook, TestGoogle, etc., with APITestCase, so that setup gets run appropriately."""
def test_new_use... | the_stack_v2_python_sparse | klevr/test_social.py | tejas-trivedi/Klevr-Backend | train | 0 |
cf911bc53770a904ab10bce7a394875349319bd6 | [
"if not headA or not headB:\n return None\np1 = headA\np2 = headB\nl1 = self.getLen(p1)\nl2 = self.getLen(p2)\nif l1 > l2:\n for i in range(l1 - l2):\n p1 = p1.next\nelse:\n for i in range(l2 - l1):\n p2 = p2.next\nwhile p1 and p2 and (p1.val != p2.val):\n p1 = p1.next\n p2 = p2.next\nr... | <|body_start_0|>
if not headA or not headB:
return None
p1 = headA
p2 = headB
l1 = self.getLen(p1)
l2 = self.getLen(p2)
if l1 > l2:
for i in range(l1 - l2):
p1 = p1.next
else:
for i in range(l2 - l1):
... | Solution2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution2:
def findFirstCommonNode(self, headA, headB):
""":type headA, headB: ListNode :rtype: ListNode"""
<|body_0|>
def getLen(self, head):
"""给定头节点返回链表长度"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not headA or not headB:
retu... | stack_v2_sparse_classes_75kplus_train_005983 | 2,021 | no_license | [
{
"docstring": ":type headA, headB: ListNode :rtype: ListNode",
"name": "findFirstCommonNode",
"signature": "def findFirstCommonNode(self, headA, headB)"
},
{
"docstring": "给定头节点返回链表长度",
"name": "getLen",
"signature": "def getLen(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024751 | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def findFirstCommonNode(self, headA, headB): :type headA, headB: ListNode :rtype: ListNode
- def getLen(self, head): 给定头节点返回链表长度 | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def findFirstCommonNode(self, headA, headB): :type headA, headB: ListNode :rtype: ListNode
- def getLen(self, head): 给定头节点返回链表长度
<|skeleton|>
class Solution2:
def findFir... | 1db60502acb208f22d2149a4824e1219d8938225 | <|skeleton|>
class Solution2:
def findFirstCommonNode(self, headA, headB):
""":type headA, headB: ListNode :rtype: ListNode"""
<|body_0|>
def getLen(self, head):
"""给定头节点返回链表长度"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution2:
def findFirstCommonNode(self, headA, headB):
""":type headA, headB: ListNode :rtype: ListNode"""
if not headA or not headB:
return None
p1 = headA
p2 = headB
l1 = self.getLen(p1)
l2 = self.getLen(p2)
if l1 > l2:
for i i... | the_stack_v2_python_sparse | code_with_name/test51_prob52_两个链表的第一个公共节点.py | Binjer/jianzhi_offer | train | 2 | |
8a9a4f6d5a4893354f1446c8dd8857bcbc6e4b41 | [
"super(CheckStatusOS, self).__init__()\nself.system_type = sys_type_os\nos_info = status_info['os']\nself.info_cpu = os_info['cpu']\nself.chk_cpu = self.info_cpu['use_rate']\nself.info_memory = os_info['memory']\nself.chk_memory = self.info_memory['used']\nself.info_disk = os_info['disk']\nself.chk_disk = self._get... | <|body_start_0|>
super(CheckStatusOS, self).__init__()
self.system_type = sys_type_os
os_info = status_info['os']
self.info_cpu = os_info['cpu']
self.chk_cpu = self.info_cpu['use_rate']
self.info_memory = os_info['memory']
self.chk_memory = self.info_memory['used'... | Status of OS is checked. | CheckStatusOS | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckStatusOS:
"""Status of OS is checked."""
def __init__(self, status_info, conf_thr):
"""Constructor Argument: status_info : acquired status information(one element in information) (dict) conf_thr : threshold definition (ConfThreshold class)"""
<|body_0|>
def _get_mnt... | stack_v2_sparse_classes_75kplus_train_005984 | 16,247 | permissive | [
{
"docstring": "Constructor Argument: status_info : acquired status information(one element in information) (dict) conf_thr : threshold definition (ConfThreshold class)",
"name": "__init__",
"signature": "def __init__(self, status_info, conf_thr)"
},
{
"docstring": "Disk information is converted... | 2 | null | Implement the Python class `CheckStatusOS` described below.
Class description:
Status of OS is checked.
Method signatures and docstrings:
- def __init__(self, status_info, conf_thr): Constructor Argument: status_info : acquired status information(one element in information) (dict) conf_thr : threshold definition (Con... | Implement the Python class `CheckStatusOS` described below.
Class description:
Status of OS is checked.
Method signatures and docstrings:
- def __init__(self, status_info, conf_thr): Constructor Argument: status_info : acquired status information(one element in information) (dict) conf_thr : threshold definition (Con... | e550d1b5ec9419f1fb3eb6e058ce46b57c92ee2f | <|skeleton|>
class CheckStatusOS:
"""Status of OS is checked."""
def __init__(self, status_info, conf_thr):
"""Constructor Argument: status_info : acquired status information(one element in information) (dict) conf_thr : threshold definition (ConfThreshold class)"""
<|body_0|>
def _get_mnt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckStatusOS:
"""Status of OS is checked."""
def __init__(self, status_info, conf_thr):
"""Constructor Argument: status_info : acquired status information(one element in information) (dict) conf_thr : threshold definition (ConfThreshold class)"""
super(CheckStatusOS, self).__init__()
... | the_stack_v2_python_sparse | lib/ControllerStatusGet/EmControllerStatusGetExecutor.py | lixiaochun/element-manager | train | 0 |
9b8a252a62a26d82ce6ed147176adb9d3b70e0a6 | [
"max_of_min_val = min((2 * x if x % 2 else x for x in nums))\nfor i in range(len(nums)):\n while not nums[i] % 2:\n nums[i] = nums[i] // 2\nnums.sort()\nmin_max_diff = nums[-1] - nums[0]\nwhile True:\n n = nums.pop(0)\n if n == max_of_min_val:\n return min_max_diff\n bisect.insort(nums, 2 ... | <|body_start_0|>
max_of_min_val = min((2 * x if x % 2 else x for x in nums))
for i in range(len(nums)):
while not nums[i] % 2:
nums[i] = nums[i] // 2
nums.sort()
min_max_diff = nums[-1] - nums[0]
while True:
n = nums.pop(0)
if n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumDeviationStartingFromMin(self, nums: List[int]) -> int:
"""Following hint 1, the array is modified to start from the smallest values possible Runtime complexity: O(nlog n) + O(n log C log n) = O(nlog n log C), where n=len(nums) and C is the largest value of C (note t... | stack_v2_sparse_classes_75kplus_train_005985 | 4,604 | no_license | [
{
"docstring": "Following hint 1, the array is modified to start from the smallest values possible Runtime complexity: O(nlog n) + O(n log C log n) = O(nlog n log C), where n=len(nums) and C is the largest value of C (note that integers are not bounded in Python) Space complexity: O(n)",
"name": "minimumDev... | 2 | stack_v2_sparse_classes_30k_train_036829 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumDeviationStartingFromMin(self, nums: List[int]) -> int: Following hint 1, the array is modified to start from the smallest values possible Runtime complexity: O(nlog n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumDeviationStartingFromMin(self, nums: List[int]) -> int: Following hint 1, the array is modified to start from the smallest values possible Runtime complexity: O(nlog n... | ee8237b66975fb5584a3d68b311e762c0462c8aa | <|skeleton|>
class Solution:
def minimumDeviationStartingFromMin(self, nums: List[int]) -> int:
"""Following hint 1, the array is modified to start from the smallest values possible Runtime complexity: O(nlog n) + O(n log C log n) = O(nlog n log C), where n=len(nums) and C is the largest value of C (note t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minimumDeviationStartingFromMin(self, nums: List[int]) -> int:
"""Following hint 1, the array is modified to start from the smallest values possible Runtime complexity: O(nlog n) + O(n log C log n) = O(nlog n log C), where n=len(nums) and C is the largest value of C (note that integers a... | the_stack_v2_python_sparse | LC1675-Minimize-Deviation-in-Array.py | kate-melnykova/LeetCode-solutions | train | 2 | |
12254d006245e24817d2ad965fe1b577c2cc1286 | [
"import time\nimport thread\nthread.start_new_thread(self.run, ())",
"import viewer_basics\ntry:\n self.app = viewer_basics.SecondThreadApp(0)\n self.app.MainLoop()\nexcept TypeError:\n self.app = None",
"import viewer_basics\nif self.app:\n evt = viewer_basics.AddCone()\n viewer_basics.wxPostEve... | <|body_start_0|>
import time
import thread
thread.start_new_thread(self.run, ())
<|end_body_0|>
<|body_start_1|>
import viewer_basics
try:
self.app = viewer_basics.SecondThreadApp(0)
self.app.MainLoop()
except TypeError:
self.app = Non... | viewer_thread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class viewer_thread:
def start(self):
"""start the GUI thread"""
<|body_0|>
def run(self):
"""Note that viewer_basices is first imported ***here***. This is the second thread. viewer_basics imports wxPython. if we imported it at the module level instead of in this function... | stack_v2_sparse_classes_75kplus_train_005986 | 3,430 | no_license | [
{
"docstring": "start the GUI thread",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "Note that viewer_basices is first imported ***here***. This is the second thread. viewer_basics imports wxPython. if we imported it at the module level instead of in this function, the impor... | 3 | stack_v2_sparse_classes_30k_train_023180 | Implement the Python class `viewer_thread` described below.
Class description:
Implement the viewer_thread class.
Method signatures and docstrings:
- def start(self): start the GUI thread
- def run(self): Note that viewer_basices is first imported ***here***. This is the second thread. viewer_basics imports wxPython.... | Implement the Python class `viewer_thread` described below.
Class description:
Implement the viewer_thread class.
Method signatures and docstrings:
- def start(self): start the GUI thread
- def run(self): Note that viewer_basices is first imported ***here***. This is the second thread. viewer_basics imports wxPython.... | 13cceab2a1891ab443e62078be729dc1e1e2e283 | <|skeleton|>
class viewer_thread:
def start(self):
"""start the GUI thread"""
<|body_0|>
def run(self):
"""Note that viewer_basices is first imported ***here***. This is the second thread. viewer_basics imports wxPython. if we imported it at the module level instead of in this function... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class viewer_thread:
def start(self):
"""start the GUI thread"""
import time
import thread
thread.start_new_thread(self.run, ())
def run(self):
"""Note that viewer_basices is first imported ***here***. This is the second thread. viewer_basics imports wxPython. if we impo... | the_stack_v2_python_sparse | wxPython/demo/viewer.py | nvaccess/wxPython | train | 1 | |
8880c9cf1240a1481e2413155dd65a66495e1ef4 | [
"self.conv1 = nn.Conv2d(4, 32, 8, 4)\nself.conv2 = nn.Conv2d(32, 64, 4, 2)\nself.conv3 = nn.Conv2d(64, 64, 3, 1)\nshape = self.observation_space.shape[1:]\nfor c in [self.conv1, self.conv2, self.conv3]:\n shape = conv_out_shape(shape, c)\nself.nunits = 64 * np.prod(shape)\nself.fc = nn.Linear(self.nunits, 512)\n... | <|body_start_0|>
self.conv1 = nn.Conv2d(4, 32, 8, 4)
self.conv2 = nn.Conv2d(32, 64, 4, 2)
self.conv3 = nn.Conv2d(64, 64, 3, 1)
shape = self.observation_space.shape[1:]
for c in [self.conv1, self.conv2, self.conv3]:
shape = conv_out_shape(shape, c)
self.nunits ... | Deep network from https://www.nature.com/articles/nature14236. | NatureDQNVF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NatureDQNVF:
"""Deep network from https://www.nature.com/articles/nature14236."""
def build(self):
"""Build network."""
<|body_0|>
def forward(self, x):
"""Forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.conv1 = nn.Conv2d(4, 32, 8,... | stack_v2_sparse_classes_75kplus_train_005987 | 21,636 | no_license | [
{
"docstring": "Build network.",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "Forward.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044143 | Implement the Python class `NatureDQNVF` described below.
Class description:
Deep network from https://www.nature.com/articles/nature14236.
Method signatures and docstrings:
- def build(self): Build network.
- def forward(self, x): Forward. | Implement the Python class `NatureDQNVF` described below.
Class description:
Deep network from https://www.nature.com/articles/nature14236.
Method signatures and docstrings:
- def build(self): Build network.
- def forward(self, x): Forward.
<|skeleton|>
class NatureDQNVF:
"""Deep network from https://www.nature.... | e71c4b12955b01bfb907aa31c91ded6bcd8aaec8 | <|skeleton|>
class NatureDQNVF:
"""Deep network from https://www.nature.com/articles/nature14236."""
def build(self):
"""Build network."""
<|body_0|>
def forward(self, x):
"""Forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NatureDQNVF:
"""Deep network from https://www.nature.com/articles/nature14236."""
def build(self):
"""Build network."""
self.conv1 = nn.Conv2d(4, 32, 8, 4)
self.conv2 = nn.Conv2d(32, 64, 4, 2)
self.conv3 = nn.Conv2d(64, 64, 3, 1)
shape = self.observation_space.shap... | the_stack_v2_python_sparse | dl/rl/algorithms/ppo2_ngu.py | cbschaff/dl | 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_75kplus_train_005988 | 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_test_002876 | 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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | 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 |
2e2f74f3e66dccbf36da63f0881231899e9a88de | [
"def display_base(self, axisId):\n pass\n\ndef project_data(self, dataPoints):\n pass",
"import matplotlib.pyplot as plt\ndata = np.array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]).T\nprint(data.shape)\nprint(data)\nmy_projMod = ProjectionModelPCA(data)\ndata_projected = my_projMod.project_data(data)\nprint('proje... | <|body_start_0|>
def display_base(self, axisId):
pass
def project_data(self, dataPoints):
pass
<|end_body_0|>
<|body_start_1|>
import matplotlib.pyplot as plt
data = np.array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]).T
print(data.shape)
print(data)
... | Docstring for ProjectionModelLDA. :version: :author: sik | ProjectionModelLDA | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectionModelLDA:
"""Docstring for ProjectionModelLDA. :version: :author: sik"""
def __init__(self):
"""TODO: to be defined1. @return string : @author sik"""
<|body_0|>
def main(self):
"""Tests @return string : @author sik"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_005989 | 991 | permissive | [
{
"docstring": "TODO: to be defined1. @return string : @author sik",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Tests @return string : @author sik",
"name": "main",
"signature": "def main(self)"
}
] | 2 | null | Implement the Python class `ProjectionModelLDA` described below.
Class description:
Docstring for ProjectionModelLDA. :version: :author: sik
Method signatures and docstrings:
- def __init__(self): TODO: to be defined1. @return string : @author sik
- def main(self): Tests @return string : @author sik | Implement the Python class `ProjectionModelLDA` described below.
Class description:
Docstring for ProjectionModelLDA. :version: :author: sik
Method signatures and docstrings:
- def __init__(self): TODO: to be defined1. @return string : @author sik
- def main(self): Tests @return string : @author sik
<|skeleton|>
cla... | 335ba35c1843589904b9b238d4592d929b0005af | <|skeleton|>
class ProjectionModelLDA:
"""Docstring for ProjectionModelLDA. :version: :author: sik"""
def __init__(self):
"""TODO: to be defined1. @return string : @author sik"""
<|body_0|>
def main(self):
"""Tests @return string : @author sik"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectionModelLDA:
"""Docstring for ProjectionModelLDA. :version: :author: sik"""
def __init__(self):
"""TODO: to be defined1. @return string : @author sik"""
def display_base(self, axisId):
pass
def project_data(self, dataPoints):
pass
def main(self... | the_stack_v2_python_sparse | src/sampling_strategy/projection_model_lda.py | I2Cvb/hyper_learn | train | 0 |
5fd0a5d0a424910e19bae9beecf0714fd241e6f0 | [
"if len(s) < k:\n return 0\nc = min(set(s), key=s.count)\nif s.count(c) >= k:\n return len(s)\nreturn max((self.longestSubstring(t, k) for t in s.split(c)))",
"for c in set(s):\n if s.count(c) < k:\n return max((self.longestSubstring(t, k) for t in s.split(c)))\nreturn len(s)",
"if len(s) < k:\n... | <|body_start_0|>
if len(s) < k:
return 0
c = min(set(s), key=s.count)
if s.count(c) >= k:
return len(s)
return max((self.longestSubstring(t, k) for t in s.split(c)))
<|end_body_0|>
<|body_start_1|>
for c in set(s):
if s.count(c) < k:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/87768/4-lines-Python If every character appears at least k times, the whole string is ok. Otherwise split by a... | stack_v2_sparse_classes_75kplus_train_005990 | 3,250 | no_license | [
{
"docstring": ":type s: str :type k: int :rtype: int https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/87768/4-lines-Python If every character appears at least k times, the whole string is ok. Otherwise split by a least frequent character (because it will always be to... | 4 | stack_v2_sparse_classes_30k_train_041845 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/87768/4-lines... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/87768/4-lines... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/87768/4-lines-Python If every character appears at least k times, the whole string is ok. Otherwise split by a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/87768/4-lines-Python If every character appears at least k times, the whole string is ok. Otherwise split by a least frequen... | the_stack_v2_python_sparse | LeetCode/395_longest_substring_with_at_least_k_repeating_characters.py | yao23/Machine_Learning_Playground | train | 12 | |
f3e8aa576d9170280eae5af567f15f8000251926 | [
"self.backup_type = backup_type\nself.copy_partially_successful_run = copy_partially_successful_run\nself.extended_retention_policy_vec = extended_retention_policy_vec\nself.granularity_bucket = granularity_bucket\nself.id = id\nself.num_days_to_keep = num_days_to_keep\nself.retention_policy = retention_policy\nsel... | <|body_start_0|>
self.backup_type = backup_type
self.copy_partially_successful_run = copy_partially_successful_run
self.extended_retention_policy_vec = extended_retention_policy_vec
self.granularity_bucket = granularity_bucket
self.id = id
self.num_days_to_keep = num_days... | Implementation of the 'SnapshotTargetPolicyProto' model. Message that specifies the policy for copying backup snapshots to a target. This message also specifies the retention policy that should be applied to the snapshots after they have been copied to the specified target. Attributes: backup_type (int): The backup typ... | SnapshotTargetPolicyProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnapshotTargetPolicyProto:
"""Implementation of the 'SnapshotTargetPolicyProto' model. Message that specifies the policy for copying backup snapshots to a target. This message also specifies the retention policy that should be applied to the snapshots after they have been copied to the specified ... | stack_v2_sparse_classes_75kplus_train_005991 | 6,226 | permissive | [
{
"docstring": "Constructor for the SnapshotTargetPolicyProto class",
"name": "__init__",
"signature": "def __init__(self, backup_type=None, copy_partially_successful_run=None, extended_retention_policy_vec=None, granularity_bucket=None, id=None, num_days_to_keep=None, retention_policy=None, snapshot_ta... | 2 | stack_v2_sparse_classes_30k_train_020412 | Implement the Python class `SnapshotTargetPolicyProto` described below.
Class description:
Implementation of the 'SnapshotTargetPolicyProto' model. Message that specifies the policy for copying backup snapshots to a target. This message also specifies the retention policy that should be applied to the snapshots after ... | Implement the Python class `SnapshotTargetPolicyProto` described below.
Class description:
Implementation of the 'SnapshotTargetPolicyProto' model. Message that specifies the policy for copying backup snapshots to a target. This message also specifies the retention policy that should be applied to the snapshots after ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SnapshotTargetPolicyProto:
"""Implementation of the 'SnapshotTargetPolicyProto' model. Message that specifies the policy for copying backup snapshots to a target. This message also specifies the retention policy that should be applied to the snapshots after they have been copied to the specified ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnapshotTargetPolicyProto:
"""Implementation of the 'SnapshotTargetPolicyProto' model. Message that specifies the policy for copying backup snapshots to a target. This message also specifies the retention policy that should be applied to the snapshots after they have been copied to the specified target. Attri... | the_stack_v2_python_sparse | cohesity_management_sdk/models/snapshot_target_policy_proto.py | cohesity/management-sdk-python | train | 24 |
b0adbf9635704ca7c1ac0db0ad5be2b374809b06 | [
"check = await DBCoolDownEvent.check_global_group_cool_down_event(group_id=group_id)\nif check.success() and check.result == 1:\n return check\nelif check.success() and check.result in [0, 2]:\n result = await DBCoolDownEvent.add_global_group_cool_down_event(group_id=group_id, stop_at=datetime.datetime.now() ... | <|body_start_0|>
check = await DBCoolDownEvent.check_global_group_cool_down_event(group_id=group_id)
if check.success() and check.result == 1:
return check
elif check.success() and check.result in [0, 2]:
result = await DBCoolDownEvent.add_global_group_cool_down_event(gro... | 插件冷却工具类, 用于声明当前 matcher 权限及冷却等信息, 并负责处理具体冷却事件 - type: 冷却类型 - cool_down_time: 冷却时间, 单位秒 | PluginCoolDown | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PluginCoolDown:
"""插件冷却工具类, 用于声明当前 matcher 权限及冷却等信息, 并负责处理具体冷却事件 - type: 冷却类型 - cool_down_time: 冷却时间, 单位秒"""
async def check_and_set_global_group_cool_down(cls, group_id, seconds: int) -> Result.IntResult:
""":return: result = 1: Success with still CoolDown with duration in info resu... | stack_v2_sparse_classes_75kplus_train_005992 | 5,166 | permissive | [
{
"docstring": ":return: result = 1: Success with still CoolDown with duration in info result = 0: Success with not in CoolDown and set a new CoolDown event result = -1: Error",
"name": "check_and_set_global_group_cool_down",
"signature": "async def check_and_set_global_group_cool_down(cls, group_id, se... | 4 | stack_v2_sparse_classes_30k_train_001688 | Implement the Python class `PluginCoolDown` described below.
Class description:
插件冷却工具类, 用于声明当前 matcher 权限及冷却等信息, 并负责处理具体冷却事件 - type: 冷却类型 - cool_down_time: 冷却时间, 单位秒
Method signatures and docstrings:
- async def check_and_set_global_group_cool_down(cls, group_id, seconds: int) -> Result.IntResult: :return: result = ... | Implement the Python class `PluginCoolDown` described below.
Class description:
插件冷却工具类, 用于声明当前 matcher 权限及冷却等信息, 并负责处理具体冷却事件 - type: 冷却类型 - cool_down_time: 冷却时间, 单位秒
Method signatures and docstrings:
- async def check_and_set_global_group_cool_down(cls, group_id, seconds: int) -> Result.IntResult: :return: result = ... | 53a6683fccb0618e306abe9e103cec78445f3796 | <|skeleton|>
class PluginCoolDown:
"""插件冷却工具类, 用于声明当前 matcher 权限及冷却等信息, 并负责处理具体冷却事件 - type: 冷却类型 - cool_down_time: 冷却时间, 单位秒"""
async def check_and_set_global_group_cool_down(cls, group_id, seconds: int) -> Result.IntResult:
""":return: result = 1: Success with still CoolDown with duration in info resu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PluginCoolDown:
"""插件冷却工具类, 用于声明当前 matcher 权限及冷却等信息, 并负责处理具体冷却事件 - type: 冷却类型 - cool_down_time: 冷却时间, 单位秒"""
async def check_and_set_global_group_cool_down(cls, group_id, seconds: int) -> Result.IntResult:
""":return: result = 1: Success with still CoolDown with duration in info result = 0: Succe... | the_stack_v2_python_sparse | omega_miya/utils/omega_plugin_utils/cooldown.py | yekang-wu/omega-miya | train | 0 |
ca3c36319cd3895211cee02eec8a6ae55ede7cd1 | [
"if not nums:\n return 0\nd = {}\nmax_len = 0\nfor a in nums:\n if a not in d:\n l_len = d.get(a - 1, 0)\n r_len = d.get(a + 1, 0)\n cur_len = 1 + l_len + r_len\n if cur_len > max_len:\n max_len = cur_len\n d[a] = cur_len\n d[a - l_len] = cur_len\n d... | <|body_start_0|>
if not nums:
return 0
d = {}
max_len = 0
for a in nums:
if a not in d:
l_len = d.get(a - 1, 0)
r_len = d.get(a + 1, 0)
cur_len = 1 + l_len + r_len
if cur_len > max_len:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
"""20191009 80 ms 15.1 MB Python3 # 不判空 76 ms 15 MB Python3 # 先判空 网友的解法: https://leetcode-cn.com/problems/longest-consecutive-sequence/solution/dong-tai-gui-hua-python-ti-jie-by-jalan/ 这个思路太巧妙了, 维护了一张字典(哈希表), 然后遍历数组, 如果元素不再字... | stack_v2_sparse_classes_75kplus_train_005993 | 2,784 | no_license | [
{
"docstring": "20191009 80 ms 15.1 MB Python3 # 不判空 76 ms 15 MB Python3 # 先判空 网友的解法: https://leetcode-cn.com/problems/longest-consecutive-sequence/solution/dong-tai-gui-hua-python-ti-jie-by-jalan/ 这个思路太巧妙了, 维护了一张字典(哈希表), 然后遍历数组, 如果元素不再字典中, 就将它加入哈希表中, 并做一些更新 巧妙的地方在于, 每次都更新边界值, 这样如果字典中已有 [1, 3], 增加 2 的时候, 会通过 2 ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive(self, nums: List[int]) -> int: 20191009 80 ms 15.1 MB Python3 # 不判空 76 ms 15 MB Python3 # 先判空 网友的解法: https://leetcode-cn.com/problems/longest-consecutive-s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive(self, nums: List[int]) -> int: 20191009 80 ms 15.1 MB Python3 # 不判空 76 ms 15 MB Python3 # 先判空 网友的解法: https://leetcode-cn.com/problems/longest-consecutive-s... | 99a3abf1774933af73a8405f9b59e5e64906bca4 | <|skeleton|>
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
"""20191009 80 ms 15.1 MB Python3 # 不判空 76 ms 15 MB Python3 # 先判空 网友的解法: https://leetcode-cn.com/problems/longest-consecutive-sequence/solution/dong-tai-gui-hua-python-ti-jie-by-jalan/ 这个思路太巧妙了, 维护了一张字典(哈希表), 然后遍历数组, 如果元素不再字... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
"""20191009 80 ms 15.1 MB Python3 # 不判空 76 ms 15 MB Python3 # 先判空 网友的解法: https://leetcode-cn.com/problems/longest-consecutive-sequence/solution/dong-tai-gui-hua-python-ti-jie-by-jalan/ 这个思路太巧妙了, 维护了一张字典(哈希表), 然后遍历数组, 如果元素不再字典中, 就将它加入哈希表中,... | the_stack_v2_python_sparse | leetcode/128.longest-consecutive-sequence.py | iamkissg/leetcode | train | 0 | |
383cc12c88aef974a478e88fa6dcdf40c34db09c | [
"email = self.cleaned_data['email']\nself.users_cache = Account._default_manager.filter(email__iexact=email)\nif not len(self.users_cache):\n raise forms.ValidationError(self.error_messages['unknown'])\nif not any((user.is_active for user in self.users_cache)):\n raise forms.ValidationError(self.error_message... | <|body_start_0|>
email = self.cleaned_data['email']
self.users_cache = Account._default_manager.filter(email__iexact=email)
if not len(self.users_cache):
raise forms.ValidationError(self.error_messages['unknown'])
if not any((user.is_active for user in self.users_cache)):
... | PasswordResetForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
<|body_0|>
def save(self, domain_override=None, subject=settings.ACCOUNT_EMAIL_PASSWORD_RESET_SUBJECT, text_email_template_name='password_reset_email.txt', html... | stack_v2_sparse_classes_75kplus_train_005994 | 3,717 | permissive | [
{
"docstring": "Validates that an active user exists with the given email address.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "Generates a one-use only link for resetting password and sends to the user.",
"name": "save",
"signature": "def save(self, d... | 2 | null | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that an active user exists with the given email address.
- def save(self, domain_override=None, subject=settings.ACCOUNT_EMAIL_... | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that an active user exists with the given email address.
- def save(self, domain_override=None, subject=settings.ACCOUNT_EMAIL_... | c327928ee79063887c8783ffd9d68a25c367d496 | <|skeleton|>
class PasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
<|body_0|>
def save(self, domain_override=None, subject=settings.ACCOUNT_EMAIL_PASSWORD_RESET_SUBJECT, text_email_template_name='password_reset_email.txt', html... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
email = self.cleaned_data['email']
self.users_cache = Account._default_manager.filter(email__iexact=email)
if not len(self.users_cache):
raise forms.Va... | the_stack_v2_python_sparse | slothauth/forms.py | cdelguercio/slothauth | train | 2 | |
4dbea83dfaf3dd8886ca14ff6c3f6357acf090bf | [
"self.inputs.write(self.filename)\ndirname = path.dirname(self.filename)\nn3 = int(self.inputs['n3'])\nn2 = int(self.inputs['n2'])\nn1 = int(self.inputs['n1'])\nself.data = np.zeros([n1, n2, n3, 3])\nfor i, fname in enumerate(['file_u', 'file_v', 'file_w']):\n new_filename = path.join(dirname, self.inputs[fname]... | <|body_start_0|>
self.inputs.write(self.filename)
dirname = path.dirname(self.filename)
n3 = int(self.inputs['n3'])
n2 = int(self.inputs['n2'])
n1 = int(self.inputs['n1'])
self.data = np.zeros([n1, n2, n3, 3])
for i, fname in enumerate(['file_u', 'file_v', 'file_w... | A mann turbulence file is loaded using the inputfile used to create it. The actual path of the turbulence files is included in the mann inputfile. The class is loading the three files u,v,w and merge them into a 4D array located in self.data. methods: -------- write: write a file reade: read a file | MannTurbFile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MannTurbFile:
"""A mann turbulence file is loaded using the inputfile used to create it. The actual path of the turbulence files is included in the mann inputfile. The class is loading the three files u,v,w and merge them into a 4D array located in self.data. methods: -------- write: write a file... | stack_v2_sparse_classes_75kplus_train_005995 | 5,413 | permissive | [
{
"docstring": "Write a file (overrided) First write the input file corresponding to the new file. Then write the 3 corresponding turbulence files.",
"name": "_write",
"signature": "def _write(self)"
},
{
"docstring": "Read the file (overrided) The method first create a MannInputFile instance, t... | 2 | stack_v2_sparse_classes_30k_train_005104 | Implement the Python class `MannTurbFile` described below.
Class description:
A mann turbulence file is loaded using the inputfile used to create it. The actual path of the turbulence files is included in the mann inputfile. The class is loading the three files u,v,w and merge them into a 4D array located in self.data... | Implement the Python class `MannTurbFile` described below.
Class description:
A mann turbulence file is loaded using the inputfile used to create it. The actual path of the turbulence files is included in the mann inputfile. The class is loading the three files u,v,w and merge them into a 4D array located in self.data... | f8ad09018420cfb3a419173f97b129de7118d814 | <|skeleton|>
class MannTurbFile:
"""A mann turbulence file is loaded using the inputfile used to create it. The actual path of the turbulence files is included in the mann inputfile. The class is loading the three files u,v,w and merge them into a 4D array located in self.data. methods: -------- write: write a file... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MannTurbFile:
"""A mann turbulence file is loaded using the inputfile used to create it. The actual path of the turbulence files is included in the mann inputfile. The class is loading the three files u,v,w and merge them into a 4D array located in self.data. methods: -------- write: write a file reade: read ... | the_stack_v2_python_sparse | py4we/mann.py | gtpedrosa/Python4WindEnergy | train | 0 |
cf69a9883dea22212323bca0ab5c5c8f3ad1c178 | [
"super(VanillaEmbedder, self).__init__()\nself.embedding = embedding\nself.embedding_dim = embedding_dim",
"try:\n tokens = iter_dict['tokens']\n assert tokens.dim() == 2\n embedding = self.embedding(tokens)\n return embedding\nexcept AttributeError:\n raise ValueError(f'iter_dict passed should hav... | <|body_start_0|>
super(VanillaEmbedder, self).__init__()
self.embedding = embedding
self.embedding_dim = embedding_dim
<|end_body_0|>
<|body_start_1|>
try:
tokens = iter_dict['tokens']
assert tokens.dim() == 2
embedding = self.embedding(tokens)
... | VanillaEmbedder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VanillaEmbedder:
def __init__(self, embedding: nn.Embedding, embedding_dim: int):
"""Vanilla Embedder embeds the tokens using the embedding passed. Parameters ---------- embedding : nn.Embedding A pytoch embedding that maps textual units to embeddings embedding_dim : int The embedding di... | stack_v2_sparse_classes_75kplus_train_005996 | 1,645 | permissive | [
{
"docstring": "Vanilla Embedder embeds the tokens using the embedding passed. Parameters ---------- embedding : nn.Embedding A pytoch embedding that maps textual units to embeddings embedding_dim : int The embedding dimension",
"name": "__init__",
"signature": "def __init__(self, embedding: nn.Embeddin... | 2 | stack_v2_sparse_classes_30k_train_054260 | Implement the Python class `VanillaEmbedder` described below.
Class description:
Implement the VanillaEmbedder class.
Method signatures and docstrings:
- def __init__(self, embedding: nn.Embedding, embedding_dim: int): Vanilla Embedder embeds the tokens using the embedding passed. Parameters ---------- embedding : nn... | Implement the Python class `VanillaEmbedder` described below.
Class description:
Implement the VanillaEmbedder class.
Method signatures and docstrings:
- def __init__(self, embedding: nn.Embedding, embedding_dim: int): Vanilla Embedder embeds the tokens using the embedding passed. Parameters ---------- embedding : nn... | cb4c1413ddc3c749835e1cb80db31c0060e7a1eb | <|skeleton|>
class VanillaEmbedder:
def __init__(self, embedding: nn.Embedding, embedding_dim: int):
"""Vanilla Embedder embeds the tokens using the embedding passed. Parameters ---------- embedding : nn.Embedding A pytoch embedding that maps textual units to embeddings embedding_dim : int The embedding di... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VanillaEmbedder:
def __init__(self, embedding: nn.Embedding, embedding_dim: int):
"""Vanilla Embedder embeds the tokens using the embedding passed. Parameters ---------- embedding : nn.Embedding A pytoch embedding that maps textual units to embeddings embedding_dim : int The embedding dimension"""
... | the_stack_v2_python_sparse | sciwing/modules/embedders/vanilla_embedder.py | yaxche-io/sciwing | train | 0 | |
816af626ffa87e53c5ff3f64285d077ca4ea5941 | [
"self.device = device\nself.matting_module = matting_module\nself.trimap_generator = trimap_generator",
"if len(images) != len(masks):\n raise ValueError('Images and Masks lists should have same length!')\nimages = thread_pool_processing(lambda x: convert_image(load_image(x)), images)\nmasks = thread_pool_proc... | <|body_start_0|>
self.device = device
self.matting_module = matting_module
self.trimap_generator = trimap_generator
<|end_body_0|>
<|body_start_1|>
if len(images) != len(masks):
raise ValueError('Images and Masks lists should have same length!')
images = thread_pool_... | Improving the edges of the object mask using neural networks for matting and algorithms for creating trimap. Neural network for matting performs accurate object edge detection by using a special map called trimap, with unknown area that we scan for boundary, already known general object area and the background. | MattingMethod | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MattingMethod:
"""Improving the edges of the object mask using neural networks for matting and algorithms for creating trimap. Neural network for matting performs accurate object edge detection by using a special map called trimap, with unknown area that we scan for boundary, already known genera... | stack_v2_sparse_classes_75kplus_train_005997 | 2,690 | permissive | [
{
"docstring": "Initializes Matting Method class. Args: matting_module: Initialized matting neural network class trimap_generator: Initialized trimap generator class device: Processing device used for applying mask to image",
"name": "__init__",
"signature": "def __init__(self, matting_module: Union[FBA... | 2 | null | Implement the Python class `MattingMethod` described below.
Class description:
Improving the edges of the object mask using neural networks for matting and algorithms for creating trimap. Neural network for matting performs accurate object edge detection by using a special map called trimap, with unknown area that we ... | Implement the Python class `MattingMethod` described below.
Class description:
Improving the edges of the object mask using neural networks for matting and algorithms for creating trimap. Neural network for matting performs accurate object edge detection by using a special map called trimap, with unknown area that we ... | 2935e4655d2c0260195e22ac08af6c43b5969fdd | <|skeleton|>
class MattingMethod:
"""Improving the edges of the object mask using neural networks for matting and algorithms for creating trimap. Neural network for matting performs accurate object edge detection by using a special map called trimap, with unknown area that we scan for boundary, already known genera... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MattingMethod:
"""Improving the edges of the object mask using neural networks for matting and algorithms for creating trimap. Neural network for matting performs accurate object edge detection by using a special map called trimap, with unknown area that we scan for boundary, already known general object area... | the_stack_v2_python_sparse | carvekit/pipelines/postprocessing.py | OPHoperHPO/image-background-remove-tool | train | 1,029 |
3d2a9b7782448fb7a65c9d65715362958ce73809 | [
"self.N = N\nself.timestep = timestep * unit.femtosecond\nself.collision_rate = collision_rate * (1 / unit.picosecond)\nself.length_scale = length_scale * unit.nanometer\nself.temperature = temperature * unit.kelvin\nself.mass = mass * unit.amu",
"mass_in_kg = self.mass._value * 1.66 * 10 ** (-27) * unit.kilogram... | <|body_start_0|>
self.N = N
self.timestep = timestep * unit.femtosecond
self.collision_rate = collision_rate * (1 / unit.picosecond)
self.length_scale = length_scale * unit.nanometer
self.temperature = temperature * unit.kelvin
self.mass = mass * unit.amu
<|end_body_0|>
... | The methods in this class provide ways of calculating physically meaningful quantities in the Rouse model fromn polychrom parameter values and vice versa. The parameters in the constructor are usually set for computational convenience and do not have any physical meaning, except the number of monomers, N. Notes ----- T... | SimulationParams | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulationParams:
"""The methods in this class provide ways of calculating physically meaningful quantities in the Rouse model fromn polychrom parameter values and vice versa. The parameters in the constructor are usually set for computational convenience and do not have any physical meaning, exc... | stack_v2_sparse_classes_75kplus_train_005998 | 9,573 | permissive | [
{
"docstring": "Parameters ---------- N : int number of particles (default 1000) timestep : float timestep in femtoseconds (default 170) collision_rate : float collision rate in inverse picoseconds (default 2.0) mass : float Particle mass (default 100 amu) temperature : float temperature in kelvins, (defaults t... | 5 | stack_v2_sparse_classes_30k_train_050074 | Implement the Python class `SimulationParams` described below.
Class description:
The methods in this class provide ways of calculating physically meaningful quantities in the Rouse model fromn polychrom parameter values and vice versa. The parameters in the constructor are usually set for computational convenience an... | Implement the Python class `SimulationParams` described below.
Class description:
The methods in this class provide ways of calculating physically meaningful quantities in the Rouse model fromn polychrom parameter values and vice versa. The parameters in the constructor are usually set for computational convenience an... | 8052c597b0566f88a7b7ef80658a3f077e474a7e | <|skeleton|>
class SimulationParams:
"""The methods in this class provide ways of calculating physically meaningful quantities in the Rouse model fromn polychrom parameter values and vice versa. The parameters in the constructor are usually set for computational convenience and do not have any physical meaning, exc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimulationParams:
"""The methods in this class provide ways of calculating physically meaningful quantities in the Rouse model fromn polychrom parameter values and vice versa. The parameters in the constructor are usually set for computational convenience and do not have any physical meaning, except the numbe... | the_stack_v2_python_sparse | polychrom/param_units.py | open2c/polychrom | train | 24 |
530238e63a0c0470a8bf4368f9fffb3fa6466ad2 | [
"comment = IdeaComment.objects.filter(pk=comment_pk, think=idea_pk).first()\nif not comment:\n return self.success()\nif comment.user_id != request._request.uid:\n return self.error(errorcode.MSG_NOT_OWNER, errorcode.NOT_OWNER)\ntry:\n comment.delete()\nexcept:\n return self.error(errorcode.MSG_DB_ERROR... | <|body_start_0|>
comment = IdeaComment.objects.filter(pk=comment_pk, think=idea_pk).first()
if not comment:
return self.success()
if comment.user_id != request._request.uid:
return self.error(errorcode.MSG_NOT_OWNER, errorcode.NOT_OWNER)
try:
comment.d... | MonoIdeaCommentView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonoIdeaCommentView:
def delete(self, request, idea_pk, comment_pk):
"""删除评论"""
<|body_0|>
def put(self, request, idea_pk, comment_pk):
"""修改评论"""
<|body_1|>
def get(self, request, idea_pk, comment_pk):
"""查看评论"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_75kplus_train_005999 | 8,429 | no_license | [
{
"docstring": "删除评论",
"name": "delete",
"signature": "def delete(self, request, idea_pk, comment_pk)"
},
{
"docstring": "修改评论",
"name": "put",
"signature": "def put(self, request, idea_pk, comment_pk)"
},
{
"docstring": "查看评论",
"name": "get",
"signature": "def get(self, ... | 3 | null | Implement the Python class `MonoIdeaCommentView` described below.
Class description:
Implement the MonoIdeaCommentView class.
Method signatures and docstrings:
- def delete(self, request, idea_pk, comment_pk): 删除评论
- def put(self, request, idea_pk, comment_pk): 修改评论
- def get(self, request, idea_pk, comment_pk): 查看评论 | Implement the Python class `MonoIdeaCommentView` described below.
Class description:
Implement the MonoIdeaCommentView class.
Method signatures and docstrings:
- def delete(self, request, idea_pk, comment_pk): 删除评论
- def put(self, request, idea_pk, comment_pk): 修改评论
- def get(self, request, idea_pk, comment_pk): 查看评论... | 6a68fb207f43e5ed65299cc08535b35d5e934ead | <|skeleton|>
class MonoIdeaCommentView:
def delete(self, request, idea_pk, comment_pk):
"""删除评论"""
<|body_0|>
def put(self, request, idea_pk, comment_pk):
"""修改评论"""
<|body_1|>
def get(self, request, idea_pk, comment_pk):
"""查看评论"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MonoIdeaCommentView:
def delete(self, request, idea_pk, comment_pk):
"""删除评论"""
comment = IdeaComment.objects.filter(pk=comment_pk, think=idea_pk).first()
if not comment:
return self.success()
if comment.user_id != request._request.uid:
return self.error... | the_stack_v2_python_sparse | apps/ideas/views.py | Slowhalfframe/fanyijiang-API | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.