blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
46b238e212e14c1bc720874bdfe8c685667a8479 | [
"if not points:\n return 0\npoints = sorted(points, key=lambda x: x[1])\nend = float('-inf')\nres = 0\nfor s, e in points:\n if s > end:\n end = e\n res += 1\nreturn res",
"if not points:\n return 0\npoints = sorted(points, key=lambda x: (x[0], x[1]))\nres = 0\nstart = points[0][0]\nend = p... | <|body_start_0|>
if not points:
return 0
points = sorted(points, key=lambda x: x[1])
end = float('-inf')
res = 0
for s, e in points:
if s > end:
end = e
res += 1
return res
<|end_body_0|>
<|body_start_1|>
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def force_findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not ... | stack_v2_sparse_classes_10k_train_001100 | 2,436 | no_license | [
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "findMinArrowShots",
"signature": "def findMinArrowShots(self, points)"
},
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "force_findMinArrowShots",
"signature": "def force_findMinArrowShots(self, po... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int
- def force_findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int
- def force_findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int
<|skeleton|... | 8595b04cf5a024c2cd8a97f750d890a818568401 | <|skeleton|>
class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def force_findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
if not points:
return 0
points = sorted(points, key=lambda x: x[1])
end = float('-inf')
res = 0
for s, e in points:
if s > end:
... | the_stack_v2_python_sparse | python/452.minimum-number-of-arrows-to-burst-balloons.py | tainenko/Leetcode2019 | train | 5 | |
1c57739dd3b589adda0cdb9c1f55a9ab4ad87373 | [
"n1_dic = {}\nn2_dic = {}\nres = []\nfor n1 in nums1:\n n1_dic[n1] = n1_dic.get(n1, 0) + 1\nfor n2 in nums2:\n n2_dic[n2] = n2_dic.get(n2, 0) + 1\nfor n, c in n1_dic.items():\n if n2_dic.get(n) == c:\n res += [n] * c\n elif n in n2_dic:\n res += [n] * min(c, n2_dic.get(n))\nreturn res",
... | <|body_start_0|>
n1_dic = {}
n2_dic = {}
res = []
for n1 in nums1:
n1_dic[n1] = n1_dic.get(n1, 0) + 1
for n2 in nums2:
n2_dic[n2] = n2_dic.get(n2, 0) + 1
for n, c in n1_dic.items():
if n2_dic.get(n) == c:
res += [n] * c
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""借用两个字典,用于计数,然后找到共同的数,1、如果计数相等,则乘以计数,2、如果不相等,则乘以两个字典的最小值"""
<|body_0|>
def intersect1(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""先排序,再用双指针法,空间复杂度为O(1)"""
<|body_... | stack_v2_sparse_classes_10k_train_001101 | 3,351 | no_license | [
{
"docstring": "借用两个字典,用于计数,然后找到共同的数,1、如果计数相等,则乘以计数,2、如果不相等,则乘以两个字典的最小值",
"name": "intersect",
"signature": "def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]"
},
{
"docstring": "先排序,再用双指针法,空间复杂度为O(1)",
"name": "intersect1",
"signature": "def intersect1(self, nums1: Li... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: 借用两个字典,用于计数,然后找到共同的数,1、如果计数相等,则乘以计数,2、如果不相等,则乘以两个字典的最小值
- def intersect1(self, nums1: List[int], nums2: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: 借用两个字典,用于计数,然后找到共同的数,1、如果计数相等,则乘以计数,2、如果不相等,则乘以两个字典的最小值
- def intersect1(self, nums1: List[int], nums2: List... | 069bb0b751ef7f469036b9897436eb5d138ffa24 | <|skeleton|>
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""借用两个字典,用于计数,然后找到共同的数,1、如果计数相等,则乘以计数,2、如果不相等,则乘以两个字典的最小值"""
<|body_0|>
def intersect1(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""先排序,再用双指针法,空间复杂度为O(1)"""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""借用两个字典,用于计数,然后找到共同的数,1、如果计数相等,则乘以计数,2、如果不相等,则乘以两个字典的最小值"""
n1_dic = {}
n2_dic = {}
res = []
for n1 in nums1:
n1_dic[n1] = n1_dic.get(n1, 0) + 1
for n2 in nums2:
... | the_stack_v2_python_sparse | 算法/Week_02/350. 两个数组的交集 II.py | RichieSong/algorithm | train | 0 | |
e027a9183c2c149dd94aeeaa48900e5a483960bd | [
"super().__init__()\nself._img_size = config.get('img_size')\nself._input_channel = config.get('input_channel')\nself._filter_sizes = config.get('filter_size')\nself._kernel_size = config.get('kernel_size')\nself._padding = padding\nself._stride = stride\nself._dilation = dilation\nself._encoder_maxpool_count = con... | <|body_start_0|>
super().__init__()
self._img_size = config.get('img_size')
self._input_channel = config.get('input_channel')
self._filter_sizes = config.get('filter_size')
self._kernel_size = config.get('kernel_size')
self._padding = padding
self._stride = stride... | Deterministic_Conv_Encoder | Deterministic_Conv_Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Deterministic_Conv_Encoder:
"""Deterministic_Conv_Encoder"""
def __init__(self, config, padding=0, stride=2, dilation=1):
"""NP"""
<|body_0|>
def forward(self, inputs):
"""Args: input : imamges (num_tasks, n_way, k_shot, filter_size img_size, img_size) Return: ou... | stack_v2_sparse_classes_10k_train_001102 | 18,202 | no_license | [
{
"docstring": "NP",
"name": "__init__",
"signature": "def __init__(self, config, padding=0, stride=2, dilation=1)"
},
{
"docstring": "Args: input : imamges (num_tasks, n_way, k_shot, filter_size img_size, img_size) Return: output :",
"name": "forward",
"signature": "def forward(self, in... | 2 | stack_v2_sparse_classes_30k_train_003421 | Implement the Python class `Deterministic_Conv_Encoder` described below.
Class description:
Deterministic_Conv_Encoder
Method signatures and docstrings:
- def __init__(self, config, padding=0, stride=2, dilation=1): NP
- def forward(self, inputs): Args: input : imamges (num_tasks, n_way, k_shot, filter_size img_size,... | Implement the Python class `Deterministic_Conv_Encoder` described below.
Class description:
Deterministic_Conv_Encoder
Method signatures and docstrings:
- def __init__(self, config, padding=0, stride=2, dilation=1): NP
- def forward(self, inputs): Args: input : imamges (num_tasks, n_way, k_shot, filter_size img_size,... | c7e1bfb49ebaec6937ed7b186689227f95a43e0f | <|skeleton|>
class Deterministic_Conv_Encoder:
"""Deterministic_Conv_Encoder"""
def __init__(self, config, padding=0, stride=2, dilation=1):
"""NP"""
<|body_0|>
def forward(self, inputs):
"""Args: input : imamges (num_tasks, n_way, k_shot, filter_size img_size, img_size) Return: ou... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Deterministic_Conv_Encoder:
"""Deterministic_Conv_Encoder"""
def __init__(self, config, padding=0, stride=2, dilation=1):
"""NP"""
super().__init__()
self._img_size = config.get('img_size')
self._input_channel = config.get('input_channel')
self._filter_sizes = conf... | the_stack_v2_python_sparse | model/MAML/Part/encoder.py | MingyuKim87/MLwM | train | 0 |
b06fb0a67af2b4d00f281074cd37d2b21d85bd6c | [
"super().__init__(data, chunksize, axis, **kwargs)\na = self.kwargs.pop('start', 0)\nb = self.kwargs.pop('stop', self.data.shape[axis])\nself.start, self.stop, _ = slice(a, b).indices(data.shape[axis])\nself.data.close()",
"s = list(self.data.shape)\ns[self.axis] = self.stop - self.start\nreturn tuple(s)",
"sel... | <|body_start_0|>
super().__init__(data, chunksize, axis, **kwargs)
a = self.kwargs.pop('start', 0)
b = self.kwargs.pop('stop', self.data.shape[axis])
self.start, self.stop, _ = slice(a, b).indices(data.shape[axis])
self.data.close()
<|end_body_0|>
<|body_start_1|>
s = li... | A Producer of ndarrays from an openseize file Reader instance. Attrs: Producer Attrs start: The start sample along production axis at which data production begins. stop: The stop sample along production axis at which data production stops. kwargs: Arguments passed to read method of a file reader instance. Notes: The da... | ReaderProducer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReaderProducer:
"""A Producer of ndarrays from an openseize file Reader instance. Attrs: Producer Attrs start: The start sample along production axis at which data production begins. stop: The stop sample along production axis at which data production stops. kwargs: Arguments passed to read metho... | stack_v2_sparse_classes_10k_train_001103 | 17,903 | permissive | [
{
"docstring": "Initialize this Producer with a closed 'data' Reader instance.",
"name": "__init__",
"signature": "def __init__(self, data, chunksize, axis, **kwargs)"
},
{
"docstring": "Return the summed shape of all arrays in this Reader.",
"name": "shape",
"signature": "def shape(self... | 3 | stack_v2_sparse_classes_30k_train_002350 | Implement the Python class `ReaderProducer` described below.
Class description:
A Producer of ndarrays from an openseize file Reader instance. Attrs: Producer Attrs start: The start sample along production axis at which data production begins. stop: The stop sample along production axis at which data production stops.... | Implement the Python class `ReaderProducer` described below.
Class description:
A Producer of ndarrays from an openseize file Reader instance. Attrs: Producer Attrs start: The start sample along production axis at which data production begins. stop: The stop sample along production axis at which data production stops.... | 09ee87e044c7272754e33636dc2f14932145c903 | <|skeleton|>
class ReaderProducer:
"""A Producer of ndarrays from an openseize file Reader instance. Attrs: Producer Attrs start: The start sample along production axis at which data production begins. stop: The stop sample along production axis at which data production stops. kwargs: Arguments passed to read metho... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReaderProducer:
"""A Producer of ndarrays from an openseize file Reader instance. Attrs: Producer Attrs start: The start sample along production axis at which data production begins. stop: The stop sample along production axis at which data production stops. kwargs: Arguments passed to read method of a file r... | the_stack_v2_python_sparse | src/openseize/core/producer.py | mscaudill/openseize | train | 12 |
ec8088077279899aaa232eaaed0696e8faeaa525 | [
"super(CustomSchedule, self).__init__()\nself.d_model = model\nself.d_model = tf.cast(self.d_model, tf.float32)\nself.warmup_steps = warmup_steps",
"p1 = tf.math.rsqrt(step)\np2 = step * self.warmup_steps ** (-1.5)\noutput = tf.math.rsqrt(self.d_model) * tf.math.minimum(p1, p2)\nreturn output"
] | <|body_start_0|>
super(CustomSchedule, self).__init__()
self.d_model = model
self.d_model = tf.cast(self.d_model, tf.float32)
self.warmup_steps = warmup_steps
<|end_body_0|>
<|body_start_1|>
p1 = tf.math.rsqrt(step)
p2 = step * self.warmup_steps ** (-1.5)
output ... | Custom Schedule class | CustomSchedule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSchedule:
"""Custom Schedule class"""
def __init__(self, model, warmup_steps=4000):
"""Class Constructor"""
<|body_0|>
def __call__(self, step):
"""Method call"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(CustomSchedule, self).__i... | stack_v2_sparse_classes_10k_train_001104 | 4,824 | no_license | [
{
"docstring": "Class Constructor",
"name": "__init__",
"signature": "def __init__(self, model, warmup_steps=4000)"
},
{
"docstring": "Method call",
"name": "__call__",
"signature": "def __call__(self, step)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002723 | Implement the Python class `CustomSchedule` described below.
Class description:
Custom Schedule class
Method signatures and docstrings:
- def __init__(self, model, warmup_steps=4000): Class Constructor
- def __call__(self, step): Method call | Implement the Python class `CustomSchedule` described below.
Class description:
Custom Schedule class
Method signatures and docstrings:
- def __init__(self, model, warmup_steps=4000): Class Constructor
- def __call__(self, step): Method call
<|skeleton|>
class CustomSchedule:
"""Custom Schedule class"""
def... | fc2cec306961f7ca2448965ddd3a2f656bbe10c7 | <|skeleton|>
class CustomSchedule:
"""Custom Schedule class"""
def __init__(self, model, warmup_steps=4000):
"""Class Constructor"""
<|body_0|>
def __call__(self, step):
"""Method call"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomSchedule:
"""Custom Schedule class"""
def __init__(self, model, warmup_steps=4000):
"""Class Constructor"""
super(CustomSchedule, self).__init__()
self.d_model = model
self.d_model = tf.cast(self.d_model, tf.float32)
self.warmup_steps = warmup_steps
def ... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-train.py | dalexach/holbertonschool-machine_learning | train | 2 |
ae4e3880ffa17975430fea490f616daefa904fd9 | [
"config = ContainerConfig('shipper/base', \"echo 'hi'\")\nexpected = {'AttachStderr': False, 'AttachStdin': False, 'AttachStdout': False, 'Cmd': ['echo', 'hi'], 'Dns': None, 'Env': None, 'Hostname': None, 'Image': 'shipper/base', 'Memory': 0, 'OpenStdin': False, 'StdinOnce': False, 'ExposedPorts': {}, 'Tty': False,... | <|body_start_0|>
config = ContainerConfig('shipper/base', "echo 'hi'")
expected = {'AttachStderr': False, 'AttachStdin': False, 'AttachStdout': False, 'Cmd': ['echo', 'hi'], 'Dns': None, 'Env': None, 'Hostname': None, 'Image': 'shipper/base', 'Memory': 0, 'OpenStdin': False, 'StdinOnce': False, 'Exposed... | Tests container wrappers | ShipperContainerTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShipperContainerTestCase:
"""Tests container wrappers"""
def test_container_config_defaults(self):
"""Makes sure defaults for container config function are sane."""
<|body_0|>
def test_container_config(self):
"""Make sure all parameters are converted properly and... | stack_v2_sparse_classes_10k_train_001105 | 49,482 | no_license | [
{
"docstring": "Makes sure defaults for container config function are sane.",
"name": "test_container_config_defaults",
"signature": "def test_container_config_defaults(self)"
},
{
"docstring": "Make sure all parameters are converted properly and to the right properties.",
"name": "test_cont... | 2 | null | Implement the Python class `ShipperContainerTestCase` described below.
Class description:
Tests container wrappers
Method signatures and docstrings:
- def test_container_config_defaults(self): Makes sure defaults for container config function are sane.
- def test_container_config(self): Make sure all parameters are c... | Implement the Python class `ShipperContainerTestCase` described below.
Class description:
Tests container wrappers
Method signatures and docstrings:
- def test_container_config_defaults(self): Makes sure defaults for container config function are sane.
- def test_container_config(self): Make sure all parameters are c... | 0ac6653219c2701c13c508c5c4fc9bc3437eea06 | <|skeleton|>
class ShipperContainerTestCase:
"""Tests container wrappers"""
def test_container_config_defaults(self):
"""Makes sure defaults for container config function are sane."""
<|body_0|>
def test_container_config(self):
"""Make sure all parameters are converted properly and... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ShipperContainerTestCase:
"""Tests container wrappers"""
def test_container_config_defaults(self):
"""Makes sure defaults for container config function are sane."""
config = ContainerConfig('shipper/base', "echo 'hi'")
expected = {'AttachStderr': False, 'AttachStdin': False, 'Atta... | the_stack_v2_python_sparse | repoData/mailgun-shipper/allPythonContent.py | aCoffeeYin/pyreco | train | 0 |
2599df9f5dd544c1919cc88697b9cce75b5cf2d7 | [
"self.temp_path = mkdtemp(prefix='pelicantests.')\nself.temp_cache = mkdtemp(prefix='pelican_cache.')\nos.chdir(TEST_DATA_DIR)",
"rmtree(self.temp_path)\nrmtree(self.temp_cache)\nos.chdir(PLUGIN_DIR)",
"base_path = os.path.dirname(os.path.abspath(__file__))\nbase_path = os.path.join(base_path, 'test_data')\ncon... | <|body_start_0|>
self.temp_path = mkdtemp(prefix='pelicantests.')
self.temp_cache = mkdtemp(prefix='pelican_cache.')
os.chdir(TEST_DATA_DIR)
<|end_body_0|>
<|body_start_1|>
rmtree(self.temp_path)
rmtree(self.temp_cache)
os.chdir(PLUGIN_DIR)
<|end_body_1|>
<|body_start_2... | Test running Pelican with the Plugin | TestFullRun | [
"AGPL-3.0-only",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFullRun:
"""Test running Pelican with the Plugin"""
def setUp(self):
"""Create temporary output and cache folders"""
<|body_0|>
def tearDown(self):
"""Remove output and cache folders"""
<|body_1|>
def test_generic_tag_with_config(self):
"... | stack_v2_sparse_classes_10k_train_001106 | 2,091 | permissive | [
{
"docstring": "Create temporary output and cache folders",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Remove output and cache folders",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "Test generation of site with a generic tag tha... | 3 | stack_v2_sparse_classes_30k_train_004750 | Implement the Python class `TestFullRun` described below.
Class description:
Test running Pelican with the Plugin
Method signatures and docstrings:
- def setUp(self): Create temporary output and cache folders
- def tearDown(self): Remove output and cache folders
- def test_generic_tag_with_config(self): Test generati... | Implement the Python class `TestFullRun` described below.
Class description:
Test running Pelican with the Plugin
Method signatures and docstrings:
- def setUp(self): Create temporary output and cache folders
- def tearDown(self): Remove output and cache folders
- def test_generic_tag_with_config(self): Test generati... | b5d68070b6f15677a183424c84e30440e128e1ea | <|skeleton|>
class TestFullRun:
"""Test running Pelican with the Plugin"""
def setUp(self):
"""Create temporary output and cache folders"""
<|body_0|>
def tearDown(self):
"""Remove output and cache folders"""
<|body_1|>
def test_generic_tag_with_config(self):
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestFullRun:
"""Test running Pelican with the Plugin"""
def setUp(self):
"""Create temporary output and cache folders"""
self.temp_path = mkdtemp(prefix='pelicantests.')
self.temp_cache = mkdtemp(prefix='pelican_cache.')
os.chdir(TEST_DATA_DIR)
def tearDown(self):
... | the_stack_v2_python_sparse | plugins/liquid_tags/test_generic.py | JackMcKew/jackmckew.dev | train | 15 |
90c430c99d1bb2798fbe46dba714401a4be85254 | [
"dir_path = Path(dir_path)\ndestination = dir_path / usage_constant.USAGE_STATS_FILE\ntemp = dir_path / f'{usage_constant.USAGE_STATS_FILE}.tmp'\nwith temp.open(mode='w') as json_file:\n json_file.write(json.dumps(asdict(data)))\nif sys.platform == 'win32':\n destination.unlink(missing_ok=True)\ntemp.rename(d... | <|body_start_0|>
dir_path = Path(dir_path)
destination = dir_path / usage_constant.USAGE_STATS_FILE
temp = dir_path / f'{usage_constant.USAGE_STATS_FILE}.tmp'
with temp.open(mode='w') as json_file:
json_file.write(json.dumps(asdict(data)))
if sys.platform == 'win32':
... | The client implementation for usage report. It is in charge of writing usage stats to the directory and report usage stats. | UsageReportClient | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsageReportClient:
"""The client implementation for usage report. It is in charge of writing usage stats to the directory and report usage stats."""
def write_usage_data(self, data: UsageStatsToWrite, dir_path: str) -> None:
"""Write the usage data to the directory. Params: data: Dat... | stack_v2_sparse_classes_10k_train_001107 | 29,968 | permissive | [
{
"docstring": "Write the usage data to the directory. Params: data: Data to report dir_path: The path to the directory to write usage data.",
"name": "write_usage_data",
"signature": "def write_usage_data(self, data: UsageStatsToWrite, dir_path: str) -> None"
},
{
"docstring": "Report the usage... | 2 | null | Implement the Python class `UsageReportClient` described below.
Class description:
The client implementation for usage report. It is in charge of writing usage stats to the directory and report usage stats.
Method signatures and docstrings:
- def write_usage_data(self, data: UsageStatsToWrite, dir_path: str) -> None:... | Implement the Python class `UsageReportClient` described below.
Class description:
The client implementation for usage report. It is in charge of writing usage stats to the directory and report usage stats.
Method signatures and docstrings:
- def write_usage_data(self, data: UsageStatsToWrite, dir_path: str) -> None:... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class UsageReportClient:
"""The client implementation for usage report. It is in charge of writing usage stats to the directory and report usage stats."""
def write_usage_data(self, data: UsageStatsToWrite, dir_path: str) -> None:
"""Write the usage data to the directory. Params: data: Dat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UsageReportClient:
"""The client implementation for usage report. It is in charge of writing usage stats to the directory and report usage stats."""
def write_usage_data(self, data: UsageStatsToWrite, dir_path: str) -> None:
"""Write the usage data to the directory. Params: data: Data to report d... | the_stack_v2_python_sparse | python/ray/_private/usage/usage_lib.py | ray-project/ray | train | 29,482 |
20bfbb8ce46abcacffd5f9d200fe880aa1807102 | [
"if len(s) <= 1:\n return len(s)\nn = len(s)\ns1 = s\ns2 = ''.join(list(s)[::-1])\ndp = [[0 for _ in range(n + 1)] for _ in range(n + 1)]\nfor i in range(1, n + 1):\n for j in range(1, n + 1):\n if s1[i - 1] == s2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n else:\n dp[i][j]... | <|body_start_0|>
if len(s) <= 1:
return len(s)
n = len(s)
s1 = s
s2 = ''.join(list(s)[::-1])
dp = [[0 for _ in range(n + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindromeSubseq0(self, s):
""":type s: str :rtype: int 解法:求s和s反转后的字符串的最长公共子序列"""
<|body_0|>
def longestPalindromeSubseq(self, s):
""":type s: str :rtype: int 解法:dp, 直接求最长回文子序列的长度,dp[i][j]表示s[i:j]的最长回文子序列的长度"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_10k_train_001108 | 1,566 | no_license | [
{
"docstring": ":type s: str :rtype: int 解法:求s和s反转后的字符串的最长公共子序列",
"name": "longestPalindromeSubseq0",
"signature": "def longestPalindromeSubseq0(self, s)"
},
{
"docstring": ":type s: str :rtype: int 解法:dp, 直接求最长回文子序列的长度,dp[i][j]表示s[i:j]的最长回文子序列的长度",
"name": "longestPalindromeSubseq",
"si... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindromeSubseq0(self, s): :type s: str :rtype: int 解法:求s和s反转后的字符串的最长公共子序列
- def longestPalindromeSubseq(self, s): :type s: str :rtype: int 解法:dp, 直接求最长回文子序列的长度,dp[i]... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindromeSubseq0(self, s): :type s: str :rtype: int 解法:求s和s反转后的字符串的最长公共子序列
- def longestPalindromeSubseq(self, s): :type s: str :rtype: int 解法:dp, 直接求最长回文子序列的长度,dp[i]... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def longestPalindromeSubseq0(self, s):
""":type s: str :rtype: int 解法:求s和s反转后的字符串的最长公共子序列"""
<|body_0|>
def longestPalindromeSubseq(self, s):
""":type s: str :rtype: int 解法:dp, 直接求最长回文子序列的长度,dp[i][j]表示s[i:j]的最长回文子序列的长度"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindromeSubseq0(self, s):
""":type s: str :rtype: int 解法:求s和s反转后的字符串的最长公共子序列"""
if len(s) <= 1:
return len(s)
n = len(s)
s1 = s
s2 = ''.join(list(s)[::-1])
dp = [[0 for _ in range(n + 1)] for _ in range(n + 1)]
for i in... | the_stack_v2_python_sparse | 516.最长回文子序列.py | yangyuxiang1996/leetcode | train | 0 | |
df88b00bb7546e7d79a2ac618ec0ec15fe4eb668 | [
"if root is None:\n return ''\ncurr_lvl = [root]\nnext_lvl = []\nans = []\nwhile curr_lvl:\n tmp_ans = ','.join((str(node.val) if node is not None else '*' for node in curr_lvl))\n ans.append(tmp_ans)\n nxt_lvl = []\n for each in curr_lvl:\n if each is not None:\n nxt_lvl.append(eac... | <|body_start_0|>
if root is None:
return ''
curr_lvl = [root]
next_lvl = []
ans = []
while curr_lvl:
tmp_ans = ','.join((str(node.val) if node is not None else '*' for node in curr_lvl))
ans.append(tmp_ans)
nxt_lvl = []
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_001109 | 1,779 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_003170 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | eeaa632e4d2b103c79925e823a05072a7264460e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root is None:
return ''
curr_lvl = [root]
next_lvl = []
ans = []
while curr_lvl:
tmp_ans = ','.join((str(node.val) if node is n... | the_stack_v2_python_sparse | Serialize and Deserialize Binary Tree.py | RiddhiRex/Leetcode | train | 0 | |
3b5266a4acee04ad6a39a2efb0e8516bdc6c0a55 | [
"mean, stddevs = super().get_mean_and_stddevs(sites, rup, dists, imt, stddev_types)\nif imt == PGA():\n freq = 50.0\nelif imt == PGV():\n freq = 2.0\nelse:\n freq = 1.0 / imt.period\nx1 = np.min([-0.18 + 0.17 * np.log10(freq), 0])\nif rup.hypo_depth < 20.0:\n x0 = np.max([0.217 - 0.321 * np.log10(freq),... | <|body_start_0|>
mean, stddevs = super().get_mean_and_stddevs(sites, rup, dists, imt, stddev_types)
if imt == PGA():
freq = 50.0
elif imt == PGV():
freq = 2.0
else:
freq = 1.0 / imt.period
x1 = np.min([-0.18 + 0.17 * np.log10(freq), 0])
... | Modification of the original base class adjusted for application to the Hawaii region as described in: Atkinson, G. M. (2010) 'Ground-Motion Prediction Equations for Hawaii from a Referenced Empirical Approach", Bulletin of the Seismological Society of America, Vol. 100, No. 2, pp. 751–761 | Atkinson2010Hawaii | [
"BSD-3-Clause",
"AGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Atkinson2010Hawaii:
"""Modification of the original base class adjusted for application to the Hawaii region as described in: Atkinson, G. M. (2010) 'Ground-Motion Prediction Equations for Hawaii from a Referenced Empirical Approach", Bulletin of the Seismological Society of America, Vol. 100, No... | stack_v2_sparse_classes_10k_train_001110 | 18,299 | permissive | [
{
"docstring": "Using a frequency dependent correction for the mean ground motion. Standard deviation is fixed.",
"name": "get_mean_and_stddevs",
"signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)"
},
{
"docstring": "Return total standard deviation.",
"name": ... | 2 | null | Implement the Python class `Atkinson2010Hawaii` described below.
Class description:
Modification of the original base class adjusted for application to the Hawaii region as described in: Atkinson, G. M. (2010) 'Ground-Motion Prediction Equations for Hawaii from a Referenced Empirical Approach", Bulletin of the Seismol... | Implement the Python class `Atkinson2010Hawaii` described below.
Class description:
Modification of the original base class adjusted for application to the Hawaii region as described in: Atkinson, G. M. (2010) 'Ground-Motion Prediction Equations for Hawaii from a Referenced Empirical Approach", Bulletin of the Seismol... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class Atkinson2010Hawaii:
"""Modification of the original base class adjusted for application to the Hawaii region as described in: Atkinson, G. M. (2010) 'Ground-Motion Prediction Equations for Hawaii from a Referenced Empirical Approach", Bulletin of the Seismological Society of America, Vol. 100, No... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Atkinson2010Hawaii:
"""Modification of the original base class adjusted for application to the Hawaii region as described in: Atkinson, G. M. (2010) 'Ground-Motion Prediction Equations for Hawaii from a Referenced Empirical Approach", Bulletin of the Seismological Society of America, Vol. 100, No. 2, pp. 751–... | the_stack_v2_python_sparse | openquake/hazardlib/gsim/boore_atkinson_2008.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
189c763023eca6be54ac3d713a99b6a0b0e2142c | [
"from yahoo_finance import Share\nself._name = name\nself._symbol = symbol\nself.state = None\nself.price_change = None\nself.price_open = None\nself.prev_close = None\nself.stock = Share(symbol)",
"self.stock.refresh()\nself.state = self.stock.get_price()\nself.price_change = self.stock.get_change()\nself.price_... | <|body_start_0|>
from yahoo_finance import Share
self._name = name
self._symbol = symbol
self.state = None
self.price_change = None
self.price_open = None
self.prev_close = None
self.stock = Share(symbol)
<|end_body_0|>
<|body_start_1|>
self.stock... | Get data from Yahoo Finance. | YahooFinanceData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YahooFinanceData:
"""Get data from Yahoo Finance."""
def __init__(self, name, symbol):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Get the latest data and updates the states."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_001111 | 3,588 | permissive | [
{
"docstring": "Initialize the data object.",
"name": "__init__",
"signature": "def __init__(self, name, symbol)"
},
{
"docstring": "Get the latest data and updates the states.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007323 | Implement the Python class `YahooFinanceData` described below.
Class description:
Get data from Yahoo Finance.
Method signatures and docstrings:
- def __init__(self, name, symbol): Initialize the data object.
- def update(self): Get the latest data and updates the states. | Implement the Python class `YahooFinanceData` described below.
Class description:
Get data from Yahoo Finance.
Method signatures and docstrings:
- def __init__(self, name, symbol): Initialize the data object.
- def update(self): Get the latest data and updates the states.
<|skeleton|>
class YahooFinanceData:
"""... | ca0e92aba83de2fd6cb1cc4d14f3b4471f17cf3d | <|skeleton|>
class YahooFinanceData:
"""Get data from Yahoo Finance."""
def __init__(self, name, symbol):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Get the latest data and updates the states."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class YahooFinanceData:
"""Get data from Yahoo Finance."""
def __init__(self, name, symbol):
"""Initialize the data object."""
from yahoo_finance import Share
self._name = name
self._symbol = symbol
self.state = None
self.price_change = None
self.price_op... | the_stack_v2_python_sparse | homeassistant/components/sensor/yahoo_finance.py | Smart-Torvy/torvy-home-assistant | train | 2 |
dba68d4485364fa26db1cbc8a52e061d388a8914 | [
"self._atoms = atoms\nself._max_executors = max_executors\nself._atom_time_map = atom_time_map\nself._project_directory = project_directory",
"try:\n total_estimated_runtime = self._set_expected_atom_times(self._atoms, self._atom_time_map, self._project_directory)\nexcept _AtomTimingDataError:\n grouper = A... | <|body_start_0|>
self._atoms = atoms
self._max_executors = max_executors
self._atom_time_map = atom_time_map
self._project_directory = project_directory
<|end_body_0|>
<|body_start_1|>
try:
total_estimated_runtime = self._set_expected_atom_times(self._atoms, self._at... | This class implements the algorithm to best split & group atoms based on historic time values. This algorithm is somewhat complicated, so I'm going to give a summary here. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Let N be the number of concurrent... | TimeBasedAtomGrouper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeBasedAtomGrouper:
"""This class implements the algorithm to best split & group atoms based on historic time values. This algorithm is somewhat complicated, so I'm going to give a summary here. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | stack_v2_sparse_classes_10k_train_001112 | 11,090 | permissive | [
{
"docstring": ":param atoms: the list of atoms for this build :type atoms: list[app.master.atom.Atom] :param max_executors: the maximum number of executors for this build :type max_executors: int :param atom_time_map: a dictionary containing the historic times for atoms for this particular job :type atom_time_... | 4 | stack_v2_sparse_classes_30k_val_000408 | Implement the Python class `TimeBasedAtomGrouper` described below.
Class description:
This class implements the algorithm to best split & group atoms based on historic time values. This algorithm is somewhat complicated, so I'm going to give a summary here. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | Implement the Python class `TimeBasedAtomGrouper` described below.
Class description:
This class implements the algorithm to best split & group atoms based on historic time values. This algorithm is somewhat complicated, so I'm going to give a summary here. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | 55d18016f2c7d2dbb8aec5879459cae654edb045 | <|skeleton|>
class TimeBasedAtomGrouper:
"""This class implements the algorithm to best split & group atoms based on historic time values. This algorithm is somewhat complicated, so I'm going to give a summary here. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TimeBasedAtomGrouper:
"""This class implements the algorithm to best split & group atoms based on historic time values. This algorithm is somewhat complicated, so I'm going to give a summary here. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | the_stack_v2_python_sparse | app/master/time_based_atom_grouper.py | box/ClusterRunner | train | 168 |
04196ffd985a957a79ac589bcef4b42d2e871035 | [
"self._attr_name = f'{client_name} {sensor_type.name}'\nself.type = sensor_type.key\nself.api = api\nself.entity_description = sensor_type",
"try:\n self.api.update()\nexcept requests.exceptions.ConnectionError:\n return\nif self.api.status is None:\n _LOGGER.debug('Update of %s requested, but no status ... | <|body_start_0|>
self._attr_name = f'{client_name} {sensor_type.name}'
self.type = sensor_type.key
self.api = api
self.entity_description = sensor_type
<|end_body_0|>
<|body_start_1|>
try:
self.api.update()
except requests.exceptions.ConnectionError:
... | Representation of a pyLoad sensor. | PyLoadSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyLoadSensor:
"""Representation of a pyLoad sensor."""
def __init__(self, api: PyLoadAPI, sensor_type: SensorEntityDescription, client_name) -> None:
"""Initialize a new pyLoad sensor."""
<|body_0|>
def update(self) -> None:
"""Update state of sensor."""
... | stack_v2_sparse_classes_10k_train_001113 | 5,310 | permissive | [
{
"docstring": "Initialize a new pyLoad sensor.",
"name": "__init__",
"signature": "def __init__(self, api: PyLoadAPI, sensor_type: SensorEntityDescription, client_name) -> None"
},
{
"docstring": "Update state of sensor.",
"name": "update",
"signature": "def update(self) -> None"
}
] | 2 | null | Implement the Python class `PyLoadSensor` described below.
Class description:
Representation of a pyLoad sensor.
Method signatures and docstrings:
- def __init__(self, api: PyLoadAPI, sensor_type: SensorEntityDescription, client_name) -> None: Initialize a new pyLoad sensor.
- def update(self) -> None: Update state o... | Implement the Python class `PyLoadSensor` described below.
Class description:
Representation of a pyLoad sensor.
Method signatures and docstrings:
- def __init__(self, api: PyLoadAPI, sensor_type: SensorEntityDescription, client_name) -> None: Initialize a new pyLoad sensor.
- def update(self) -> None: Update state o... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class PyLoadSensor:
"""Representation of a pyLoad sensor."""
def __init__(self, api: PyLoadAPI, sensor_type: SensorEntityDescription, client_name) -> None:
"""Initialize a new pyLoad sensor."""
<|body_0|>
def update(self) -> None:
"""Update state of sensor."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PyLoadSensor:
"""Representation of a pyLoad sensor."""
def __init__(self, api: PyLoadAPI, sensor_type: SensorEntityDescription, client_name) -> None:
"""Initialize a new pyLoad sensor."""
self._attr_name = f'{client_name} {sensor_type.name}'
self.type = sensor_type.key
sel... | the_stack_v2_python_sparse | homeassistant/components/pyload/sensor.py | home-assistant/core | train | 35,501 |
bdc6963a4cd8a0dce0b434bcbd93fb72337706ff | [
"if isinstance(dataset, lgb.Dataset):\n x = LGBMUtils.to_array(dataset=dataset.data)\n if dataset.label is None:\n return x\n y = LGBMUtils.to_array(dataset=dataset.label)\n return LGBMUtils.to_array(LGBMUtils.concatenate_x_y(x=x, y=y)[0])\ntry:\n return MLUtils.to_array(dataset=dataset)\nexce... | <|body_start_0|>
if isinstance(dataset, lgb.Dataset):
x = LGBMUtils.to_array(dataset=dataset.data)
if dataset.label is None:
return x
y = LGBMUtils.to_array(dataset=dataset.label)
return LGBMUtils.to_array(LGBMUtils.concatenate_x_y(x=x, y=y)[0])
... | Utilities functions for the LightGBM framework. | LGBMUtils | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LGBMUtils:
"""Utilities functions for the LightGBM framework."""
def to_array(dataset: LGBMTypes.DatasetType) -> np.ndarray:
"""Convert the given dataset to np.ndarray. :param dataset: The dataset to convert. Must be one of {lgb.Dataset, pd.DataFrame, pd.Series, scipy.sparse.base.spm... | stack_v2_sparse_classes_10k_train_001114 | 8,278 | permissive | [
{
"docstring": "Convert the given dataset to np.ndarray. :param dataset: The dataset to convert. Must be one of {lgb.Dataset, pd.DataFrame, pd.Series, scipy.sparse.base.spmatrix, list, tuple, dict}. :return: The dataset as a ndarray. :raise MLRunInvalidArgumentError: If the dataset type is not supported.",
... | 3 | stack_v2_sparse_classes_30k_train_006075 | Implement the Python class `LGBMUtils` described below.
Class description:
Utilities functions for the LightGBM framework.
Method signatures and docstrings:
- def to_array(dataset: LGBMTypes.DatasetType) -> np.ndarray: Convert the given dataset to np.ndarray. :param dataset: The dataset to convert. Must be one of {lg... | Implement the Python class `LGBMUtils` described below.
Class description:
Utilities functions for the LightGBM framework.
Method signatures and docstrings:
- def to_array(dataset: LGBMTypes.DatasetType) -> np.ndarray: Convert the given dataset to np.ndarray. :param dataset: The dataset to convert. Must be one of {lg... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class LGBMUtils:
"""Utilities functions for the LightGBM framework."""
def to_array(dataset: LGBMTypes.DatasetType) -> np.ndarray:
"""Convert the given dataset to np.ndarray. :param dataset: The dataset to convert. Must be one of {lgb.Dataset, pd.DataFrame, pd.Series, scipy.sparse.base.spm... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LGBMUtils:
"""Utilities functions for the LightGBM framework."""
def to_array(dataset: LGBMTypes.DatasetType) -> np.ndarray:
"""Convert the given dataset to np.ndarray. :param dataset: The dataset to convert. Must be one of {lgb.Dataset, pd.DataFrame, pd.Series, scipy.sparse.base.spmatrix, list, ... | the_stack_v2_python_sparse | mlrun/frameworks/lgbm/utils.py | mlrun/mlrun | train | 1,093 |
deb6f550e5ad9fbe2611a40371aeace4074f907d | [
"self.n, self.m = data.shape\nself.shmem_data = mp.RawArray(ctypes.c_double, self.n * self.m)\n_data = shmem_as_ndarray(self.shmem_data).reshape((self.n, self.m))\n_data[:, :] = data\nself.leafsize = leafsize\nself._nprocs = nprocs\nself._chunk = chunk\nself._schedule = schedule",
"nx = x.shape[0]\nshmem_x = mp.R... | <|body_start_0|>
self.n, self.m = data.shape
self.shmem_data = mp.RawArray(ctypes.c_double, self.n * self.m)
_data = shmem_as_ndarray(self.shmem_data).reshape((self.n, self.m))
_data[:, :] = data
self.leafsize = leafsize
self._nprocs = nprocs
self._chunk = chunk
... | Multiprocessing cKDTree subclass, shared memory | cKDTree_MP | [
"GPL-2.0-only",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"LicenseRef-scancode-mit-old-style",
"dtoa",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain-disclaimer",
"Zlib",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-lic... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cKDTree_MP:
"""Multiprocessing cKDTree subclass, shared memory"""
def __init__(self, data, leafsize=10, nprocs=2, chunk=None, schedule='guided'):
"""Same as cKDTree.__init__ except that an internal copy of data to shared memory is made. Extra keyword arguments: chunk : Minimum chunk ... | stack_v2_sparse_classes_10k_train_001115 | 10,163 | permissive | [
{
"docstring": "Same as cKDTree.__init__ except that an internal copy of data to shared memory is made. Extra keyword arguments: chunk : Minimum chunk size for the load balancer. schedule: Strategy for balancing work load ('static', 'dynamic' or 'guided').",
"name": "__init__",
"signature": "def __init_... | 2 | stack_v2_sparse_classes_30k_train_001355 | Implement the Python class `cKDTree_MP` described below.
Class description:
Multiprocessing cKDTree subclass, shared memory
Method signatures and docstrings:
- def __init__(self, data, leafsize=10, nprocs=2, chunk=None, schedule='guided'): Same as cKDTree.__init__ except that an internal copy of data to shared memory... | Implement the Python class `cKDTree_MP` described below.
Class description:
Multiprocessing cKDTree subclass, shared memory
Method signatures and docstrings:
- def __init__(self, data, leafsize=10, nprocs=2, chunk=None, schedule='guided'): Same as cKDTree.__init__ except that an internal copy of data to shared memory... | 930d26886fdf8591b51da9d53e2aca743bf128ba | <|skeleton|>
class cKDTree_MP:
"""Multiprocessing cKDTree subclass, shared memory"""
def __init__(self, data, leafsize=10, nprocs=2, chunk=None, schedule='guided'):
"""Same as cKDTree.__init__ except that an internal copy of data to shared memory is made. Extra keyword arguments: chunk : Minimum chunk ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class cKDTree_MP:
"""Multiprocessing cKDTree subclass, shared memory"""
def __init__(self, data, leafsize=10, nprocs=2, chunk=None, schedule='guided'):
"""Same as cKDTree.__init__ except that an internal copy of data to shared memory is made. Extra keyword arguments: chunk : Minimum chunk size for the ... | the_stack_v2_python_sparse | 3/amd64/envs/navigator/lib/python3.6/site-packages/pyresample/_spatial_mp.py | DFO-Ocean-Navigator/navigator-toolchain | train | 0 |
156b8e8d0514351b9a8cfa17116d8c256e5a9a78 | [
"num_of_samples = container.shape[0]\nif 12 <= num_of_samples < 20:\n window_size = 3\nelif 20 <= num_of_samples < 50:\n window_size = 6\nelif 50 <= num_of_samples < 120:\n window_size = 12\nelif 120 <= num_of_samples < 300:\n window_size = 30\nelif 300 <= num_of_samples < 500:\n window_size = 75\nel... | <|body_start_0|>
num_of_samples = container.shape[0]
if 12 <= num_of_samples < 20:
window_size = 3
elif 20 <= num_of_samples < 50:
window_size = 6
elif 50 <= num_of_samples < 120:
window_size = 12
elif 120 <= num_of_samples < 300:
w... | Class for estimating parameters of rolling windows. | RollingWindowsEstimator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RollingWindowsEstimator:
"""Class for estimating parameters of rolling windows."""
def estimate_rolling_window_size(cls, container: Union[QFDataFrame, QFSeries]) -> int:
"""Estimates the size of the rolling window based on the number of samples. Parameters ---------- container contai... | stack_v2_sparse_classes_10k_train_001116 | 2,801 | permissive | [
{
"docstring": "Estimates the size of the rolling window based on the number of samples. Parameters ---------- container container with data analysed using rolling window Returns ------- window_size the calculated size of the rolling window",
"name": "estimate_rolling_window_size",
"signature": "def est... | 2 | null | Implement the Python class `RollingWindowsEstimator` described below.
Class description:
Class for estimating parameters of rolling windows.
Method signatures and docstrings:
- def estimate_rolling_window_size(cls, container: Union[QFDataFrame, QFSeries]) -> int: Estimates the size of the rolling window based on the ... | Implement the Python class `RollingWindowsEstimator` described below.
Class description:
Class for estimating parameters of rolling windows.
Method signatures and docstrings:
- def estimate_rolling_window_size(cls, container: Union[QFDataFrame, QFSeries]) -> int: Estimates the size of the rolling window based on the ... | f707e51bc2ff45f6e46dcdd24d59d83ce7dc4f94 | <|skeleton|>
class RollingWindowsEstimator:
"""Class for estimating parameters of rolling windows."""
def estimate_rolling_window_size(cls, container: Union[QFDataFrame, QFSeries]) -> int:
"""Estimates the size of the rolling window based on the number of samples. Parameters ---------- container contai... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RollingWindowsEstimator:
"""Class for estimating parameters of rolling windows."""
def estimate_rolling_window_size(cls, container: Union[QFDataFrame, QFSeries]) -> int:
"""Estimates the size of the rolling window based on the number of samples. Parameters ---------- container container with data... | the_stack_v2_python_sparse | qf_lib/common/utils/factorization/data_models/rolling_window_estimation.py | quarkfin/qf-lib | train | 379 |
202fdefc51bec7b3d58f249785e761d1850abed4 | [
"self.plaintext = plaintext\nself.key = '6440777308024991'\nself.info = {}",
"plaintext_bytes = self.plaintext.encode('utf-8')\nkey_bytes = self.key.encode('utf-8')\ncipher_encrypt = AES.new(key_bytes, AES.MODE_CFB)\niv_bytes = cipher_encrypt.iv\nself.init_vector = b64encode(iv_bytes).decode('utf-8')\ncipher_text... | <|body_start_0|>
self.plaintext = plaintext
self.key = '6440777308024991'
self.info = {}
<|end_body_0|>
<|body_start_1|>
plaintext_bytes = self.plaintext.encode('utf-8')
key_bytes = self.key.encode('utf-8')
cipher_encrypt = AES.new(key_bytes, AES.MODE_CFB)
iv_byt... | A class for encrypting plaintext passed in via user input | password_encrypt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class password_encrypt:
"""A class for encrypting plaintext passed in via user input"""
def __init__(self, plaintext='', key=''):
"""init method for password encryption class"""
<|body_0|>
def encryptPassword(self):
"""encrypt user inputted plaintext"""
<|body_... | stack_v2_sparse_classes_10k_train_001117 | 2,888 | no_license | [
{
"docstring": "init method for password encryption class",
"name": "__init__",
"signature": "def __init__(self, plaintext='', key='')"
},
{
"docstring": "encrypt user inputted plaintext",
"name": "encryptPassword",
"signature": "def encryptPassword(self)"
},
{
"docstring": "Save... | 3 | stack_v2_sparse_classes_30k_train_005335 | Implement the Python class `password_encrypt` described below.
Class description:
A class for encrypting plaintext passed in via user input
Method signatures and docstrings:
- def __init__(self, plaintext='', key=''): init method for password encryption class
- def encryptPassword(self): encrypt user inputted plainte... | Implement the Python class `password_encrypt` described below.
Class description:
A class for encrypting plaintext passed in via user input
Method signatures and docstrings:
- def __init__(self, plaintext='', key=''): init method for password encryption class
- def encryptPassword(self): encrypt user inputted plainte... | 7a331478914c6cafd79d8b3c6b18afb95429d52f | <|skeleton|>
class password_encrypt:
"""A class for encrypting plaintext passed in via user input"""
def __init__(self, plaintext='', key=''):
"""init method for password encryption class"""
<|body_0|>
def encryptPassword(self):
"""encrypt user inputted plaintext"""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class password_encrypt:
"""A class for encrypting plaintext passed in via user input"""
def __init__(self, plaintext='', key=''):
"""init method for password encryption class"""
self.plaintext = plaintext
self.key = '6440777308024991'
self.info = {}
def encryptPassword(self... | the_stack_v2_python_sparse | pycryptodome_assignment/password_encrypt.py | sbrohl3/projects | train | 0 |
8491149bed629fec1046aea3520efb29dc71ec5d | [
"issue_id = mr.GetPositiveIntParam('issue_id')\nif not issue_id:\n return {'params': {}, 'notified': [], 'message': 'Cannot proceed without a valid issue ID.'}\ncommenter_id = mr.GetPositiveIntParam('commenter_id')\nomit_ids = [commenter_id]\nhostport = mr.GetParam('hostport')\ndelta_blocker_iids = mr.GetIntList... | <|body_start_0|>
issue_id = mr.GetPositiveIntParam('issue_id')
if not issue_id:
return {'params': {}, 'notified': [], 'message': 'Cannot proceed without a valid issue ID.'}
commenter_id = mr.GetPositiveIntParam('commenter_id')
omit_ids = [commenter_id]
hostport = mr.G... | JSON servlet that notifies appropriate users after a blocking change. | NotifyBlockingChangeTask | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotifyBlockingChangeTask:
"""JSON servlet that notifies appropriate users after a blocking change."""
def HandleRequest(self, mr):
"""Process the task to notify users after an issue blocking change. Args: mr: common information parsed from the HTTP request. Returns: Results dictionar... | stack_v2_sparse_classes_10k_train_001118 | 41,907 | permissive | [
{
"docstring": "Process the task to notify users after an issue blocking change. Args: mr: common information parsed from the HTTP request. Returns: Results dictionary in JSON format which is useful just for debugging. The main goal is the side-effect of sending emails.",
"name": "HandleRequest",
"signa... | 2 | null | Implement the Python class `NotifyBlockingChangeTask` described below.
Class description:
JSON servlet that notifies appropriate users after a blocking change.
Method signatures and docstrings:
- def HandleRequest(self, mr): Process the task to notify users after an issue blocking change. Args: mr: common information... | Implement the Python class `NotifyBlockingChangeTask` described below.
Class description:
JSON servlet that notifies appropriate users after a blocking change.
Method signatures and docstrings:
- def HandleRequest(self, mr): Process the task to notify users after an issue blocking change. Args: mr: common information... | b5d4783f99461438ca9e6a477535617fadab6ba3 | <|skeleton|>
class NotifyBlockingChangeTask:
"""JSON servlet that notifies appropriate users after a blocking change."""
def HandleRequest(self, mr):
"""Process the task to notify users after an issue blocking change. Args: mr: common information parsed from the HTTP request. Returns: Results dictionar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NotifyBlockingChangeTask:
"""JSON servlet that notifies appropriate users after a blocking change."""
def HandleRequest(self, mr):
"""Process the task to notify users after an issue blocking change. Args: mr: common information parsed from the HTTP request. Returns: Results dictionary in JSON for... | the_stack_v2_python_sparse | appengine/monorail/features/notify.py | xinghun61/infra | train | 2 |
5c6395936796ea51dc5732efb296c5de2ccee48d | [
"gtk.ComboBoxEntry.__init__(self)\nself.props.width_request = width\nself.props.height_request = height\n_list = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)\nself.set_model(_list)\nself.set_text_column(0)\nself.set_tooltip_markup(tooltip)\nself.show()",
"_return = False\n_model = ... | <|body_start_0|>
gtk.ComboBoxEntry.__init__(self)
self.props.width_request = width
self.props.height_request = height
_list = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
self.set_model(_list)
self.set_text_column(0)
self.set_toolti... | This is the RAMSTK ComboBox with Entry class. | RAMSTKComboBoxEntry | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RAMSTKComboBoxEntry:
"""This is the RAMSTK ComboBox with Entry class."""
def __init__(self, width=200, height=30, tooltip='RAMSTK WARNING: Missing tooltip. Please register an Enhancement type bug.'):
"""Create RAMSTK Combo widgets. :keyword int width: width of the gtk.ComboBox() wid... | stack_v2_sparse_classes_10k_train_001119 | 6,449 | permissive | [
{
"docstring": "Create RAMSTK Combo widgets. :keyword int width: width of the gtk.ComboBox() widget. Default is 200. :keyword int height: height of the gtk.ComboBox() widget. Default is 30. :keyword bool simple: indicates whether the gtk.ComboBox() contains only the display information or if there is additional... | 2 | stack_v2_sparse_classes_30k_train_006728 | Implement the Python class `RAMSTKComboBoxEntry` described below.
Class description:
This is the RAMSTK ComboBox with Entry class.
Method signatures and docstrings:
- def __init__(self, width=200, height=30, tooltip='RAMSTK WARNING: Missing tooltip. Please register an Enhancement type bug.'): Create RAMSTK Combo wid... | Implement the Python class `RAMSTKComboBoxEntry` described below.
Class description:
This is the RAMSTK ComboBox with Entry class.
Method signatures and docstrings:
- def __init__(self, width=200, height=30, tooltip='RAMSTK WARNING: Missing tooltip. Please register an Enhancement type bug.'): Create RAMSTK Combo wid... | 488ffed8b842399ddcae93007de6c6f1dda23d05 | <|skeleton|>
class RAMSTKComboBoxEntry:
"""This is the RAMSTK ComboBox with Entry class."""
def __init__(self, width=200, height=30, tooltip='RAMSTK WARNING: Missing tooltip. Please register an Enhancement type bug.'):
"""Create RAMSTK Combo widgets. :keyword int width: width of the gtk.ComboBox() wid... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RAMSTKComboBoxEntry:
"""This is the RAMSTK ComboBox with Entry class."""
def __init__(self, width=200, height=30, tooltip='RAMSTK WARNING: Missing tooltip. Please register an Enhancement type bug.'):
"""Create RAMSTK Combo widgets. :keyword int width: width of the gtk.ComboBox() widget. Default ... | the_stack_v2_python_sparse | src/ramstk/gui/gtk/ramstk/Combo.py | JmiXIII/ramstk | train | 0 |
b463872977a62b61f4a49818ff1fb0cee388d0b2 | [
"super().__init__(model_path, device, ie_core, num_requests, 'Person Detection', output_shape)\n_, _, h, w = self.input_size\nself.input_height = h\nself.input_width = w\nself.last_scales = None",
"initial_h, initial_w = frame.shape[:2]\nscale_h, scale_w = (initial_h / float(self.input_height), initial_w / float(... | <|body_start_0|>
super().__init__(model_path, device, ie_core, num_requests, 'Person Detection', output_shape)
_, _, h, w = self.input_size
self.input_height = h
self.input_width = w
self.last_scales = None
<|end_body_0|>
<|body_start_1|>
initial_h, initial_w = frame.sha... | Class that allows worknig with person detectpr models. | PersonDetector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonDetector:
"""Class that allows worknig with person detectpr models."""
def __init__(self, model_path, device, ie_core, num_requests, output_shape=None):
"""Constructor"""
<|body_0|>
def _prepare_frame(self, frame):
"""Converts input image according model re... | stack_v2_sparse_classes_10k_train_001120 | 2,799 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, model_path, device, ie_core, num_requests, output_shape=None)"
},
{
"docstring": "Converts input image according model requirements",
"name": "_prepare_frame",
"signature": "def _prepare_frame(self, frame)... | 5 | stack_v2_sparse_classes_30k_train_006278 | Implement the Python class `PersonDetector` described below.
Class description:
Class that allows worknig with person detectpr models.
Method signatures and docstrings:
- def __init__(self, model_path, device, ie_core, num_requests, output_shape=None): Constructor
- def _prepare_frame(self, frame): Converts input ima... | Implement the Python class `PersonDetector` described below.
Class description:
Class that allows worknig with person detectpr models.
Method signatures and docstrings:
- def __init__(self, model_path, device, ie_core, num_requests, output_shape=None): Constructor
- def _prepare_frame(self, frame): Converts input ima... | 7929adbe91e9cfe8dc5dc1daad5ae7392f9719a0 | <|skeleton|>
class PersonDetector:
"""Class that allows worknig with person detectpr models."""
def __init__(self, model_path, device, ie_core, num_requests, output_shape=None):
"""Constructor"""
<|body_0|>
def _prepare_frame(self, frame):
"""Converts input image according model re... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PersonDetector:
"""Class that allows worknig with person detectpr models."""
def __init__(self, model_path, device, ie_core, num_requests, output_shape=None):
"""Constructor"""
super().__init__(model_path, device, ie_core, num_requests, 'Person Detection', output_shape)
_, _, h, w... | the_stack_v2_python_sparse | demos/gesture_recognition_demo/python/gesture_recognition_demo/person_detector.py | openvinotoolkit/open_model_zoo | train | 1,712 |
b02ae622b23c37bc236e4dbf86e6838c7678f4fa | [
"base_rest = BaseRestApi()\nusers = users if isinstance(users, list) else [users]\nresult = base_rest.request('POST', RC.REST_OBJ_USER, RC.USER_CREATE_LIST, params=users)\nreturn result['status_code']",
"base_rest = BaseRestApi()\nresult = base_rest.request('GET', RC.REST_OBJ_USER, user_name)\nif expected_error:\... | <|body_start_0|>
base_rest = BaseRestApi()
users = users if isinstance(users, list) else [users]
result = base_rest.request('POST', RC.REST_OBJ_USER, RC.USER_CREATE_LIST, params=users)
return result['status_code']
<|end_body_0|>
<|body_start_1|>
base_rest = BaseRestApi()
... | Provide Rest API for User rest object | UserRest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRest:
"""Provide Rest API for User rest object"""
def create(users):
"""Create user or users :param users: list of users bodies :type users: list :returns: status code :type: int"""
<|body_0|>
def get(user_name, expected_error=False):
"""Get user entry :param... | stack_v2_sparse_classes_10k_train_001121 | 1,981 | no_license | [
{
"docstring": "Create user or users :param users: list of users bodies :type users: list :returns: status code :type: int",
"name": "create",
"signature": "def create(users)"
},
{
"docstring": "Get user entry :param user_name: user name :type user_name: str :param expected_error: :type expected... | 4 | stack_v2_sparse_classes_30k_train_001835 | Implement the Python class `UserRest` described below.
Class description:
Provide Rest API for User rest object
Method signatures and docstrings:
- def create(users): Create user or users :param users: list of users bodies :type users: list :returns: status code :type: int
- def get(user_name, expected_error=False): ... | Implement the Python class `UserRest` described below.
Class description:
Provide Rest API for User rest object
Method signatures and docstrings:
- def create(users): Create user or users :param users: list of users bodies :type users: list :returns: status code :type: int
- def get(user_name, expected_error=False): ... | 341cad07bf93fdbb8b353ce98315051f773202f5 | <|skeleton|>
class UserRest:
"""Provide Rest API for User rest object"""
def create(users):
"""Create user or users :param users: list of users bodies :type users: list :returns: status code :type: int"""
<|body_0|>
def get(user_name, expected_error=False):
"""Get user entry :param... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserRest:
"""Provide Rest API for User rest object"""
def create(users):
"""Create user or users :param users: list of users bodies :type users: list :returns: status code :type: int"""
base_rest = BaseRestApi()
users = users if isinstance(users, list) else [users]
result ... | the_stack_v2_python_sparse | modules/rest_functions/user_rest.py | Pir-4/CloudmoreTask | train | 0 |
1f149501ee1f991a2fe0e31947b627d399d8a74a | [
"self.distance_x = distance_x\nself.eps = eps\nself.lr_lamb = lr_lamb\nself.lr_param = lr_param\nself.auditor_nsteps = auditor_nsteps\nself.auditor_lr = auditor_lr\nsuper().__init__(module=module, criterion=criterion, regression=regression, **kwargs)",
"self.initialize_criterion()\nkwargs = self.get_params_for('m... | <|body_start_0|>
self.distance_x = distance_x
self.eps = eps
self.lr_lamb = lr_lamb
self.lr_param = lr_param
self.auditor_nsteps = auditor_nsteps
self.auditor_lr = auditor_lr
super().__init__(module=module, criterion=criterion, regression=regression, **kwargs)
<|e... | Sensitive Subspace Robustness (SenSR). SenSR is an in-processing method for individual fairness which enforces performance invariance under certain sensitive perturbations to the input [#yurochkin19]_. References: .. [#yurochkin19] `M. Yurochkin, A. Bower, and Y. Sun, "Training individually fair ML models with sensitiv... | SenSR | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SenSR:
"""Sensitive Subspace Robustness (SenSR). SenSR is an in-processing method for individual fairness which enforces performance invariance under certain sensitive perturbations to the input [#yurochkin19]_. References: .. [#yurochkin19] `M. Yurochkin, A. Bower, and Y. Sun, "Training individu... | stack_v2_sparse_classes_10k_train_001122 | 15,710 | permissive | [
{
"docstring": "Args: module (torch.nn.Module): Network architecture. criterion (torch.nn.Module): Loss function. distance_x (inFairness.distances.Distance): Distance metric in the input space. eps (float): :math:`\\\\epsilon` parameter in the SenSR algorithm. lr_lamb (float): :math:`\\\\lambda` parameter in th... | 2 | stack_v2_sparse_classes_30k_train_005689 | Implement the Python class `SenSR` described below.
Class description:
Sensitive Subspace Robustness (SenSR). SenSR is an in-processing method for individual fairness which enforces performance invariance under certain sensitive perturbations to the input [#yurochkin19]_. References: .. [#yurochkin19] `M. Yurochkin, A... | Implement the Python class `SenSR` described below.
Class description:
Sensitive Subspace Robustness (SenSR). SenSR is an in-processing method for individual fairness which enforces performance invariance under certain sensitive perturbations to the input [#yurochkin19]_. References: .. [#yurochkin19] `M. Yurochkin, A... | 6f9972e4a7dbca2402f29b86ea67889143dbeb3e | <|skeleton|>
class SenSR:
"""Sensitive Subspace Robustness (SenSR). SenSR is an in-processing method for individual fairness which enforces performance invariance under certain sensitive perturbations to the input [#yurochkin19]_. References: .. [#yurochkin19] `M. Yurochkin, A. Bower, and Y. Sun, "Training individu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SenSR:
"""Sensitive Subspace Robustness (SenSR). SenSR is an in-processing method for individual fairness which enforces performance invariance under certain sensitive perturbations to the input [#yurochkin19]_. References: .. [#yurochkin19] `M. Yurochkin, A. Bower, and Y. Sun, "Training individually fair ML ... | the_stack_v2_python_sparse | aif360/sklearn/inprocessing/infairness.py | Trusted-AI/AIF360 | train | 1,157 |
5c144fc89b07f85459d6b92764fb9c0112265826 | [
"self.name = name\nself.dictionary = Dictionary()\nself.res_random = RandomResponder('Random', self.dictionary)\nself.res_what = RepeatResponder('Repeat', self.dictionary)\nself.res_pattern = PatternResponder('Pattern', self.dictionary)",
"x = random.randint(0, 100)\nif x <= 60:\n self.responder = self.res_pat... | <|body_start_0|>
self.name = name
self.dictionary = Dictionary()
self.res_random = RandomResponder('Random', self.dictionary)
self.res_what = RepeatResponder('Repeat', self.dictionary)
self.res_pattern = PatternResponder('Pattern', self.dictionary)
<|end_body_0|>
<|body_start_1|... | ピティナの本体クラス | Ptna | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ptna:
"""ピティナの本体クラス"""
def __init__(self, name):
"""Ptnaオブジェクトの名前をnameに格納 応答オブジェクトをランダムに生成してresponderに格納 @param name Ptnaオブジェクトの名前"""
<|body_0|>
def dialogue(self, input):
"""応答オブジェクトのresponse()を呼び出して 応答文字列を取得する @param input ユーザーによって入力された文字列 戻り値 応答文字列"""
... | stack_v2_sparse_classes_10k_train_001123 | 1,559 | no_license | [
{
"docstring": "Ptnaオブジェクトの名前をnameに格納 応答オブジェクトをランダムに生成してresponderに格納 @param name Ptnaオブジェクトの名前",
"name": "__init__",
"signature": "def __init__(self, name)"
},
{
"docstring": "応答オブジェクトのresponse()を呼び出して 応答文字列を取得する @param input ユーザーによって入力された文字列 戻り値 応答文字列",
"name": "dialogue",
"signature": ... | 2 | null | Implement the Python class `Ptna` described below.
Class description:
ピティナの本体クラス
Method signatures and docstrings:
- def __init__(self, name): Ptnaオブジェクトの名前をnameに格納 応答オブジェクトをランダムに生成してresponderに格納 @param name Ptnaオブジェクトの名前
- def dialogue(self, input): 応答オブジェクトのresponse()を呼び出して 応答文字列を取得する @param input ユーザーによって入力された文字列 ... | Implement the Python class `Ptna` described below.
Class description:
ピティナの本体クラス
Method signatures and docstrings:
- def __init__(self, name): Ptnaオブジェクトの名前をnameに格納 応答オブジェクトをランダムに生成してresponderに格納 @param name Ptnaオブジェクトの名前
- def dialogue(self, input): 応答オブジェクトのresponse()を呼び出して 応答文字列を取得する @param input ユーザーによって入力された文字列 ... | 26126c02cfa0dc4c0db726f2f2cabb162511a5b5 | <|skeleton|>
class Ptna:
"""ピティナの本体クラス"""
def __init__(self, name):
"""Ptnaオブジェクトの名前をnameに格納 応答オブジェクトをランダムに生成してresponderに格納 @param name Ptnaオブジェクトの名前"""
<|body_0|>
def dialogue(self, input):
"""応答オブジェクトのresponse()を呼び出して 応答文字列を取得する @param input ユーザーによって入力された文字列 戻り値 応答文字列"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Ptna:
"""ピティナの本体クラス"""
def __init__(self, name):
"""Ptnaオブジェクトの名前をnameに格納 応答オブジェクトをランダムに生成してresponderに格納 @param name Ptnaオブジェクトの名前"""
self.name = name
self.dictionary = Dictionary()
self.res_random = RandomResponder('Random', self.dictionary)
self.res_what = Repeat... | the_stack_v2_python_sparse | normal/PythonAI/chap05/sec03/Ptna/ptna.py | munezou/PycharmProject | train | 2 |
bd0f1abfcf830758fb58ba5e12d93d44f79d7085 | [
"super().__init__()\npe = torch.zeros(max_len, d_model)\nposition = torch.arange(0.0, max_len).unsqueeze(1)\ndiv_term = torch.exp(torch.arange(0.0, d_model, 2) * -(math.log(10000.0) / d_model))\npe[:, 0::2] = torch.sin(position * div_term)\npe[:, 1::2] = torch.cos(position * div_term)\npe = torch.cat((pe, torch.zer... | <|body_start_0|>
super().__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0.0, max_len).unsqueeze(1)
div_term = torch.exp(torch.arange(0.0, d_model, 2) * -(math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.... | Class implementing fixed positional encodings. Fixed positional encodings up to max_len position are computed once during object construction. | FixedPositionalEncoding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixedPositionalEncoding:
"""Class implementing fixed positional encodings. Fixed positional encodings up to max_len position are computed once during object construction."""
def __init__(self, d_model: int, max_len=5000):
""":param d_model: dimensionality of the embeddings :param max... | stack_v2_sparse_classes_10k_train_001124 | 21,238 | no_license | [
{
"docstring": ":param d_model: dimensionality of the embeddings :param max_len: maximum length of the sequence",
"name": "__init__",
"signature": "def __init__(self, d_model: int, max_len=5000)"
},
{
"docstring": "Forward pass through the FixedPositionalEncoding. :param x: input of shape [batch... | 2 | null | Implement the Python class `FixedPositionalEncoding` described below.
Class description:
Class implementing fixed positional encodings. Fixed positional encodings up to max_len position are computed once during object construction.
Method signatures and docstrings:
- def __init__(self, d_model: int, max_len=5000): :p... | Implement the Python class `FixedPositionalEncoding` described below.
Class description:
Class implementing fixed positional encodings. Fixed positional encodings up to max_len position are computed once during object construction.
Method signatures and docstrings:
- def __init__(self, d_model: int, max_len=5000): :p... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class FixedPositionalEncoding:
"""Class implementing fixed positional encodings. Fixed positional encodings up to max_len position are computed once during object construction."""
def __init__(self, d_model: int, max_len=5000):
""":param d_model: dimensionality of the embeddings :param max... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FixedPositionalEncoding:
"""Class implementing fixed positional encodings. Fixed positional encodings up to max_len position are computed once during object construction."""
def __init__(self, d_model: int, max_len=5000):
""":param d_model: dimensionality of the embeddings :param max_len: maximum... | the_stack_v2_python_sparse | generated/test_allegro_allRank.py | jansel/pytorch-jit-paritybench | train | 35 |
2dc54fa465b4c299ac2d858e69f178c69b3aef25 | [
"self.heights = heights\nmin_ = 0\nmax_ = max((max(row) for row in heights)) - min((min(row) for row in heights))\nwhile min_ < max_:\n guess = (min_ + max_) // 2\n if self.verifyIsPossible(guess):\n max_ = guess\n else:\n min_ = guess + 1\nreturn max_",
"rec = [(0, 0)]\nattainable = set(re... | <|body_start_0|>
self.heights = heights
min_ = 0
max_ = max((max(row) for row in heights)) - min((min(row) for row in heights))
while min_ < max_:
guess = (min_ + max_) // 2
if self.verifyIsPossible(guess):
max_ = guess
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
"""Find the minimum effort required to get from top-left corner of heights to lower-right :param heights: rectangular-like map represented as list of lists :return: the minimum effort required Time complexity: O(mn *... | stack_v2_sparse_classes_10k_train_001125 | 4,330 | no_license | [
{
"docstring": "Find the minimum effort required to get from top-left corner of heights to lower-right :param heights: rectangular-like map represented as list of lists :return: the minimum effort required Time complexity: O(mn * log(var)), where the heights is m-by-n board and var is the spread of values in he... | 2 | stack_v2_sparse_classes_30k_train_006025 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumEffortPath(self, heights: List[List[int]]) -> int: Find the minimum effort required to get from top-left corner of heights to lower-right :param heights: rectangular-l... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumEffortPath(self, heights: List[List[int]]) -> int: Find the minimum effort required to get from top-left corner of heights to lower-right :param heights: rectangular-l... | ee8237b66975fb5584a3d68b311e762c0462c8aa | <|skeleton|>
class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
"""Find the minimum effort required to get from top-left corner of heights to lower-right :param heights: rectangular-like map represented as list of lists :return: the minimum effort required Time complexity: O(mn *... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
"""Find the minimum effort required to get from top-left corner of heights to lower-right :param heights: rectangular-like map represented as list of lists :return: the minimum effort required Time complexity: O(mn * log(var)), wh... | the_stack_v2_python_sparse | LC1631-Path-With-Minimum-Effort.py | kate-melnykova/LeetCode-solutions | train | 2 | |
b9b9c89c7b6bebe0f9a65395b49ce93366956486 | [
"file_offset = file_object.tell()\nif format_version == 1:\n data_type_map = self._GetDataTypeMap('recycle_bin_metadata_utf16le_string')\nelse:\n data_type_map = self._GetDataTypeMap('recycle_bin_metadata_utf16le_string_with_size')\ntry:\n original_filename, _ = self._ReadStructureFromFileObject(file_objec... | <|body_start_0|>
file_offset = file_object.tell()
if format_version == 1:
data_type_map = self._GetDataTypeMap('recycle_bin_metadata_utf16le_string')
else:
data_type_map = self._GetDataTypeMap('recycle_bin_metadata_utf16le_string_with_size')
try:
origi... | Parses the Windows $Recycle.Bin $I files. | WinRecycleBinParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WinRecycleBinParser:
"""Parses the Windows $Recycle.Bin $I files."""
def _ParseOriginalFilename(self, file_object, format_version):
"""Parses the original filename. Args: file_object (FileIO): file-like object. format_version (int): format version. Returns: str: filename or None on e... | stack_v2_sparse_classes_10k_train_001126 | 9,268 | permissive | [
{
"docstring": "Parses the original filename. Args: file_object (FileIO): file-like object. format_version (int): format version. Returns: str: filename or None on error. Raises: ParseError: if the original filename cannot be read.",
"name": "_ParseOriginalFilename",
"signature": "def _ParseOriginalFile... | 2 | null | Implement the Python class `WinRecycleBinParser` described below.
Class description:
Parses the Windows $Recycle.Bin $I files.
Method signatures and docstrings:
- def _ParseOriginalFilename(self, file_object, format_version): Parses the original filename. Args: file_object (FileIO): file-like object. format_version (... | Implement the Python class `WinRecycleBinParser` described below.
Class description:
Parses the Windows $Recycle.Bin $I files.
Method signatures and docstrings:
- def _ParseOriginalFilename(self, file_object, format_version): Parses the original filename. Args: file_object (FileIO): file-like object. format_version (... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class WinRecycleBinParser:
"""Parses the Windows $Recycle.Bin $I files."""
def _ParseOriginalFilename(self, file_object, format_version):
"""Parses the original filename. Args: file_object (FileIO): file-like object. format_version (int): format version. Returns: str: filename or None on e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WinRecycleBinParser:
"""Parses the Windows $Recycle.Bin $I files."""
def _ParseOriginalFilename(self, file_object, format_version):
"""Parses the original filename. Args: file_object (FileIO): file-like object. format_version (int): format version. Returns: str: filename or None on error. Raises:... | the_stack_v2_python_sparse | plaso/parsers/recycler.py | log2timeline/plaso | train | 1,506 |
393ce01e14959781ac450a66c8a6b22f6b364e59 | [
"x = str(x)\na = x[::-1]\nif x == a:\n return True\nelse:\n return False",
"if x < 0:\n return False\nelif x % 10 == 0 and x != 0:\n return False\nelse:\n revertedNumber = 0\n while x > revertedNumber:\n revertedNumber = revertedNumber * 10 + x % 10\n x /= 10\n return x == rever... | <|body_start_0|>
x = str(x)
a = x[::-1]
if x == a:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
if x < 0:
return False
elif x % 10 == 0 and x != 0:
return False
else:
revertedNumber = 0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindromeStr(self, x):
""":type x: int :rtype: bool"""
<|body_0|>
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
x = str(x)
a = x[::-1]
if x == a:
... | stack_v2_sparse_classes_10k_train_001127 | 1,925 | no_license | [
{
"docstring": ":type x: int :rtype: bool",
"name": "isPalindromeStr",
"signature": "def isPalindromeStr(self, x)"
},
{
"docstring": ":type x: int :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, x)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindromeStr(self, x): :type x: int :rtype: bool
- def isPalindrome(self, x): :type x: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindromeStr(self, x): :type x: int :rtype: bool
- def isPalindrome(self, x): :type x: int :rtype: bool
<|skeleton|>
class Solution:
def isPalindromeStr(self, x):
... | 3f7b2ea959308eb80f4c65be35aaeed666570f80 | <|skeleton|>
class Solution:
def isPalindromeStr(self, x):
""":type x: int :rtype: bool"""
<|body_0|>
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindromeStr(self, x):
""":type x: int :rtype: bool"""
x = str(x)
a = x[::-1]
if x == a:
return True
else:
return False
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
if x < 0:
return ... | the_stack_v2_python_sparse | 9.回文数.py | dxc19951001/Everyday_LeetCode | train | 1 | |
6886fba10bdf115c4faf2c56c6f7f24405dd76dc | [
"self.all_under_hierarchy = all_under_hierarchy\nself.compact_version = compact_version\nself.consecutive_failures = consecutive_failures\nself.environment = environment\nself.exclude_users_within_alert_threshold = exclude_users_within_alert_threshold\nself.group_by = group_by\nself.health_status = health_status\ns... | <|body_start_0|>
self.all_under_hierarchy = all_under_hierarchy
self.compact_version = compact_version
self.consecutive_failures = consecutive_failures
self.environment = environment
self.exclude_users_within_alert_threshold = exclude_users_within_alert_threshold
self.gro... | Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters' model. TODO: type description here. Attributes: all_under_hierarchy (bool): Specifies if subtenants of the given tenants should be considered for report generation. compact_version (string): Specifies the Cohe... | SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters:
"""Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters' model. TODO: type description here. Attributes: all_under_hierarchy (bool): Specifies if subten... | stack_v2_sparse_classes_10k_train_001128 | 8,990 | permissive | [
{
"docstring": "Constructor for the SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters class",
"name": "__init__",
"signature": "def __init__(self, all_under_hierarchy=None, compact_version=None, consecutive_failures=None, environment=None, exclude_users_within_alert_... | 2 | stack_v2_sparse_classes_30k_train_006534 | Implement the Python class `SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters` described below.
Class description:
Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters' model. TODO: type description here. Attributes: all_unde... | Implement the Python class `SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters` described below.
Class description:
Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters' model. TODO: type description here. Attributes: all_unde... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters:
"""Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters' model. TODO: type description here. Attributes: all_under_hierarchy (bool): Specifies if subten... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters:
"""Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters' model. TODO: type description here. Attributes: all_under_hierarchy (bool): Specifies if subtenants of the g... | the_stack_v2_python_sparse | cohesity_management_sdk/models/scheduler_proto_scheduler_job_schedule_job_parameters_report_job_parameter_report_parameters.py | cohesity/management-sdk-python | train | 24 |
00aebdf3dfd86c7ea7580ca6118a1db55fb135ab | [
"if not 0 < train_prop <= 1:\n raise ValueError(\"'train_prop' must be in (0, 1] (got {}).\".format(train_prop))\nself.train_prop = train_prop\nself._stat_func = stat_func\nself.loc_mean_fit = -1.0\nself.last_timestamp = -1\nself._fitted = False",
"self.last_timestamp = X[-1]\nlast_ind = int(np.ceil(y.size * s... | <|body_start_0|>
if not 0 < train_prop <= 1:
raise ValueError("'train_prop' must be in (0, 1] (got {}).".format(train_prop))
self.train_prop = train_prop
self._stat_func = stat_func
self.loc_mean_fit = -1.0
self.last_timestamp = -1
self._fitted = False
<|end_b... | Local statistical forecasting model for time-series. This model calculates a statistic from the most recent time-series observations, tipically the mean or median, and use the obtained value as the forecasted value for future timestamps. | _TSLocalStat | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TSLocalStat:
"""Local statistical forecasting model for time-series. This model calculates a statistic from the most recent time-series observations, tipically the mean or median, and use the obtained value as the forecasted value for future timestamps."""
def __init__(self, stat_func: t.Ca... | stack_v2_sparse_classes_10k_train_001129 | 12,299 | permissive | [
{
"docstring": "Init a Local statistical forecasting model.",
"name": "__init__",
"signature": "def __init__(self, stat_func: t.Callable[[np.ndarray], float], train_prop: float)"
},
{
"docstring": "Fit a local statistical forecasting model.",
"name": "fit",
"signature": "def fit(self, X:... | 3 | stack_v2_sparse_classes_30k_train_000136 | Implement the Python class `_TSLocalStat` described below.
Class description:
Local statistical forecasting model for time-series. This model calculates a statistic from the most recent time-series observations, tipically the mean or median, and use the obtained value as the forecasted value for future timestamps.
Me... | Implement the Python class `_TSLocalStat` described below.
Class description:
Local statistical forecasting model for time-series. This model calculates a statistic from the most recent time-series observations, tipically the mean or median, and use the obtained value as the forecasted value for future timestamps.
Me... | 61cc1f63fa055c7466151cfefa7baff8df1702b7 | <|skeleton|>
class _TSLocalStat:
"""Local statistical forecasting model for time-series. This model calculates a statistic from the most recent time-series observations, tipically the mean or median, and use the obtained value as the forecasted value for future timestamps."""
def __init__(self, stat_func: t.Ca... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _TSLocalStat:
"""Local statistical forecasting model for time-series. This model calculates a statistic from the most recent time-series observations, tipically the mean or median, and use the obtained value as the forecasted value for future timestamps."""
def __init__(self, stat_func: t.Callable[[np.nd... | the_stack_v2_python_sparse | tspymfe/_models.py | FelSiq/ts-pymfe | train | 9 |
4eef498f79aa600c8c1a94fd9f337e2091e43c50 | [
"tools.validate_int(routine_id, min=0, max=65535, name='Routine ID')\ntools.validate_int(control_type, min=0, max=127, name='Routine control type')\nif data is not None:\n if not isinstance(data, bytes):\n raise ValueError('data must be a valid bytes object')\nrequest = Request(service=cls, subfunction=co... | <|body_start_0|>
tools.validate_int(routine_id, min=0, max=65535, name='Routine ID')
tools.validate_int(control_type, min=0, max=127, name='Routine control type')
if data is not None:
if not isinstance(data, bytes):
raise ValueError('data must be a valid bytes object'... | RoutineControl | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoutineControl:
def make_request(cls, routine_id: int, control_type: int, data: Optional[bytes]=None) -> Request:
"""Generates a request for RoutineControl :param routine_id: The routine ID. Value should be between 0 and 0xFFFF :type routine_id: int :param control_type: Service subfuncti... | stack_v2_sparse_classes_10k_train_001130 | 4,320 | permissive | [
{
"docstring": "Generates a request for RoutineControl :param routine_id: The routine ID. Value should be between 0 and 0xFFFF :type routine_id: int :param control_type: Service subfunction. Allowed values are from 0 to 0x7F :type control_type: int :param data: Optional additional data to provide to the server ... | 2 | stack_v2_sparse_classes_30k_test_000048 | Implement the Python class `RoutineControl` described below.
Class description:
Implement the RoutineControl class.
Method signatures and docstrings:
- def make_request(cls, routine_id: int, control_type: int, data: Optional[bytes]=None) -> Request: Generates a request for RoutineControl :param routine_id: The routin... | Implement the Python class `RoutineControl` described below.
Class description:
Implement the RoutineControl class.
Method signatures and docstrings:
- def make_request(cls, routine_id: int, control_type: int, data: Optional[bytes]=None) -> Request: Generates a request for RoutineControl :param routine_id: The routin... | 1b93cc3cd0e09a21d48881ba53aed257f841bb89 | <|skeleton|>
class RoutineControl:
def make_request(cls, routine_id: int, control_type: int, data: Optional[bytes]=None) -> Request:
"""Generates a request for RoutineControl :param routine_id: The routine ID. Value should be between 0 and 0xFFFF :type routine_id: int :param control_type: Service subfuncti... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RoutineControl:
def make_request(cls, routine_id: int, control_type: int, data: Optional[bytes]=None) -> Request:
"""Generates a request for RoutineControl :param routine_id: The routine ID. Value should be between 0 and 0xFFFF :type routine_id: int :param control_type: Service subfunction. Allowed va... | the_stack_v2_python_sparse | udsoncan/services/RoutineControl.py | pylessard/python-udsoncan | train | 477 | |
0d65bdee099cfd21e80c837f14281944ebe55d3c | [
"cords = np.zeros((8, 4))\nextent = bbox.extent\ncords[0, :] = np.array([extent.x, extent.y, -extent.z, 1])\ncords[1, :] = np.array([-extent.x, extent.y, -extent.z, 1])\ncords[2, :] = np.array([-extent.x, -extent.y, -extent.z, 1])\ncords[3, :] = np.array([extent.x, -extent.y, -extent.z, 1])\ncords[4, :] = np.array(... | <|body_start_0|>
cords = np.zeros((8, 4))
extent = bbox.extent
cords[0, :] = np.array([extent.x, extent.y, -extent.z, 1])
cords[1, :] = np.array([-extent.x, extent.y, -extent.z, 1])
cords[2, :] = np.array([-extent.x, -extent.y, -extent.z, 1])
cords[3, :] = np.array([exten... | utility functions to handle carla bounding boxes | BboxUtils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BboxUtils:
"""utility functions to handle carla bounding boxes"""
def get_3d_bb_points(bbox):
"""Returns 3D bounding box"""
<|body_0|>
def get_2d_bb_points(bbox):
"""Returns 3D bounding box"""
<|body_1|>
def get_matrix(transform):
"""Creates ... | stack_v2_sparse_classes_10k_train_001131 | 9,169 | no_license | [
{
"docstring": "Returns 3D bounding box",
"name": "get_3d_bb_points",
"signature": "def get_3d_bb_points(bbox)"
},
{
"docstring": "Returns 3D bounding box",
"name": "get_2d_bb_points",
"signature": "def get_2d_bb_points(bbox)"
},
{
"docstring": "Creates matrix from carla transfor... | 3 | stack_v2_sparse_classes_30k_train_003265 | Implement the Python class `BboxUtils` described below.
Class description:
utility functions to handle carla bounding boxes
Method signatures and docstrings:
- def get_3d_bb_points(bbox): Returns 3D bounding box
- def get_2d_bb_points(bbox): Returns 3D bounding box
- def get_matrix(transform): Creates matrix from car... | Implement the Python class `BboxUtils` described below.
Class description:
utility functions to handle carla bounding boxes
Method signatures and docstrings:
- def get_3d_bb_points(bbox): Returns 3D bounding box
- def get_2d_bb_points(bbox): Returns 3D bounding box
- def get_matrix(transform): Creates matrix from car... | d0db1c4124751e83ec8b121c8e3a9ccfc9cdf577 | <|skeleton|>
class BboxUtils:
"""utility functions to handle carla bounding boxes"""
def get_3d_bb_points(bbox):
"""Returns 3D bounding box"""
<|body_0|>
def get_2d_bb_points(bbox):
"""Returns 3D bounding box"""
<|body_1|>
def get_matrix(transform):
"""Creates ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BboxUtils:
"""utility functions to handle carla bounding boxes"""
def get_3d_bb_points(bbox):
"""Returns 3D bounding box"""
cords = np.zeros((8, 4))
extent = bbox.extent
cords[0, :] = np.array([extent.x, extent.y, -extent.z, 1])
cords[1, :] = np.array([-extent.x, e... | the_stack_v2_python_sparse | mapping/plane_map.py | mengxingshifen1218/Safe_Occlusion_Aware_Planning | train | 1 |
c4c84fc9aa825bbe3ee887aae9f3d14c89e9b7f8 | [
"new_urls = set()\nlinks = soup.find_all('a', href=re.compile('/item/'))\nfor link in links:\n new_url = link['href']\n new_full_url = 'http://baike.baidu.com' + new_url\n new_urls.add(new_full_url)\nreturn new_urls",
"res_data = dict()\nres_data['url'] = page_url\ntitle_node = soup.find('dd', class_='le... | <|body_start_0|>
new_urls = set()
links = soup.find_all('a', href=re.compile('/item/'))
for link in links:
new_url = link['href']
new_full_url = 'http://baike.baidu.com' + new_url
new_urls.add(new_full_url)
return new_urls
<|end_body_0|>
<|body_start_... | HtmlParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtmlParser:
def __get_new_urls(self, page_url, soup):
"""发现新的url"""
<|body_0|>
def __get_new_data(self, page_url, soup):
"""获取内容"""
<|body_1|>
def parse(self, page_url, html_content):
"""解析 html"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_10k_train_001132 | 1,465 | no_license | [
{
"docstring": "发现新的url",
"name": "__get_new_urls",
"signature": "def __get_new_urls(self, page_url, soup)"
},
{
"docstring": "获取内容",
"name": "__get_new_data",
"signature": "def __get_new_data(self, page_url, soup)"
},
{
"docstring": "解析 html",
"name": "parse",
"signature... | 3 | stack_v2_sparse_classes_30k_train_003567 | Implement the Python class `HtmlParser` described below.
Class description:
Implement the HtmlParser class.
Method signatures and docstrings:
- def __get_new_urls(self, page_url, soup): 发现新的url
- def __get_new_data(self, page_url, soup): 获取内容
- def parse(self, page_url, html_content): 解析 html | Implement the Python class `HtmlParser` described below.
Class description:
Implement the HtmlParser class.
Method signatures and docstrings:
- def __get_new_urls(self, page_url, soup): 发现新的url
- def __get_new_data(self, page_url, soup): 获取内容
- def parse(self, page_url, html_content): 解析 html
<|skeleton|>
class Html... | 98e41ebf5eb3ab2335c82bcc78d8171fd7e8d460 | <|skeleton|>
class HtmlParser:
def __get_new_urls(self, page_url, soup):
"""发现新的url"""
<|body_0|>
def __get_new_data(self, page_url, soup):
"""获取内容"""
<|body_1|>
def parse(self, page_url, html_content):
"""解析 html"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HtmlParser:
def __get_new_urls(self, page_url, soup):
"""发现新的url"""
new_urls = set()
links = soup.find_all('a', href=re.compile('/item/'))
for link in links:
new_url = link['href']
new_full_url = 'http://baike.baidu.com' + new_url
new_urls.ad... | the_stack_v2_python_sparse | spider004/html_parser.py | geeksuperbin/newspider | train | 0 | |
e785c85afa12588ea4d8003148057f66ca8c7497 | [
"credentials = authorized_user.Credentials.from_authorized_user_info({'client_id': 'client_id', 'client_secret': 'client_secret', 'refresh_token': 'refresh_token'})\nentity = TestModel(id='foo', credentials=credentials)\nentity.put()\nretrieved = TestModel.get_by_id('foo')\nself.assertIsNotNone(retrieved.credential... | <|body_start_0|>
credentials = authorized_user.Credentials.from_authorized_user_info({'client_id': 'client_id', 'client_secret': 'client_secret', 'refresh_token': 'refresh_token'})
entity = TestModel(id='foo', credentials=credentials)
entity.put()
retrieved = TestModel.get_by_id('foo')
... | Tests for oauth2_util.CredentialsProperty. | CredentialsPropertyTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CredentialsPropertyTest:
"""Tests for oauth2_util.CredentialsProperty."""
def testStore(self):
"""Tests that credentials can be stored and retrieved."""
<|body_0|>
def testValidate(self):
"""Tests that the credentials type is validated."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_001133 | 2,907 | permissive | [
{
"docstring": "Tests that credentials can be stored and retrieved.",
"name": "testStore",
"signature": "def testStore(self)"
},
{
"docstring": "Tests that the credentials type is validated.",
"name": "testValidate",
"signature": "def testValidate(self)"
},
{
"docstring": "Tests ... | 3 | stack_v2_sparse_classes_30k_train_005453 | Implement the Python class `CredentialsPropertyTest` described below.
Class description:
Tests for oauth2_util.CredentialsProperty.
Method signatures and docstrings:
- def testStore(self): Tests that credentials can be stored and retrieved.
- def testValidate(self): Tests that the credentials type is validated.
- def... | Implement the Python class `CredentialsPropertyTest` described below.
Class description:
Tests for oauth2_util.CredentialsProperty.
Method signatures and docstrings:
- def testStore(self): Tests that credentials can be stored and retrieved.
- def testValidate(self): Tests that the credentials type is validated.
- def... | 5e10bed02089e4cf29ae4d9d67e127f77e8fb3c9 | <|skeleton|>
class CredentialsPropertyTest:
"""Tests for oauth2_util.CredentialsProperty."""
def testStore(self):
"""Tests that credentials can be stored and retrieved."""
<|body_0|>
def testValidate(self):
"""Tests that the credentials type is validated."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CredentialsPropertyTest:
"""Tests for oauth2_util.CredentialsProperty."""
def testStore(self):
"""Tests that credentials can be stored and retrieved."""
credentials = authorized_user.Credentials.from_authorized_user_info({'client_id': 'client_id', 'client_secret': 'client_secret', 'refres... | the_stack_v2_python_sparse | multitest_transport/util/oauth2_util_test.py | maksonlee/multitest_transport | train | 0 |
69f674fbe02b4bb587a634fa80ac1144dd354f90 | [
"if releaselevel not in self._specifiers:\n raise ValueError(f'''Value \"{releaselevel}\" for releaselevel not in ({','.join(sorted(self._specifiers.keys()))})''')\nself.major, self.minor, self.micro = (major, minor, micro)\nself.releaselevel, self.serial, self.label = (releaselevel, serial, label)",
"items = ... | <|body_start_0|>
if releaselevel not in self._specifiers:
raise ValueError(f'''Value "{releaselevel}" for releaselevel not in ({','.join(sorted(self._specifiers.keys()))})''')
self.major, self.minor, self.micro = (major, minor, micro)
self.releaselevel, self.serial, self.label = (rel... | This class attempts to be compliant with a subset of `PEP 440 <https://www.python.org/dev/peps/pep-0440/>`_. Note: If you actually happen to read the PEP, you will notice that pre- and post- releases, as well as "release epochs", are not supported. | Version | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Version:
"""This class attempts to be compliant with a subset of `PEP 440 <https://www.python.org/dev/peps/pep-0440/>`_. Note: If you actually happen to read the PEP, you will notice that pre- and post- releases, as well as "release epochs", are not supported."""
def __init__(self, major, mi... | stack_v2_sparse_classes_10k_train_001134 | 6,479 | permissive | [
{
"docstring": "Create new version object. Provided arguments are stored in public class attributes by the same name. Args: major (int): Major version minor (int): Minor version micro (int): Micro (aka patchlevel) version releaselevel (str): Optional PEP 440 specifier serial (int): Optional number associated wi... | 3 | null | Implement the Python class `Version` described below.
Class description:
This class attempts to be compliant with a subset of `PEP 440 <https://www.python.org/dev/peps/pep-0440/>`_. Note: If you actually happen to read the PEP, you will notice that pre- and post- releases, as well as "release epochs", are not supporte... | Implement the Python class `Version` described below.
Class description:
This class attempts to be compliant with a subset of `PEP 440 <https://www.python.org/dev/peps/pep-0440/>`_. Note: If you actually happen to read the PEP, you will notice that pre- and post- releases, as well as "release epochs", are not supporte... | deacf4c422bc9e50cb347e11a8cbfa0195bd4274 | <|skeleton|>
class Version:
"""This class attempts to be compliant with a subset of `PEP 440 <https://www.python.org/dev/peps/pep-0440/>`_. Note: If you actually happen to read the PEP, you will notice that pre- and post- releases, as well as "release epochs", are not supported."""
def __init__(self, major, mi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Version:
"""This class attempts to be compliant with a subset of `PEP 440 <https://www.python.org/dev/peps/pep-0440/>`_. Note: If you actually happen to read the PEP, you will notice that pre- and post- releases, as well as "release epochs", are not supported."""
def __init__(self, major, minor, micro, r... | the_stack_v2_python_sparse | idaes/ver.py | IDAES/idaes-pse | train | 173 |
ed7c41fc23722fe01cadd4e8f5c2db00dfaa878f | [
"result = self.device.brightness\ntry:\n brightness_value = int(result)\nexcept ValueError:\n _LOGGER.debug(\"VeSync - received unexpected 'brightness' value from pyvesync api: %s\", result)\n return 0\nreturn round(max(1, brightness_value) / 100 * 255)",
"attribute_adjustment_only = False\nif self.color... | <|body_start_0|>
result = self.device.brightness
try:
brightness_value = int(result)
except ValueError:
_LOGGER.debug("VeSync - received unexpected 'brightness' value from pyvesync api: %s", result)
return 0
return round(max(1, brightness_value) / 100 ... | Base class for VeSync Light Devices Representations. | VeSyncBaseLight | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VeSyncBaseLight:
"""Base class for VeSync Light Devices Representations."""
def brightness(self) -> int:
"""Get light brightness."""
<|body_0|>
def turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_10k_train_001135 | 6,590 | permissive | [
{
"docstring": "Get light brightness.",
"name": "brightness",
"signature": "def brightness(self) -> int"
},
{
"docstring": "Turn the device on.",
"name": "turn_on",
"signature": "def turn_on(self, **kwargs: Any) -> None"
}
] | 2 | null | Implement the Python class `VeSyncBaseLight` described below.
Class description:
Base class for VeSync Light Devices Representations.
Method signatures and docstrings:
- def brightness(self) -> int: Get light brightness.
- def turn_on(self, **kwargs: Any) -> None: Turn the device on. | Implement the Python class `VeSyncBaseLight` described below.
Class description:
Base class for VeSync Light Devices Representations.
Method signatures and docstrings:
- def brightness(self) -> int: Get light brightness.
- def turn_on(self, **kwargs: Any) -> None: Turn the device on.
<|skeleton|>
class VeSyncBaseLig... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class VeSyncBaseLight:
"""Base class for VeSync Light Devices Representations."""
def brightness(self) -> int:
"""Get light brightness."""
<|body_0|>
def turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VeSyncBaseLight:
"""Base class for VeSync Light Devices Representations."""
def brightness(self) -> int:
"""Get light brightness."""
result = self.device.brightness
try:
brightness_value = int(result)
except ValueError:
_LOGGER.debug("VeSync - recei... | the_stack_v2_python_sparse | homeassistant/components/vesync/light.py | home-assistant/core | train | 35,501 |
3f31cc61ce42c8bff65299ebaa2803b1218af43c | [
"self.url = url\nself.username = username\nself.password = password\nself.contexts = []\nif isinstance(contexts, list):\n self.contexts = contexts",
"if metric_name in self.contexts:\n return metric_name\nreturn 'default'",
"data_regex = '\\n ^[a-z\\\\s]+:\\\\s*\\n (?P<active_connect... | <|body_start_0|>
self.url = url
self.username = username
self.password = password
self.contexts = []
if isinstance(contexts, list):
self.contexts = contexts
<|end_body_0|>
<|body_start_1|>
if metric_name in self.contexts:
return metric_name
... | This ressource manage data in Nginx stub status page | StubStatusPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StubStatusPage:
"""This ressource manage data in Nginx stub status page"""
def __init__(self, url='', username='', password='', contexts=None):
"""Initialize ressource attributes :param url: Nginx stub status url :param username: Username authorized to view stats :param password: Pas... | stack_v2_sparse_classes_10k_train_001136 | 3,072 | no_license | [
{
"docstring": "Initialize ressource attributes :param url: Nginx stub status url :param username: Username authorized to view stats :param password: Password of username authorized to view stats :param contexts: Managed contexts for probe metrics :type url: string :type username: string :type password: string ... | 4 | stack_v2_sparse_classes_30k_train_006839 | Implement the Python class `StubStatusPage` described below.
Class description:
This ressource manage data in Nginx stub status page
Method signatures and docstrings:
- def __init__(self, url='', username='', password='', contexts=None): Initialize ressource attributes :param url: Nginx stub status url :param usernam... | Implement the Python class `StubStatusPage` described below.
Class description:
This ressource manage data in Nginx stub status page
Method signatures and docstrings:
- def __init__(self, url='', username='', password='', contexts=None): Initialize ressource attributes :param url: Nginx stub status url :param usernam... | 947199bf8525f64d2765f3b4e4e0e59bc56b5208 | <|skeleton|>
class StubStatusPage:
"""This ressource manage data in Nginx stub status page"""
def __init__(self, url='', username='', password='', contexts=None):
"""Initialize ressource attributes :param url: Nginx stub status url :param username: Username authorized to view stats :param password: Pas... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StubStatusPage:
"""This ressource manage data in Nginx stub status page"""
def __init__(self, url='', username='', password='', contexts=None):
"""Initialize ressource attributes :param url: Nginx stub status url :param username: Username authorized to view stats :param password: Password of user... | the_stack_v2_python_sparse | temelio_monitoring/resource/webserver/nginx/stub_status_page.py | Temelio/monitoring-lib-python | train | 0 |
5d117a377f379ffef5a3894a86fab6d8fe8e4eb6 | [
"self.mols = mols\nif which('parmchk'):\n self.parmchk_version = 'parmchk'\nelse:\n self.parmchk_version = 'parmchk2'",
"command = parmchk_version + ' -i {} -f {} -o {} -w {}'.format(filename, format, outfile_name, print_improper_dihedrals)\nexit_code = subprocess.call(shlex.split(command))\nreturn exit_cod... | <|body_start_0|>
self.mols = mols
if which('parmchk'):
self.parmchk_version = 'parmchk'
else:
self.parmchk_version = 'parmchk2'
<|end_body_0|>
<|body_start_1|>
command = parmchk_version + ' -i {} -f {} -o {} -w {}'.format(filename, format, outfile_name, print_imp... | A wrapper for AntechamberRunner software | AntechamberRunner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AntechamberRunner:
"""A wrapper for AntechamberRunner software"""
def __init__(self, mols):
"""Args: mols: List of molecules"""
<|body_0|>
def _run_parmchk(self, filename='mol.mol2', format='mol2', outfile_name='mol.frcmod', print_improper_dihedrals='Y'):
"""run ... | stack_v2_sparse_classes_10k_train_001137 | 6,484 | no_license | [
{
"docstring": "Args: mols: List of molecules",
"name": "__init__",
"signature": "def __init__(self, mols)"
},
{
"docstring": "run parmchk",
"name": "_run_parmchk",
"signature": "def _run_parmchk(self, filename='mol.mol2', format='mol2', outfile_name='mol.frcmod', print_improper_dihedral... | 6 | stack_v2_sparse_classes_30k_train_001618 | Implement the Python class `AntechamberRunner` described below.
Class description:
A wrapper for AntechamberRunner software
Method signatures and docstrings:
- def __init__(self, mols): Args: mols: List of molecules
- def _run_parmchk(self, filename='mol.mol2', format='mol2', outfile_name='mol.frcmod', print_improper... | Implement the Python class `AntechamberRunner` described below.
Class description:
A wrapper for AntechamberRunner software
Method signatures and docstrings:
- def __init__(self, mols): Args: mols: List of molecules
- def _run_parmchk(self, filename='mol.mol2', format='mol2', outfile_name='mol.frcmod', print_improper... | b07ebd0d32a3968fd6c120579f87590ec8bdd3ae | <|skeleton|>
class AntechamberRunner:
"""A wrapper for AntechamberRunner software"""
def __init__(self, mols):
"""Args: mols: List of molecules"""
<|body_0|>
def _run_parmchk(self, filename='mol.mol2', format='mol2', outfile_name='mol.frcmod', print_improper_dihedrals='Y'):
"""run ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AntechamberRunner:
"""A wrapper for AntechamberRunner software"""
def __init__(self, mols):
"""Args: mols: List of molecules"""
self.mols = mols
if which('parmchk'):
self.parmchk_version = 'parmchk'
else:
self.parmchk_version = 'parmchk2'
def _... | the_stack_v2_python_sparse | rubicon/io/amber/antechamber.py | molmd/rubicon | train | 0 |
8088bc5b2311607af3c9946eb29481f6881a7730 | [
"if not provider:\n raise ValueError('Cache provider input must not be empty.')\nself._instances = {}\nself._provider = provider\nself._unique_settings_keys = unique_settings_keys",
"instance_vals = {key: config.get(key) for key in self._unique_settings_keys}\ninstance_key = hashlib.sha256(str(instance_vals).e... | <|body_start_0|>
if not provider:
raise ValueError('Cache provider input must not be empty.')
self._instances = {}
self._provider = provider
self._unique_settings_keys = unique_settings_keys
<|end_body_0|>
<|body_start_1|>
instance_vals = {key: config.get(key) for ke... | Cache the result of another provider. | CachedProvider | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CachedProvider:
"""Cache the result of another provider."""
def __init__(self, provider: BaseProvider, unique_settings_keys: tuple=()):
"""Initialize the cached provider instance."""
<|body_0|>
def provide(self, config: BaseSettings, injector: BaseInjector):
"""P... | stack_v2_sparse_classes_10k_train_001138 | 4,857 | permissive | [
{
"docstring": "Initialize the cached provider instance.",
"name": "__init__",
"signature": "def __init__(self, provider: BaseProvider, unique_settings_keys: tuple=())"
},
{
"docstring": "Provide the object instance given a config and injector. Instances are cached keyed on a SHA256 digest of th... | 2 | null | Implement the Python class `CachedProvider` described below.
Class description:
Cache the result of another provider.
Method signatures and docstrings:
- def __init__(self, provider: BaseProvider, unique_settings_keys: tuple=()): Initialize the cached provider instance.
- def provide(self, config: BaseSettings, injec... | Implement the Python class `CachedProvider` described below.
Class description:
Cache the result of another provider.
Method signatures and docstrings:
- def __init__(self, provider: BaseProvider, unique_settings_keys: tuple=()): Initialize the cached provider instance.
- def provide(self, config: BaseSettings, injec... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class CachedProvider:
"""Cache the result of another provider."""
def __init__(self, provider: BaseProvider, unique_settings_keys: tuple=()):
"""Initialize the cached provider instance."""
<|body_0|>
def provide(self, config: BaseSettings, injector: BaseInjector):
"""P... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CachedProvider:
"""Cache the result of another provider."""
def __init__(self, provider: BaseProvider, unique_settings_keys: tuple=()):
"""Initialize the cached provider instance."""
if not provider:
raise ValueError('Cache provider input must not be empty.')
self._ins... | the_stack_v2_python_sparse | aries_cloudagent/config/provider.py | hyperledger/aries-cloudagent-python | train | 370 |
f9e7fead436b149db2096f71f4c710d2a1a0881a | [
"self.strings = []\nfor x in range(0, len(document) - 1):\n if x + k < len(document):\n self.strings.append(document[x:x + k])\n else:\n self.strings.append(document[x:len(document)])\ncomp = lambda x, y: 0 if len(x) == len(y) else -1 if len(x) > len(y) else 1\nself.strings = mysort(self.strings... | <|body_start_0|>
self.strings = []
for x in range(0, len(document) - 1):
if x + k < len(document):
self.strings.append(document[x:x + k])
else:
self.strings.append(document[x:len(document)])
comp = lambda x, y: 0 if len(x) == len(y) else -1... | PrefixSearcher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrefixSearcher:
def __init__(self, document, k):
"""Initializes a prefix searcher using a document and a maximum search string length k."""
<|body_0|>
def search(self, q):
"""Return true if the document contains search string q (of length up to n). If q is longer tha... | stack_v2_sparse_classes_10k_train_001139 | 8,672 | no_license | [
{
"docstring": "Initializes a prefix searcher using a document and a maximum search string length k.",
"name": "__init__",
"signature": "def __init__(self, document, k)"
},
{
"docstring": "Return true if the document contains search string q (of length up to n). If q is longer than n, then raise... | 2 | stack_v2_sparse_classes_30k_train_002334 | Implement the Python class `PrefixSearcher` described below.
Class description:
Implement the PrefixSearcher class.
Method signatures and docstrings:
- def __init__(self, document, k): Initializes a prefix searcher using a document and a maximum search string length k.
- def search(self, q): Return true if the docume... | Implement the Python class `PrefixSearcher` described below.
Class description:
Implement the PrefixSearcher class.
Method signatures and docstrings:
- def __init__(self, document, k): Initializes a prefix searcher using a document and a maximum search string length k.
- def search(self, q): Return true if the docume... | b4edf759b2916ab44f08741a6f19b103a9070203 | <|skeleton|>
class PrefixSearcher:
def __init__(self, document, k):
"""Initializes a prefix searcher using a document and a maximum search string length k."""
<|body_0|>
def search(self, q):
"""Return true if the document contains search string q (of length up to n). If q is longer tha... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrefixSearcher:
def __init__(self, document, k):
"""Initializes a prefix searcher using a document and a maximum search string length k."""
self.strings = []
for x in range(0, len(document) - 1):
if x + k < len(document):
self.strings.append(document[x:x + k... | the_stack_v2_python_sparse | lab03/lab03.py | saronson/cs331-s21-jmallett2 | train | 2 | |
c4e01cf6bcdf0f289e6ca94943139fcde6fbaae5 | [
"super().__init__('object_detection_2d_yolov5_node')\nself.image_subscriber = self.create_subscription(ROS_Image, input_rgb_image_topic, self.callback, 1)\nif output_rgb_image_topic is not None:\n self.image_publisher = self.create_publisher(ROS_Image, output_rgb_image_topic, 1)\nelse:\n self.image_publisher ... | <|body_start_0|>
super().__init__('object_detection_2d_yolov5_node')
self.image_subscriber = self.create_subscription(ROS_Image, input_rgb_image_topic, self.callback, 1)
if output_rgb_image_topic is not None:
self.image_publisher = self.create_publisher(ROS_Image, output_rgb_image_to... | ObjectDetectionYOLOV5Node | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectDetectionYOLOV5Node:
def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/objects', device='cuda', model='yolov5s'):
"""Creates a ROS2 Node for object detection with YOLOV5. :param input_rgb_image_... | stack_v2_sparse_classes_10k_train_001140 | 6,214 | permissive | [
{
"docstring": "Creates a ROS2 Node for object detection with YOLOV5. :param input_rgb_image_topic: Topic from which we are reading the input image :type input_rgb_image_topic: str :param output_rgb_image_topic: Topic to which we are publishing the annotated image (if None, no annotated image is published) :typ... | 2 | null | Implement the Python class `ObjectDetectionYOLOV5Node` described below.
Class description:
Implement the ObjectDetectionYOLOV5Node class.
Method signatures and docstrings:
- def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/object... | Implement the Python class `ObjectDetectionYOLOV5Node` described below.
Class description:
Implement the ObjectDetectionYOLOV5Node class.
Method signatures and docstrings:
- def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/object... | b3d6ce670cdf63469fc5766630eb295d67b3d788 | <|skeleton|>
class ObjectDetectionYOLOV5Node:
def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/objects', device='cuda', model='yolov5s'):
"""Creates a ROS2 Node for object detection with YOLOV5. :param input_rgb_image_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ObjectDetectionYOLOV5Node:
def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/objects', device='cuda', model='yolov5s'):
"""Creates a ROS2 Node for object detection with YOLOV5. :param input_rgb_image_topic: Topic f... | the_stack_v2_python_sparse | projects/opendr_ws_2/src/opendr_perception/opendr_perception/object_detection_2d_yolov5_node.py | opendr-eu/opendr | train | 535 | |
c678e68edb104d717d535528680cfac28a545ef4 | [
"super(JDDCodec, self).__init__(search_space, **kwargs)\nself.func_type, self.func_prob = self.get_choices()\nself.func_type_num = len(self.func_type)",
"channel_types = ['16', '32', '48']\nchannel_prob = [1, 0.5, 0.2]\nblock_types = ['R']\nblock_prob = [1]\nmodel_type = self.search_space['modules'][0]\nchannel_t... | <|body_start_0|>
super(JDDCodec, self).__init__(search_space, **kwargs)
self.func_type, self.func_prob = self.get_choices()
self.func_type_num = len(self.func_type)
<|end_body_0|>
<|body_start_1|>
channel_types = ['16', '32', '48']
channel_prob = [1, 0.5, 0.2]
block_type... | Codec of the JDD search space. | JDDCodec | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JDDCodec:
"""Codec of the JDD search space."""
def __init__(self, search_space=None, **kwargs):
"""Construct the SRCodec class. :param codec_name: name of the codec :type codec_name: str :param search_space: Search space of the codec :type search_space: dictionary "S_" means that the... | stack_v2_sparse_classes_10k_train_001141 | 3,268 | permissive | [
{
"docstring": "Construct the SRCodec class. :param codec_name: name of the codec :type codec_name: str :param search_space: Search space of the codec :type search_space: dictionary \"S_\" means that the shrink RDB blcock with 1x1 convolution . \"G_\" means that the RDB block with channel shuffle and group conv... | 3 | stack_v2_sparse_classes_30k_train_006420 | Implement the Python class `JDDCodec` described below.
Class description:
Codec of the JDD search space.
Method signatures and docstrings:
- def __init__(self, search_space=None, **kwargs): Construct the SRCodec class. :param codec_name: name of the codec :type codec_name: str :param search_space: Search space of the... | Implement the Python class `JDDCodec` described below.
Class description:
Codec of the JDD search space.
Method signatures and docstrings:
- def __init__(self, search_space=None, **kwargs): Construct the SRCodec class. :param codec_name: name of the codec :type codec_name: str :param search_space: Search space of the... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class JDDCodec:
"""Codec of the JDD search space."""
def __init__(self, search_space=None, **kwargs):
"""Construct the SRCodec class. :param codec_name: name of the codec :type codec_name: str :param search_space: Search space of the codec :type search_space: dictionary "S_" means that the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JDDCodec:
"""Codec of the JDD search space."""
def __init__(self, search_space=None, **kwargs):
"""Construct the SRCodec class. :param codec_name: name of the codec :type codec_name: str :param search_space: Search space of the codec :type search_space: dictionary "S_" means that the shrink RDB b... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/algorithms/nas/jdd_ea/jdd_ea_codec.py | Huawei-Ascend/modelzoo | train | 1 |
f8d0df0718d469b9b0403c64373581c7d87f7417 | [
"instance_selections = iam.list_instance_selection(system_id)\nif not instance_selections:\n return []\nreturn [RawInstanceSelection(**i) for i in instance_selections]",
"action = Action(**iam.get_action(system_id, action_id))\nresource_type = action.get_related_resource_type(resource_type_system_id, resource_... | <|body_start_0|>
instance_selections = iam.list_instance_selection(system_id)
if not instance_selections:
return []
return [RawInstanceSelection(**i) for i in instance_selections]
<|end_body_0|>
<|body_start_1|>
action = Action(**iam.get_action(system_id, action_id))
... | InstanceSelectionService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceSelectionService:
def list_raw_by_system(self, system_id: str) -> List[RawInstanceSelection]:
"""获取系统所有的实例视图, 用于manager api"""
<|body_0|>
def list_by_action_resource_type(self, system_id: str, action_id: str, resource_type_system_id: str, resource_type_id: str) -> Li... | stack_v2_sparse_classes_10k_train_001142 | 1,802 | permissive | [
{
"docstring": "获取系统所有的实例视图, 用于manager api",
"name": "list_raw_by_system",
"signature": "def list_raw_by_system(self, system_id: str) -> List[RawInstanceSelection]"
},
{
"docstring": "获取某个操作关联的资源类型的实例视图, 前端展示",
"name": "list_by_action_resource_type",
"signature": "def list_by_action_reso... | 2 | null | Implement the Python class `InstanceSelectionService` described below.
Class description:
Implement the InstanceSelectionService class.
Method signatures and docstrings:
- def list_raw_by_system(self, system_id: str) -> List[RawInstanceSelection]: 获取系统所有的实例视图, 用于manager api
- def list_by_action_resource_type(self, sy... | Implement the Python class `InstanceSelectionService` described below.
Class description:
Implement the InstanceSelectionService class.
Method signatures and docstrings:
- def list_raw_by_system(self, system_id: str) -> List[RawInstanceSelection]: 获取系统所有的实例视图, 用于manager api
- def list_by_action_resource_type(self, sy... | 33c8f4ffe8697081abcfc5771b98a88c0578059f | <|skeleton|>
class InstanceSelectionService:
def list_raw_by_system(self, system_id: str) -> List[RawInstanceSelection]:
"""获取系统所有的实例视图, 用于manager api"""
<|body_0|>
def list_by_action_resource_type(self, system_id: str, action_id: str, resource_type_system_id: str, resource_type_id: str) -> Li... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InstanceSelectionService:
def list_raw_by_system(self, system_id: str) -> List[RawInstanceSelection]:
"""获取系统所有的实例视图, 用于manager api"""
instance_selections = iam.list_instance_selection(system_id)
if not instance_selections:
return []
return [RawInstanceSelection(**i... | the_stack_v2_python_sparse | saas/backend/service/instance_selection.py | robert871126/bk-iam-saas | train | 0 | |
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 season = db.season_by_id(season_id, session)\nexcept NoResultFound:\n raise NotFoundError('season with ID %s not found' % season_id)\nif not db.season_in_show(show_... | <|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:
season = db.season_by_id(season_id, session)
except NoResultFound:
raise NotFoundError('seas... | SeriesSeasonAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeriesSeasonAPI:
def get(self, show_id, season_id, session):
"""Get season by show ID and season ID"""
<|body_0|>
def delete(self, show_id, season_id, session):
"""Forgets season by show ID and season ID"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_001143 | 47,001 | permissive | [
{
"docstring": "Get season by show ID and season ID",
"name": "get",
"signature": "def get(self, show_id, season_id, session)"
},
{
"docstring": "Forgets season by show ID and season ID",
"name": "delete",
"signature": "def delete(self, show_id, season_id, session)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002160 | Implement the Python class `SeriesSeasonAPI` described below.
Class description:
Implement the SeriesSeasonAPI class.
Method signatures and docstrings:
- def get(self, show_id, season_id, session): Get season by show ID and season ID
- def delete(self, show_id, season_id, session): Forgets season by show ID and seaso... | Implement the Python class `SeriesSeasonAPI` described below.
Class description:
Implement the SeriesSeasonAPI class.
Method signatures and docstrings:
- def get(self, show_id, season_id, session): Get season by show ID and season ID
- def delete(self, show_id, season_id, session): Forgets season by show ID and seaso... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class SeriesSeasonAPI:
def get(self, show_id, season_id, session):
"""Get season by show ID and season ID"""
<|body_0|>
def delete(self, show_id, season_id, session):
"""Forgets season by show ID and season ID"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SeriesSeasonAPI:
def get(self, show_id, season_id, session):
"""Get season by show ID and season ID"""
try:
db.show_by_id(show_id, session=session)
except NoResultFound:
raise NotFoundError('show with ID %s not found' % show_id)
try:
season =... | the_stack_v2_python_sparse | flexget/components/series/api.py | BrutuZ/Flexget | train | 1 | |
ca4f73c0708fcd8d86875cdae063c88eef86c9d3 | [
"self.left = None\nself.right = None\nself.data = data\nself.parent = parent",
"if data < self.data:\n if self.left is None:\n self.left = Node(data, self)\n else:\n self.left.insert(data)\nelif data > self.data:\n if self.right is None:\n self.right = Node(data, self)\n else:\n ... | <|body_start_0|>
self.left = None
self.right = None
self.data = data
self.parent = parent
<|end_body_0|>
<|body_start_1|>
if data < self.data:
if self.left is None:
self.left = Node(data, self)
else:
self.left.insert(data)
... | Tree node: left and right child + data which can be any object | Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
"""Tree node: left and right child + data which can be any object"""
def __init__(self, data, parent):
"""Node constructor @param data node data object"""
<|body_0|>
def insert(self, data):
"""Insert new node with data @param data node data object to insert... | stack_v2_sparse_classes_10k_train_001144 | 2,595 | no_license | [
{
"docstring": "Node constructor @param data node data object",
"name": "__init__",
"signature": "def __init__(self, data, parent)"
},
{
"docstring": "Insert new node with data @param data node data object to insert",
"name": "insert",
"signature": "def insert(self, data)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_000850 | Implement the Python class `Node` described below.
Class description:
Tree node: left and right child + data which can be any object
Method signatures and docstrings:
- def __init__(self, data, parent): Node constructor @param data node data object
- def insert(self, data): Insert new node with data @param data node ... | Implement the Python class `Node` described below.
Class description:
Tree node: left and right child + data which can be any object
Method signatures and docstrings:
- def __init__(self, data, parent): Node constructor @param data node data object
- def insert(self, data): Insert new node with data @param data node ... | ec3a9afab657861d471550ca8fcb4b2a269cf46b | <|skeleton|>
class Node:
"""Tree node: left and right child + data which can be any object"""
def __init__(self, data, parent):
"""Node constructor @param data node data object"""
<|body_0|>
def insert(self, data):
"""Insert new node with data @param data node data object to insert... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Node:
"""Tree node: left and right child + data which can be any object"""
def __init__(self, data, parent):
"""Node constructor @param data node data object"""
self.left = None
self.right = None
self.data = data
self.parent = parent
def insert(self, data):
... | the_stack_v2_python_sparse | Medium/c11 Lowest Common Ancestor.py | mgorgei/codeeval | train | 1 |
deddc093edcbd0ecbe5e5a821330de0d03642b86 | [
"if 'next' in self.request.POST:\n return self.request.POST.get('next')\nreturn reverse('my_reservations')",
"if 'pk' in request.POST:\n pk = request.POST.get('pk')\n try:\n reservation = Reservation.objects.get(pk=pk)\n if reservation.can_delete(request.user):\n reservation.dele... | <|body_start_0|>
if 'next' in self.request.POST:
return self.request.POST.get('next')
return reverse('my_reservations')
<|end_body_0|>
<|body_start_1|>
if 'pk' in request.POST:
pk = request.POST.get('pk')
try:
reservation = Reservation.objects... | View for deleting a reservation (Cannot be DeleteView due to the abstract inheritance of reservations) | DeleteReservationView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteReservationView:
"""View for deleting a reservation (Cannot be DeleteView due to the abstract inheritance of reservations)"""
def get_redirect_url(self, *args, **kwargs):
"""Gives the redirect url for when the reservation is deleted :return: The redirect url"""
<|body_0... | stack_v2_sparse_classes_10k_train_001145 | 12,808 | permissive | [
{
"docstring": "Gives the redirect url for when the reservation is deleted :return: The redirect url",
"name": "get_redirect_url",
"signature": "def get_redirect_url(self, *args, **kwargs)"
},
{
"docstring": "Delete the reservation if it can be deleted by the current user and exists :param reque... | 2 | stack_v2_sparse_classes_30k_train_006614 | Implement the Python class `DeleteReservationView` described below.
Class description:
View for deleting a reservation (Cannot be DeleteView due to the abstract inheritance of reservations)
Method signatures and docstrings:
- def get_redirect_url(self, *args, **kwargs): Gives the redirect url for when the reservation... | Implement the Python class `DeleteReservationView` described below.
Class description:
View for deleting a reservation (Cannot be DeleteView due to the abstract inheritance of reservations)
Method signatures and docstrings:
- def get_redirect_url(self, *args, **kwargs): Gives the redirect url for when the reservation... | 1d190a86e3277315804bfcc0b8f9abd4f9c1d780 | <|skeleton|>
class DeleteReservationView:
"""View for deleting a reservation (Cannot be DeleteView due to the abstract inheritance of reservations)"""
def get_redirect_url(self, *args, **kwargs):
"""Gives the redirect url for when the reservation is deleted :return: The redirect url"""
<|body_0... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeleteReservationView:
"""View for deleting a reservation (Cannot be DeleteView due to the abstract inheritance of reservations)"""
def get_redirect_url(self, *args, **kwargs):
"""Gives the redirect url for when the reservation is deleted :return: The redirect url"""
if 'next' in self.req... | the_stack_v2_python_sparse | make_queue/views/reservation/reservation.py | mahoyen/web | train | 0 |
7576878efced270a4ccd33431e7197a34cd2a522 | [
"self.finalized = finalized\nself.paused = paused\nself.previous_view_name = previous_view_name",
"if dictionary is None:\n return None\nfinalized = dictionary.get('finalized')\npaused = dictionary.get('paused')\nprevious_view_name = dictionary.get('previousViewName')\nreturn cls(finalized, paused, previous_vi... | <|body_start_0|>
self.finalized = finalized
self.paused = paused
self.previous_view_name = previous_view_name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
finalized = dictionary.get('finalized')
paused = dictionary.get('paused')
... | Implementation of the 'MirrorParams' model. TODO: type description here. Attributes: finalized (bool): TODO: Type description here. paused (bool): Is mirroring paused. previous_view_name (string): View to be used as previous view. | MirrorParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MirrorParams:
"""Implementation of the 'MirrorParams' model. TODO: type description here. Attributes: finalized (bool): TODO: Type description here. paused (bool): Is mirroring paused. previous_view_name (string): View to be used as previous view."""
def __init__(self, finalized=None, paused... | stack_v2_sparse_classes_10k_train_001146 | 1,797 | permissive | [
{
"docstring": "Constructor for the MirrorParams class",
"name": "__init__",
"signature": "def __init__(self, finalized=None, paused=None, previous_view_name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation o... | 2 | null | Implement the Python class `MirrorParams` described below.
Class description:
Implementation of the 'MirrorParams' model. TODO: type description here. Attributes: finalized (bool): TODO: Type description here. paused (bool): Is mirroring paused. previous_view_name (string): View to be used as previous view.
Method si... | Implement the Python class `MirrorParams` described below.
Class description:
Implementation of the 'MirrorParams' model. TODO: type description here. Attributes: finalized (bool): TODO: Type description here. paused (bool): Is mirroring paused. previous_view_name (string): View to be used as previous view.
Method si... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class MirrorParams:
"""Implementation of the 'MirrorParams' model. TODO: type description here. Attributes: finalized (bool): TODO: Type description here. paused (bool): Is mirroring paused. previous_view_name (string): View to be used as previous view."""
def __init__(self, finalized=None, paused... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MirrorParams:
"""Implementation of the 'MirrorParams' model. TODO: type description here. Attributes: finalized (bool): TODO: Type description here. paused (bool): Is mirroring paused. previous_view_name (string): View to be used as previous view."""
def __init__(self, finalized=None, paused=None, previo... | the_stack_v2_python_sparse | cohesity_management_sdk/models/mirror_params.py | cohesity/management-sdk-python | train | 24 |
aae63d85692a785855c99db9fdba382ab24119eb | [
"count1 = 0\ncount2 = 0\ncount3 = 0\nfor i in range(len(nums)):\n if nums[i] == 0:\n count1 += 1\n elif nums[i] == 1:\n count2 += 1\n else:\n count3 += 1\nfor i in range(len(nums)):\n if i < count1:\n nums[i] = 0\n elif count1 <= i < count1 + count2:\n nums[i] = 1\n... | <|body_start_0|>
count1 = 0
count2 = 0
count3 = 0
for i in range(len(nums)):
if nums[i] == 0:
count1 += 1
elif nums[i] == 1:
count2 += 1
else:
count3 += 1
for i in range(len(nums)):
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors1(self, nums: List[int]) -> None:
"""单指针排序 :param nums: :return:"""
<|body_1|>
def sortColors2(self, nums: List[... | stack_v2_sparse_classes_10k_train_001147 | 2,482 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums: List[int]) -> None"
},
{
"docstring": "单指针排序 :param nums: :return:",
"name": "sortColors1",
"signature": "def sortColors1(self, nums: List[int]) -> None"... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def sortColors1(self, nums: List[int]) -> None: 单指针排序 :param nums: :return:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def sortColors1(self, nums: List[int]) -> None: 单指针排序 :param nums: :return:... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors1(self, nums: List[int]) -> None:
"""单指针排序 :param nums: :return:"""
<|body_1|>
def sortColors2(self, nums: List[... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def sortColors(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
count1 = 0
count2 = 0
count3 = 0
for i in range(len(nums)):
if nums[i] == 0:
count1 += 1
elif nums[i] == 1:
... | the_stack_v2_python_sparse | datastructure/array/SortColors.py | yinhuax/leet_code | train | 0 | |
4d2f34ae516b50bcbba723eda24108ad92f8ce14 | [
"if not board or len(board) != 9 or len(board[0]) != 9:\n return False\nfor i in range(9):\n rowFlag = set([])\n colFlag = set([])\n for j in range(9):\n if board[i][j] != '.':\n if board[i][j] in rowFlag:\n return False\n else:\n rowFlag.add(bo... | <|body_start_0|>
if not board or len(board) != 9 or len(board[0]) != 9:
return False
for i in range(9):
rowFlag = set([])
colFlag = set([])
for j in range(9):
if board[i][j] != '.':
if board[i][j] in rowFlag:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidSudoku(self, board):
""":type board: List[List[str]] :rtype: bool 暴力统计Sudoku的两个条件 1. 每一行每一列都不能有相同的数字 2. 每个3*3 的格子不能有相同的数字"""
<|body_0|>
def isValidSudoku2(self, board):
""":type board: List[List[str]] :rtype: bool 暴力统计Sudoku的两个条件 1. 每一行每一列都不能有相同的... | stack_v2_sparse_classes_10k_train_001148 | 2,678 | no_license | [
{
"docstring": ":type board: List[List[str]] :rtype: bool 暴力统计Sudoku的两个条件 1. 每一行每一列都不能有相同的数字 2. 每个3*3 的格子不能有相同的数字",
"name": "isValidSudoku",
"signature": "def isValidSudoku(self, board)"
},
{
"docstring": ":type board: List[List[str]] :rtype: bool 暴力统计Sudoku的两个条件 1. 每一行每一列都不能有相同的数字 2. 每个3*3 的格子不... | 2 | stack_v2_sparse_classes_30k_train_004748 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidSudoku(self, board): :type board: List[List[str]] :rtype: bool 暴力统计Sudoku的两个条件 1. 每一行每一列都不能有相同的数字 2. 每个3*3 的格子不能有相同的数字
- def isValidSudoku2(self, board): :type board: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidSudoku(self, board): :type board: List[List[str]] :rtype: bool 暴力统计Sudoku的两个条件 1. 每一行每一列都不能有相同的数字 2. 每个3*3 的格子不能有相同的数字
- def isValidSudoku2(self, board): :type board: ... | 96adb6c04c344e792e35dc70dc45eb76b5402008 | <|skeleton|>
class Solution:
def isValidSudoku(self, board):
""":type board: List[List[str]] :rtype: bool 暴力统计Sudoku的两个条件 1. 每一行每一列都不能有相同的数字 2. 每个3*3 的格子不能有相同的数字"""
<|body_0|>
def isValidSudoku2(self, board):
""":type board: List[List[str]] :rtype: bool 暴力统计Sudoku的两个条件 1. 每一行每一列都不能有相同的... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isValidSudoku(self, board):
""":type board: List[List[str]] :rtype: bool 暴力统计Sudoku的两个条件 1. 每一行每一列都不能有相同的数字 2. 每个3*3 的格子不能有相同的数字"""
if not board or len(board) != 9 or len(board[0]) != 9:
return False
for i in range(9):
rowFlag = set([])
... | the_stack_v2_python_sparse | JiQiang/leetcode_py/regular/ValidSudoku36.py | Hearen/AlgorithmHackers | train | 10 | |
cc878044d30b3563836322d6f429d72294c9dd17 | [
"request = current.request\nsettings = current.deployment_settings\nscope = 'profile'\nredirect_uri = '%s/%s/default/humanitarian_id/login' % (settings.get_base_public_url(), request.application)\nOAuthAccount.__init__(self, client_id=channel['id'], client_secret=channel['secret'], auth_url=self.AUTH_URL, token_url... | <|body_start_0|>
request = current.request
settings = current.deployment_settings
scope = 'profile'
redirect_uri = '%s/%s/default/humanitarian_id/login' % (settings.get_base_public_url(), request.application)
OAuthAccount.__init__(self, client_id=channel['id'], client_secret=chan... | OAuth implementation for Humanitarian.ID https://docs.google.com/document/d/1-FGDOo2BkhuclxqHcBjCprywZKE_wA6IFTbrs8W26i0 | HumanitarianIDAccount | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HumanitarianIDAccount:
"""OAuth implementation for Humanitarian.ID https://docs.google.com/document/d/1-FGDOo2BkhuclxqHcBjCprywZKE_wA6IFTbrs8W26i0"""
def __init__(self, channel):
"""Constructor @param channel: dict with Humanitarian.ID API credentials: {id=clientID, secret=clientSecr... | stack_v2_sparse_classes_10k_train_001149 | 31,965 | permissive | [
{
"docstring": "Constructor @param channel: dict with Humanitarian.ID API credentials: {id=clientID, secret=clientSecret}",
"name": "__init__",
"signature": "def __init__(self, channel)"
},
{
"docstring": "Build the url opener for managing HTTP Basic Authentication",
"name": "__build_url_ope... | 6 | null | Implement the Python class `HumanitarianIDAccount` described below.
Class description:
OAuth implementation for Humanitarian.ID https://docs.google.com/document/d/1-FGDOo2BkhuclxqHcBjCprywZKE_wA6IFTbrs8W26i0
Method signatures and docstrings:
- def __init__(self, channel): Constructor @param channel: dict with Humanit... | Implement the Python class `HumanitarianIDAccount` described below.
Class description:
OAuth implementation for Humanitarian.ID https://docs.google.com/document/d/1-FGDOo2BkhuclxqHcBjCprywZKE_wA6IFTbrs8W26i0
Method signatures and docstrings:
- def __init__(self, channel): Constructor @param channel: dict with Humanit... | 7ec4b959d009daf26d5ca6ce91dd9c3c0bd978d6 | <|skeleton|>
class HumanitarianIDAccount:
"""OAuth implementation for Humanitarian.ID https://docs.google.com/document/d/1-FGDOo2BkhuclxqHcBjCprywZKE_wA6IFTbrs8W26i0"""
def __init__(self, channel):
"""Constructor @param channel: dict with Humanitarian.ID API credentials: {id=clientID, secret=clientSecr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HumanitarianIDAccount:
"""OAuth implementation for Humanitarian.ID https://docs.google.com/document/d/1-FGDOo2BkhuclxqHcBjCprywZKE_wA6IFTbrs8W26i0"""
def __init__(self, channel):
"""Constructor @param channel: dict with Humanitarian.ID API credentials: {id=clientID, secret=clientSecret}"""
... | the_stack_v2_python_sparse | modules/core/aaa/oauth.py | nursix/drkcm | train | 3 |
a86b02581f06d22d5907fefdb2ff7bb64f911b59 | [
"pol, cov = (np.array(pol), np.array(cov))\nif cov.shape != (pol.size, pol.size):\n raise ValueError\nself.pol = pol\nself.deg = len(self.pol) - 1\nself.cov = cov\nself.covpol = np.zeros((2 * self.deg + 1,))\nfor i in range(self.deg + 1):\n for j in range(self.deg + 1):\n self.covpol[i + j] += self.cov... | <|body_start_0|>
pol, cov = (np.array(pol), np.array(cov))
if cov.shape != (pol.size, pol.size):
raise ValueError
self.pol = pol
self.deg = len(self.pol) - 1
self.cov = cov
self.covpol = np.zeros((2 * self.deg + 1,))
for i in range(self.deg + 1):
... | Store and evaluate polynomials with covariance matrix on their coefficients. | Polynomial | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Polynomial:
"""Store and evaluate polynomials with covariance matrix on their coefficients."""
def __init__(self, pol, cov):
"""Compute standard devation polynomial. Considering we have polynomial P(x) = \\sum_i a_i x^i, and \\sigma_ij the covariance of the i-th and j-th coefficients... | stack_v2_sparse_classes_10k_train_001150 | 35,535 | permissive | [
{
"docstring": "Compute standard devation polynomial. Considering we have polynomial P(x) = \\\\sum_i a_i x^i, and \\\\sigma_ij the covariance of the i-th and j-th coefficients, a_i and a_j, we compute \\\\sigma_f(x) = \\\\sqrt(\\\\sum_ij \\\\sigma_ij x^{i+j}) as the variance of the polynomial f evaluated at x.... | 2 | stack_v2_sparse_classes_30k_train_000589 | Implement the Python class `Polynomial` described below.
Class description:
Store and evaluate polynomials with covariance matrix on their coefficients.
Method signatures and docstrings:
- def __init__(self, pol, cov): Compute standard devation polynomial. Considering we have polynomial P(x) = \\sum_i a_i x^i, and \\... | Implement the Python class `Polynomial` described below.
Class description:
Store and evaluate polynomials with covariance matrix on their coefficients.
Method signatures and docstrings:
- def __init__(self, pol, cov): Compute standard devation polynomial. Considering we have polynomial P(x) = \\sum_i a_i x^i, and \\... | 99107a0d4935296b673f67469c1e2bd258954b9b | <|skeleton|>
class Polynomial:
"""Store and evaluate polynomials with covariance matrix on their coefficients."""
def __init__(self, pol, cov):
"""Compute standard devation polynomial. Considering we have polynomial P(x) = \\sum_i a_i x^i, and \\sigma_ij the covariance of the i-th and j-th coefficients... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Polynomial:
"""Store and evaluate polynomials with covariance matrix on their coefficients."""
def __init__(self, pol, cov):
"""Compute standard devation polynomial. Considering we have polynomial P(x) = \\sum_i a_i x^i, and \\sigma_ij the covariance of the i-th and j-th coefficients, a_i and a_j... | the_stack_v2_python_sparse | maths.py | yketa/active_work | train | 1 |
cf223f2937e86fe317e5b3706026fddc724017fd | [
"logging.Handler.__init__(self)\nif not isinstance(database, LogMaster) and (not isinstance(database, LogReadWrite)):\n raise TypeError('A LogMaster or LogReadWrite object must be specified. A {:} was specified instead'.format(type(database)))\nself.database_name = database.database_name\nself.write_log = databa... | <|body_start_0|>
logging.Handler.__init__(self)
if not isinstance(database, LogMaster) and (not isinstance(database, LogReadWrite)):
raise TypeError('A LogMaster or LogReadWrite object must be specified. A {:} was specified instead'.format(type(database)))
self.database_name = databa... | A handler class which writes logging records, appropriately formatted, to the a specified database's permanent log. This is used to simplify the log generation process with the use of the python "logging" package. | MongoLogHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MongoLogHandler:
"""A handler class which writes logging records, appropriately formatted, to the a specified database's permanent log. This is used to simplify the log generation process with the use of the python "logging" package."""
def __init__(self, database):
"""A LogMaster or... | stack_v2_sparse_classes_10k_train_001151 | 47,472 | no_license | [
{
"docstring": "A LogMaster or LogReadWrite object must be specified. The resulting handler object will have a 'database_name' attribute that can be used to identify the handler's destination.",
"name": "__init__",
"signature": "def __init__(self, database)"
},
{
"docstring": "If a formatter is ... | 2 | stack_v2_sparse_classes_30k_train_001979 | Implement the Python class `MongoLogHandler` described below.
Class description:
A handler class which writes logging records, appropriately formatted, to the a specified database's permanent log. This is used to simplify the log generation process with the use of the python "logging" package.
Method signatures and d... | Implement the Python class `MongoLogHandler` described below.
Class description:
A handler class which writes logging records, appropriately formatted, to the a specified database's permanent log. This is used to simplify the log generation process with the use of the python "logging" package.
Method signatures and d... | aab8f9789cb6d9b824836ffa4613b4b17d7d4df6 | <|skeleton|>
class MongoLogHandler:
"""A handler class which writes logging records, appropriately formatted, to the a specified database's permanent log. This is used to simplify the log generation process with the use of the python "logging" package."""
def __init__(self, database):
"""A LogMaster or... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MongoLogHandler:
"""A handler class which writes logging records, appropriately formatted, to the a specified database's permanent log. This is used to simplify the log generation process with the use of the python "logging" package."""
def __init__(self, database):
"""A LogMaster or LogReadWrite... | the_stack_v2_python_sparse | Drivers/Database/MongoDB.py | cdfredrick/AstroComb_HPF | train | 1 |
8a9d8c0c54737c212f044049372d30160d48e093 | [
"response_object = {'status': 'fail'}\nuser = UserModel.find_by_id(_id=user_id)\nif not user:\n return (response_object, 404)\nelse:\n response_object['status'] = 'success'\n response_object['current_time'] = int(time())\n response_object['confirmation'] = [each.json() for each in user.confirmation.orde... | <|body_start_0|>
response_object = {'status': 'fail'}
user = UserModel.find_by_id(_id=user_id)
if not user:
return (response_object, 404)
else:
response_object['status'] = 'success'
response_object['current_time'] = int(time())
response_obj... | ConfirmationByUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfirmationByUser:
def get(cls, user_id: int):
"""Returns confirmation for specific user"""
<|body_0|>
def post(cls, user_id: int):
"""Resend confirmation email"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
response_object = {'status': 'fail'}
... | stack_v2_sparse_classes_10k_train_001152 | 4,034 | no_license | [
{
"docstring": "Returns confirmation for specific user",
"name": "get",
"signature": "def get(cls, user_id: int)"
},
{
"docstring": "Resend confirmation email",
"name": "post",
"signature": "def post(cls, user_id: int)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003427 | Implement the Python class `ConfirmationByUser` described below.
Class description:
Implement the ConfirmationByUser class.
Method signatures and docstrings:
- def get(cls, user_id: int): Returns confirmation for specific user
- def post(cls, user_id: int): Resend confirmation email | Implement the Python class `ConfirmationByUser` described below.
Class description:
Implement the ConfirmationByUser class.
Method signatures and docstrings:
- def get(cls, user_id: int): Returns confirmation for specific user
- def post(cls, user_id: int): Resend confirmation email
<|skeleton|>
class ConfirmationBy... | 92bc183b6423ba41aa7d073ec83af2b585c54a40 | <|skeleton|>
class ConfirmationByUser:
def get(cls, user_id: int):
"""Returns confirmation for specific user"""
<|body_0|>
def post(cls, user_id: int):
"""Resend confirmation email"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConfirmationByUser:
def get(cls, user_id: int):
"""Returns confirmation for specific user"""
response_object = {'status': 'fail'}
user = UserModel.find_by_id(_id=user_id)
if not user:
return (response_object, 404)
else:
response_object['status'] ... | the_stack_v2_python_sparse | services/users/project/api/views/confirmations.py | jjason0/SupplyItCodeBase-1 | train | 0 | |
1f9abfc2b2e3389924d02d87ffc02caf2d3b2d71 | [
"if end not in bank:\n return -1\nqueue = deque([(start, 0)])\nvisited = set([start])\nwhile queue:\n v, step = queue.popleft()\n if v == end:\n return step\n for i in range(8):\n for c in 'ACGT':\n n = v[:i] + c + v[i + 1:]\n if n in bank and n not in visited:\n ... | <|body_start_0|>
if end not in bank:
return -1
queue = deque([(start, 0)])
visited = set([start])
while queue:
v, step = queue.popleft()
if v == end:
return step
for i in range(8):
for c in 'ACGT':
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minMutation(self, start, end, bank):
""":type start: str :type end: str :type bank: List[str] :rtype: int bfs思想,队列中保持每个遍历的有效字符串和其突变的基因个数元组,即(start, step)元组。类似走迷宫,四个方向就是可变的四 个字母"ACGT",当突变后的字符串在bank中就step+1,终止条件就是突变后的字符串==end。其中增加visited来保存已经遇到过的有效 突变字符串,以增加运算速度。 Runtime: 12 ... | stack_v2_sparse_classes_10k_train_001153 | 2,730 | no_license | [
{
"docstring": ":type start: str :type end: str :type bank: List[str] :rtype: int bfs思想,队列中保持每个遍历的有效字符串和其突变的基因个数元组,即(start, step)元组。类似走迷宫,四个方向就是可变的四 个字母\"ACGT\",当突变后的字符串在bank中就step+1,终止条件就是突变后的字符串==end。其中增加visited来保存已经遇到过的有效 突变字符串,以增加运算速度。 Runtime: 12 ms, faster than 88.32% of Python online submissions for Mini... | 2 | stack_v2_sparse_classes_30k_train_001769 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMutation(self, start, end, bank): :type start: str :type end: str :type bank: List[str] :rtype: int bfs思想,队列中保持每个遍历的有效字符串和其突变的基因个数元组,即(start, step)元组。类似走迷宫,四个方向就是可变的四 个字母"... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMutation(self, start, end, bank): :type start: str :type end: str :type bank: List[str] :rtype: int bfs思想,队列中保持每个遍历的有效字符串和其突变的基因个数元组,即(start, step)元组。类似走迷宫,四个方向就是可变的四 个字母"... | bad06f681d8d3f2b841cb3c8a969198b8643f864 | <|skeleton|>
class Solution:
def minMutation(self, start, end, bank):
""":type start: str :type end: str :type bank: List[str] :rtype: int bfs思想,队列中保持每个遍历的有效字符串和其突变的基因个数元组,即(start, step)元组。类似走迷宫,四个方向就是可变的四 个字母"ACGT",当突变后的字符串在bank中就step+1,终止条件就是突变后的字符串==end。其中增加visited来保存已经遇到过的有效 突变字符串,以增加运算速度。 Runtime: 12 ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minMutation(self, start, end, bank):
""":type start: str :type end: str :type bank: List[str] :rtype: int bfs思想,队列中保持每个遍历的有效字符串和其突变的基因个数元组,即(start, step)元组。类似走迷宫,四个方向就是可变的四 个字母"ACGT",当突变后的字符串在bank中就step+1,终止条件就是突变后的字符串==end。其中增加visited来保存已经遇到过的有效 突变字符串,以增加运算速度。 Runtime: 12 ms, faster tha... | the_stack_v2_python_sparse | 433_mini_genetic_mutation.py | subicWang/leetcode_aotang | train | 0 | |
00ad2569c7c6229910c2c772c714b517c0a9ad0a | [
"self.train_number = self.request.rel_url.query.get('train', None)\nif self.train_number:\n return web.HTTPMovedPermanently('/%s/train/%s' % (self.request.language, self.train_number))\nself.train_number = self.request.match_info.get('train')\nreturn await super(TrainView, self).get()",
"try:\n context = cf... | <|body_start_0|>
self.train_number = self.request.rel_url.query.get('train', None)
if self.train_number:
return web.HTTPMovedPermanently('/%s/train/%s' % (self.request.language, self.train_number))
self.train_number = self.request.match_info.get('train')
return await super(Tr... | Page that displays details about a specific train. | TrainView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainView:
"""Page that displays details about a specific train."""
async def get(self):
"""Reply to HTTP GET request."""
<|body_0|>
def context(self) -> dict:
"""Gets the context to render the template with. Returns: The context to pass to the template."""
... | stack_v2_sparse_classes_10k_train_001154 | 1,595 | no_license | [
{
"docstring": "Reply to HTTP GET request.",
"name": "get",
"signature": "async def get(self)"
},
{
"docstring": "Gets the context to render the template with. Returns: The context to pass to the template.",
"name": "context",
"signature": "def context(self) -> dict"
}
] | 2 | stack_v2_sparse_classes_30k_train_004069 | Implement the Python class `TrainView` described below.
Class description:
Page that displays details about a specific train.
Method signatures and docstrings:
- async def get(self): Reply to HTTP GET request.
- def context(self) -> dict: Gets the context to render the template with. Returns: The context to pass to t... | Implement the Python class `TrainView` described below.
Class description:
Page that displays details about a specific train.
Method signatures and docstrings:
- async def get(self): Reply to HTTP GET request.
- def context(self) -> dict: Gets the context to render the template with. Returns: The context to pass to t... | fc182e2f8bb45682361ac16befd2710f3492e65f | <|skeleton|>
class TrainView:
"""Page that displays details about a specific train."""
async def get(self):
"""Reply to HTTP GET request."""
<|body_0|>
def context(self) -> dict:
"""Gets the context to render the template with. Returns: The context to pass to the template."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TrainView:
"""Page that displays details about a specific train."""
async def get(self):
"""Reply to HTTP GET request."""
self.train_number = self.request.rel_url.query.get('train', None)
if self.train_number:
return web.HTTPMovedPermanently('/%s/train/%s' % (self.requ... | the_stack_v2_python_sparse | cfrweb/views/train.py | Photonios/cfr.ninja | train | 4 |
8d4a7674d4d269f5e27f8d2dc6d4868214ea8c9e | [
"self.buckets = 1000\nself.itemsPerBucket = 1001\nself.table = [[] for _ in range(self.buckets)]",
"if not self.contains(key):\n hashKey = key % self.buckets\n if len(self.table[hashKey]) <= 0:\n self.table[hashKey] = [False] * self.itemsPerBucket\n self.table[hashKey][key / self.buckets] = True",... | <|body_start_0|>
self.buckets = 1000
self.itemsPerBucket = 1001
self.table = [[] for _ in range(self.buckets)]
<|end_body_0|>
<|body_start_1|>
if not self.contains(key):
hashKey = key % self.buckets
if len(self.table[hashKey]) <= 0:
self.table[has... | MyHashSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyHashSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def add(self, key):
""":type key: int :rtype: None"""
<|body_1|>
def remove(self, key):
""":type key: int :rtype: None"""
<|body_2|>
def contains(se... | stack_v2_sparse_classes_10k_train_001155 | 1,333 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type key: int :rtype: None",
"name": "add",
"signature": "def add(self, key)"
},
{
"docstring": ":type key: int :rtype: None",
"name": "remove",
... | 4 | stack_v2_sparse_classes_30k_train_005300 | Implement the Python class `MyHashSet` described below.
Class description:
Implement the MyHashSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def add(self, key): :type key: int :rtype: None
- def remove(self, key): :type key: int :rtype: None
- def contains(s... | Implement the Python class `MyHashSet` described below.
Class description:
Implement the MyHashSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def add(self, key): :type key: int :rtype: None
- def remove(self, key): :type key: int :rtype: None
- def contains(s... | 58b65c4282c5ccd0f66ec670954973422f3b6afd | <|skeleton|>
class MyHashSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def add(self, key):
""":type key: int :rtype: None"""
<|body_1|>
def remove(self, key):
""":type key: int :rtype: None"""
<|body_2|>
def contains(se... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyHashSet:
def __init__(self):
"""Initialize your data structure here."""
self.buckets = 1000
self.itemsPerBucket = 1001
self.table = [[] for _ in range(self.buckets)]
def add(self, key):
""":type key: int :rtype: None"""
if not self.contains(key):
... | the_stack_v2_python_sparse | 20190131/705_Design_HashSet.py | zdsh/leetcode | train | 0 | |
a2027fc35fac278eedc0d6b16539ecf32c5ecaa2 | [
"super(FeatureNN, self).__init__()\nself._num_units = num_units\nself._dropout = dropout\nself._trainable = trainable\nself._tf_name_scope = name_scope\nself._feature_num = feature_num\nself._shallow = shallow\nself._activation = activation",
"self.hidden_layers = [ActivationLayer(self._num_units, trainable=self.... | <|body_start_0|>
super(FeatureNN, self).__init__()
self._num_units = num_units
self._dropout = dropout
self._trainable = trainable
self._tf_name_scope = name_scope
self._feature_num = feature_num
self._shallow = shallow
self._activation = activation
<|end_... | Neural Network model for each individual feature. Attributes: hidden_layers: A list containing hidden layers. The first layer is an `ActivationLayer` containing `num_units` neurons with specified `activation`. If `shallow` is False, then it additionally contains 2 tf.keras.layers.Dense ReLU layers with 64, 32 hidden un... | FeatureNN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureNN:
"""Neural Network model for each individual feature. Attributes: hidden_layers: A list containing hidden layers. The first layer is an `ActivationLayer` containing `num_units` neurons with specified `activation`. If `shallow` is False, then it additionally contains 2 tf.keras.layers.De... | stack_v2_sparse_classes_10k_train_001156 | 10,796 | permissive | [
{
"docstring": "Initializes FeatureNN hyperparameters. Args: num_units: Number of hidden units in first hidden layer. dropout: Coefficient for dropout regularization. trainable: Whether the FeatureNN parameters are trainable or not. shallow: If True, then a shallow network with a single hidden layer is created,... | 3 | null | Implement the Python class `FeatureNN` described below.
Class description:
Neural Network model for each individual feature. Attributes: hidden_layers: A list containing hidden layers. The first layer is an `ActivationLayer` containing `num_units` neurons with specified `activation`. If `shallow` is False, then it add... | Implement the Python class `FeatureNN` described below.
Class description:
Neural Network model for each individual feature. Attributes: hidden_layers: A list containing hidden layers. The first layer is an `ActivationLayer` containing `num_units` neurons with specified `activation`. If `shallow` is False, then it add... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class FeatureNN:
"""Neural Network model for each individual feature. Attributes: hidden_layers: A list containing hidden layers. The first layer is an `ActivationLayer` containing `num_units` neurons with specified `activation`. If `shallow` is False, then it additionally contains 2 tf.keras.layers.De... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FeatureNN:
"""Neural Network model for each individual feature. Attributes: hidden_layers: A list containing hidden layers. The first layer is an `ActivationLayer` containing `num_units` neurons with specified `activation`. If `shallow` is False, then it additionally contains 2 tf.keras.layers.Dense ReLU laye... | the_stack_v2_python_sparse | neural_additive_models/models.py | Ayoob7/google-research | train | 2 |
0749002de17f03cf3b1a6a207c0bd0c87cbcdbb9 | [
"raw_config = self.config.to_json()\nraw_config.type = self.config.type\nmap_dict = LossMappingDict()\nself.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_dict.params_mapping_dict).backend_mapping(raw_config)\nself._cls = ClassFactory.get_cls(ClassType.LOSS, self.map_config.type)",
"params = se... | <|body_start_0|>
raw_config = self.config.to_json()
raw_config.type = self.config.type
map_dict = LossMappingDict()
self.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_dict.params_mapping_dict).backend_mapping(raw_config)
self._cls = ClassFactory.get_cls(ClassT... | Register and call loss class. | Loss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Loss:
"""Register and call loss class."""
def __init__(self):
"""Initialize."""
<|body_0|>
def __call__(self):
"""Call loss cls."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
raw_config = self.config.to_json()
raw_config.type = self.co... | stack_v2_sparse_classes_10k_train_001157 | 2,539 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Call loss cls.",
"name": "__call__",
"signature": "def __call__(self)"
}
] | 2 | null | Implement the Python class `Loss` described below.
Class description:
Register and call loss class.
Method signatures and docstrings:
- def __init__(self): Initialize.
- def __call__(self): Call loss cls. | Implement the Python class `Loss` described below.
Class description:
Register and call loss class.
Method signatures and docstrings:
- def __init__(self): Initialize.
- def __call__(self): Call loss cls.
<|skeleton|>
class Loss:
"""Register and call loss class."""
def __init__(self):
"""Initialize.... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class Loss:
"""Register and call loss class."""
def __init__(self):
"""Initialize."""
<|body_0|>
def __call__(self):
"""Call loss cls."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Loss:
"""Register and call loss class."""
def __init__(self):
"""Initialize."""
raw_config = self.config.to_json()
raw_config.type = self.config.type
map_dict = LossMappingDict()
self.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_dict.params_map... | the_stack_v2_python_sparse | zeus/modules/loss/loss.py | huawei-noah/xingtian | train | 308 |
43f87fd7151725d032194be10f7a5313f44ff2de | [
"self.airgap_config = airgap_config\nself.cluster_id = cluster_id\nself.cluster_incarnation_id = cluster_incarnation_id\nself.current_operation = current_operation\nself.message = message\nself.name = name\nself.node_statuses = node_statuses\nself.removal_state = removal_state\nself.services_synced = services_synce... | <|body_start_0|>
self.airgap_config = airgap_config
self.cluster_id = cluster_id
self.cluster_incarnation_id = cluster_incarnation_id
self.current_operation = current_operation
self.message = message
self.name = name
self.node_statuses = node_statuses
self... | Implementation of the 'ClusterStatusResult' model. Specifies the result of getting the status of a Cluster. Attributes: airgap_config (AirgapConfig): Specifies Airgap config cluster_id (long|int): Specifies the ID of the Cluster. cluster_incarnation_id (long|int): Specifies the incarnation ID of the Cluster. current_op... | ClusterStatusResult | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterStatusResult:
"""Implementation of the 'ClusterStatusResult' model. Specifies the result of getting the status of a Cluster. Attributes: airgap_config (AirgapConfig): Specifies Airgap config cluster_id (long|int): Specifies the ID of the Cluster. cluster_incarnation_id (long|int): Specifie... | stack_v2_sparse_classes_10k_train_001158 | 10,055 | permissive | [
{
"docstring": "Constructor for the ClusterStatusResult class",
"name": "__init__",
"signature": "def __init__(self, airgap_config=None, cluster_id=None, cluster_incarnation_id=None, current_operation=None, message=None, name=None, node_statuses=None, removal_state=None, services_synced=None, software_v... | 2 | null | Implement the Python class `ClusterStatusResult` described below.
Class description:
Implementation of the 'ClusterStatusResult' model. Specifies the result of getting the status of a Cluster. Attributes: airgap_config (AirgapConfig): Specifies Airgap config cluster_id (long|int): Specifies the ID of the Cluster. clus... | Implement the Python class `ClusterStatusResult` described below.
Class description:
Implementation of the 'ClusterStatusResult' model. Specifies the result of getting the status of a Cluster. Attributes: airgap_config (AirgapConfig): Specifies Airgap config cluster_id (long|int): Specifies the ID of the Cluster. clus... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ClusterStatusResult:
"""Implementation of the 'ClusterStatusResult' model. Specifies the result of getting the status of a Cluster. Attributes: airgap_config (AirgapConfig): Specifies Airgap config cluster_id (long|int): Specifies the ID of the Cluster. cluster_incarnation_id (long|int): Specifie... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClusterStatusResult:
"""Implementation of the 'ClusterStatusResult' model. Specifies the result of getting the status of a Cluster. Attributes: airgap_config (AirgapConfig): Specifies Airgap config cluster_id (long|int): Specifies the ID of the Cluster. cluster_incarnation_id (long|int): Specifies the incarna... | the_stack_v2_python_sparse | cohesity_management_sdk/models/cluster_status_result.py | cohesity/management-sdk-python | train | 24 |
130ee80c384f85d2dc8d0e6909bad75f629f5641 | [
"self.log = logging.getLogger('lapis.vidme')\nself.useragent = useragent\nself.username = vidme_user\nself.password = vidme_password\nself.headers = {'User-Agent': self.useragent}",
"self.log.info('Logging into vid.me with username %s...', self.username)\nresponse = requests.post('https://api.vid.me/auth/create',... | <|body_start_0|>
self.log = logging.getLogger('lapis.vidme')
self.useragent = useragent
self.username = vidme_user
self.password = vidme_password
self.headers = {'User-Agent': self.useragent}
<|end_body_0|>
<|body_start_1|>
self.log.info('Logging into vid.me with usernam... | A vid.me export plugin. Here's where magic turns to sorcery. Will upload a single video (currently supported via tumblr). You must have a vid.me account for this to be used. | VidmePlugin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VidmePlugin:
"""A vid.me export plugin. Here's where magic turns to sorcery. Will upload a single video (currently supported via tumblr). You must have a vid.me account for this to be used."""
def __init__(self, useragent: str, vidme_user: str='', vidme_password: str='', **options):
... | stack_v2_sparse_classes_10k_train_001159 | 5,786 | permissive | [
{
"docstring": "Initialize the vid.me export API. :param useragent: The useragent to use for the vid.me API. :param vidme_user: The username with which to login to vid.me :param vidme_password: The password with which to login to vid.me :param options: Other passed options. Unused.",
"name": "__init__",
... | 4 | stack_v2_sparse_classes_30k_train_004586 | Implement the Python class `VidmePlugin` described below.
Class description:
A vid.me export plugin. Here's where magic turns to sorcery. Will upload a single video (currently supported via tumblr). You must have a vid.me account for this to be used.
Method signatures and docstrings:
- def __init__(self, useragent: s... | Implement the Python class `VidmePlugin` described below.
Class description:
A vid.me export plugin. Here's where magic turns to sorcery. Will upload a single video (currently supported via tumblr). You must have a vid.me account for this to be used.
Method signatures and docstrings:
- def __init__(self, useragent: s... | 29503bb70b7b9e47a5cea1ea03098543b1a01efb | <|skeleton|>
class VidmePlugin:
"""A vid.me export plugin. Here's where magic turns to sorcery. Will upload a single video (currently supported via tumblr). You must have a vid.me account for this to be used."""
def __init__(self, useragent: str, vidme_user: str='', vidme_password: str='', **options):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VidmePlugin:
"""A vid.me export plugin. Here's where magic turns to sorcery. Will upload a single video (currently supported via tumblr). You must have a vid.me account for this to be used."""
def __init__(self, useragent: str, vidme_user: str='', vidme_password: str='', **options):
"""Initialize... | the_stack_v2_python_sparse | plugins/vidme.py | spiral6/VelvetBot | train | 0 |
452abf09f69370ec9fb99d01c3ed7b5dc37a26ce | [
"a = '1'\nfor _ in range(1, n):\n a_next = []\n i = 0\n while i < len(a):\n dig = a[i]\n j = 1\n while i + j < len(a):\n if a[i + j] == dig:\n j += 1\n else:\n break\n a_next += [str(j), dig]\n i += j\n a = ''.join(a_... | <|body_start_0|>
a = '1'
for _ in range(1, n):
a_next = []
i = 0
while i < len(a):
dig = a[i]
j = 1
while i + j < len(a):
if a[i + j] == dig:
j += 1
else:
... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countAndSay1(self, n):
"""direct loop"""
<|body_0|>
def countAndSay2(self, n):
"""recursive"""
<|body_1|>
def generating_digits(self, a):
"""recursive main program"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
a ... | stack_v2_sparse_classes_10k_train_001160 | 2,178 | permissive | [
{
"docstring": "direct loop",
"name": "countAndSay1",
"signature": "def countAndSay1(self, n)"
},
{
"docstring": "recursive",
"name": "countAndSay2",
"signature": "def countAndSay2(self, n)"
},
{
"docstring": "recursive main program",
"name": "generating_digits",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_005621 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countAndSay1(self, n): direct loop
- def countAndSay2(self, n): recursive
- def generating_digits(self, a): recursive main program | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countAndSay1(self, n): direct loop
- def countAndSay2(self, n): recursive
- def generating_digits(self, a): recursive main program
<|skeleton|>
class Solution:
def coun... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def countAndSay1(self, n):
"""direct loop"""
<|body_0|>
def countAndSay2(self, n):
"""recursive"""
<|body_1|>
def generating_digits(self, a):
"""recursive main program"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def countAndSay1(self, n):
"""direct loop"""
a = '1'
for _ in range(1, n):
a_next = []
i = 0
while i < len(a):
dig = a[i]
j = 1
while i + j < len(a):
if a[i + j] == dig:
... | the_stack_v2_python_sparse | leetcode/0038_count_and_say.py | chaosWsF/Python-Practice | train | 1 | |
f71043721417d00212bc58287a844aacdc4aca5b | [
"if not self.instance:\n raise RuntimeError('Manager method should be called: instance.images.get_or_download()')\nimage = Image.objects.get_image_from_url(url=url)\nif image.id:\n image_link = self.get_or_create(image=image, object_id=self.instance.id, content_type=ContentType.objects.get_for_model(self.inst... | <|body_start_0|>
if not self.instance:
raise RuntimeError('Manager method should be called: instance.images.get_or_download()')
image = Image.objects.get_image_from_url(url=url)
if image.id:
image_link = self.get_or_create(image=image, object_id=self.instance.id, content_... | ImageLinkManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageLinkManager:
def get_or_download(self, url, **kwargs):
"""Try to get already downloaded or download image using self.download() method Return tuple with image_link instance and boolean flag equal True if image was downloaded"""
<|body_0|>
def download(self, url, **kwarg... | stack_v2_sparse_classes_10k_train_001161 | 5,904 | permissive | [
{
"docstring": "Try to get already downloaded or download image using self.download() method Return tuple with image_link instance and boolean flag equal True if image was downloaded",
"name": "get_or_download",
"signature": "def get_or_download(self, url, **kwargs)"
},
{
"docstring": "Download ... | 2 | stack_v2_sparse_classes_30k_train_000912 | Implement the Python class `ImageLinkManager` described below.
Class description:
Implement the ImageLinkManager class.
Method signatures and docstrings:
- def get_or_download(self, url, **kwargs): Try to get already downloaded or download image using self.download() method Return tuple with image_link instance and b... | Implement the Python class `ImageLinkManager` described below.
Class description:
Implement the ImageLinkManager class.
Method signatures and docstrings:
- def get_or_download(self, url, **kwargs): Try to get already downloaded or download image using self.download() method Return tuple with image_link instance and b... | c393dc8c2d59dc99aa2c3314d3372b6e2bf5497f | <|skeleton|>
class ImageLinkManager:
def get_or_download(self, url, **kwargs):
"""Try to get already downloaded or download image using self.download() method Return tuple with image_link instance and boolean flag equal True if image was downloaded"""
<|body_0|>
def download(self, url, **kwarg... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImageLinkManager:
def get_or_download(self, url, **kwargs):
"""Try to get already downloaded or download image using self.download() method Return tuple with image_link instance and boolean flag equal True if image was downloaded"""
if not self.instance:
raise RuntimeError('Manager... | the_stack_v2_python_sparse | cinemanio/images/models.py | cinemanio/backend | train | 4 | |
976ef4a4e02f900221e023f10dda42e190459cf7 | [
"BaseNet.__init__(self, name=name)\nself.global_net = INetAffine(decay=decay, affine_w_initializer=affine_w_initializer, affine_b_initializer=affine_b_initializer, acti_func=acti_func, name='inet-global')\nself.local_net = INetDense(decay=decay, disp_w_initializer=disp_w_initializer, disp_b_initializer=disp_b_initi... | <|body_start_0|>
BaseNet.__init__(self, name=name)
self.global_net = INetAffine(decay=decay, affine_w_initializer=affine_w_initializer, affine_b_initializer=affine_b_initializer, acti_func=acti_func, name='inet-global')
self.local_net = INetDense(decay=decay, disp_w_initializer=disp_w_initialize... | ### Description Re-implementation of the registration network proposed in: Hu et al., Label-driven weakly-supervised learning for multimodal deformable image registration, arXiv:1711.01666 https://arxiv.org/abs/1711.01666 Hu et al., Weakly-Supervised Convolutional Neural Networks for Multimodal Image Registration, Medi... | INetHybridPreWarp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class INetHybridPreWarp:
"""### Description Re-implementation of the registration network proposed in: Hu et al., Label-driven weakly-supervised learning for multimodal deformable image registration, arXiv:1711.01666 https://arxiv.org/abs/1711.01666 Hu et al., Weakly-Supervised Convolutional Neural Net... | stack_v2_sparse_classes_10k_train_001162 | 7,784 | permissive | [
{
"docstring": ":param decay: float, regularisation decay :param affine_w_initializer: weight initialisation for affine registration network :param affine_b_initializer: bias initialisation for affine registration network :param disp_w_initializer: weight initialisation for dense registration network :param dis... | 2 | stack_v2_sparse_classes_30k_train_004219 | Implement the Python class `INetHybridPreWarp` described below.
Class description:
### Description Re-implementation of the registration network proposed in: Hu et al., Label-driven weakly-supervised learning for multimodal deformable image registration, arXiv:1711.01666 https://arxiv.org/abs/1711.01666 Hu et al., Wea... | Implement the Python class `INetHybridPreWarp` described below.
Class description:
### Description Re-implementation of the registration network proposed in: Hu et al., Label-driven weakly-supervised learning for multimodal deformable image registration, arXiv:1711.01666 https://arxiv.org/abs/1711.01666 Hu et al., Wea... | 67db048685705e36622bc2851b4c7794e56065ad | <|skeleton|>
class INetHybridPreWarp:
"""### Description Re-implementation of the registration network proposed in: Hu et al., Label-driven weakly-supervised learning for multimodal deformable image registration, arXiv:1711.01666 https://arxiv.org/abs/1711.01666 Hu et al., Weakly-Supervised Convolutional Neural Net... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class INetHybridPreWarp:
"""### Description Re-implementation of the registration network proposed in: Hu et al., Label-driven weakly-supervised learning for multimodal deformable image registration, arXiv:1711.01666 https://arxiv.org/abs/1711.01666 Hu et al., Weakly-Supervised Convolutional Neural Networks for Mul... | the_stack_v2_python_sparse | niftynet/network/interventional_hybrid_net.py | BRAINSia/NiftyNet | train | 0 |
0ade7ff3a4375de4aa53f5b86599052a7db04930 | [
"self._request_context = request_context\nself._request = request\nself._scalars_plugin_instance = scalars_plugin_instance\nself._experiment = experiment",
"run, tag = metrics.run_tag_from_session_and_metric(self._request.session_name, self._request.metric_name)\nbody, _ = self._scalars_plugin_instance.scalars_im... | <|body_start_0|>
self._request_context = request_context
self._request = request
self._scalars_plugin_instance = scalars_plugin_instance
self._experiment = experiment
<|end_body_0|>
<|body_start_1|>
run, tag = metrics.run_tag_from_session_and_metric(self._request.session_name, s... | Handles a ListMetricEvals request. | Handler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Handler:
"""Handles a ListMetricEvals request."""
def __init__(self, request_context, request, scalars_plugin_instance, experiment):
"""Constructor. Args: request_context: A tensorboard.context.RequestContext. request: A ListSessionGroupsRequest protobuf. scalars_plugin_instance: A s... | stack_v2_sparse_classes_10k_train_001163 | 2,132 | permissive | [
{
"docstring": "Constructor. Args: request_context: A tensorboard.context.RequestContext. request: A ListSessionGroupsRequest protobuf. scalars_plugin_instance: A scalars_plugin.ScalarsPlugin. experiment: A experiment ID, as a possibly-empty `str`.",
"name": "__init__",
"signature": "def __init__(self, ... | 2 | stack_v2_sparse_classes_30k_train_000015 | Implement the Python class `Handler` described below.
Class description:
Handles a ListMetricEvals request.
Method signatures and docstrings:
- def __init__(self, request_context, request, scalars_plugin_instance, experiment): Constructor. Args: request_context: A tensorboard.context.RequestContext. request: A ListSe... | Implement the Python class `Handler` described below.
Class description:
Handles a ListMetricEvals request.
Method signatures and docstrings:
- def __init__(self, request_context, request, scalars_plugin_instance, experiment): Constructor. Args: request_context: A tensorboard.context.RequestContext. request: A ListSe... | 5961c76dca0fb9bb40d146f5ce13834ac29d8ddb | <|skeleton|>
class Handler:
"""Handles a ListMetricEvals request."""
def __init__(self, request_context, request, scalars_plugin_instance, experiment):
"""Constructor. Args: request_context: A tensorboard.context.RequestContext. request: A ListSessionGroupsRequest protobuf. scalars_plugin_instance: A s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Handler:
"""Handles a ListMetricEvals request."""
def __init__(self, request_context, request, scalars_plugin_instance, experiment):
"""Constructor. Args: request_context: A tensorboard.context.RequestContext. request: A ListSessionGroupsRequest protobuf. scalars_plugin_instance: A scalars_plugin... | the_stack_v2_python_sparse | tensorboard/plugins/hparams/list_metric_evals.py | tensorflow/tensorboard | train | 6,766 |
c9f563abf840c3ebb0a8a297798ed6739ccf4414 | [
"super().__init__()\nself._truncated_mode = truncated_mode\nself._truncated_length_left = truncated_length_left\nself._truncated_length_right = truncated_length_right\nif self._truncated_length_left:\n self._left_truncatedlength_unit = units.TruncatedLength(self._truncated_length_left, self._truncated_mode)\nif ... | <|body_start_0|>
super().__init__()
self._truncated_mode = truncated_mode
self._truncated_length_left = truncated_length_left
self._truncated_length_right = truncated_length_right
if self._truncated_length_left:
self._left_truncatedlength_unit = units.TruncatedLength(... | Baisc preprocessor helper. :param truncated_mode: String, mode used by :class:`TruncatedLength`. Can be 'pre' or 'post'. :param truncated_length_left: Integer, maximize length of :attr:`left` in the data_pack. :param truncated_length_right: Integer, maximize length of :attr:`right` in the data_pack. :param filter_mode:... | BasicPreprocessor | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicPreprocessor:
"""Baisc preprocessor helper. :param truncated_mode: String, mode used by :class:`TruncatedLength`. Can be 'pre' or 'post'. :param truncated_length_left: Integer, maximize length of :attr:`left` in the data_pack. :param truncated_length_right: Integer, maximize length of :attr:... | stack_v2_sparse_classes_10k_train_001164 | 6,828 | permissive | [
{
"docstring": "Initialization.",
"name": "__init__",
"signature": "def __init__(self, truncated_mode: str='pre', truncated_length_left: int=None, truncated_length_right: int=None, filter_mode: str='df', filter_low_freq: float=1, filter_high_freq: float=float('inf'), remove_stop_words: bool=False, ngram... | 3 | stack_v2_sparse_classes_30k_train_002309 | Implement the Python class `BasicPreprocessor` described below.
Class description:
Baisc preprocessor helper. :param truncated_mode: String, mode used by :class:`TruncatedLength`. Can be 'pre' or 'post'. :param truncated_length_left: Integer, maximize length of :attr:`left` in the data_pack. :param truncated_length_ri... | Implement the Python class `BasicPreprocessor` described below.
Class description:
Baisc preprocessor helper. :param truncated_mode: String, mode used by :class:`TruncatedLength`. Can be 'pre' or 'post'. :param truncated_length_left: Integer, maximize length of :attr:`left` in the data_pack. :param truncated_length_ri... | 4198ebce942f4afe7ddca6a96ab6f4464ade4518 | <|skeleton|>
class BasicPreprocessor:
"""Baisc preprocessor helper. :param truncated_mode: String, mode used by :class:`TruncatedLength`. Can be 'pre' or 'post'. :param truncated_length_left: Integer, maximize length of :attr:`left` in the data_pack. :param truncated_length_right: Integer, maximize length of :attr:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BasicPreprocessor:
"""Baisc preprocessor helper. :param truncated_mode: String, mode used by :class:`TruncatedLength`. Can be 'pre' or 'post'. :param truncated_length_left: Integer, maximize length of :attr:`left` in the data_pack. :param truncated_length_right: Integer, maximize length of :attr:`right` in th... | the_stack_v2_python_sparse | poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/preprocessors/basic_preprocessor.py | microsoft/ContextualSP | train | 332 |
897fdbe53e5e28a8bd8d7101b59c1625d47c2f80 | [
"super().__init__(*args, **kwargs)\nself.model_dir: str = model_dir\nfrom .common import Filter\nself._transforms = [Filter(reserved_keys=['input', 'target'])]",
"for t in self._transforms:\n data = t(data)\nreturn data"
] | <|body_start_0|>
super().__init__(*args, **kwargs)
self.model_dir: str = model_dir
from .common import Filter
self._transforms = [Filter(reserved_keys=['input', 'target'])]
<|end_body_0|>
<|body_start_1|>
for t in self._transforms:
data = t(data)
return data
... | ImageDenoisePreprocessor | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageDenoisePreprocessor:
def __init__(self, model_dir: str, *args, **kwargs):
"""Args: model_dir (str): model path"""
<|body_0|>
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""process the raw input data Args: data Dict[str, Any] Returns: Dict[str, An... | stack_v2_sparse_classes_10k_train_001165 | 8,906 | permissive | [
{
"docstring": "Args: model_dir (str): model path",
"name": "__init__",
"signature": "def __init__(self, model_dir: str, *args, **kwargs)"
},
{
"docstring": "process the raw input data Args: data Dict[str, Any] Returns: Dict[str, Any]: the preprocessed data",
"name": "__call__",
"signatu... | 2 | null | Implement the Python class `ImageDenoisePreprocessor` described below.
Class description:
Implement the ImageDenoisePreprocessor class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): Args: model_dir (str): model path
- def __call__(self, data: Dict[str, Any]) -> Dict[str, Any... | Implement the Python class `ImageDenoisePreprocessor` described below.
Class description:
Implement the ImageDenoisePreprocessor class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): Args: model_dir (str): model path
- def __call__(self, data: Dict[str, Any]) -> Dict[str, Any... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class ImageDenoisePreprocessor:
def __init__(self, model_dir: str, *args, **kwargs):
"""Args: model_dir (str): model path"""
<|body_0|>
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""process the raw input data Args: data Dict[str, Any] Returns: Dict[str, An... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImageDenoisePreprocessor:
def __init__(self, model_dir: str, *args, **kwargs):
"""Args: model_dir (str): model path"""
super().__init__(*args, **kwargs)
self.model_dir: str = model_dir
from .common import Filter
self._transforms = [Filter(reserved_keys=['input', 'target... | the_stack_v2_python_sparse | ai/modelscope/modelscope/preprocessors/image.py | alldatacenter/alldata | train | 774 | |
fdda69ad1936bf4ab96633eab342d3d044c13bbe | [
"self.bucket_info = bucket_info\nself.cluster_info = cluster_info\nself.name = name\nself.mtype = mtype\nself.uuid = uuid",
"if dictionary is None:\n return None\nbucket_info = cohesity_management_sdk.models.couchbase_bucket.CouchbaseBucket.from_dictionary(dictionary.get('bucketInfo')) if dictionary.get('bucke... | <|body_start_0|>
self.bucket_info = bucket_info
self.cluster_info = cluster_info
self.name = name
self.mtype = mtype
self.uuid = uuid
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
bucket_info = cohesity_management_sdk.models.couch... | Implementation of the 'CouchbaseProtectionSource' model. Specifies an Object representing Couchbase. Attributes: bucket_info (CouchbaseBucket): Information of a Couchbase Bucket, only valid for an entity of type kBucket. cluster_info (CouchbaseCluster): Information of a couchbase cluster, only valid for an entity of ty... | CouchbaseProtectionSource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CouchbaseProtectionSource:
"""Implementation of the 'CouchbaseProtectionSource' model. Specifies an Object representing Couchbase. Attributes: bucket_info (CouchbaseBucket): Information of a Couchbase Bucket, only valid for an entity of type kBucket. cluster_info (CouchbaseCluster): Information o... | stack_v2_sparse_classes_10k_train_001166 | 3,036 | permissive | [
{
"docstring": "Constructor for the CouchbaseProtectionSource class",
"name": "__init__",
"signature": "def __init__(self, bucket_info=None, cluster_info=None, name=None, mtype=None, uuid=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary):... | 2 | null | Implement the Python class `CouchbaseProtectionSource` described below.
Class description:
Implementation of the 'CouchbaseProtectionSource' model. Specifies an Object representing Couchbase. Attributes: bucket_info (CouchbaseBucket): Information of a Couchbase Bucket, only valid for an entity of type kBucket. cluster... | Implement the Python class `CouchbaseProtectionSource` described below.
Class description:
Implementation of the 'CouchbaseProtectionSource' model. Specifies an Object representing Couchbase. Attributes: bucket_info (CouchbaseBucket): Information of a Couchbase Bucket, only valid for an entity of type kBucket. cluster... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CouchbaseProtectionSource:
"""Implementation of the 'CouchbaseProtectionSource' model. Specifies an Object representing Couchbase. Attributes: bucket_info (CouchbaseBucket): Information of a Couchbase Bucket, only valid for an entity of type kBucket. cluster_info (CouchbaseCluster): Information o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CouchbaseProtectionSource:
"""Implementation of the 'CouchbaseProtectionSource' model. Specifies an Object representing Couchbase. Attributes: bucket_info (CouchbaseBucket): Information of a Couchbase Bucket, only valid for an entity of type kBucket. cluster_info (CouchbaseCluster): Information of a couchbase... | the_stack_v2_python_sparse | cohesity_management_sdk/models/couchbase_protection_source.py | cohesity/management-sdk-python | train | 24 |
9649de1fa39eeba6ff22ee66fe7f8285b650c110 | [
"if not args_lateral:\n args_lateral = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}\nif not args_longitudinal:\n args_longitudinal = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}\nself.node = node\nself._lon_controller = PIDLongitudinalController(**args_longitudinal)\nself._lat_controller = PIDLateralController(**args_lateral... | <|body_start_0|>
if not args_lateral:
args_lateral = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}
if not args_longitudinal:
args_longitudinal = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}
self.node = node
self._lon_controller = PIDLongitudinalController(**args_longitudinal)
... | VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side | VehiclePIDController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VehiclePIDController:
"""VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side"""
def __init__(self, node, args_lateral=None, args_longitudinal=None):
""":param vehicle: actor to apply to ... | stack_v2_sparse_classes_10k_train_001167 | 6,324 | permissive | [
{
"docstring": ":param vehicle: actor to apply to local planner logic onto :param args_lateral: dictionary of arguments to set the lateral PID controller using the following semantics: K_P -- Proportional term K_D -- Differential term K_I -- Integral term :param args_longitudinal: dictionary of arguments to set... | 2 | stack_v2_sparse_classes_30k_train_004974 | Implement the Python class `VehiclePIDController` described below.
Class description:
VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side
Method signatures and docstrings:
- def __init__(self, node, args_lateral=None, ar... | Implement the Python class `VehiclePIDController` described below.
Class description:
VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side
Method signatures and docstrings:
- def __init__(self, node, args_lateral=None, ar... | e9063d97ff5a724f76adbb1b852dc71da1dcfeec | <|skeleton|>
class VehiclePIDController:
"""VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side"""
def __init__(self, node, args_lateral=None, args_longitudinal=None):
""":param vehicle: actor to apply to ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VehiclePIDController:
"""VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side"""
def __init__(self, node, args_lateral=None, args_longitudinal=None):
""":param vehicle: actor to apply to local planner... | the_stack_v2_python_sparse | carla_ad_agent/src/carla_ad_agent/vehicle_pid_controller.py | carla-simulator/ros-bridge | train | 448 |
d6e7cf3c9edf18bd33d7f270bdd6482b06c36740 | [
"if not l1 or not l2:\n return l1 or l2\nif l1.val <= l2.val:\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1\nelse:\n l2.next = self.mergeTwoLists(l1, l2.next)\n return l2",
"dummy = ListNode(0)\nlast = dummy\nwhile l1 and l2:\n if l1.val <= l2.val:\n last.next = l1\n l1 =... | <|body_start_0|>
if not l1 or not l2:
return l1 or l2
if l1.val <= l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
<|end_body_0|>
<|body_start_1|>
dummy = Li... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists_v1(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
def mergeTwoLists_v0(self, l1, ... | stack_v2_sparse_classes_10k_train_001168 | 3,475 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists_v1",
"signature": "def mergeTwoLists_v1(self... | 3 | stack_v2_sparse_classes_30k_train_006588 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists_v1(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists_v1(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNo... | b5e09f24e8e96454dc99e20281e853fb9fcc85ed | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists_v1(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
def mergeTwoLists_v0(self, l1, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
if not l1 or not l2:
return l1 or l2
if l1.val <= l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = ... | the_stack_v2_python_sparse | python/21_Merge_Two_Sorted_Lists.py | Moby5/myleetcode | train | 2 | |
bf2d31d8dd13d7c1bc6c3cbef8dd6300cb327961 | [
"if data_type == 'mel' or data_type == 'scatter':\n self.data_type = data_type\nelse:\n raise ValueError(\"data_type must be 'mel' or 'scatter'.\")",
"if self.data_type == 'mel':\n mean = 2.3779549598693848\nelif self.data_type == 'scatter':\n mean = 0.21285544335842133\nif 'data' in sample:\n key ... | <|body_start_0|>
if data_type == 'mel' or data_type == 'scatter':
self.data_type = data_type
else:
raise ValueError("data_type must be 'mel' or 'scatter'.")
<|end_body_0|>
<|body_start_1|>
if self.data_type == 'mel':
mean = 2.3779549598693848
elif sel... | Subtract mean from audio input. | SubtractMean | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubtractMean:
"""Subtract mean from audio input."""
def __init__(self, data_type):
"""Initialize SubtractMean."""
<|body_0|>
def __call__(self, sample):
"""Subtract the appropriate mean from the sample data."""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_10k_train_001169 | 1,433 | no_license | [
{
"docstring": "Initialize SubtractMean.",
"name": "__init__",
"signature": "def __init__(self, data_type)"
},
{
"docstring": "Subtract the appropriate mean from the sample data.",
"name": "__call__",
"signature": "def __call__(self, sample)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004802 | Implement the Python class `SubtractMean` described below.
Class description:
Subtract mean from audio input.
Method signatures and docstrings:
- def __init__(self, data_type): Initialize SubtractMean.
- def __call__(self, sample): Subtract the appropriate mean from the sample data. | Implement the Python class `SubtractMean` described below.
Class description:
Subtract mean from audio input.
Method signatures and docstrings:
- def __init__(self, data_type): Initialize SubtractMean.
- def __call__(self, sample): Subtract the appropriate mean from the sample data.
<|skeleton|>
class SubtractMean:
... | 55a62c62d26534f3f1a0d7d529cc79d4796680a1 | <|skeleton|>
class SubtractMean:
"""Subtract mean from audio input."""
def __init__(self, data_type):
"""Initialize SubtractMean."""
<|body_0|>
def __call__(self, sample):
"""Subtract the appropriate mean from the sample data."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SubtractMean:
"""Subtract mean from audio input."""
def __init__(self, data_type):
"""Initialize SubtractMean."""
if data_type == 'mel' or data_type == 'scatter':
self.data_type = data_type
else:
raise ValueError("data_type must be 'mel' or 'scatter'.")
... | the_stack_v2_python_sparse | dc/datasets/transforms.py | yamato2199/DeepContentRecommenders | train | 1 |
4b34d4fdbf315181bd2dad599f5c6445659aa7a7 | [
"self.language = self.language.casefold()\nif self.region is not None:\n self.region = self.region.upper()",
"if not is_language_match(self.language, dialect.language):\n return (-1, 0)\nis_exact_language = self.language == dialect.language\nif self.region is None and dialect.region is None:\n return (2 ... | <|body_start_0|>
self.language = self.language.casefold()
if self.region is not None:
self.region = self.region.upper()
<|end_body_0|>
<|body_start_1|>
if not is_language_match(self.language, dialect.language):
return (-1, 0)
is_exact_language = self.language == ... | Language with optional region and script/code. | Dialect | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dialect:
"""Language with optional region and script/code."""
def __post_init__(self) -> None:
"""Fix casing of language/region."""
<|body_0|>
def score(self, dialect: Dialect, country: str | None=None) -> tuple[float, float]:
"""Return score for match with anoth... | stack_v2_sparse_classes_10k_train_001170 | 5,648 | permissive | [
{
"docstring": "Fix casing of language/region.",
"name": "__post_init__",
"signature": "def __post_init__(self) -> None"
},
{
"docstring": "Return score for match with another dialect where higher is better. Score < 0 indicates a failure to match.",
"name": "score",
"signature": "def sco... | 3 | null | Implement the Python class `Dialect` described below.
Class description:
Language with optional region and script/code.
Method signatures and docstrings:
- def __post_init__(self) -> None: Fix casing of language/region.
- def score(self, dialect: Dialect, country: str | None=None) -> tuple[float, float]: Return score... | Implement the Python class `Dialect` described below.
Class description:
Language with optional region and script/code.
Method signatures and docstrings:
- def __post_init__(self) -> None: Fix casing of language/region.
- def score(self, dialect: Dialect, country: str | None=None) -> tuple[float, float]: Return score... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class Dialect:
"""Language with optional region and script/code."""
def __post_init__(self) -> None:
"""Fix casing of language/region."""
<|body_0|>
def score(self, dialect: Dialect, country: str | None=None) -> tuple[float, float]:
"""Return score for match with anoth... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Dialect:
"""Language with optional region and script/code."""
def __post_init__(self) -> None:
"""Fix casing of language/region."""
self.language = self.language.casefold()
if self.region is not None:
self.region = self.region.upper()
def score(self, dialect: Dial... | the_stack_v2_python_sparse | homeassistant/util/language.py | home-assistant/core | train | 35,501 |
04e56764d5a4c05096e2388a99b526e66617a596 | [
"self.output_dir = outputDir\nself.package = package\nself.generate_id = uuid.uuid4\nself.pages = pages\nself.itemStr = ''\nself.resStr = ''",
"filename = 'imsmanifest.xml'\nout = open(self.output_dir / filename, 'w', encoding='utf-8')\nout.write(self.createXML())\nout.close()\nlrm = model_to_dict(self.package.du... | <|body_start_0|>
self.output_dir = outputDir
self.package = package
self.generate_id = uuid.uuid4
self.pages = pages
self.itemStr = ''
self.resStr = ''
<|end_body_0|>
<|body_start_1|>
filename = 'imsmanifest.xml'
out = open(self.output_dir / filename, 'w'... | Represents an imsmanifest xml file | Manifest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Manifest:
"""Represents an imsmanifest xml file"""
def __init__(self, outputDir, package, pages):
"""Initialize 'output_dir' is the directory that we read the html from and also output the mainfest.xml"""
<|body_0|>
def save(self):
"""Save a imsmanifest file and ... | stack_v2_sparse_classes_10k_train_001171 | 6,218 | no_license | [
{
"docstring": "Initialize 'output_dir' is the directory that we read the html from and also output the mainfest.xml",
"name": "__init__",
"signature": "def __init__(self, outputDir, package, pages)"
},
{
"docstring": "Save a imsmanifest file and metadata to self.output_dir",
"name": "save",... | 4 | stack_v2_sparse_classes_30k_train_002998 | Implement the Python class `Manifest` described below.
Class description:
Represents an imsmanifest xml file
Method signatures and docstrings:
- def __init__(self, outputDir, package, pages): Initialize 'output_dir' is the directory that we read the html from and also output the mainfest.xml
- def save(self): Save a ... | Implement the Python class `Manifest` described below.
Class description:
Represents an imsmanifest xml file
Method signatures and docstrings:
- def __init__(self, outputDir, package, pages): Initialize 'output_dir' is the directory that we read the html from and also output the mainfest.xml
- def save(self): Save a ... | 2cf50de25cdb8427668ec98c5ae3b17f3c2edbcf | <|skeleton|>
class Manifest:
"""Represents an imsmanifest xml file"""
def __init__(self, outputDir, package, pages):
"""Initialize 'output_dir' is the directory that we read the html from and also output the mainfest.xml"""
<|body_0|>
def save(self):
"""Save a imsmanifest file and ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Manifest:
"""Represents an imsmanifest xml file"""
def __init__(self, outputDir, package, pages):
"""Initialize 'output_dir' is the directory that we read the html from and also output the mainfest.xml"""
self.output_dir = outputDir
self.package = package
self.generate_id ... | the_stack_v2_python_sparse | exeapp/views/export/imsexport.py | TUM-MZ/creyoco | train | 1 |
84cbf9f0b28d1f2a3c30ccebb19e3ab0b429cacc | [
"total_issues = 0\nif os.path.isfile(logfile):\n with open(logfile) as open_file:\n stripped_line = list([line.rstrip() for line in open_file.readlines()])\n for line in stripped_line:\n line_found = re.search(log_message, line, re.IGNORECASE)\n if line_found:\n ... | <|body_start_0|>
total_issues = 0
if os.path.isfile(logfile):
with open(logfile) as open_file:
stripped_line = list([line.rstrip() for line in open_file.readlines()])
for line in stripped_line:
line_found = re.search(log_message, line, re.I... | Class to check for issues found in psad logs. | CheckStatus | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckStatus:
"""Class to check for issues found in psad logs."""
def check_psad(log_message, logfile):
"""Check number of occurrences of issues in the specified logfile. Returns: An int representing the number of issues found."""
<|body_0|>
def search_logfile(logfile):
... | stack_v2_sparse_classes_10k_train_001172 | 5,322 | permissive | [
{
"docstring": "Check number of occurrences of issues in the specified logfile. Returns: An int representing the number of issues found.",
"name": "check_psad",
"signature": "def check_psad(log_message, logfile)"
},
{
"docstring": "Look for positive scan results.",
"name": "search_logfile",
... | 5 | null | Implement the Python class `CheckStatus` described below.
Class description:
Class to check for issues found in psad logs.
Method signatures and docstrings:
- def check_psad(log_message, logfile): Check number of occurrences of issues in the specified logfile. Returns: An int representing the number of issues found.
... | Implement the Python class `CheckStatus` described below.
Class description:
Class to check for issues found in psad logs.
Method signatures and docstrings:
- def check_psad(log_message, logfile): Check number of occurrences of issues in the specified logfile. Returns: An int representing the number of issues found.
... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class CheckStatus:
"""Class to check for issues found in psad logs."""
def check_psad(log_message, logfile):
"""Check number of occurrences of issues in the specified logfile. Returns: An int representing the number of issues found."""
<|body_0|>
def search_logfile(logfile):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CheckStatus:
"""Class to check for issues found in psad logs."""
def check_psad(log_message, logfile):
"""Check number of occurrences of issues in the specified logfile. Returns: An int representing the number of issues found."""
total_issues = 0
if os.path.isfile(logfile):
... | the_stack_v2_python_sparse | docker/oso-psad/src/scripts/check_psad.py | openshift/openshift-tools | train | 170 |
227b67acc3af1459d1f52eb6dea52e39782e2e39 | [
"if not root:\n return None\nif key > root.val:\n root.right = self.deleteNode(root.right, key)\nelif key < root.val:\n root.left = self.deleteNode(root.left, key)\nelif not root.left and (not root.right):\n root = None\nelif root.right:\n root.val = self.successor(root)\n root.right = self.delete... | <|body_start_0|>
if not root:
return None
if key > root.val:
root.right = self.deleteNode(root.right, key)
elif key < root.val:
root.left = self.deleteNode(root.left, key)
elif not root.left and (not root.right):
root = None
elif ro... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteNode(self, root, key):
""":type root: TreeNode :type key: int :rtype: TreeNode"""
<|body_0|>
def successor(self, root):
"""One step right and then always left"""
<|body_1|>
def predecessor(self, root):
"""One step left and the... | stack_v2_sparse_classes_10k_train_001173 | 2,749 | no_license | [
{
"docstring": ":type root: TreeNode :type key: int :rtype: TreeNode",
"name": "deleteNode",
"signature": "def deleteNode(self, root, key)"
},
{
"docstring": "One step right and then always left",
"name": "successor",
"signature": "def successor(self, root)"
},
{
"docstring": "On... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteNode(self, root, key): :type root: TreeNode :type key: int :rtype: TreeNode
- def successor(self, root): One step right and then always left
- def predecessor(self, roo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteNode(self, root, key): :type root: TreeNode :type key: int :rtype: TreeNode
- def successor(self, root): One step right and then always left
- def predecessor(self, roo... | 90c000c3be70727cde4f7494fbbb1c425bfd3da4 | <|skeleton|>
class Solution:
def deleteNode(self, root, key):
""":type root: TreeNode :type key: int :rtype: TreeNode"""
<|body_0|>
def successor(self, root):
"""One step right and then always left"""
<|body_1|>
def predecessor(self, root):
"""One step left and the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def deleteNode(self, root, key):
""":type root: TreeNode :type key: int :rtype: TreeNode"""
if not root:
return None
if key > root.val:
root.right = self.deleteNode(root.right, key)
elif key < root.val:
root.left = self.deleteNode(r... | the_stack_v2_python_sparse | 450.delete-node-in-a-bst.py | chenjienan/python-leetcode | train | 16 | |
30f126b48c2c2c1b925fdb0453832f01e9b22b0a | [
"cls.endpoint = '/api/courseentry/'\ncls.course = CourseFactory(name='Course', description='Description', start='2020-01-05', cost=5000, deleted=False)\ncls.student = StudentFactory(user__username='student', user__first_name='Name', user__last_name='Surname', about='About student')\ncls.superuser = User.objects.cre... | <|body_start_0|>
cls.endpoint = '/api/courseentry/'
cls.course = CourseFactory(name='Course', description='Description', start='2020-01-05', cost=5000, deleted=False)
cls.student = StudentFactory(user__username='student', user__first_name='Name', user__last_name='Surname', about='About student')... | Тесты записей на курс | CourseEntryTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseEntryTestCase:
"""Тесты записей на курс"""
def setUpTestData(cls):
"""Данные для тесткейса"""
<|body_0|>
def test_course_entry_list(self):
"""Список записей на курс"""
<|body_1|>
def test_get_course_entry(self):
"""Получение записи на к... | stack_v2_sparse_classes_10k_train_001174 | 33,302 | no_license | [
{
"docstring": "Данные для тесткейса",
"name": "setUpTestData",
"signature": "def setUpTestData(cls)"
},
{
"docstring": "Список записей на курс",
"name": "test_course_entry_list",
"signature": "def test_course_entry_list(self)"
},
{
"docstring": "Получение записи на курс",
"n... | 5 | stack_v2_sparse_classes_30k_train_002544 | Implement the Python class `CourseEntryTestCase` described below.
Class description:
Тесты записей на курс
Method signatures and docstrings:
- def setUpTestData(cls): Данные для тесткейса
- def test_course_entry_list(self): Список записей на курс
- def test_get_course_entry(self): Получение записи на курс
- def test_... | Implement the Python class `CourseEntryTestCase` described below.
Class description:
Тесты записей на курс
Method signatures and docstrings:
- def setUpTestData(cls): Данные для тесткейса
- def test_course_entry_list(self): Список записей на курс
- def test_get_course_entry(self): Получение записи на курс
- def test_... | 3de0f8eeb4dbf9ec37b17ece0dde51c9e0f381ac | <|skeleton|>
class CourseEntryTestCase:
"""Тесты записей на курс"""
def setUpTestData(cls):
"""Данные для тесткейса"""
<|body_0|>
def test_course_entry_list(self):
"""Список записей на курс"""
<|body_1|>
def test_get_course_entry(self):
"""Получение записи на к... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CourseEntryTestCase:
"""Тесты записей на курс"""
def setUpTestData(cls):
"""Данные для тесткейса"""
cls.endpoint = '/api/courseentry/'
cls.course = CourseFactory(name='Course', description='Description', start='2020-01-05', cost=5000, deleted=False)
cls.student = StudentFa... | the_stack_v2_python_sparse | education_django/education_app/test_api.py | ilyaignatyev/python-web-otus-ru | train | 0 |
08182f71ff655a78b624cd0c406e0b6411767cb0 | [
"super(OAuth2UserAccountClient, self).__init__(cache_key_base=refresh_token, auth_uri=auth_uri, token_uri=token_uri, access_token_cache=access_token_cache, datetime_strategy=datetime_strategy, disable_ssl_certificate_validation=disable_ssl_certificate_validation, proxy_host=proxy_host, proxy_port=proxy_port, proxy_... | <|body_start_0|>
super(OAuth2UserAccountClient, self).__init__(cache_key_base=refresh_token, auth_uri=auth_uri, token_uri=token_uri, access_token_cache=access_token_cache, datetime_strategy=datetime_strategy, disable_ssl_certificate_validation=disable_ssl_certificate_validation, proxy_host=proxy_host, proxy_por... | An OAuth2 client. | OAuth2UserAccountClient | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OAuth2UserAccountClient:
"""An OAuth2 client."""
def __init__(self, token_uri, client_id, client_secret, refresh_token, auth_uri=None, access_token_cache=None, datetime_strategy=datetime.datetime, disable_ssl_certificate_validation=False, proxy_host=None, proxy_port=None, proxy_user=None, pr... | stack_v2_sparse_classes_10k_train_001175 | 29,065 | permissive | [
{
"docstring": "Creates an OAuth2UserAccountClient. Args: token_uri: The URI used to refresh access tokens. client_id: The OAuth2 client ID of this client. client_secret: The OAuth2 client secret of this client. refresh_token: The token used to refresh the access token. auth_uri: The URI for OAuth2 authorizatio... | 3 | stack_v2_sparse_classes_30k_train_005855 | Implement the Python class `OAuth2UserAccountClient` described below.
Class description:
An OAuth2 client.
Method signatures and docstrings:
- def __init__(self, token_uri, client_id, client_secret, refresh_token, auth_uri=None, access_token_cache=None, datetime_strategy=datetime.datetime, disable_ssl_certificate_val... | Implement the Python class `OAuth2UserAccountClient` described below.
Class description:
An OAuth2 client.
Method signatures and docstrings:
- def __init__(self, token_uri, client_id, client_secret, refresh_token, auth_uri=None, access_token_cache=None, datetime_strategy=datetime.datetime, disable_ssl_certificate_val... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class OAuth2UserAccountClient:
"""An OAuth2 client."""
def __init__(self, token_uri, client_id, client_secret, refresh_token, auth_uri=None, access_token_cache=None, datetime_strategy=datetime.datetime, disable_ssl_certificate_validation=False, proxy_host=None, proxy_port=None, proxy_user=None, pr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OAuth2UserAccountClient:
"""An OAuth2 client."""
def __init__(self, token_uri, client_id, client_secret, refresh_token, auth_uri=None, access_token_cache=None, datetime_strategy=datetime.datetime, disable_ssl_certificate_validation=False, proxy_host=None, proxy_port=None, proxy_user=None, proxy_pass=None... | the_stack_v2_python_sparse | third_party/gsutil/third_party/gcs-oauth2-boto-plugin/gcs_oauth2_boto_plugin/oauth2_client.py | catapult-project/catapult | train | 2,032 |
2176476bd36a670fd4c2dd3318b45a5b2972d229 | [
"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. | LoggingServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoggingServiceServicer:
"""Missing associated documentation comment in .proto file."""
def addLogEvent(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def getLogEvents(self, request, context):
"""Missing associat... | stack_v2_sparse_classes_10k_train_001176 | 7,376 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "addLogEvent",
"signature": "def addLogEvent(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "getLogEvents",
"signature": "def getLogEvents(se... | 4 | stack_v2_sparse_classes_30k_train_004416 | Implement the Python class `LoggingServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def addLogEvent(self, request, context): Missing associated documentation comment in .proto file.
- def getLogEvents(self, request, conte... | Implement the Python class `LoggingServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def addLogEvent(self, request, context): Missing associated documentation comment in .proto file.
- def getLogEvents(self, request, conte... | dc1ea0b58f92429ec8e7b54a8f23525abe024ba9 | <|skeleton|>
class LoggingServiceServicer:
"""Missing associated documentation comment in .proto file."""
def addLogEvent(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def getLogEvents(self, request, context):
"""Missing associat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LoggingServiceServicer:
"""Missing associated documentation comment in .proto file."""
def addLogEvent(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemente... | the_stack_v2_python_sparse | custos-client-sdks/custos-python-sdk/custos/server/core/LoggingService_pb2_grpc.py | apache/airavata-custos | train | 12 |
5df7507e614c1a2ef8a1bd1716481c4ef702b4e3 | [
"if not root:\n return ''\nq = [root]\ncoded = [root.val]\nwhile q:\n n = len(q)\n for _ in range(n):\n node = q.pop(0)\n if not node:\n continue\n q.append(node.left)\n q.append(node.right)\n coded += [node.val if node else 'N' for node in q]\nreturn coded",
"if... | <|body_start_0|>
if not root:
return ''
q = [root]
coded = [root.val]
while q:
n = len(q)
for _ in range(n):
node = q.pop(0)
if not node:
continue
q.append(node.left)
q... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_001177 | 2,617 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_005160 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 0127190b27862ec7e7f4f2fcce5ce958d480cdac | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
q = [root]
coded = [root.val]
while q:
n = len(q)
for _ in range(n):
node = q.pop(0)
... | the_stack_v2_python_sparse | 449.serialize-and-deserialize-bst.py | Iverance/leetcode | train | 0 | |
4da0e5b71fa6866f00420ffd2fa6863de55e646c | [
"head = None\npre = None\ncurr = root\nwhile curr:\n while curr:\n if curr.left:\n if pre:\n pre.next = curr.left\n else:\n head = curr.left\n pre = curr.left\n if curr.right:\n if pre:\n pre.next = curr.right\... | <|body_start_0|>
head = None
pre = None
curr = root
while curr:
while curr:
if curr.left:
if pre:
pre.next = curr.left
else:
head = curr.left
pre = curr... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def connect(self, root):
""":type root: TreeLinkNode :rtype: nothing"""
<|body_0|>
def connect_self(self, root):
""":type root: TreeLinkNode :rtype: nothing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
head = None
pre = None
... | stack_v2_sparse_classes_10k_train_001178 | 2,403 | no_license | [
{
"docstring": ":type root: TreeLinkNode :rtype: nothing",
"name": "connect",
"signature": "def connect(self, root)"
},
{
"docstring": ":type root: TreeLinkNode :rtype: nothing",
"name": "connect_self",
"signature": "def connect_self(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001504 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): :type root: TreeLinkNode :rtype: nothing
- def connect_self(self, root): :type root: TreeLinkNode :rtype: nothing | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): :type root: TreeLinkNode :rtype: nothing
- def connect_self(self, root): :type root: TreeLinkNode :rtype: nothing
<|skeleton|>
class Solution:
def ... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def connect(self, root):
""":type root: TreeLinkNode :rtype: nothing"""
<|body_0|>
def connect_self(self, root):
""":type root: TreeLinkNode :rtype: nothing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def connect(self, root):
""":type root: TreeLinkNode :rtype: nothing"""
head = None
pre = None
curr = root
while curr:
while curr:
if curr.left:
if pre:
pre.next = curr.left
... | the_stack_v2_python_sparse | 117_populating_next_right_pointers_in_each_node_2/sol.py | lianke123321/leetcode_sol | train | 0 | |
b224eac4dfb3aa0ace048e9a1a177cba9b8e55c1 | [
"self._cr.execute('SELECT complete_name FROM stock_location WHERE complete_name = %s', (self.complete_name,))\nres = self._cr.fetchall()\nif res:\n raise ValidationError('Please use another Location Name. The Name already exists: ' + self.complete_name)",
"if default is None:\n default = {}\nif 'name' not i... | <|body_start_0|>
self._cr.execute('SELECT complete_name FROM stock_location WHERE complete_name = %s', (self.complete_name,))
res = self._cr.fetchall()
if res:
raise ValidationError('Please use another Location Name. The Name already exists: ' + self.complete_name)
<|end_body_0|>
<|... | flspStockLocation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class flspStockLocation:
def _constraint_only_unique_complete_name(self):
"""Date: Mar/16th/2021/Tuesday Purpose: To create only unique "complete name" (complete name = Parent Location / Location Name) To raise exception if the complete name exists Assumption: There may be duplicated complete ... | stack_v2_sparse_classes_10k_train_001179 | 1,591 | no_license | [
{
"docstring": "Date: Mar/16th/2021/Tuesday Purpose: To create only unique \"complete name\" (complete name = Parent Location / Location Name) To raise exception if the complete name exists Assumption: There may be duplicated complete names existing in database, so _sql_constraints would not work Author: Perry ... | 2 | null | Implement the Python class `flspStockLocation` described below.
Class description:
Implement the flspStockLocation class.
Method signatures and docstrings:
- def _constraint_only_unique_complete_name(self): Date: Mar/16th/2021/Tuesday Purpose: To create only unique "complete name" (complete name = Parent Location / L... | Implement the Python class `flspStockLocation` described below.
Class description:
Implement the flspStockLocation class.
Method signatures and docstrings:
- def _constraint_only_unique_complete_name(self): Date: Mar/16th/2021/Tuesday Purpose: To create only unique "complete name" (complete name = Parent Location / L... | 4a82cd5cfd1898c6da860cb68dff3a14e037bbad | <|skeleton|>
class flspStockLocation:
def _constraint_only_unique_complete_name(self):
"""Date: Mar/16th/2021/Tuesday Purpose: To create only unique "complete name" (complete name = Parent Location / Location Name) To raise exception if the complete name exists Assumption: There may be duplicated complete ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class flspStockLocation:
def _constraint_only_unique_complete_name(self):
"""Date: Mar/16th/2021/Tuesday Purpose: To create only unique "complete name" (complete name = Parent Location / Location Name) To raise exception if the complete name exists Assumption: There may be duplicated complete names existing... | the_stack_v2_python_sparse | flspstock/models/flsp_stock_location.py | odoo-smg/firstlight | train | 3 | |
d8d60c8924f65dfd9c30068aeb5530f2b7bba38b | [
"super(RNNDecoder, self).__init__()\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)\nself.F = tf.keras.layers.Dense(vocab)",
"attention = SelfAttention(s_prev.shape[1])\ncontext, ... | <|body_start_0|>
super(RNNDecoder, self).__init__()
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
self.F = tf.keras.layers.Dense(vocab)
<|end_body_0|>
<... | Class RNNDecoder to decode for machine translation | RNNDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""Class RNNDecoder to decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor Arguments: - vocab is an integer representing the size of the output vocabulary - embedding is an integer representing the dimensionality of t... | stack_v2_sparse_classes_10k_train_001180 | 2,681 | no_license | [
{
"docstring": "Class constructor Arguments: - vocab is an integer representing the size of the output vocabulary - embedding is an integer representing the dimensionality of the embedding vector - units is an integer representing the number of hidden units in the RNN cell - batch is an integer representing the... | 2 | stack_v2_sparse_classes_30k_train_000856 | Implement the Python class `RNNDecoder` described below.
Class description:
Class RNNDecoder to decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor Arguments: - vocab is an integer representing the size of the output vocabulary - emb... | Implement the Python class `RNNDecoder` described below.
Class description:
Class RNNDecoder to decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor Arguments: - vocab is an integer representing the size of the output vocabulary - emb... | fc2cec306961f7ca2448965ddd3a2f656bbe10c7 | <|skeleton|>
class RNNDecoder:
"""Class RNNDecoder to decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor Arguments: - vocab is an integer representing the size of the output vocabulary - embedding is an integer representing the dimensionality of t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RNNDecoder:
"""Class RNNDecoder to decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor Arguments: - vocab is an integer representing the size of the output vocabulary - embedding is an integer representing the dimensionality of the embedding ... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | dalexach/holbertonschool-machine_learning | train | 2 |
ac1c3aa9e64d4773e93327f3808d8d8b03cb45b5 | [
"self.pi_means = means\nself.pi_variances = variances\nself.weight = weight",
"C1_coef = 0.5 * (np.log(pi_variances / q_variances) + pi_means ** 2 / pi_variances - q_means ** 2 / q_variances)\nC2_coef = q_means / q_variances - pi_means / pi_variances\nC3_coef = 1.0 / 2.0 * pi_variances - 1.0 / 2.0 * q_variances\n... | <|body_start_0|>
self.pi_means = means
self.pi_variances = variances
self.weight = weight
<|end_body_0|>
<|body_start_1|>
C1_coef = 0.5 * (np.log(pi_variances / q_variances) + pi_means ** 2 / pi_variances - q_means ** 2 / q_variances)
C2_coef = q_means / q_variances - pi_means /... | Exponential Divergence where q and pi are both mean field normals. Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) | MFN_MFN_ED | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MFN_MFN_ED:
"""Exponential Divergence where q and pi are both mean field normals. Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable)"""
def __init__(self, means, variances, weight=1.0):
"""MFN ... | stack_v2_sparse_classes_10k_train_001181 | 14,750 | no_license | [
{
"docstring": "MFN for prior specified by vector of means & variances",
"name": "__init__",
"signature": "def __init__(self, means, variances, weight=1.0)"
},
{
"docstring": "Compute the inner coefficients before taking the squares",
"name": "ED_term",
"signature": "def ED_term(self, q_... | 3 | stack_v2_sparse_classes_30k_train_005001 | Implement the Python class `MFN_MFN_ED` described below.
Class description:
Exponential Divergence where q and pi are both mean field normals. Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable)
Method signatures and docstrings:... | Implement the Python class `MFN_MFN_ED` described below.
Class description:
Exponential Divergence where q and pi are both mean field normals. Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable)
Method signatures and docstrings:... | 6e51c10227ca8300853f2341906503d072cc0685 | <|skeleton|>
class MFN_MFN_ED:
"""Exponential Divergence where q and pi are both mean field normals. Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable)"""
def __init__(self, means, variances, weight=1.0):
"""MFN ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MFN_MFN_ED:
"""Exponential Divergence where q and pi are both mean field normals. Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable)"""
def __init__(self, means, variances, weight=1.0):
"""MFN for prior spe... | the_stack_v2_python_sparse | Divergence.py | JeremiasKnoblauch/GVI_consistency | train | 0 |
c4e849864d94b8b94dc15c79409964e27fd5d805 | [
"test_info = db.get_test(item_id)\nif not test_info:\n pecan.abort(404)\ntest_list = db.get_test_results(item_id)\ntest_name_list = [test_dict[0] for test_dict in test_list]\nreturn {'cpid': test_info.cpid, 'created_at': test_info.created_at, 'duration_seconds': test_info.duration_seconds, 'results': test_name_l... | <|body_start_0|>
test_info = db.get_test(item_id)
if not test_info:
pecan.abort(404)
test_list = db.get_test_results(item_id)
test_name_list = [test_dict[0] for test_dict in test_list]
return {'cpid': test_info.cpid, 'created_at': test_info.created_at, 'duration_secon... | /v1/results handler. | ResultsController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResultsController:
"""/v1/results handler."""
def get_item(self, item_id):
"""Handler for getting item"""
<|body_0|>
def store_item(self, item_in_json):
"""Handler for storing item. Should return new item id"""
<|body_1|>
def get(self):
"""Ge... | stack_v2_sparse_classes_10k_train_001182 | 8,563 | permissive | [
{
"docstring": "Handler for getting item",
"name": "get_item",
"signature": "def get_item(self, item_id)"
},
{
"docstring": "Handler for storing item. Should return new item id",
"name": "store_item",
"signature": "def store_item(self, item_in_json)"
},
{
"docstring": "Get inform... | 3 | stack_v2_sparse_classes_30k_train_006817 | Implement the Python class `ResultsController` described below.
Class description:
/v1/results handler.
Method signatures and docstrings:
- def get_item(self, item_id): Handler for getting item
- def store_item(self, item_in_json): Handler for storing item. Should return new item id
- def get(self): Get information o... | Implement the Python class `ResultsController` described below.
Class description:
/v1/results handler.
Method signatures and docstrings:
- def get_item(self, item_id): Handler for getting item
- def store_item(self, item_in_json): Handler for storing item. Should return new item id
- def get(self): Get information o... | 711f7527c430873edbed72e4f85af916b2088014 | <|skeleton|>
class ResultsController:
"""/v1/results handler."""
def get_item(self, item_id):
"""Handler for getting item"""
<|body_0|>
def store_item(self, item_in_json):
"""Handler for storing item. Should return new item id"""
<|body_1|>
def get(self):
"""Ge... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResultsController:
"""/v1/results handler."""
def get_item(self, item_id):
"""Handler for getting item"""
test_info = db.get_test(item_id)
if not test_info:
pecan.abort(404)
test_list = db.get_test_results(item_id)
test_name_list = [test_dict[0] for tes... | the_stack_v2_python_sparse | refstack/api/controllers/v1.py | russell/refstack | train | 0 |
d9f63b1a4634f19267f5e865b78daf1d9ceefc15 | [
"self.protected_count = protected_count\nself.protected_size = protected_size\nself.unprotected_count = unprotected_count\nself.unprotected_size = unprotected_size",
"if dictionary is None:\n return None\nprotected_count = dictionary.get('protectedCount')\nprotected_size = dictionary.get('protectedSize')\nunpr... | <|body_start_0|>
self.protected_count = protected_count
self.protected_size = protected_size
self.unprotected_count = unprotected_count
self.unprotected_size = unprotected_size
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
protected_count... | Implementation of the 'ProtectionSummary' model. Specifies the number of protected and unprotected objects, and their sizes information of the given entity. Attributes: protected_count (long|int): Specifies the number of objects that are protected under the given entity. protected_size (long|int): Specifies the total s... | ProtectionSummary | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectionSummary:
"""Implementation of the 'ProtectionSummary' model. Specifies the number of protected and unprotected objects, and their sizes information of the given entity. Attributes: protected_count (long|int): Specifies the number of objects that are protected under the given entity. pro... | stack_v2_sparse_classes_10k_train_001183 | 2,551 | permissive | [
{
"docstring": "Constructor for the ProtectionSummary class",
"name": "__init__",
"signature": "def __init__(self, protected_count=None, protected_size=None, unprotected_count=None, unprotected_size=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (d... | 2 | stack_v2_sparse_classes_30k_train_005742 | Implement the Python class `ProtectionSummary` described below.
Class description:
Implementation of the 'ProtectionSummary' model. Specifies the number of protected and unprotected objects, and their sizes information of the given entity. Attributes: protected_count (long|int): Specifies the number of objects that ar... | Implement the Python class `ProtectionSummary` described below.
Class description:
Implementation of the 'ProtectionSummary' model. Specifies the number of protected and unprotected objects, and their sizes information of the given entity. Attributes: protected_count (long|int): Specifies the number of objects that ar... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectionSummary:
"""Implementation of the 'ProtectionSummary' model. Specifies the number of protected and unprotected objects, and their sizes information of the given entity. Attributes: protected_count (long|int): Specifies the number of objects that are protected under the given entity. pro... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProtectionSummary:
"""Implementation of the 'ProtectionSummary' model. Specifies the number of protected and unprotected objects, and their sizes information of the given entity. Attributes: protected_count (long|int): Specifies the number of objects that are protected under the given entity. protected_size (... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protection_summary.py | cohesity/management-sdk-python | train | 24 |
091f3bf0eb432fbd27cb769bd8cd5ca61181aaa0 | [
"import collections\nif len(hand) % W != 0:\n return False\nmaps = collections.Counter(hand)\nprint(maps)\nstart = sorted(maps.keys(), reverse=True)\nwhile start:\n for i in range(W):\n key = start[-1] + i\n if key not in maps or maps[key] <= 0:\n return False\n else:\n ... | <|body_start_0|>
import collections
if len(hand) % W != 0:
return False
maps = collections.Counter(hand)
print(maps)
start = sorted(maps.keys(), reverse=True)
while start:
for i in range(W):
key = start[-1] + i
if ke... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isNStraightHand(self, hand, W):
""":type hand: List[int] :type W: int :rtype: bool 204 ms"""
<|body_0|>
def isNStraightHand_1(self, hand, W):
"""198ms :param hand: :param W: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
impo... | stack_v2_sparse_classes_10k_train_001184 | 1,902 | no_license | [
{
"docstring": ":type hand: List[int] :type W: int :rtype: bool 204 ms",
"name": "isNStraightHand",
"signature": "def isNStraightHand(self, hand, W)"
},
{
"docstring": "198ms :param hand: :param W: :return:",
"name": "isNStraightHand_1",
"signature": "def isNStraightHand_1(self, hand, W)... | 2 | stack_v2_sparse_classes_30k_train_006881 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isNStraightHand(self, hand, W): :type hand: List[int] :type W: int :rtype: bool 204 ms
- def isNStraightHand_1(self, hand, W): 198ms :param hand: :param W: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isNStraightHand(self, hand, W): :type hand: List[int] :type W: int :rtype: bool 204 ms
- def isNStraightHand_1(self, hand, W): 198ms :param hand: :param W: :return:
<|skelet... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def isNStraightHand(self, hand, W):
""":type hand: List[int] :type W: int :rtype: bool 204 ms"""
<|body_0|>
def isNStraightHand_1(self, hand, W):
"""198ms :param hand: :param W: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isNStraightHand(self, hand, W):
""":type hand: List[int] :type W: int :rtype: bool 204 ms"""
import collections
if len(hand) % W != 0:
return False
maps = collections.Counter(hand)
print(maps)
start = sorted(maps.keys(), reverse=True)
... | the_stack_v2_python_sparse | HandOfStraights_MID_846.py | 953250587/leetcode-python | train | 2 | |
0d329c74abd1b6cf79b45535999e320f2f8eb5c8 | [
"response = get_and_check_page(self, 'huntserver:create_account', 200)\npost_context = {'user-first_name': 'first', 'user-last_name': 'last', 'user-username': 'user7', 'user-email': 'user7@example.com', 'person-phone': '777-777-7777', 'person-allergies': 'something', 'user-password': 'password', 'user-confirm_passw... | <|body_start_0|>
response = get_and_check_page(self, 'huntserver:create_account', 200)
post_context = {'user-first_name': 'first', 'user-last_name': 'last', 'user-username': 'user7', 'user-email': 'user7@example.com', 'person-phone': '777-777-7777', 'person-allergies': 'something', 'user-password': 'pas... | AuthTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthTests:
def test_create_account(self):
"""Test the account creation view"""
<|body_0|>
def test_login_selection(self):
"""Test the login selection view"""
<|body_1|>
def test_account_logout(self):
"""Test the account logout view"""
<|b... | stack_v2_sparse_classes_10k_train_001185 | 33,380 | permissive | [
{
"docstring": "Test the account creation view",
"name": "test_create_account",
"signature": "def test_create_account(self)"
},
{
"docstring": "Test the login selection view",
"name": "test_login_selection",
"signature": "def test_login_selection(self)"
},
{
"docstring": "Test th... | 4 | stack_v2_sparse_classes_30k_test_000275 | Implement the Python class `AuthTests` described below.
Class description:
Implement the AuthTests class.
Method signatures and docstrings:
- def test_create_account(self): Test the account creation view
- def test_login_selection(self): Test the login selection view
- def test_account_logout(self): Test the account ... | Implement the Python class `AuthTests` described below.
Class description:
Implement the AuthTests class.
Method signatures and docstrings:
- def test_create_account(self): Test the account creation view
- def test_login_selection(self): Test the login selection view
- def test_account_logout(self): Test the account ... | 44f87cc5cfe8bb23a8e04fddee187b9056407741 | <|skeleton|>
class AuthTests:
def test_create_account(self):
"""Test the account creation view"""
<|body_0|>
def test_login_selection(self):
"""Test the login selection view"""
<|body_1|>
def test_account_logout(self):
"""Test the account logout view"""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AuthTests:
def test_create_account(self):
"""Test the account creation view"""
response = get_and_check_page(self, 'huntserver:create_account', 200)
post_context = {'user-first_name': 'first', 'user-last_name': 'last', 'user-username': 'user7', 'user-email': 'user7@example.com', 'perso... | the_stack_v2_python_sparse | huntserver/tests.py | dlareau/puzzlehunt_server | train | 20 | |
73c0b537b4cea0625ec2f1e75b908c02115ec6e7 | [
"super().__init__()\nself.enc_blocks = nn.ModuleList([Block(chs[i], chs[i + 1]) for i in range(len(chs) - 1)])\nself.pool = nn.MaxPool2d(2)",
"ftrs = []\nfor block in self.enc_blocks:\n x = block(x)\n ftrs.append(x)\n x = self.pool(x)\nreturn ftrs"
] | <|body_start_0|>
super().__init__()
self.enc_blocks = nn.ModuleList([Block(chs[i], chs[i + 1]) for i in range(len(chs) - 1)])
self.pool = nn.MaxPool2d(2)
<|end_body_0|>
<|body_start_1|>
ftrs = []
for block in self.enc_blocks:
x = block(x)
ftrs.append(x)
... | U-net encoder half | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""U-net encoder half"""
def __init__(self, chs=(6, 64, 128, 256, 512, 1024)):
"""Class for U-net encoder half. Inputs: chs - The channels of the block of the encoder. Default = (6,64,128,256,512,1024)"""
<|body_0|>
def forward(self, x):
"""Forward of th... | stack_v2_sparse_classes_10k_train_001186 | 11,891 | no_license | [
{
"docstring": "Class for U-net encoder half. Inputs: chs - The channels of the block of the encoder. Default = (6,64,128,256,512,1024)",
"name": "__init__",
"signature": "def __init__(self, chs=(6, 64, 128, 256, 512, 1024))"
},
{
"docstring": "Forward of the U-net encoder. Inputs: x - Input bat... | 2 | stack_v2_sparse_classes_30k_train_004791 | Implement the Python class `Encoder` described below.
Class description:
U-net encoder half
Method signatures and docstrings:
- def __init__(self, chs=(6, 64, 128, 256, 512, 1024)): Class for U-net encoder half. Inputs: chs - The channels of the block of the encoder. Default = (6,64,128,256,512,1024)
- def forward(se... | Implement the Python class `Encoder` described below.
Class description:
U-net encoder half
Method signatures and docstrings:
- def __init__(self, chs=(6, 64, 128, 256, 512, 1024)): Class for U-net encoder half. Inputs: chs - The channels of the block of the encoder. Default = (6,64,128,256,512,1024)
- def forward(se... | 0b65d43a9bb5e70d7e4e3fcd322b47b173e16fa6 | <|skeleton|>
class Encoder:
"""U-net encoder half"""
def __init__(self, chs=(6, 64, 128, 256, 512, 1024)):
"""Class for U-net encoder half. Inputs: chs - The channels of the block of the encoder. Default = (6,64,128,256,512,1024)"""
<|body_0|>
def forward(self, x):
"""Forward of th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Encoder:
"""U-net encoder half"""
def __init__(self, chs=(6, 64, 128, 256, 512, 1024)):
"""Class for U-net encoder half. Inputs: chs - The channels of the block of the encoder. Default = (6,64,128,256,512,1024)"""
super().__init__()
self.enc_blocks = nn.ModuleList([Block(chs[i], c... | the_stack_v2_python_sparse | models/attackers/inversion_attacker_2.py | RamonDijkstra/AI-FACT | train | 0 |
8ed9114963a5ae6745ce47fbe24e26786d3ad766 | [
"self._clip_reward = clip_reward\nself.intrinsic_model = intrinsic_rewards.RNDIntrinsicReward(sess=sess, tf_device=tf_device, summary_writer=summary_writer)\nsuper(RNDDQNAgent, self).__init__(sess=sess, num_actions=num_actions, observation_shape=observation_shape, gamma=gamma, update_horizon=update_horizon, min_rep... | <|body_start_0|>
self._clip_reward = clip_reward
self.intrinsic_model = intrinsic_rewards.RNDIntrinsicReward(sess=sess, tf_device=tf_device, summary_writer=summary_writer)
super(RNDDQNAgent, self).__init__(sess=sess, num_actions=num_actions, observation_shape=observation_shape, gamma=gamma, upda... | Implements a DQN agent with a RND intrinsic reward. | RNDDQNAgent | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNDDQNAgent:
"""Implements a DQN agent with a RND intrinsic reward."""
def __init__(self, sess, num_actions, observation_shape=base_dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, gamma=0.99, update_horizon=1, min_replay_history=20000, update_period=4, target_update_period=8000, epsilon_fn=linearly_... | stack_v2_sparse_classes_10k_train_001187 | 10,489 | permissive | [
{
"docstring": "Initializes the agent and constructs the components of its graph. Args: sess: `tf.Session`, for executing ops. num_actions: int, number of actions the agent can take at any state. observation_shape: tuple of ints describing the observation shape. gamma: float, discount factor with the usual RL m... | 2 | stack_v2_sparse_classes_30k_train_003905 | Implement the Python class `RNDDQNAgent` described below.
Class description:
Implements a DQN agent with a RND intrinsic reward.
Method signatures and docstrings:
- def __init__(self, sess, num_actions, observation_shape=base_dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, gamma=0.99, update_horizon=1, min_replay_history=200... | Implement the Python class `RNDDQNAgent` described below.
Class description:
Implements a DQN agent with a RND intrinsic reward.
Method signatures and docstrings:
- def __init__(self, sess, num_actions, observation_shape=base_dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, gamma=0.99, update_horizon=1, min_replay_history=200... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class RNDDQNAgent:
"""Implements a DQN agent with a RND intrinsic reward."""
def __init__(self, sess, num_actions, observation_shape=base_dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, gamma=0.99, update_horizon=1, min_replay_history=20000, update_period=4, target_update_period=8000, epsilon_fn=linearly_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RNDDQNAgent:
"""Implements a DQN agent with a RND intrinsic reward."""
def __init__(self, sess, num_actions, observation_shape=base_dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, gamma=0.99, update_horizon=1, min_replay_history=20000, update_period=4, target_update_period=8000, epsilon_fn=linearly_decaying_epsi... | the_stack_v2_python_sparse | bonus_based_exploration/intrinsic_motivation/intrinsic_dqn_agent.py | Jimmy-INL/google-research | train | 1 |
79205759e44904843ef5999daeaeaf4fb8e02563 | [
"s = sum(nums)\nif s % k != 0:\n return False\ntarget = s // k\nvisited = [False for _ in nums]\nreturn self.dfs(nums, 0, None, target, visited, k)",
"if k == 1:\n return True\nif cur_sum and cur_sum == target_sum:\n return self.dfs(nums, 0, None, target_sum, visited, k - 1)\nfor i in range(start_idx, le... | <|body_start_0|>
s = sum(nums)
if s % k != 0:
return False
target = s // k
visited = [False for _ in nums]
return self.dfs(nums, 0, None, target, visited, k)
<|end_body_0|>
<|body_start_1|>
if k == 1:
return True
if cur_sum and cur_sum == ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
"""resurive search"""
<|body_0|>
def dfs(self, nums, start_idx, cur_sum, target_sum, visited, k):
"""some corner cases: 1. target_sum default at 0: sum or empty array is 0? 2. nxt_sum = (cur_s... | stack_v2_sparse_classes_10k_train_001188 | 3,307 | no_license | [
{
"docstring": "resurive search",
"name": "canPartitionKSubsets",
"signature": "def canPartitionKSubsets(self, nums: List[int], k: int) -> bool"
},
{
"docstring": "some corner cases: 1. target_sum default at 0: sum or empty array is 0? 2. nxt_sum = (cur_sum or 0) + nums[i] rather than cur_sum or... | 2 | stack_v2_sparse_classes_30k_train_002920 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: resurive search
- def dfs(self, nums, start_idx, cur_sum, target_sum, visited, k): some corner cases: 1. target_s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: resurive search
- def dfs(self, nums, start_idx, cur_sum, target_sum, visited, k): some corner cases: 1. target_s... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
"""resurive search"""
<|body_0|>
def dfs(self, nums, start_idx, cur_sum, target_sum, visited, k):
"""some corner cases: 1. target_sum default at 0: sum or empty array is 0? 2. nxt_sum = (cur_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
"""resurive search"""
s = sum(nums)
if s % k != 0:
return False
target = s // k
visited = [False for _ in nums]
return self.dfs(nums, 0, None, target, visited, k)
def dfs... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/698 Partition to K Equal Sum Subsets.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
20e7991f4068a4b7c31b61b3a22a35b4a3a510be | [
"super().__init__()\nif residuals is not None:\n residuals = residuals.lower()\nself.residuals = residuals\nself.body = nn.Sequential(nn.Linear(features_in, features_out, bias=False), norm_factory(features_out), activation_factory())",
"if self.residuals is None:\n return self.body(x)\nif self.residuals == ... | <|body_start_0|>
super().__init__()
if residuals is not None:
residuals = residuals.lower()
self.residuals = residuals
self.body = nn.Sequential(nn.Linear(features_in, features_out, bias=False), norm_factory(features_out), activation_factory())
<|end_body_0|>
<|body_start_1|... | A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor. | MLPBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLPBlock:
"""A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor."""
def __init__(self, features_in, features_out, activation_factory, norm_factory, residuals=None):
"""Args: features_in: The numbe... | stack_v2_sparse_classes_10k_train_001189 | 9,125 | permissive | [
{
"docstring": "Args: features_in: The number of features of the block input. features_out: The number of features of the block output. activation_factory: A factory functional to create the activation layers in the block. norm_factory: A factory functional to create the normalization layers used in the block. ... | 2 | stack_v2_sparse_classes_30k_train_007120 | Implement the Python class `MLPBlock` described below.
Class description:
A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor.
Method signatures and docstrings:
- def __init__(self, features_in, features_out, activation_factory, no... | Implement the Python class `MLPBlock` described below.
Class description:
A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor.
Method signatures and docstrings:
- def __init__(self, features_in, features_out, activation_factory, no... | a27e329cd30337995c359160a0d878bf331c13fb | <|skeleton|>
class MLPBlock:
"""A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor."""
def __init__(self, features_in, features_out, activation_factory, norm_factory, residuals=None):
"""Args: features_in: The numbe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MLPBlock:
"""A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor."""
def __init__(self, features_in, features_out, activation_factory, norm_factory, residuals=None):
"""Args: features_in: The number of features... | the_stack_v2_python_sparse | quantnn/models/pytorch/fully_connected.py | simonpf/quantnn | train | 7 |
1adc618aef64a56acde9078374245a604d2fdec6 | [
"cur = head\ncount = 0\nwhile cur and count != k:\n cur = cur.next\n count += 1\nif count == k:\n cur = self.reverseKGroup(cur, k)\n while count > 0:\n count -= 1\n temp = head.next\n head.next = cur\n cur = head\n head = temp\n head = cur\nreturn head",
"curr = h... | <|body_start_0|>
cur = head
count = 0
while cur and count != k:
cur = cur.next
count += 1
if count == k:
cur = self.reverseKGroup(cur, k)
while count > 0:
count -= 1
temp = head.next
head.next... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def reverseKGroup_self(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_001190 | 1,575 | no_license | [
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "reverseKGroup",
"signature": "def reverseKGroup(self, head, k)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "reverseKGroup_self",
"signature": "def reverseKGroup_self(self, h... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def reverseKGroup_self(self, head, k): :type head: ListNode :type k: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def reverseKGroup_self(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def reverseKGroup_self(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
cur = head
count = 0
while cur and count != k:
cur = cur.next
count += 1
if count == k:
cur = self.reverseKGroup(cur, k)
... | the_stack_v2_python_sparse | 25_reverse_nodes_in_k-group/sol.py | lianke123321/leetcode_sol | train | 0 | |
0d1e4d090509f11e2f63497f77507bed5cac6e99 | [
"time_elements_structure = self._GetValueFromStructure(structure, 'date_time')\nevent_data = IOSSysdiagnoseLogdData()\nevent_data.body = self._GetValueFromStructure(structure, 'body', default_value='')\nevent_data.logger = self._GetValueFromStructure(structure, 'logger', default_value='')\nevent_data.written_time =... | <|body_start_0|>
time_elements_structure = self._GetValueFromStructure(structure, 'date_time')
event_data = IOSSysdiagnoseLogdData()
event_data.body = self._GetValueFromStructure(structure, 'body', default_value='')
event_data.logger = self._GetValueFromStructure(structure, 'logger', def... | Text parser plugin for iOS sysdiagnose logd files (logd.0.log). | IOSSysdiagnoseLogdTextPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IOSSysdiagnoseLogdTextPlugin:
"""Text parser plugin for iOS sysdiagnose logd files (logd.0.log)."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other compon... | stack_v2_sparse_classes_10k_train_001191 | 5,087 | permissive | [
{
"docstring": "Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. key (str): name of the parsed structure. structure (pyparsing.ParseResults): tokens from a parsed log line. Raises: ParseError: if the stru... | 3 | stack_v2_sparse_classes_30k_train_000754 | Implement the Python class `IOSSysdiagnoseLogdTextPlugin` described below.
Class description:
Text parser plugin for iOS sysdiagnose logd files (logd.0.log).
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator... | Implement the Python class `IOSSysdiagnoseLogdTextPlugin` described below.
Class description:
Text parser plugin for iOS sysdiagnose logd files (logd.0.log).
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class IOSSysdiagnoseLogdTextPlugin:
"""Text parser plugin for iOS sysdiagnose logd files (logd.0.log)."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other compon... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IOSSysdiagnoseLogdTextPlugin:
"""Text parser plugin for iOS sysdiagnose logd files (logd.0.log)."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as... | the_stack_v2_python_sparse | plaso/parsers/text_plugins/ios_logd.py | log2timeline/plaso | train | 1,506 |
2ecd56bafe05303196afacdc6ff5eaeb468638fd | [
"f = open(file_trace, 'r')\ncount = 0\ntxt = f.readlines()\nf.close()\ntopic_dict = {}\ntopic_unpro_dict = {}\nword = []\nword_value = []\nfor line in txt:\n if 'Topic' in line:\n line_clean = line.split(':')\n line_clean_clean = line_clean[0].split()\n name = ''.join(line_clean_clean)\n ... | <|body_start_0|>
f = open(file_trace, 'r')
count = 0
txt = f.readlines()
f.close()
topic_dict = {}
topic_unpro_dict = {}
word = []
word_value = []
for line in txt:
if 'Topic' in line:
line_clean = line.split(':')
... | 主题两两之间的相似,并输出 | lda | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class lda:
"""主题两两之间的相似,并输出"""
def f_open_file(word_number=50, file_trace='./lda/iphone5s/diff-sampling/model-1.txt'):
"""打开模型并保存为字典"""
<|body_0|>
def f_static_word(static_word_dict, static_word_topicNum=30, static_word_wordNum=50):
"""统计词并输出"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_001192 | 2,462 | no_license | [
{
"docstring": "打开模型并保存为字典",
"name": "f_open_file",
"signature": "def f_open_file(word_number=50, file_trace='./lda/iphone5s/diff-sampling/model-1.txt')"
},
{
"docstring": "统计词并输出",
"name": "f_static_word",
"signature": "def f_static_word(static_word_dict, static_word_topicNum=30, static... | 4 | stack_v2_sparse_classes_30k_train_001515 | Implement the Python class `lda` described below.
Class description:
主题两两之间的相似,并输出
Method signatures and docstrings:
- def f_open_file(word_number=50, file_trace='./lda/iphone5s/diff-sampling/model-1.txt'): 打开模型并保存为字典
- def f_static_word(static_word_dict, static_word_topicNum=30, static_word_wordNum=50): 统计词并输出
- def... | Implement the Python class `lda` described below.
Class description:
主题两两之间的相似,并输出
Method signatures and docstrings:
- def f_open_file(word_number=50, file_trace='./lda/iphone5s/diff-sampling/model-1.txt'): 打开模型并保存为字典
- def f_static_word(static_word_dict, static_word_topicNum=30, static_word_wordNum=50): 统计词并输出
- def... | 309f6fecf9b8ee9c69472c0aedb0004c00e8f682 | <|skeleton|>
class lda:
"""主题两两之间的相似,并输出"""
def f_open_file(word_number=50, file_trace='./lda/iphone5s/diff-sampling/model-1.txt'):
"""打开模型并保存为字典"""
<|body_0|>
def f_static_word(static_word_dict, static_word_topicNum=30, static_word_wordNum=50):
"""统计词并输出"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class lda:
"""主题两两之间的相似,并输出"""
def f_open_file(word_number=50, file_trace='./lda/iphone5s/diff-sampling/model-1.txt'):
"""打开模型并保存为字典"""
f = open(file_trace, 'r')
count = 0
txt = f.readlines()
f.close()
topic_dict = {}
topic_unpro_dict = {}
word = ... | the_stack_v2_python_sparse | 20140814/topic_combination.py | KAI-YIP/nlp | train | 2 |
615f20e83a11cc1bf9b1899748835559aa3d6293 | [
"if not root:\n return 'null'\noutput = []\nmy_queue = []\nmy_queue.append(root)\nwhile my_queue:\n l = len(my_queue)\n for i in range(l):\n curr_node = my_queue.pop(0)\n if curr_node:\n output.append(curr_node.val)\n my_queue.append(curr_node.left)\n my_queue... | <|body_start_0|>
if not root:
return 'null'
output = []
my_queue = []
my_queue.append(root)
while my_queue:
l = len(my_queue)
for i in range(l):
curr_node = my_queue.pop(0)
if curr_node:
outpu... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_001193 | 2,255 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 3f5ad6164c147e7b51b7850dcd279150fa8a7600 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return 'null'
output = []
my_queue = []
my_queue.append(root)
while my_queue:
l = len(my_queue)
for i in ... | the_stack_v2_python_sparse | Round_1/297. Serialize and Deserialize Binary Tree/solution_2.py | buptwxd2/leetcode | train | 0 | |
1fc8e5c695007c61734c84b725d8c559e698fee2 | [
"super().__init__()\nself.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True)\nself.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=False)\nself.relu = nn.ReLU(inplace=True)",
"out = self.relu(x)\nout = self.conv1(out)\nout = self.relu(out)\nout = se... | <|body_start_0|>
super().__init__()
self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True)
self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=False)
self.relu = nn.ReLU(inplace=True)
<|end_body_0|>
<|body_start_1|>
... | Residual convolution module. | ResidualConvUnit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualConvUnit:
"""Residual convolution module."""
def __init__(self, features):
"""Init. Args: features (int): number of features"""
<|body_0|>
def forward(self, x):
"""Forward pass. Args: x (tensor): input Returns: tensor: output"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_10k_train_001194 | 5,777 | permissive | [
{
"docstring": "Init. Args: features (int): number of features",
"name": "__init__",
"signature": "def __init__(self, features)"
},
{
"docstring": "Forward pass. Args: x (tensor): input Returns: tensor: output",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | null | Implement the Python class `ResidualConvUnit` described below.
Class description:
Residual convolution module.
Method signatures and docstrings:
- def __init__(self, features): Init. Args: features (int): number of features
- def forward(self, x): Forward pass. Args: x (tensor): input Returns: tensor: output | Implement the Python class `ResidualConvUnit` described below.
Class description:
Residual convolution module.
Method signatures and docstrings:
- def __init__(self, features): Init. Args: features (int): number of features
- def forward(self, x): Forward pass. Args: x (tensor): input Returns: tensor: output
<|skele... | a00c3619bf4042e446e1919087f0b09fe9fa3a65 | <|skeleton|>
class ResidualConvUnit:
"""Residual convolution module."""
def __init__(self, features):
"""Init. Args: features (int): number of features"""
<|body_0|>
def forward(self, x):
"""Forward pass. Args: x (tensor): input Returns: tensor: output"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResidualConvUnit:
"""Residual convolution module."""
def __init__(self, features):
"""Init. Args: features (int): number of features"""
super().__init__()
self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True)
self.conv2 = nn.Conv2d(featu... | the_stack_v2_python_sparse | nasws/cnn/search_space/monodepth/models/midas_net_old.py | kcyu2014/nas-landmarkreg | train | 10 |
71156aeeb4aa55a28606b2986da44c480f05d46a | [
"if args.target_instance:\n raise exceptions.ToolException('You cannot specify [--target-instance] for a global forwarding rule.')\nif args.target_pool:\n raise exceptions.ToolException('You cannot specify [--target-pool] for a global forwarding rule.')\nif getattr(args, 'backend_service', None):\n raise e... | <|body_start_0|>
if args.target_instance:
raise exceptions.ToolException('You cannot specify [--target-instance] for a global forwarding rule.')
if args.target_pool:
raise exceptions.ToolException('You cannot specify [--target-pool] for a global forwarding rule.')
if geta... | Base class for modifying forwarding rule targets. | ForwardingRulesTargetMutator | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForwardingRulesTargetMutator:
"""Base class for modifying forwarding rule targets."""
def ValidateGlobalArgs(self, args):
"""Validate the global forwarding rules args."""
<|body_0|>
def GetGlobalTarget(self, args):
"""Return the forwarding target for a globally s... | stack_v2_sparse_classes_10k_train_001195 | 7,875 | permissive | [
{
"docstring": "Validate the global forwarding rules args.",
"name": "ValidateGlobalArgs",
"signature": "def ValidateGlobalArgs(self, args)"
},
{
"docstring": "Return the forwarding target for a globally scoped request.",
"name": "GetGlobalTarget",
"signature": "def GetGlobalTarget(self,... | 5 | stack_v2_sparse_classes_30k_train_001073 | Implement the Python class `ForwardingRulesTargetMutator` described below.
Class description:
Base class for modifying forwarding rule targets.
Method signatures and docstrings:
- def ValidateGlobalArgs(self, args): Validate the global forwarding rules args.
- def GetGlobalTarget(self, args): Return the forwarding ta... | Implement the Python class `ForwardingRulesTargetMutator` described below.
Class description:
Base class for modifying forwarding rule targets.
Method signatures and docstrings:
- def ValidateGlobalArgs(self, args): Validate the global forwarding rules args.
- def GetGlobalTarget(self, args): Return the forwarding ta... | c98b58aeb0994e011df960163541e9379ae7ea06 | <|skeleton|>
class ForwardingRulesTargetMutator:
"""Base class for modifying forwarding rule targets."""
def ValidateGlobalArgs(self, args):
"""Validate the global forwarding rules args."""
<|body_0|>
def GetGlobalTarget(self, args):
"""Return the forwarding target for a globally s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ForwardingRulesTargetMutator:
"""Base class for modifying forwarding rule targets."""
def ValidateGlobalArgs(self, args):
"""Validate the global forwarding rules args."""
if args.target_instance:
raise exceptions.ToolException('You cannot specify [--target-instance] for a glob... | the_stack_v2_python_sparse | google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/compute/forwarding_rules_utils.py | KaranToor/MA450 | train | 1 |
e6272ef93d4353d773bbea0a369090364c83a9b3 | [
"for test_point in vectors:\n entropy_input = int(test_point['EntropyInput'], 16)\n received = sp.test_point_gen(entropy_input)\n self.assertEqual(test_point, received)",
"test_point = vectors[secrets.randbelow(15)]\noffset = 8 * secrets.randbelow(32)\nwidth = secrets.randbelow(256)\nReturnedBits = int(t... | <|body_start_0|>
for test_point in vectors:
entropy_input = int(test_point['EntropyInput'], 16)
received = sp.test_point_gen(entropy_input)
self.assertEqual(test_point, received)
<|end_body_0|>
<|body_start_1|>
test_point = vectors[secrets.randbelow(15)]
offs... | TestNistOfficial | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestNistOfficial:
def test_compare(self):
"""Ensure that known seeds generate the expected results."""
<|body_0|>
def test_getrandbits(self):
"""Test secure_random.getrandbits() using test vectors Reseed PRNG using entropy_input. Use sp.getrandbits to forward the gen... | stack_v2_sparse_classes_10k_train_001196 | 13,435 | permissive | [
{
"docstring": "Ensure that known seeds generate the expected results.",
"name": "test_compare",
"signature": "def test_compare(self)"
},
{
"docstring": "Test secure_random.getrandbits() using test vectors Reseed PRNG using entropy_input. Use sp.getrandbits to forward the generator to a randomly... | 2 | null | Implement the Python class `TestNistOfficial` described below.
Class description:
Implement the TestNistOfficial class.
Method signatures and docstrings:
- def test_compare(self): Ensure that known seeds generate the expected results.
- def test_getrandbits(self): Test secure_random.getrandbits() using test vectors R... | Implement the Python class `TestNistOfficial` described below.
Class description:
Implement the TestNistOfficial class.
Method signatures and docstrings:
- def test_compare(self): Ensure that known seeds generate the expected results.
- def test_getrandbits(self): Test secure_random.getrandbits() using test vectors R... | 51f6017b8425b14d5a4aa9abace8fe5a25ef08c8 | <|skeleton|>
class TestNistOfficial:
def test_compare(self):
"""Ensure that known seeds generate the expected results."""
<|body_0|>
def test_getrandbits(self):
"""Test secure_random.getrandbits() using test vectors Reseed PRNG using entropy_input. Use sp.getrandbits to forward the gen... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestNistOfficial:
def test_compare(self):
"""Ensure that known seeds generate the expected results."""
for test_point in vectors:
entropy_input = int(test_point['EntropyInput'], 16)
received = sp.test_point_gen(entropy_input)
self.assertEqual(test_point, rec... | the_stack_v2_python_sparse | util/topgen/secure_prng_test.py | lowRISC/opentitan | train | 2,077 | |
7b3943700dd932d3aeb67973c6b8cc31641f5ffb | [
"struct = mojom.Struct('test')\nindex = 1\nfor kind in kinds:\n struct.AddField('%d' % index, kind)\n index += 1\nps = pack.PackedStruct(struct)\nnum_fields = len(ps.packed_fields)\nself.assertEquals(len(kinds), num_fields)\nfor i in xrange(num_fields):\n self.assertEquals('%d' % fields[i], ps.packed_field... | <|body_start_0|>
struct = mojom.Struct('test')
index = 1
for kind in kinds:
struct.AddField('%d' % index, kind)
index += 1
ps = pack.PackedStruct(struct)
num_fields = len(ps.packed_fields)
self.assertEquals(len(kinds), num_fields)
for i in ... | PackTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackTest:
def _CheckPackSequence(self, kinds, fields, offsets):
"""Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fields that are to be created. fields: The expected order of the resulting fields, with the integer "... | stack_v2_sparse_classes_10k_train_001197 | 4,828 | permissive | [
{
"docstring": "Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fields that are to be created. fields: The expected order of the resulting fields, with the integer \"1\" first. offsets: The expected order of offsets, with the integer \"0\" ... | 6 | null | Implement the Python class `PackTest` described below.
Class description:
Implement the PackTest class.
Method signatures and docstrings:
- def _CheckPackSequence(self, kinds, fields, offsets): Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fiel... | Implement the Python class `PackTest` described below.
Class description:
Implement the PackTest class.
Method signatures and docstrings:
- def _CheckPackSequence(self, kinds, fields, offsets): Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fiel... | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | <|skeleton|>
class PackTest:
def _CheckPackSequence(self, kinds, fields, offsets):
"""Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fields that are to be created. fields: The expected order of the resulting fields, with the integer "... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PackTest:
def _CheckPackSequence(self, kinds, fields, offsets):
"""Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fields that are to be created. fields: The expected order of the resulting fields, with the integer "1" first. offs... | the_stack_v2_python_sparse | mojo/public/tools/bindings/pylib/mojom_tests/generate/pack_unittest.py | Samsung/Castanets | train | 58 | |
d4cc121dc4da2ca81e100bf2acb364ed55606185 | [
"queryset = Like.objects.all()\nif self.action == 'destroy':\n return queryset.filter(id=self.kwargs['pk'])\nreturn queryset",
"if self.action in ['destroy']:\n permissions = [IsAuthenticated, IsObjectOwner]\nelse:\n permissions = [IsAuthenticated]\nreturn [p() for p in permissions]",
"queryset = Like.... | <|body_start_0|>
queryset = Like.objects.all()
if self.action == 'destroy':
return queryset.filter(id=self.kwargs['pk'])
return queryset
<|end_body_0|>
<|body_start_1|>
if self.action in ['destroy']:
permissions = [IsAuthenticated, IsObjectOwner]
else:
... | LikeViewSet Handle create, delete, list of photos. | LikeViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LikeViewSet:
"""LikeViewSet Handle create, delete, list of photos."""
def get_queryset(self):
"""Restrict list to public-only."""
<|body_0|>
def get_permissions(self):
"""Assign permissions based on action."""
<|body_1|>
def list(self, request, photo... | stack_v2_sparse_classes_10k_train_001198 | 2,329 | permissive | [
{
"docstring": "Restrict list to public-only.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Assign permissions based on action.",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Show all the likes of a ph... | 5 | stack_v2_sparse_classes_30k_train_006956 | Implement the Python class `LikeViewSet` described below.
Class description:
LikeViewSet Handle create, delete, list of photos.
Method signatures and docstrings:
- def get_queryset(self): Restrict list to public-only.
- def get_permissions(self): Assign permissions based on action.
- def list(self, request, photo_pk=... | Implement the Python class `LikeViewSet` described below.
Class description:
LikeViewSet Handle create, delete, list of photos.
Method signatures and docstrings:
- def get_queryset(self): Restrict list to public-only.
- def get_permissions(self): Assign permissions based on action.
- def list(self, request, photo_pk=... | 83b79ed62e21c654d0945decaaf6571e19c8c12a | <|skeleton|>
class LikeViewSet:
"""LikeViewSet Handle create, delete, list of photos."""
def get_queryset(self):
"""Restrict list to public-only."""
<|body_0|>
def get_permissions(self):
"""Assign permissions based on action."""
<|body_1|>
def list(self, request, photo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LikeViewSet:
"""LikeViewSet Handle create, delete, list of photos."""
def get_queryset(self):
"""Restrict list to public-only."""
queryset = Like.objects.all()
if self.action == 'destroy':
return queryset.filter(id=self.kwargs['pk'])
return queryset
def ge... | the_stack_v2_python_sparse | ig_clone_api/photos/views/likes.py | whosgriffith/ig-clone-api | train | 0 |
c68fc85e83eb424ffa23ce3f9e648f1c6a1ba6b1 | [
"if a & 1:\n return 3 * a + 1\nelse:\n return int(a / 2)",
"seq = []\nwhile True:\n a = cls.collatz(a)\n seq.append(a)\n if a == 1:\n break\nreturn seq",
"seq = cls.collatzSequence(a)\nseq = [a] + list(seq[0:-1])\nreturn tuple(map(lambda x: 1 - x & 1, seq))",
"w = 1\nfor i in seq[::-1]:\... | <|body_start_0|>
if a & 1:
return 3 * a + 1
else:
return int(a / 2)
<|end_body_0|>
<|body_start_1|>
seq = []
while True:
a = cls.collatz(a)
seq.append(a)
if a == 1:
break
return seq
<|end_body_1|>
<|bod... | contains common functions for Collatz Conjecture all methods in this class are class methods so no object creation required | Collatz | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Collatz:
"""contains common functions for Collatz Conjecture all methods in this class are class methods so no object creation required"""
def collatz(cls, a):
"""apply collatz function on a given number Parameters ---------- a : int Return ------ int"""
<|body_0|>
def c... | stack_v2_sparse_classes_10k_train_001199 | 3,247 | no_license | [
{
"docstring": "apply collatz function on a given number Parameters ---------- a : int Return ------ int",
"name": "collatz",
"signature": "def collatz(cls, a)"
},
{
"docstring": "return the collatz sequence of a number This will calculate all the sequence of numbers to get to 1 using collatz fu... | 4 | stack_v2_sparse_classes_30k_train_003718 | Implement the Python class `Collatz` described below.
Class description:
contains common functions for Collatz Conjecture all methods in this class are class methods so no object creation required
Method signatures and docstrings:
- def collatz(cls, a): apply collatz function on a given number Parameters ---------- a... | Implement the Python class `Collatz` described below.
Class description:
contains common functions for Collatz Conjecture all methods in this class are class methods so no object creation required
Method signatures and docstrings:
- def collatz(cls, a): apply collatz function on a given number Parameters ---------- a... | 2fa4eb77826e6d0f901043a900331b0c5e1f24ce | <|skeleton|>
class Collatz:
"""contains common functions for Collatz Conjecture all methods in this class are class methods so no object creation required"""
def collatz(cls, a):
"""apply collatz function on a given number Parameters ---------- a : int Return ------ int"""
<|body_0|>
def c... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Collatz:
"""contains common functions for Collatz Conjecture all methods in this class are class methods so no object creation required"""
def collatz(cls, a):
"""apply collatz function on a given number Parameters ---------- a : int Return ------ int"""
if a & 1:
return 3 * a... | the_stack_v2_python_sparse | collatz.py | ink-hat/xmark | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.