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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
36bea736905f0277ad12805247592c226c75f683 | [
"if not root:\n return ''\ncur_list = [root]\nval_list = [str(root.val)]\nwhile len(cur_list):\n pointer = cur_list.pop(0)\n if pointer.left:\n cur_list.append(pointer.left)\n val_list.append(str(pointer.left.val))\n else:\n val_list.append('NA')\n if pointer.right:\n cur_... | <|body_start_0|>
if not root:
return ''
cur_list = [root]
val_list = [str(root.val)]
while len(cur_list):
pointer = cur_list.pop(0)
if pointer.left:
cur_list.append(pointer.left)
val_list.append(str(pointer.left.val))
... | 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_002300 | 3,830 | 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_004143 | 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:... | 9387c1cbf1cac2db1aebf5ad196230705ab0fcc7 | <|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 ''
cur_list = [root]
val_list = [str(root.val)]
while len(cur_list):
pointer = cur_list.pop(0)
if pointer.... | the_stack_v2_python_sparse | serialize_and_deserialize_binary_tree.py | lightening0907/algorithm | train | 0 | |
28ba5d0174603e0b7b01a65286129057f3deb4c8 | [
"try:\n parsed_url = urlparse(url)\nexcept Exception as e:\n logging.error('Failed to parse url: ' + str(e))\n raise FailedDownloadingFileException('The provided url is not in a recognized format.')\nif not parsed_url.path.lower().split('?')[0].endswith(schema_generator.SchemaGenerator.valid_extensions):\n... | <|body_start_0|>
try:
parsed_url = urlparse(url)
except Exception as e:
logging.error('Failed to parse url: ' + str(e))
raise FailedDownloadingFileException('The provided url is not in a recognized format.')
if not parsed_url.path.lower().split('?')[0].endswit... | This class functionality is to read supported file types into temporary files. | FileDownloader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileDownloader:
"""This class functionality is to read supported file types into temporary files."""
def download_temp(url, sftp_username=None, sftp_password=None):
"""Parses the url and downloads the file into a temporary file."""
<|body_0|>
def __https_file_downloader(... | stack_v2_sparse_classes_10k_train_002301 | 4,953 | no_license | [
{
"docstring": "Parses the url and downloads the file into a temporary file.",
"name": "download_temp",
"signature": "def download_temp(url, sftp_username=None, sftp_password=None)"
},
{
"docstring": "Takes in a given https url and downloads the file into a temporary file.",
"name": "__https... | 3 | stack_v2_sparse_classes_30k_train_006497 | Implement the Python class `FileDownloader` described below.
Class description:
This class functionality is to read supported file types into temporary files.
Method signatures and docstrings:
- def download_temp(url, sftp_username=None, sftp_password=None): Parses the url and downloads the file into a temporary file... | Implement the Python class `FileDownloader` described below.
Class description:
This class functionality is to read supported file types into temporary files.
Method signatures and docstrings:
- def download_temp(url, sftp_username=None, sftp_password=None): Parses the url and downloads the file into a temporary file... | 873c96bdf5fd07ddc986d3944a90c5bcfa898b2d | <|skeleton|>
class FileDownloader:
"""This class functionality is to read supported file types into temporary files."""
def download_temp(url, sftp_username=None, sftp_password=None):
"""Parses the url and downloads the file into a temporary file."""
<|body_0|>
def __https_file_downloader(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FileDownloader:
"""This class functionality is to read supported file types into temporary files."""
def download_temp(url, sftp_username=None, sftp_password=None):
"""Parses the url and downloads the file into a temporary file."""
try:
parsed_url = urlparse(url)
excep... | the_stack_v2_python_sparse | cataloger/utilities/file_downloader.py | timeonator/opendatapdx | train | 1 |
c296f2751865c7f5f948a68ae90e26f5e00985b4 | [
"self.max_read_iops = max_read_iops\nself.max_write_iops = max_write_iops\nself.read_iops_samples = read_iops_samples\nself.write_iops_samples = write_iops_samples",
"if dictionary is None:\n return None\nmax_read_iops = dictionary.get('maxReadIops')\nmax_write_iops = dictionary.get('maxWriteIops')\nread_iops_... | <|body_start_0|>
self.max_read_iops = max_read_iops
self.max_write_iops = max_write_iops
self.read_iops_samples = read_iops_samples
self.write_iops_samples = write_iops_samples
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
max_read_iops =... | Implementation of the 'IopsTile' model. IOPs information for dashboard. Attributes: max_read_iops (long|int): Maximum Read IOs per second in last 24 hours. max_write_iops (long|int): Maximum number of Write IOs per second in last 24 hours. read_iops_samples (list of Sample): Read IOs per second samples taken for the pa... | IopsTile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IopsTile:
"""Implementation of the 'IopsTile' model. IOPs information for dashboard. Attributes: max_read_iops (long|int): Maximum Read IOs per second in last 24 hours. max_write_iops (long|int): Maximum number of Write IOs per second in last 24 hours. read_iops_samples (list of Sample): Read IOs... | stack_v2_sparse_classes_10k_train_002302 | 3,022 | permissive | [
{
"docstring": "Constructor for the IopsTile class",
"name": "__init__",
"signature": "def __init__(self, max_read_iops=None, max_write_iops=None, read_iops_samples=None, write_iops_samples=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary... | 2 | stack_v2_sparse_classes_30k_train_000192 | Implement the Python class `IopsTile` described below.
Class description:
Implementation of the 'IopsTile' model. IOPs information for dashboard. Attributes: max_read_iops (long|int): Maximum Read IOs per second in last 24 hours. max_write_iops (long|int): Maximum number of Write IOs per second in last 24 hours. read_... | Implement the Python class `IopsTile` described below.
Class description:
Implementation of the 'IopsTile' model. IOPs information for dashboard. Attributes: max_read_iops (long|int): Maximum Read IOs per second in last 24 hours. max_write_iops (long|int): Maximum number of Write IOs per second in last 24 hours. read_... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class IopsTile:
"""Implementation of the 'IopsTile' model. IOPs information for dashboard. Attributes: max_read_iops (long|int): Maximum Read IOs per second in last 24 hours. max_write_iops (long|int): Maximum number of Write IOs per second in last 24 hours. read_iops_samples (list of Sample): Read IOs... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IopsTile:
"""Implementation of the 'IopsTile' model. IOPs information for dashboard. Attributes: max_read_iops (long|int): Maximum Read IOs per second in last 24 hours. max_write_iops (long|int): Maximum number of Write IOs per second in last 24 hours. read_iops_samples (list of Sample): Read IOs per second s... | the_stack_v2_python_sparse | cohesity_management_sdk/models/iops_tile.py | cohesity/management-sdk-python | train | 24 |
364a476317899eda3709d936233f29175071eaaa | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BrowserSharedCookieHistory()",
"from .browser_shared_cookie_source_environment import BrowserSharedCookieSourceEnvironment\nfrom .identity_set import IdentitySet\nfrom .browser_shared_cookie_source_environment import BrowserSharedCooki... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return BrowserSharedCookieHistory()
<|end_body_0|>
<|body_start_1|>
from .browser_shared_cookie_source_environment import BrowserSharedCookieSourceEnvironment
from .identity_set import Identity... | BrowserSharedCookieHistory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrowserSharedCookieHistory:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BrowserSharedCookieHistory:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and... | stack_v2_sparse_classes_10k_train_002303 | 4,881 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: BrowserSharedCookieHistory",
"name": "create_from_discriminator_value",
"signature": "def create_from_discri... | 3 | stack_v2_sparse_classes_30k_train_003835 | Implement the Python class `BrowserSharedCookieHistory` described below.
Class description:
Implement the BrowserSharedCookieHistory class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BrowserSharedCookieHistory: Creates a new instance of the appropr... | Implement the Python class `BrowserSharedCookieHistory` described below.
Class description:
Implement the BrowserSharedCookieHistory class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BrowserSharedCookieHistory: Creates a new instance of the appropr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BrowserSharedCookieHistory:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BrowserSharedCookieHistory:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BrowserSharedCookieHistory:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BrowserSharedCookieHistory:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | the_stack_v2_python_sparse | msgraph/generated/models/browser_shared_cookie_history.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
d8edef84a12d610f1752cfb28d7e7095e32b6a8f | [
"self.ar_coeffs = ar_coeffs\nself.ma_coeffs = ma_coeffs\nself.arma_process = sm.tsa.ArmaProcess.from_coeffs(self.ar_coeffs, self.ma_coeffs)",
"if seed is None:\n seed = 0\nnp.random.seed(seed)\nindex = pd.date_range(**date_range_kwargs)\nnsample = index.size\ndata = self.arma_process.generate_sample(nsample=ns... | <|body_start_0|>
self.ar_coeffs = ar_coeffs
self.ma_coeffs = ma_coeffs
self.arma_process = sm.tsa.ArmaProcess.from_coeffs(self.ar_coeffs, self.ma_coeffs)
<|end_body_0|>
<|body_start_1|>
if seed is None:
seed = 0
np.random.seed(seed)
index = pd.date_range(**da... | A thin wrapper around statsmodels `ArmaProcess`, with Pandas support. | ArmaProcess | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArmaProcess:
"""A thin wrapper around statsmodels `ArmaProcess`, with Pandas support."""
def __init__(self, ar_coeffs: List[float], ma_coeffs: List[float]) -> None:
"""Initialize `arma_process` using given coefficients. Useful properties include - arroots - isinvertible - isstationar... | stack_v2_sparse_classes_10k_train_002304 | 14,310 | permissive | [
{
"docstring": "Initialize `arma_process` using given coefficients. Useful properties include - arroots - isinvertible - isstationary - maroots Further details are available at - https://www.statsmodels.org/stable/generated/statsmodels.tsa.arima_process.ArmaProcess.html # pylint: disable=line-too-long",
"na... | 2 | stack_v2_sparse_classes_30k_train_002395 | Implement the Python class `ArmaProcess` described below.
Class description:
A thin wrapper around statsmodels `ArmaProcess`, with Pandas support.
Method signatures and docstrings:
- def __init__(self, ar_coeffs: List[float], ma_coeffs: List[float]) -> None: Initialize `arma_process` using given coefficients. Useful ... | Implement the Python class `ArmaProcess` described below.
Class description:
A thin wrapper around statsmodels `ArmaProcess`, with Pandas support.
Method signatures and docstrings:
- def __init__(self, ar_coeffs: List[float], ma_coeffs: List[float]) -> None: Initialize `arma_process` using given coefficients. Useful ... | 363c59fa29df2ba2719cbad2f8a19ae12cc54a92 | <|skeleton|>
class ArmaProcess:
"""A thin wrapper around statsmodels `ArmaProcess`, with Pandas support."""
def __init__(self, ar_coeffs: List[float], ma_coeffs: List[float]) -> None:
"""Initialize `arma_process` using given coefficients. Useful properties include - arroots - isinvertible - isstationar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ArmaProcess:
"""A thin wrapper around statsmodels `ArmaProcess`, with Pandas support."""
def __init__(self, ar_coeffs: List[float], ma_coeffs: List[float]) -> None:
"""Initialize `arma_process` using given coefficients. Useful properties include - arroots - isinvertible - isstationary - maroots F... | the_stack_v2_python_sparse | core/artificial_signal_generators.py | srlindemann/amp | train | 0 |
a388a3252656e046f945c827b53f38990382404e | [
"def encode_extra_types(obj):\n \"\"\"MessagePack hook to serialize extra types.\n\n The recipe took from the MessagePack for Python docs:\n https://github.com/msgpack/msgpack-python#packingunpacking-of-custom-data-type\n\n Supported types:\n - Django models (through `... | <|body_start_0|>
def encode_extra_types(obj):
"""MessagePack hook to serialize extra types.
The recipe took from the MessagePack for Python docs:
https://github.com/msgpack/msgpack-python#packingunpacking-of-custom-data-type
Supported typ... | Serialize/deserialize Python collection with Django models. Serialize/deserialize the data with the MessagePack like Redis Channels layer backend does. If `data` contains Django models, then it is serialized by the Django serialization utilities. For details see: Django serialization: https://docs.djangoproject.com/en/... | Serializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Serializer:
"""Serialize/deserialize Python collection with Django models. Serialize/deserialize the data with the MessagePack like Redis Channels layer backend does. If `data` contains Django models, then it is serialized by the Django serialization utilities. For details see: Django serializati... | stack_v2_sparse_classes_10k_train_002305 | 3,850 | permissive | [
{
"docstring": "Serialize the `data`.",
"name": "serialize",
"signature": "def serialize(data)"
},
{
"docstring": "Deserialize the `data`.",
"name": "deserialize",
"signature": "def deserialize(data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004171 | Implement the Python class `Serializer` described below.
Class description:
Serialize/deserialize Python collection with Django models. Serialize/deserialize the data with the MessagePack like Redis Channels layer backend does. If `data` contains Django models, then it is serialized by the Django serialization utiliti... | Implement the Python class `Serializer` described below.
Class description:
Serialize/deserialize Python collection with Django models. Serialize/deserialize the data with the MessagePack like Redis Channels layer backend does. If `data` contains Django models, then it is serialized by the Django serialization utiliti... | 09a2ffdde45a1553abd09b5b3e595402b6e6c9b1 | <|skeleton|>
class Serializer:
"""Serialize/deserialize Python collection with Django models. Serialize/deserialize the data with the MessagePack like Redis Channels layer backend does. If `data` contains Django models, then it is serialized by the Django serialization utilities. For details see: Django serializati... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Serializer:
"""Serialize/deserialize Python collection with Django models. Serialize/deserialize the data with the MessagePack like Redis Channels layer backend does. If `data` contains Django models, then it is serialized by the Django serialization utilities. For details see: Django serialization: https://d... | the_stack_v2_python_sparse | channels_graphql_ws/serializer.py | datadvance/DjangoChannelsGraphqlWs | train | 295 |
9ea014162748b92664743cf57ecc1f484e34447a | [
"self.Wh = np.random.normal(size=(h + i, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"xMax = np.max(x, axis=-1, keepdims=True)\ne_x = np.exp(x - xMax)\nreturn e_x / e_x.sum(axis=-1, keepdims=True)",
"hidden_con = np.concatenate((h_prev.T, x_t.T), axis=0... | <|body_start_0|>
self.Wh = np.random.normal(size=(h + i, h))
self.Wy = np.random.normal(size=(h, o))
self.bh = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
xMax = np.max(x, axis=-1, keepdims=True)
e_x = np.exp(x - xMax)
return e_x /... | RNNCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNCell:
def __init__(self, i, h, o):
"""class condtructor :param i: dim of the data :param h: dim of hidden state :param o: dim of outputs Note: create public attributes Wh, Wy, bh, by Note: Wh and bh: for the concatenated Hidden state and input Wy and by: for the output Note: Weights: ... | stack_v2_sparse_classes_10k_train_002306 | 1,817 | no_license | [
{
"docstring": "class condtructor :param i: dim of the data :param h: dim of hidden state :param o: dim of outputs Note: create public attributes Wh, Wy, bh, by Note: Wh and bh: for the concatenated Hidden state and input Wy and by: for the output Note: Weights: initialized using fandom normal distribution in l... | 3 | stack_v2_sparse_classes_30k_train_001243 | Implement the Python class `RNNCell` described below.
Class description:
Implement the RNNCell class.
Method signatures and docstrings:
- def __init__(self, i, h, o): class condtructor :param i: dim of the data :param h: dim of hidden state :param o: dim of outputs Note: create public attributes Wh, Wy, bh, by Note: ... | Implement the Python class `RNNCell` described below.
Class description:
Implement the RNNCell class.
Method signatures and docstrings:
- def __init__(self, i, h, o): class condtructor :param i: dim of the data :param h: dim of hidden state :param o: dim of outputs Note: create public attributes Wh, Wy, bh, by Note: ... | 4ac942126918c7acaa9ef88d18efe299b2f726fe | <|skeleton|>
class RNNCell:
def __init__(self, i, h, o):
"""class condtructor :param i: dim of the data :param h: dim of hidden state :param o: dim of outputs Note: create public attributes Wh, Wy, bh, by Note: Wh and bh: for the concatenated Hidden state and input Wy and by: for the output Note: Weights: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RNNCell:
def __init__(self, i, h, o):
"""class condtructor :param i: dim of the data :param h: dim of hidden state :param o: dim of outputs Note: create public attributes Wh, Wy, bh, by Note: Wh and bh: for the concatenated Hidden state and input Wy and by: for the output Note: Weights: initialized us... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/0-rnn_cell.py | DracoMindz/holbertonschool-machine_learning | train | 2 | |
ece1d797a3b98dc341b9b1e116a2373ea328ba2d | [
"number_frequency_map = {}\nfor num in arr:\n number_frequency_map[num] = number_frequency_map.get(num, 0) + 1\nlucky_number = -1\nfor key, value in number_frequency_map.items():\n if key == value:\n lucky_number = max(value, lucky_number)\nreturn lucky_number",
"lucky_list = []\nfor i in arr:\n i... | <|body_start_0|>
number_frequency_map = {}
for num in arr:
number_frequency_map[num] = number_frequency_map.get(num, 0) + 1
lucky_number = -1
for key, value in number_frequency_map.items():
if key == value:
lucky_number = max(value, lucky_number)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLucky(self, arr: List[int]) -> int:
"""Time: O(N) Space: O(N)"""
<|body_0|>
def findLucky_2(self, arr: List[int]) -> int:
"""Time: O(N^2) Space: O(N)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
number_frequency_map = {}
... | stack_v2_sparse_classes_10k_train_002307 | 2,039 | no_license | [
{
"docstring": "Time: O(N) Space: O(N)",
"name": "findLucky",
"signature": "def findLucky(self, arr: List[int]) -> int"
},
{
"docstring": "Time: O(N^2) Space: O(N)",
"name": "findLucky_2",
"signature": "def findLucky_2(self, arr: List[int]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLucky(self, arr: List[int]) -> int: Time: O(N) Space: O(N)
- def findLucky_2(self, arr: List[int]) -> int: Time: O(N^2) Space: O(N) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLucky(self, arr: List[int]) -> int: Time: O(N) Space: O(N)
- def findLucky_2(self, arr: List[int]) -> int: Time: O(N^2) Space: O(N)
<|skeleton|>
class Solution:
def... | 57534898c17d058ef1dba2b1cb8cdcd8d1d2a41c | <|skeleton|>
class Solution:
def findLucky(self, arr: List[int]) -> int:
"""Time: O(N) Space: O(N)"""
<|body_0|>
def findLucky_2(self, arr: List[int]) -> int:
"""Time: O(N^2) Space: O(N)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findLucky(self, arr: List[int]) -> int:
"""Time: O(N) Space: O(N)"""
number_frequency_map = {}
for num in arr:
number_frequency_map[num] = number_frequency_map.get(num, 0) + 1
lucky_number = -1
for key, value in number_frequency_map.items():
... | the_stack_v2_python_sparse | leetcode/leetcode_question_bank/problems/1394_find_lucky_integer_in_an_array/lucky_integer.py | arivolispark/datastructuresandalgorithms | train | 0 | |
26db360cbafd14ccfdb0466d616245d11efd3415 | [
"self.api = api\nself.station = station\nsuper().__init__(hass, _LOGGER, name=name, update_interval=MIN_TIME_BETWEEN_UPDATES)",
"try:\n return await self.api.async_get_station_measurements(self.station.uuid)\nexcept CONNECT_ERRORS as err:\n raise UpdateFailed(f'Failed to communicate with API: {err}') from e... | <|body_start_0|>
self.api = api
self.station = station
super().__init__(hass, _LOGGER, name=name, update_interval=MIN_TIME_BETWEEN_UPDATES)
<|end_body_0|>
<|body_start_1|>
try:
return await self.api.async_get_station_measurements(self.station.uuid)
except CONNECT_ERR... | DataUpdateCoordinator for the pegel_online integration. | PegelOnlineDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PegelOnlineDataUpdateCoordinator:
"""DataUpdateCoordinator for the pegel_online integration."""
def __init__(self, hass: HomeAssistant, name: str, api: PegelOnline, station: Station) -> None:
"""Initialize the PegelOnlineDataUpdateCoordinator."""
<|body_0|>
async def _as... | stack_v2_sparse_classes_10k_train_002308 | 1,227 | permissive | [
{
"docstring": "Initialize the PegelOnlineDataUpdateCoordinator.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, name: str, api: PegelOnline, station: Station) -> None"
},
{
"docstring": "Fetch data from API endpoint.",
"name": "_async_update_data",
"signature... | 2 | null | Implement the Python class `PegelOnlineDataUpdateCoordinator` described below.
Class description:
DataUpdateCoordinator for the pegel_online integration.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, name: str, api: PegelOnline, station: Station) -> None: Initialize the PegelOnlineDataUp... | Implement the Python class `PegelOnlineDataUpdateCoordinator` described below.
Class description:
DataUpdateCoordinator for the pegel_online integration.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, name: str, api: PegelOnline, station: Station) -> None: Initialize the PegelOnlineDataUp... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class PegelOnlineDataUpdateCoordinator:
"""DataUpdateCoordinator for the pegel_online integration."""
def __init__(self, hass: HomeAssistant, name: str, api: PegelOnline, station: Station) -> None:
"""Initialize the PegelOnlineDataUpdateCoordinator."""
<|body_0|>
async def _as... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PegelOnlineDataUpdateCoordinator:
"""DataUpdateCoordinator for the pegel_online integration."""
def __init__(self, hass: HomeAssistant, name: str, api: PegelOnline, station: Station) -> None:
"""Initialize the PegelOnlineDataUpdateCoordinator."""
self.api = api
self.station = stat... | the_stack_v2_python_sparse | homeassistant/components/pegel_online/coordinator.py | home-assistant/core | train | 35,501 |
77346fe559d546712187956ec4b5f3bb8f842a2e | [
"sample = list(self.fetch_samples(sample_id=sample_id))\nif len(sample) > 0:\n LOG.info('Deleting sample %s from database', sample[0].id)\n self.delete_commit(sample)",
"LOG.info('Deleting entire group %s from database', group_id)\nsamples = self.fetch_samples(group_id=group_id)\nfor sample in samples:\n ... | <|body_start_0|>
sample = list(self.fetch_samples(sample_id=sample_id))
if len(sample) > 0:
LOG.info('Deleting sample %s from database', sample[0].id)
self.delete_commit(sample)
<|end_body_0|>
<|body_start_1|>
LOG.info('Deleting entire group %s from database', group_id)
... | Methods for deleting samples from database | DeleteMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteMixin:
"""Methods for deleting samples from database"""
def delete_sample(self, sample_id):
"""Delete single sample from database"""
<|body_0|>
def delete_group(self, group_id):
"""Delete entire group from database"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_002309 | 807 | permissive | [
{
"docstring": "Delete single sample from database",
"name": "delete_sample",
"signature": "def delete_sample(self, sample_id)"
},
{
"docstring": "Delete entire group from database",
"name": "delete_group",
"signature": "def delete_group(self, group_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004629 | Implement the Python class `DeleteMixin` described below.
Class description:
Methods for deleting samples from database
Method signatures and docstrings:
- def delete_sample(self, sample_id): Delete single sample from database
- def delete_group(self, group_id): Delete entire group from database | Implement the Python class `DeleteMixin` described below.
Class description:
Methods for deleting samples from database
Method signatures and docstrings:
- def delete_sample(self, sample_id): Delete single sample from database
- def delete_group(self, group_id): Delete entire group from database
<|skeleton|>
class D... | 13f80c592ade1693590992bc66af31b8c0600210 | <|skeleton|>
class DeleteMixin:
"""Methods for deleting samples from database"""
def delete_sample(self, sample_id):
"""Delete single sample from database"""
<|body_0|>
def delete_group(self, group_id):
"""Delete entire group from database"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeleteMixin:
"""Methods for deleting samples from database"""
def delete_sample(self, sample_id):
"""Delete single sample from database"""
sample = list(self.fetch_samples(sample_id=sample_id))
if len(sample) > 0:
LOG.info('Deleting sample %s from database', sample[0].... | the_stack_v2_python_sparse | chanjo/store/delete.py | Clinical-Genomics/chanjo | train | 10 |
8d5b41c37cb068490bb3cafe719cea9e64cb1d21 | [
"self.linha = int(linha)\nself.coluna = int(coluna)\nself.robo = robo\nself.arena = []\nself.robo.posicao = 0\nfor i in range(linha):\n entrada = input()\n line = []\n for j in range(coluna):\n line.append(entrada[j])\n if not self.robo.posicao != 0:\n self.encontraPos(entrada[j], ... | <|body_start_0|>
self.linha = int(linha)
self.coluna = int(coluna)
self.robo = robo
self.arena = []
self.robo.posicao = 0
for i in range(linha):
entrada = input()
line = []
for j in range(coluna):
line.append(entrada[j])... | Classe Arena. | Arena | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Arena:
"""Classe Arena."""
def __init__(self, linha, coluna, robo):
"""Construtor."""
<|body_0|>
def __repr__(self):
"""Plota arena."""
<|body_1|>
def encontraPos(self, entrada, x, y):
"""Enc."""
<|body_2|>
def posAnteior(self):
... | stack_v2_sparse_classes_10k_train_002310 | 3,220 | no_license | [
{
"docstring": "Construtor.",
"name": "__init__",
"signature": "def __init__(self, linha, coluna, robo)"
},
{
"docstring": "Plota arena.",
"name": "__repr__",
"signature": "def __repr__(self)"
},
{
"docstring": "Enc.",
"name": "encontraPos",
"signature": "def encontraPos(... | 6 | stack_v2_sparse_classes_30k_train_002015 | Implement the Python class `Arena` described below.
Class description:
Classe Arena.
Method signatures and docstrings:
- def __init__(self, linha, coluna, robo): Construtor.
- def __repr__(self): Plota arena.
- def encontraPos(self, entrada, x, y): Enc.
- def posAnteior(self): Altera na Arena a posicao anterior.
- de... | Implement the Python class `Arena` described below.
Class description:
Classe Arena.
Method signatures and docstrings:
- def __init__(self, linha, coluna, robo): Construtor.
- def __repr__(self): Plota arena.
- def encontraPos(self, entrada, x, y): Enc.
- def posAnteior(self): Altera na Arena a posicao anterior.
- de... | e79b79c8b78693bf1d5d8843f7b0121be70bca70 | <|skeleton|>
class Arena:
"""Classe Arena."""
def __init__(self, linha, coluna, robo):
"""Construtor."""
<|body_0|>
def __repr__(self):
"""Plota arena."""
<|body_1|>
def encontraPos(self, entrada, x, y):
"""Enc."""
<|body_2|>
def posAnteior(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Arena:
"""Classe Arena."""
def __init__(self, linha, coluna, robo):
"""Construtor."""
self.linha = int(linha)
self.coluna = int(coluna)
self.robo = robo
self.arena = []
self.robo.posicao = 0
for i in range(linha):
entrada = input()
... | the_stack_v2_python_sparse | roboColecionadorOO.py | jonathasfsilva/lab-jfs-20181 | train | 0 |
4e839ba3808743ba8c8785079521bbfa02a0e34f | [
"id = request.GET.get('id', None)\nif id is None:\n offering_courses = OfferingCourse.objects.all()\n serializer = OfferingCourseSerializer(offering_courses, many=True)\n return JsonResponse({'offering_courses': serializer.data}, safe=False)\nelse:\n offering_course = get_object_or_404(OfferingCourse, i... | <|body_start_0|>
id = request.GET.get('id', None)
if id is None:
offering_courses = OfferingCourse.objects.all()
serializer = OfferingCourseSerializer(offering_courses, many=True)
return JsonResponse({'offering_courses': serializer.data}, safe=False)
else:
... | 开设课程view | OfferingCourses | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfferingCourses:
"""开设课程view"""
def get(self, request):
"""查询开设课程"""
<|body_0|>
def put(self, request):
"""修改开设课程"""
<|body_1|>
def post(self, request):
"""增加开设课程"""
<|body_2|>
def delete(self, request):
"""删除开设课程"""
... | stack_v2_sparse_classes_10k_train_002311 | 15,061 | permissive | [
{
"docstring": "查询开设课程",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "修改开设课程",
"name": "put",
"signature": "def put(self, request)"
},
{
"docstring": "增加开设课程",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "删除开... | 4 | stack_v2_sparse_classes_30k_train_003092 | Implement the Python class `OfferingCourses` described below.
Class description:
开设课程view
Method signatures and docstrings:
- def get(self, request): 查询开设课程
- def put(self, request): 修改开设课程
- def post(self, request): 增加开设课程
- def delete(self, request): 删除开设课程 | Implement the Python class `OfferingCourses` described below.
Class description:
开设课程view
Method signatures and docstrings:
- def get(self, request): 查询开设课程
- def put(self, request): 修改开设课程
- def post(self, request): 增加开设课程
- def delete(self, request): 删除开设课程
<|skeleton|>
class OfferingCourses:
"""开设课程view"""
... | 7aaa1be773718de1beb3ce0080edca7c4114b7ad | <|skeleton|>
class OfferingCourses:
"""开设课程view"""
def get(self, request):
"""查询开设课程"""
<|body_0|>
def put(self, request):
"""修改开设课程"""
<|body_1|>
def post(self, request):
"""增加开设课程"""
<|body_2|>
def delete(self, request):
"""删除开设课程"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OfferingCourses:
"""开设课程view"""
def get(self, request):
"""查询开设课程"""
id = request.GET.get('id', None)
if id is None:
offering_courses = OfferingCourse.objects.all()
serializer = OfferingCourseSerializer(offering_courses, many=True)
return JsonRe... | the_stack_v2_python_sparse | plan/views.py | MIXISAMA/MIS-backend | train | 0 |
89f95e76da8855e7c66229e30d32b041b0dbc7c5 | [
"items = []\nif info.line.strip().startswith(('import ', 'from ')) and info.is_python_like:\n items += module_completion(info.line, [info.filename])\nelif info.obj:\n base = info.obj\n tokens = set(info.split_words(-1))\n items = [item for item in tokens if item.startswith(base) and len(item) > len(base... | <|body_start_0|>
items = []
if info.line.strip().startswith(('import ', 'from ')) and info.is_python_like:
items += module_completion(info.line, [info.filename])
elif info.obj:
base = info.obj
tokens = set(info.split_words(-1))
items = [item for it... | Basic Introspection Plugin for Spyder | FallbackPlugin | [
"Python-2.0",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FallbackPlugin:
"""Basic Introspection Plugin for Spyder"""
def get_completions(self, info):
"""Return a list of completion strings Simple completion based on python-like identifiers and whitespace"""
<|body_0|>
def get_definition(self, info):
"""Find the definit... | stack_v2_sparse_classes_10k_train_002312 | 13,005 | permissive | [
{
"docstring": "Return a list of completion strings Simple completion based on python-like identifiers and whitespace",
"name": "get_completions",
"signature": "def get_completions(self, info)"
},
{
"docstring": "Find the definition for an object within a set of source code This is used to find ... | 2 | stack_v2_sparse_classes_30k_train_007095 | Implement the Python class `FallbackPlugin` described below.
Class description:
Basic Introspection Plugin for Spyder
Method signatures and docstrings:
- def get_completions(self, info): Return a list of completion strings Simple completion based on python-like identifiers and whitespace
- def get_definition(self, in... | Implement the Python class `FallbackPlugin` described below.
Class description:
Basic Introspection Plugin for Spyder
Method signatures and docstrings:
- def get_completions(self, info): Return a list of completion strings Simple completion based on python-like identifiers and whitespace
- def get_definition(self, in... | 2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6 | <|skeleton|>
class FallbackPlugin:
"""Basic Introspection Plugin for Spyder"""
def get_completions(self, info):
"""Return a list of completion strings Simple completion based on python-like identifiers and whitespace"""
<|body_0|>
def get_definition(self, info):
"""Find the definit... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FallbackPlugin:
"""Basic Introspection Plugin for Spyder"""
def get_completions(self, info):
"""Return a list of completion strings Simple completion based on python-like identifiers and whitespace"""
items = []
if info.line.strip().startswith(('import ', 'from ')) and info.is_pyt... | the_stack_v2_python_sparse | lib/python2.7/site-packages/spyderlib/utils/introspection/fallback_plugin.py | wangyum/Anaconda | train | 11 |
d4e64a98de5a58c7fd5ddbd72b6e1516adfe6f4b | [
"if Singleton.__instance == None:\n Singleton()\nreturn Singleton.__instance",
"if Singleton.__instance != None:\n raise Exception('This class is a singleton!')\nelse:\n Singleton.__instance = self"
] | <|body_start_0|>
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
<|end_body_0|>
<|body_start_1|>
if Singleton.__instance != None:
raise Exception('This class is a singleton!')
else:
Singleton.__instance = self
<|end_body_1|>
| Singleton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Singleton:
def getInstance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if Singleton.__instance == None:
Singleton()
return Single... | stack_v2_sparse_classes_10k_train_002313 | 1,319 | no_license | [
{
"docstring": "Static access method.",
"name": "getInstance",
"signature": "def getInstance()"
},
{
"docstring": "Virtually private constructor.",
"name": "__init__",
"signature": "def __init__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000709 | Implement the Python class `Singleton` described below.
Class description:
Implement the Singleton class.
Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self): Virtually private constructor. | Implement the Python class `Singleton` described below.
Class description:
Implement the Singleton class.
Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self): Virtually private constructor.
<|skeleton|>
class Singleton:
def getInstance():
"""Static access me... | ed5f232f6737bc9f750d704455442f239d4f0561 | <|skeleton|>
class Singleton:
def getInstance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Singleton:
def getInstance():
"""Static access method."""
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
def __init__(self):
"""Virtually private constructor."""
if Singleton.__instance != None:
raise Exception('Thi... | the_stack_v2_python_sparse | codes/design_pattern/02_singleton.py | Ziaeemehr/workshop_scripting | train | 4 | |
e05c94385259b4a27a8898fd11c194dd761a9f6f | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SharedInsight()",
"from .entity import Entity\nfrom .resource_reference import ResourceReference\nfrom .resource_visualization import ResourceVisualization\nfrom .sharing_detail import SharingDetail\nfrom .entity import Entity\nfrom .r... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SharedInsight()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .resource_reference import ResourceReference
from .resource_visualization import ResourceVisualiza... | SharedInsight | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SharedInsight:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedInsight:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_10k_train_002314 | 4,000 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: SharedInsight",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | null | Implement the Python class `SharedInsight` described below.
Class description:
Implement the SharedInsight class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedInsight: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `SharedInsight` described below.
Class description:
Implement the SharedInsight class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedInsight: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SharedInsight:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedInsight:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SharedInsight:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharedInsight:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: SharedInsigh... | the_stack_v2_python_sparse | msgraph/generated/models/shared_insight.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
9dffa748bf4130da477d2e19d7e1e1a4fb6a5bfb | [
"assert len(sep) == 1\nself._sep = sep\nsuper().__init__(*args, **kwargs)",
"if value is None:\n return None\nelif not isinstance(value, list) or set(map(type, value)) != {str}:\n raise ValueError('ListField stores lists of strings.')\nif any((self._sep in item for item in value)):\n raise ValueError(f'L... | <|body_start_0|>
assert len(sep) == 1
self._sep = sep
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
if value is None:
return None
elif not isinstance(value, list) or set(map(type, value)) != {str}:
raise ValueError('ListField stores li... | A field to facilitate storing lists of strings as a textfield. | ListField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListField:
"""A field to facilitate storing lists of strings as a textfield."""
def __init__(self, sep: str=',', *args: T.Any, **kwargs: T.Any) -> None:
"""init. Args: sep: What separator to use to separate fields. *args: Passed to pw.CharField. *kwargs: Passed to pw.CharField."""
... | stack_v2_sparse_classes_10k_train_002315 | 9,976 | no_license | [
{
"docstring": "init. Args: sep: What separator to use to separate fields. *args: Passed to pw.CharField. *kwargs: Passed to pw.CharField.",
"name": "__init__",
"signature": "def __init__(self, sep: str=',', *args: T.Any, **kwargs: T.Any) -> None"
},
{
"docstring": "Validate and convert to strin... | 3 | stack_v2_sparse_classes_30k_train_001977 | Implement the Python class `ListField` described below.
Class description:
A field to facilitate storing lists of strings as a textfield.
Method signatures and docstrings:
- def __init__(self, sep: str=',', *args: T.Any, **kwargs: T.Any) -> None: init. Args: sep: What separator to use to separate fields. *args: Passe... | Implement the Python class `ListField` described below.
Class description:
A field to facilitate storing lists of strings as a textfield.
Method signatures and docstrings:
- def __init__(self, sep: str=',', *args: T.Any, **kwargs: T.Any) -> None: init. Args: sep: What separator to use to separate fields. *args: Passe... | 46a5fee829c6e722afced0a3bc93cc41ded8c68e | <|skeleton|>
class ListField:
"""A field to facilitate storing lists of strings as a textfield."""
def __init__(self, sep: str=',', *args: T.Any, **kwargs: T.Any) -> None:
"""init. Args: sep: What separator to use to separate fields. *args: Passed to pw.CharField. *kwargs: Passed to pw.CharField."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ListField:
"""A field to facilitate storing lists of strings as a textfield."""
def __init__(self, sep: str=',', *args: T.Any, **kwargs: T.Any) -> None:
"""init. Args: sep: What separator to use to separate fields. *args: Passed to pw.CharField. *kwargs: Passed to pw.CharField."""
assert ... | the_stack_v2_python_sparse | services/web/backend/flask_app/database/models.py | arenabox/openFraming | train | 0 |
7170a4a385d109166c0a985d85f7ccca6c99e23d | [
"if not head or not head.next:\n return head\np = head\nq = head.next\nhead.next = None\nwhile q:\n r = q.next\n q.next = p\n p = q\n q = r\nreturn p",
"if not head or not head.next:\n return head\np = head.next\nnewHead = self.reverseList(p)\np.next = head\nhead.next = None\nreturn newHead"
] | <|body_start_0|>
if not head or not head.next:
return head
p = head
q = head.next
head.next = None
while q:
r = q.next
q.next = p
p = q
q = r
return p
<|end_body_0|>
<|body_start_1|>
if not head or not h... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList1(self, head):
"""迭代 :param head: :return:"""
<|body_0|>
def reverseList(self, head: ListNode) -> ListNode:
"""递归 :param head: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head or not head.next:
... | stack_v2_sparse_classes_10k_train_002316 | 868 | no_license | [
{
"docstring": "迭代 :param head: :return:",
"name": "reverseList1",
"signature": "def reverseList1(self, head)"
},
{
"docstring": "递归 :param head: :return:",
"name": "reverseList",
"signature": "def reverseList(self, head: ListNode) -> ListNode"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList1(self, head): 迭代 :param head: :return:
- def reverseList(self, head: ListNode) -> ListNode: 递归 :param head: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList1(self, head): 迭代 :param head: :return:
- def reverseList(self, head: ListNode) -> ListNode: 递归 :param head: :return:
<|skeleton|>
class Solution:
def revers... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def reverseList1(self, head):
"""迭代 :param head: :return:"""
<|body_0|>
def reverseList(self, head: ListNode) -> ListNode:
"""递归 :param head: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList1(self, head):
"""迭代 :param head: :return:"""
if not head or not head.next:
return head
p = head
q = head.next
head.next = None
while q:
r = q.next
q.next = p
p = q
q = r
... | the_stack_v2_python_sparse | 206_反转链表.py | lovehhf/LeetCode | train | 0 | |
ed94486254899116b94770c0259e0fb6dc50c06d | [
"date_formatter = date.getLocaleFormatter(self.request, 'date', 'long')\n\ndef _q_data_item(q):\n item = {}\n item['qid'] = 'q_%s' % q.question_id\n if q.question_number:\n item['subject'] = u'Q %s %s' % (q.question_number, q.short_name)\n else:\n item['subject'] = q.short_name\n item['... | <|body_start_0|>
date_formatter = date.getLocaleFormatter(self.request, 'date', 'long')
def _q_data_item(q):
item = {}
item['qid'] = 'q_%s' % q.question_id
if q.question_number:
item['subject'] = u'Q %s %s' % (q.question_number, q.short_name)
... | QuestionInStateViewlet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionInStateViewlet:
def _setData(self):
"""return the data of the query"""
<|body_0|>
def update(self):
"""refresh the query"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
date_formatter = date.getLocaleFormatter(self.request, 'date', 'long')
... | stack_v2_sparse_classes_10k_train_002317 | 27,657 | no_license | [
{
"docstring": "return the data of the query",
"name": "_setData",
"signature": "def _setData(self)"
},
{
"docstring": "refresh the query",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001156 | Implement the Python class `QuestionInStateViewlet` described below.
Class description:
Implement the QuestionInStateViewlet class.
Method signatures and docstrings:
- def _setData(self): return the data of the query
- def update(self): refresh the query | Implement the Python class `QuestionInStateViewlet` described below.
Class description:
Implement the QuestionInStateViewlet class.
Method signatures and docstrings:
- def _setData(self): return the data of the query
- def update(self): refresh the query
<|skeleton|>
class QuestionInStateViewlet:
def _setData(s... | 5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d | <|skeleton|>
class QuestionInStateViewlet:
def _setData(self):
"""return the data of the query"""
<|body_0|>
def update(self):
"""refresh the query"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QuestionInStateViewlet:
def _setData(self):
"""return the data of the query"""
date_formatter = date.getLocaleFormatter(self.request, 'date', 'long')
def _q_data_item(q):
item = {}
item['qid'] = 'q_%s' % q.question_id
if q.question_number:
... | the_stack_v2_python_sparse | bungeni.main/branches/mr/bungeni/ui/viewlets/workspace.py | malangalanga/bungeni-portal | train | 0 | |
a5048a5623ff03a9a7e278c717148999e69b8549 | [
"lines = make_model()\nlog = get_logger(level='warning', encoding='utf-8')\nmodel = read_abaqus(lines, log=log, debug=False)\nmodel.write('spike.inp')\nos.remove('spike.inp')\nabaqus_filename = os.path.join(MODEL_PATH, 'abaqus.inp')\nwith open(abaqus_filename, 'w') as abaqus_file:\n abaqus_file.writelines('\\n'.... | <|body_start_0|>
lines = make_model()
log = get_logger(level='warning', encoding='utf-8')
model = read_abaqus(lines, log=log, debug=False)
model.write('spike.inp')
os.remove('spike.inp')
abaqus_filename = os.path.join(MODEL_PATH, 'abaqus.inp')
with open(abaqus_fil... | TestAbaqus | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAbaqus:
def test_abaqus_1(self):
"""simple test"""
<|body_0|>
def test_abaqus_2(self):
"""two hex blocks with duplicate node ids"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
lines = make_model()
log = get_logger(level='warning', encod... | stack_v2_sparse_classes_10k_train_002318 | 3,005 | no_license | [
{
"docstring": "simple test",
"name": "test_abaqus_1",
"signature": "def test_abaqus_1(self)"
},
{
"docstring": "two hex blocks with duplicate node ids",
"name": "test_abaqus_2",
"signature": "def test_abaqus_2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003884 | Implement the Python class `TestAbaqus` described below.
Class description:
Implement the TestAbaqus class.
Method signatures and docstrings:
- def test_abaqus_1(self): simple test
- def test_abaqus_2(self): two hex blocks with duplicate node ids | Implement the Python class `TestAbaqus` described below.
Class description:
Implement the TestAbaqus class.
Method signatures and docstrings:
- def test_abaqus_1(self): simple test
- def test_abaqus_2(self): two hex blocks with duplicate node ids
<|skeleton|>
class TestAbaqus:
def test_abaqus_1(self):
"... | d9ffdb4ac845b13bcf6aea96ff5d37cc026c5267 | <|skeleton|>
class TestAbaqus:
def test_abaqus_1(self):
"""simple test"""
<|body_0|>
def test_abaqus_2(self):
"""two hex blocks with duplicate node ids"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestAbaqus:
def test_abaqus_1(self):
"""simple test"""
lines = make_model()
log = get_logger(level='warning', encoding='utf-8')
model = read_abaqus(lines, log=log, debug=False)
model.write('spike.inp')
os.remove('spike.inp')
abaqus_filename = os.path.joi... | the_stack_v2_python_sparse | pyNastran/converters/abaqus/test_unit_abaqus.py | ratalex/pyNastran | train | 0 | |
c079ccd79ea0b2e24628d41bb02a42ab6dcae4e2 | [
"self.model_type = model_type\nself.model_name = model_name\nself.model_task = model_task\nself.model_description = model_description\nself.model_folder = os.path.join(ROOT_DIR, self.model_type, self.model_task, self.model_name)\nself.bucket = s3.S3Bucket(bucket_name='s3ludos')\nif not os.path.isdir(self.model_fold... | <|body_start_0|>
self.model_type = model_type
self.model_name = model_name
self.model_task = model_task
self.model_description = model_description
self.model_folder = os.path.join(ROOT_DIR, self.model_type, self.model_task, self.model_name)
self.bucket = s3.S3Bucket(bucke... | Base class for the model | BaseModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseModel:
"""Base class for the model"""
def __init__(self, model_name: str, model_task: str, model_description: str='', expname: str=None, model_type: str='models'):
"""Args: model_type (str): Type of the model, 'models' model_name (str): Name of your model model_task (str): Task o... | stack_v2_sparse_classes_10k_train_002319 | 3,053 | no_license | [
{
"docstring": "Args: model_type (str): Type of the model, 'models' model_name (str): Name of your model model_task (str): Task of your model stage (str): training or prediction expname (str): Name of the experiment",
"name": "__init__",
"signature": "def __init__(self, model_name: str, model_task: str,... | 2 | stack_v2_sparse_classes_30k_train_000663 | Implement the Python class `BaseModel` described below.
Class description:
Base class for the model
Method signatures and docstrings:
- def __init__(self, model_name: str, model_task: str, model_description: str='', expname: str=None, model_type: str='models'): Args: model_type (str): Type of the model, 'models' mode... | Implement the Python class `BaseModel` described below.
Class description:
Base class for the model
Method signatures and docstrings:
- def __init__(self, model_name: str, model_task: str, model_description: str='', expname: str=None, model_type: str='models'): Args: model_type (str): Type of the model, 'models' mode... | fd09eb1bceafe794d8784a21cfd3753cfd371258 | <|skeleton|>
class BaseModel:
"""Base class for the model"""
def __init__(self, model_name: str, model_task: str, model_description: str='', expname: str=None, model_type: str='models'):
"""Args: model_type (str): Type of the model, 'models' model_name (str): Name of your model model_task (str): Task o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaseModel:
"""Base class for the model"""
def __init__(self, model_name: str, model_task: str, model_description: str='', expname: str=None, model_type: str='models'):
"""Args: model_type (str): Type of the model, 'models' model_name (str): Name of your model model_task (str): Task of your model ... | the_stack_v2_python_sparse | ludos/models/common.py | cthorey/ludos | train | 0 |
eb6fc78df232b9999907f3ff2815886f1ae26f5d | [
"DataUnitSettings.__init__(self, n)\nself.registerCounted('IntensityTransferFunctions', 1)\nself.register('InterpolationTimepoints', 1)\nself.set('Type', 'Adjust')\nself.registerPrivate('ColorTransferFunction', 1)\nself.registerCounted('Source')\nself.register('VoxelSize')\nself.register('Spacing')\nself.register('... | <|body_start_0|>
DataUnitSettings.__init__(self, n)
self.registerCounted('IntensityTransferFunctions', 1)
self.register('InterpolationTimepoints', 1)
self.set('Type', 'Adjust')
self.registerPrivate('ColorTransferFunction', 1)
self.registerCounted('Source')
self.re... | Description: Stores settings related to dataset adjustment | AdjustSettings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdjustSettings:
"""Description: Stores settings related to dataset adjustment"""
def __init__(self, n=-1):
"""Constructor"""
<|body_0|>
def initialize(self, dataunit, channels, timepoints):
"""Set initial values for settings based on number of channels and timepo... | stack_v2_sparse_classes_10k_train_002320 | 2,815 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, n=-1)"
},
{
"docstring": "Set initial values for settings based on number of channels and timepoints",
"name": "initialize",
"signature": "def initialize(self, dataunit, channels, timepoints)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005469 | Implement the Python class `AdjustSettings` described below.
Class description:
Description: Stores settings related to dataset adjustment
Method signatures and docstrings:
- def __init__(self, n=-1): Constructor
- def initialize(self, dataunit, channels, timepoints): Set initial values for settings based on number o... | Implement the Python class `AdjustSettings` described below.
Class description:
Description: Stores settings related to dataset adjustment
Method signatures and docstrings:
- def __init__(self, n=-1): Constructor
- def initialize(self, dataunit, channels, timepoints): Set initial values for settings based on number o... | ea8bafa073de5090bd8f83fb4f5ca16669d0211f | <|skeleton|>
class AdjustSettings:
"""Description: Stores settings related to dataset adjustment"""
def __init__(self, n=-1):
"""Constructor"""
<|body_0|>
def initialize(self, dataunit, channels, timepoints):
"""Set initial values for settings based on number of channels and timepo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AdjustSettings:
"""Description: Stores settings related to dataset adjustment"""
def __init__(self, n=-1):
"""Constructor"""
DataUnitSettings.__init__(self, n)
self.registerCounted('IntensityTransferFunctions', 1)
self.register('InterpolationTimepoints', 1)
self.se... | the_stack_v2_python_sparse | Graphs/LX-2/molecule_otsu = False/BioImageXD-1.0/Modules/Task/Adjust/AdjustSettings.py | giacomo21/Image-analysis | train | 1 |
22797439416b5ec13b2082d3d7d637441f0214c3 | [
"self.data_dir = FileOps.download_dataset(data_dir)\nself.batch_size = batch_size\nself.mode = mode\nself.num_parallel_batches = num_parallel_batches\nself.repeat_num = repeat_num\nself.dtype = tf.float16 if fp16 is True else tf.float32\nself.drop_remainder = drop_remainder\nself._include_mask = False\nself._datase... | <|body_start_0|>
self.data_dir = FileOps.download_dataset(data_dir)
self.batch_size = batch_size
self.mode = mode
self.num_parallel_batches = num_parallel_batches
self.repeat_num = repeat_num
self.dtype = tf.float16 if fp16 is True else tf.float32
self.drop_remain... | This is a class for Coco TFRecords dataset. :param data_dir: Coco TFRecords data directory :type data_dir: str :param batch_size: batch size :type batch_size: int :param mode: dataset mode, train or val :type mode: str :param num_parallel_batches: number of parallel batches :type num_parallel_batches: int, default 1 :p... | CocoDataset | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CocoDataset:
"""This is a class for Coco TFRecords dataset. :param data_dir: Coco TFRecords data directory :type data_dir: str :param batch_size: batch size :type batch_size: int :param mode: dataset mode, train or val :type mode: str :param num_parallel_batches: number of parallel batches :type ... | stack_v2_sparse_classes_10k_train_002321 | 5,507 | permissive | [
{
"docstring": "Init CocoTF.",
"name": "__init__",
"signature": "def __init__(self, data_dir, batch_size, mode, num_parallel_batches=1, repeat_num=5, padding=8, fp16=False, drop_remainder=False)"
},
{
"docstring": "Coco data files of type TFRecords.",
"name": "_file_pattern",
"signature"... | 4 | null | Implement the Python class `CocoDataset` described below.
Class description:
This is a class for Coco TFRecords dataset. :param data_dir: Coco TFRecords data directory :type data_dir: str :param batch_size: batch size :type batch_size: int :param mode: dataset mode, train or val :type mode: str :param num_parallel_bat... | Implement the Python class `CocoDataset` described below.
Class description:
This is a class for Coco TFRecords dataset. :param data_dir: Coco TFRecords data directory :type data_dir: str :param batch_size: batch size :type batch_size: int :param mode: dataset mode, train or val :type mode: str :param num_parallel_bat... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class CocoDataset:
"""This is a class for Coco TFRecords dataset. :param data_dir: Coco TFRecords data directory :type data_dir: str :param batch_size: batch size :type batch_size: int :param mode: dataset mode, train or val :type mode: str :param num_parallel_batches: number of parallel batches :type ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CocoDataset:
"""This is a class for Coco TFRecords dataset. :param data_dir: Coco TFRecords data directory :type data_dir: str :param batch_size: batch size :type batch_size: int :param mode: dataset mode, train or val :type mode: str :param num_parallel_batches: number of parallel batches :type num_parallel_... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/datasets/tensorflow/coco.py | Huawei-Ascend/modelzoo | train | 1 |
d113ebbfe7c02fb786ba4624e88cd009a9ba2598 | [
"with open(img_path, 'rb') as f:\n base64_data = base64.b64encode(f.read())\n base64_data = base64_data.decode('utf8')\n return base64_data",
"base64_encoding = base64_encoding.encode('utf8')\nimg_data = base64.b64decode(base64_encoding)\nwith open(des_img_path, 'wb') as file:\n file.write(img_data)"
... | <|body_start_0|>
with open(img_path, 'rb') as f:
base64_data = base64.b64encode(f.read())
base64_data = base64_data.decode('utf8')
return base64_data
<|end_body_0|>
<|body_start_1|>
base64_encoding = base64_encoding.encode('utf8')
img_data = base64.b64decode(... | ImageTransform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageTransform:
def img_to_base64(img_path):
""":param img_path: :return:"""
<|body_0|>
def base64_to_img(base64_encoding, des_img_path):
""":param des_img_path: :param base64_encoding: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
with o... | stack_v2_sparse_classes_10k_train_002322 | 1,206 | no_license | [
{
"docstring": ":param img_path: :return:",
"name": "img_to_base64",
"signature": "def img_to_base64(img_path)"
},
{
"docstring": ":param des_img_path: :param base64_encoding: :return:",
"name": "base64_to_img",
"signature": "def base64_to_img(base64_encoding, des_img_path)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005997 | Implement the Python class `ImageTransform` described below.
Class description:
Implement the ImageTransform class.
Method signatures and docstrings:
- def img_to_base64(img_path): :param img_path: :return:
- def base64_to_img(base64_encoding, des_img_path): :param des_img_path: :param base64_encoding: :return: | Implement the Python class `ImageTransform` described below.
Class description:
Implement the ImageTransform class.
Method signatures and docstrings:
- def img_to_base64(img_path): :param img_path: :return:
- def base64_to_img(base64_encoding, des_img_path): :param des_img_path: :param base64_encoding: :return:
<|sk... | ee41eb80d6b8823cfd764920ed8aa4c682d9a013 | <|skeleton|>
class ImageTransform:
def img_to_base64(img_path):
""":param img_path: :return:"""
<|body_0|>
def base64_to_img(base64_encoding, des_img_path):
""":param des_img_path: :param base64_encoding: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImageTransform:
def img_to_base64(img_path):
""":param img_path: :return:"""
with open(img_path, 'rb') as f:
base64_data = base64.b64encode(f.read())
base64_data = base64_data.decode('utf8')
return base64_data
def base64_to_img(base64_encoding, des_img_... | the_stack_v2_python_sparse | data_custom_backend/llib/cv_utility/image_transform.py | marjeylee/cmdb | train | 0 | |
1738ed8d4580f1107dfbee9373698fe766ade0ac | [
"ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(self._build_enforcement_target_attr, role_id=role_id, project_id=project_id, group_id=group_id))\ninherited = self._check_if_inherited()\nPROVIDERS.assignment_api.get_grant(role_id=role_id, group_id=group_id, project_id=project_id,... | <|body_start_0|>
ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(self._build_enforcement_target_attr, role_id=role_id, project_id=project_id, group_id=group_id))
inherited = self._check_if_inherited()
PROVIDERS.assignment_api.get_grant(role_id=role_id, group_i... | ProjectGroupGrantResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectGroupGrantResource:
def get(self, project_id, group_id, role_id):
"""Check grant for project, group, role. GET/HEAD /v3/projects/{project_id/groups/{group_id}/roles/{role_id}"""
<|body_0|>
def put(self, project_id, group_id, role_id):
"""Grant role for group o... | stack_v2_sparse_classes_10k_train_002323 | 22,149 | permissive | [
{
"docstring": "Check grant for project, group, role. GET/HEAD /v3/projects/{project_id/groups/{group_id}/roles/{role_id}",
"name": "get",
"signature": "def get(self, project_id, group_id, role_id)"
},
{
"docstring": "Grant role for group on project. PUT /v3/projects/{project_id}/groups/{group_i... | 3 | stack_v2_sparse_classes_30k_train_006296 | Implement the Python class `ProjectGroupGrantResource` described below.
Class description:
Implement the ProjectGroupGrantResource class.
Method signatures and docstrings:
- def get(self, project_id, group_id, role_id): Check grant for project, group, role. GET/HEAD /v3/projects/{project_id/groups/{group_id}/roles/{r... | Implement the Python class `ProjectGroupGrantResource` described below.
Class description:
Implement the ProjectGroupGrantResource class.
Method signatures and docstrings:
- def get(self, project_id, group_id, role_id): Check grant for project, group, role. GET/HEAD /v3/projects/{project_id/groups/{group_id}/roles/{r... | 03a0a8146a78682ede9eca12a5a7fdacde2035c8 | <|skeleton|>
class ProjectGroupGrantResource:
def get(self, project_id, group_id, role_id):
"""Check grant for project, group, role. GET/HEAD /v3/projects/{project_id/groups/{group_id}/roles/{role_id}"""
<|body_0|>
def put(self, project_id, group_id, role_id):
"""Grant role for group o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProjectGroupGrantResource:
def get(self, project_id, group_id, role_id):
"""Check grant for project, group, role. GET/HEAD /v3/projects/{project_id/groups/{group_id}/roles/{role_id}"""
ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(self._build_enforcement_t... | the_stack_v2_python_sparse | keystone/api/projects.py | sapcc/keystone | train | 0 | |
011241ab57547be3ce8b0ab58fb256e7c80156d2 | [
"queryset = Workshop.objects.filter(club=obj, date__gte=date.today()).order_by('date', 'time')\nserializer = WorkshopSerializer(queryset, many=True)\nreturn serializer.data",
"queryset = Workshop.objects.filter(club=obj, date__lt=date.today()).order_by('-date', '-time')\nserializer = WorkshopSerializer(queryset, ... | <|body_start_0|>
queryset = Workshop.objects.filter(club=obj, date__gte=date.today()).order_by('date', 'time')
serializer = WorkshopSerializer(queryset, many=True)
return serializer.data
<|end_body_0|>
<|body_start_1|>
queryset = Workshop.objects.filter(club=obj, date__lt=date.today()).... | ClubDetailWorkshopSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClubDetailWorkshopSerializer:
def get_active_workshops(self, obj):
"""Active Workshops of the Club"""
<|body_0|>
def get_past_workshops(self, obj):
"""Past Workshops of the Club"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
queryset = Workshop.obj... | stack_v2_sparse_classes_10k_train_002324 | 18,006 | no_license | [
{
"docstring": "Active Workshops of the Club",
"name": "get_active_workshops",
"signature": "def get_active_workshops(self, obj)"
},
{
"docstring": "Past Workshops of the Club",
"name": "get_past_workshops",
"signature": "def get_past_workshops(self, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005283 | Implement the Python class `ClubDetailWorkshopSerializer` described below.
Class description:
Implement the ClubDetailWorkshopSerializer class.
Method signatures and docstrings:
- def get_active_workshops(self, obj): Active Workshops of the Club
- def get_past_workshops(self, obj): Past Workshops of the Club | Implement the Python class `ClubDetailWorkshopSerializer` described below.
Class description:
Implement the ClubDetailWorkshopSerializer class.
Method signatures and docstrings:
- def get_active_workshops(self, obj): Active Workshops of the Club
- def get_past_workshops(self, obj): Past Workshops of the Club
<|skele... | 7cd4eb5d82917dcc554331d3893108b809468505 | <|skeleton|>
class ClubDetailWorkshopSerializer:
def get_active_workshops(self, obj):
"""Active Workshops of the Club"""
<|body_0|>
def get_past_workshops(self, obj):
"""Past Workshops of the Club"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClubDetailWorkshopSerializer:
def get_active_workshops(self, obj):
"""Active Workshops of the Club"""
queryset = Workshop.objects.filter(club=obj, date__gte=date.today()).order_by('date', 'time')
serializer = WorkshopSerializer(queryset, many=True)
return serializer.data
d... | the_stack_v2_python_sparse | workshop/serializers.py | aishwary023/workshops-app-backend | train | 0 | |
d4ba1cd917884ee1503fe147fe6bb3ed9493e61f | [
"if not root:\n return 'n'\ns = ''\nstack = [root]\nwhile stack:\n root = stack.pop(0)\n if root:\n s += str(root.val)\n stack.append(root.left)\n stack.append(root.right)\n else:\n s += 'n'\n s += ' '\nreturn s",
"if not data:\n return None\ntree = data.split()\nif t... | <|body_start_0|>
if not root:
return 'n'
s = ''
stack = [root]
while stack:
root = stack.pop(0)
if root:
s += str(root.val)
stack.append(root.left)
stack.append(root.right)
else:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_002325 | 2,353 | 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_002505 | 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:... | ce29ea836bd20841d69972180273e4d4ec11514d | <|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 'n'
s = ''
stack = [root]
while stack:
root = stack.pop(0)
if root:
s += str(root.val)
... | the_stack_v2_python_sparse | 37.py | NeilWangziyu/JZOffer | train | 1 | |
2a96946ba686a7a1d5903a949c583e63a1ad9946 | [
"self.device = device\nself.max_length = max_length\nself.config = AutoConfig.from_pretrained(model_name_or_path, cache_dir=cache_dir)\nself.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, cache_dir=cache_dir)\nself.model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path, config=self.config, ... | <|body_start_0|>
self.device = device
self.max_length = max_length
self.config = AutoConfig.from_pretrained(model_name_or_path, cache_dir=cache_dir)
self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, cache_dir=cache_dir)
self.model = AutoModelForSeq2SeqLM.from_pre... | UniEvaluator | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UniEvaluator:
def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None):
"""Set up model"""
<|body_0|>
def score(self, inputs, task, category, dim, batch_size=8):
"""Get scores for the given samples. final_score = postive_score / (posti... | stack_v2_sparse_classes_10k_train_002326 | 4,582 | permissive | [
{
"docstring": "Set up model",
"name": "__init__",
"signature": "def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None)"
},
{
"docstring": "Get scores for the given samples. final_score = postive_score / (postive_score + negative_score)",
"name": "score",
... | 2 | stack_v2_sparse_classes_30k_train_001918 | Implement the Python class `UniEvaluator` described below.
Class description:
Implement the UniEvaluator class.
Method signatures and docstrings:
- def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None): Set up model
- def score(self, inputs, task, category, dim, batch_size=8): Get s... | Implement the Python class `UniEvaluator` described below.
Class description:
Implement the UniEvaluator class.
Method signatures and docstrings:
- def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None): Set up model
- def score(self, inputs, task, category, dim, batch_size=8): Get s... | c7b60f75470f067d1342705708810a660eabd684 | <|skeleton|>
class UniEvaluator:
def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None):
"""Set up model"""
<|body_0|>
def score(self, inputs, task, category, dim, batch_size=8):
"""Get scores for the given samples. final_score = postive_score / (posti... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UniEvaluator:
def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None):
"""Set up model"""
self.device = device
self.max_length = max_length
self.config = AutoConfig.from_pretrained(model_name_or_path, cache_dir=cache_dir)
self.tokenizer ... | the_stack_v2_python_sparse | applications/Chat/evaluate/unieval/scorer.py | hpcaitech/ColossalAI | train | 32,044 | |
5e4198dcc9da98e7c4922d426edff324a07f9969 | [
"@self.router.get('/info', response_model=Info, response_model_exclude={'minzoom', 'maxzoom', 'center'}, response_model_exclude_none=True, responses={200: {'description': \"Return dataset's basic info or the list of available bands.\"}})\ndef info(src_path=Depends(self.path_dependency), bands_params=Depends(BandsPa... | <|body_start_0|>
@self.router.get('/info', response_model=Info, response_model_exclude={'minzoom', 'maxzoom', 'center'}, response_model_exclude_none=True, responses={200: {'description': "Return dataset's basic info or the list of available bands."}})
def info(src_path=Depends(self.path_dependency), ban... | Custom Tiler Factory for MultiBandReader classes. Note: To be able to use the rio_tiler.io.MultiBandReader we need to be able to pass a `bands` argument to most of its methods. By using the `BandsExprParams` for the `layer_dependency`, the .tile(), .point(), .preview() and the .part() methods will receive bands or expr... | MultiBandTilerFactory | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiBandTilerFactory:
"""Custom Tiler Factory for MultiBandReader classes. Note: To be able to use the rio_tiler.io.MultiBandReader we need to be able to pass a `bands` argument to most of its methods. By using the `BandsExprParams` for the `layer_dependency`, the .tile(), .point(), .preview() a... | stack_v2_sparse_classes_10k_train_002327 | 48,399 | permissive | [
{
"docstring": "Register /info endpoint.",
"name": "info",
"signature": "def info(self)"
},
{
"docstring": "Register /metadata endpoint.",
"name": "metadata",
"signature": "def metadata(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002633 | Implement the Python class `MultiBandTilerFactory` described below.
Class description:
Custom Tiler Factory for MultiBandReader classes. Note: To be able to use the rio_tiler.io.MultiBandReader we need to be able to pass a `bands` argument to most of its methods. By using the `BandsExprParams` for the `layer_dependenc... | Implement the Python class `MultiBandTilerFactory` described below.
Class description:
Custom Tiler Factory for MultiBandReader classes. Note: To be able to use the rio_tiler.io.MultiBandReader we need to be able to pass a `bands` argument to most of its methods. By using the `BandsExprParams` for the `layer_dependenc... | 2168c9284b39a46c4d1a095542c77addc690a738 | <|skeleton|>
class MultiBandTilerFactory:
"""Custom Tiler Factory for MultiBandReader classes. Note: To be able to use the rio_tiler.io.MultiBandReader we need to be able to pass a `bands` argument to most of its methods. By using the `BandsExprParams` for the `layer_dependency`, the .tile(), .point(), .preview() a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiBandTilerFactory:
"""Custom Tiler Factory for MultiBandReader classes. Note: To be able to use the rio_tiler.io.MultiBandReader we need to be able to pass a `bands` argument to most of its methods. By using the `BandsExprParams` for the `layer_dependency`, the .tile(), .point(), .preview() and the .part(... | the_stack_v2_python_sparse | src/titiler/core/titiler/core/factory.py | kylebarron/titiler | train | 0 |
a8e6acf38526e16b0a98e994e5692d53285264c5 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('yufeng72', 'yufeng72')\nurl = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/cbf14bb032ef4bd38e20429f71acb61a_2.csv'\nresponse = urllib.request.urlopen(url)\nr = csv.reader(io.StringIO(respon... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('yufeng72', 'yufeng72')
url = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/cbf14bb032ef4bd38e20429f71acb61a_2.csv'
response = urllib.... | RetrieveCollegesUniversities | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetrieveCollegesUniversities:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document descri... | stack_v2_sparse_classes_10k_train_002328 | 5,033 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_000899 | Implement the Python class `RetrieveCollegesUniversities` described below.
Class description:
Implement the RetrieveCollegesUniversities class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.Pro... | Implement the Python class `RetrieveCollegesUniversities` described below.
Class description:
Implement the RetrieveCollegesUniversities class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.Pro... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class RetrieveCollegesUniversities:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document descri... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RetrieveCollegesUniversities:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('yufeng72', 'yufeng72')... | the_stack_v2_python_sparse | yufeng72/RetrieveCollegesUniversities.py | maximega/course-2019-spr-proj | train | 2 | |
8e43691036f9dcded320b1e2f45e9f7698c44438 | [
"super().__init__(model_dir, *args, **kwargs)\nself.model_dir: str = model_dir\nself.sequence_length = kwargs.pop('sequence_length', 512)\nself.tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=True)",
"text = data\noutput = self.tokenizer([text], return_tensors='pt')\nreturn {'text': text, 'input_ids... | <|body_start_0|>
super().__init__(model_dir, *args, **kwargs)
self.model_dir: str = model_dir
self.sequence_length = kwargs.pop('sequence_length', 512)
self.tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=True)
<|end_body_0|>
<|body_start_1|>
text = data
ou... | The relation extraction preprocessor used in normal RE task. | RelationExtractionPreprocessor | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelationExtractionPreprocessor:
"""The relation extraction preprocessor used in normal RE task."""
def __init__(self, model_dir: str, *args, **kwargs):
"""preprocess the data Args: model_dir (str): model path"""
<|body_0|>
def __call__(self, data: str) -> Dict[str, Any]:... | stack_v2_sparse_classes_10k_train_002329 | 1,650 | permissive | [
{
"docstring": "preprocess the data 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 (str): a sentence Example: 'you are so handsome.' Returns: Dict[str, Any]: the p... | 2 | null | Implement the Python class `RelationExtractionPreprocessor` described below.
Class description:
The relation extraction preprocessor used in normal RE task.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): preprocess the data Args: model_dir (str): model path
- def __call__(sel... | Implement the Python class `RelationExtractionPreprocessor` described below.
Class description:
The relation extraction preprocessor used in normal RE task.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): preprocess the data Args: model_dir (str): model path
- def __call__(sel... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class RelationExtractionPreprocessor:
"""The relation extraction preprocessor used in normal RE task."""
def __init__(self, model_dir: str, *args, **kwargs):
"""preprocess the data Args: model_dir (str): model path"""
<|body_0|>
def __call__(self, data: str) -> Dict[str, Any]:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RelationExtractionPreprocessor:
"""The relation extraction preprocessor used in normal RE task."""
def __init__(self, model_dir: str, *args, **kwargs):
"""preprocess the data Args: model_dir (str): model path"""
super().__init__(model_dir, *args, **kwargs)
self.model_dir: str = mo... | the_stack_v2_python_sparse | ai/modelscope/modelscope/preprocessors/nlp/relation_extraction_preprocessor.py | alldatacenter/alldata | train | 774 |
e1e91015a9c30ca44aa92454e15189e1076b821b | [
"self.typology = 'Area'\nself.id = identifier\nself.name = name\nself.trt = trt\nself.geometry = geometry\nself.upper_depth = upper_depth\nself.lower_depth = lower_depth\nself.mag_scale_rel = mag_scale_rel\nself.rupt_aspect_ratio = rupt_aspect_ratio\nself.mfd = mfd\nself.nodal_plane_dist = nodal_plane_dist\nself.hy... | <|body_start_0|>
self.typology = 'Area'
self.id = identifier
self.name = name
self.trt = trt
self.geometry = geometry
self.upper_depth = upper_depth
self.lower_depth = lower_depth
self.mag_scale_rel = mag_scale_rel
self.rupt_aspect_ratio = rupt_asp... | Describes the Area Source :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: nhlib.geo.polygon.Polygon class :param float upper_depth: Upper seismogenic depth (km) :param float lower_depth: Lower seismogenic depth (km) :pa... | mtkAreaSource | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mtkAreaSource:
"""Describes the Area Source :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: nhlib.geo.polygon.Polygon class :param float upper_depth: Upper seismogenic depth (km) :param float lowe... | stack_v2_sparse_classes_10k_train_002330 | 9,101 | permissive | [
{
"docstring": "Instantiates class with two essential attributes: identifier and name",
"name": "__init__",
"signature": "def __init__(self, identifier, name, trt=None, geometry=None, upper_depth=None, lower_depth=None, mag_scale_rel=None, rupt_aspect_ratio=None, mfd=None, nodal_plane_dist=None, hypo_de... | 5 | stack_v2_sparse_classes_30k_train_005788 | Implement the Python class `mtkAreaSource` described below.
Class description:
Describes the Area Source :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: nhlib.geo.polygon.Polygon class :param float upper_depth: Upper s... | Implement the Python class `mtkAreaSource` described below.
Class description:
Describes the Area Source :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: nhlib.geo.polygon.Polygon class :param float upper_depth: Upper s... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class mtkAreaSource:
"""Describes the Area Source :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: nhlib.geo.polygon.Polygon class :param float upper_depth: Upper seismogenic depth (km) :param float lowe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class mtkAreaSource:
"""Describes the Area Source :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: nhlib.geo.polygon.Polygon class :param float upper_depth: Upper seismogenic depth (km) :param float lower_depth: Lowe... | the_stack_v2_python_sparse | openquake/hmtk/sources/area_source.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
4a0521e733d7580ef3eba6519f3e26a369b68637 | [
"super().__init__()\nself.spherical_cheb = SphericalChebConv(in_channels, out_channels, lap, kernel_size)\nself.batchnorm = nn.BatchNorm1d(out_channels)",
"x = self.spherical_cheb(x)\nx = self.batchnorm(x.permute(0, 2, 1))\nx = F.relu(x.permute(0, 2, 1))\nreturn x"
] | <|body_start_0|>
super().__init__()
self.spherical_cheb = SphericalChebConv(in_channels, out_channels, lap, kernel_size)
self.batchnorm = nn.BatchNorm1d(out_channels)
<|end_body_0|>
<|body_start_1|>
x = self.spherical_cheb(x)
x = self.batchnorm(x.permute(0, 2, 1))
x = F.... | Building Block with a Chebyshev Convolution, Batchnormalization, and ReLu activation. | SphericalChebBN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalChebBN:
"""Building Block with a Chebyshev Convolution, Batchnormalization, and ReLu activation."""
def __init__(self, in_channels, out_channels, lap, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. out_channels (int): output number of c... | stack_v2_sparse_classes_10k_train_002331 | 41,403 | no_license | [
{
"docstring": "Initialization. Args: in_channels (int): initial number of channels. out_channels (int): output number of channels. lap (:obj:`torch.sparse.FloatTensor`): laplacian. kernel_size (int, optional): polynomial degree. Defaults to 3.",
"name": "__init__",
"signature": "def __init__(self, in_c... | 2 | null | Implement the Python class `SphericalChebBN` described below.
Class description:
Building Block with a Chebyshev Convolution, Batchnormalization, and ReLu activation.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, lap, kernel_size): Initialization. Args: in_channels (int): initial n... | Implement the Python class `SphericalChebBN` described below.
Class description:
Building Block with a Chebyshev Convolution, Batchnormalization, and ReLu activation.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, lap, kernel_size): Initialization. Args: in_channels (int): initial n... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SphericalChebBN:
"""Building Block with a Chebyshev Convolution, Batchnormalization, and ReLu activation."""
def __init__(self, in_channels, out_channels, lap, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. out_channels (int): output number of c... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SphericalChebBN:
"""Building Block with a Chebyshev Convolution, Batchnormalization, and ReLu activation."""
def __init__(self, in_channels, out_channels, lap, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. out_channels (int): output number of channels. lap ... | the_stack_v2_python_sparse | generated/test_deepsphere_deepsphere_pytorch.py | jansel/pytorch-jit-paritybench | train | 35 |
166f1110ae1960c9a1910891171dde528767ece6 | [
"params = self.get_set_params(locals())\nresponse = await self.api.request('donut.getFriends', params)\nmodel = donut.GetFriendsResponse\nreturn model(**response).response",
"params = self.get_set_params(locals())\nresponse = await self.api.request('donut.getSubscription', params)\nmodel = donut.GetSubscriptionRe... | <|body_start_0|>
params = self.get_set_params(locals())
response = await self.api.request('donut.getFriends', params)
model = donut.GetFriendsResponse
return model(**response).response
<|end_body_0|>
<|body_start_1|>
params = self.get_set_params(locals())
response = awai... | DonutCategory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DonutCategory:
async def get_friends(self, owner_id: int, offset: Optional[int]=None, count: Optional[int]=None, fields: Optional[List[str]]=None, **kwargs) -> donut.GetFriendsResponseModel:
"""donut.getFriends method :param owner_id: :param offset: :param count: :param fields:"""
... | stack_v2_sparse_classes_10k_train_002332 | 1,897 | permissive | [
{
"docstring": "donut.getFriends method :param owner_id: :param offset: :param count: :param fields:",
"name": "get_friends",
"signature": "async def get_friends(self, owner_id: int, offset: Optional[int]=None, count: Optional[int]=None, fields: Optional[List[str]]=None, **kwargs) -> donut.GetFriendsRes... | 4 | stack_v2_sparse_classes_30k_val_000385 | Implement the Python class `DonutCategory` described below.
Class description:
Implement the DonutCategory class.
Method signatures and docstrings:
- async def get_friends(self, owner_id: int, offset: Optional[int]=None, count: Optional[int]=None, fields: Optional[List[str]]=None, **kwargs) -> donut.GetFriendsRespons... | Implement the Python class `DonutCategory` described below.
Class description:
Implement the DonutCategory class.
Method signatures and docstrings:
- async def get_friends(self, owner_id: int, offset: Optional[int]=None, count: Optional[int]=None, fields: Optional[List[str]]=None, **kwargs) -> donut.GetFriendsRespons... | dfcedd4023aa170dd7f802ac662f0e2ed9033904 | <|skeleton|>
class DonutCategory:
async def get_friends(self, owner_id: int, offset: Optional[int]=None, count: Optional[int]=None, fields: Optional[List[str]]=None, **kwargs) -> donut.GetFriendsResponseModel:
"""donut.getFriends method :param owner_id: :param offset: :param count: :param fields:"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DonutCategory:
async def get_friends(self, owner_id: int, offset: Optional[int]=None, count: Optional[int]=None, fields: Optional[List[str]]=None, **kwargs) -> donut.GetFriendsResponseModel:
"""donut.getFriends method :param owner_id: :param offset: :param count: :param fields:"""
params = sel... | the_stack_v2_python_sparse | codegen/results/methods/donut.py | ScriptHound/vkbottle-types | train | 0 | |
3f3fedc0d4facd3f6b20650ffed04ee9a33d24d8 | [
"data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.add_dataStage03QuantificationOtherData(data.data)\ndata.clear_data()",
"data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.update_dataStage03QuantificationOtherData(data.data)\ndata.clear_data()"
] | <|body_start_0|>
data = base_importData()
data.read_csv(filename)
data.format_data()
self.add_dataStage03QuantificationOtherData(data.data)
data.clear_data()
<|end_body_0|>
<|body_start_1|>
data = base_importData()
data.read_csv(filename)
data.format_data... | stage03_quantification_otherData_io | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stage03_quantification_otherData_io:
def import_dataStage03QuantificationOtherData_add(self, filename):
"""table adds"""
<|body_0|>
def import_dataStage03QuantificationOtherData_update(self, filename):
"""table adds"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_10k_train_002333 | 982 | permissive | [
{
"docstring": "table adds",
"name": "import_dataStage03QuantificationOtherData_add",
"signature": "def import_dataStage03QuantificationOtherData_add(self, filename)"
},
{
"docstring": "table adds",
"name": "import_dataStage03QuantificationOtherData_update",
"signature": "def import_data... | 2 | stack_v2_sparse_classes_30k_train_006713 | Implement the Python class `stage03_quantification_otherData_io` described below.
Class description:
Implement the stage03_quantification_otherData_io class.
Method signatures and docstrings:
- def import_dataStage03QuantificationOtherData_add(self, filename): table adds
- def import_dataStage03QuantificationOtherDat... | Implement the Python class `stage03_quantification_otherData_io` described below.
Class description:
Implement the stage03_quantification_otherData_io class.
Method signatures and docstrings:
- def import_dataStage03QuantificationOtherData_add(self, filename): table adds
- def import_dataStage03QuantificationOtherDat... | 0eeed0191f952ea0226ab8bbc234a30638fb2f9f | <|skeleton|>
class stage03_quantification_otherData_io:
def import_dataStage03QuantificationOtherData_add(self, filename):
"""table adds"""
<|body_0|>
def import_dataStage03QuantificationOtherData_update(self, filename):
"""table adds"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class stage03_quantification_otherData_io:
def import_dataStage03QuantificationOtherData_add(self, filename):
"""table adds"""
data = base_importData()
data.read_csv(filename)
data.format_data()
self.add_dataStage03QuantificationOtherData(data.data)
data.clear_data()
... | the_stack_v2_python_sparse | SBaaS_thermodynamics/stage03_quantification_otherData_io.py | dmccloskey/SBaaS_thermodynamics | train | 0 | |
d416e44660facb07879f2d214c0706e9b0ff04d0 | [
"self.number = number\nself.title = title\nself.paragraphs = []\nfor paragraph_lines in paragraphs:\n new_pragraph = Paragraph.Paragraph(paragraph_lines)\n self.paragraphs.append(new_pragraph)",
"if paragraph_idx:\n self.paragraphs[paragraph_idx].read()\nelse:\n for paragraph in self.paragraphs:\n ... | <|body_start_0|>
self.number = number
self.title = title
self.paragraphs = []
for paragraph_lines in paragraphs:
new_pragraph = Paragraph.Paragraph(paragraph_lines)
self.paragraphs.append(new_pragraph)
<|end_body_0|>
<|body_start_1|>
if paragraph_idx:
... | Chapter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Chapter:
def __init__(self, number, title, paragraphs):
"""A chapter consists of multiple paragraphs."""
<|body_0|>
def read(self, paragraph_idx=None):
"""A paragraph can be read."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.number = number
... | stack_v2_sparse_classes_10k_train_002334 | 676 | no_license | [
{
"docstring": "A chapter consists of multiple paragraphs.",
"name": "__init__",
"signature": "def __init__(self, number, title, paragraphs)"
},
{
"docstring": "A paragraph can be read.",
"name": "read",
"signature": "def read(self, paragraph_idx=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000787 | Implement the Python class `Chapter` described below.
Class description:
Implement the Chapter class.
Method signatures and docstrings:
- def __init__(self, number, title, paragraphs): A chapter consists of multiple paragraphs.
- def read(self, paragraph_idx=None): A paragraph can be read. | Implement the Python class `Chapter` described below.
Class description:
Implement the Chapter class.
Method signatures and docstrings:
- def __init__(self, number, title, paragraphs): A chapter consists of multiple paragraphs.
- def read(self, paragraph_idx=None): A paragraph can be read.
<|skeleton|>
class Chapter... | 70dac5017980c8f30294f2cbd98e5bfd905bfaa7 | <|skeleton|>
class Chapter:
def __init__(self, number, title, paragraphs):
"""A chapter consists of multiple paragraphs."""
<|body_0|>
def read(self, paragraph_idx=None):
"""A paragraph can be read."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Chapter:
def __init__(self, number, title, paragraphs):
"""A chapter consists of multiple paragraphs."""
self.number = number
self.title = title
self.paragraphs = []
for paragraph_lines in paragraphs:
new_pragraph = Paragraph.Paragraph(paragraph_lines)
... | the_stack_v2_python_sparse | week2/objectOriented/Chapter.py | MalteMagnussen/PythonProjects | train | 0 | |
ab8730795161ecb89426f9f0db37c162c2c1f894 | [
"self.dic = {}\nfor word in set(dictionary):\n if word:\n if len(word) <= 2:\n if word not in self.dic:\n self.dic[word] = set()\n self.dic[word].add(word)\n else:\n abb = word[0] + str(len(word) - 2) + word[-1]\n if abb in self.dic:\n ... | <|body_start_0|>
self.dic = {}
for word in set(dictionary):
if word:
if len(word) <= 2:
if word not in self.dic:
self.dic[word] = set()
self.dic[word].add(word)
else:
abb =... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
"""check if a word is unique. :type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_10k_train_002335 | 1,496 | no_license | [
{
"docstring": "initialize your data structure here. :type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": "check if a word is unique. :type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
... | 2 | stack_v2_sparse_classes_30k_train_002698 | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str]
- def isUnique(self, word): check if a word is unique. :type word: str ... | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str]
- def isUnique(self, word): check if a word is unique. :type word: str ... | f1b85a2bfee024ef3afdf2ca0b223842c2d2d3f3 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
"""check if a word is unique. :type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
self.dic = {}
for word in set(dictionary):
if word:
if len(word) <= 2:
if word not in self.dic:
... | the_stack_v2_python_sparse | 288-Unique-Word-Abbreviation/solution.py | Xochitlxie/Leetcode | train | 0 | |
bbabdd8dcb523a539fc0cba2f95ba346e0000c55 | [
"if level != 0:\n image1 = ImageExtender.extend_image(image, int(image.width), int(image.height))\n image2 = GaussianNoiseGenerator.generate_gaussian_noise_by_level(image1, level, image.width)\n return BoundedImageCropper.crop_bounded_image_inverse(image2, (255, 255, 255, 0))\nelse:\n return image",
"... | <|body_start_0|>
if level != 0:
image1 = ImageExtender.extend_image(image, int(image.width), int(image.height))
image2 = GaussianNoiseGenerator.generate_gaussian_noise_by_level(image1, level, image.width)
return BoundedImageCropper.crop_bounded_image_inverse(image2, (255, 255... | NoisedImageGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoisedImageGenerator:
def generate_noised_image_by_level(image, level):
"""Blur an image with the intended noise level :param image: the image to modify :param level: the level of the noise (more explanation in gaussian_noise_generator) :type image: an image file :type level: int (prefer... | stack_v2_sparse_classes_10k_train_002336 | 1,670 | permissive | [
{
"docstring": "Blur an image with the intended noise level :param image: the image to modify :param level: the level of the noise (more explanation in gaussian_noise_generator) :type image: an image file :type level: int (preferably from 0 to 100)",
"name": "generate_noised_image_by_level",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_003701 | Implement the Python class `NoisedImageGenerator` described below.
Class description:
Implement the NoisedImageGenerator class.
Method signatures and docstrings:
- def generate_noised_image_by_level(image, level): Blur an image with the intended noise level :param image: the image to modify :param level: the level of... | Implement the Python class `NoisedImageGenerator` described below.
Class description:
Implement the NoisedImageGenerator class.
Method signatures and docstrings:
- def generate_noised_image_by_level(image, level): Blur an image with the intended noise level :param image: the image to modify :param level: the level of... | 8931c8859878692134f5113d4c6c3e17561f0196 | <|skeleton|>
class NoisedImageGenerator:
def generate_noised_image_by_level(image, level):
"""Blur an image with the intended noise level :param image: the image to modify :param level: the level of the noise (more explanation in gaussian_noise_generator) :type image: an image file :type level: int (prefer... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NoisedImageGenerator:
def generate_noised_image_by_level(image, level):
"""Blur an image with the intended noise level :param image: the image to modify :param level: the level of the noise (more explanation in gaussian_noise_generator) :type image: an image file :type level: int (preferably from 0 to... | the_stack_v2_python_sparse | UpdatedSyntheticDataset/SyntheticDataset2/ElementsCreator/noised_image_generator.py | FlintHill/SUAS-Competition | train | 5 | |
cdad07f5439fc88c0cf211d88719d8bc2954088d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn CountryNamedLocation()",
"from .country_lookup_method_type import CountryLookupMethodType\nfrom .named_location import NamedLocation\nfrom .country_lookup_method_type import CountryLookupMethodType\nfrom .named_location import NamedLoc... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return CountryNamedLocation()
<|end_body_0|>
<|body_start_1|>
from .country_lookup_method_type import CountryLookupMethodType
from .named_location import NamedLocation
from .country_loo... | CountryNamedLocation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CountryNamedLocation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CountryNamedLocation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | stack_v2_sparse_classes_10k_train_002337 | 3,404 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: CountryNamedLocation",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | null | Implement the Python class `CountryNamedLocation` described below.
Class description:
Implement the CountryNamedLocation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CountryNamedLocation: Creates a new instance of the appropriate class based o... | Implement the Python class `CountryNamedLocation` described below.
Class description:
Implement the CountryNamedLocation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CountryNamedLocation: Creates a new instance of the appropriate class based o... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class CountryNamedLocation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CountryNamedLocation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CountryNamedLocation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CountryNamedLocation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | the_stack_v2_python_sparse | msgraph/generated/models/country_named_location.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
7136d4ae62e2ae0b5068ec8bf798387d27d730c3 | [
"ObjectManager.__init__(self)\nself.getters.update({'session_template': 'get_foreign_key', 'session_user_role': 'get_foreign_key', 'max': 'get_general', 'min': 'get_general'})\nself.setters.update({'session_template': 'set_foreign_key', 'session_user_role': 'set_foreign_key', 'max': 'set_general', 'min': 'set_gener... | <|body_start_0|>
ObjectManager.__init__(self)
self.getters.update({'session_template': 'get_foreign_key', 'session_user_role': 'get_foreign_key', 'max': 'get_general', 'min': 'get_general'})
self.setters.update({'session_template': 'set_foreign_key', 'session_user_role': 'set_foreign_key', 'max'... | Manage SessionTemplateUserRoleRequirements in the Power Reg system | SessionTemplateUserRoleRequirementManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionTemplateUserRoleRequirementManager:
"""Manage SessionTemplateUserRoleRequirements in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, session_template_id, session_user_role_id, min, max, credential_type_ids=None... | stack_v2_sparse_classes_10k_train_002338 | 2,528 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new SessionTemplateUserRoleRequirement @param session_template_id Primary key for an session_template @param session_user_role_id Primary key for a session_user_role @param min Minimum... | 2 | stack_v2_sparse_classes_30k_train_003374 | Implement the Python class `SessionTemplateUserRoleRequirementManager` described below.
Class description:
Manage SessionTemplateUserRoleRequirements in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, session_template_id, session_user_role_id, mi... | Implement the Python class `SessionTemplateUserRoleRequirementManager` described below.
Class description:
Manage SessionTemplateUserRoleRequirements in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, session_template_id, session_user_role_id, mi... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class SessionTemplateUserRoleRequirementManager:
"""Manage SessionTemplateUserRoleRequirements in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, session_template_id, session_user_role_id, min, max, credential_type_ids=None... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SessionTemplateUserRoleRequirementManager:
"""Manage SessionTemplateUserRoleRequirements in the Power Reg system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.getters.update({'session_template': 'get_foreign_key', 'session_user_role': 'get_foreign_key'... | the_stack_v2_python_sparse | pr_services/event_system/session_template_user_role_requirement_manager.py | ninemoreminutes/openassign-server | train | 0 |
331641bf91c540417e5f07c2dfa9a22fe1589517 | [
"self.hashMap = {}\nself.upper = N - len(blacklist)\nfor num in blacklist:\n self.hashMap[num] = -1\ni = N - 1\nfor num in blacklist:\n if num >= N - len(blacklist):\n continue\n while i in self.hashMap:\n i -= 1\n self.hashMap[num] = i\n i -= 1",
"number = random.randint(0, self.uppe... | <|body_start_0|>
self.hashMap = {}
self.upper = N - len(blacklist)
for num in blacklist:
self.hashMap[num] = -1
i = N - 1
for num in blacklist:
if num >= N - len(blacklist):
continue
while i in self.hashMap:
i -=... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, N, blacklist):
""":type N: int :type blacklist: List[int]"""
<|body_0|>
def pick(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.hashMap = {}
self.upper = N - len(blacklist)
for... | stack_v2_sparse_classes_10k_train_002339 | 1,765 | no_license | [
{
"docstring": ":type N: int :type blacklist: List[int]",
"name": "__init__",
"signature": "def __init__(self, N, blacklist)"
},
{
"docstring": ":rtype: int",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, N, blacklist): :type N: int :type blacklist: List[int]
- def pick(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, N, blacklist): :type N: int :type blacklist: List[int]
- def pick(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, N, blacklist):
... | 1d8821da01c9c200732a6b7037b8631689e2f7e7 | <|skeleton|>
class Solution:
def __init__(self, N, blacklist):
""":type N: int :type blacklist: List[int]"""
<|body_0|>
def pick(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, N, blacklist):
""":type N: int :type blacklist: List[int]"""
self.hashMap = {}
self.upper = N - len(blacklist)
for num in blacklist:
self.hashMap[num] = -1
i = N - 1
for num in blacklist:
if num >= N - len(bla... | the_stack_v2_python_sparse | Leetcode0710.py | xiaojinghu/Leetcode | train | 0 | |
4ced799c2e6370ca55cc2a371541627f77ffaa3d | [
"ls = len(s)\nlp = len(p)\nif ls < lp or lp == 0:\n return []\ndic = dict()\nfor c in p:\n if c in dic:\n dic[c] += 1\n else:\n dic[c] = 1\nimport copy\nr = []\nfor i in range(0, ls - lp + 1):\n t = copy.deepcopy(dic)\n f = True\n for j in range(i, i + lp):\n if s[j] in t and ... | <|body_start_0|>
ls = len(s)
lp = len(p)
if ls < lp or lp == 0:
return []
dic = dict()
for c in p:
if c in dic:
dic[c] += 1
else:
dic[c] = 1
import copy
r = []
for i in range(0, ls - lp + ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findAnagrams1(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ls = len(s)
lp... | stack_v2_sparse_classes_10k_train_002340 | 1,779 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams1",
"signature": "def findAnagrams1(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams",
"signature": "def findAnagrams(self, s, p)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005845 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams1(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams1(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
<|skeleton|>
class Solutio... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def findAnagrams1(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findAnagrams1(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
ls = len(s)
lp = len(p)
if ls < lp or lp == 0:
return []
dic = dict()
for c in p:
if c in dic:
dic[c] += 1
else:
... | the_stack_v2_python_sparse | py/leetcode/438.py | wfeng1991/learnpy | train | 0 | |
205cc4c2ace0f961ed950863bb236ffe9cfe5070 | [
"polling_interval = kwargs.pop('_polling_interval', 5)\nsas_parameter = self._models.SASTokenParameter(storage_resource_uri=blob_storage_url, token=sas_token)\ncontinuation_token = kwargs.pop('continuation_token', None)\nstatus_response = None\nif continuation_token:\n status_url = base64.b64decode(continuation_... | <|body_start_0|>
polling_interval = kwargs.pop('_polling_interval', 5)
sas_parameter = self._models.SASTokenParameter(storage_resource_uri=blob_storage_url, token=sas_token)
continuation_token = kwargs.pop('continuation_token', None)
status_response = None
if continuation_token:
... | Performs Key Vault backup and restore operations. :param str vault_url: URL of the vault on which the client will operate. This is also called the vault's "DNS Name". You should validate that this URL references a valid Key Vault or Managed HSM resource. See https://aka.ms/azsdk/blog/vault-uri for details. :param crede... | KeyVaultBackupClient | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyVaultBackupClient:
"""Performs Key Vault backup and restore operations. :param str vault_url: URL of the vault on which the client will operate. This is also called the vault's "DNS Name". You should validate that this URL references a valid Key Vault or Managed HSM resource. See https://aka.m... | stack_v2_sparse_classes_10k_train_002341 | 8,780 | permissive | [
{
"docstring": "Begin a full backup of the Key Vault. :param str blob_storage_url: URL of the blob storage container in which the backup will be stored, for example https://<account>.blob.core.windows.net/backup :param str sas_token: a Shared Access Signature (SAS) token authorizing access to the blob storage r... | 2 | stack_v2_sparse_classes_30k_train_003087 | Implement the Python class `KeyVaultBackupClient` described below.
Class description:
Performs Key Vault backup and restore operations. :param str vault_url: URL of the vault on which the client will operate. This is also called the vault's "DNS Name". You should validate that this URL references a valid Key Vault or ... | Implement the Python class `KeyVaultBackupClient` described below.
Class description:
Performs Key Vault backup and restore operations. :param str vault_url: URL of the vault on which the client will operate. This is also called the vault's "DNS Name". You should validate that this URL references a valid Key Vault or ... | c2ca191e736bb06bfbbbc9493e8325763ba990bb | <|skeleton|>
class KeyVaultBackupClient:
"""Performs Key Vault backup and restore operations. :param str vault_url: URL of the vault on which the client will operate. This is also called the vault's "DNS Name". You should validate that this URL references a valid Key Vault or Managed HSM resource. See https://aka.m... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KeyVaultBackupClient:
"""Performs Key Vault backup and restore operations. :param str vault_url: URL of the vault on which the client will operate. This is also called the vault's "DNS Name". You should validate that this URL references a valid Key Vault or Managed HSM resource. See https://aka.ms/azsdk/blog/... | the_stack_v2_python_sparse | sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_backup_client.py | Azure/azure-sdk-for-python | train | 4,046 |
35ce505d9abbc2926d4ea59da3b1b58ac65d3ac4 | [
"bin_path = '/home/cephuser/venv/bin/'\nself.prefix = bin_path + 's3cmd'\nif options is None:\n options = []\nself.operation = operation\nself.options = ' '.join(options)",
"if params is None:\n params = []\ncommand_list = [self.prefix, self.options, self.operation] + params\ncmd = list(filter(lambda cmd: l... | <|body_start_0|>
bin_path = '/home/cephuser/venv/bin/'
self.prefix = bin_path + 's3cmd'
if options is None:
options = []
self.operation = operation
self.options = ' '.join(options)
<|end_body_0|>
<|body_start_1|>
if params is None:
params = []
... | S3CMD | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3CMD:
def __init__(self, operation, options=None):
"""Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command"""
<|body_0|>
def command(self, params=None):
"""Args: params(list): list of params... | stack_v2_sparse_classes_10k_train_002342 | 1,012 | permissive | [
{
"docstring": "Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command",
"name": "__init__",
"signature": "def __init__(self, operation, options=None)"
},
{
"docstring": "Args: params(list): list of params to be passed in ... | 2 | stack_v2_sparse_classes_30k_test_000340 | Implement the Python class `S3CMD` described below.
Class description:
Implement the S3CMD class.
Method signatures and docstrings:
- def __init__(self, operation, options=None): Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command
- def comm... | Implement the Python class `S3CMD` described below.
Class description:
Implement the S3CMD class.
Method signatures and docstrings:
- def __init__(self, operation, options=None): Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command
- def comm... | 4c3b9b3e8e7f42d43270a9b79299a8b404a76046 | <|skeleton|>
class S3CMD:
def __init__(self, operation, options=None):
"""Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command"""
<|body_0|>
def command(self, params=None):
"""Args: params(list): list of params... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class S3CMD:
def __init__(self, operation, options=None):
"""Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command"""
bin_path = '/home/cephuser/venv/bin/'
self.prefix = bin_path + 's3cmd'
if options is None:
... | the_stack_v2_python_sparse | rgw/v2/lib/s3cmd/resource_op.py | red-hat-storage/ceph-qe-scripts | train | 9 | |
6f2301e3e6bd43e8a82926349a880ca4b23fdc3b | [
"mocker.patch.object(demisto, 'command', return_value='xdr-iocs-enable')\nmocker.patch.object(demisto, 'args', return_value={'indicator': '11.11.11.11'})\nmocker.patch('XDR_iocs.Client.http_request', return_value={})\noutputs = mocker.patch('XDR_iocs.return_outputs')\nenable_ioc = mocker.patch('XDR_iocs.prepare_ena... | <|body_start_0|>
mocker.patch.object(demisto, 'command', return_value='xdr-iocs-enable')
mocker.patch.object(demisto, 'args', return_value={'indicator': '11.11.11.11'})
mocker.patch('XDR_iocs.Client.http_request', return_value={})
outputs = mocker.patch('XDR_iocs.return_outputs')
... | TestIOCSCommand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestIOCSCommand:
def test_iocs_command_with_enable(self, mocker):
"""Given: - enable command Then: - Verify enable command is called."""
<|body_0|>
def test_iocs_command_with_disable(self, mocker):
"""Given: - disable command Then: - Verify disable command is called.... | stack_v2_sparse_classes_10k_train_002343 | 41,271 | permissive | [
{
"docstring": "Given: - enable command Then: - Verify enable command is called.",
"name": "test_iocs_command_with_enable",
"signature": "def test_iocs_command_with_enable(self, mocker)"
},
{
"docstring": "Given: - disable command Then: - Verify disable command is called.",
"name": "test_ioc... | 2 | stack_v2_sparse_classes_30k_train_001938 | Implement the Python class `TestIOCSCommand` described below.
Class description:
Implement the TestIOCSCommand class.
Method signatures and docstrings:
- def test_iocs_command_with_enable(self, mocker): Given: - enable command Then: - Verify enable command is called.
- def test_iocs_command_with_disable(self, mocker)... | Implement the Python class `TestIOCSCommand` described below.
Class description:
Implement the TestIOCSCommand class.
Method signatures and docstrings:
- def test_iocs_command_with_enable(self, mocker): Given: - enable command Then: - Verify enable command is called.
- def test_iocs_command_with_disable(self, mocker)... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestIOCSCommand:
def test_iocs_command_with_enable(self, mocker):
"""Given: - enable command Then: - Verify enable command is called."""
<|body_0|>
def test_iocs_command_with_disable(self, mocker):
"""Given: - disable command Then: - Verify disable command is called.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestIOCSCommand:
def test_iocs_command_with_enable(self, mocker):
"""Given: - enable command Then: - Verify enable command is called."""
mocker.patch.object(demisto, 'command', return_value='xdr-iocs-enable')
mocker.patch.object(demisto, 'args', return_value={'indicator': '11.11.11.11'... | the_stack_v2_python_sparse | Packs/CortexXDR/Integrations/XDR_iocs/XDR_iocs_test.py | demisto/content | train | 1,023 | |
e720d7ab130c3b9c9b948ceec477ecb80dabe8db | [
"diff = [g - c for g, c in zip(gas, cost)]\nif sum(diff) < 0:\n return -1\ntank = 0\nlength = len(gas)\nfor index in range(length):\n tmp_index = index\n while True:\n tank += gas[tmp_index]\n tank -= cost[tmp_index]\n if tank < 0:\n break\n tmp_index = (tmp_index + 1... | <|body_start_0|>
diff = [g - c for g, c in zip(gas, cost)]
if sum(diff) < 0:
return -1
tank = 0
length = len(gas)
for index in range(length):
tmp_index = index
while True:
tank += gas[tmp_index]
tank -= cost[tmp_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit2(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_10k_train_002344 | 2,266 | no_license | [
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit",
"signature": "def canCompleteCircuit(self, gas, cost)"
},
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit2",
"signature": "def canCo... | 2 | stack_v2_sparse_classes_30k_train_003506 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit2(self, gas, cost): :type gas: List[int] :type cost: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit2(self, gas, cost): :type gas: List[int] :type cost: List[... | a8b59573dc201438ebd5a5ab64e9ac61255a4abd | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit2(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
diff = [g - c for g, c in zip(gas, cost)]
if sum(diff) < 0:
return -1
tank = 0
length = len(gas)
for index in range(length):
t... | the_stack_v2_python_sparse | summer/2018_07_21/gas-station.py | shaheming/leecode | train | 0 | |
838af8ab1f9b343943eea58f3354c3e2c5176188 | [
"if n == 1:\n return 0\ndp = [0] * (n + 1)\ndp[2] = 1\nfor i in range(3, n + 1):\n if i % 2:\n dp[i] = min(dp[(i + 1) // 2], dp[(i - 1) // 2]) + 2\n else:\n dp[i] = dp[i // 2] + 1\nreturn dp[n]",
"def help(n, mem):\n if n in mem:\n return mem[n]\n if n == 1:\n mem[n] = 0... | <|body_start_0|>
if n == 1:
return 0
dp = [0] * (n + 1)
dp[2] = 1
for i in range(3, n + 1):
if i % 2:
dp[i] = min(dp[(i + 1) // 2], dp[(i - 1) // 2]) + 2
else:
dp[i] = dp[i // 2] + 1
return dp[n]
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def integerReplacement1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def integerReplacement(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 1:
return 0
dp = [0] * (n ... | stack_v2_sparse_classes_10k_train_002345 | 846 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "integerReplacement1",
"signature": "def integerReplacement1(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "integerReplacement",
"signature": "def integerReplacement(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerReplacement1(self, n): :type n: int :rtype: int
- def integerReplacement(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerReplacement1(self, n): :type n: int :rtype: int
- def integerReplacement(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def integerReplacement1(... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def integerReplacement1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def integerReplacement(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def integerReplacement1(self, n):
""":type n: int :rtype: int"""
if n == 1:
return 0
dp = [0] * (n + 1)
dp[2] = 1
for i in range(3, n + 1):
if i % 2:
dp[i] = min(dp[(i + 1) // 2], dp[(i - 1) // 2]) + 2
else:
... | the_stack_v2_python_sparse | py/leetcode/397.py | wfeng1991/learnpy | train | 0 | |
6b50876f984fb071cf6dddc0a55b801ecd64dd7c | [
"size = 0\ncid = CustomID()\nuser: UserModel = self.current_user\nfn = os.path.join(upload_dir, str(cid.to_hex()))\nm = hashlib.blake2b()\npost = await self.post_data()\nfield: FileField = post.get('file', None)\nif not (field and isinstance(field, FileField)):\n return self.finish(RETCODE.INVALID_POSTDATA, '没有提... | <|body_start_0|>
size = 0
cid = CustomID()
user: UserModel = self.current_user
fn = os.path.join(upload_dir, str(cid.to_hex()))
m = hashlib.blake2b()
post = await self.post_data()
field: FileField = post.get('file', None)
if not (field and isinstance(field... | UploadView | [
"Zlib"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadView:
async def upload(self):
"""上传图片 随机文件名,上传至指定目录。完成后修改文件名为hash值 :return:"""
<|body_0|>
async def qn_token(self):
"""获取七牛 token :return:"""
<|body_1|>
async def qn_callback(self):
"""七牛回调 :return:"""
<|body_2|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_002346 | 3,832 | permissive | [
{
"docstring": "上传图片 随机文件名,上传至指定目录。完成后修改文件名为hash值 :return:",
"name": "upload",
"signature": "async def upload(self)"
},
{
"docstring": "获取七牛 token :return:",
"name": "qn_token",
"signature": "async def qn_token(self)"
},
{
"docstring": "七牛回调 :return:",
"name": "qn_callback",
... | 3 | stack_v2_sparse_classes_30k_train_002884 | Implement the Python class `UploadView` described below.
Class description:
Implement the UploadView class.
Method signatures and docstrings:
- async def upload(self): 上传图片 随机文件名,上传至指定目录。完成后修改文件名为hash值 :return:
- async def qn_token(self): 获取七牛 token :return:
- async def qn_callback(self): 七牛回调 :return: | Implement the Python class `UploadView` described below.
Class description:
Implement the UploadView class.
Method signatures and docstrings:
- async def upload(self): 上传图片 随机文件名,上传至指定目录。完成后修改文件名为hash值 :return:
- async def qn_token(self): 获取七牛 token :return:
- async def qn_callback(self): 七牛回调 :return:
<|skeleton|>
... | c3a4af0f98693a08b850b47ff01091c4e884cc18 | <|skeleton|>
class UploadView:
async def upload(self):
"""上传图片 随机文件名,上传至指定目录。完成后修改文件名为hash值 :return:"""
<|body_0|>
async def qn_token(self):
"""获取七牛 token :return:"""
<|body_1|>
async def qn_callback(self):
"""七牛回调 :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UploadView:
async def upload(self):
"""上传图片 随机文件名,上传至指定目录。完成后修改文件名为hash值 :return:"""
size = 0
cid = CustomID()
user: UserModel = self.current_user
fn = os.path.join(upload_dir, str(cid.to_hex()))
m = hashlib.blake2b()
post = await self.post_data()
... | the_stack_v2_python_sparse | backend/api/upload.py | LiangTang1993/Icarus | train | 1 | |
ba1045b4a133fee2f842f1993b3470169335c839 | [
"Parametre.__init__(self, 'hotboot', 'hotboot')\nself.aide_courte = 'permet de redémarrer les modules du MUD'\nself.aide_longue = \"Cette commande permet de redémarrer un ou plusieurs modules pendant l'exécution du MUD. Cela permet de corriger des bugs, intégrer des modifications, ajouter ou retirer des commandes s... | <|body_start_0|>
Parametre.__init__(self, 'hotboot', 'hotboot')
self.aide_courte = 'permet de redémarrer les modules du MUD'
self.aide_longue = "Cette commande permet de redémarrer un ou plusieurs modules pendant l'exécution du MUD. Cela permet de corriger des bugs, intégrer des modifications, a... | Commande 'module hotboot'. | PrmHotboot | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmHotboot:
"""Commande 'module hotboot'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametre.... | stack_v2_sparse_classes_10k_train_002347 | 3,062 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmHotboot` described below.
Class description:
Commande 'module hotboot'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmHotboot` described below.
Class description:
Commande 'module hotboot'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmHotboot:
"""Commande 'module... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmHotboot:
"""Commande 'module hotboot'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrmHotboot:
"""Commande 'module hotboot'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'hotboot', 'hotboot')
self.aide_courte = 'permet de redémarrer les modules du MUD'
self.aide_longue = "Cette commande permet de redémarrer un ou plusie... | the_stack_v2_python_sparse | src/primaires/joueur/commandes/module/hotboot.py | vincent-lg/tsunami | train | 5 |
a7b47a5a44788ad09de86c3227d85f8ec52e2ce8 | [
"super().__init__(*args, **kwargs)\nself.invite_only = invite_only\nself.show_invisible = show_invisible",
"existing_groups: Iterable[Group]\ninput_value: Optional[str]\nif value:\n if not self.multivalued:\n value = [value]\n value = [v for v in value if v]\n input_value = ','.join((force_str(v) ... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.invite_only = invite_only
self.show_invisible = show_invisible
<|end_body_0|>
<|body_start_1|>
existing_groups: Iterable[Group]
input_value: Optional[str]
if value:
if not self.multivalued:
... | A form widget allowing people to select one or more Group objects. This widget offers both the ability to see which groups are already in the list, as well as interactive search and filtering. Version Changed: 5.0.6: * Added an option for enabling specifying invisible review groups. * Added support for Python type hint... | RelatedGroupWidget | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelatedGroupWidget:
"""A form widget allowing people to select one or more Group objects. This widget offers both the ability to see which groups are already in the list, as well as interactive search and filtering. Version Changed: 5.0.6: * Added an option for enabling specifying invisible revie... | stack_v2_sparse_classes_10k_train_002348 | 16,804 | permissive | [
{
"docstring": "Initialize the RelatedGroupWidget. Version Changed: 5.0.6: Added the ``show_invisible`` argument. Args: invite_only (bool, optional): Whether or not to limit results to accessible review groups that are invite-only. show_invisible (bool, optional): Whether to include accessible invisible review ... | 3 | null | Implement the Python class `RelatedGroupWidget` described below.
Class description:
A form widget allowing people to select one or more Group objects. This widget offers both the ability to see which groups are already in the list, as well as interactive search and filtering. Version Changed: 5.0.6: * Added an option ... | Implement the Python class `RelatedGroupWidget` described below.
Class description:
A form widget allowing people to select one or more Group objects. This widget offers both the ability to see which groups are already in the list, as well as interactive search and filtering. Version Changed: 5.0.6: * Added an option ... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class RelatedGroupWidget:
"""A form widget allowing people to select one or more Group objects. This widget offers both the ability to see which groups are already in the list, as well as interactive search and filtering. Version Changed: 5.0.6: * Added an option for enabling specifying invisible revie... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RelatedGroupWidget:
"""A form widget allowing people to select one or more Group objects. This widget offers both the ability to see which groups are already in the list, as well as interactive search and filtering. Version Changed: 5.0.6: * Added an option for enabling specifying invisible review groups. * A... | the_stack_v2_python_sparse | reviewboard/admin/form_widgets.py | reviewboard/reviewboard | train | 1,141 |
6fc4b746b192a737442735583c4009decb5234d3 | [
"if not root:\n return '[]'\nres = []\nqueue = collections.deque()\nqueue.append(root)\nwhile queue:\n node = queue.popleft()\n if node:\n res.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\n else:\n res.append('null')\nreturn '[' + ','.join(res) +... | <|body_start_0|>
if not root:
return '[]'
res = []
queue = collections.deque()
queue.append(root)
while queue:
node = queue.popleft()
if node:
res.append(str(node.val))
queue.append(node.left)
que... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def serialize(self, root):
"""类似于面试题32 :param root: 传入一棵树 :return: 返回字符串"""
<|body_0|>
def deserialize(self, data):
""":param data: 是一个字符串 :return: 返回一棵树"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return '[]'
... | stack_v2_sparse_classes_10k_train_002349 | 2,245 | no_license | [
{
"docstring": "类似于面试题32 :param root: 传入一棵树 :return: 返回字符串",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": ":param data: 是一个字符串 :return: 返回一棵树",
"name": "deserialize",
"signature": "def deserialize(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005602 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def serialize(self, root): 类似于面试题32 :param root: 传入一棵树 :return: 返回字符串
- def deserialize(self, data): :param data: 是一个字符串 :return: 返回一棵树 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def serialize(self, root): 类似于面试题32 :param root: 传入一棵树 :return: 返回字符串
- def deserialize(self, data): :param data: 是一个字符串 :return: 返回一棵树
<|skeleton|>
class Solution:
def ser... | f1bbd6b3197cd9ac4f0d35a37539c11b02272065 | <|skeleton|>
class Solution:
def serialize(self, root):
"""类似于面试题32 :param root: 传入一棵树 :return: 返回字符串"""
<|body_0|>
def deserialize(self, data):
""":param data: 是一个字符串 :return: 返回一棵树"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def serialize(self, root):
"""类似于面试题32 :param root: 传入一棵树 :return: 返回字符串"""
if not root:
return '[]'
res = []
queue = collections.deque()
queue.append(root)
while queue:
node = queue.popleft()
if node:
... | the_stack_v2_python_sparse | offer/树/37. 序列化二叉树/Codec.py | guohaoyuan/algorithms-for-work | train | 2 | |
2fae4983fba0c3f1e6384fa52990e36b107925d8 | [
"self.char = ''\nself.d = {}\nself.end = False",
"c, n = (word[0], len(word))\nnode = self.d.get(c)\nif not node:\n self.d[c] = Trie()\n self.d[c].char = c\n node = self.d[c]\nif n == 1:\n node.end = True\nelse:\n node.insert(word[1:])",
"node = self\nfor c in word:\n node = node.d.get(c)\n ... | <|body_start_0|>
self.char = ''
self.d = {}
self.end = False
<|end_body_0|>
<|body_start_1|>
c, n = (word[0], len(word))
node = self.d.get(c)
if not node:
self.d[c] = Trie()
self.d[c].char = c
node = self.d[c]
if n == 1:
... | Trie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_10k_train_002350 | 1,311 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a word into the trie.",
"name": "insert",
"signature": "def insert(self, word: str) -> None"
},
{
"docstring": "Returns if the word is in the tr... | 4 | stack_v2_sparse_classes_30k_train_003482 | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | 12f62a218e827e6be2578b206dee9ce256da8d3d | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Trie:
def __init__(self):
"""Initialize your data structure here."""
self.char = ''
self.d = {}
self.end = False
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
c, n = (word[0], len(word))
node = self.d.get(c)
if not... | the_stack_v2_python_sparse | Python3/0208_Implement_Trie.py | kiranani/playground | train | 0 | |
c793207626c423bbf2cc159ffc8d8a5e88c08c86 | [
"super(RateConverter, self).__init__(id=id)\nself.base_currency = base_currency\nself.user = user\nself.key = key",
"errors = super(RateConverter, self).add_data(data)\nself.cache_currencies()\nreturn errors",
"from .serializers import RateAmountSerializer\nerrors = []\nfor line in data:\n serializer = RateA... | <|body_start_0|>
super(RateConverter, self).__init__(id=id)
self.base_currency = base_currency
self.user = user
self.key = key
<|end_body_0|>
<|body_start_1|>
errors = super(RateConverter, self).add_data(data)
self.cache_currencies()
return errors
<|end_body_1|>
... | Converter of rates | RateConverter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RateConverter:
"""Converter of rates"""
def __init__(self, user: User, id: str=None, key: str=None, base_currency: str=settings.BASE_CURRENCY):
"""Initialize :param user: Django User :param key: key for user :param base_currency: destination currency"""
<|body_0|>
def ad... | stack_v2_sparse_classes_10k_train_002351 | 16,208 | permissive | [
{
"docstring": "Initialize :param user: Django User :param key: key for user :param base_currency: destination currency",
"name": "__init__",
"signature": "def __init__(self, user: User, id: str=None, key: str=None, base_currency: str=settings.BASE_CURRENCY)"
},
{
"docstring": "Check data and ad... | 5 | stack_v2_sparse_classes_30k_train_007098 | Implement the Python class `RateConverter` described below.
Class description:
Converter of rates
Method signatures and docstrings:
- def __init__(self, user: User, id: str=None, key: str=None, base_currency: str=settings.BASE_CURRENCY): Initialize :param user: Django User :param key: key for user :param base_currenc... | Implement the Python class `RateConverter` described below.
Class description:
Converter of rates
Method signatures and docstrings:
- def __init__(self, user: User, id: str=None, key: str=None, base_currency: str=settings.BASE_CURRENCY): Initialize :param user: Django User :param key: key for user :param base_currenc... | 23cc075377d47ac631634cd71fd0e7d6b0a57bad | <|skeleton|>
class RateConverter:
"""Converter of rates"""
def __init__(self, user: User, id: str=None, key: str=None, base_currency: str=settings.BASE_CURRENCY):
"""Initialize :param user: Django User :param key: key for user :param base_currency: destination currency"""
<|body_0|>
def ad... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RateConverter:
"""Converter of rates"""
def __init__(self, user: User, id: str=None, key: str=None, base_currency: str=settings.BASE_CURRENCY):
"""Initialize :param user: Django User :param key: key for user :param base_currency: destination currency"""
super(RateConverter, self).__init__... | the_stack_v2_python_sparse | src/geocurrency/rates/models.py | fmeurou/geocurrency | train | 5 |
122c588d57997f9321217bfeded4ff5641c1fb71 | [
"rospy.init_node('mapper')\nself._map = Map()\nrospy.Subscriber('scan', LaserScan, self.scan_callback, queue_size=1)\nself._map_pub = rospy.Publisher('map', OccupancyGrid, latch=True)\nself._map_data_pub = rospy.Publisher('map_metadata', MapMetaData, latch=True)\nrospy.spin()",
"self._map.grid[0, 0] = 1.0\nself._... | <|body_start_0|>
rospy.init_node('mapper')
self._map = Map()
rospy.Subscriber('scan', LaserScan, self.scan_callback, queue_size=1)
self._map_pub = rospy.Publisher('map', OccupancyGrid, latch=True)
self._map_data_pub = rospy.Publisher('map_metadata', MapMetaData, latch=True)
... | The Mapper class creates a map from laser scan data. | Mapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mapper:
"""The Mapper class creates a map from laser scan data."""
def __init__(self):
"""Start the mapper."""
<|body_0|>
def scan_callback(self, scan):
"""Update the map on every scan callback."""
<|body_1|>
def publish_map(self):
"""Publish... | stack_v2_sparse_classes_10k_train_002352 | 5,549 | permissive | [
{
"docstring": "Start the mapper.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Update the map on every scan callback.",
"name": "scan_callback",
"signature": "def scan_callback(self, scan)"
},
{
"docstring": "Publish the map.",
"name": "publish_m... | 3 | stack_v2_sparse_classes_30k_train_000248 | Implement the Python class `Mapper` described below.
Class description:
The Mapper class creates a map from laser scan data.
Method signatures and docstrings:
- def __init__(self): Start the mapper.
- def scan_callback(self, scan): Update the map on every scan callback.
- def publish_map(self): Publish the map. | Implement the Python class `Mapper` described below.
Class description:
The Mapper class creates a map from laser scan data.
Method signatures and docstrings:
- def __init__(self): Start the mapper.
- def scan_callback(self, scan): Update the map on every scan callback.
- def publish_map(self): Publish the map.
<|sk... | 43387024c313e40596dd49f1686d2bb1e7f7e319 | <|skeleton|>
class Mapper:
"""The Mapper class creates a map from laser scan data."""
def __init__(self):
"""Start the mapper."""
<|body_0|>
def scan_callback(self, scan):
"""Update the map on every scan callback."""
<|body_1|>
def publish_map(self):
"""Publish... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Mapper:
"""The Mapper class creates a map from laser scan data."""
def __init__(self):
"""Start the mapper."""
rospy.init_node('mapper')
self._map = Map()
rospy.Subscriber('scan', LaserScan, self.scan_callback, queue_size=1)
self._map_pub = rospy.Publisher('map', O... | the_stack_v2_python_sparse | crazyflie_demo/scripts/mapping/mapper.py | GalBrandwine/crazyflie_ros | train | 3 |
b376105dc380f41b6006b1a698b0c4a0f93540f6 | [
"self.config = self.trainer.config\nif vega.is_npu_device():\n count_input = torch.FloatTensor(1, 3, 1024, 1024).npu()\nelse:\n count_input = torch.FloatTensor(1, 3, 1024, 1024).cuda()\nflops_count, params_count = calc_model_flops_params(self.trainer.model, count_input)\nself.flops_count, self.params_count = ... | <|body_start_0|>
self.config = self.trainer.config
if vega.is_npu_device():
count_input = torch.FloatTensor(1, 3, 1024, 1024).npu()
else:
count_input = torch.FloatTensor(1, 3, 1024, 1024).cuda()
flops_count, params_count = calc_model_flops_params(self.trainer.mode... | Construct the trainer of Adelaide-EA. | SegmentationEATrainerCallback | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegmentationEATrainerCallback:
"""Construct the trainer of Adelaide-EA."""
def before_train(self, logs=None):
"""Be called before the training process."""
<|body_0|>
def after_epoch(self, epoch, logs=None):
"""Update flops and params."""
<|body_1|>
<|end... | stack_v2_sparse_classes_10k_train_002353 | 1,941 | permissive | [
{
"docstring": "Be called before the training process.",
"name": "before_train",
"signature": "def before_train(self, logs=None)"
},
{
"docstring": "Update flops and params.",
"name": "after_epoch",
"signature": "def after_epoch(self, epoch, logs=None)"
}
] | 2 | null | Implement the Python class `SegmentationEATrainerCallback` described below.
Class description:
Construct the trainer of Adelaide-EA.
Method signatures and docstrings:
- def before_train(self, logs=None): Be called before the training process.
- def after_epoch(self, epoch, logs=None): Update flops and params. | Implement the Python class `SegmentationEATrainerCallback` described below.
Class description:
Construct the trainer of Adelaide-EA.
Method signatures and docstrings:
- def before_train(self, logs=None): Be called before the training process.
- def after_epoch(self, epoch, logs=None): Update flops and params.
<|skel... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class SegmentationEATrainerCallback:
"""Construct the trainer of Adelaide-EA."""
def before_train(self, logs=None):
"""Be called before the training process."""
<|body_0|>
def after_epoch(self, epoch, logs=None):
"""Update flops and params."""
<|body_1|>
<|end... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SegmentationEATrainerCallback:
"""Construct the trainer of Adelaide-EA."""
def before_train(self, logs=None):
"""Be called before the training process."""
self.config = self.trainer.config
if vega.is_npu_device():
count_input = torch.FloatTensor(1, 3, 1024, 1024).npu()... | the_stack_v2_python_sparse | vega/algorithms/nas/segmentation_ea/segmentation_ea_trainercallback.py | huawei-noah/vega | train | 850 |
983c79f1d8e645ce3e9c205ccef45fdd7d09fc6c | [
"assert features.is_contiguous()\nassert idx.is_contiguous()\nassert weight.is_contiguous()\nm, c = features.size()\nn = idx.size(0)\nctx.three_interpolate_for_backward = (idx, weight, m)\noutput = torch.cuda.FloatTensor(n, c)\nsparse_interpolate_ext.three_interpolate_wrapper(c, m, n, features, idx, weight, output)... | <|body_start_0|>
assert features.is_contiguous()
assert idx.is_contiguous()
assert weight.is_contiguous()
m, c = features.size()
n = idx.size(0)
ctx.three_interpolate_for_backward = (idx, weight, m)
output = torch.cuda.FloatTensor(n, c)
sparse_interpolate_... | SparseThreeInterpolate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseThreeInterpolate:
def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
"""Performs weight linear interpolation on 3 features :param ctx: :param features: (M, C) Features descriptors to be interpolated from :param idx: (n, 3) three neare... | stack_v2_sparse_classes_10k_train_002354 | 3,814 | permissive | [
{
"docstring": "Performs weight linear interpolation on 3 features :param ctx: :param features: (M, C) Features descriptors to be interpolated from :param idx: (n, 3) three nearest neighbors of the target features in features :param weight: (n, 3) weights :return: output: (N, C) tensor of the interpolated featu... | 2 | stack_v2_sparse_classes_30k_train_001998 | Implement the Python class `SparseThreeInterpolate` described below.
Class description:
Implement the SparseThreeInterpolate class.
Method signatures and docstrings:
- def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: Performs weight linear interpolation on 3 features ... | Implement the Python class `SparseThreeInterpolate` described below.
Class description:
Implement the SparseThreeInterpolate class.
Method signatures and docstrings:
- def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: Performs weight linear interpolation on 3 features ... | 9987806185a4e1619bc15ceecb8a1755e764ff68 | <|skeleton|>
class SparseThreeInterpolate:
def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
"""Performs weight linear interpolation on 3 features :param ctx: :param features: (M, C) Features descriptors to be interpolated from :param idx: (n, 3) three neare... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SparseThreeInterpolate:
def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
"""Performs weight linear interpolation on 3 features :param ctx: :param features: (M, C) Features descriptors to be interpolated from :param idx: (n, 3) three nearest neighbors o... | the_stack_v2_python_sparse | gorilla3d/ops/sparse_interpolate/sparse_interpolate.py | SijanNeupane49/gorilla-3d | train | 0 | |
79c6fd96ee3fa40e17e393494783294e2869252f | [
"if not any(values.values()):\n values['eia860'] = Eia860Settings()\n values['eia861'] = Eia861Settings()\n values['eia923'] = Eia923Settings()\nreturn values",
"eia923 = values.get('eia923')\neia860 = values.get('eia860')\nif not eia923 and eia860:\n values['eia923'] = Eia923Settings(years=eia860.yea... | <|body_start_0|>
if not any(values.values()):
values['eia860'] = Eia860Settings()
values['eia861'] = Eia861Settings()
values['eia923'] = Eia923Settings()
return values
<|end_body_0|>
<|body_start_1|>
eia923 = values.get('eia923')
eia860 = values.get('... | An immutable pydantic model to validate EIA datasets settings. Args: eia860: Immutable pydantic model to validate eia860 settings. eia923: Immutable pydantic model to validate eia923 settings. | EiaSettings | [
"CC-BY-4.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EiaSettings:
"""An immutable pydantic model to validate EIA datasets settings. Args: eia860: Immutable pydantic model to validate eia860 settings. eia923: Immutable pydantic model to validate eia923 settings."""
def default_load_all(cls, values):
"""If no datasets are specified defau... | stack_v2_sparse_classes_10k_train_002355 | 24,804 | permissive | [
{
"docstring": "If no datasets are specified default to all. Args: values (Dict[str, BaseModel]): dataset settings. Returns: values (Dict[str, BaseModel]): dataset settings.",
"name": "default_load_all",
"signature": "def default_load_all(cls, values)"
},
{
"docstring": "Make sure the dependenci... | 2 | stack_v2_sparse_classes_30k_train_002863 | Implement the Python class `EiaSettings` described below.
Class description:
An immutable pydantic model to validate EIA datasets settings. Args: eia860: Immutable pydantic model to validate eia860 settings. eia923: Immutable pydantic model to validate eia923 settings.
Method signatures and docstrings:
- def default_... | Implement the Python class `EiaSettings` described below.
Class description:
An immutable pydantic model to validate EIA datasets settings. Args: eia860: Immutable pydantic model to validate eia860 settings. eia923: Immutable pydantic model to validate eia923 settings.
Method signatures and docstrings:
- def default_... | 6afae8aade053408f23ac4332d5cbb438ab72dc6 | <|skeleton|>
class EiaSettings:
"""An immutable pydantic model to validate EIA datasets settings. Args: eia860: Immutable pydantic model to validate eia860 settings. eia923: Immutable pydantic model to validate eia923 settings."""
def default_load_all(cls, values):
"""If no datasets are specified defau... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EiaSettings:
"""An immutable pydantic model to validate EIA datasets settings. Args: eia860: Immutable pydantic model to validate eia860 settings. eia923: Immutable pydantic model to validate eia923 settings."""
def default_load_all(cls, values):
"""If no datasets are specified default to all. Ar... | the_stack_v2_python_sparse | src/pudl/settings.py | catalyst-cooperative/pudl | train | 382 |
09708350bf3d70b4c8c284e8cb9f8ec62cbe963e | [
"if len(nums) < 3:\n return 0\nfirstBiggest, secondBiggest, thirdBiggest = (float('-inf'), float('-inf'), float('-inf'))\nfirstSmallest, secondSmallest = (float('-inf'), float('-inf'))\nC = Counter(nums)\nfirstBiggest = max(C)\nC[firstBiggest] -= 1\nif not C[firstBiggest]:\n del C[firstBiggest]\nsecondBiggest... | <|body_start_0|>
if len(nums) < 3:
return 0
firstBiggest, secondBiggest, thirdBiggest = (float('-inf'), float('-inf'), float('-inf'))
firstSmallest, secondSmallest = (float('-inf'), float('-inf'))
C = Counter(nums)
firstBiggest = max(C)
C[firstBiggest] -= 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximumProduct(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maximumProductFirstSolution(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) < 3:
... | stack_v2_sparse_classes_10k_train_002356 | 1,631 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maximumProduct",
"signature": "def maximumProduct(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maximumProductFirstSolution",
"signature": "def maximumProductFirstSolution(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumProduct(self, nums): :type nums: List[int] :rtype: int
- def maximumProductFirstSolution(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumProduct(self, nums): :type nums: List[int] :rtype: int
- def maximumProductFirstSolution(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 25e5caf324e25edfdf0a7a3be1e572f5d4c88837 | <|skeleton|>
class Solution:
def maximumProduct(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maximumProductFirstSolution(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maximumProduct(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) < 3:
return 0
firstBiggest, secondBiggest, thirdBiggest = (float('-inf'), float('-inf'), float('-inf'))
firstSmallest, secondSmallest = (float('-inf'), float('-inf'))
... | the_stack_v2_python_sparse | Arrays/maximum_product_of_three_numbers.py | msraju2009/CodingProblemsPractice | train | 0 | |
e6f3b3cfe120ccaa761d3edfa1f2339c4c5846b2 | [
"try:\n self.__genre = 'review'\n self.__task_elements_dict = {'priority': self.task.priority, 'level': self.task.level, 'last_updated_time': datetime.strftime(datetime.utcnow(), '%Y-%m-%dT%H:%M:%SZ'), 'pickup_date': datetime.strftime(datetime.utcnow(), '%Y-%m-%dT%H:%M:%SZ'), 'connector_instance_log_id': self... | <|body_start_0|>
try:
self.__genre = 'review'
self.__task_elements_dict = {'priority': self.task.priority, 'level': self.task.level, 'last_updated_time': datetime.strftime(datetime.utcnow(), '%Y-%m-%dT%H:%M:%SZ'), 'pickup_date': datetime.strftime(datetime.utcnow(), '%Y-%m-%dT%H:%M:%SZ'),... | This will fetch the info for Sample uris is http://www.customerservicescoreboard.com/Bank+of+America | CustomerServiceScoreBoardConnector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerServiceScoreBoardConnector:
"""This will fetch the info for Sample uris is http://www.customerservicescoreboard.com/Bank+of+America"""
def fetch(self):
"""Fetch of customerservicescoreboard.com"""
<|body_0|>
def __iteratePosts(self):
"""It will Iterate Ov... | stack_v2_sparse_classes_10k_train_002357 | 7,675 | no_license | [
{
"docstring": "Fetch of customerservicescoreboard.com",
"name": "fetch",
"signature": "def fetch(self)"
},
{
"docstring": "It will Iterate Over the links found in the Current URI",
"name": "__iteratePosts",
"signature": "def __iteratePosts(self)"
},
{
"docstring": "This will tak... | 5 | stack_v2_sparse_classes_30k_train_007234 | Implement the Python class `CustomerServiceScoreBoardConnector` described below.
Class description:
This will fetch the info for Sample uris is http://www.customerservicescoreboard.com/Bank+of+America
Method signatures and docstrings:
- def fetch(self): Fetch of customerservicescoreboard.com
- def __iteratePosts(self... | Implement the Python class `CustomerServiceScoreBoardConnector` described below.
Class description:
This will fetch the info for Sample uris is http://www.customerservicescoreboard.com/Bank+of+America
Method signatures and docstrings:
- def fetch(self): Fetch of customerservicescoreboard.com
- def __iteratePosts(self... | dbd14efb81b28be6340dfd00df9d31cc6a290b08 | <|skeleton|>
class CustomerServiceScoreBoardConnector:
"""This will fetch the info for Sample uris is http://www.customerservicescoreboard.com/Bank+of+America"""
def fetch(self):
"""Fetch of customerservicescoreboard.com"""
<|body_0|>
def __iteratePosts(self):
"""It will Iterate Ov... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomerServiceScoreBoardConnector:
"""This will fetch the info for Sample uris is http://www.customerservicescoreboard.com/Bank+of+America"""
def fetch(self):
"""Fetch of customerservicescoreboard.com"""
try:
self.__genre = 'review'
self.__task_elements_dict = {'p... | the_stack_v2_python_sparse | crawler/connectors/customerservicescoreboardconnector.py | jsyadav/CrawlerFramework | train | 1 |
3381a9138c5525d1bf3a77d35b79f4586eafc6b8 | [
"startTime = datetime.datetime.now()\nif trial:\n endTime = datetime.datetime.now()\n return {'start': startTime, 'end': endTime}\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate(TEAM_NAME, TEAM_NAME)\ndocument = repo[DEMOGRAPHIC_DATA_COUNTY_NAME].find_one()\nkeys = []\nfor key in do... | <|body_start_0|>
startTime = datetime.datetime.now()
if trial:
endTime = datetime.datetime.now()
return {'start': startTime, 'end': endTime}
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate(TEAM_NAME, TEAM_NAME)
document = re... | transformationSummaryMetrics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class transformationSummaryMetrics:
def execute(trial=False):
"""Retrieve summary demographic data for all facts by county and town and insert into collection ex) {'Fact': 'Population estimates, July 1, 2017, (V2017)', 'Town_Min': 'Middleton town, Essex County, Massachusetts', 'Town_Min_Val': ... | stack_v2_sparse_classes_10k_train_002358 | 7,267 | no_license | [
{
"docstring": "Retrieve summary demographic data for all facts by county and town and insert into collection ex) {'Fact': 'Population estimates, July 1, 2017, (V2017)', 'Town_Min': 'Middleton town, Essex County, Massachusetts', 'Town_Min_Val': '9,861', 'Town_Max': 'Littleton town, Middlesex County, Massachuset... | 2 | stack_v2_sparse_classes_30k_train_005701 | Implement the Python class `transformationSummaryMetrics` described below.
Class description:
Implement the transformationSummaryMetrics class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve summary demographic data for all facts by county and town and insert into collection ex) {'Fact': 'Popu... | Implement the Python class `transformationSummaryMetrics` described below.
Class description:
Implement the transformationSummaryMetrics class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve summary demographic data for all facts by county and town and insert into collection ex) {'Fact': 'Popu... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class transformationSummaryMetrics:
def execute(trial=False):
"""Retrieve summary demographic data for all facts by county and town and insert into collection ex) {'Fact': 'Population estimates, July 1, 2017, (V2017)', 'Town_Min': 'Middleton town, Essex County, Massachusetts', 'Town_Min_Val': ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class transformationSummaryMetrics:
def execute(trial=False):
"""Retrieve summary demographic data for all facts by county and town and insert into collection ex) {'Fact': 'Population estimates, July 1, 2017, (V2017)', 'Town_Min': 'Middleton town, Essex County, Massachusetts', 'Town_Min_Val': '9,861', 'Town... | the_stack_v2_python_sparse | ldisalvo_skeesara_vidyaap/transformationSummaryMetrics.py | maximega/course-2019-spr-proj | train | 2 | |
6100f1a09996674b67a958a7026ada368ae699fb | [
"nn.Module.__init__(self)\nself.P = P\nself.nu = nu\nself.eps = eps",
"dist = torch.sum((input - torch.matmul(self.P, input.transpose(0, 1)).transpose(0, 1)) ** 2, dim=1)\nif self.soft_boundary:\n scores = dist - R ** 2\n loss = R ** 2 + 1 / self.nu * torch.mean(torch.max(torch.zeros_like(scores), scores))\... | <|body_start_0|>
nn.Module.__init__(self)
self.P = P
self.nu = nu
self.eps = eps
<|end_body_0|>
<|body_start_1|>
dist = torch.sum((input - torch.matmul(self.P, input.transpose(0, 1)).transpose(0, 1)) ** 2, dim=1)
if self.soft_boundary:
scores = dist - R ** 2
... | Implementation of the DeepSVDD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by Arnout Devos et al. (2019). | DeepSVDDLossSubspace | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepSVDDLossSubspace:
"""Implementation of the DeepSVDD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by Arnout Devos et al. (2019)."""
de... | stack_v2_sparse_classes_10k_train_002359 | 18,386 | permissive | [
{
"docstring": "Constructor of the DeepSVDD loss Subspace. ---------- INPUT |---- P (torch.Tensor) The projection matrix to the subspace of normal | sample. P is a MxM matrix where M is the embedding dimension. |---- nu (float) a priory fraction of outliers. |---- eps (float) epsilon to ensure numerical stabili... | 2 | stack_v2_sparse_classes_30k_train_002904 | Implement the Python class `DeepSVDDLossSubspace` described below.
Class description:
Implementation of the DeepSVDD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by... | Implement the Python class `DeepSVDDLossSubspace` described below.
Class description:
Implementation of the DeepSVDD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by... | 850b6195d6290a50eee865b4d5a66f5db5260e8f | <|skeleton|>
class DeepSVDDLossSubspace:
"""Implementation of the DeepSVDD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by Arnout Devos et al. (2019)."""
de... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeepSVDDLossSubspace:
"""Implementation of the DeepSVDD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by Arnout Devos et al. (2019)."""
def __init__(se... | the_stack_v2_python_sparse | Code/src/models/optim/CustomLosses.py | antoine-spahr/X-ray-Anomaly-Detection | train | 3 |
dc32d9e620f1bec5cb404a7ce702f4b26d02de5e | [
"self.job_id = job_id\nself.cloud_target_type = cloud_target_type\nself.expiry_time_usecs = expiry_time_usecs\nself.target_id = target_id\nself.target_name = target_name\nself.total_snapshots = total_snapshots\nself.mtype = mtype",
"if dictionary is None:\n return None\njob_id = dictionary.get('JobId')\ncloud_... | <|body_start_0|>
self.job_id = job_id
self.cloud_target_type = cloud_target_type
self.expiry_time_usecs = expiry_time_usecs
self.target_id = target_id
self.target_name = target_name
self.total_snapshots = total_snapshots
self.mtype = mtype
<|end_body_0|>
<|body_s... | Implementation of the 'GdprCopyTask' model. CopyTask defines the copy tasks of a job. Attributes: job_id (long|int): Specifies the job with which this copy task is tied to. Note: this is only used for internal aggregation. cloud_target_type (string): Specifies the cloud deploy target type. For example 'kAzure','kAWS', ... | GdprCopyTask | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GdprCopyTask:
"""Implementation of the 'GdprCopyTask' model. CopyTask defines the copy tasks of a job. Attributes: job_id (long|int): Specifies the job with which this copy task is tied to. Note: this is only used for internal aggregation. cloud_target_type (string): Specifies the cloud deploy ta... | stack_v2_sparse_classes_10k_train_002360 | 3,218 | permissive | [
{
"docstring": "Constructor for the GdprCopyTask class",
"name": "__init__",
"signature": "def __init__(self, job_id=None, cloud_target_type=None, expiry_time_usecs=None, target_id=None, target_name=None, total_snapshots=None, mtype=None)"
},
{
"docstring": "Creates an instance of this model fro... | 2 | stack_v2_sparse_classes_30k_train_001191 | Implement the Python class `GdprCopyTask` described below.
Class description:
Implementation of the 'GdprCopyTask' model. CopyTask defines the copy tasks of a job. Attributes: job_id (long|int): Specifies the job with which this copy task is tied to. Note: this is only used for internal aggregation. cloud_target_type ... | Implement the Python class `GdprCopyTask` described below.
Class description:
Implementation of the 'GdprCopyTask' model. CopyTask defines the copy tasks of a job. Attributes: job_id (long|int): Specifies the job with which this copy task is tied to. Note: this is only used for internal aggregation. cloud_target_type ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class GdprCopyTask:
"""Implementation of the 'GdprCopyTask' model. CopyTask defines the copy tasks of a job. Attributes: job_id (long|int): Specifies the job with which this copy task is tied to. Note: this is only used for internal aggregation. cloud_target_type (string): Specifies the cloud deploy ta... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GdprCopyTask:
"""Implementation of the 'GdprCopyTask' model. CopyTask defines the copy tasks of a job. Attributes: job_id (long|int): Specifies the job with which this copy task is tied to. Note: this is only used for internal aggregation. cloud_target_type (string): Specifies the cloud deploy target type. Fo... | the_stack_v2_python_sparse | cohesity_management_sdk/models/gdpr_copy_task.py | cohesity/management-sdk-python | train | 24 |
e9b6bf2dd1eb7ddd3c48b9f328ed2be0afecd239 | [
"queryset = self.filter_queryset(self.get_queryset())\nuid = force_text(urlsafe_base64_decode(self.kwargs['uid']))\ntoken = self.kwargs['token']\nobj = get_object_or_404(queryset, pk=uid)\nself.check_object_permissions(self.request, obj)\nif not default_token_generator.check_token(user=obj, token=token):\n raise... | <|body_start_0|>
queryset = self.filter_queryset(self.get_queryset())
uid = force_text(urlsafe_base64_decode(self.kwargs['uid']))
token = self.kwargs['token']
obj = get_object_or_404(queryset, pk=uid)
self.check_object_permissions(self.request, obj)
if not default_token_g... | User activate view. | UserActivation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserActivation:
"""User activate view."""
def get_object(self) -> User:
"""Get user by uid and check permissions. :return: User."""
<|body_0|>
def get(self, request: Request, *args: tuple, **kwargs: dict) -> Response:
"""Activate user. :param request: :return:"""... | stack_v2_sparse_classes_10k_train_002361 | 5,061 | no_license | [
{
"docstring": "Get user by uid and check permissions. :return: User.",
"name": "get_object",
"signature": "def get_object(self) -> User"
},
{
"docstring": "Activate user. :param request: :return:",
"name": "get",
"signature": "def get(self, request: Request, *args: tuple, **kwargs: dict... | 2 | stack_v2_sparse_classes_30k_train_002270 | Implement the Python class `UserActivation` described below.
Class description:
User activate view.
Method signatures and docstrings:
- def get_object(self) -> User: Get user by uid and check permissions. :return: User.
- def get(self, request: Request, *args: tuple, **kwargs: dict) -> Response: Activate user. :param... | Implement the Python class `UserActivation` described below.
Class description:
User activate view.
Method signatures and docstrings:
- def get_object(self) -> User: Get user by uid and check permissions. :return: User.
- def get(self, request: Request, *args: tuple, **kwargs: dict) -> Response: Activate user. :param... | 713b9d84ac70d964d46f189ab1f9c7b944b9684b | <|skeleton|>
class UserActivation:
"""User activate view."""
def get_object(self) -> User:
"""Get user by uid and check permissions. :return: User."""
<|body_0|>
def get(self, request: Request, *args: tuple, **kwargs: dict) -> Response:
"""Activate user. :param request: :return:"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserActivation:
"""User activate view."""
def get_object(self) -> User:
"""Get user by uid and check permissions. :return: User."""
queryset = self.filter_queryset(self.get_queryset())
uid = force_text(urlsafe_base64_decode(self.kwargs['uid']))
token = self.kwargs['token']... | the_stack_v2_python_sparse | jobadvisor/users/views/registration.py | ewgen19892/jobadvisor | train | 0 |
6be363362f51f0d889ac06917a9e911ed094a888 | [
"if isinstance(obj, str):\n raise NotImplementedError\nself.converter = obj\nself.N = N\nself.results = None\nself.include_dummy = False\nif to_exclude is None:\n self.to_exclude = []\nelse:\n self.to_exclude = to_exclude\nif to_include is None:\n self.to_include = []\nelse:\n self.to_include = to_in... | <|body_start_0|>
if isinstance(obj, str):
raise NotImplementedError
self.converter = obj
self.N = N
self.results = None
self.include_dummy = False
if to_exclude is None:
self.to_exclude = []
else:
self.to_exclude = to_exclude
... | Convenient class to benchmark several methods for a given converter :: c = Bam2Bed(infile, outfile) b = Benchmark(c, N=5) b.run_methods() b.plot() | Benchmark | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Benchmark:
"""Convenient class to benchmark several methods for a given converter :: c = Bam2Bed(infile, outfile) b = Benchmark(c, N=5) b.run_methods() b.plot()"""
def __init__(self, obj, N=5, to_exclude=None, to_include=None):
""".. rubric:: constructor :param obj: can be an instanc... | stack_v2_sparse_classes_10k_train_002362 | 6,414 | permissive | [
{
"docstring": ".. rubric:: constructor :param obj: can be an instance of a converter class or a class name :param int N: number of replicates :param list to_exclude: methods to exclude from the benchmark :param list to_include: methods to include ONLY Use one of to_exclude or to_include. If both are provided, ... | 3 | stack_v2_sparse_classes_30k_train_006901 | Implement the Python class `Benchmark` described below.
Class description:
Convenient class to benchmark several methods for a given converter :: c = Bam2Bed(infile, outfile) b = Benchmark(c, N=5) b.run_methods() b.plot()
Method signatures and docstrings:
- def __init__(self, obj, N=5, to_exclude=None, to_include=Non... | Implement the Python class `Benchmark` described below.
Class description:
Convenient class to benchmark several methods for a given converter :: c = Bam2Bed(infile, outfile) b = Benchmark(c, N=5) b.run_methods() b.plot()
Method signatures and docstrings:
- def __init__(self, obj, N=5, to_exclude=None, to_include=Non... | 60a746290e763fd1041732dab0bda123841e5b26 | <|skeleton|>
class Benchmark:
"""Convenient class to benchmark several methods for a given converter :: c = Bam2Bed(infile, outfile) b = Benchmark(c, N=5) b.run_methods() b.plot()"""
def __init__(self, obj, N=5, to_exclude=None, to_include=None):
""".. rubric:: constructor :param obj: can be an instanc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Benchmark:
"""Convenient class to benchmark several methods for a given converter :: c = Bam2Bed(infile, outfile) b = Benchmark(c, N=5) b.run_methods() b.plot()"""
def __init__(self, obj, N=5, to_exclude=None, to_include=None):
""".. rubric:: constructor :param obj: can be an instance of a conver... | the_stack_v2_python_sparse | bioconvert/core/benchmark.py | ddesvillechabrol/bioconvert | train | 1 |
3d2c1538dd30697dabbc21cbf9d9835334a7d8aa | [
"soup = bs(response.text, 'html.parser')\npage_div = soup.find('div', class_='col-md-2 col-xs-3 text-right')\nself.max_page = int(page_div.select('a')[-1].get('href').split('/')[-1]) if page_div.select('a')[-1] else 0\nyield scrapy.Request(response.url, callback=self.parse_get_next_page)",
"soup = bs(response.tex... | <|body_start_0|>
soup = bs(response.text, 'html.parser')
page_div = soup.find('div', class_='col-md-2 col-xs-3 text-right')
self.max_page = int(page_div.select('a')[-1].get('href').split('/')[-1]) if page_div.select('a')[-1] else 0
yield scrapy.Request(response.url, callback=self.parse_g... | dprSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dprSpider:
def parse(self, response):
""":param response: :return: 最大页码数"""
<|body_0|>
def parse_get_next_page(self, response):
""":param response: :return:一级目录链接"""
<|body_1|>
def get_news_detail(self, response):
""":param response: x新闻正文respons... | stack_v2_sparse_classes_10k_train_002363 | 4,942 | no_license | [
{
"docstring": ":param response: :return: 最大页码数",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": ":param response: :return:一级目录链接",
"name": "parse_get_next_page",
"signature": "def parse_get_next_page(self, response)"
},
{
"docstring": ":param respons... | 3 | stack_v2_sparse_classes_30k_test_000193 | Implement the Python class `dprSpider` described below.
Class description:
Implement the dprSpider class.
Method signatures and docstrings:
- def parse(self, response): :param response: :return: 最大页码数
- def parse_get_next_page(self, response): :param response: :return:一级目录链接
- def get_news_detail(self, response): :pa... | Implement the Python class `dprSpider` described below.
Class description:
Implement the dprSpider class.
Method signatures and docstrings:
- def parse(self, response): :param response: :return: 最大页码数
- def parse_get_next_page(self, response): :param response: :return:一级目录链接
- def get_news_detail(self, response): :pa... | 1bcb03a48aff1ebca4e04a5c060be299ca9881d4 | <|skeleton|>
class dprSpider:
def parse(self, response):
""":param response: :return: 最大页码数"""
<|body_0|>
def parse_get_next_page(self, response):
""":param response: :return:一级目录链接"""
<|body_1|>
def get_news_detail(self, response):
""":param response: x新闻正文respons... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class dprSpider:
def parse(self, response):
""":param response: :return: 最大页码数"""
soup = bs(response.text, 'html.parser')
page_div = soup.find('div', class_='col-md-2 col-xs-3 text-right')
self.max_page = int(page_div.select('a')[-1].get('href').split('/')[-1]) if page_div.select('a'... | the_stack_v2_python_sparse | crawler/v1/dprgoid.py | AMAtreus/dg_crawler_website | train | 0 | |
340ca5d86442dc63c1c4bb8325f9e14a4238ffd1 | [
"ROWS = len(A)\nCOLS = len(A[0])\ngrid = [[0 for _ in range(COLS)] for _ in range(2)]\nfor i in range(ROWS - 1, -1, -1):\n for j in range(COLS):\n if i == ROWS - 1:\n grid[i & 1][j] = A[i][j]\n else:\n grid[i & 1][j] = grid[i + 1 & 1][j]\n if j + 1 < COLS:\n ... | <|body_start_0|>
ROWS = len(A)
COLS = len(A[0])
grid = [[0 for _ in range(COLS)] for _ in range(2)]
for i in range(ROWS - 1, -1, -1):
for j in range(COLS):
if i == ROWS - 1:
grid[i & 1][j] = A[i][j]
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minFallingPathSumBackwardDP(self, A: List[List[int]]) -> int:
"""Just save the min falling path (i, j) -> minimum value start from bottom row as base case, build next layer above based on bottom row."""
<|body_0|>
def minFallingPathSum(self, A: List[List[int]])... | stack_v2_sparse_classes_10k_train_002364 | 3,215 | no_license | [
{
"docstring": "Just save the min falling path (i, j) -> minimum value start from bottom row as base case, build next layer above based on bottom row.",
"name": "minFallingPathSumBackwardDP",
"signature": "def minFallingPathSumBackwardDP(self, A: List[List[int]]) -> int"
},
{
"docstring": "Just ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minFallingPathSumBackwardDP(self, A: List[List[int]]) -> int: Just save the min falling path (i, j) -> minimum value start from bottom row as base case, build next layer abov... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minFallingPathSumBackwardDP(self, A: List[List[int]]) -> int: Just save the min falling path (i, j) -> minimum value start from bottom row as base case, build next layer abov... | 483f0c93faca8ccaf038b77ebe2fa712f6b0c6bc | <|skeleton|>
class Solution:
def minFallingPathSumBackwardDP(self, A: List[List[int]]) -> int:
"""Just save the min falling path (i, j) -> minimum value start from bottom row as base case, build next layer above based on bottom row."""
<|body_0|>
def minFallingPathSum(self, A: List[List[int]])... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minFallingPathSumBackwardDP(self, A: List[List[int]]) -> int:
"""Just save the min falling path (i, j) -> minimum value start from bottom row as base case, build next layer above based on bottom row."""
ROWS = len(A)
COLS = len(A[0])
grid = [[0 for _ in range(COLS... | the_stack_v2_python_sparse | Algorithms and Data Structures Practice/LeetCode Questions/MOST IMPORTANT PROBLEMS/931. Minimum Falling Path Sum.py | harman666666/Algorithms-Data-Structures-and-Design | train | 3 | |
368f6af11c168552220469a2544d8c0b88f0ff25 | [
"context = req.environ['nova.context']\nauthorize(context)\nreturn volume_types.get_all_types(context)",
"context = req.environ['nova.context']\nauthorize(context)\nif not body or body == '':\n raise exc.HTTPUnprocessableEntity()\nvol_type = body.get('volume_type', None)\nif vol_type is None or vol_type == '':... | <|body_start_0|>
context = req.environ['nova.context']
authorize(context)
return volume_types.get_all_types(context)
<|end_body_0|>
<|body_start_1|>
context = req.environ['nova.context']
authorize(context)
if not body or body == '':
raise exc.HTTPUnprocessabl... | The volume types API controller for the Openstack API | VolumeTypesController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolumeTypesController:
"""The volume types API controller for the Openstack API"""
def index(self, req):
"""Returns the list of volume types"""
<|body_0|>
def create(self, req, body):
"""Creates a new volume type."""
<|body_1|>
def show(self, req, id... | stack_v2_sparse_classes_10k_train_002365 | 8,791 | permissive | [
{
"docstring": "Returns the list of volume types",
"name": "index",
"signature": "def index(self, req)"
},
{
"docstring": "Creates a new volume type.",
"name": "create",
"signature": "def create(self, req, body)"
},
{
"docstring": "Return a single volume type item",
"name": "... | 5 | stack_v2_sparse_classes_30k_train_005099 | Implement the Python class `VolumeTypesController` described below.
Class description:
The volume types API controller for the Openstack API
Method signatures and docstrings:
- def index(self, req): Returns the list of volume types
- def create(self, req, body): Creates a new volume type.
- def show(self, req, id): R... | Implement the Python class `VolumeTypesController` described below.
Class description:
The volume types API controller for the Openstack API
Method signatures and docstrings:
- def index(self, req): Returns the list of volume types
- def create(self, req, body): Creates a new volume type.
- def show(self, req, id): R... | d3de121d6ad35431fb63c20b2185f0f61ceb9e8e | <|skeleton|>
class VolumeTypesController:
"""The volume types API controller for the Openstack API"""
def index(self, req):
"""Returns the list of volume types"""
<|body_0|>
def create(self, req, body):
"""Creates a new volume type."""
<|body_1|>
def show(self, req, id... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VolumeTypesController:
"""The volume types API controller for the Openstack API"""
def index(self, req):
"""Returns the list of volume types"""
context = req.environ['nova.context']
authorize(context)
return volume_types.get_all_types(context)
def create(self, req, bo... | the_stack_v2_python_sparse | nova/api/openstack/compute/contrib/volumetypes.py | rcbops/nova-buildpackage | train | 0 |
14fb1f79292a79bb569ac8b964e3c211c10be157 | [
"essential_keys = ['nvars', 'c', 'freq']\nfor key in essential_keys:\n if key not in problem_params:\n msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys()))\n raise ParameterError(msg)\nif (problem_params['nvars'] + 1) % 2 != 0:\n raise ProblemError('setup requi... | <|body_start_0|>
essential_keys = ['nvars', 'c', 'freq']
for key in essential_keys:
if key not in problem_params:
msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys()))
raise ParameterError(msg)
if (problem_params['nvar... | Example implementing the unforced 1D advection equation with periodic BC in [0,1], discretized using upwinding finite differences Attributes: A: FD discretization of the gradient operator using upwinding dx: distance between two spatial nodes | advection1d_dirichlet | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class advection1d_dirichlet:
"""Example implementing the unforced 1D advection equation with periodic BC in [0,1], discretized using upwinding finite differences Attributes: A: FD discretization of the gradient operator using upwinding dx: distance between two spatial nodes"""
def __init__(self, p... | stack_v2_sparse_classes_10k_train_002366 | 5,002 | permissive | [
{
"docstring": "Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class)",
"name": "__init__",
"signature": "def __init__(self, problem_params, dtype_u=mesh, dtype_f=m... | 5 | stack_v2_sparse_classes_30k_train_005919 | Implement the Python class `advection1d_dirichlet` described below.
Class description:
Example implementing the unforced 1D advection equation with periodic BC in [0,1], discretized using upwinding finite differences Attributes: A: FD discretization of the gradient operator using upwinding dx: distance between two spa... | Implement the Python class `advection1d_dirichlet` described below.
Class description:
Example implementing the unforced 1D advection equation with periodic BC in [0,1], discretized using upwinding finite differences Attributes: A: FD discretization of the gradient operator using upwinding dx: distance between two spa... | de2cd523411276083355389d7e7993106cedf93d | <|skeleton|>
class advection1d_dirichlet:
"""Example implementing the unforced 1D advection equation with periodic BC in [0,1], discretized using upwinding finite differences Attributes: A: FD discretization of the gradient operator using upwinding dx: distance between two spatial nodes"""
def __init__(self, p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class advection1d_dirichlet:
"""Example implementing the unforced 1D advection equation with periodic BC in [0,1], discretized using upwinding finite differences Attributes: A: FD discretization of the gradient operator using upwinding dx: distance between two spatial nodes"""
def __init__(self, problem_params... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/AdvectionEquation_1D_FD_dirichlet.py | ruthschoebel/pySDC | train | 0 |
2511a8af35db60015dba0d5b1537075669473edd | [
"ret = []\nfor i in range(numRows):\n row = [1]\n if ret:\n for i in range(len(ret[-1]) - 1):\n row.append(ret[-1][i] + ret[-1][i + 1])\n row.append(1)\n ret.append(row)\nreturn ret",
"if numRows == 0:\n return []\nret = [[1]]\nfor i in range(1, numRows):\n row = [1]\n f... | <|body_start_0|>
ret = []
for i in range(numRows):
row = [1]
if ret:
for i in range(len(ret[-1]) - 1):
row.append(ret[-1][i] + ret[-1][i + 1])
row.append(1)
ret.append(row)
return ret
<|end_body_0|>
<|body_s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
"""07/17/2021 08:17"""
<|body_0|>
def generate(self, numRows: int) -> List[List[int]]:
"""07/31/2022 22:48"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = []
for i in range... | stack_v2_sparse_classes_10k_train_002367 | 1,597 | no_license | [
{
"docstring": "07/17/2021 08:17",
"name": "generate",
"signature": "def generate(self, numRows: int) -> List[List[int]]"
},
{
"docstring": "07/31/2022 22:48",
"name": "generate",
"signature": "def generate(self, numRows: int) -> List[List[int]]"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generate(self, numRows: int) -> List[List[int]]: 07/17/2021 08:17
- def generate(self, numRows: int) -> List[List[int]]: 07/31/2022 22:48 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generate(self, numRows: int) -> List[List[int]]: 07/17/2021 08:17
- def generate(self, numRows: int) -> List[List[int]]: 07/31/2022 22:48
<|skeleton|>
class Solution:
d... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
"""07/17/2021 08:17"""
<|body_0|>
def generate(self, numRows: int) -> List[List[int]]:
"""07/31/2022 22:48"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def generate(self, numRows: int) -> List[List[int]]:
"""07/17/2021 08:17"""
ret = []
for i in range(numRows):
row = [1]
if ret:
for i in range(len(ret[-1]) - 1):
row.append(ret[-1][i] + ret[-1][i + 1])
... | the_stack_v2_python_sparse | leetcode/solved/118_Pascal's_Triangle/solution.py | sungminoh/algorithms | train | 0 | |
b3b06e495044b2c5b5889a3f971cb715508a9e68 | [
"if not root:\n return ''\nqueue = deque()\nqueue.append(root)\nresult = []\nwhile queue:\n curr = queue.popleft()\n if curr != None:\n result.append(str(curr.val))\n result.append(',')\n queue.append(curr.left)\n queue.append(curr.right)\n else:\n result.append('null'... | <|body_start_0|>
if not root:
return ''
queue = deque()
queue.append(root)
result = []
while queue:
curr = queue.popleft()
if curr != None:
result.append(str(curr.val))
result.append(',')
queue.ap... | 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_002368 | 2,099 | 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_val_000025 | 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:... | 52bf12095996a9137b1ea213ac43e1fe07806956 | <|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 ''
queue = deque()
queue.append(root)
result = []
while queue:
curr = queue.popleft()
if curr != N... | the_stack_v2_python_sparse | serialize-and-deserialize-binary-tree/serialize-and-deserialize-binary-tree.py | siva4646/LeetCode_Python | train | 0 | |
765f41b4953076d60696f39ed97239d2fe446025 | [
"input_tensor = tf.ones([1, 4, 4, 2])\noutput_tensor = cnn_autoencoder_model.encoder(input_tensor, layers_list=(64, 2), pool_list=(2, 2))\nself.assertAllEqual(output_tensor.shape, [1, 2, 2, 2])\nexpected = tf.constant([[[[-0.02436768, -0.27847868], [-0.0774256, -0.5111736]], [[0.50436425, -0.1713084], [0.2803106, -... | <|body_start_0|>
input_tensor = tf.ones([1, 4, 4, 2])
output_tensor = cnn_autoencoder_model.encoder(input_tensor, layers_list=(64, 2), pool_list=(2, 2))
self.assertAllEqual(output_tensor.shape, [1, 2, 2, 2])
expected = tf.constant([[[[-0.02436768, -0.27847868], [-0.0774256, -0.5111736]],... | CNNAutoencoderModelTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNNAutoencoderModelTest:
def test_encoder_default(self):
"""Tests encoder with default inputs."""
<|body_0|>
def test_encoder_pool_list_values(self):
"""Tests encoder with default inputs."""
<|body_1|>
def test_encoder_batch_norm_all(self):
"""Te... | stack_v2_sparse_classes_10k_train_002369 | 4,774 | permissive | [
{
"docstring": "Tests encoder with default inputs.",
"name": "test_encoder_default",
"signature": "def test_encoder_default(self)"
},
{
"docstring": "Tests encoder with default inputs.",
"name": "test_encoder_pool_list_values",
"signature": "def test_encoder_pool_list_values(self)"
},
... | 5 | null | Implement the Python class `CNNAutoencoderModelTest` described below.
Class description:
Implement the CNNAutoencoderModelTest class.
Method signatures and docstrings:
- def test_encoder_default(self): Tests encoder with default inputs.
- def test_encoder_pool_list_values(self): Tests encoder with default inputs.
- d... | Implement the Python class `CNNAutoencoderModelTest` described below.
Class description:
Implement the CNNAutoencoderModelTest class.
Method signatures and docstrings:
- def test_encoder_default(self): Tests encoder with default inputs.
- def test_encoder_pool_list_values(self): Tests encoder with default inputs.
- d... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class CNNAutoencoderModelTest:
def test_encoder_default(self):
"""Tests encoder with default inputs."""
<|body_0|>
def test_encoder_pool_list_values(self):
"""Tests encoder with default inputs."""
<|body_1|>
def test_encoder_batch_norm_all(self):
"""Te... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CNNAutoencoderModelTest:
def test_encoder_default(self):
"""Tests encoder with default inputs."""
input_tensor = tf.ones([1, 4, 4, 2])
output_tensor = cnn_autoencoder_model.encoder(input_tensor, layers_list=(64, 2), pool_list=(2, 2))
self.assertAllEqual(output_tensor.shape, [1,... | the_stack_v2_python_sparse | simulation_research/next_day_wildfire_spread/models/cnn_autoencoder_model_test.py | Jimmy-INL/google-research | train | 1 | |
413973fe2c109f9747000d793dfa108bdbf7a173 | [
"self.map_func = map_func\nself.reduce_func = reduce_func\nself.pool = multiprocessing.Pool(num_workers)",
"partitioned_data = collections.defaultdict(list)\nfor key, value in mapped_values:\n partitioned_data[key].append(value)\nreturn partitioned_data.items()",
"map_responses = self.pool.map(self.map_func,... | <|body_start_0|>
self.map_func = map_func
self.reduce_func = reduce_func
self.pool = multiprocessing.Pool(num_workers)
<|end_body_0|>
<|body_start_1|>
partitioned_data = collections.defaultdict(list)
for key, value in mapped_values:
partitioned_data[key].append(value... | SimpleMapReduce | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleMapReduce:
def __init__(self, map_func, reduce_func, num_workers=None):
"""map_func Function to map inputs to intermediate data.Takes as argument one input value and returns a tuple with the key and a value to be reduced. reduce_func Function to reduce partitioned version of interm... | stack_v2_sparse_classes_10k_train_002370 | 2,086 | no_license | [
{
"docstring": "map_func Function to map inputs to intermediate data.Takes as argument one input value and returns a tuple with the key and a value to be reduced. reduce_func Function to reduce partitioned version of intermediate data to final output. Takes as argument a key as produced by map_func and a sequen... | 3 | null | Implement the Python class `SimpleMapReduce` described below.
Class description:
Implement the SimpleMapReduce class.
Method signatures and docstrings:
- def __init__(self, map_func, reduce_func, num_workers=None): map_func Function to map inputs to intermediate data.Takes as argument one input value and returns a tu... | Implement the Python class `SimpleMapReduce` described below.
Class description:
Implement the SimpleMapReduce class.
Method signatures and docstrings:
- def __init__(self, map_func, reduce_func, num_workers=None): map_func Function to map inputs to intermediate data.Takes as argument one input value and returns a tu... | c3c554f14b378b487c632e11f22e5e3118be940c | <|skeleton|>
class SimpleMapReduce:
def __init__(self, map_func, reduce_func, num_workers=None):
"""map_func Function to map inputs to intermediate data.Takes as argument one input value and returns a tuple with the key and a value to be reduced. reduce_func Function to reduce partitioned version of interm... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SimpleMapReduce:
def __init__(self, map_func, reduce_func, num_workers=None):
"""map_func Function to map inputs to intermediate data.Takes as argument one input value and returns a tuple with the key and a value to be reduced. reduce_func Function to reduce partitioned version of intermediate data to... | the_stack_v2_python_sparse | Simple_Python/standard/multiprocessing/multiprocessing_24.py | yafeile/Simple_Study | train | 0 | |
059e83a3f1c7a999df0f2ab18dc8000302497dbf | [
"main_data = self.get_main_data(imdb_id, api_data)\nratings_data = self.get_ratings_data(imdb_id, api_data)\nif ratings_data and main_data:\n return {'omdb_main': main_data, 'omdb_ratings': ratings_data}\nelse:\n raise GatherException(imdb_id, 'Failed standardise')",
"try:\n main_data = [{'imdb_id': imdb... | <|body_start_0|>
main_data = self.get_main_data(imdb_id, api_data)
ratings_data = self.get_ratings_data(imdb_id, api_data)
if ratings_data and main_data:
return {'omdb_main': main_data, 'omdb_ratings': ratings_data}
else:
raise GatherException(imdb_id, 'Failed sta... | This class standardises the response returned from the OMDB API, removing unwanted data, and structuring the remaining data so that it is easier to handle in later processes. | StandardiseResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StandardiseResponse:
"""This class standardises the response returned from the OMDB API, removing unwanted data, and structuring the remaining data so that it is easier to handle in later processes."""
def standardise(self, imdb_id, api_data):
"""Constructs a new dictionary from the ... | stack_v2_sparse_classes_10k_train_002371 | 5,419 | permissive | [
{
"docstring": "Constructs a new dictionary from the API data. :param imdb_id: The imdb_id for the requested film :param api_data: The raw response from the OMDB API :return: A standardised dictionary.",
"name": "standardise",
"signature": "def standardise(self, imdb_id, api_data)"
},
{
"docstri... | 3 | stack_v2_sparse_classes_30k_val_000333 | Implement the Python class `StandardiseResponse` described below.
Class description:
This class standardises the response returned from the OMDB API, removing unwanted data, and structuring the remaining data so that it is easier to handle in later processes.
Method signatures and docstrings:
- def standardise(self, ... | Implement the Python class `StandardiseResponse` described below.
Class description:
This class standardises the response returned from the OMDB API, removing unwanted data, and structuring the remaining data so that it is easier to handle in later processes.
Method signatures and docstrings:
- def standardise(self, ... | cd6974764f8136529e5d4a3c191ad34865bfe732 | <|skeleton|>
class StandardiseResponse:
"""This class standardises the response returned from the OMDB API, removing unwanted data, and structuring the remaining data so that it is easier to handle in later processes."""
def standardise(self, imdb_id, api_data):
"""Constructs a new dictionary from the ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StandardiseResponse:
"""This class standardises the response returned from the OMDB API, removing unwanted data, and structuring the remaining data so that it is easier to handle in later processes."""
def standardise(self, imdb_id, api_data):
"""Constructs a new dictionary from the API data. :pa... | the_stack_v2_python_sparse | processes/get_omdb.py | kinoreel/kino-gather | train | 0 |
e260482940e11314881315ce489a1aaca5e444f0 | [
"course_key = self.course.location.course_key\nbadge_class = BadgeClassFactory.create(course_id=course_key)\nfor dummy in range(3):\n BadgeAssertionFactory.create(user=self.user, badge_class=badge_class)\nfor dummy in range(3):\n BadgeAssertionFactory.create(user=self.user)\nfor dummy in range(6):\n BadgeA... | <|body_start_0|>
course_key = self.course.location.course_key
badge_class = BadgeClassFactory.create(course_id=course_key)
for dummy in range(3):
BadgeAssertionFactory.create(user=self.user, badge_class=badge_class)
for dummy in range(3):
BadgeAssertionFactory.cre... | Test the Badge Assertions view with the course_id filter. | TestUserCourseBadgeAssertions | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUserCourseBadgeAssertions:
"""Test the Badge Assertions view with the course_id filter."""
def test_get_assertions(self):
"""Verify we can get assertions via the course_id and username."""
<|body_0|>
def test_assertion_structure(self):
"""Verify the badge ass... | stack_v2_sparse_classes_10k_train_002372 | 8,941 | permissive | [
{
"docstring": "Verify we can get assertions via the course_id and username.",
"name": "test_get_assertions",
"signature": "def test_get_assertions(self)"
},
{
"docstring": "Verify the badge assertion structure is as expected when a course is involved.",
"name": "test_assertion_structure",
... | 2 | stack_v2_sparse_classes_30k_train_000824 | Implement the Python class `TestUserCourseBadgeAssertions` described below.
Class description:
Test the Badge Assertions view with the course_id filter.
Method signatures and docstrings:
- def test_get_assertions(self): Verify we can get assertions via the course_id and username.
- def test_assertion_structure(self):... | Implement the Python class `TestUserCourseBadgeAssertions` described below.
Class description:
Test the Badge Assertions view with the course_id filter.
Method signatures and docstrings:
- def test_get_assertions(self): Verify we can get assertions via the course_id and username.
- def test_assertion_structure(self):... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class TestUserCourseBadgeAssertions:
"""Test the Badge Assertions view with the course_id filter."""
def test_get_assertions(self):
"""Verify we can get assertions via the course_id and username."""
<|body_0|>
def test_assertion_structure(self):
"""Verify the badge ass... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestUserCourseBadgeAssertions:
"""Test the Badge Assertions view with the course_id filter."""
def test_get_assertions(self):
"""Verify we can get assertions via the course_id and username."""
course_key = self.course.location.course_key
badge_class = BadgeClassFactory.create(cour... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/badges/api/tests.py | luque/better-ways-of-thinking-about-software | train | 3 |
414c7e9dbe1a590259815fb994394a87e1fb9a7b | [
"cls.NETWORK_ATTACHMENT_ARG = flags.NetworkAttachmentArgument()\ncls.NETWORK_ATTACHMENT_ARG.AddArgument(parser, operation_type='create')\ncls.SUBNETWORK_ARG = subnetwork_flags.SubnetworkArgumentForNetworkAttachment()\ncls.SUBNETWORK_ARG.AddArgument(parser)\nparser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)\n... | <|body_start_0|>
cls.NETWORK_ATTACHMENT_ARG = flags.NetworkAttachmentArgument()
cls.NETWORK_ATTACHMENT_ARG.AddArgument(parser, operation_type='create')
cls.SUBNETWORK_ARG = subnetwork_flags.SubnetworkArgumentForNetworkAttachment()
cls.SUBNETWORK_ARG.AddArgument(parser)
parser.dis... | Create a Google Compute Engine network attachment. | Create | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Create:
"""Create a Google Compute Engine network attachment."""
def Args(cls, parser):
"""Create a Google Compute Engine network attachment. Args: parser: the parser that parses the input from the user."""
<|body_0|>
def Run(self, args):
"""Issue a network attac... | stack_v2_sparse_classes_10k_train_002373 | 5,014 | permissive | [
{
"docstring": "Create a Google Compute Engine network attachment. Args: parser: the parser that parses the input from the user.",
"name": "Args",
"signature": "def Args(cls, parser)"
},
{
"docstring": "Issue a network attachment INSERT request.",
"name": "Run",
"signature": "def Run(sel... | 2 | null | Implement the Python class `Create` described below.
Class description:
Create a Google Compute Engine network attachment.
Method signatures and docstrings:
- def Args(cls, parser): Create a Google Compute Engine network attachment. Args: parser: the parser that parses the input from the user.
- def Run(self, args): ... | Implement the Python class `Create` described below.
Class description:
Create a Google Compute Engine network attachment.
Method signatures and docstrings:
- def Args(cls, parser): Create a Google Compute Engine network attachment. Args: parser: the parser that parses the input from the user.
- def Run(self, args): ... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Create:
"""Create a Google Compute Engine network attachment."""
def Args(cls, parser):
"""Create a Google Compute Engine network attachment. Args: parser: the parser that parses the input from the user."""
<|body_0|>
def Run(self, args):
"""Issue a network attac... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Create:
"""Create a Google Compute Engine network attachment."""
def Args(cls, parser):
"""Create a Google Compute Engine network attachment. Args: parser: the parser that parses the input from the user."""
cls.NETWORK_ATTACHMENT_ARG = flags.NetworkAttachmentArgument()
cls.NETWORK... | the_stack_v2_python_sparse | lib/surface/compute/network_attachments/create.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
8cf82579b9009fbccb5335b99d74f667b681244d | [
"super(SubNet, self).__init__()\nself.norm = nn.BatchNorm1d(in_size)\nself.drop = nn.Dropout(p=dropout)\nself.linear_1 = nn.Linear(in_size, hidden_size)\nself.linear_2 = nn.Linear(hidden_size, hidden_size)\nself.linear_3 = nn.Linear(hidden_size, hidden_size)",
"normed = self.norm(x)\ndropped = self.drop(normed)\n... | <|body_start_0|>
super(SubNet, self).__init__()
self.norm = nn.BatchNorm1d(in_size)
self.drop = nn.Dropout(p=dropout)
self.linear_1 = nn.Linear(in_size, hidden_size)
self.linear_2 = nn.Linear(hidden_size, hidden_size)
self.linear_3 = nn.Linear(hidden_size, hidden_size)
<|... | The subnetwork that is used in TFN for video and audio in the pre-fusion stage | SubNet | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubNet:
"""The subnetwork that is used in TFN for video and audio in the pre-fusion stage"""
def __init__(self, in_size, hidden_size, dropout):
"""Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a tenso... | stack_v2_sparse_classes_10k_train_002374 | 3,873 | permissive | [
{
"docstring": "Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a tensor of shape (batch_size, hidden_size)",
"name": "__init__",
"signature": "def __init__(self, in_size, hidden_size, dropout)"
},
{
"docstring": "... | 2 | stack_v2_sparse_classes_30k_train_001841 | Implement the Python class `SubNet` described below.
Class description:
The subnetwork that is used in TFN for video and audio in the pre-fusion stage
Method signatures and docstrings:
- def __init__(self, in_size, hidden_size, dropout): Args: in_size: input dimension hidden_size: hidden layer dimension dropout: drop... | Implement the Python class `SubNet` described below.
Class description:
The subnetwork that is used in TFN for video and audio in the pre-fusion stage
Method signatures and docstrings:
- def __init__(self, in_size, hidden_size, dropout): Args: in_size: input dimension hidden_size: hidden layer dimension dropout: drop... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class SubNet:
"""The subnetwork that is used in TFN for video and audio in the pre-fusion stage"""
def __init__(self, in_size, hidden_size, dropout):
"""Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a tenso... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SubNet:
"""The subnetwork that is used in TFN for video and audio in the pre-fusion stage"""
def __init__(self, in_size, hidden_size, dropout):
"""Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a tensor of shape (b... | the_stack_v2_python_sparse | PyTorch/contrib/others/MMSA_ID2979_for_PyTorch/models/subNets/FeatureNets.py | Ascend/ModelZoo-PyTorch | train | 23 |
89ff15bbd2be63a50bc35b21850606205f9fee65 | [
"super().__init__()\nself.graph, self.session = parse_tf_model_bytes(model_bytes, device, session_config)\nself.input_image = self.graph.get_tensor_by_name('input:0')\nself.segmented_tensor = self.graph.get_tensor_by_name('output_prediction:0')",
"img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)\nfeed = {self.i... | <|body_start_0|>
super().__init__()
self.graph, self.session = parse_tf_model_bytes(model_bytes, device, session_config)
self.input_image = self.graph.get_tensor_by_name('input:0')
self.segmented_tensor = self.graph.get_tensor_by_name('output_prediction:0')
<|end_body_0|>
<|body_start_1... | Loads a model and uses it to run depth prediction, meaning that it takes an image as input and returns a matrix the size of the input image where the value of each 'pixel' corresponds to the pixel's distance from the camera in meters. Does not support batch prediction TODO: Is this true? | DepthPredictor | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DepthPredictor:
"""Loads a model and uses it to run depth prediction, meaning that it takes an image as input and returns a matrix the size of the input image where the value of each 'pixel' corresponds to the pixel's distance from the camera in meters. Does not support batch prediction TODO: Is ... | stack_v2_sparse_classes_10k_train_002375 | 2,142 | permissive | [
{
"docstring": ":param model_bytes: Model file data, likely a loaded *.pb file :param device: The device to run the model on :param session_config: Model configuration options",
"name": "__init__",
"signature": "def __init__(self, model_bytes, device: str=None, session_config: tf.compat.v1.ConfigProto=N... | 2 | stack_v2_sparse_classes_30k_train_007049 | Implement the Python class `DepthPredictor` described below.
Class description:
Loads a model and uses it to run depth prediction, meaning that it takes an image as input and returns a matrix the size of the input image where the value of each 'pixel' corresponds to the pixel's distance from the camera in meters. Does... | Implement the Python class `DepthPredictor` described below.
Class description:
Loads a model and uses it to run depth prediction, meaning that it takes an image as input and returns a matrix the size of the input image where the value of each 'pixel' corresponds to the pixel's distance from the camera in meters. Does... | 7412902fed8f91c9c82bd42b0180e07673c38bf1 | <|skeleton|>
class DepthPredictor:
"""Loads a model and uses it to run depth prediction, meaning that it takes an image as input and returns a matrix the size of the input image where the value of each 'pixel' corresponds to the pixel's distance from the camera in meters. Does not support batch prediction TODO: Is ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DepthPredictor:
"""Loads a model and uses it to run depth prediction, meaning that it takes an image as input and returns a matrix the size of the input image where the value of each 'pixel' corresponds to the pixel's distance from the camera in meters. Does not support batch prediction TODO: Is this true?"""... | the_stack_v2_python_sparse | vcap_utils/vcap_utils/backends/depth.py | opencv/open_vision_capsules | train | 124 |
3fce6e554bc2be9ebd9b14f817c77b4e02837152 | [
"if cve is None:\n raise ValueError('CVE ID Required')\nmowCVE.__init__(self, cve=cve, **kwargs)\n'\\n self.description = kwargs.get(\"description\", None)\\n self.title = kwargs.get(\"title\", None)\\n self.cvss2 = cvss.CVSS2(kwargs.get(\"cvss2\", None))\\n self.cvss3 = cvss.CVSS3(kw... | <|body_start_0|>
if cve is None:
raise ValueError('CVE ID Required')
mowCVE.__init__(self, cve=cve, **kwargs)
'\n self.description = kwargs.get("description", None)\n self.title = kwargs.get("title", None)\n self.cvss2 = cvss.CVSS2(kwargs.get("cvss2", None))\n ... | Red Hat CVE Class that Updates mowCVE with Data from CVE | mowCVERedHat | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mowCVERedHat:
"""Red Hat CVE Class that Updates mowCVE with Data from CVE"""
def __init__(self, cve=None, **kwargs):
"""Initialze a Holder for CVE Things"""
<|body_0|>
def pull_rh_cve(self):
"""Reach out, Grab the CVE Data and Parse it"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_002376 | 6,606 | permissive | [
{
"docstring": "Initialze a Holder for CVE Things",
"name": "__init__",
"signature": "def __init__(self, cve=None, **kwargs)"
},
{
"docstring": "Reach out, Grab the CVE Data and Parse it",
"name": "pull_rh_cve",
"signature": "def pull_rh_cve(self)"
},
{
"docstring": "Takes the pa... | 3 | stack_v2_sparse_classes_30k_train_005803 | Implement the Python class `mowCVERedHat` described below.
Class description:
Red Hat CVE Class that Updates mowCVE with Data from CVE
Method signatures and docstrings:
- def __init__(self, cve=None, **kwargs): Initialze a Holder for CVE Things
- def pull_rh_cve(self): Reach out, Grab the CVE Data and Parse it
- def ... | Implement the Python class `mowCVERedHat` described below.
Class description:
Red Hat CVE Class that Updates mowCVE with Data from CVE
Method signatures and docstrings:
- def __init__(self, cve=None, **kwargs): Initialze a Holder for CVE Things
- def pull_rh_cve(self): Reach out, Grab the CVE Data and Parse it
- def ... | b9399f32950125ac7bfc48595da1c713544a1dfe | <|skeleton|>
class mowCVERedHat:
"""Red Hat CVE Class that Updates mowCVE with Data from CVE"""
def __init__(self, cve=None, **kwargs):
"""Initialze a Holder for CVE Things"""
<|body_0|>
def pull_rh_cve(self):
"""Reach out, Grab the CVE Data and Parse it"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class mowCVERedHat:
"""Red Hat CVE Class that Updates mowCVE with Data from CVE"""
def __init__(self, cve=None, **kwargs):
"""Initialze a Holder for CVE Things"""
if cve is None:
raise ValueError('CVE ID Required')
mowCVE.__init__(self, cve=cve, **kwargs)
'\n ... | the_stack_v2_python_sparse | audittools/redhat_cve.py | chalbersma/manowar | train | 3 |
5f77c5318a4541c5e746d74d3fe1d3c2d656643a | [
"email_content, receivers_email = self.generate_report(task_id=task_id)\nlogger.info('task task_id:{} has been checked out, hunter will send result to email:{}'.format(task_id, receivers_email))\nif receivers_email is not None and receivers_email.strip() != '':\n EmailUtils().send_mail_with_ssl(receivers_email, ... | <|body_start_0|>
email_content, receivers_email = self.generate_report(task_id=task_id)
logger.info('task task_id:{} has been checked out, hunter will send result to email:{}'.format(task_id, receivers_email))
if receivers_email is not None and receivers_email.strip() != '':
EmailUti... | EmailObserver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailObserver:
def notify(self, task_id):
"""发送邮件通知 :return:"""
<|body_0|>
def generate_report(self, task_id):
"""生成邮件发送报告 :param cls: :param task_id: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
email_content, receivers_email = self.gen... | stack_v2_sparse_classes_10k_train_002377 | 4,435 | permissive | [
{
"docstring": "发送邮件通知 :return:",
"name": "notify",
"signature": "def notify(self, task_id)"
},
{
"docstring": "生成邮件发送报告 :param cls: :param task_id: :return:",
"name": "generate_report",
"signature": "def generate_report(self, task_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003513 | Implement the Python class `EmailObserver` described below.
Class description:
Implement the EmailObserver class.
Method signatures and docstrings:
- def notify(self, task_id): 发送邮件通知 :return:
- def generate_report(self, task_id): 生成邮件发送报告 :param cls: :param task_id: :return: | Implement the Python class `EmailObserver` described below.
Class description:
Implement the EmailObserver class.
Method signatures and docstrings:
- def notify(self, task_id): 发送邮件通知 :return:
- def generate_report(self, task_id): 生成邮件发送报告 :param cls: :param task_id: :return:
<|skeleton|>
class EmailObserver:
d... | 4ee5cca8dc5fc5d7e631e935517bd0f493c30a37 | <|skeleton|>
class EmailObserver:
def notify(self, task_id):
"""发送邮件通知 :return:"""
<|body_0|>
def generate_report(self, task_id):
"""生成邮件发送报告 :param cls: :param task_id: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EmailObserver:
def notify(self, task_id):
"""发送邮件通知 :return:"""
email_content, receivers_email = self.generate_report(task_id=task_id)
logger.info('task task_id:{} has been checked out, hunter will send result to email:{}'.format(task_id, receivers_email))
if receivers_email is... | the_stack_v2_python_sparse | HunterCelery/notice/email_observer.py | a1kaid/hunter | train | 0 | |
40a96bfe0a1328d123da5121b4fac09389faa053 | [
"if token_cache is None:\n token_cache = JSONFileCache(self._SSO_TOKEN_CACHE_DIR)\nself._token_cache = token_cache\nif cache is None:\n cache = {}\nself.cache = cache\nself._load_config = load_config\nself._client_creator = client_creator\nself._profile_name = profile_name",
"loaded_config = self._load_conf... | <|body_start_0|>
if token_cache is None:
token_cache = JSONFileCache(self._SSO_TOKEN_CACHE_DIR)
self._token_cache = token_cache
if cache is None:
cache = {}
self.cache = cache
self._load_config = load_config
self._client_creator = client_creator
... | AWS SSO credential provider. | SSOProvider | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSOProvider:
"""AWS SSO credential provider."""
def __init__(self, load_config, client_creator, profile_name, cache=None, token_cache=None):
"""Instantiate class."""
<|body_0|>
def _load_sso_config(self):
"""Load sso config."""
<|body_1|>
def load(se... | stack_v2_sparse_classes_10k_train_002378 | 11,021 | permissive | [
{
"docstring": "Instantiate class.",
"name": "__init__",
"signature": "def __init__(self, load_config, client_creator, profile_name, cache=None, token_cache=None)"
},
{
"docstring": "Load sso config.",
"name": "_load_sso_config",
"signature": "def _load_sso_config(self)"
},
{
"do... | 3 | null | Implement the Python class `SSOProvider` described below.
Class description:
AWS SSO credential provider.
Method signatures and docstrings:
- def __init__(self, load_config, client_creator, profile_name, cache=None, token_cache=None): Instantiate class.
- def _load_sso_config(self): Load sso config.
- def load(self):... | Implement the Python class `SSOProvider` described below.
Class description:
AWS SSO credential provider.
Method signatures and docstrings:
- def __init__(self, load_config, client_creator, profile_name, cache=None, token_cache=None): Instantiate class.
- def _load_sso_config(self): Load sso config.
- def load(self):... | 0763b06aee07d2cf3f037a49ca0cb81a048c5deb | <|skeleton|>
class SSOProvider:
"""AWS SSO credential provider."""
def __init__(self, load_config, client_creator, profile_name, cache=None, token_cache=None):
"""Instantiate class."""
<|body_0|>
def _load_sso_config(self):
"""Load sso config."""
<|body_1|>
def load(se... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SSOProvider:
"""AWS SSO credential provider."""
def __init__(self, load_config, client_creator, profile_name, cache=None, token_cache=None):
"""Instantiate class."""
if token_cache is None:
token_cache = JSONFileCache(self._SSO_TOKEN_CACHE_DIR)
self._token_cache = toke... | the_stack_v2_python_sparse | runway/aws_sso_botocore/credentials.py | onicagroup/runway | train | 156 |
b1bf98d5a2673a7878b261bdf63093cff0a8f234 | [
"cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')\nres = cm.api.get_import(cluster)\nreturn Response(res)",
"cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')\nserializer = self.post_serializer(data=request.data, context={'request': request, 'cluster': cluster})\nif serializer.is_valid():... | <|body_start_0|>
cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')
res = cm.api.get_import(cluster)
return Response(res)
<|end_body_0|>
<|body_start_1|>
cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')
serializer = self.post_serializer(data=request.data,... | ClusterImport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterImport:
def get(self, request, cluster_id):
"""List all imports avaliable for specified cluster"""
<|body_0|>
def post(self, request, cluster_id):
"""Update bind for cluster"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cluster = check_obj(... | stack_v2_sparse_classes_10k_train_002379 | 32,530 | permissive | [
{
"docstring": "List all imports avaliable for specified cluster",
"name": "get",
"signature": "def get(self, request, cluster_id)"
},
{
"docstring": "Update bind for cluster",
"name": "post",
"signature": "def post(self, request, cluster_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000624 | Implement the Python class `ClusterImport` described below.
Class description:
Implement the ClusterImport class.
Method signatures and docstrings:
- def get(self, request, cluster_id): List all imports avaliable for specified cluster
- def post(self, request, cluster_id): Update bind for cluster | Implement the Python class `ClusterImport` described below.
Class description:
Implement the ClusterImport class.
Method signatures and docstrings:
- def get(self, request, cluster_id): List all imports avaliable for specified cluster
- def post(self, request, cluster_id): Update bind for cluster
<|skeleton|>
class ... | e1c67e3041437ad9e17dccc6c95c5ac02184eddb | <|skeleton|>
class ClusterImport:
def get(self, request, cluster_id):
"""List all imports avaliable for specified cluster"""
<|body_0|>
def post(self, request, cluster_id):
"""Update bind for cluster"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClusterImport:
def get(self, request, cluster_id):
"""List all imports avaliable for specified cluster"""
cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')
res = cm.api.get_import(cluster)
return Response(res)
def post(self, request, cluster_id):
"""Upd... | the_stack_v2_python_sparse | api/cluster_views.py | amleshkov/adcm | train | 0 | |
77757e8284e30c20656b352b994b57920eb5479f | [
"self.cache = {}\nself.frequency = collections.defaultdict(list)\nself.capacity = capacity",
"if key not in self.cache:\n return -1\nfor freq in self.frequency:\n if key in self.frequency[freq]:\n self.frequency[freq].remove(key)\n if not self.frequency[freq]:\n self.frequency.pop(f... | <|body_start_0|>
self.cache = {}
self.frequency = collections.defaultdict(list)
self.capacity = capacity
<|end_body_0|>
<|body_start_1|>
if key not in self.cache:
return -1
for freq in self.frequency:
if key in self.frequency[freq]:
self.f... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k_train_002380 | 1,356 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_000680 | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 2fe336e0de336f6d5f67b058ddb5cf50c9f00d4e | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.cache = {}
self.frequency = collections.defaultdict(list)
self.capacity = capacity
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.cache:
return -1
... | the_stack_v2_python_sparse | c++/460. LFU Cache.py | rhzx3519/leetcode | train | 3 | |
f1d07364d9b62b14c520ec4de393d84ae86fe86d | [
"total_sum = sum(nums)\nif total_sum % 2 != 0:\n return False\nsub_set_sum = total_sum // 2\ndp = [False] * (sub_set_sum + 1)\ndp[0] = True\nfor num in nums:\n for j in range(sub_set_sum, num - 1, -1):\n dp[j] = dp[j] or dp[j - num]\nreturn dp[sub_set_sum]",
"total_sum = sum(nums)\nif total_sum % 2 !... | <|body_start_0|>
total_sum = sum(nums)
if total_sum % 2 != 0:
return False
sub_set_sum = total_sum // 2
dp = [False] * (sub_set_sum + 1)
dp[0] = True
for num in nums:
for j in range(sub_set_sum, num - 1, -1):
dp[j] = dp[j] or dp[j -... | Array | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Array:
def can_partition(self, nums: List[int]) -> bool:
"""Approach: DP (1D Array) Time Complexity: O(m * n) Space Complexity: O(m) :param nums: :return:"""
<|body_0|>
def can_partition_(self, nums: List[int]) -> bool:
"""Approach: DP (2D Array) Time Complexity: O(m... | stack_v2_sparse_classes_10k_train_002381 | 1,709 | no_license | [
{
"docstring": "Approach: DP (1D Array) Time Complexity: O(m * n) Space Complexity: O(m) :param nums: :return:",
"name": "can_partition",
"signature": "def can_partition(self, nums: List[int]) -> bool"
},
{
"docstring": "Approach: DP (2D Array) Time Complexity: O(m * n) Space Complexity: O(m * n... | 2 | null | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def can_partition(self, nums: List[int]) -> bool: Approach: DP (1D Array) Time Complexity: O(m * n) Space Complexity: O(m) :param nums: :return:
- def can_partition_(self, nums: List[i... | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def can_partition(self, nums: List[int]) -> bool: Approach: DP (1D Array) Time Complexity: O(m * n) Space Complexity: O(m) :param nums: :return:
- def can_partition_(self, nums: List[i... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Array:
def can_partition(self, nums: List[int]) -> bool:
"""Approach: DP (1D Array) Time Complexity: O(m * n) Space Complexity: O(m) :param nums: :return:"""
<|body_0|>
def can_partition_(self, nums: List[int]) -> bool:
"""Approach: DP (2D Array) Time Complexity: O(m... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Array:
def can_partition(self, nums: List[int]) -> bool:
"""Approach: DP (1D Array) Time Complexity: O(m * n) Space Complexity: O(m) :param nums: :return:"""
total_sum = sum(nums)
if total_sum % 2 != 0:
return False
sub_set_sum = total_sum // 2
dp = [False] ... | the_stack_v2_python_sparse | revisited_2021/dp/partition_equal_subset_sum.py | Shiv2157k/leet_code | train | 1 | |
9927888e9df972509a201241abfe195fb7e16430 | [
"assert len(sizes) == 2, 'SSD requires sizes to be (size_min, size_max)'\nanchors = []\nfor i in range(alloc_size[0]):\n for j in range(alloc_size[1]):\n cy = (i + offsets[0]) * step\n cx = (j + offsets[1]) * step\n r = ratios[0]\n anchors.append([cx, cy, sizes[0] / 2, sizes[0] / 2])\... | <|body_start_0|>
assert len(sizes) == 2, 'SSD requires sizes to be (size_min, size_max)'
anchors = []
for i in range(alloc_size[0]):
for j in range(alloc_size[1]):
cy = (i + offsets[0]) * step
cx = (j + offsets[1]) * step
r = ratios[0]
... | Bounding box anchor generator for Single-shot Object Detection, corresponding to anchors structure used in ssd_mobilenet_v1_coco from TF Object Detection API This class inherits SSDAnchorGenerator and uses the same input parameters. Main differences: - First branch is not added with another anchor with size extracted f... | LiteAnchorGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LiteAnchorGenerator:
"""Bounding box anchor generator for Single-shot Object Detection, corresponding to anchors structure used in ssd_mobilenet_v1_coco from TF Object Detection API This class inherits SSDAnchorGenerator and uses the same input parameters. Main differences: - First branch is not ... | stack_v2_sparse_classes_10k_train_002382 | 5,184 | permissive | [
{
"docstring": "Generate anchors for once. Anchors are stored with (center_x, center_y, w, h) format.",
"name": "_generate_anchors",
"signature": "def _generate_anchors(self, sizes, ratios, step, alloc_size, offsets)"
},
{
"docstring": "Number of anchors at each pixel.",
"name": "num_depth",... | 2 | stack_v2_sparse_classes_30k_train_000089 | Implement the Python class `LiteAnchorGenerator` described below.
Class description:
Bounding box anchor generator for Single-shot Object Detection, corresponding to anchors structure used in ssd_mobilenet_v1_coco from TF Object Detection API This class inherits SSDAnchorGenerator and uses the same input parameters. M... | Implement the Python class `LiteAnchorGenerator` described below.
Class description:
Bounding box anchor generator for Single-shot Object Detection, corresponding to anchors structure used in ssd_mobilenet_v1_coco from TF Object Detection API This class inherits SSDAnchorGenerator and uses the same input parameters. M... | 567775619f3b97d47e7c360748912a4fd883ff52 | <|skeleton|>
class LiteAnchorGenerator:
"""Bounding box anchor generator for Single-shot Object Detection, corresponding to anchors structure used in ssd_mobilenet_v1_coco from TF Object Detection API This class inherits SSDAnchorGenerator and uses the same input parameters. Main differences: - First branch is not ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LiteAnchorGenerator:
"""Bounding box anchor generator for Single-shot Object Detection, corresponding to anchors structure used in ssd_mobilenet_v1_coco from TF Object Detection API This class inherits SSDAnchorGenerator and uses the same input parameters. Main differences: - First branch is not added with an... | the_stack_v2_python_sparse | gluoncv/model_zoo/ssd/anchor.py | dmlc/gluon-cv | train | 6,064 |
e061b8e09f6649ed13e439ca3980e9eda94f5946 | [
"endpoint = 'show version '\nPARSER = 'raw/showEdgeVersion'\nEXPECT_PROMPT = ['bytes*', 'NSXEdge>']\nmapped_pydict = utilities.get_mapped_pydict_for_expect(client_object.connection, endpoint, PARSER, EXPECT_PROMPT, ' ')\nclient_object.connection.close()\nget_edge_version_schema_object = show_edge_version_schema.Sho... | <|body_start_0|>
endpoint = 'show version '
PARSER = 'raw/showEdgeVersion'
EXPECT_PROMPT = ['bytes*', 'NSXEdge>']
mapped_pydict = utilities.get_mapped_pydict_for_expect(client_object.connection, endpoint, PARSER, EXPECT_PROMPT, ' ')
client_object.connection.close()
get_ed... | Edge70OSImpl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Edge70OSImpl:
def get_os_info(cls, client_object, **kwargs):
"""Returns the Kernel version, Build number, Name and Version information for given NSX edge NSXEdge>show version ... Name: NSX Edge ... Version: 7.0.0.0.0 ... Build Number: 2252106 ... Kernel: 3.2.62"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_002383 | 8,973 | no_license | [
{
"docstring": "Returns the Kernel version, Build number, Name and Version information for given NSX edge NSXEdge>show version ... Name: NSX Edge ... Version: 7.0.0.0.0 ... Build Number: 2252106 ... Kernel: 3.2.62",
"name": "get_os_info",
"signature": "def get_os_info(cls, client_object, **kwargs)"
},... | 5 | stack_v2_sparse_classes_30k_test_000281 | Implement the Python class `Edge70OSImpl` described below.
Class description:
Implement the Edge70OSImpl class.
Method signatures and docstrings:
- def get_os_info(cls, client_object, **kwargs): Returns the Kernel version, Build number, Name and Version information for given NSX edge NSXEdge>show version ... Name: NS... | Implement the Python class `Edge70OSImpl` described below.
Class description:
Implement the Edge70OSImpl class.
Method signatures and docstrings:
- def get_os_info(cls, client_object, **kwargs): Returns the Kernel version, Build number, Name and Version information for given NSX edge NSXEdge>show version ... Name: NS... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class Edge70OSImpl:
def get_os_info(cls, client_object, **kwargs):
"""Returns the Kernel version, Build number, Name and Version information for given NSX edge NSXEdge>show version ... Name: NSX Edge ... Version: 7.0.0.0.0 ... Build Number: 2252106 ... Kernel: 3.2.62"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Edge70OSImpl:
def get_os_info(cls, client_object, **kwargs):
"""Returns the Kernel version, Build number, Name and Version information for given NSX edge NSXEdge>show version ... Name: NSX Edge ... Version: 7.0.0.0.0 ... Build Number: 2252106 ... Kernel: 3.2.62"""
endpoint = 'show version '
... | the_stack_v2_python_sparse | SystemTesting/pylib/vmware/nsx/edge/cli/edge70_os_impl.py | Cloudxtreme/MyProject | train | 0 | |
bd0f1abfcf830758fb58ba5e12d93d44f79d7085 | [
"super(Encoder, self).__init__()\nself.layers = clones(layer, N)\nself.norm = LayerNorm(layer.size)\nself.position = position",
"if self.position:\n x = self.position(x, mask, indices)\nmask = mask.unsqueeze(-2)\nfor layer in self.layers:\n x = layer(x, mask)\nreturn self.norm(x)"
] | <|body_start_0|>
super(Encoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
self.position = position
<|end_body_0|>
<|body_start_1|>
if self.position:
x = self.position(x, mask, indices)
mask = mask.unsqueeze(-2)
... | Stack of Transformer encoder blocks with positional encoding. | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Stack of Transformer encoder blocks with positional encoding."""
def __init__(self, layer, N, position):
""":param layer: single building block to clone :param N: number of copies :param position: positional encoding module"""
<|body_0|>
def forward(self, x, ... | stack_v2_sparse_classes_10k_train_002384 | 21,238 | no_license | [
{
"docstring": ":param layer: single building block to clone :param N: number of copies :param position: positional encoding module",
"name": "__init__",
"signature": "def __init__(self, layer, N, position)"
},
{
"docstring": "Forward pass through each block of the Transformer. :param x: input o... | 2 | null | Implement the Python class `Encoder` described below.
Class description:
Stack of Transformer encoder blocks with positional encoding.
Method signatures and docstrings:
- def __init__(self, layer, N, position): :param layer: single building block to clone :param N: number of copies :param position: positional encodin... | Implement the Python class `Encoder` described below.
Class description:
Stack of Transformer encoder blocks with positional encoding.
Method signatures and docstrings:
- def __init__(self, layer, N, position): :param layer: single building block to clone :param N: number of copies :param position: positional encodin... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Encoder:
"""Stack of Transformer encoder blocks with positional encoding."""
def __init__(self, layer, N, position):
""":param layer: single building block to clone :param N: number of copies :param position: positional encoding module"""
<|body_0|>
def forward(self, x, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Encoder:
"""Stack of Transformer encoder blocks with positional encoding."""
def __init__(self, layer, N, position):
""":param layer: single building block to clone :param N: number of copies :param position: positional encoding module"""
super(Encoder, self).__init__()
self.layer... | the_stack_v2_python_sparse | generated/test_allegro_allRank.py | jansel/pytorch-jit-paritybench | train | 35 |
334839b5ccb98cd07b5b6540cb19f92b130228f6 | [
"def insert(target):\n left, right = (0, len(res) - 1)\n while left <= right:\n mid = left + (right - left) / 2\n if res[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n if left == len(res):\n res.append(target)\n else:\n res[left] = ta... | <|body_start_0|>
def insert(target):
left, right = (0, len(res) - 1)
while left <= right:
mid = left + (right - left) / 2
if res[mid] < target:
left = mid + 1
else:
right = mid - 1
if left... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_0|>
def maxEnvelopes2(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def insert... | stack_v2_sparse_classes_10k_train_002385 | 3,342 | no_license | [
{
"docstring": ":type envelopes: List[List[int]] :rtype: int",
"name": "maxEnvelopes",
"signature": "def maxEnvelopes(self, envelopes)"
},
{
"docstring": ":type envelopes: List[List[int]] :rtype: int",
"name": "maxEnvelopes2",
"signature": "def maxEnvelopes2(self, envelopes)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int
- def maxEnvelopes2(self, envelopes): :type envelopes: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int
- def maxEnvelopes2(self, envelopes): :type envelopes: List[List[int]] :rtype: int
<|skeleton|>
c... | 340ae58fb65b97aa6c6ab2daa8cbd82d1093deae | <|skeleton|>
class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_0|>
def maxEnvelopes2(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
def insert(target):
left, right = (0, len(res) - 1)
while left <= right:
mid = left + (right - left) / 2
if res[mid] < target:
... | the_stack_v2_python_sparse | learnpythonthehardway/russian-doll-envelopes-354.py | dgpllc/leetcode-python | train | 0 | |
b43cb61973a4e9d90321c6d69200533dabaacdcb | [
"if not root:\n return ''\npreOrderList = []\n\ndef preOrder(node):\n if not node:\n preOrderList.append('#')\n return\n preOrderList.append(node.val)\n preOrder(node.left)\n preOrder(node.right)\npreOrder(root)\nreturn ' '.join(map(str, preOrderList))",
"if not data:\n return None... | <|body_start_0|>
if not root:
return ''
preOrderList = []
def preOrder(node):
if not node:
preOrderList.append('#')
return
preOrderList.append(node.val)
preOrder(node.left)
preOrder(node.right)
p... | 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_002386 | 2,238 | 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:... | 63ac5a0921835b1e9d65f71e1346bbb7d66dad9b | <|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 ''
preOrderList = []
def preOrder(node):
if not node:
preOrderList.append('#')
return
... | the_stack_v2_python_sparse | LeetCode/困难/树/297. 二叉树的序列化与反序列化.py | homezzm/leetcode | train | 1 | |
260e8b84b1e48c39c0961a5ee70432922e837ae5 | [
"super().__init__(master, **options)\nself.pack()\nself._player_info = player_info\nself._selected_color_bgr = StringVar(self, '顏色未定')\nself._selected_color_bgr.trace('w', self._update_player_color)\nself._previous_selected_color_bgr = self._selected_color_bgr.get()\nself._setup_layout(color_list)",
"color_label ... | <|body_start_0|>
super().__init__(master, **options)
self.pack()
self._player_info = player_info
self._selected_color_bgr = StringVar(self, '顏色未定')
self._selected_color_bgr.trace('w', self._update_player_color)
self._previous_selected_color_bgr = self._selected_color_bgr.... | The widget for setting and displaying BasicPlayerInfo or its derived class Usage: ``` playerInfoWidget = PlayerInfoWidget(...) playerInfoWidget.pack() playerInfoWidget.refresh() # To reflect the changes in BasicPlayerInfo ``` @var _player_info The object of BasicPlayerInfo or its derived class that binds to this widget... | BasicPlayerInfoWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicPlayerInfoWidget:
"""The widget for setting and displaying BasicPlayerInfo or its derived class Usage: ``` playerInfoWidget = PlayerInfoWidget(...) playerInfoWidget.pack() playerInfoWidget.refresh() # To reflect the changes in BasicPlayerInfo ``` @var _player_info The object of BasicPlayerIn... | stack_v2_sparse_classes_10k_train_002387 | 8,055 | no_license | [
{
"docstring": "Constructor Constructor will invoke BasicPlayerInfoWidget._setup_layout() to setup its layout. @param master Specify he parent widget @param player_info Specify the target player information to be shwon @param color_list Specify he selectable color for this player. It will be a list of string re... | 5 | stack_v2_sparse_classes_30k_train_006729 | Implement the Python class `BasicPlayerInfoWidget` described below.
Class description:
The widget for setting and displaying BasicPlayerInfo or its derived class Usage: ``` playerInfoWidget = PlayerInfoWidget(...) playerInfoWidget.pack() playerInfoWidget.refresh() # To reflect the changes in BasicPlayerInfo ``` @var _... | Implement the Python class `BasicPlayerInfoWidget` described below.
Class description:
The widget for setting and displaying BasicPlayerInfo or its derived class Usage: ``` playerInfoWidget = PlayerInfoWidget(...) playerInfoWidget.pack() playerInfoWidget.refresh() # To reflect the changes in BasicPlayerInfo ``` @var _... | dc695322095b2eae4527fcdd33cf6304fbf39600 | <|skeleton|>
class BasicPlayerInfoWidget:
"""The widget for setting and displaying BasicPlayerInfo or its derived class Usage: ``` playerInfoWidget = PlayerInfoWidget(...) playerInfoWidget.pack() playerInfoWidget.refresh() # To reflect the changes in BasicPlayerInfo ``` @var _player_info The object of BasicPlayerIn... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BasicPlayerInfoWidget:
"""The widget for setting and displaying BasicPlayerInfo or its derived class Usage: ``` playerInfoWidget = PlayerInfoWidget(...) playerInfoWidget.pack() playerInfoWidget.refresh() # To reflect the changes in BasicPlayerInfo ``` @var _player_info The object of BasicPlayerInfo or its der... | the_stack_v2_python_sparse | game_essential/game_widgets.py | LanKuDot/MazeArena-Console | train | 0 |
599ac5d70a03e18ea6841a4f40fd20fa0ac1ebe1 | [
"if len(data['changes']):\n if not isinstance(to, (list, set)):\n to = [to]\n if len(to) > 0:\n with transaction.atomic():\n message = Message()\n message.create_message_from_template(template_name=template_name, data=data)\n message.save()\n message.s... | <|body_start_0|>
if len(data['changes']):
if not isinstance(to, (list, set)):
to = [to]
if len(to) > 0:
with transaction.atomic():
message = Message()
message.create_message_from_template(template_name=template_name,... | Миксин для оповещения пользователя, что модератор исправил/изменил материал | MixinSaveModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixinSaveModel:
"""Миксин для оповещения пользователя, что модератор исправил/изменил материал"""
def _send_private_message(template_name, data, to):
"""Формирование автоматического уведомления с указанием измененных полей"""
<|body_0|>
def save_model(self, request, obj,... | stack_v2_sparse_classes_10k_train_002388 | 5,107 | no_license | [
{
"docstring": "Формирование автоматического уведомления с указанием измененных полей",
"name": "_send_private_message",
"signature": "def _send_private_message(template_name, data, to)"
},
{
"docstring": "Метод вызывается при сохранении материала из админки. При изменении полей формирует данные... | 2 | stack_v2_sparse_classes_30k_train_003564 | Implement the Python class `MixinSaveModel` described below.
Class description:
Миксин для оповещения пользователя, что модератор исправил/изменил материал
Method signatures and docstrings:
- def _send_private_message(template_name, data, to): Формирование автоматического уведомления с указанием измененных полей
- de... | Implement the Python class `MixinSaveModel` described below.
Class description:
Миксин для оповещения пользователя, что модератор исправил/изменил материал
Method signatures and docstrings:
- def _send_private_message(template_name, data, to): Формирование автоматического уведомления с указанием измененных полей
- de... | 9c46e756e285fba9853dad6c510b1f87968a7092 | <|skeleton|>
class MixinSaveModel:
"""Миксин для оповещения пользователя, что модератор исправил/изменил материал"""
def _send_private_message(template_name, data, to):
"""Формирование автоматического уведомления с указанием измененных полей"""
<|body_0|>
def save_model(self, request, obj,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MixinSaveModel:
"""Миксин для оповещения пользователя, что модератор исправил/изменил материал"""
def _send_private_message(template_name, data, to):
"""Формирование автоматического уведомления с указанием измененных полей"""
if len(data['changes']):
if not isinstance(to, (lis... | the_stack_v2_python_sparse | main/admin.py | thewebcat/livecamsbay | train | 1 |
da0c4e1077bf059179a43f5ee32eeaa020ff1e03 | [
"steps = dict()\n\ndef dfs(root, step):\n if root is None:\n return\n if step not in steps:\n steps[step] = root.val\n else:\n steps[step] = max(steps[step], root.val)\n if root.left:\n dfs(root.left, step + 1)\n if root.right:\n dfs(root.right, step + 1)\ndfs(root,... | <|body_start_0|>
steps = dict()
def dfs(root, step):
if root is None:
return
if step not in steps:
steps[step] = root.val
else:
steps[step] = max(steps[step], root.val)
if root.left:
dfs(root... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestValues(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def largestValuesBFS(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
steps = dict()
def ... | stack_v2_sparse_classes_10k_train_002389 | 1,886 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "largestValues",
"signature": "def largestValues(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "largestValuesBFS",
"signature": "def largestValuesBFS(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002400 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestValues(self, root): :type root: TreeNode :rtype: List[int]
- def largestValuesBFS(self, root): :type root: TreeNode :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestValues(self, root): :type root: TreeNode :rtype: List[int]
- def largestValuesBFS(self, root): :type root: TreeNode :rtype: List[int]
<|skeleton|>
class Solution:
... | 1520e1e9bb0c428797a3e5234e5b328110472c20 | <|skeleton|>
class Solution:
def largestValues(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def largestValuesBFS(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def largestValues(self, root):
""":type root: TreeNode :rtype: List[int]"""
steps = dict()
def dfs(root, step):
if root is None:
return
if step not in steps:
steps[step] = root.val
else:
step... | the_stack_v2_python_sparse | Depth-first Search/515. Find Largest Value in Each Tree Row.py | tinkle1129/Leetcode_Solution | train | 0 | |
3597588e3098aa04ef38b3a65fa995ed19282795 | [
"if not nums2 or not nums1:\n return []\nheap = []\nret = []\nheappush(heap, [nums1[0] + nums2[0], 0, 0])\nwhile len(ret) < k and heap:\n min_of_cur = heappop(heap)\n _, i, j = min_of_cur\n ret.append([nums1[i], nums2[j]])\n if j + 1 < len(nums2):\n heappush(heap, [nums1[i] + nums2[j + 1], i, ... | <|body_start_0|>
if not nums2 or not nums1:
return []
heap = []
ret = []
heappush(heap, [nums1[0] + nums2[0], 0, 0])
while len(ret) < k and heap:
min_of_cur = heappop(heap)
_, i, j = min_of_cur
ret.append([nums1[i], nums2[j]])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
<|body_0|>
def kSmallestPairs3(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: ... | stack_v2_sparse_classes_10k_train_002390 | 3,335 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]",
"name": "kSmallestPairs",
"signature": "def kSmallestPairs(self, nums1, nums2, k)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]",
"nam... | 4 | stack_v2_sparse_classes_30k_train_005827 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kSmallestPairs(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]
- def kSmallestPairs3(self, nums1, nums2, k): :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kSmallestPairs(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]
- def kSmallestPairs3(self, nums1, nums2, k): :type ... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
<|body_0|>
def kSmallestPairs3(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
if not nums2 or not nums1:
return []
heap = []
ret = []
heappush(heap, [nums1[0] + nums2[0], 0, 0])
while le... | the_stack_v2_python_sparse | python/leetcode/373_Find_K_Pairs_with_Smallest_Sums.py | bobcaoge/my-code | train | 0 | |
abe7cfd8d0733d37bcc78cbca32ae742cf4e858f | [
"if UserProfile.objects.filter(username=username):\n raise serializers.ValidationError(username + ' 账号已存在')\nreturn username",
"REGEX_MOBILE = '^1[358]\\\\d{9}$|^147\\\\d{8}$|^176\\\\d{8}$'\nif not re.match(REGEX_MOBILE, mobile):\n raise serializers.ValidationError('手机号码不合法')\nif UserProfile.objects.filter(... | <|body_start_0|>
if UserProfile.objects.filter(username=username):
raise serializers.ValidationError(username + ' 账号已存在')
return username
<|end_body_0|>
<|body_start_1|>
REGEX_MOBILE = '^1[358]\\d{9}$|^147\\d{8}$|^176\\d{8}$'
if not re.match(REGEX_MOBILE, mobile):
... | 创建用户序列化 | UserCreateSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCreateSerializer:
"""创建用户序列化"""
def validate_username(self, username):
"""校验用户名是否存在 :param username: :return:"""
<|body_0|>
def validate_mobile(self, mobile):
"""校验手机号是否合法、是否已被注册 :param mobile: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_10k_train_002391 | 3,031 | no_license | [
{
"docstring": "校验用户名是否存在 :param username: :return:",
"name": "validate_username",
"signature": "def validate_username(self, username)"
},
{
"docstring": "校验手机号是否合法、是否已被注册 :param mobile: :return:",
"name": "validate_mobile",
"signature": "def validate_mobile(self, mobile)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005025 | Implement the Python class `UserCreateSerializer` described below.
Class description:
创建用户序列化
Method signatures and docstrings:
- def validate_username(self, username): 校验用户名是否存在 :param username: :return:
- def validate_mobile(self, mobile): 校验手机号是否合法、是否已被注册 :param mobile: :return: | Implement the Python class `UserCreateSerializer` described below.
Class description:
创建用户序列化
Method signatures and docstrings:
- def validate_username(self, username): 校验用户名是否存在 :param username: :return:
- def validate_mobile(self, mobile): 校验手机号是否合法、是否已被注册 :param mobile: :return:
<|skeleton|>
class UserCreateSeria... | db1d7c4eb2d5d229ab54c6d5775f96fc1843716e | <|skeleton|>
class UserCreateSerializer:
"""创建用户序列化"""
def validate_username(self, username):
"""校验用户名是否存在 :param username: :return:"""
<|body_0|>
def validate_mobile(self, mobile):
"""校验手机号是否合法、是否已被注册 :param mobile: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserCreateSerializer:
"""创建用户序列化"""
def validate_username(self, username):
"""校验用户名是否存在 :param username: :return:"""
if UserProfile.objects.filter(username=username):
raise serializers.ValidationError(username + ' 账号已存在')
return username
def validate_mobile(self, ... | the_stack_v2_python_sparse | apps/rbac/serializers/user_serializer.py | fengjy96/rest_task | train | 0 |
b551968c9de039248ef33a8d7247a2552d8bef8d | [
"assert is_unwrappable_to(env, DiscreteEnv)\nassert is_unwrappable_to(env, FeatureWrapper)\nsuper(MaxEntIRL, self).__init__(env, expert_trajs, rl_alg_factory, metrics, config)\nself.transition_matrix = get_transition_matrix(self.env)\nself.n_states, self.n_actions, _ = self.transition_matrix.shape\nfeature_wrapper ... | <|body_start_0|>
assert is_unwrappable_to(env, DiscreteEnv)
assert is_unwrappable_to(env, FeatureWrapper)
super(MaxEntIRL, self).__init__(env, expert_trajs, rl_alg_factory, metrics, config)
self.transition_matrix = get_transition_matrix(self.env)
self.n_states, self.n_actions, _ ... | Maximum Entropy IRL (Ziebart et al., 2008). Not to be confused with Maximum Entropy Deep IRL (Wulfmeier et al., 2016) or Maximum Causal Entropy IRL (Ziebart et al., 2010). | MaxEntIRL | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxEntIRL:
"""Maximum Entropy IRL (Ziebart et al., 2008). Not to be confused with Maximum Entropy Deep IRL (Wulfmeier et al., 2016) or Maximum Causal Entropy IRL (Ziebart et al., 2010)."""
def __init__(self, env: gym.Env, expert_trajs: List[Dict[str, list]], rl_alg_factory: Callable[[gym.Env... | stack_v2_sparse_classes_10k_train_002392 | 5,210 | no_license | [
{
"docstring": "See :class:`irl_benchmark.irl.algorithms.base_algorithm.BaseIRLAlgorithm`.",
"name": "__init__",
"signature": "def __init__(self, env: gym.Env, expert_trajs: List[Dict[str, list]], rl_alg_factory: Callable[[gym.Env], BaseRLAlgorithm], metrics: List[BaseMetric], config: dict)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_003305 | Implement the Python class `MaxEntIRL` described below.
Class description:
Maximum Entropy IRL (Ziebart et al., 2008). Not to be confused with Maximum Entropy Deep IRL (Wulfmeier et al., 2016) or Maximum Causal Entropy IRL (Ziebart et al., 2010).
Method signatures and docstrings:
- def __init__(self, env: gym.Env, ex... | Implement the Python class `MaxEntIRL` described below.
Class description:
Maximum Entropy IRL (Ziebart et al., 2008). Not to be confused with Maximum Entropy Deep IRL (Wulfmeier et al., 2016) or Maximum Causal Entropy IRL (Ziebart et al., 2010).
Method signatures and docstrings:
- def __init__(self, env: gym.Env, ex... | 8dbf62c79a106e460a542c4008903aec8ec472c6 | <|skeleton|>
class MaxEntIRL:
"""Maximum Entropy IRL (Ziebart et al., 2008). Not to be confused with Maximum Entropy Deep IRL (Wulfmeier et al., 2016) or Maximum Causal Entropy IRL (Ziebart et al., 2010)."""
def __init__(self, env: gym.Env, expert_trajs: List[Dict[str, list]], rl_alg_factory: Callable[[gym.Env... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MaxEntIRL:
"""Maximum Entropy IRL (Ziebart et al., 2008). Not to be confused with Maximum Entropy Deep IRL (Wulfmeier et al., 2016) or Maximum Causal Entropy IRL (Ziebart et al., 2010)."""
def __init__(self, env: gym.Env, expert_trajs: List[Dict[str, list]], rl_alg_factory: Callable[[gym.Env], BaseRLAlgo... | the_stack_v2_python_sparse | irl_benchmark/irl/algorithms/me_irl.py | dit7ya/irl-benchmark-1 | train | 0 |
ae929564c0ee8bb868cd44fc714185f8709db7ad | [
"if not 'image' in data:\n data['image'] = 'images/no_image.png'\nreturn data",
"group = self.Meta.model(**validated_data)\ngroup.save()\nauthor = validated_data['author']\ngroup.members.add(author)\nreturn group"
] | <|body_start_0|>
if not 'image' in data:
data['image'] = 'images/no_image.png'
return data
<|end_body_0|>
<|body_start_1|>
group = self.Meta.model(**validated_data)
group.save()
author = validated_data['author']
group.members.add(author)
return group
... | GroupRegisterSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupRegisterSerializer:
def validate(self, data):
"""Checks to be sure that the received password and confirm_password fields are exactly the same"""
<|body_0|>
def create(self, validated_data):
"""Creates the user if validation succeeds"""
<|body_1|>
<|end... | stack_v2_sparse_classes_10k_train_002393 | 6,287 | no_license | [
{
"docstring": "Checks to be sure that the received password and confirm_password fields are exactly the same",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Creates the user if validation succeeds",
"name": "create",
"signature": "def create(self, valida... | 2 | stack_v2_sparse_classes_30k_train_006503 | Implement the Python class `GroupRegisterSerializer` described below.
Class description:
Implement the GroupRegisterSerializer class.
Method signatures and docstrings:
- def validate(self, data): Checks to be sure that the received password and confirm_password fields are exactly the same
- def create(self, validated... | Implement the Python class `GroupRegisterSerializer` described below.
Class description:
Implement the GroupRegisterSerializer class.
Method signatures and docstrings:
- def validate(self, data): Checks to be sure that the received password and confirm_password fields are exactly the same
- def create(self, validated... | db7582b75f1a3dea4468749912cccd15c9341436 | <|skeleton|>
class GroupRegisterSerializer:
def validate(self, data):
"""Checks to be sure that the received password and confirm_password fields are exactly the same"""
<|body_0|>
def create(self, validated_data):
"""Creates the user if validation succeeds"""
<|body_1|>
<|end... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GroupRegisterSerializer:
def validate(self, data):
"""Checks to be sure that the received password and confirm_password fields are exactly the same"""
if not 'image' in data:
data['image'] = 'images/no_image.png'
return data
def create(self, validated_data):
""... | the_stack_v2_python_sparse | django_app/group/serializer/group.py | jmnghn/chming | train | 0 | |
daf7ce02d1a3d3a275d7e2a771f708388619e0df | [
"self.log.info('login from QQ')\ncode = context.get('code')\nredirect_uri = context.get('redirect_uri')\nif not code or not redirect_uri:\n return None\naccess_token = self.get_token(code, redirect_uri)\ninfo = self.get_info(access_token)\nuser_info = self.get_user_info(access_token, info['openid'], info['client... | <|body_start_0|>
self.log.info('login from QQ')
code = context.get('code')
redirect_uri = context.get('redirect_uri')
if not code or not redirect_uri:
return None
access_token = self.get_token(code, redirect_uri)
info = self.get_info(access_token)
user... | Sign in with QQ :Example: from client.user.login import QQLogin QQLogin() .. notes:: | QQLogin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QQLogin:
"""Sign in with QQ :Example: from client.user.login import QQLogin QQLogin() .. notes::"""
def login(self, context):
"""QQ Login :type context: Context :param context: :rtype: dict :return: token and instance of user"""
<|body_0|>
def get_token(self, code, redir... | stack_v2_sparse_classes_10k_train_002394 | 17,886 | permissive | [
{
"docstring": "QQ Login :type context: Context :param context: :rtype: dict :return: token and instance of user",
"name": "login",
"signature": "def login(self, context)"
},
{
"docstring": "Get qq access token :type code: str :param code: authorization code :type redirect_uri: str :param redire... | 4 | stack_v2_sparse_classes_30k_train_001970 | Implement the Python class `QQLogin` described below.
Class description:
Sign in with QQ :Example: from client.user.login import QQLogin QQLogin() .. notes::
Method signatures and docstrings:
- def login(self, context): QQ Login :type context: Context :param context: :rtype: dict :return: token and instance of user
-... | Implement the Python class `QQLogin` described below.
Class description:
Sign in with QQ :Example: from client.user.login import QQLogin QQLogin() .. notes::
Method signatures and docstrings:
- def login(self, context): QQ Login :type context: Context :param context: :rtype: dict :return: token and instance of user
-... | 945c4fd2755f5b0dea11e54eb649eeb37ec93d01 | <|skeleton|>
class QQLogin:
"""Sign in with QQ :Example: from client.user.login import QQLogin QQLogin() .. notes::"""
def login(self, context):
"""QQ Login :type context: Context :param context: :rtype: dict :return: token and instance of user"""
<|body_0|>
def get_token(self, code, redir... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QQLogin:
"""Sign in with QQ :Example: from client.user.login import QQLogin QQLogin() .. notes::"""
def login(self, context):
"""QQ Login :type context: Context :param context: :rtype: dict :return: token and instance of user"""
self.log.info('login from QQ')
code = context.get('c... | the_stack_v2_python_sparse | open-hackathon-server/src/hackathon/user/oauth_login.py | kaiyuanshe/open-hackathon | train | 46 |
79f1f9403e408b557a41330ebb7d2d08d8b3f800 | [
"try:\n self.assertEqual(subtract(30, 16), 15)\nexcept Exception as error:\n print(f'Got error in {inspect.stack()[0][3]}, {error}')",
"try:\n self.assertEqual(subtract(-18, -5), -13)\nexcept Exception as error:\n print(error)",
"try:\n self.assertEqual(subtract(0, -6), 7)\nexcept Exception as er... | <|body_start_0|>
try:
self.assertEqual(subtract(30, 16), 15)
except Exception as error:
print(f'Got error in {inspect.stack()[0][3]}, {error}')
<|end_body_0|>
<|body_start_1|>
try:
self.assertEqual(subtract(-18, -5), -13)
except Exception as error:
... | Test subtract function from calculation.py module. | TestSubtractFunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSubtractFunction:
"""Test subtract function from calculation.py module."""
def test_subtract_all_args_greater_zero(self):
"""Test subtract function if all arguments are greater than zero."""
<|body_0|>
def test_subtract_all_args_less_zero(self):
"""Test subtr... | stack_v2_sparse_classes_10k_train_002395 | 1,838 | no_license | [
{
"docstring": "Test subtract function if all arguments are greater than zero.",
"name": "test_subtract_all_args_greater_zero",
"signature": "def test_subtract_all_args_greater_zero(self)"
},
{
"docstring": "Test subtract function if all arguments are less than zero.",
"name": "test_subtract... | 3 | stack_v2_sparse_classes_30k_test_000072 | Implement the Python class `TestSubtractFunction` described below.
Class description:
Test subtract function from calculation.py module.
Method signatures and docstrings:
- def test_subtract_all_args_greater_zero(self): Test subtract function if all arguments are greater than zero.
- def test_subtract_all_args_less_z... | Implement the Python class `TestSubtractFunction` described below.
Class description:
Test subtract function from calculation.py module.
Method signatures and docstrings:
- def test_subtract_all_args_greater_zero(self): Test subtract function if all arguments are greater than zero.
- def test_subtract_all_args_less_z... | 3a500c9d55fecf4032b5faf59a1cbecf64592e9a | <|skeleton|>
class TestSubtractFunction:
"""Test subtract function from calculation.py module."""
def test_subtract_all_args_greater_zero(self):
"""Test subtract function if all arguments are greater than zero."""
<|body_0|>
def test_subtract_all_args_less_zero(self):
"""Test subtr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestSubtractFunction:
"""Test subtract function from calculation.py module."""
def test_subtract_all_args_greater_zero(self):
"""Test subtract function if all arguments are greater than zero."""
try:
self.assertEqual(subtract(30, 16), 15)
except Exception as error:
... | the_stack_v2_python_sparse | python10/test_calculation.py | maksimok93/Dp-189 | train | 0 |
2299156860a1fd49c12de9c00453e6f7735567c6 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn LearningContent()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'additionalTags': lambda n: setattr(self, 'additional_tags', n.get_collection_of_primitive_values(str)), 'contentW... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return LearningContent()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Callable[[Any], None]] = {'additionalTags': lambda n: se... | LearningContent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearningContent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningContent:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_10k_train_002396 | 7,407 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: LearningContent",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | stack_v2_sparse_classes_30k_train_003160 | Implement the Python class `LearningContent` described below.
Class description:
Implement the LearningContent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningContent: Creates a new instance of the appropriate class based on discriminator... | Implement the Python class `LearningContent` described below.
Class description:
Implement the LearningContent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningContent: Creates a new instance of the appropriate class based on discriminator... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class LearningContent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningContent:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LearningContent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LearningContent:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Learning... | the_stack_v2_python_sparse | msgraph/generated/models/learning_content.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
cb9c86f5e3f00ad8afaa3ec6519bd594a10e3fae | [
"variation_id = variation['_id']\nidentifier = valid_result.identifier\ntoken_type = valid_result.classification_token.token_type\ntoken_type_l = token_type.lower()\nvrs_ref_allele_seq = None\nif 'uncertain' in token_type_l:\n warnings = ['Ambiguous regions cannot be normalized']\nelif 'range' not in token_type_... | <|body_start_0|>
variation_id = variation['_id']
identifier = valid_result.identifier
token_type = valid_result.classification_token.token_type
token_type_l = token_type.lower()
vrs_ref_allele_seq = None
if 'uncertain' in token_type_l:
warnings = ['Ambiguous r... | Class for represnting VRSATILE objects | ToVRSATILE | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToVRSATILE:
"""Class for represnting VRSATILE objects"""
def get_variation_descriptor(self, label: str, variation: Dict, valid_result: ValidationResult, _id: str, warnings: List, gene: Optional[str]=None) -> Tuple[VariationDescriptor, List]:
"""Return variation descriptor and warning... | stack_v2_sparse_classes_10k_train_002397 | 3,637 | permissive | [
{
"docstring": "Return variation descriptor and warnings :param str label: Initial input query :param Dict variation: VRS variation object :param ValidationResult valid_result: Valid result for query :param str _id: _id field for variation descriptor :param List warnings: List of warnings :param Optional[str] g... | 2 | stack_v2_sparse_classes_30k_train_000770 | Implement the Python class `ToVRSATILE` described below.
Class description:
Class for represnting VRSATILE objects
Method signatures and docstrings:
- def get_variation_descriptor(self, label: str, variation: Dict, valid_result: ValidationResult, _id: str, warnings: List, gene: Optional[str]=None) -> Tuple[VariationD... | Implement the Python class `ToVRSATILE` described below.
Class description:
Class for represnting VRSATILE objects
Method signatures and docstrings:
- def get_variation_descriptor(self, label: str, variation: Dict, valid_result: ValidationResult, _id: str, warnings: List, gene: Optional[str]=None) -> Tuple[VariationD... | 4614e6dd0b3b5612d48f1e69be4e1476977aafba | <|skeleton|>
class ToVRSATILE:
"""Class for represnting VRSATILE objects"""
def get_variation_descriptor(self, label: str, variation: Dict, valid_result: ValidationResult, _id: str, warnings: List, gene: Optional[str]=None) -> Tuple[VariationDescriptor, List]:
"""Return variation descriptor and warning... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ToVRSATILE:
"""Class for represnting VRSATILE objects"""
def get_variation_descriptor(self, label: str, variation: Dict, valid_result: ValidationResult, _id: str, warnings: List, gene: Optional[str]=None) -> Tuple[VariationDescriptor, List]:
"""Return variation descriptor and warnings :param str ... | the_stack_v2_python_sparse | variation/to_vrsatile.py | cancervariants/variation-normalization | train | 4 |
a232274be705e3cfa03016d853a3c6eb22b30968 | [
"if not spectator_apps.is_enabled('reading'):\n raise ImproperlyConfigured(\"To use the CreatorManager.by_publications() method, 'spectator.reading' must by in INSTALLED_APPS.\")\nqs = self.get_queryset()\nqs = qs.exclude(publications__reading__isnull=True).exclude(publications__reading__is_finished=False).annot... | <|body_start_0|>
if not spectator_apps.is_enabled('reading'):
raise ImproperlyConfigured("To use the CreatorManager.by_publications() method, 'spectator.reading' must by in INSTALLED_APPS.")
qs = self.get_queryset()
qs = qs.exclude(publications__reading__isnull=True).exclude(publicat... | CreatorManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreatorManager:
def by_publications(self):
"""The Creators who have been most-read, ordered by number of read publications (ignoring if any of those publicatinos have been read multiple times.) Each Creator will have a `num_publications` attribute."""
<|body_0|>
def by_readi... | stack_v2_sparse_classes_10k_train_002398 | 4,128 | permissive | [
{
"docstring": "The Creators who have been most-read, ordered by number of read publications (ignoring if any of those publicatinos have been read multiple times.) Each Creator will have a `num_publications` attribute.",
"name": "by_publications",
"signature": "def by_publications(self)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_006379 | Implement the Python class `CreatorManager` described below.
Class description:
Implement the CreatorManager class.
Method signatures and docstrings:
- def by_publications(self): The Creators who have been most-read, ordered by number of read publications (ignoring if any of those publicatinos have been read multiple... | Implement the Python class `CreatorManager` described below.
Class description:
Implement the CreatorManager class.
Method signatures and docstrings:
- def by_publications(self): The Creators who have been most-read, ordered by number of read publications (ignoring if any of those publicatinos have been read multiple... | 2d89dcdb624b01452a5b6ca0ee092774fcc0aa52 | <|skeleton|>
class CreatorManager:
def by_publications(self):
"""The Creators who have been most-read, ordered by number of read publications (ignoring if any of those publicatinos have been read multiple times.) Each Creator will have a `num_publications` attribute."""
<|body_0|>
def by_readi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CreatorManager:
def by_publications(self):
"""The Creators who have been most-read, ordered by number of read publications (ignoring if any of those publicatinos have been read multiple times.) Each Creator will have a `num_publications` attribute."""
if not spectator_apps.is_enabled('reading'... | the_stack_v2_python_sparse | spectator/core/managers.py | philgyford/django-spectator | train | 45 | |
fe1b68be12c5b5606e3c516dd1543be259d091e3 | [
"data_list = []\nresults = self.query.all()\nformatter = self.request.locale.dates.getFormatter('date', 'short')\nfor result in results:\n data = {}\n data['qid'] = 'i-' + str(result.parliamentary_item_id)\n if type(result) == domain.AgendaItem:\n g = u' ' + result.group.type + u' ' + result.group.s... | <|body_start_0|>
data_list = []
results = self.query.all()
formatter = self.request.locale.dates.getFormatter('date', 'short')
for result in results:
data = {}
data['qid'] = 'i-' + str(result.parliamentary_item_id)
if type(result) == domain.AgendaItem:... | Group parliamentary items per stage: e.g. action required, in progress, answered/debated, 'dead' (withdrawn, elapsed, inadmissible) | ItemInStageViewlet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemInStageViewlet:
"""Group parliamentary items per stage: e.g. action required, in progress, answered/debated, 'dead' (withdrawn, elapsed, inadmissible)"""
def getData(self):
"""return the data of the query"""
<|body_0|>
def update(self):
"""refresh the query""... | stack_v2_sparse_classes_10k_train_002399 | 35,739 | no_license | [
{
"docstring": "return the data of the query",
"name": "getData",
"signature": "def getData(self)"
},
{
"docstring": "refresh the query",
"name": "update",
"signature": "def update(self)"
}
] | 2 | null | Implement the Python class `ItemInStageViewlet` described below.
Class description:
Group parliamentary items per stage: e.g. action required, in progress, answered/debated, 'dead' (withdrawn, elapsed, inadmissible)
Method signatures and docstrings:
- def getData(self): return the data of the query
- def update(self)... | Implement the Python class `ItemInStageViewlet` described below.
Class description:
Group parliamentary items per stage: e.g. action required, in progress, answered/debated, 'dead' (withdrawn, elapsed, inadmissible)
Method signatures and docstrings:
- def getData(self): return the data of the query
- def update(self)... | 5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d | <|skeleton|>
class ItemInStageViewlet:
"""Group parliamentary items per stage: e.g. action required, in progress, answered/debated, 'dead' (withdrawn, elapsed, inadmissible)"""
def getData(self):
"""return the data of the query"""
<|body_0|>
def update(self):
"""refresh the query""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ItemInStageViewlet:
"""Group parliamentary items per stage: e.g. action required, in progress, answered/debated, 'dead' (withdrawn, elapsed, inadmissible)"""
def getData(self):
"""return the data of the query"""
data_list = []
results = self.query.all()
formatter = self.re... | the_stack_v2_python_sparse | bungeni.buildout/branches/bungeni.buildout-refactor-2010-06-02/src/bungeni.main/bungeni/ui/viewlets/workspace.py | malangalanga/bungeni-portal | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.