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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3687c175c5dbc53b54e8ef982b25e27a4d52edfa | [
"self.log_type = log_type\nself.directory = directory\nself.extension = extension\nself.__check_exists()",
"self.__check_exists()\nfile_path = self.__get_path()\ntime_str = str(datetime.datetime.now()) + ' : ' if write_time else ''\nwith open(file_path, 'a') as log:\n log.write('%s%s\\n' % (time_str, text))",
... | <|body_start_0|>
self.log_type = log_type
self.directory = directory
self.extension = extension
self.__check_exists()
<|end_body_0|>
<|body_start_1|>
self.__check_exists()
file_path = self.__get_path()
time_str = str(datetime.datetime.now()) + ' : ' if write_time... | AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ A class which manages the logs | Logs | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logs:
"""AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ A class which manages the logs"""
def __init__(self, log_type: str, directory: str='%s/logs', extension: str=DEEP_EXT_CSV) -> None:
"""AUTHORS: -------- :author: Alix Leroy :author: Samu... | stack_v2_sparse_classes_10k_train_007100 | 4,235 | permissive | [
{
"docstring": "AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ Initialize a log object. PARAMETERS: ----------- :param log_type: str: The log type (notification, history :param directory: str :param extension: str: RETURN: ------- :return: None",
"name": "__init__",... | 6 | stack_v2_sparse_classes_30k_train_003741 | Implement the Python class `Logs` described below.
Class description:
AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ A class which manages the logs
Method signatures and docstrings:
- def __init__(self, log_type: str, directory: str='%s/logs', extension: str=DEEP_EXT_CSV) -> ... | Implement the Python class `Logs` described below.
Class description:
AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ A class which manages the logs
Method signatures and docstrings:
- def __init__(self, log_type: str, directory: str='%s/logs', extension: str=DEEP_EXT_CSV) -> ... | 3f9a1314ccfc1428d50de6a49a040aab4cb56dad | <|skeleton|>
class Logs:
"""AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ A class which manages the logs"""
def __init__(self, log_type: str, directory: str='%s/logs', extension: str=DEEP_EXT_CSV) -> None:
"""AUTHORS: -------- :author: Alix Leroy :author: Samu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Logs:
"""AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake DESCRIPTION: ------------ A class which manages the logs"""
def __init__(self, log_type: str, directory: str='%s/logs', extension: str=DEEP_EXT_CSV) -> None:
"""AUTHORS: -------- :author: Alix Leroy :author: Samuel Westlake D... | the_stack_v2_python_sparse | deeplodocus/utils/logs.py | Deeplodocus/deeplodocus | train | 2 |
60f29405f39725e1835d6d3c98c65e40f682f986 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EdiscoverySearch()",
"from .data_source import DataSource\nfrom .data_source_scopes import DataSourceScopes\nfrom .ediscovery_add_to_review_set_operation import EdiscoveryAddToReviewSetOperation\nfrom .ediscovery_estimate_operation imp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return EdiscoverySearch()
<|end_body_0|>
<|body_start_1|>
from .data_source import DataSource
from .data_source_scopes import DataSourceScopes
from .ediscovery_add_to_review_set_operati... | EdiscoverySearch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdiscoverySearch:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoverySearch:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_10k_train_007101 | 5,246 | 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: EdiscoverySearch",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | stack_v2_sparse_classes_30k_train_001893 | Implement the Python class `EdiscoverySearch` described below.
Class description:
Implement the EdiscoverySearch class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoverySearch: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `EdiscoverySearch` described below.
Class description:
Implement the EdiscoverySearch class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoverySearch: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class EdiscoverySearch:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoverySearch:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EdiscoverySearch:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoverySearch:
"""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: Edisco... | the_stack_v2_python_sparse | msgraph/generated/models/security/ediscovery_search.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
06005864f49d8d7056eb9cbf0a53d337c3c907bb | [
"self._go = import_or_raise('plotly.graph_objects', error_msg='Cannot find dependency plotly.graph_objects')\nself.results = results\nself.objective = objective",
"if not interactive_plot:\n plot_obj = SearchIterationPlot(self.results, self.objective)\n return self._go.Figure(plot_obj.best_score_by_iter_fig... | <|body_start_0|>
self._go = import_or_raise('plotly.graph_objects', error_msg='Cannot find dependency plotly.graph_objects')
self.results = results
self.objective = objective
<|end_body_0|>
<|body_start_1|>
if not interactive_plot:
plot_obj = SearchIterationPlot(self.results... | Plots for the AutoMLSearch class. | PipelineSearchPlots | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelineSearchPlots:
"""Plots for the AutoMLSearch class."""
def __init__(self, results, objective):
"""Make plots for the AutoMLSearch class. Arguments: data (AutoMLSearch): Automated pipeline search object"""
<|body_0|>
def search_iteration_plot(self, interactive_plot=... | stack_v2_sparse_classes_10k_train_007102 | 4,225 | permissive | [
{
"docstring": "Make plots for the AutoMLSearch class. Arguments: data (AutoMLSearch): Automated pipeline search object",
"name": "__init__",
"signature": "def __init__(self, results, objective)"
},
{
"docstring": "Shows a plot of the best score at each iteration using data gathered during train... | 2 | stack_v2_sparse_classes_30k_train_005278 | Implement the Python class `PipelineSearchPlots` described below.
Class description:
Plots for the AutoMLSearch class.
Method signatures and docstrings:
- def __init__(self, results, objective): Make plots for the AutoMLSearch class. Arguments: data (AutoMLSearch): Automated pipeline search object
- def search_iterat... | Implement the Python class `PipelineSearchPlots` described below.
Class description:
Plots for the AutoMLSearch class.
Method signatures and docstrings:
- def __init__(self, results, objective): Make plots for the AutoMLSearch class. Arguments: data (AutoMLSearch): Automated pipeline search object
- def search_iterat... | 3b5bf62b08a5a5bc6485ba5387a08c32e1857473 | <|skeleton|>
class PipelineSearchPlots:
"""Plots for the AutoMLSearch class."""
def __init__(self, results, objective):
"""Make plots for the AutoMLSearch class. Arguments: data (AutoMLSearch): Automated pipeline search object"""
<|body_0|>
def search_iteration_plot(self, interactive_plot=... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PipelineSearchPlots:
"""Plots for the AutoMLSearch class."""
def __init__(self, results, objective):
"""Make plots for the AutoMLSearch class. Arguments: data (AutoMLSearch): Automated pipeline search object"""
self._go = import_or_raise('plotly.graph_objects', error_msg='Cannot find depe... | the_stack_v2_python_sparse | evalml/automl/pipeline_search_plots.py | ObinnaObeleagu/evalml | train | 1 |
31c7d54cb2ebf974366c31050cedde8cf2113d27 | [
"ctx.save_for_backward(input)\ninput_shape = input.shape[0]\neven_indices = [i for i in range(0, input_shape, 2)]\nodd_indices = [i for i in range(1, input_shape, 2)]\noutput = input.clone()\noutput[even_indices] = output[even_indices].clamp(min=0)\noutput[odd_indices] = 0 - output[odd_indices]\noutput[odd_indices]... | <|body_start_0|>
ctx.save_for_backward(input)
input_shape = input.shape[0]
even_indices = [i for i in range(0, input_shape, 2)]
odd_indices = [i for i in range(1, input_shape, 2)]
output = input.clone()
output[even_indices] = output[even_indices].clamp(min=0)
outp... | brelu_function | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class brelu_function:
def forward(ctx, input):
"""In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation. You can cache arbitrary objects for use in the backw... | stack_v2_sparse_classes_10k_train_007103 | 32,265 | no_license | [
{
"docstring": "In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation. You can cache arbitrary objects for use in the backward pass using the ctx.save_for_backward method.",
... | 2 | stack_v2_sparse_classes_30k_train_002096 | Implement the Python class `brelu_function` described below.
Class description:
Implement the brelu_function class.
Method signatures and docstrings:
- def forward(ctx, input): In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be u... | Implement the Python class `brelu_function` described below.
Class description:
Implement the brelu_function class.
Method signatures and docstrings:
- def forward(ctx, input): In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be u... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class brelu_function:
def forward(ctx, input):
"""In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation. You can cache arbitrary objects for use in the backw... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class brelu_function:
def forward(ctx, input):
"""In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation. You can cache arbitrary objects for use in the backward pass using... | the_stack_v2_python_sparse | generated/test_digantamisra98_Echo.py | jansel/pytorch-jit-paritybench | train | 35 | |
4ffe6b92d6d24f1fecb74a43cdf54a1ba52d04e5 | [
"for item in list_target:\n if func_condition(item):\n yield item",
"for item in list_target:\n if func_condition(item):\n return item",
"number = 0\nfor item in list_target:\n if func_condition(item):\n number += 1\nreturn number",
"for item in list_target:\n if func_conditio... | <|body_start_0|>
for item in list_target:
if func_condition(item):
yield item
<|end_body_0|>
<|body_start_1|>
for item in list_target:
if func_condition(item):
return item
<|end_body_1|>
<|body_start_2|>
number = 0
for item in lis... | 列表助手类 | ListHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListHelper:
"""列表助手类"""
def find_all(list_target, func_condition):
"""通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型."""
<|body_0|>
def find_single_condition(list_target, func_condition):
"... | stack_v2_sparse_classes_10k_train_007104 | 2,479 | no_license | [
{
"docstring": "通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型.",
"name": "find_all",
"signature": "def find_all(list_target, func_condition)"
},
{
"docstring": "通用的查找某个条件的单个元素的方法 :param list_target: 需要查找的列表 :param func_co... | 4 | null | Implement the Python class `ListHelper` described below.
Class description:
列表助手类
Method signatures and docstrings:
- def find_all(list_target, func_condition): 通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型.
- def find_single_condition(list_ta... | Implement the Python class `ListHelper` described below.
Class description:
列表助手类
Method signatures and docstrings:
- def find_all(list_target, func_condition): 通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型.
- def find_single_condition(list_ta... | 55e6681da1a9faf9c0ec618ed60f5da9ecc6beb6 | <|skeleton|>
class ListHelper:
"""列表助手类"""
def find_all(list_target, func_condition):
"""通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型."""
<|body_0|>
def find_single_condition(list_target, func_condition):
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ListHelper:
"""列表助手类"""
def find_all(list_target, func_condition):
"""通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型."""
for item in list_target:
if func_condition(item):
yield item
... | the_stack_v2_python_sparse | MyNotes_01/Step01/4-CORE/day04_17/common/list_helper.py | ZimingGuo/MyNotes01 | train | 0 |
c27ed9954d6fe65a5b6744be342aa351e8c941dd | [
"index1 = index2 = -1\nmin_distance = len(words)\nfor idx in range(len(words)):\n if words[idx] == word1:\n index1 = idx\n elif words[idx] == word2:\n index2 = idx\n if index1 != -1 and index2 != -1:\n min_distance = min(min_distance, abs(index1 - index2))\nreturn min_distance",
"min... | <|body_start_0|>
index1 = index2 = -1
min_distance = len(words)
for idx in range(len(words)):
if words[idx] == word1:
index1 = idx
elif words[idx] == word2:
index2 = idx
if index1 != -1 and index2 != -1:
min_dist... | Words | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Words:
def shortest_distance(self, words: List[str], word1: str, word2: str) -> int:
"""Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param word2: :return:"""
<|body_0|>
def shortest_distance_(self, words: List[str], word1: ... | stack_v2_sparse_classes_10k_train_007105 | 1,554 | no_license | [
{
"docstring": "Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param word2: :return:",
"name": "shortest_distance",
"signature": "def shortest_distance(self, words: List[str], word1: str, word2: str) -> int"
},
{
"docstring": "Approach: Brute For... | 2 | null | Implement the Python class `Words` described below.
Class description:
Implement the Words class.
Method signatures and docstrings:
- def shortest_distance(self, words: List[str], word1: str, word2: str) -> int: Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param wor... | Implement the Python class `Words` described below.
Class description:
Implement the Words class.
Method signatures and docstrings:
- def shortest_distance(self, words: List[str], word1: str, word2: str) -> int: Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param wor... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Words:
def shortest_distance(self, words: List[str], word1: str, word2: str) -> int:
"""Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param word2: :return:"""
<|body_0|>
def shortest_distance_(self, words: List[str], word1: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Words:
def shortest_distance(self, words: List[str], word1: str, word2: str) -> int:
"""Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param word2: :return:"""
index1 = index2 = -1
min_distance = len(words)
for idx in range(len(... | the_stack_v2_python_sparse | revisited_2021/arrays/shortest_word_distance.py | Shiv2157k/leet_code | train | 1 | |
b8c38b60f69da355289aedf8171a20a4dfe8f089 | [
"super(LearningHandler, self).__init__()\nself.lr = lr\nself.drop = drop\nself.lr_tensor = lr_tensor\nself.patience = patience\nself.tau = tau\nself.tau_tensor = tau_tensor\nself.min_tem = min_tem\nself.gumble = gumble",
"self.assign_op = tf.no_op()\nself.scheduler_stage = 0\nself.best_loss = np.inf\nself.wait = ... | <|body_start_0|>
super(LearningHandler, self).__init__()
self.lr = lr
self.drop = drop
self.lr_tensor = lr_tensor
self.patience = patience
self.tau = tau
self.tau_tensor = tau_tensor
self.min_tem = min_tem
self.gumble = gumble
<|end_body_0|>
<|bod... | Class for managing the learning rate scheduling and early stopping criteria. Learning rate scheduling is implemented by multiplying the learning rate by 'drop' everytime the validation loss does not see any improvement for 'patience' training steps | LearningHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearningHandler:
"""Class for managing the learning rate scheduling and early stopping criteria. Learning rate scheduling is implemented by multiplying the learning rate by 'drop' everytime the validation loss does not see any improvement for 'patience' training steps"""
def __init__(self, l... | stack_v2_sparse_classes_10k_train_007106 | 10,329 | permissive | [
{
"docstring": "initializer. Args: lr: initial learning rate drop: factor by which learning rate is reduced lr_tensor: tensorflow (or keras) tensor for the learning rate patience: patience of the learning rate scheduler tau_tensor: tensor to kepp the changed temperature tau: temperature min_tem: minimum tempera... | 3 | null | Implement the Python class `LearningHandler` described below.
Class description:
Class for managing the learning rate scheduling and early stopping criteria. Learning rate scheduling is implemented by multiplying the learning rate by 'drop' everytime the validation loss does not see any improvement for 'patience' trai... | Implement the Python class `LearningHandler` described below.
Class description:
Class for managing the learning rate scheduling and early stopping criteria. Learning rate scheduling is implemented by multiplying the learning rate by 'drop' everytime the validation loss does not see any improvement for 'patience' trai... | dea327aa9e7ef7f7bca5a6c225dbdca1077a06e9 | <|skeleton|>
class LearningHandler:
"""Class for managing the learning rate scheduling and early stopping criteria. Learning rate scheduling is implemented by multiplying the learning rate by 'drop' everytime the validation loss does not see any improvement for 'patience' training steps"""
def __init__(self, l... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LearningHandler:
"""Class for managing the learning rate scheduling and early stopping criteria. Learning rate scheduling is implemented by multiplying the learning rate by 'drop' everytime the validation loss does not see any improvement for 'patience' training steps"""
def __init__(self, lr, drop, lr_t... | the_stack_v2_python_sparse | clustering_normalized_cuts/util.py | Tarkiyah/googleResearch | train | 11 |
d205a0585ccfdbb1075d2b33e40a4b0bbbd1cd71 | [
"super().__init__()\nself.vgg = vgg19(pretrained=True).features if not batch_norm else vgg19_bn(pretrained=True).features\nself.layers = [18, 27] if not batch_norm else [26, 39]\nself.model = nn.Sequential(nn.Conv2d(512, 512, kernel_size=1), nn.ReLU(inplace=True), nn.Dropout(0.8), nn.Conv2d(512, 512, kernel_size=1)... | <|body_start_0|>
super().__init__()
self.vgg = vgg19(pretrained=True).features if not batch_norm else vgg19_bn(pretrained=True).features
self.layers = [18, 27] if not batch_norm else [26, 39]
self.model = nn.Sequential(nn.Conv2d(512, 512, kernel_size=1), nn.ReLU(inplace=True), nn.Dropout... | TableNet. | TableNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TableNet:
"""TableNet."""
def __init__(self, num_class: int, batch_norm: bool=False):
"""Initialize TableNet. Args: num_class (int): Number of classes per point. batch_norm (bool): Select VGG with or without batch normalization."""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_10k_train_007107 | 5,468 | no_license | [
{
"docstring": "Initialize TableNet. Args: num_class (int): Number of classes per point. batch_norm (bool): Select VGG with or without batch normalization.",
"name": "__init__",
"signature": "def __init__(self, num_class: int, batch_norm: bool=False)"
},
{
"docstring": "Forward pass. Args: x (te... | 2 | null | Implement the Python class `TableNet` described below.
Class description:
TableNet.
Method signatures and docstrings:
- def __init__(self, num_class: int, batch_norm: bool=False): Initialize TableNet. Args: num_class (int): Number of classes per point. batch_norm (bool): Select VGG with or without batch normalization... | Implement the Python class `TableNet` described below.
Class description:
TableNet.
Method signatures and docstrings:
- def __init__(self, num_class: int, batch_norm: bool=False): Initialize TableNet. Args: num_class (int): Number of classes per point. batch_norm (bool): Select VGG with or without batch normalization... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class TableNet:
"""TableNet."""
def __init__(self, num_class: int, batch_norm: bool=False):
"""Initialize TableNet. Args: num_class (int): Number of classes per point. batch_norm (bool): Select VGG with or without batch normalization."""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TableNet:
"""TableNet."""
def __init__(self, num_class: int, batch_norm: bool=False):
"""Initialize TableNet. Args: num_class (int): Number of classes per point. batch_norm (bool): Select VGG with or without batch normalization."""
super().__init__()
self.vgg = vgg19(pretrained=Tr... | the_stack_v2_python_sparse | generated/test_tomassosorio_OCR_tablenet.py | jansel/pytorch-jit-paritybench | train | 35 |
2e764bb05e37ef38e6a6be032a292111d2edaef8 | [
"if n == 1:\n return '1'\ni = 1\nret = '1'\nwhile i < n:\n i += 1\n pre_ret = ret\n pre_c = pre_ret[0]\n cnt = 1\n ret = ''\n for c in pre_ret[1:]:\n if c == pre_c:\n cnt += 1\n else:\n ret += f'{cnt}{pre_c}'\n pre_c = c\n cnt = 1\n r... | <|body_start_0|>
if n == 1:
return '1'
i = 1
ret = '1'
while i < n:
i += 1
pre_ret = ret
pre_c = pre_ret[0]
cnt = 1
ret = ''
for c in pre_ret[1:]:
if c == pre_c:
cnt +=... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countAndSay2(self, n: int) -> str:
"""CREATED AT: 2022/2/15 30 / 30 test cases passed. Status: Accepted Runtime: 40 ms, faster than 94.24% Memory Usage: 14 MB, less than 78.47% 1 <= n <= 30"""
<|body_0|>
def countAndSay(self, n):
""":type n: int :rtype:... | stack_v2_sparse_classes_10k_train_007108 | 1,775 | permissive | [
{
"docstring": "CREATED AT: 2022/2/15 30 / 30 test cases passed. Status: Accepted Runtime: 40 ms, faster than 94.24% Memory Usage: 14 MB, less than 78.47% 1 <= n <= 30",
"name": "countAndSay2",
"signature": "def countAndSay2(self, n: int) -> str"
},
{
"docstring": ":type n: int :rtype: str",
... | 2 | stack_v2_sparse_classes_30k_train_004191 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countAndSay2(self, n: int) -> str: CREATED AT: 2022/2/15 30 / 30 test cases passed. Status: Accepted Runtime: 40 ms, faster than 94.24% Memory Usage: 14 MB, less than 78.47% ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countAndSay2(self, n: int) -> str: CREATED AT: 2022/2/15 30 / 30 test cases passed. Status: Accepted Runtime: 40 ms, faster than 94.24% Memory Usage: 14 MB, less than 78.47% ... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def countAndSay2(self, n: int) -> str:
"""CREATED AT: 2022/2/15 30 / 30 test cases passed. Status: Accepted Runtime: 40 ms, faster than 94.24% Memory Usage: 14 MB, less than 78.47% 1 <= n <= 30"""
<|body_0|>
def countAndSay(self, n):
""":type n: int :rtype:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def countAndSay2(self, n: int) -> str:
"""CREATED AT: 2022/2/15 30 / 30 test cases passed. Status: Accepted Runtime: 40 ms, faster than 94.24% Memory Usage: 14 MB, less than 78.47% 1 <= n <= 30"""
if n == 1:
return '1'
i = 1
ret = '1'
while i < n:
... | the_stack_v2_python_sparse | src/38-CountAndSay.py | Jiezhi/myleetcode | train | 1 | |
43c98885deaf83d02e1da14a2443529426613e01 | [
"self.stack = []\ntemp = root\nwhile temp != None:\n self.stack.append(temp)\n temp = temp.left",
"if len(self.stack) != 0:\n return True\nelse:\n return False",
"if len(self.stack) != 0:\n curr = self.stack.pop()\n nextsmall = curr\n if curr.right != None:\n curr = curr.right\n ... | <|body_start_0|>
self.stack = []
temp = root
while temp != None:
self.stack.append(temp)
temp = temp.left
<|end_body_0|>
<|body_start_1|>
if len(self.stack) != 0:
return True
else:
return False
<|end_body_1|>
<|body_start_2|>
... | BSTIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def hasNext(self):
""":rtype: bool"""
<|body_1|>
def next(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.stack = []
... | stack_v2_sparse_classes_10k_train_007109 | 1,326 | no_license | [
{
"docstring": ":type root: TreeNode",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",
"signature": "def hasNext(self)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_006385 | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def hasNext(self): :rtype: bool
- def next(self): :rtype: int | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def hasNext(self): :rtype: bool
- def next(self): :rtype: int
<|skeleton|>
class BSTIterator:
def __init__(self, root... | 466dbaef48b28ad1b44944cb3eb830b0cd7c7c97 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def hasNext(self):
""":rtype: bool"""
<|body_1|>
def next(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
self.stack = []
temp = root
while temp != None:
self.stack.append(temp)
temp = temp.left
def hasNext(self):
""":rtype: bool"""
if len(self.stack) != 0:
ret... | the_stack_v2_python_sparse | Pythons Solutions/Trees/BST_iterator.py | dexteridea22/Interviewbit-Selected_Problems | train | 1 | |
0170bb51f7fd819d904993d49e39490e9376a418 | [
"super().__init__(original_radiis, radii, outer_polygon)\nself.points_locations = []\nself.labels = []\nself.wanted_size = wanted_size\nself.load_save = load_save\nself.seed = seed\nfile_name, _ = os.path.splitext(class_path)\ntype_area_name = file_name.split('/')[-1]\nself.full_base_dir = os.path.join(CACHE_BASE_D... | <|body_start_0|>
super().__init__(original_radiis, radii, outer_polygon)
self.points_locations = []
self.labels = []
self.wanted_size = wanted_size
self.load_save = load_save
self.seed = seed
file_name, _ = os.path.splitext(class_path)
type_area_name = fil... | A dataset contains only one class | ClassDataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassDataset:
"""A dataset contains only one class"""
def __init__(self, class_path: str, class_label: float, original_radiis: List[int], wanted_size: int, radii: List[int]=None, outer_polygon=None, dataset_type_name: str=None, load_save=True, return_point=False, seed=None, only_higher_than=... | stack_v2_sparse_classes_10k_train_007110 | 4,446 | no_license | [
{
"docstring": "Args: class_path: The path to the data of the first class wanted in the dataset class_label: The label of the first class wanted in the dataset original_radiis: outer_polygon:",
"name": "__init__",
"signature": "def __init__(self, class_path: str, class_label: float, original_radiis: Lis... | 3 | stack_v2_sparse_classes_30k_train_000737 | Implement the Python class `ClassDataset` described below.
Class description:
A dataset contains only one class
Method signatures and docstrings:
- def __init__(self, class_path: str, class_label: float, original_radiis: List[int], wanted_size: int, radii: List[int]=None, outer_polygon=None, dataset_type_name: str=No... | Implement the Python class `ClassDataset` described below.
Class description:
A dataset contains only one class
Method signatures and docstrings:
- def __init__(self, class_path: str, class_label: float, original_radiis: List[int], wanted_size: int, radii: List[int]=None, outer_polygon=None, dataset_type_name: str=No... | 69c8f1b40de3011d61c7a2720d006c131d6e9a1c | <|skeleton|>
class ClassDataset:
"""A dataset contains only one class"""
def __init__(self, class_path: str, class_label: float, original_radiis: List[int], wanted_size: int, radii: List[int]=None, outer_polygon=None, dataset_type_name: str=None, load_save=True, return_point=False, seed=None, only_higher_than=... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClassDataset:
"""A dataset contains only one class"""
def __init__(self, class_path: str, class_label: float, original_radiis: List[int], wanted_size: int, radii: List[int]=None, outer_polygon=None, dataset_type_name: str=None, load_save=True, return_point=False, seed=None, only_higher_than=None):
... | the_stack_v2_python_sparse | topo2vec/datasets/class_dataset.py | urielsinger/topo2vec | train | 2 |
302c780ee6c9e6bdaf11138406aa3005def3a15d | [
"super(Clusters, self).__init__(gis=gis, url=url)\nself._con = gis\nself._url = url\nif url.lower().endswith('/clusters'):\n self._url = url\nelse:\n self._url = url + '/clusters'\nif initialize:\n self._init(gis)",
"url = self._url + '/create'\nparams = {'f': 'json', 'clusterName': cluster_name, 'machin... | <|body_start_0|>
super(Clusters, self).__init__(gis=gis, url=url)
self._con = gis
self._url = url
if url.lower().endswith('/clusters'):
self._url = url
else:
self._url = url + '/clusters'
if initialize:
self._init(gis)
<|end_body_0|>
<... | This resource is a collection of all the clusters created within your site. The Create Cluster operation lets you define a new cluster configuration. =============== ==================================================================== **Argument** **Description** --------------- ----------------------------------------... | Clusters | [
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Clusters:
"""This resource is a collection of all the clusters created within your site. The Create Cluster operation lets you define a new cluster configuration. =============== ==================================================================== **Argument** **Description** --------------- ----... | stack_v2_sparse_classes_10k_train_007111 | 14,794 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, url, gis, initialize=False)"
},
{
"docstring": "Creating a new cluster involves defining a clustering protocol that will be shared by all server machines participating in the cluster. All server machines that are ... | 3 | stack_v2_sparse_classes_30k_train_001221 | Implement the Python class `Clusters` described below.
Class description:
This resource is a collection of all the clusters created within your site. The Create Cluster operation lets you define a new cluster configuration. =============== ==================================================================== **Argument... | Implement the Python class `Clusters` described below.
Class description:
This resource is a collection of all the clusters created within your site. The Create Cluster operation lets you define a new cluster configuration. =============== ==================================================================== **Argument... | a874fe7e5c95196e4de68db2da0e2a05eb70e5d8 | <|skeleton|>
class Clusters:
"""This resource is a collection of all the clusters created within your site. The Create Cluster operation lets you define a new cluster configuration. =============== ==================================================================== **Argument** **Description** --------------- ----... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Clusters:
"""This resource is a collection of all the clusters created within your site. The Create Cluster operation lets you define a new cluster configuration. =============== ==================================================================== **Argument** **Description** --------------- -----------------... | the_stack_v2_python_sparse | arcpyenv/arcgispro-py3-clone/Lib/site-packages/arcgis/gis/server/admin/_clusters.py | SherbazHashmi/HackathonServer | train | 3 |
d9ee8d8817e3d95297c0e1f1c5df35f1f95ff8a9 | [
"self.legend = legend\nself.ax = ax\nself.colors = ['b', 'g', 'r', 'c', 'm', 'y', 'b']\nself.line_styles = ['-', '-', '--', '-.', ':']\nself.line = []\nself.ax.set_ylabel(ylabel)\nself.ax.set_xlabel(xlabel)\nself.ax.set_title(title)\nself.ax.grid(True)\nself.init = True",
"if self.init == True:\n for i in rang... | <|body_start_0|>
self.legend = legend
self.ax = ax
self.colors = ['b', 'g', 'r', 'c', 'm', 'y', 'b']
self.line_styles = ['-', '-', '--', '-.', ':']
self.line = []
self.ax.set_ylabel(ylabel)
self.ax.set_xlabel(xlabel)
self.ax.set_title(title)
self.a... | Create each individual subplot. | myPlot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class myPlot:
"""Create each individual subplot."""
def __init__(self, ax, xlabel='', ylabel='', title='', legend=None):
"""ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis title - Plot title legend - A tuple of strings that identify... | stack_v2_sparse_classes_10k_train_007112 | 6,668 | no_license | [
{
"docstring": "ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis title - Plot title legend - A tuple of strings that identify the data. EX: (\"data1\",\"data2\", ... , \"dataN\")",
"name": "__init__",
"signature": "def __init__(self, ax, xlabel=''... | 2 | stack_v2_sparse_classes_30k_train_004047 | Implement the Python class `myPlot` described below.
Class description:
Create each individual subplot.
Method signatures and docstrings:
- def __init__(self, ax, xlabel='', ylabel='', title='', legend=None): ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis tit... | Implement the Python class `myPlot` described below.
Class description:
Create each individual subplot.
Method signatures and docstrings:
- def __init__(self, ax, xlabel='', ylabel='', title='', legend=None): ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis tit... | 498a54f9777c5a849b0af491d9e76fcc470aa083 | <|skeleton|>
class myPlot:
"""Create each individual subplot."""
def __init__(self, ax, xlabel='', ylabel='', title='', legend=None):
"""ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis title - Plot title legend - A tuple of strings that identify... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class myPlot:
"""Create each individual subplot."""
def __init__(self, ax, xlabel='', ylabel='', title='', legend=None):
"""ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis title - Plot title legend - A tuple of strings that identify the data. EX... | the_stack_v2_python_sparse | DeepWNCS/Testbed/Plant-side/Plotter.py | msh0576/RL_WCPS | train | 1 |
ba38a2f65c3802efcbda9d5b727ca3b97add63bf | [
"super(CrossValidationJointFusionWorkflow, self).__init__(name=name, **kwargs)\nself.csv_file = File(value=os.path.abspath(csv_file), exists=True)\nself.hasHeader = traits.Bool(hasHeader)\nself.sample_size = traits.Int(size)\nself.config['execution'] = {'remove_unnecessary_outputs': 'true'}",
"csvReader = CSVRead... | <|body_start_0|>
super(CrossValidationJointFusionWorkflow, self).__init__(name=name, **kwargs)
self.csv_file = File(value=os.path.abspath(csv_file), exists=True)
self.hasHeader = traits.Bool(hasHeader)
self.sample_size = traits.Int(size)
self.config['execution'] = {'remove_unnece... | Nipype workflow for Multi-Label Atlas Fusion cross-validation experiment :param Workflow: | CrossValidationJointFusionWorkflow | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrossValidationJointFusionWorkflow:
"""Nipype workflow for Multi-Label Atlas Fusion cross-validation experiment :param Workflow:"""
def __init__(self, csv_file=None, size=0, hasHeader=False, name='CrossValidationJointFusionWorkflow', **kwargs):
"""This function... :param self: :param... | stack_v2_sparse_classes_10k_train_007113 | 18,518 | permissive | [
{
"docstring": "This function... :param self: :param csv_file: :param size: :param hasHeader: :param name: :param **kwargs: :return:",
"name": "__init__",
"signature": "def __init__(self, csv_file=None, size=0, hasHeader=False, name='CrossValidationJointFusionWorkflow', **kwargs)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_005480 | Implement the Python class `CrossValidationJointFusionWorkflow` described below.
Class description:
Nipype workflow for Multi-Label Atlas Fusion cross-validation experiment :param Workflow:
Method signatures and docstrings:
- def __init__(self, csv_file=None, size=0, hasHeader=False, name='CrossValidationJointFusionW... | Implement the Python class `CrossValidationJointFusionWorkflow` described below.
Class description:
Nipype workflow for Multi-Label Atlas Fusion cross-validation experiment :param Workflow:
Method signatures and docstrings:
- def __init__(self, csv_file=None, size=0, hasHeader=False, name='CrossValidationJointFusionW... | 64bb590918a188b660225e44ae54c1072f3a8056 | <|skeleton|>
class CrossValidationJointFusionWorkflow:
"""Nipype workflow for Multi-Label Atlas Fusion cross-validation experiment :param Workflow:"""
def __init__(self, csv_file=None, size=0, hasHeader=False, name='CrossValidationJointFusionWorkflow', **kwargs):
"""This function... :param self: :param... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CrossValidationJointFusionWorkflow:
"""Nipype workflow for Multi-Label Atlas Fusion cross-validation experiment :param Workflow:"""
def __init__(self, csv_file=None, size=0, hasHeader=False, name='CrossValidationJointFusionWorkflow', **kwargs):
"""This function... :param self: :param csv_file: :p... | the_stack_v2_python_sparse | AutoWorkup/BAW/workflows/crossValidate.py | BRAINSia/BRAINSTools | train | 101 |
75455841030bdbb9160abe2cfd88a463c92783b3 | [
"ret = [1] * len(nums)\naccum = 1\nfor i, n in enumerate(nums):\n ret[i] *= accum\n accum *= n\naccum = 1\nfor i, n in enumerate(nums[-1::-1]):\n ret[len(nums) - 1 - i] *= accum\n accum *= n\nreturn ret",
"if not nums:\n return []\nprefix = [1]\nfor i in range(len(nums)):\n prefix.append(prefix[... | <|body_start_0|>
ret = [1] * len(nums)
accum = 1
for i, n in enumerate(nums):
ret[i] *= accum
accum *= n
accum = 1
for i, n in enumerate(nums[-1::-1]):
ret[len(nums) - 1 - i] *= accum
accum *= n
return ret
<|end_body_0|>
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
"""08/25/2019 19:56"""
<|body_0|>
def productExceptSelf(self, nums: List[int]) -> List[int]:
"""12/03/2021 20:57"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = [1] * len(num... | stack_v2_sparse_classes_10k_train_007114 | 2,089 | no_license | [
{
"docstring": "08/25/2019 19:56",
"name": "productExceptSelf",
"signature": "def productExceptSelf(self, nums: List[int]) -> List[int]"
},
{
"docstring": "12/03/2021 20:57",
"name": "productExceptSelf",
"signature": "def productExceptSelf(self, nums: List[int]) -> List[int]"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf(self, nums: List[int]) -> List[int]: 08/25/2019 19:56
- def productExceptSelf(self, nums: List[int]) -> List[int]: 12/03/2021 20:57 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf(self, nums: List[int]) -> List[int]: 08/25/2019 19:56
- def productExceptSelf(self, nums: List[int]) -> List[int]: 12/03/2021 20:57
<|skeleton|>
class Solu... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
"""08/25/2019 19:56"""
<|body_0|>
def productExceptSelf(self, nums: List[int]) -> List[int]:
"""12/03/2021 20:57"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
"""08/25/2019 19:56"""
ret = [1] * len(nums)
accum = 1
for i, n in enumerate(nums):
ret[i] *= accum
accum *= n
accum = 1
for i, n in enumerate(nums[-1::-1]):
... | the_stack_v2_python_sparse | leetcode/solved/238_Product_of_Array_Except_Self/solution.py | sungminoh/algorithms | train | 0 | |
b675dad499f071c9c8fc9c126aad4a5c344cb5a2 | [
"if Queen.safe_xy(x, y, available):\n if Queen.safe_diagonal(x, y, available):\n return (True, available)\nreturn (False, available)",
"if x in available.keys():\n available.pop(x)\nfor row, col in available.items():\n if y in col:\n col.pop(y)\n if len(col) == 0:\n return False\n... | <|body_start_0|>
if Queen.safe_xy(x, y, available):
if Queen.safe_diagonal(x, y, available):
return (True, available)
return (False, available)
<|end_body_0|>
<|body_start_1|>
if x in available.keys():
available.pop(x)
for row, col in available.it... | Queen class | Queen | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Queen:
"""Queen class"""
def attack(x, y, available):
"""Simulate attack * Validate if x and is safe * Validate if diagonal is safe * Delete posibilities in board"""
<|body_0|>
def safe_xy(x, y, available):
"""Validate x in y Delete positions in x Delete cols for... | stack_v2_sparse_classes_10k_train_007115 | 1,574 | permissive | [
{
"docstring": "Simulate attack * Validate if x and is safe * Validate if diagonal is safe * Delete posibilities in board",
"name": "attack",
"signature": "def attack(x, y, available)"
},
{
"docstring": "Validate x in y Delete positions in x Delete cols for y positions in n rows if one col will ... | 3 | stack_v2_sparse_classes_30k_train_006842 | Implement the Python class `Queen` described below.
Class description:
Queen class
Method signatures and docstrings:
- def attack(x, y, available): Simulate attack * Validate if x and is safe * Validate if diagonal is safe * Delete posibilities in board
- def safe_xy(x, y, available): Validate x in y Delete positions... | Implement the Python class `Queen` described below.
Class description:
Queen class
Method signatures and docstrings:
- def attack(x, y, available): Simulate attack * Validate if x and is safe * Validate if diagonal is safe * Delete posibilities in board
- def safe_xy(x, y, available): Validate x in y Delete positions... | 11a08a315dc76e7d2ddc9c742380dcfa9fd58e23 | <|skeleton|>
class Queen:
"""Queen class"""
def attack(x, y, available):
"""Simulate attack * Validate if x and is safe * Validate if diagonal is safe * Delete posibilities in board"""
<|body_0|>
def safe_xy(x, y, available):
"""Validate x in y Delete positions in x Delete cols for... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Queen:
"""Queen class"""
def attack(x, y, available):
"""Simulate attack * Validate if x and is safe * Validate if diagonal is safe * Delete posibilities in board"""
if Queen.safe_xy(x, y, available):
if Queen.safe_diagonal(x, y, available):
return (True, avail... | the_stack_v2_python_sparse | modules/queens/simulation/queen.py | eocode/Queens | train | 0 |
52f225e4b58285928faa9ac996dda1cbb2ad79be | [
"ansible_hosts = get_value('ansible', 'ansible_host_path')\nre_pattern = '^\\\\s*\\\\[(?P<host>.*)\\\\]'\nhost_list = [{'name': 'all', 'children': [{'name': 'all'}]}]\nif File.if_file_exists(ansible_hosts):\n host_dic = {'name': File.get_file_name(ansible_hosts), 'children': []}\n with open(ansible_hosts) as ... | <|body_start_0|>
ansible_hosts = get_value('ansible', 'ansible_host_path')
re_pattern = '^\\s*\\[(?P<host>.*)\\]'
host_list = [{'name': 'all', 'children': [{'name': 'all'}]}]
if File.if_file_exists(ansible_hosts):
host_dic = {'name': File.get_file_name(ansible_hosts), 'childr... | Ansible | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ansible:
def get_group():
"""返回 ansible hosts group"""
<|body_0|>
def get_hosts():
"""返回 ansible hosts file"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ansible_hosts = get_value('ansible', 'ansible_host_path')
re_pattern = '^\\s*\\[(?P<h... | stack_v2_sparse_classes_10k_train_007116 | 2,028 | no_license | [
{
"docstring": "返回 ansible hosts group",
"name": "get_group",
"signature": "def get_group()"
},
{
"docstring": "返回 ansible hosts file",
"name": "get_hosts",
"signature": "def get_hosts()"
}
] | 2 | stack_v2_sparse_classes_30k_train_000904 | Implement the Python class `Ansible` described below.
Class description:
Implement the Ansible class.
Method signatures and docstrings:
- def get_group(): 返回 ansible hosts group
- def get_hosts(): 返回 ansible hosts file | Implement the Python class `Ansible` described below.
Class description:
Implement the Ansible class.
Method signatures and docstrings:
- def get_group(): 返回 ansible hosts group
- def get_hosts(): 返回 ansible hosts file
<|skeleton|>
class Ansible:
def get_group():
"""返回 ansible hosts group"""
<|b... | 60e9481ab84628cf817fde1c52f4a15d5085e503 | <|skeleton|>
class Ansible:
def get_group():
"""返回 ansible hosts group"""
<|body_0|>
def get_hosts():
"""返回 ansible hosts file"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Ansible:
def get_group():
"""返回 ansible hosts group"""
ansible_hosts = get_value('ansible', 'ansible_host_path')
re_pattern = '^\\s*\\[(?P<host>.*)\\]'
host_list = [{'name': 'all', 'children': [{'name': 'all'}]}]
if File.if_file_exists(ansible_hosts):
host_d... | the_stack_v2_python_sparse | common/ansible.py | qt-pay/python-devops | train | 0 | |
d565910d68cffc62b4548fa3136756275666f185 | [
"self.max_document_length = max_document_length\nself.min_frequency = min_frequency\nself.vocabulary = {'__PADDING__': 0, '__UNK__': 1}\nself.reverse_vocab = {0: '__PADDING__', 1: '__UNK__'}\nself.length = 2\nself.tokenizer_fn = tokenizer_fn\nself.word_freq = {'__PADDING__': -1, '__UNK__': 0}",
"for line in strs:... | <|body_start_0|>
self.max_document_length = max_document_length
self.min_frequency = min_frequency
self.vocabulary = {'__PADDING__': 0, '__UNK__': 1}
self.reverse_vocab = {0: '__PADDING__', 1: '__UNK__'}
self.length = 2
self.tokenizer_fn = tokenizer_fn
self.word_f... | 词表处理器 | TFVocabProcessor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFVocabProcessor:
"""词表处理器"""
def __init__(self, max_document_length, min_frequency=0, tokenizer_fn=None):
"""初始化 Args: max_document_length: 最长序列长度,不足长度自动padding min_frequency: 最小频次,小于等于该值词语抛弃,用UNK替代 tokenize_fn: 切分函数,输入是字符串,输出是list,yield方式返回"""
<|body_0|>
def _tokenizer... | stack_v2_sparse_classes_10k_train_007117 | 3,309 | permissive | [
{
"docstring": "初始化 Args: max_document_length: 最长序列长度,不足长度自动padding min_frequency: 最小频次,小于等于该值词语抛弃,用UNK替代 tokenize_fn: 切分函数,输入是字符串,输出是list,yield方式返回",
"name": "__init__",
"signature": "def __init__(self, max_document_length, min_frequency=0, tokenizer_fn=None)"
},
{
"docstring": "按空格切分,语料需要事先处理好... | 6 | stack_v2_sparse_classes_30k_train_000729 | Implement the Python class `TFVocabProcessor` described below.
Class description:
词表处理器
Method signatures and docstrings:
- def __init__(self, max_document_length, min_frequency=0, tokenizer_fn=None): 初始化 Args: max_document_length: 最长序列长度,不足长度自动padding min_frequency: 最小频次,小于等于该值词语抛弃,用UNK替代 tokenize_fn: 切分函数,输入是字符串,输出... | Implement the Python class `TFVocabProcessor` described below.
Class description:
词表处理器
Method signatures and docstrings:
- def __init__(self, max_document_length, min_frequency=0, tokenizer_fn=None): 初始化 Args: max_document_length: 最长序列长度,不足长度自动padding min_frequency: 最小频次,小于等于该值词语抛弃,用UNK替代 tokenize_fn: 切分函数,输入是字符串,输出... | c4423c2625c398f5a93c747f3516f378b31ece46 | <|skeleton|>
class TFVocabProcessor:
"""词表处理器"""
def __init__(self, max_document_length, min_frequency=0, tokenizer_fn=None):
"""初始化 Args: max_document_length: 最长序列长度,不足长度自动padding min_frequency: 最小频次,小于等于该值词语抛弃,用UNK替代 tokenize_fn: 切分函数,输入是字符串,输出是list,yield方式返回"""
<|body_0|>
def _tokenizer... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TFVocabProcessor:
"""词表处理器"""
def __init__(self, max_document_length, min_frequency=0, tokenizer_fn=None):
"""初始化 Args: max_document_length: 最长序列长度,不足长度自动padding min_frequency: 最小频次,小于等于该值词语抛弃,用UNK替代 tokenize_fn: 切分函数,输入是字符串,输出是list,yield方式返回"""
self.max_document_length = max_document_len... | the_stack_v2_python_sparse | utils/tf_vocab_processor.py | snowhws/deeplearning | train | 10 |
f609d5e7c1662b2ab545b7b059d1819d4fa51147 | [
"self.size = 0\nself.val2index = dict()\nself.index2val = dict()",
"if val not in self.val2index:\n self.size += 1\n self.index2val[self.size] = val\n self.val2index[val] = self.size\n return True\nelse:\n return False",
"if val in self.val2index:\n index = self.val2index[val]\n lastVal = s... | <|body_start_0|>
self.size = 0
self.val2index = dict()
self.index2val = dict()
<|end_body_0|>
<|body_start_1|>
if val not in self.val2index:
self.size += 1
self.index2val[self.size] = val
self.val2index[val] = self.size
return True
... | RandomizedSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_007118 | 1,697 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool",
"name": "insert",
"signature": ... | 4 | null | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the set. Returns true if the set did not already contain the specif... | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the set. Returns true if the set did not already contain the specif... | 2c3dbcbcb20cfdb276c0886e0193ef42551c5747 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
self.size = 0
self.val2index = dict()
self.index2val = dict()
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. ... | the_stack_v2_python_sparse | 380-Insert-Delete-GetRandom-O(1)/Solution.py | Lucces/leetcode | train | 0 | |
32386b116366ad506499352b7802573b8a14b170 | [
"self._hass = hass\nself._recp_nrs = recp_nrs\nself._signal_cli_rest_api = signal_cli_rest_api",
"_LOGGER.debug('Sending signal message')\ndata = kwargs.get(ATTR_DATA)\ntry:\n data = DATA_SCHEMA(data)\nexcept vol.Invalid as ex:\n _LOGGER.error('Invalid message data: %s', ex)\n raise ex\nfilenames = self.... | <|body_start_0|>
self._hass = hass
self._recp_nrs = recp_nrs
self._signal_cli_rest_api = signal_cli_rest_api
<|end_body_0|>
<|body_start_1|>
_LOGGER.debug('Sending signal message')
data = kwargs.get(ATTR_DATA)
try:
data = DATA_SCHEMA(data)
except vol.... | Implement the notification service for SignalMessenger. | SignalNotificationService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignalNotificationService:
"""Implement the notification service for SignalMessenger."""
def __init__(self, hass: HomeAssistant, recp_nrs: list[str], signal_cli_rest_api: SignalCliRestApi) -> None:
"""Initialize the service."""
<|body_0|>
def send_message(self, message: ... | stack_v2_sparse_classes_10k_train_007119 | 5,525 | permissive | [
{
"docstring": "Initialize the service.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, recp_nrs: list[str], signal_cli_rest_api: SignalCliRestApi) -> None"
},
{
"docstring": "Send a message to a one or more recipients. Additionally a file can be attached.",
"name... | 4 | null | Implement the Python class `SignalNotificationService` described below.
Class description:
Implement the notification service for SignalMessenger.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, recp_nrs: list[str], signal_cli_rest_api: SignalCliRestApi) -> None: Initialize the service.
- ... | Implement the Python class `SignalNotificationService` described below.
Class description:
Implement the notification service for SignalMessenger.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, recp_nrs: list[str], signal_cli_rest_api: SignalCliRestApi) -> None: Initialize the service.
- ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SignalNotificationService:
"""Implement the notification service for SignalMessenger."""
def __init__(self, hass: HomeAssistant, recp_nrs: list[str], signal_cli_rest_api: SignalCliRestApi) -> None:
"""Initialize the service."""
<|body_0|>
def send_message(self, message: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SignalNotificationService:
"""Implement the notification service for SignalMessenger."""
def __init__(self, hass: HomeAssistant, recp_nrs: list[str], signal_cli_rest_api: SignalCliRestApi) -> None:
"""Initialize the service."""
self._hass = hass
self._recp_nrs = recp_nrs
s... | the_stack_v2_python_sparse | homeassistant/components/signal_messenger/notify.py | home-assistant/core | train | 35,501 |
1e611737a52ac21b9885d3d4a26c8c3de1a43cd7 | [
"global _SESSIONS\nif not _SESSIONS:\n from evennia.server.sessionhandler import SESSIONS as _SESSIONS\nif ev_channel:\n channel = search.channel_search(ev_channel)\n if not channel:\n raise RuntimeError(\"Evennia Channel '%s' not found.\" % ev_channel)\n channel = channel[0]\n self.db.ev_chan... | <|body_start_0|>
global _SESSIONS
if not _SESSIONS:
from evennia.server.sessionhandler import SESSIONS as _SESSIONS
if ev_channel:
channel = search.channel_search(ev_channel)
if not channel:
raise RuntimeError("Evennia Channel '%s' not found." ... | An RSS relayer. The RSS protocol itself runs a ticker to update its feed at regular intervals. | RSSBot | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RSSBot:
"""An RSS relayer. The RSS protocol itself runs a ticker to update its feed at regular intervals."""
def start(self, ev_channel=None, rss_url=None, rss_rate=None):
"""Start by telling the portal to start a new RSS session Args: ev_channel (str): Key of the Evennia channel to ... | stack_v2_sparse_classes_10k_train_007120 | 13,744 | permissive | [
{
"docstring": "Start by telling the portal to start a new RSS session Args: ev_channel (str): Key of the Evennia channel to connect to. rss_url (str): Full URL to the RSS feed to subscribe to. rss_update_rate (int): How often for the feedreader to update. Raises: RuntimeError: If `ev_channel` does not exist.",... | 2 | stack_v2_sparse_classes_30k_train_000022 | Implement the Python class `RSSBot` described below.
Class description:
An RSS relayer. The RSS protocol itself runs a ticker to update its feed at regular intervals.
Method signatures and docstrings:
- def start(self, ev_channel=None, rss_url=None, rss_rate=None): Start by telling the portal to start a new RSS sessi... | Implement the Python class `RSSBot` described below.
Class description:
An RSS relayer. The RSS protocol itself runs a ticker to update its feed at regular intervals.
Method signatures and docstrings:
- def start(self, ev_channel=None, rss_url=None, rss_rate=None): Start by telling the portal to start a new RSS sessi... | 384d08f9d877c7ad758292822e6f04292fdad047 | <|skeleton|>
class RSSBot:
"""An RSS relayer. The RSS protocol itself runs a ticker to update its feed at regular intervals."""
def start(self, ev_channel=None, rss_url=None, rss_rate=None):
"""Start by telling the portal to start a new RSS session Args: ev_channel (str): Key of the Evennia channel to ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RSSBot:
"""An RSS relayer. The RSS protocol itself runs a ticker to update its feed at regular intervals."""
def start(self, ev_channel=None, rss_url=None, rss_rate=None):
"""Start by telling the portal to start a new RSS session Args: ev_channel (str): Key of the Evennia channel to connect to. r... | the_stack_v2_python_sparse | evennia/players/bots.py | robbintt/evennia | train | 1 |
c228545508f8bd41e887a0aaacb2167d5bc5ea39 | [
"super(Triangle, self).__init__(element_id, unit_length)\nassert size in range(3)\nself.size = size",
"super(Triangle, self).init(points)\nif self.element_id in ['1', '2']:\n self.segments += [Segment(p1=self.points[i], p2=self.segments[(i + 1) % 3].midpoint) for i in range(3)]",
"self.state = position // AN... | <|body_start_0|>
super(Triangle, self).__init__(element_id, unit_length)
assert size in range(3)
self.size = size
<|end_body_0|>
<|body_start_1|>
super(Triangle, self).init(points)
if self.element_id in ['1', '2']:
self.segments += [Segment(p1=self.points[i], p2=self... | Class for triangle. Note that point0 is right angle vertex. | Triangle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Triangle:
"""Class for triangle. Note that point0 is right angle vertex."""
def __init__(self, element_id, size=0, unit_length=0.0):
"""Input: size: 0 means small, 1 means medium, 2 means large"""
<|body_0|>
def init(self, points):
"""For triangle, I think we sho... | stack_v2_sparse_classes_10k_train_007121 | 17,615 | permissive | [
{
"docstring": "Input: size: 0 means small, 1 means medium, 2 means large",
"name": "__init__",
"signature": "def __init__(self, element_id, size=0, unit_length=0.0)"
},
{
"docstring": "For triangle, I think we should add more segments.",
"name": "init",
"signature": "def init(self, poin... | 6 | stack_v2_sparse_classes_30k_train_001921 | Implement the Python class `Triangle` described below.
Class description:
Class for triangle. Note that point0 is right angle vertex.
Method signatures and docstrings:
- def __init__(self, element_id, size=0, unit_length=0.0): Input: size: 0 means small, 1 means medium, 2 means large
- def init(self, points): For tri... | Implement the Python class `Triangle` described below.
Class description:
Class for triangle. Note that point0 is right angle vertex.
Method signatures and docstrings:
- def __init__(self, element_id, size=0, unit_length=0.0): Input: size: 0 means small, 1 means medium, 2 means large
- def init(self, points): For tri... | dcc26a99343e7d29199662ef3c9bf63f29513381 | <|skeleton|>
class Triangle:
"""Class for triangle. Note that point0 is right angle vertex."""
def __init__(self, element_id, size=0, unit_length=0.0):
"""Input: size: 0 means small, 1 means medium, 2 means large"""
<|body_0|>
def init(self, points):
"""For triangle, I think we sho... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Triangle:
"""Class for triangle. Note that point0 is right angle vertex."""
def __init__(self, element_id, size=0, unit_length=0.0):
"""Input: size: 0 means small, 1 means medium, 2 means large"""
super(Triangle, self).__init__(element_id, unit_length)
assert size in range(3)
... | the_stack_v2_python_sparse | normal_tangram/tangram_element.py | Wuziyi616/Artificial_Intelligence_Project1 | train | 12 |
d2dc697b39b91d66ff8468df872febc845ed19ad | [
"super().__init__()\nself.in_channels = in_channels\nself.out_channels = out_channels\nself.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, **kwargs)\nself.bn = nn.BatchNorm2d(out_channels)\nself.relu = nn.ReLU(inplace=True)",
"x = self.conv(features)\nx = self.bn(x)\nx = self.relu(x)\nreturn... | <|body_start_0|>
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, **kwargs)
self.bn = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
<|end_body_0|>
... | BasicBlock2D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicBlock2D:
def __init__(self, in_channels, out_channels, **kwargs):
"""Initializes convolutional block Args: in_channels: int, Number of input channels out_channels: int, Number of output channels **kwargs: Dict, Extra arguments for nn.Conv2d"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_10k_train_007122 | 1,038 | permissive | [
{
"docstring": "Initializes convolutional block Args: in_channels: int, Number of input channels out_channels: int, Number of output channels **kwargs: Dict, Extra arguments for nn.Conv2d",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels, **kwargs)"
},
{
"docstring... | 2 | stack_v2_sparse_classes_30k_train_002708 | Implement the Python class `BasicBlock2D` described below.
Class description:
Implement the BasicBlock2D class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, **kwargs): Initializes convolutional block Args: in_channels: int, Number of input channels out_channels: int, Number of out... | Implement the Python class `BasicBlock2D` described below.
Class description:
Implement the BasicBlock2D class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, **kwargs): Initializes convolutional block Args: in_channels: int, Number of input channels out_channels: int, Number of out... | a904f61dffee3d4ba55fabbce7f4207a016fae0e | <|skeleton|>
class BasicBlock2D:
def __init__(self, in_channels, out_channels, **kwargs):
"""Initializes convolutional block Args: in_channels: int, Number of input channels out_channels: int, Number of output channels **kwargs: Dict, Extra arguments for nn.Conv2d"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BasicBlock2D:
def __init__(self, in_channels, out_channels, **kwargs):
"""Initializes convolutional block Args: in_channels: int, Number of input channels out_channels: int, Number of output channels **kwargs: Dict, Extra arguments for nn.Conv2d"""
super().__init__()
self.in_channels =... | the_stack_v2_python_sparse | pcdet/models/model_utils/basic_block_2d.py | chenyilun95/DSGN2 | train | 65 | |
cb43760b3ed69ffd8414e0397ccf4b2895c838fb | [
"logger.info('Reading zipcodes from %s', filename)\nwith open(filename, 'r') as f:\n reader = csv.reader(f, delimiter=cls.DELIMITER)\n zipcodes = dict(((zipcode, (float(latitude), float(longitude))) for zipcode, latitude, longitude in reader))\nlogger.info('Loaded %d zipcodes', len(zipcodes))\nreturn zipcodes... | <|body_start_0|>
logger.info('Reading zipcodes from %s', filename)
with open(filename, 'r') as f:
reader = csv.reader(f, delimiter=cls.DELIMITER)
zipcodes = dict(((zipcode, (float(latitude), float(longitude))) for zipcode, latitude, longitude in reader))
logger.info('Load... | Helper class for storage of geocoded zipcode data in a CSV file. Each line in the file is: zipcode,latitude_degrees,longitude_degrees | GeocodedZipCodeCsv | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeocodedZipCodeCsv:
"""Helper class for storage of geocoded zipcode data in a CSV file. Each line in the file is: zipcode,latitude_degrees,longitude_degrees"""
def read(cls, filename):
"""Returns dictionary of zipcode, (latitude, longitude) pairs."""
<|body_0|>
def write... | stack_v2_sparse_classes_10k_train_007123 | 8,013 | permissive | [
{
"docstring": "Returns dictionary of zipcode, (latitude, longitude) pairs.",
"name": "read",
"signature": "def read(cls, filename)"
},
{
"docstring": "Writes series of zipcode, (latitude, longitude) pairs to file.",
"name": "write",
"signature": "def write(cls, f, data)"
}
] | 2 | null | Implement the Python class `GeocodedZipCodeCsv` described below.
Class description:
Helper class for storage of geocoded zipcode data in a CSV file. Each line in the file is: zipcode,latitude_degrees,longitude_degrees
Method signatures and docstrings:
- def read(cls, filename): Returns dictionary of zipcode, (latitud... | Implement the Python class `GeocodedZipCodeCsv` described below.
Class description:
Helper class for storage of geocoded zipcode data in a CSV file. Each line in the file is: zipcode,latitude_degrees,longitude_degrees
Method signatures and docstrings:
- def read(cls, filename): Returns dictionary of zipcode, (latitud... | 7c63c31fd6bb95ed4f7d368f1e1252175f0c71ca | <|skeleton|>
class GeocodedZipCodeCsv:
"""Helper class for storage of geocoded zipcode data in a CSV file. Each line in the file is: zipcode,latitude_degrees,longitude_degrees"""
def read(cls, filename):
"""Returns dictionary of zipcode, (latitude, longitude) pairs."""
<|body_0|>
def write... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GeocodedZipCodeCsv:
"""Helper class for storage of geocoded zipcode data in a CSV file. Each line in the file is: zipcode,latitude_degrees,longitude_degrees"""
def read(cls, filename):
"""Returns dictionary of zipcode, (latitude, longitude) pairs."""
logger.info('Reading zipcodes from %s'... | the_stack_v2_python_sparse | cfgov/housing_counselor/geocoder.py | raft-tech/cfgov-refresh | train | 4 |
304acb7016bb103c0a2c3224b7ad2c9b43df6cc5 | [
"if not isinstance(existing_channels, ChannelMontageTuple):\n existing_channels = ChannelMontageTuple(existing_channels, True)\nif not isinstance(channels_required, ChannelMontageTuple):\n channels_required = ChannelMontageTuple(channels_required, True)\nself.channels_required = channels_required\nself.existi... | <|body_start_0|>
if not isinstance(existing_channels, ChannelMontageTuple):
existing_channels = ChannelMontageTuple(existing_channels, True)
if not isinstance(channels_required, ChannelMontageTuple):
channels_required = ChannelMontageTuple(channels_required, True)
self.ch... | TODO | ChannelMontageCreator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChannelMontageCreator:
"""TODO"""
def __init__(self, existing_channels, channels_required, allow_missing=False):
"""TODO"""
<|body_0|>
def _create_montage(channel_data, channels, montage_to_create):
"""TODO Args: channel_data: channels: montage_to_create: Returns... | stack_v2_sparse_classes_10k_train_007124 | 7,729 | permissive | [
{
"docstring": "TODO",
"name": "__init__",
"signature": "def __init__(self, existing_channels, channels_required, allow_missing=False)"
},
{
"docstring": "TODO Args: channel_data: channels: montage_to_create: Returns:",
"name": "_create_montage",
"signature": "def _create_montage(channel... | 3 | stack_v2_sparse_classes_30k_train_005637 | Implement the Python class `ChannelMontageCreator` described below.
Class description:
TODO
Method signatures and docstrings:
- def __init__(self, existing_channels, channels_required, allow_missing=False): TODO
- def _create_montage(channel_data, channels, montage_to_create): TODO Args: channel_data: channels: monta... | Implement the Python class `ChannelMontageCreator` described below.
Class description:
TODO
Method signatures and docstrings:
- def __init__(self, existing_channels, channels_required, allow_missing=False): TODO
- def _create_montage(channel_data, channels, montage_to_create): TODO Args: channel_data: channels: monta... | f7c8e3f1368f43226872a69b0fbb8c29990e4bd9 | <|skeleton|>
class ChannelMontageCreator:
"""TODO"""
def __init__(self, existing_channels, channels_required, allow_missing=False):
"""TODO"""
<|body_0|>
def _create_montage(channel_data, channels, montage_to_create):
"""TODO Args: channel_data: channels: montage_to_create: Returns... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChannelMontageCreator:
"""TODO"""
def __init__(self, existing_channels, channels_required, allow_missing=False):
"""TODO"""
if not isinstance(existing_channels, ChannelMontageTuple):
existing_channels = ChannelMontageTuple(existing_channels, True)
if not isinstance(cha... | the_stack_v2_python_sparse | utime/io/channels/montage_creator.py | jennynanap/U-Time | train | 0 |
e15b397f260425437358783b99127347d9fdcb3c | [
"client_obj = Client(client_id=client_id, client_name=client_name, client_cnp=client_cnp)\ntry:\n self._repository.insert(client_obj)\nexcept RepositoryException as e:\n Session.set_message(e.message)\n return False\nreturn True",
"client = self._repository.select_by_id(client_id)\nif not client:\n Se... | <|body_start_0|>
client_obj = Client(client_id=client_id, client_name=client_name, client_cnp=client_cnp)
try:
self._repository.insert(client_obj)
except RepositoryException as e:
Session.set_message(e.message)
return False
return True
<|end_body_0|>
... | ClientController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientController:
def store(self, client_id, client_name, client_cnp):
"""Store a new client Input: instance - an object Output: True - success False - failure Raises:"""
<|body_0|>
def update(self, client_id, client_name, client_cnp):
"""Update a client by id Time c... | stack_v2_sparse_classes_10k_train_007125 | 3,407 | permissive | [
{
"docstring": "Store a new client Input: instance - an object Output: True - success False - failure Raises:",
"name": "store",
"signature": "def store(self, client_id, client_name, client_cnp)"
},
{
"docstring": "Update a client by id Time complexity: O(1) Input: instance - an object Output: T... | 3 | stack_v2_sparse_classes_30k_train_001701 | Implement the Python class `ClientController` described below.
Class description:
Implement the ClientController class.
Method signatures and docstrings:
- def store(self, client_id, client_name, client_cnp): Store a new client Input: instance - an object Output: True - success False - failure Raises:
- def update(se... | Implement the Python class `ClientController` described below.
Class description:
Implement the ClientController class.
Method signatures and docstrings:
- def store(self, client_id, client_name, client_cnp): Store a new client Input: instance - an object Output: True - success False - failure Raises:
- def update(se... | 9496cb63594dcf1cc2cec8650b8eee603f85fdab | <|skeleton|>
class ClientController:
def store(self, client_id, client_name, client_cnp):
"""Store a new client Input: instance - an object Output: True - success False - failure Raises:"""
<|body_0|>
def update(self, client_id, client_name, client_cnp):
"""Update a client by id Time c... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClientController:
def store(self, client_id, client_name, client_cnp):
"""Store a new client Input: instance - an object Output: True - success False - failure Raises:"""
client_obj = Client(client_id=client_id, client_name=client_name, client_cnp=client_cnp)
try:
self._rep... | the_stack_v2_python_sparse | fundamentals-of-programming/labs/lab_5-11/controller/client.py | vampy/university | train | 1 | |
230f5f17b1dc1a7d637581d25d54f89adaa38d6f | [
"super(GRUCell, self).__init__()\nself.hidden = nn.CellList([nn.Dense(dim_hid, dim_hid, has_bias=bias) for _ in range(3)])\nself.input = nn.CellList([nn.Dense(dim_in, dim_hid, has_bias=bias) for _ in range(3)])\nself.sigmoid = nn.Sigmoid()\nself.tanh = nn.Tanh()",
"r = self.sigmoid(self.input[0](inputs) + self.hi... | <|body_start_0|>
super(GRUCell, self).__init__()
self.hidden = nn.CellList([nn.Dense(dim_hid, dim_hid, has_bias=bias) for _ in range(3)])
self.input = nn.CellList([nn.Dense(dim_in, dim_hid, has_bias=bias) for _ in range(3)])
self.sigmoid = nn.Sigmoid()
self.tanh = nn.Tanh()
<|end... | GRUCell | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRUCell:
def __init__(self, dim_in: int, dim_hid: int, bias: bool=True):
"""Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional adding a bias term or not. The default is True."""
<|body_0|>
def construct(self, i... | stack_v2_sparse_classes_10k_train_007126 | 9,199 | permissive | [
{
"docstring": "Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional adding a bias term or not. The default is True.",
"name": "__init__",
"signature": "def __init__(self, dim_in: int, dim_hid: int, bias: bool=True)"
},
{
"docstring"... | 2 | null | Implement the Python class `GRUCell` described below.
Class description:
Implement the GRUCell class.
Method signatures and docstrings:
- def __init__(self, dim_in: int, dim_hid: int, bias: bool=True): Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional ... | Implement the Python class `GRUCell` described below.
Class description:
Implement the GRUCell class.
Method signatures and docstrings:
- def __init__(self, dim_in: int, dim_hid: int, bias: bool=True): Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional ... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class GRUCell:
def __init__(self, dim_in: int, dim_hid: int, bias: bool=True):
"""Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional adding a bias term or not. The default is True."""
<|body_0|>
def construct(self, i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GRUCell:
def __init__(self, dim_in: int, dim_hid: int, bias: bool=True):
"""Parameters ---------- dim_in : int input dimension. dim_hid : int dimension of hidden layers. bias : bool, optional adding a bias term or not. The default is True."""
super(GRUCell, self).__init__()
self.hidden... | the_stack_v2_python_sparse | research/gnn/nri-mpm/models/base.py | mindspore-ai/models | train | 301 | |
2316e308729ea728882c3d29a2257666cf8bd79e | [
"logger.info('Kallisto Indexer')\nTool.__init__(self)\nif configuration is None:\n configuration = {}\nself.configuration.update(configuration)",
"command_line = 'kallisto index -i ' + cdna_idx_file + ' ' + cdna_file_loc\nlogger.info('command : ' + command_line)\ntry:\n args = shlex.split(command_line)\n ... | <|body_start_0|>
logger.info('Kallisto Indexer')
Tool.__init__(self)
if configuration is None:
configuration = {}
self.configuration.update(configuration)
<|end_body_0|>
<|body_start_1|>
command_line = 'kallisto index -i ' + cdna_idx_file + ' ' + cdna_file_loc
... | Tool for running indexers over a genome FASTA file | kallistoIndexerTool | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class kallistoIndexerTool:
"""Tool for running indexers over a genome FASTA file"""
def __init__(self, configuration=None):
"""Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be c... | stack_v2_sparse_classes_10k_train_007127 | 4,323 | permissive | [
{
"docstring": "Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which are specific to each Tool.",
"name": "__init__",
"signature": "def __init__(self, configuration=None)"
},... | 3 | stack_v2_sparse_classes_30k_train_004490 | Implement the Python class `kallistoIndexerTool` described below.
Class description:
Tool for running indexers over a genome FASTA file
Method signatures and docstrings:
- def __init__(self, configuration=None): Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary contai... | Implement the Python class `kallistoIndexerTool` described below.
Class description:
Tool for running indexers over a genome FASTA file
Method signatures and docstrings:
- def __init__(self, configuration=None): Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary contai... | 50c7115c0c1a6af48dc34f275e469d1b9eb02999 | <|skeleton|>
class kallistoIndexerTool:
"""Tool for running indexers over a genome FASTA file"""
def __init__(self, configuration=None):
"""Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be c... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class kallistoIndexerTool:
"""Tool for running indexers over a genome FASTA file"""
def __init__(self, configuration=None):
"""Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, w... | the_stack_v2_python_sparse | tool/kallisto_indexer.py | Multiscale-Genomics/mg-process-fastq | train | 2 |
69ef8b95244ba262646f9a23e85ee544d12ee7ab | [
"grammar = nltk.data.load('./TestFiles/pcfg.pcfg')\nwith open('./TestFiles/sentences', 'r') as sentences:\n test_sentences = sentences.readlines()\nwith open('./TestFiles/trees', 'r') as trees:\n expected_trees = trees.readlines()\nparser = PCKY(grammar)\nfor sentence, expected in zip(test_sentences, expected... | <|body_start_0|>
grammar = nltk.data.load('./TestFiles/pcfg.pcfg')
with open('./TestFiles/sentences', 'r') as sentences:
test_sentences = sentences.readlines()
with open('./TestFiles/trees', 'r') as trees:
expected_trees = trees.readlines()
parser = PCKY(grammar)
... | This class contains tests for the PCKY class | TestPCKY | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPCKY:
"""This class contains tests for the PCKY class"""
def test_parse(self):
"""Test grammar parse example :return: void"""
<|body_0|>
def test_unk(self):
"""Test unknown words :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
gramm... | stack_v2_sparse_classes_10k_train_007128 | 5,674 | no_license | [
{
"docstring": "Test grammar parse example :return: void",
"name": "test_parse",
"signature": "def test_parse(self)"
},
{
"docstring": "Test unknown words :return:",
"name": "test_unk",
"signature": "def test_unk(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000322 | Implement the Python class `TestPCKY` described below.
Class description:
This class contains tests for the PCKY class
Method signatures and docstrings:
- def test_parse(self): Test grammar parse example :return: void
- def test_unk(self): Test unknown words :return: | Implement the Python class `TestPCKY` described below.
Class description:
This class contains tests for the PCKY class
Method signatures and docstrings:
- def test_parse(self): Test grammar parse example :return: void
- def test_unk(self): Test unknown words :return:
<|skeleton|>
class TestPCKY:
"""This class co... | 7af7b357347ed526de7a3d6f16652843d214dcbf | <|skeleton|>
class TestPCKY:
"""This class contains tests for the PCKY class"""
def test_parse(self):
"""Test grammar parse example :return: void"""
<|body_0|>
def test_unk(self):
"""Test unknown words :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestPCKY:
"""This class contains tests for the PCKY class"""
def test_parse(self):
"""Test grammar parse example :return: void"""
grammar = nltk.data.load('./TestFiles/pcfg.pcfg')
with open('./TestFiles/sentences', 'r') as sentences:
test_sentences = sentences.readline... | the_stack_v2_python_sparse | Parser/pcky.py | zoew2/Projects | train | 0 |
d6d013ecf9167030c28e20f045494d47640981d2 | [
"n = len(nums)\nans = 0\nfor i in range(n):\n prod = 1\n for j in range(i, n):\n prod *= nums[j]\n if prod >= k:\n continue\n else:\n ans += 1\nreturn ans",
"if k <= 1:\n return 0\nn = len(nums)\nl = 0\nprod = 1\nans = 0\nfor r in range(n):\n prod *= nums[r]\... | <|body_start_0|>
n = len(nums)
ans = 0
for i in range(n):
prod = 1
for j in range(i, n):
prod *= nums[j]
if prod >= k:
continue
else:
ans += 1
return ans
<|end_body_0|>
<|body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
"""Brute Force, Time: O(n^2), Space: O(1)"""
<|body_0|>
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
"""Sliding Window, Time: O(n), Space: O(1)"""
<|bod... | stack_v2_sparse_classes_10k_train_007129 | 1,521 | no_license | [
{
"docstring": "Brute Force, Time: O(n^2), Space: O(1)",
"name": "numSubarrayProductLessThanK",
"signature": "def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int"
},
{
"docstring": "Sliding Window, Time: O(n), Space: O(1)",
"name": "numSubarrayProductLessThanK",
"signat... | 2 | stack_v2_sparse_classes_30k_train_001313 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: Brute Force, Time: O(n^2), Space: O(1)
- def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: Brute Force, Time: O(n^2), Space: O(1)
- def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> ... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
"""Brute Force, Time: O(n^2), Space: O(1)"""
<|body_0|>
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
"""Sliding Window, Time: O(n), Space: O(1)"""
<|bod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
"""Brute Force, Time: O(n^2), Space: O(1)"""
n = len(nums)
ans = 0
for i in range(n):
prod = 1
for j in range(i, n):
prod *= nums[j]
if prod ... | the_stack_v2_python_sparse | python/713-Subarray Product Less Than K.py | cwza/leetcode | train | 0 | |
4c63fbd7c64251ffc4ab2e8b269460ee951a99fd | [
"queryset = model_admin.queryset(request)\nresults = queryset.values_list('ip__country').order_by('ip__country').distinct()\ndata = ((code[0] or 'none', dict(COUNTRIES).get(code[0], _('None'))) for code in results if code[0] not in ['None', ''])\nreturn data",
"value = self.value()\nif value == 'none':\n retur... | <|body_start_0|>
queryset = model_admin.queryset(request)
results = queryset.values_list('ip__country').order_by('ip__country').distinct()
data = ((code[0] or 'none', dict(COUNTRIES).get(code[0], _('None'))) for code in results if code[0] not in ['None', ''])
return data
<|end_body_0|>
... | Filtre admin des pays des IP des accès | AccessIPCountryFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessIPCountryFilter:
"""Filtre admin des pays des IP des accès"""
def lookups(self, request, model_admin):
"""Renvoyer les options de pays"""
<|body_0|>
def queryset(self, request, queryset):
"""Filtrer le queryset par le pays sélectionné"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_007130 | 1,802 | no_license | [
{
"docstring": "Renvoyer les options de pays",
"name": "lookups",
"signature": "def lookups(self, request, model_admin)"
},
{
"docstring": "Filtrer le queryset par le pays sélectionné",
"name": "queryset",
"signature": "def queryset(self, request, queryset)"
}
] | 2 | null | Implement the Python class `AccessIPCountryFilter` described below.
Class description:
Filtre admin des pays des IP des accès
Method signatures and docstrings:
- def lookups(self, request, model_admin): Renvoyer les options de pays
- def queryset(self, request, queryset): Filtrer le queryset par le pays sélectionné | Implement the Python class `AccessIPCountryFilter` described below.
Class description:
Filtre admin des pays des IP des accès
Method signatures and docstrings:
- def lookups(self, request, model_admin): Renvoyer les options de pays
- def queryset(self, request, queryset): Filtrer le queryset par le pays sélectionné
... | 8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7 | <|skeleton|>
class AccessIPCountryFilter:
"""Filtre admin des pays des IP des accès"""
def lookups(self, request, model_admin):
"""Renvoyer les options de pays"""
<|body_0|>
def queryset(self, request, queryset):
"""Filtrer le queryset par le pays sélectionné"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AccessIPCountryFilter:
"""Filtre admin des pays des IP des accès"""
def lookups(self, request, model_admin):
"""Renvoyer les options de pays"""
queryset = model_admin.queryset(request)
results = queryset.values_list('ip__country').order_by('ip__country').distinct()
data = ... | the_stack_v2_python_sparse | scoop/user/access/admin/filters.py | artscoop/scoop | train | 0 |
d169f06c49e9beae3dc4d69b030f5ba9b0cf214c | [
"self.file_select_policy = file_select_policy\nself.file_size = file_size\nself.file_size_policy = file_size_policy\nself.hot_file_window = hot_file_window\nself.nfs_mount_path = nfs_mount_path\nself.num_file_access = num_file_access\nself.source_view_name = source_view_name\nself.uptier_all_files = uptier_all_file... | <|body_start_0|>
self.file_select_policy = file_select_policy
self.file_size = file_size
self.file_size_policy = file_size_policy
self.hot_file_window = hot_file_window
self.nfs_mount_path = nfs_mount_path
self.num_file_access = num_file_access
self.source_view_na... | Implementation of the 'FileUptieringParams' model. File Uptiering Parameters for NAS migration. Attributes: file_select_policy (int): File uptier policy based on file access/modify time. file_size (int): Gives the size criteria to be used for selecting the files to be uptiered. The hot files, which are greater or small... | FileUptieringParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileUptieringParams:
"""Implementation of the 'FileUptieringParams' model. File Uptiering Parameters for NAS migration. Attributes: file_select_policy (int): File uptier policy based on file access/modify time. file_size (int): Gives the size criteria to be used for selecting the files to be upti... | stack_v2_sparse_classes_10k_train_007131 | 4,196 | permissive | [
{
"docstring": "Constructor for the FileUptieringParams class",
"name": "__init__",
"signature": "def __init__(self, file_select_policy=None, file_size=None, file_size_policy=None, hot_file_window=None, nfs_mount_path=None, num_file_access=None, source_view_name=None, uptier_all_files=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_003356 | Implement the Python class `FileUptieringParams` described below.
Class description:
Implementation of the 'FileUptieringParams' model. File Uptiering Parameters for NAS migration. Attributes: file_select_policy (int): File uptier policy based on file access/modify time. file_size (int): Gives the size criteria to be ... | Implement the Python class `FileUptieringParams` described below.
Class description:
Implementation of the 'FileUptieringParams' model. File Uptiering Parameters for NAS migration. Attributes: file_select_policy (int): File uptier policy based on file access/modify time. file_size (int): Gives the size criteria to be ... | 0093194d125fc6746f55b8499da1270c64f473fc | <|skeleton|>
class FileUptieringParams:
"""Implementation of the 'FileUptieringParams' model. File Uptiering Parameters for NAS migration. Attributes: file_select_policy (int): File uptier policy based on file access/modify time. file_size (int): Gives the size criteria to be used for selecting the files to be upti... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FileUptieringParams:
"""Implementation of the 'FileUptieringParams' model. File Uptiering Parameters for NAS migration. Attributes: file_select_policy (int): File uptier policy based on file access/modify time. file_size (int): Gives the size criteria to be used for selecting the files to be uptiered. The hot... | the_stack_v2_python_sparse | cohesity_management_sdk/models/file_uptiering_params.py | hsantoyo2/management-sdk-python | train | 0 |
2befbbdf6cc69112b02c640f885ff35af2e28aa1 | [
"self.x = x\nself.y = y\nself.yaw = yaw\nself.v = v",
"delta = np.clip(delta, -max_steer, max_steer)\nself.x += self.v * np.cos(self.yaw) * dt\nself.y += self.v * np.sin(self.yaw) * dt\nself.yaw += self.v / L * np.tan(delta) * dt\nself.yaw = normalize_angle(self.yaw)\nself.v += acceleration * dt"
] | <|body_start_0|>
self.x = x
self.y = y
self.yaw = yaw
self.v = v
<|end_body_0|>
<|body_start_1|>
delta = np.clip(delta, -max_steer, max_steer)
self.x += self.v * np.cos(self.yaw) * dt
self.y += self.v * np.sin(self.yaw) * dt
self.yaw += self.v / L * np.ta... | State | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class State:
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0):
"""Initialize the state of the vehicle Keyword Arguments: x {float} -- [X-coordinate] (default: {0.0}) y {float} -- [Y-Coordinate] (default: {0.0}) yaw {float} -- [Yaw/heading angle] (default: {0.0}) v {float} -- [velocity] (defaul... | stack_v2_sparse_classes_10k_train_007132 | 5,612 | no_license | [
{
"docstring": "Initialize the state of the vehicle Keyword Arguments: x {float} -- [X-coordinate] (default: {0.0}) y {float} -- [Y-Coordinate] (default: {0.0}) yaw {float} -- [Yaw/heading angle] (default: {0.0}) v {float} -- [velocity] (default: {0.0})",
"name": "__init__",
"signature": "def __init__(s... | 2 | stack_v2_sparse_classes_30k_test_000284 | Implement the Python class `State` described below.
Class description:
Implement the State class.
Method signatures and docstrings:
- def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0): Initialize the state of the vehicle Keyword Arguments: x {float} -- [X-coordinate] (default: {0.0}) y {float} -- [Y-Coordinate] (defau... | Implement the Python class `State` described below.
Class description:
Implement the State class.
Method signatures and docstrings:
- def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0): Initialize the state of the vehicle Keyword Arguments: x {float} -- [X-coordinate] (default: {0.0}) y {float} -- [Y-Coordinate] (defau... | 84388bce6bb8313949e1607782dceed4abf546ea | <|skeleton|>
class State:
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0):
"""Initialize the state of the vehicle Keyword Arguments: x {float} -- [X-coordinate] (default: {0.0}) y {float} -- [Y-Coordinate] (default: {0.0}) yaw {float} -- [Yaw/heading angle] (default: {0.0}) v {float} -- [velocity] (defaul... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class State:
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0):
"""Initialize the state of the vehicle Keyword Arguments: x {float} -- [X-coordinate] (default: {0.0}) y {float} -- [Y-Coordinate] (default: {0.0}) yaw {float} -- [Yaw/heading angle] (default: {0.0}) v {float} -- [velocity] (default: {0.0})"""
... | the_stack_v2_python_sparse | study.py | FernCarrera/Localization | train | 0 | |
6ced01b005d905c3a622fc55d1629cf98e835c1c | [
"super(AudioTextVideoFusion, self).__init__(name=name)\nself._audio_backbone = audio_backbone\nself._audio_model_kwargs = audio_model_kwargs or {}\nself._text_backbone = text_backbone\nself._text_model_kwargs = text_model_kwargs or {}\nself._video_backbone = video_backbone\nself._video_model_kwargs = video_model_kw... | <|body_start_0|>
super(AudioTextVideoFusion, self).__init__(name=name)
self._audio_backbone = audio_backbone
self._audio_model_kwargs = audio_model_kwargs or {}
self._text_backbone = text_backbone
self._text_model_kwargs = text_model_kwargs or {}
self._video_backbone = vi... | Module to fuse audio, text and video for joint embedding learning. | AudioTextVideoFusion | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AudioTextVideoFusion:
"""Module to fuse audio, text and video for joint embedding learning."""
def __init__(self, audio_backbone='resnet18', audio_model_kwargs=None, text_backbone='linear', text_model_kwargs=None, video_backbone='resnet50', video_model_kwargs=None, name='audio_text_video_mod... | stack_v2_sparse_classes_10k_train_007133 | 7,989 | permissive | [
{
"docstring": "Initialize the AudioTextVideoFusion class. Args: audio_backbone: Backbone for audio. audio_model_kwargs: Other specific parameters to pass to the audio module. text_backbone: The base language model name. text_model_kwargs: Other specific parameters to pass to the text module. video_backbone: Th... | 2 | null | Implement the Python class `AudioTextVideoFusion` described below.
Class description:
Module to fuse audio, text and video for joint embedding learning.
Method signatures and docstrings:
- def __init__(self, audio_backbone='resnet18', audio_model_kwargs=None, text_backbone='linear', text_model_kwargs=None, video_back... | Implement the Python class `AudioTextVideoFusion` described below.
Class description:
Module to fuse audio, text and video for joint embedding learning.
Method signatures and docstrings:
- def __init__(self, audio_backbone='resnet18', audio_model_kwargs=None, text_backbone='linear', text_model_kwargs=None, video_back... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class AudioTextVideoFusion:
"""Module to fuse audio, text and video for joint embedding learning."""
def __init__(self, audio_backbone='resnet18', audio_model_kwargs=None, text_backbone='linear', text_model_kwargs=None, video_backbone='resnet50', video_model_kwargs=None, name='audio_text_video_mod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AudioTextVideoFusion:
"""Module to fuse audio, text and video for joint embedding learning."""
def __init__(self, audio_backbone='resnet18', audio_model_kwargs=None, text_backbone='linear', text_model_kwargs=None, video_backbone='resnet50', video_model_kwargs=None, name='audio_text_video_model', **kwargs... | the_stack_v2_python_sparse | vatt/modeling/backbones/multimodal.py | Jimmy-INL/google-research | train | 1 |
3319686966b089812c235acf94d6491e5bc64b7a | [
"if s[-1] == '1':\n return False\ndiff = defaultdict(int)\nfor i, char in enumerate(s):\n diff[i] += diff[i - 1]\n if char == '0' and (i == 0 or diff[i] > 0):\n diff[i + minJump] += 1\n diff[i + maxJump + 1] -= 1\nreturn diff[len(s) - 1] > 0",
"if s[-1] == '1':\n return False\nn = len(s)... | <|body_start_0|>
if s[-1] == '1':
return False
diff = defaultdict(int)
for i, char in enumerate(s):
diff[i] += diff[i - 1]
if char == '0' and (i == 0 or diff[i] > 0):
diff[i + minJump] += 1
diff[i + maxJump + 1] -= 1
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canReach(self, s: str, minJump: int, maxJump: int) -> bool:
"""差分数组区间更新,边遍历边还原数组值 直接更新diff字典的写法"""
<|body_0|>
def canReach2(self, s: str, minJump: int, maxJump: int) -> bool:
"""差分数组区间更新,边遍历边还原数组值 不修改diff 用 curSum 的写法"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_10k_train_007134 | 1,200 | no_license | [
{
"docstring": "差分数组区间更新,边遍历边还原数组值 直接更新diff字典的写法",
"name": "canReach",
"signature": "def canReach(self, s: str, minJump: int, maxJump: int) -> bool"
},
{
"docstring": "差分数组区间更新,边遍历边还原数组值 不修改diff 用 curSum 的写法",
"name": "canReach2",
"signature": "def canReach2(self, s: str, minJump: int, m... | 2 | stack_v2_sparse_classes_30k_train_001652 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canReach(self, s: str, minJump: int, maxJump: int) -> bool: 差分数组区间更新,边遍历边还原数组值 直接更新diff字典的写法
- def canReach2(self, s: str, minJump: int, maxJump: int) -> bool: 差分数组区间更新,边遍历边还... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canReach(self, s: str, minJump: int, maxJump: int) -> bool: 差分数组区间更新,边遍历边还原数组值 直接更新diff字典的写法
- def canReach2(self, s: str, minJump: int, maxJump: int) -> bool: 差分数组区间更新,边遍历边还... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def canReach(self, s: str, minJump: int, maxJump: int) -> bool:
"""差分数组区间更新,边遍历边还原数组值 直接更新diff字典的写法"""
<|body_0|>
def canReach2(self, s: str, minJump: int, maxJump: int) -> bool:
"""差分数组区间更新,边遍历边还原数组值 不修改diff 用 curSum 的写法"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canReach(self, s: str, minJump: int, maxJump: int) -> bool:
"""差分数组区间更新,边遍历边还原数组值 直接更新diff字典的写法"""
if s[-1] == '1':
return False
diff = defaultdict(int)
for i, char in enumerate(s):
diff[i] += diff[i - 1]
if char == '0' and (i =... | the_stack_v2_python_sparse | 22_专题/跳跃游戏/1871. 跳跃游戏-差分范围更新.py | 981377660LMT/algorithm-study | train | 225 | |
5546a8028653a9127c578d207a19c50555507e2c | [
"self.kernel = kernel\nself.current_state = state\nself.results = results\nself.reductions = self.all_states = self.trace = None\nself.new_step_size = None\nself._process_results()",
"if unnest.has_nested(self.kernel, 'reducer'):\n reducers = unnest.get_outermost(self.kernel, 'reducer')\n self.reductions = ... | <|body_start_0|>
self.kernel = kernel
self.current_state = state
self.results = results
self.reductions = self.all_states = self.trace = None
self.new_step_size = None
self._process_results()
<|end_body_0|>
<|body_start_1|>
if unnest.has_nested(self.kernel, 'redu... | Facade around outputs of `step_kernel`. Processes results and extracts useful data for analysis and further sampling. | KernelOutputs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KernelOutputs:
"""Facade around outputs of `step_kernel`. Processes results and extracts useful data for analysis and further sampling."""
def __init__(self, kernel, state, results):
"""Construct `KernelOutputs`. This processes the results, including calling `finalize` on all reducti... | stack_v2_sparse_classes_10k_train_007135 | 3,720 | permissive | [
{
"docstring": "Construct `KernelOutputs`. This processes the results, including calling `finalize` on all reductions. Args: kernel: The `TransitionKernel` which generated the outputs. state: The final chain state as returned by `step_kernel`. results: The final kernel results as returned by `step_kernel`.",
... | 4 | null | Implement the Python class `KernelOutputs` described below.
Class description:
Facade around outputs of `step_kernel`. Processes results and extracts useful data for analysis and further sampling.
Method signatures and docstrings:
- def __init__(self, kernel, state, results): Construct `KernelOutputs`. This processes... | Implement the Python class `KernelOutputs` described below.
Class description:
Facade around outputs of `step_kernel`. Processes results and extracts useful data for analysis and further sampling.
Method signatures and docstrings:
- def __init__(self, kernel, state, results): Construct `KernelOutputs`. This processes... | 42a64ba0d9e0973b1707fcd9b8bd8d14b2d4e3e5 | <|skeleton|>
class KernelOutputs:
"""Facade around outputs of `step_kernel`. Processes results and extracts useful data for analysis and further sampling."""
def __init__(self, kernel, state, results):
"""Construct `KernelOutputs`. This processes the results, including calling `finalize` on all reducti... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KernelOutputs:
"""Facade around outputs of `step_kernel`. Processes results and extracts useful data for analysis and further sampling."""
def __init__(self, kernel, state, results):
"""Construct `KernelOutputs`. This processes the results, including calling `finalize` on all reductions. Args: ke... | the_stack_v2_python_sparse | tensorflow_probability/python/experimental/mcmc/kernel_outputs.py | tensorflow/probability | train | 4,055 |
9aae18ba05fe5c0994b0e5994893120a8b13fbad | [
"nums_sored = sorted(nums)\ni, j = (0, len(nums) - 1)\nwhile i < j:\n if nums[i] == nums_sored[i]:\n i += 1\n elif nums[j] == nums_sored[j]:\n j -= 1\n elif i == j:\n return 0\n else:\n return j - i + 1\nreturn 0",
"left = len(nums)\nright = 0\nstack = []\nfor i in range(le... | <|body_start_0|>
nums_sored = sorted(nums)
i, j = (0, len(nums) - 1)
while i < j:
if nums[i] == nums_sored[i]:
i += 1
elif nums[j] == nums_sored[j]:
j -= 1
elif i == j:
return 0
else:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortest_unsorted_continuous_subarray(self, nums: List[int]) -> bool:
"""求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度"""
<|body_0|>
def shortest_unsorted_continuous_subarray2(self, nums: List[int]) -> bool:
"""求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度"""... | stack_v2_sparse_classes_10k_train_007136 | 2,871 | permissive | [
{
"docstring": "求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度",
"name": "shortest_unsorted_continuous_subarray",
"signature": "def shortest_unsorted_continuous_subarray(self, nums: List[int]) -> bool"
},
{
"docstring": "求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度",
"name": "shortest_unsorted_con... | 2 | stack_v2_sparse_classes_30k_train_006811 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortest_unsorted_continuous_subarray(self, nums: List[int]) -> bool: 求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度
- def shortest_unsorted_continuous_subarray2(self, nums: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortest_unsorted_continuous_subarray(self, nums: List[int]) -> bool: 求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度
- def shortest_unsorted_continuous_subarray2(self, nums: List... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def shortest_unsorted_continuous_subarray(self, nums: List[int]) -> bool:
"""求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度"""
<|body_0|>
def shortest_unsorted_continuous_subarray2(self, nums: List[int]) -> bool:
"""求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def shortest_unsorted_continuous_subarray(self, nums: List[int]) -> bool:
"""求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度"""
nums_sored = sorted(nums)
i, j = (0, len(nums) - 1)
while i < j:
if nums[i] == nums_sored[i]:
i += 1
elif... | the_stack_v2_python_sparse | src/leetcodepython/array/shortest_unsorted_continuous_subarray_581.py | zhangyu345293721/leetcode | train | 101 | |
dc312aa954ab604b6fa2b6584a6586ca2253a8b2 | [
"OptimizerBase.__init__(self, disp)\nself.n_epoch = n_epoch\nself.iter_per_epoch = iter_per_epoch\nself.maxiter = int(self.n_epoch * self.iter_per_epoch)\nself.print_freq = int(self.print_freq * self.iter_per_epoch)\nself.step_rate = step_rate\nself.decay = decay\nself.momentum = momentum\nself.offset = offset",
... | <|body_start_0|>
OptimizerBase.__init__(self, disp)
self.n_epoch = n_epoch
self.iter_per_epoch = iter_per_epoch
self.maxiter = int(self.n_epoch * self.iter_per_epoch)
self.print_freq = int(self.print_freq * self.iter_per_epoch)
self.step_rate = step_rate
self.deca... | A wrapper-class for AdaDelta method from climin library. Requires gradient estimation. | AdaDelta | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdaDelta:
"""A wrapper-class for AdaDelta method from climin library. Requires gradient estimation."""
def __init__(self, disp=False, iter_per_epoch=1, n_epoch=1000, step_rate=1.0, decay=0.9, momentum=0.0, offset=0.0001):
""":param iter_per_epoch: number of iteration per epoch :param... | stack_v2_sparse_classes_10k_train_007137 | 4,677 | no_license | [
{
"docstring": ":param iter_per_epoch: number of iteration per epoch :param n_epoch: maximum number of epochs (or iterations if no sample_size is provided) The names of the other parameters are the same as in the corresponding climin method :param step_rate: step size of the method :param decay: decay of the mo... | 2 | stack_v2_sparse_classes_30k_train_002154 | Implement the Python class `AdaDelta` described below.
Class description:
A wrapper-class for AdaDelta method from climin library. Requires gradient estimation.
Method signatures and docstrings:
- def __init__(self, disp=False, iter_per_epoch=1, n_epoch=1000, step_rate=1.0, decay=0.9, momentum=0.0, offset=0.0001): :p... | Implement the Python class `AdaDelta` described below.
Class description:
A wrapper-class for AdaDelta method from climin library. Requires gradient estimation.
Method signatures and docstrings:
- def __init__(self, disp=False, iter_per_epoch=1, n_epoch=1000, step_rate=1.0, decay=0.9, momentum=0.0, offset=0.0001): :p... | fbc0be813096f21e02e9f8d306df1c21f7e006a7 | <|skeleton|>
class AdaDelta:
"""A wrapper-class for AdaDelta method from climin library. Requires gradient estimation."""
def __init__(self, disp=False, iter_per_epoch=1, n_epoch=1000, step_rate=1.0, decay=0.9, momentum=0.0, offset=0.0001):
""":param iter_per_epoch: number of iteration per epoch :param... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AdaDelta:
"""A wrapper-class for AdaDelta method from climin library. Requires gradient estimation."""
def __init__(self, disp=False, iter_per_epoch=1, n_epoch=1000, step_rate=1.0, decay=0.9, momentum=0.0, offset=0.0001):
""":param iter_per_epoch: number of iteration per epoch :param n_epoch: max... | the_stack_v2_python_sparse | gplib/optim/methods/wrappers.py | izmailovpavel/gplib | train | 2 |
8e45e0361a1d45e28f606ae5750d88d0c99a961a | [
"n = len(nums)\nif n <= 1:\n return False\nnums = [num * n for num in nums]\navg = sum(nums) // n\nnums = [num - avg for num in nums]\nleftSums, rightSums = (subsetSum(nums[:n // 2]), subsetSum(nums[n // 2:]))\nif 0 in leftSums or 0 in rightSums:\n return True\nleftSums.discard(sum(nums[:n // 2]))\nrightSums.... | <|body_start_0|>
n = len(nums)
if n <= 1:
return False
nums = [num * n for num in nums]
avg = sum(nums) // n
nums = [num - avg for num in nums]
leftSums, rightSums = (subsetSum(nums[:n // 2]), subsetSum(nums[n // 2:]))
if 0 in leftSums or 0 in rightSum... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def splitArraySameAverage(self, nums: List[int]) -> bool:
"""折半枚举 O(n*2^(n/2)) # !每个数减去平均数后,变成nums中是否存在和为0的非空真子集 1. 左边可以凑出0/右边可以凑出0 2. 左边+右边可以凑出0"""
<|body_0|>
def splitArraySameAverage2(self, nums: List[int]) -> bool:
"""背包dp O(n^2 * sum(nums)) #!集合A的平均值等于... | stack_v2_sparse_classes_10k_train_007138 | 3,763 | no_license | [
{
"docstring": "折半枚举 O(n*2^(n/2)) # !每个数减去平均数后,变成nums中是否存在和为0的非空真子集 1. 左边可以凑出0/右边可以凑出0 2. 左边+右边可以凑出0",
"name": "splitArraySameAverage",
"signature": "def splitArraySameAverage(self, nums: List[int]) -> bool"
},
{
"docstring": "背包dp O(n^2 * sum(nums)) #!集合A的平均值等于B的平均值 <=> #!`集合A的平均值`等于`nums的平均值` ... | 2 | stack_v2_sparse_classes_30k_train_006373 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def splitArraySameAverage(self, nums: List[int]) -> bool: 折半枚举 O(n*2^(n/2)) # !每个数减去平均数后,变成nums中是否存在和为0的非空真子集 1. 左边可以凑出0/右边可以凑出0 2. 左边+右边可以凑出0
- def splitArraySameAverage2(self, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def splitArraySameAverage(self, nums: List[int]) -> bool: 折半枚举 O(n*2^(n/2)) # !每个数减去平均数后,变成nums中是否存在和为0的非空真子集 1. 左边可以凑出0/右边可以凑出0 2. 左边+右边可以凑出0
- def splitArraySameAverage2(self, ... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def splitArraySameAverage(self, nums: List[int]) -> bool:
"""折半枚举 O(n*2^(n/2)) # !每个数减去平均数后,变成nums中是否存在和为0的非空真子集 1. 左边可以凑出0/右边可以凑出0 2. 左边+右边可以凑出0"""
<|body_0|>
def splitArraySameAverage2(self, nums: List[int]) -> bool:
"""背包dp O(n^2 * sum(nums)) #!集合A的平均值等于... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def splitArraySameAverage(self, nums: List[int]) -> bool:
"""折半枚举 O(n*2^(n/2)) # !每个数减去平均数后,变成nums中是否存在和为0的非空真子集 1. 左边可以凑出0/右边可以凑出0 2. 左边+右边可以凑出0"""
n = len(nums)
if n <= 1:
return False
nums = [num * n for num in nums]
avg = sum(nums) // n
... | the_stack_v2_python_sparse | 22_专题/枚举/折半枚举/805. 数组的均值分割-折半枚举子序列和.py | 981377660LMT/algorithm-study | train | 225 | |
851771d7e7af23442ab74d91e229c24a15d28579 | [
"self.callbacks = callbacks\nif serializer is None:\n serializer = rpc_serializer.NoOpSerializer()\nself.serializer = serializer\nsuper(RpcDispatcher, self).__init__()",
"new_kwargs = dict()\nfor argname, arg in six.iteritems(kwargs):\n new_kwargs[argname] = self.serializer.deserialize_entity(context, arg)\... | <|body_start_0|>
self.callbacks = callbacks
if serializer is None:
serializer = rpc_serializer.NoOpSerializer()
self.serializer = serializer
super(RpcDispatcher, self).__init__()
<|end_body_0|>
<|body_start_1|>
new_kwargs = dict()
for argname, arg in six.iter... | Dispatch rpc messages according to the requested API version. This class can be used as the top level 'manager' for a service. It contains a list of underlying managers that have an API_VERSION attribute. | RpcDispatcher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RpcDispatcher:
"""Dispatch rpc messages according to the requested API version. This class can be used as the top level 'manager' for a service. It contains a list of underlying managers that have an API_VERSION attribute."""
def __init__(self, callbacks, serializer=None):
"""Initial... | stack_v2_sparse_classes_10k_train_007139 | 7,022 | permissive | [
{
"docstring": "Initialize the rpc dispatcher. :param callbacks: List of proxy objects that are an instance of a class with rpc methods exposed. Each proxy object should have an RPC_API_VERSION attribute. :param serializer: The Serializer object that will be used to deserialize arguments before the method call ... | 3 | stack_v2_sparse_classes_30k_train_001636 | Implement the Python class `RpcDispatcher` described below.
Class description:
Dispatch rpc messages according to the requested API version. This class can be used as the top level 'manager' for a service. It contains a list of underlying managers that have an API_VERSION attribute.
Method signatures and docstrings:
... | Implement the Python class `RpcDispatcher` described below.
Class description:
Dispatch rpc messages according to the requested API version. This class can be used as the top level 'manager' for a service. It contains a list of underlying managers that have an API_VERSION attribute.
Method signatures and docstrings:
... | d2fabf40119267164b9e765e59e3f99cd61fdcef | <|skeleton|>
class RpcDispatcher:
"""Dispatch rpc messages according to the requested API version. This class can be used as the top level 'manager' for a service. It contains a list of underlying managers that have an API_VERSION attribute."""
def __init__(self, callbacks, serializer=None):
"""Initial... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RpcDispatcher:
"""Dispatch rpc messages according to the requested API version. This class can be used as the top level 'manager' for a service. It contains a list of underlying managers that have an API_VERSION attribute."""
def __init__(self, callbacks, serializer=None):
"""Initialize the rpc d... | the_stack_v2_python_sparse | cloudbaseinit/openstack/common/rpc/dispatcher.py | pellaeon/bsd-cloudinit | train | 75 |
2ca1ec20745f4cf0e43e5c0b22c205a1108d9f79 | [
"self._checkpoint_every_n = checkpoint_every_n\nrun_experiment.Runner.__init__(self, base_dir, create_agent_fn, **kwargs)\nself._training_steps = int(self._training_steps * self._agent._gin_param_multiplier)",
"self._checkpointer = checkpointer.Checkpointer(self._checkpoint_dir, checkpoint_file_prefix, checkpoint... | <|body_start_0|>
self._checkpoint_every_n = checkpoint_every_n
run_experiment.Runner.__init__(self, base_dir, create_agent_fn, **kwargs)
self._training_steps = int(self._training_steps * self._agent._gin_param_multiplier)
<|end_body_0|>
<|body_start_1|>
self._checkpointer = checkpointer... | Extends the base Runner for every-n-step checkpoint writing. | ElephantRunner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElephantRunner:
"""Extends the base Runner for every-n-step checkpoint writing."""
def __init__(self, base_dir, create_agent_fn, checkpoint_every_n=1, **kwargs):
"""Initialize the Runner object in charge of running a full experiment. Args: base_dir: str, the base directory to host al... | stack_v2_sparse_classes_10k_train_007140 | 6,020 | permissive | [
{
"docstring": "Initialize the Runner object in charge of running a full experiment. Args: base_dir: str, the base directory to host all required sub-directories. create_agent_fn: A function that takes as args a Tensorflow session and an environment, and returns an agent. checkpoint_every_n: int, the frequency ... | 3 | null | Implement the Python class `ElephantRunner` described below.
Class description:
Extends the base Runner for every-n-step checkpoint writing.
Method signatures and docstrings:
- def __init__(self, base_dir, create_agent_fn, checkpoint_every_n=1, **kwargs): Initialize the Runner object in charge of running a full exper... | Implement the Python class `ElephantRunner` described below.
Class description:
Extends the base Runner for every-n-step checkpoint writing.
Method signatures and docstrings:
- def __init__(self, base_dir, create_agent_fn, checkpoint_every_n=1, **kwargs): Initialize the Runner object in charge of running a full exper... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class ElephantRunner:
"""Extends the base Runner for every-n-step checkpoint writing."""
def __init__(self, base_dir, create_agent_fn, checkpoint_every_n=1, **kwargs):
"""Initialize the Runner object in charge of running a full experiment. Args: base_dir: str, the base directory to host al... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ElephantRunner:
"""Extends the base Runner for every-n-step checkpoint writing."""
def __init__(self, base_dir, create_agent_fn, checkpoint_every_n=1, **kwargs):
"""Initialize the Runner object in charge of running a full experiment. Args: base_dir: str, the base directory to host all required su... | the_stack_v2_python_sparse | experience_replay/run_experience_replay_experiment.py | Ayoob7/google-research | train | 2 |
30bb77e3b34fb8c69385bfc2a43feb26ce1eb929 | [
"super().__init__(cfg, use_gt_categories, embedder, count_per_class)\nself.confidence_channel = confidence_channel\nself.search_count_multiplier = search_count_multiplier\nself.search_proportion = search_proportion\nassert search_count_multiplier is None or search_proportion is None, f'Cannot specify both search_co... | <|body_start_0|>
super().__init__(cfg, use_gt_categories, embedder, count_per_class)
self.confidence_channel = confidence_channel
self.search_count_multiplier = search_count_multiplier
self.search_proportion = search_proportion
assert search_count_multiplier is None or search_pro... | Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates. | DensePoseCSEConfidenceBasedSampler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DensePoseCSEConfidenceBasedSampler:
"""Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates."""
def __init__(self, cfg: CfgNode, use_gt_categories: bool, embedder: torch.nn.Module, confidence_channel: str, count_per_class: int=8... | stack_v2_sparse_classes_10k_train_007141 | 5,154 | permissive | [
{
"docstring": "Constructor Args: cfg (CfgNode): the config of the model embedder (torch.nn.Module): necessary to compute mesh vertex embeddings confidence_channel (str): confidence channel to use for sampling; possible values: \"coarse_segm_confidence\": confidences for coarse segmentation (default: \"coarse_s... | 3 | null | Implement the Python class `DensePoseCSEConfidenceBasedSampler` described below.
Class description:
Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates.
Method signatures and docstrings:
- def __init__(self, cfg: CfgNode, use_gt_categories: bool, embedd... | Implement the Python class `DensePoseCSEConfidenceBasedSampler` described below.
Class description:
Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates.
Method signatures and docstrings:
- def __init__(self, cfg: CfgNode, use_gt_categories: bool, embedd... | 80307d2d5e06f06a8a677cc2653f23a4c56402ac | <|skeleton|>
class DensePoseCSEConfidenceBasedSampler:
"""Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates."""
def __init__(self, cfg: CfgNode, use_gt_categories: bool, embedder: torch.nn.Module, confidence_channel: str, count_per_class: int=8... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DensePoseCSEConfidenceBasedSampler:
"""Samples DensePose data from DensePose predictions. Samples for each class are drawn using confidence value estimates."""
def __init__(self, cfg: CfgNode, use_gt_categories: bool, embedder: torch.nn.Module, confidence_channel: str, count_per_class: int=8, search_coun... | the_stack_v2_python_sparse | projects/DensePose/densepose/data/samplers/densepose_cse_confidence_based.py | facebookresearch/detectron2 | train | 27,469 |
4396fd8004105cab2e1345b010778c2b13abeb1b | [
"self._validate_arr_or_dict_val_type(arr_or_dict=arr_or_dict)\nif locals_ is None:\n locals_ = {}\nif globals_ is None:\n globals_ = {}\nself._arr_or_dict = arr_or_dict\nself._locals = locals_\nself._globals = globals_\nself._indent = Indent()",
"if isinstance(arr_or_dict, (Array, Dictionary)):\n return\... | <|body_start_0|>
self._validate_arr_or_dict_val_type(arr_or_dict=arr_or_dict)
if locals_ is None:
locals_ = {}
if globals_ is None:
globals_ = {}
self._arr_or_dict = arr_or_dict
self._locals = locals_
self._globals = globals_
self._indent =... | For | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class For:
def __init__(self, arr_or_dict: Union[Array, Dictionary], locals_: Optional[Dict[str, Any]]=None, globals_: Optional[Dict[str, Any]]=None) -> None:
"""A class to append for (loop) expression. Parameters ---------- arr_or_dict : Array or Dictionary Array or Dictionary instance to ite... | stack_v2_sparse_classes_10k_train_007142 | 5,769 | permissive | [
{
"docstring": "A class to append for (loop) expression. Parameters ---------- arr_or_dict : Array or Dictionary Array or Dictionary instance to iterate. locals_ : dict or None, default None Current scope's local variables. Set locals() value to this argument. If specified, all local scope VariableNameInterface... | 6 | stack_v2_sparse_classes_30k_train_004077 | Implement the Python class `For` described below.
Class description:
Implement the For class.
Method signatures and docstrings:
- def __init__(self, arr_or_dict: Union[Array, Dictionary], locals_: Optional[Dict[str, Any]]=None, globals_: Optional[Dict[str, Any]]=None) -> None: A class to append for (loop) expression.... | Implement the Python class `For` described below.
Class description:
Implement the For class.
Method signatures and docstrings:
- def __init__(self, arr_or_dict: Union[Array, Dictionary], locals_: Optional[Dict[str, Any]]=None, globals_: Optional[Dict[str, Any]]=None) -> None: A class to append for (loop) expression.... | 5c6a4674e2e9684cb2cb1325dc9b070879d4d355 | <|skeleton|>
class For:
def __init__(self, arr_or_dict: Union[Array, Dictionary], locals_: Optional[Dict[str, Any]]=None, globals_: Optional[Dict[str, Any]]=None) -> None:
"""A class to append for (loop) expression. Parameters ---------- arr_or_dict : Array or Dictionary Array or Dictionary instance to ite... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class For:
def __init__(self, arr_or_dict: Union[Array, Dictionary], locals_: Optional[Dict[str, Any]]=None, globals_: Optional[Dict[str, Any]]=None) -> None:
"""A class to append for (loop) expression. Parameters ---------- arr_or_dict : Array or Dictionary Array or Dictionary instance to iterate. locals_ ... | the_stack_v2_python_sparse | apysc/loop/_for.py | TrendingTechnology/apysc | train | 0 | |
108ef9158003c85fcde1772a5e4a57f7a0e3fd1d | [
"self.bucket_name = bucket_name\nself.file_name = file_name\nself.celebrities = []\nself.orientation_correction = None\nself.recognition_response = None\nself.recognition_service = AWSRekognition()\nsuper(RecognizeCelebrity, self).__init__(prefix='RE', phase_name='Recognition', invocation_id=invocation_id)",
"if ... | <|body_start_0|>
self.bucket_name = bucket_name
self.file_name = file_name
self.celebrities = []
self.orientation_correction = None
self.recognition_response = None
self.recognition_service = AWSRekognition()
super(RecognizeCelebrity, self).__init__(prefix='RE', p... | Celebrity recognition object, responsible for accessing celebrity recognition API using a file storage stored image. Is also responsible for validating and processing the response. | RecognizeCelebrity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecognizeCelebrity:
"""Celebrity recognition object, responsible for accessing celebrity recognition API using a file storage stored image. Is also responsible for validating and processing the response."""
def __init__(self, bucket_name: str, file_name: str, invocation_id: str):
"""... | stack_v2_sparse_classes_10k_train_007143 | 5,253 | no_license | [
{
"docstring": "Constructor of the celebrity recognition object, stores provided and locally generated data, runs main object procedure. :param bucket_name: file storage location. :param file_name: stored file name. :param invocation_id: string containing id of current cloud function invocation to be to be used... | 4 | stack_v2_sparse_classes_30k_train_000870 | Implement the Python class `RecognizeCelebrity` described below.
Class description:
Celebrity recognition object, responsible for accessing celebrity recognition API using a file storage stored image. Is also responsible for validating and processing the response.
Method signatures and docstrings:
- def __init__(self... | Implement the Python class `RecognizeCelebrity` described below.
Class description:
Celebrity recognition object, responsible for accessing celebrity recognition API using a file storage stored image. Is also responsible for validating and processing the response.
Method signatures and docstrings:
- def __init__(self... | 8f1b94518303c4e0a38df1ff6caa0e7326451d67 | <|skeleton|>
class RecognizeCelebrity:
"""Celebrity recognition object, responsible for accessing celebrity recognition API using a file storage stored image. Is also responsible for validating and processing the response."""
def __init__(self, bucket_name: str, file_name: str, invocation_id: str):
"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RecognizeCelebrity:
"""Celebrity recognition object, responsible for accessing celebrity recognition API using a file storage stored image. Is also responsible for validating and processing the response."""
def __init__(self, bucket_name: str, file_name: str, invocation_id: str):
"""Constructor o... | the_stack_v2_python_sparse | Serverless/handlers/sqs_celebrity_recognition/celebrity_recognition.py | RogerVFbr/MyCelebs | train | 0 |
1e16de79c2224c0c8fdae883716abac4af74005d | [
"self.cassandra_additional_info = cassandra_additional_info\nself.finalise_restore_task_id = finalise_restore_task_id\nself.graph_handling_enabled = graph_handling_enabled\nself.is_finalise_phase = is_finalise_phase\nself.log_recover_params = log_recover_params\nself.log_restore_directory = log_restore_directory\ns... | <|body_start_0|>
self.cassandra_additional_info = cassandra_additional_info
self.finalise_restore_task_id = finalise_restore_task_id
self.graph_handling_enabled = graph_handling_enabled
self.is_finalise_phase = is_finalise_phase
self.log_recover_params = log_recover_params
... | Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters required for Cassandra recovery. TODO (faizan.khan) : Remove this. finalise_restore_task_id... | CassandraRecoverJobParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CassandraRecoverJobParams:
"""Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters required for Cassandra recovery. TODO ... | stack_v2_sparse_classes_10k_train_007144 | 6,191 | permissive | [
{
"docstring": "Constructor for the CassandraRecoverJobParams class",
"name": "__init__",
"signature": "def __init__(self, cassandra_additional_info=None, finalise_restore_task_id=None, graph_handling_enabled=None, is_finalise_phase=None, log_recover_params=None, log_restore_directory=None, restart_allo... | 2 | stack_v2_sparse_classes_30k_train_006428 | Implement the Python class `CassandraRecoverJobParams` described below.
Class description:
Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters... | Implement the Python class `CassandraRecoverJobParams` described below.
Class description:
Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CassandraRecoverJobParams:
"""Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters required for Cassandra recovery. TODO ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CassandraRecoverJobParams:
"""Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters required for Cassandra recovery. TODO (faizan.khan)... | the_stack_v2_python_sparse | cohesity_management_sdk/models/cassandra_recover_job_params.py | cohesity/management-sdk-python | train | 24 |
9ca075134549cf6f023d31e33da5331a65ec296a | [
"res = []\n\ndef pre_order(root):\n if not root:\n return None\n res.append(root.val)\n pre_order(root.left)\n pre_order(root.right)\npre_order(root)\nreturn ' '.join(map(str, res))",
"res = deque((int(v) for v in data.split()))\n\ndef build(low_bound, high_bound):\n if res and low_bound < r... | <|body_start_0|>
res = []
def pre_order(root):
if not root:
return None
res.append(root.val)
pre_order(root.left)
pre_order(root.right)
pre_order(root)
return ' '.join(map(str, res))
<|end_body_0|>
<|body_start_1|>
... | 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_007145 | 1,292 | 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_000933 | 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:... | ba6b2500b86489cc34852ff73ba0915e57aa0275 | <|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"""
res = []
def pre_order(root):
if not root:
return None
res.append(root.val)
pre_order(root.left)
pre_order(root.r... | the_stack_v2_python_sparse | algo/first/p449_serialize_and_deserialize_bst.py | thinkreed/lc.py | train | 3 | |
b3798049e6c75374d536ff536dc61b318353630b | [
"ways = [1, 1]\nif n < 2:\n return ways[n]\nelse:\n for i in range(2, n + 1):\n tmp = ways[0] + ways[1]\n ways[0] = ways[1]\n ways[1] = tmp\n return ways[1]",
"ways = [1, 1]\nfor i in range(1, n):\n ways.append(ways[i] + ways[i - 1])\n'\\n\\t\\tfor i in range(2, n+1):\\n\\t\\t\\tw... | <|body_start_0|>
ways = [1, 1]
if n < 2:
return ways[n]
else:
for i in range(2, n + 1):
tmp = ways[0] + ways[1]
ways[0] = ways[1]
ways[1] = tmp
return ways[1]
<|end_body_0|>
<|body_start_1|>
ways = [1, 1... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs1(self, n: int) -> int:
""":type prices: List[int] :rtype: int 时间复杂度:O(n), 一次遍历, 36ms beaten 99.72% 空间复杂度:O(1), 未使用额外空间, 12.8MB beaten 99.51%"""
<|body_0|>
def climbStairs2(self, n: int) -> int:
""":type prices: List[int] :rtype: int 时间复杂度:O(... | stack_v2_sparse_classes_10k_train_007146 | 1,333 | permissive | [
{
"docstring": ":type prices: List[int] :rtype: int 时间复杂度:O(n), 一次遍历, 36ms beaten 99.72% 空间复杂度:O(1), 未使用额外空间, 12.8MB beaten 99.51%",
"name": "climbStairs1",
"signature": "def climbStairs1(self, n: int) -> int"
},
{
"docstring": ":type prices: List[int] :rtype: int 时间复杂度:O(n), 一次遍历, 40ms beaten 9... | 2 | stack_v2_sparse_classes_30k_val_000061 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs1(self, n: int) -> int: :type prices: List[int] :rtype: int 时间复杂度:O(n), 一次遍历, 36ms beaten 99.72% 空间复杂度:O(1), 未使用额外空间, 12.8MB beaten 99.51%
- def climbStairs2(self,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs1(self, n: int) -> int: :type prices: List[int] :rtype: int 时间复杂度:O(n), 一次遍历, 36ms beaten 99.72% 空间复杂度:O(1), 未使用额外空间, 12.8MB beaten 99.51%
- def climbStairs2(self,... | a2e5256f27dbfb23fc34119fc857cd9b00e28c03 | <|skeleton|>
class Solution:
def climbStairs1(self, n: int) -> int:
""":type prices: List[int] :rtype: int 时间复杂度:O(n), 一次遍历, 36ms beaten 99.72% 空间复杂度:O(1), 未使用额外空间, 12.8MB beaten 99.51%"""
<|body_0|>
def climbStairs2(self, n: int) -> int:
""":type prices: List[int] :rtype: int 时间复杂度:O(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def climbStairs1(self, n: int) -> int:
""":type prices: List[int] :rtype: int 时间复杂度:O(n), 一次遍历, 36ms beaten 99.72% 空间复杂度:O(1), 未使用额外空间, 12.8MB beaten 99.51%"""
ways = [1, 1]
if n < 2:
return ways[n]
else:
for i in range(2, n + 1):
... | the_stack_v2_python_sparse | toTheMoon/leetcode_070_ClimbingStairs.py | jercas/offer66-leetcode-newcode | train | 0 | |
c2ce97ab822b5f9eb23902211ca40ce393b28ea9 | [
"post_data = dict(self.request.POST.lists())\npregunta = Pregunta.objects.get(id=int(self.kwargs['pk']))\nself.object = form.save(commit=False)\nself.object.texto_opcion = post_data['texto_opcion'][0]\nself.object.pregunta = pregunta\nself.object.save()\nfor i in range(1, len(post_data['texto_opcion'])):\n opcio... | <|body_start_0|>
post_data = dict(self.request.POST.lists())
pregunta = Pregunta.objects.get(id=int(self.kwargs['pk']))
self.object = form.save(commit=False)
self.object.texto_opcion = post_data['texto_opcion'][0]
self.object.pregunta = pregunta
self.object.save()
... | ! Clase que gestiona la creación de opciones @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 20-02-2017 @version 1.0.0 | OpcionesCreate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpcionesCreate:
"""! Clase que gestiona la creación de opciones @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 20-02-2017 @version 1.0.0"""
def form_valid(self, form):
""... | stack_v2_sparse_classes_10k_train_007147 | 22,004 | no_license | [
{
"docstring": "! Metodo que valida si el formulario es valido @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU/GPLv2 @date 20-02-2017 @param self <b>{object}</b> Objeto que instancia la clase @param form <b>{object}</b> Objeto que contiene el formulario de registro @return Retorna el formulario v... | 2 | stack_v2_sparse_classes_30k_train_007333 | Implement the Python class `OpcionesCreate` described below.
Class description:
! Clase que gestiona la creación de opciones @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 20-02-2017 @version 1.0.0
Method... | Implement the Python class `OpcionesCreate` described below.
Class description:
! Clase que gestiona la creación de opciones @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 20-02-2017 @version 1.0.0
Method... | 93cefc3c94c62e66b103510a2f668a419e5c5cae | <|skeleton|>
class OpcionesCreate:
"""! Clase que gestiona la creación de opciones @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 20-02-2017 @version 1.0.0"""
def form_valid(self, form):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OpcionesCreate:
"""! Clase que gestiona la creación de opciones @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 20-02-2017 @version 1.0.0"""
def form_valid(self, form):
"""! Metodo que... | the_stack_v2_python_sparse | consulta/views.py | rudmanmrrod/gestor_consulta | train | 1 |
a4240c08728bc439a12c239c4891ae41f16b164d | [
"if N == 0:\n return 0\nself.M = M\nself.nums = [x for x in range(1, N + 1)]\nself.res = 0\nself.dfs(1, [str(self.nums[0])])\nreturn self.res",
"if index == len(self.nums):\n if self.cal(path) == self.M:\n self.res += 1\n return\nfor op in '+-s':\n if op != 's':\n path.append(op)\n ... | <|body_start_0|>
if N == 0:
return 0
self.M = M
self.nums = [x for x in range(1, N + 1)]
self.res = 0
self.dfs(1, [str(self.nums[0])])
return self.res
<|end_body_0|>
<|body_start_1|>
if index == len(self.nums):
if self.cal(path) == self.M:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def func(self, N, M):
"""Args: N: int M: int Return: int"""
<|body_0|>
def dfs(self, index, path):
"""Args: index: int path: list[str]"""
<|body_1|>
def cal(self, path):
"""Args: path: list[str] Return: int"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_10k_train_007148 | 1,922 | no_license | [
{
"docstring": "Args: N: int M: int Return: int",
"name": "func",
"signature": "def func(self, N, M)"
},
{
"docstring": "Args: index: int path: list[str]",
"name": "dfs",
"signature": "def dfs(self, index, path)"
},
{
"docstring": "Args: path: list[str] Return: int",
"name": ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def func(self, N, M): Args: N: int M: int Return: int
- def dfs(self, index, path): Args: index: int path: list[str]
- def cal(self, path): Args: path: list[str] Return: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def func(self, N, M): Args: N: int M: int Return: int
- def dfs(self, index, path): Args: index: int path: list[str]
- def cal(self, path): Args: path: list[str] Return: int
<|s... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def func(self, N, M):
"""Args: N: int M: int Return: int"""
<|body_0|>
def dfs(self, index, path):
"""Args: index: int path: list[str]"""
<|body_1|>
def cal(self, path):
"""Args: path: list[str] Return: int"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def func(self, N, M):
"""Args: N: int M: int Return: int"""
if N == 0:
return 0
self.M = M
self.nums = [x for x in range(1, N + 1)]
self.res = 0
self.dfs(1, [str(self.nums[0])])
return self.res
def dfs(self, index, path):
... | the_stack_v2_python_sparse | 秋招/小米/如何添加运算符.py | AiZhanghan/Leetcode | train | 0 | |
3ac85c52648c16149df7cedc01d084d65c78f9eb | [
"if self.feature in self.FEATURES_MAPPING:\n self.feature = self.FEATURES_MAPPING[self.feature]\nif 'type' in additional_data:\n self.feature_type = additional_data['type']",
"name = self.function_name\nif self.feature_type:\n name = '%s for %s' % (name, self.feature_type)\nreturn name",
"features = se... | <|body_start_0|>
if self.feature in self.FEATURES_MAPPING:
self.feature = self.FEATURES_MAPPING[self.feature]
if 'type' in additional_data:
self.feature_type = additional_data['type']
<|end_body_0|>
<|body_start_1|>
name = self.function_name
if self.feature_type:... | AbstractOverpassInsightFunction | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractOverpassInsightFunction:
def initiate(self, additional_data):
"""Initiate function :param additional_data: additional data that needed :type additional_data:dict"""
<|body_0|>
def name(self):
"""Name of insight functions :return: string of name"""
<|b... | stack_v2_sparse_classes_10k_train_007149 | 2,354 | permissive | [
{
"docstring": "Initiate function :param additional_data: additional data that needed :type additional_data:dict",
"name": "initiate",
"signature": "def initiate(self, additional_data)"
},
{
"docstring": "Name of insight functions :return: string of name",
"name": "name",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_005888 | Implement the Python class `AbstractOverpassInsightFunction` described below.
Class description:
Implement the AbstractOverpassInsightFunction class.
Method signatures and docstrings:
- def initiate(self, additional_data): Initiate function :param additional_data: additional data that needed :type additional_data:dic... | Implement the Python class `AbstractOverpassInsightFunction` described below.
Class description:
Implement the AbstractOverpassInsightFunction class.
Method signatures and docstrings:
- def initiate(self, additional_data): Initiate function :param additional_data: additional data that needed :type additional_data:dic... | 53d448b8d558e88df5710a672a76ef1f9c983e57 | <|skeleton|>
class AbstractOverpassInsightFunction:
def initiate(self, additional_data):
"""Initiate function :param additional_data: additional data that needed :type additional_data:dict"""
<|body_0|>
def name(self):
"""Name of insight functions :return: string of name"""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AbstractOverpassInsightFunction:
def initiate(self, additional_data):
"""Initiate function :param additional_data: additional data that needed :type additional_data:dict"""
if self.feature in self.FEATURES_MAPPING:
self.feature = self.FEATURES_MAPPING[self.feature]
if 'type... | the_stack_v2_python_sparse | flask_project/campaign_manager/insights_functions/_abstract_overpass_insight_function.py | russbiggs/MapCampaigner | train | 0 | |
e62877f3d9478332d872536d0238706c76563f5c | [
"Parametre.__init__(self, 'supprimer', 'del')\nself.schema = '<message>'\nself.aide_courte = 'supprime un alias'\nself.aide_longue = \"Cette commande permet de supprimer un de vos alias. Précisez simplement le nom de l'alias en paramètre.\"",
"message = dic_masques['message'].message\nmessage = message.lower()\ni... | <|body_start_0|>
Parametre.__init__(self, 'supprimer', 'del')
self.schema = '<message>'
self.aide_courte = 'supprime un alias'
self.aide_longue = "Cette commande permet de supprimer un de vos alias. Précisez simplement le nom de l'alias en paramètre."
<|end_body_0|>
<|body_start_1|>
... | Commande 'alias supprimer'. | PrmSupprimer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmSupprimer:
"""Commande 'alias supprimer'."""
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|>
Paramet... | stack_v2_sparse_classes_10k_train_007150 | 2,634 | 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 `PrmSupprimer` described below.
Class description:
Commande 'alias supprimer'.
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 `PrmSupprimer` described below.
Class description:
Commande 'alias supprimer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmSupprimer:
"""Commande 'a... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmSupprimer:
"""Commande 'alias supprimer'."""
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 PrmSupprimer:
"""Commande 'alias supprimer'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'supprimer', 'del')
self.schema = '<message>'
self.aide_courte = 'supprime un alias'
self.aide_longue = "Cette commande permet de supprimer ... | the_stack_v2_python_sparse | src/primaires/joueur/commandes/alias/supprimer.py | vincent-lg/tsunami | train | 5 |
f6f602813e8d149331f616953fcebe2f7c6aa15e | [
"cu = Change_Param(username, password, prod)\ngu = cu.get_params()\nself.suffix = self.c.get_value('Member', 'members_nocice_logs')\nself.url = self.url_joint(prod) + gu[1]\nlogs.info('test url:%s' % self.url)\nreturn self.get_requests(self.url, gu[0], data)",
"cu = Change_Param(username, password, prod)\ngu = cu... | <|body_start_0|>
cu = Change_Param(username, password, prod)
gu = cu.get_params()
self.suffix = self.c.get_value('Member', 'members_nocice_logs')
self.url = self.url_joint(prod) + gu[1]
logs.info('test url:%s' % self.url)
return self.get_requests(self.url, gu[0], data)
<|... | Member_Notice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Member_Notice:
def get_member_nocice_logs(self, username=None, password=None, data=None, prod=None):
"""相关参数有: page_no 页码 page_size 每页显示数量 read 是否已读,1已读,0未读,可用值:0,1"""
<|body_0|>
def del_member_nocice_logs_ids(self, ids, username=None, password=None, data=None, prod=None):
... | stack_v2_sparse_classes_10k_train_007151 | 2,683 | no_license | [
{
"docstring": "相关参数有: page_no 页码 page_size 每页显示数量 read 是否已读,1已读,0未读,可用值:0,1",
"name": "get_member_nocice_logs",
"signature": "def get_member_nocice_logs(self, username=None, password=None, data=None, prod=None)"
},
{
"docstring": "相关参数有: ids 要删除的消息主键",
"name": "del_member_nocice_logs_ids",
... | 3 | stack_v2_sparse_classes_30k_train_000859 | Implement the Python class `Member_Notice` described below.
Class description:
Implement the Member_Notice class.
Method signatures and docstrings:
- def get_member_nocice_logs(self, username=None, password=None, data=None, prod=None): 相关参数有: page_no 页码 page_size 每页显示数量 read 是否已读,1已读,0未读,可用值:0,1
- def del_member_noci... | Implement the Python class `Member_Notice` described below.
Class description:
Implement the Member_Notice class.
Method signatures and docstrings:
- def get_member_nocice_logs(self, username=None, password=None, data=None, prod=None): 相关参数有: page_no 页码 page_size 每页显示数量 read 是否已读,1已读,0未读,可用值:0,1
- def del_member_noci... | 235200a67c1fb125f75f9771808f6655a7b14202 | <|skeleton|>
class Member_Notice:
def get_member_nocice_logs(self, username=None, password=None, data=None, prod=None):
"""相关参数有: page_no 页码 page_size 每页显示数量 read 是否已读,1已读,0未读,可用值:0,1"""
<|body_0|>
def del_member_nocice_logs_ids(self, ids, username=None, password=None, data=None, prod=None):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Member_Notice:
def get_member_nocice_logs(self, username=None, password=None, data=None, prod=None):
"""相关参数有: page_no 页码 page_size 每页显示数量 read 是否已读,1已读,0未读,可用值:0,1"""
cu = Change_Param(username, password, prod)
gu = cu.get_params()
self.suffix = self.c.get_value('Member', 'mem... | the_stack_v2_python_sparse | business/member/member_notice.py | vothin/requsets_test | train | 0 | |
e27f524b287f45bdacf68e26fc8e63fceee91e06 | [
"n = len(init_val)\nself.segfunc = segfunc\nself.ide_ele = ide_ele\nself.num = 1 << (n - 1).bit_length()\nself.tree = [ide_ele] * 2 * self.num\nfor i in range(n):\n self.tree[self.num + i] = init_val[i]\nfor i in range(self.num - 1, 0, -1):\n self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])... | <|body_start_0|>
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - 1, 0, -1):
... | init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN) | SegTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegTree:
"""init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)"""
def __init__(self, init_val, segfunc, ide_ele):
"""init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)"... | stack_v2_sparse_classes_10k_train_007152 | 2,945 | no_license | [
{
"docstring": "init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)",
"name": "__init__",
"signature": "def __init__(self, init_val, segfunc, ide_ele)"
},
{
"docstring": "k番目の値をxに更新 k: index(0-index) x: update value",
"name": "update",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_006804 | Implement the Python class `SegTree` described below.
Class description:
init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
Method signatures and docstrings:
- def __init__(self, init_val, segfunc, ide_ele): init_val: 配列の初期値 segfunc: 区間にしたい操作 ide... | Implement the Python class `SegTree` described below.
Class description:
init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
Method signatures and docstrings:
- def __init__(self, init_val, segfunc, ide_ele): init_val: 配列の初期値 segfunc: 区間にしたい操作 ide... | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | <|skeleton|>
class SegTree:
"""init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)"""
def __init__(self, init_val, segfunc, ide_ele):
"""init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SegTree:
"""init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)"""
def __init__(self, init_val, segfunc, ide_ele):
"""init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)"""
n ... | the_stack_v2_python_sparse | Python_codes/p03061/s654525017.py | Aasthaengg/IBMdataset | train | 0 |
bb22159e1acc774ea384c7b2550ada26258c4daf | [
"if user.is_anonymous or user.is_client:\n return False\nif user.is_administrator:\n return True\nif user.is_manager or user.is_advisor:\n return organization.owning_group == user.group\nreturn self.admin_permission(user, organization, *args)",
"if user.is_anonymous or user.is_client:\n return False\n... | <|body_start_0|>
if user.is_anonymous or user.is_client:
return False
if user.is_administrator:
return True
if user.is_manager or user.is_advisor:
return organization.owning_group == user.group
return self.admin_permission(user, organization, *args)
<|... | OrganizationPermissionLogic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationPermissionLogic:
def view(self, user, organization, *args):
"""Permissions for viewing Organization"""
<|body_0|>
def create(self, user, organization, *args):
"""Permissions for creating Organization"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_10k_train_007153 | 1,236 | no_license | [
{
"docstring": "Permissions for viewing Organization",
"name": "view",
"signature": "def view(self, user, organization, *args)"
},
{
"docstring": "Permissions for creating Organization",
"name": "create",
"signature": "def create(self, user, organization, *args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003431 | Implement the Python class `OrganizationPermissionLogic` described below.
Class description:
Implement the OrganizationPermissionLogic class.
Method signatures and docstrings:
- def view(self, user, organization, *args): Permissions for viewing Organization
- def create(self, user, organization, *args): Permissions f... | Implement the Python class `OrganizationPermissionLogic` described below.
Class description:
Implement the OrganizationPermissionLogic class.
Method signatures and docstrings:
- def view(self, user, organization, *args): Permissions for viewing Organization
- def create(self, user, organization, *args): Permissions f... | 95d21cd6036a99c5f399b700a5426e9e2e17e878 | <|skeleton|>
class OrganizationPermissionLogic:
def view(self, user, organization, *args):
"""Permissions for viewing Organization"""
<|body_0|>
def create(self, user, organization, *args):
"""Permissions for creating Organization"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OrganizationPermissionLogic:
def view(self, user, organization, *args):
"""Permissions for viewing Organization"""
if user.is_anonymous or user.is_client:
return False
if user.is_administrator:
return True
if user.is_manager or user.is_advisor:
... | the_stack_v2_python_sparse | fac/perms/organization_perm.py | alexandrenorman/mixeur | train | 0 | |
0f20663fb8a4f3211c50cd95f80e4dba755a240f | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), name=name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password, name=name)\nuser.is_admin = True\nuser.is_staff = True... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), name=name)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.c... | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_10k_train_007154 | 7,149 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, name, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_001123 | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | 4d497a6261de17cc2fc058cea50e127e885e5095 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), na... | the_stack_v2_python_sparse | Project4_FortressMachine/KindFortressMachine/web/models.py | phully/PythonHomeWork | train | 0 | |
8705eb7454d9638d7a4a36d046afa81344abbb82 | [
"ones, twos = (0, 0)\nfor num in nums:\n ones = ones ^ num & ~twos\n twos = twos ^ num & ~ones\nreturn ones",
"numBit = [0] * 32\nfor i in nums:\n num = i\n index = 0\n while num:\n if num & 1:\n numBit[index] += 1\n num = num >> 1\n index += 1\nfor i in range(32):\n... | <|body_start_0|>
ones, twos = (0, 0)
for num in nums:
ones = ones ^ num & ~twos
twos = twos ^ num & ~ones
return ones
<|end_body_0|>
<|body_start_1|>
numBit = [0] * 32
for i in nums:
num = i
index = 0
while num:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
"""位运算:统计二进制各个位置上出现的次数,取余3即为答案 方法一:有限状态自动机,进位 * 方法二:统计"""
<|body_0|>
def singleNumber1(self, nums):
"""位运算:统计二进制各个位置上出现的次数,取余3即为答案 方法一:有限状态自动机,进位 方法二:统计 *"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ones, ... | stack_v2_sparse_classes_10k_train_007155 | 1,185 | no_license | [
{
"docstring": "位运算:统计二进制各个位置上出现的次数,取余3即为答案 方法一:有限状态自动机,进位 * 方法二:统计",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": "位运算:统计二进制各个位置上出现的次数,取余3即为答案 方法一:有限状态自动机,进位 方法二:统计 *",
"name": "singleNumber1",
"signature": "def singleNumber1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005740 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): 位运算:统计二进制各个位置上出现的次数,取余3即为答案 方法一:有限状态自动机,进位 * 方法二:统计
- def singleNumber1(self, nums): 位运算:统计二进制各个位置上出现的次数,取余3即为答案 方法一:有限状态自动机,进位 方法二:统计 * | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): 位运算:统计二进制各个位置上出现的次数,取余3即为答案 方法一:有限状态自动机,进位 * 方法二:统计
- def singleNumber1(self, nums): 位运算:统计二进制各个位置上出现的次数,取余3即为答案 方法一:有限状态自动机,进位 方法二:统计 *
<|skeleton... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def singleNumber(self, nums):
"""位运算:统计二进制各个位置上出现的次数,取余3即为答案 方法一:有限状态自动机,进位 * 方法二:统计"""
<|body_0|>
def singleNumber1(self, nums):
"""位运算:统计二进制各个位置上出现的次数,取余3即为答案 方法一:有限状态自动机,进位 方法二:统计 *"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def singleNumber(self, nums):
"""位运算:统计二进制各个位置上出现的次数,取余3即为答案 方法一:有限状态自动机,进位 * 方法二:统计"""
ones, twos = (0, 0)
for num in nums:
ones = ones ^ num & ~twos
twos = twos ^ num & ~ones
return ones
def singleNumber1(self, nums):
"""位运算:统计二进... | the_stack_v2_python_sparse | 4_LEETCODE/5_BinaryNumber/JZ56_数组中数字出现的次数II.py | fzingithub/SwordRefers2Offer | train | 1 | |
9adc96bd7b6fdb25b973a79394ce1289b5c0300d | [
"super(TenorNetworkModule, self).__init__()\nself.args = args\nself.setup_weights()\nself.init_parameters()",
"self.weight_matrix = torch.nn.Parameter(torch.Tensor(self.args.filters_3, self.args.filters_3, self.args.tensor_neurons))\nself.weight_matrix_block = torch.nn.Parameter(torch.Tensor(self.args.tensor_neur... | <|body_start_0|>
super(TenorNetworkModule, self).__init__()
self.args = args
self.setup_weights()
self.init_parameters()
<|end_body_0|>
<|body_start_1|>
self.weight_matrix = torch.nn.Parameter(torch.Tensor(self.args.filters_3, self.args.filters_3, self.args.tensor_neurons))
... | SimGNN Tensor Network module to calculate similarity vector. | TenorNetworkModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenorNetworkModule:
"""SimGNN Tensor Network module to calculate similarity vector."""
def __init__(self, args):
""":param args: Arguments object."""
<|body_0|>
def setup_weights(self):
"""Defining weights."""
<|body_1|>
def init_parameters(self):
... | stack_v2_sparse_classes_10k_train_007156 | 8,576 | no_license | [
{
"docstring": ":param args: Arguments object.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Defining weights.",
"name": "setup_weights",
"signature": "def setup_weights(self)"
},
{
"docstring": "Initializing weights.",
"name": "init_paramet... | 4 | null | Implement the Python class `TenorNetworkModule` described below.
Class description:
SimGNN Tensor Network module to calculate similarity vector.
Method signatures and docstrings:
- def __init__(self, args): :param args: Arguments object.
- def setup_weights(self): Defining weights.
- def init_parameters(self): Initia... | Implement the Python class `TenorNetworkModule` described below.
Class description:
SimGNN Tensor Network module to calculate similarity vector.
Method signatures and docstrings:
- def __init__(self, args): :param args: Arguments object.
- def setup_weights(self): Defining weights.
- def init_parameters(self): Initia... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class TenorNetworkModule:
"""SimGNN Tensor Network module to calculate similarity vector."""
def __init__(self, args):
""":param args: Arguments object."""
<|body_0|>
def setup_weights(self):
"""Defining weights."""
<|body_1|>
def init_parameters(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TenorNetworkModule:
"""SimGNN Tensor Network module to calculate similarity vector."""
def __init__(self, args):
""":param args: Arguments object."""
super(TenorNetworkModule, self).__init__()
self.args = args
self.setup_weights()
self.init_parameters()
def se... | the_stack_v2_python_sparse | generated/test_benedekrozemberczki_SimGNN.py | jansel/pytorch-jit-paritybench | train | 35 |
80f92d853eb103b6a1f816a7b5cec51b2e2edb49 | [
"search_query = self._parse_request()\nresults = search_query.run_query()\nreturn self.format_success(200, {'count': len(results), 'results': [result.dictionary for result in results]})",
"parser = reqparse.RequestParser()\nparser.add_argument('type', type=str, required=True, help='Type is required', location='ar... | <|body_start_0|>
search_query = self._parse_request()
results = search_query.run_query()
return self.format_success(200, {'count': len(results), 'results': [result.dictionary for result in results]})
<|end_body_0|>
<|body_start_1|>
parser = reqparse.RequestParser()
parser.add_ar... | Resource for /tribes/search | TribeSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TribeSearch:
"""Resource for /tribes/search"""
def get(self):
"""GET /tribes/search/ Query for Tribes"""
<|body_0|>
def _parse_request(self) -> TribeSearchQuery:
"""Parser for the incoming request"""
<|body_1|>
def _parse_location(self, args) -> Trib... | stack_v2_sparse_classes_10k_train_007157 | 2,026 | no_license | [
{
"docstring": "GET /tribes/search/ Query for Tribes",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Parser for the incoming request",
"name": "_parse_request",
"signature": "def _parse_request(self) -> TribeSearchQuery"
},
{
"docstring": "Parse the lat/long and ... | 3 | stack_v2_sparse_classes_30k_train_005101 | Implement the Python class `TribeSearch` described below.
Class description:
Resource for /tribes/search
Method signatures and docstrings:
- def get(self): GET /tribes/search/ Query for Tribes
- def _parse_request(self) -> TribeSearchQuery: Parser for the incoming request
- def _parse_location(self, args) -> TribeSea... | Implement the Python class `TribeSearch` described below.
Class description:
Resource for /tribes/search
Method signatures and docstrings:
- def get(self): GET /tribes/search/ Query for Tribes
- def _parse_request(self) -> TribeSearchQuery: Parser for the incoming request
- def _parse_location(self, args) -> TribeSea... | 8ab4034413262ff2271740d73df72b3d83ce5918 | <|skeleton|>
class TribeSearch:
"""Resource for /tribes/search"""
def get(self):
"""GET /tribes/search/ Query for Tribes"""
<|body_0|>
def _parse_request(self) -> TribeSearchQuery:
"""Parser for the incoming request"""
<|body_1|>
def _parse_location(self, args) -> Trib... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TribeSearch:
"""Resource for /tribes/search"""
def get(self):
"""GET /tribes/search/ Query for Tribes"""
search_query = self._parse_request()
results = search_query.run_query()
return self.format_success(200, {'count': len(results), 'results': [result.dictionary for result... | the_stack_v2_python_sparse | app/main/controllers/tribes/search_tribes_controller.py | Malawi-Water-Wells-project/malawi-auth-api | train | 1 |
1551cf21b02340673adabca151988a906dc0f1ae | [
"for i in range(1, len(array)):\n while i > 0 and array[i] < array[i - 1]:\n array[i], array[i - 1] = (array[i - 1], array[i])\n i -= 1",
"for i, val in enumerate(array):\n while i > 0 and val < array[i - 1]:\n array[i] = array[i - 1]\n i -= 1\n array[i] = val",
"j = 0\nfor ... | <|body_start_0|>
for i in range(1, len(array)):
while i > 0 and array[i] < array[i - 1]:
array[i], array[i - 1] = (array[i - 1], array[i])
i -= 1
<|end_body_0|>
<|body_start_1|>
for i, val in enumerate(array):
while i > 0 and val < array[i - 1]:
... | Contains various insertion sort implementations. http://en.wikipedia.org/wiki/Insertion_sort | Insertion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Insertion:
"""Contains various insertion sort implementations. http://en.wikipedia.org/wiki/Insertion_sort"""
def insertion(array):
"""Basic insertion sort. Still worst of O(n^2) but much faster than other algorithms of the same time complexity like bubble sort. Inplace: Yes Time com... | stack_v2_sparse_classes_10k_train_007158 | 14,101 | no_license | [
{
"docstring": "Basic insertion sort. Still worst of O(n^2) but much faster than other algorithms of the same time complexity like bubble sort. Inplace: Yes Time complexity: best O(n), avg and worst O(n^2)",
"name": "insertion",
"signature": "def insertion(array)"
},
{
"docstring": "Improves per... | 3 | stack_v2_sparse_classes_30k_train_002211 | Implement the Python class `Insertion` described below.
Class description:
Contains various insertion sort implementations. http://en.wikipedia.org/wiki/Insertion_sort
Method signatures and docstrings:
- def insertion(array): Basic insertion sort. Still worst of O(n^2) but much faster than other algorithms of the sam... | Implement the Python class `Insertion` described below.
Class description:
Contains various insertion sort implementations. http://en.wikipedia.org/wiki/Insertion_sort
Method signatures and docstrings:
- def insertion(array): Basic insertion sort. Still worst of O(n^2) but much faster than other algorithms of the sam... | c88059dc66297af577ad2b8afa4e0ac0ad622915 | <|skeleton|>
class Insertion:
"""Contains various insertion sort implementations. http://en.wikipedia.org/wiki/Insertion_sort"""
def insertion(array):
"""Basic insertion sort. Still worst of O(n^2) but much faster than other algorithms of the same time complexity like bubble sort. Inplace: Yes Time com... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Insertion:
"""Contains various insertion sort implementations. http://en.wikipedia.org/wiki/Insertion_sort"""
def insertion(array):
"""Basic insertion sort. Still worst of O(n^2) but much faster than other algorithms of the same time complexity like bubble sort. Inplace: Yes Time complexity: best... | the_stack_v2_python_sparse | codes/BuildLinks1.02/test_input/sort_codes/pysort.py | DaHuO/Supergraph | train | 2 |
6100f1a09996674b67a958a7026ada368ae699fb | [
"nn.Module.__init__(self)\nself.c = c\nself.eta = eta\nself.eps = eps",
"dist = torch.norm(self.c - input, p=2, dim=1)\nlosses = torch.where(semi_target == 0, dist ** 2, self.eta * (dist ** 2 + self.eps) ** semi_target.float())\nloss = torch.mean(losses)\nreturn loss"
] | <|body_start_0|>
nn.Module.__init__(self)
self.c = c
self.eta = eta
self.eps = eps
<|end_body_0|>
<|body_start_1|>
dist = torch.norm(self.c - input, p=2, dim=1)
losses = torch.where(semi_target == 0, dist ** 2, self.eta * (dist ** 2 + self.eps) ** semi_target.float())
... | Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019) | DeepSADLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepSADLoss:
"""Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019)"""
def __init__(self, c, eta, eps=1e-06):
"""Constructor of the DeepSAD loss. ---------- INPUT |---- c (torch.Tensor) the center of the hypersphere as a multidimensional vector. |---- eta (float) ... | stack_v2_sparse_classes_10k_train_007159 | 18,386 | permissive | [
{
"docstring": "Constructor of the DeepSAD loss. ---------- INPUT |---- c (torch.Tensor) the center of the hypersphere as a multidimensional vector. |---- eta (float) control the importance given to known or unknonw | samples. 1.0 gives equal weights, <1.0 gives more weight | to the unknown samples, >1.0 gives ... | 2 | stack_v2_sparse_classes_30k_train_007228 | Implement the Python class `DeepSADLoss` described below.
Class description:
Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019)
Method signatures and docstrings:
- def __init__(self, c, eta, eps=1e-06): Constructor of the DeepSAD loss. ---------- INPUT |---- c (torch.Tensor) the center of the hyp... | Implement the Python class `DeepSADLoss` described below.
Class description:
Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019)
Method signatures and docstrings:
- def __init__(self, c, eta, eps=1e-06): Constructor of the DeepSAD loss. ---------- INPUT |---- c (torch.Tensor) the center of the hyp... | 850b6195d6290a50eee865b4d5a66f5db5260e8f | <|skeleton|>
class DeepSADLoss:
"""Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019)"""
def __init__(self, c, eta, eps=1e-06):
"""Constructor of the DeepSAD loss. ---------- INPUT |---- c (torch.Tensor) the center of the hypersphere as a multidimensional vector. |---- eta (float) ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeepSADLoss:
"""Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019)"""
def __init__(self, c, eta, eps=1e-06):
"""Constructor of the DeepSAD loss. ---------- INPUT |---- c (torch.Tensor) the center of the hypersphere as a multidimensional vector. |---- eta (float) control the i... | the_stack_v2_python_sparse | Code/src/models/optim/CustomLosses.py | antoine-spahr/X-ray-Anomaly-Detection | train | 3 |
41a937c0f0b63e2ecf56b9041c2aa1e7b7700854 | [
"self.mode = mode\nself.config = config\nif mode == 'train':\n self.data_files = config['train_data_files']\nelif mode == 'train_eval':\n self.data_files = [config['train_data_files'][0]]\nelif mode == 'valid':\n self.data_files = [config['valid_data_file']]\nelif mode == 'test':\n self.data_files = [co... | <|body_start_0|>
self.mode = mode
self.config = config
if mode == 'train':
self.data_files = config['train_data_files']
elif mode == 'train_eval':
self.data_files = [config['train_data_files'][0]]
elif mode == 'valid':
self.data_files = [config... | Wrapper class for input_fn passed to TPUEstimator. | CIFARInput | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CIFARInput:
"""Wrapper class for input_fn passed to TPUEstimator."""
def __init__(self, mode, config):
"""Initializes a CIFARInput object. Args: mode: one of [train, valid, test, augment, sample] config: config dict built from config.py Raises: ValueError: invalid mode or data files"... | stack_v2_sparse_classes_10k_train_007160 | 5,838 | permissive | [
{
"docstring": "Initializes a CIFARInput object. Args: mode: one of [train, valid, test, augment, sample] config: config dict built from config.py Raises: ValueError: invalid mode or data files",
"name": "__init__",
"signature": "def __init__(self, mode, config)"
},
{
"docstring": "Number of ima... | 3 | null | Implement the Python class `CIFARInput` described below.
Class description:
Wrapper class for input_fn passed to TPUEstimator.
Method signatures and docstrings:
- def __init__(self, mode, config): Initializes a CIFARInput object. Args: mode: one of [train, valid, test, augment, sample] config: config dict built from ... | Implement the Python class `CIFARInput` described below.
Class description:
Wrapper class for input_fn passed to TPUEstimator.
Method signatures and docstrings:
- def __init__(self, mode, config): Initializes a CIFARInput object. Args: mode: one of [train, valid, test, augment, sample] config: config dict built from ... | a00c3619bf4042e446e1919087f0b09fe9fa3a65 | <|skeleton|>
class CIFARInput:
"""Wrapper class for input_fn passed to TPUEstimator."""
def __init__(self, mode, config):
"""Initializes a CIFARInput object. Args: mode: one of [train, valid, test, augment, sample] config: config dict built from config.py Raises: ValueError: invalid mode or data files"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CIFARInput:
"""Wrapper class for input_fn passed to TPUEstimator."""
def __init__(self, mode, config):
"""Initializes a CIFARInput object. Args: mode: one of [train, valid, test, augment, sample] config: config dict built from config.py Raises: ValueError: invalid mode or data files"""
se... | the_stack_v2_python_sparse | nasws/cnn/search_space/nasbench101/lib/cifar.py | kcyu2014/nas-landmarkreg | train | 10 |
150b66be3afb67a93774bea2d72c7c11848f8824 | [
"self.config = config\nself._dag_builder = dag_builder\nself._start = start\nself._end = end\nself._freq = freq\nself._fit_state = fit_state\nself.dag = self._dag_builder.get_dag(self.config)\nset_fit_state(self.dag, self._fit_state)\nself._methods = self._dag_builder.methods\nself._column_to_tags_mapping = self._d... | <|body_start_0|>
self.config = config
self._dag_builder = dag_builder
self._start = start
self._end = end
self._freq = freq
self._fit_state = fit_state
self.dag = self._dag_builder.get_dag(self.config)
set_fit_state(self.dag, self._fit_state)
self.... | Class for running DAGs. | IncrementalDagRunner | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IncrementalDagRunner:
"""Class for running DAGs."""
def __init__(self, config: cconfig.Config, dag_builder: DagBuilder, start: _PANDAS_DATE_TYPE, end: _PANDAS_DATE_TYPE, freq: str, fit_state: cconfig.Config) -> None:
"""Initialize DAG. :param config: config for DAG :param dag_builder... | stack_v2_sparse_classes_10k_train_007161 | 8,311 | permissive | [
{
"docstring": "Initialize DAG. :param config: config for DAG :param dag_builder: `DagBuilder` instance :param start: first prediction datetime (e.g., first time at which we generate a prediction in `predict` mode, using all available data up to and including `start`) :param end: last prediction datetime :param... | 4 | stack_v2_sparse_classes_30k_val_000272 | Implement the Python class `IncrementalDagRunner` described below.
Class description:
Class for running DAGs.
Method signatures and docstrings:
- def __init__(self, config: cconfig.Config, dag_builder: DagBuilder, start: _PANDAS_DATE_TYPE, end: _PANDAS_DATE_TYPE, freq: str, fit_state: cconfig.Config) -> None: Initial... | Implement the Python class `IncrementalDagRunner` described below.
Class description:
Class for running DAGs.
Method signatures and docstrings:
- def __init__(self, config: cconfig.Config, dag_builder: DagBuilder, start: _PANDAS_DATE_TYPE, end: _PANDAS_DATE_TYPE, freq: str, fit_state: cconfig.Config) -> None: Initial... | 363c59fa29df2ba2719cbad2f8a19ae12cc54a92 | <|skeleton|>
class IncrementalDagRunner:
"""Class for running DAGs."""
def __init__(self, config: cconfig.Config, dag_builder: DagBuilder, start: _PANDAS_DATE_TYPE, end: _PANDAS_DATE_TYPE, freq: str, fit_state: cconfig.Config) -> None:
"""Initialize DAG. :param config: config for DAG :param dag_builder... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IncrementalDagRunner:
"""Class for running DAGs."""
def __init__(self, config: cconfig.Config, dag_builder: DagBuilder, start: _PANDAS_DATE_TYPE, end: _PANDAS_DATE_TYPE, freq: str, fit_state: cconfig.Config) -> None:
"""Initialize DAG. :param config: config for DAG :param dag_builder: `DagBuilder... | the_stack_v2_python_sparse | core/dataflow/runners.py | srlindemann/amp | train | 0 |
4b730d3e38b819b3c47d559efddf8d6c464e81a6 | [
"test = '2\\n><\\n1 2'\nd = Gh(test)\nself.assertEqual(d.n, 2)\nself.assertEqual(d.numa, [1, 0])\nself.assertEqual(d.numb, [1, 2])\nself.assertEqual(Gh(test).calculate(), 'FINITE')\ntest = '3\\n>><\\n2 1 1'\nself.assertEqual(Gh(test).calculate(), 'INFINITE')\ntest = '4\\n>>><\\n1 1 1 4'\nself.assertEqual(Gh(test).c... | <|body_start_0|>
test = '2\n><\n1 2'
d = Gh(test)
self.assertEqual(d.n, 2)
self.assertEqual(d.numa, [1, 0])
self.assertEqual(d.numb, [1, 2])
self.assertEqual(Gh(test).calculate(), 'FINITE')
test = '3\n>><\n2 1 1'
self.assertEqual(Gh(test).calculate(), 'INF... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Gh class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = '2\n><\n1 2'
d = Gh(test)
self.assertEqual(d.n, 2)
... | stack_v2_sparse_classes_10k_train_007162 | 3,180 | permissive | [
{
"docstring": "Gh class testing",
"name": "test_single_test",
"signature": "def test_single_test(self)"
},
{
"docstring": "Timelimit testing",
"name": "time_limit_test",
"signature": "def time_limit_test(self, nmax)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005420 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Gh class testing
- def time_limit_test(self, nmax): Timelimit testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Gh class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"""Gh ... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Gh class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class unitTests:
def test_single_test(self):
"""Gh class testing"""
test = '2\n><\n1 2'
d = Gh(test)
self.assertEqual(d.n, 2)
self.assertEqual(d.numa, [1, 0])
self.assertEqual(d.numb, [1, 2])
self.assertEqual(Gh(test).calculate(), 'FINITE')
test = '3\n... | the_stack_v2_python_sparse | codeforces/669B_gh.py | snsokolov/contests | train | 1 | |
be03a8751b9802d45a18cf9ec1f9c1a52dab242e | [
"rcounter = 0\nlcounter = len(str) - 1\nself.reverseString(str, rcounter, lcounter)\nfor i in range(len(str)):\n if str[i] == ' ':\n self.reverseString(str, rcounter, i - 1)\n rcounter = i + 1\n elif i == len(str) - 1:\n self.reverseString(str, rcounter, i)\nprint(str)",
"while rcounter... | <|body_start_0|>
rcounter = 0
lcounter = len(str) - 1
self.reverseString(str, rcounter, lcounter)
for i in range(len(str)):
if str[i] == ' ':
self.reverseString(str, rcounter, i - 1)
rcounter = i + 1
elif i == len(str) - 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseWords(self, str):
""":type str: List[str] :rtype: None Do not return anything, modify str in-place instead."""
<|body_0|>
def reverseString(self, s, rcounter, lcounter):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_007163 | 1,633 | no_license | [
{
"docstring": ":type str: List[str] :rtype: None Do not return anything, modify str in-place instead.",
"name": "reverseWords",
"signature": "def reverseWords(self, str)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseString",
"signature": "def reverseString(self, s, rcou... | 2 | stack_v2_sparse_classes_30k_train_003447 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, str): :type str: List[str] :rtype: None Do not return anything, modify str in-place instead.
- def reverseString(self, s, rcounter, lcounter): :type s: str... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, str): :type str: List[str] :rtype: None Do not return anything, modify str in-place instead.
- def reverseString(self, s, rcounter, lcounter): :type s: str... | 786075e0f9f61cf062703bc0b41cc3191d77f033 | <|skeleton|>
class Solution:
def reverseWords(self, str):
""":type str: List[str] :rtype: None Do not return anything, modify str in-place instead."""
<|body_0|>
def reverseString(self, s, rcounter, lcounter):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseWords(self, str):
""":type str: List[str] :rtype: None Do not return anything, modify str in-place instead."""
rcounter = 0
lcounter = len(str) - 1
self.reverseString(str, rcounter, lcounter)
for i in range(len(str)):
if str[i] == ' ':
... | the_stack_v2_python_sparse | reverseWords2.py | Anirban2404/LeetCodePractice | train | 1 | |
06b9e3ef29bb3882f34db0c707a165bd9307ce45 | [
"self._request_args = request_args\nself._baseoid = baseoid\nself._accept_errors = accept_errors\nself._default_value = default_value\nself.value = None",
"get_result = await getCmd(*self._request_args, ObjectType(ObjectIdentity(self._baseoid)))\nerrindication, errstatus, errindex, restable = get_result\nif errin... | <|body_start_0|>
self._request_args = request_args
self._baseoid = baseoid
self._accept_errors = accept_errors
self._default_value = default_value
self.value = None
<|end_body_0|>
<|body_start_1|>
get_result = await getCmd(*self._request_args, ObjectType(ObjectIdentity(s... | Get the latest data and update the states. | SnmpData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnmpData:
"""Get the latest data and update the states."""
def __init__(self, request_args, baseoid, accept_errors, default_value) -> None:
"""Initialize the data object."""
<|body_0|>
async def async_update(self):
"""Get the latest data from the remote SNMP capa... | stack_v2_sparse_classes_10k_train_007164 | 7,962 | permissive | [
{
"docstring": "Initialize the data object.",
"name": "__init__",
"signature": "def __init__(self, request_args, baseoid, accept_errors, default_value) -> None"
},
{
"docstring": "Get the latest data from the remote SNMP capable host.",
"name": "async_update",
"signature": "async def asy... | 2 | null | Implement the Python class `SnmpData` described below.
Class description:
Get the latest data and update the states.
Method signatures and docstrings:
- def __init__(self, request_args, baseoid, accept_errors, default_value) -> None: Initialize the data object.
- async def async_update(self): Get the latest data from... | Implement the Python class `SnmpData` described below.
Class description:
Get the latest data and update the states.
Method signatures and docstrings:
- def __init__(self, request_args, baseoid, accept_errors, default_value) -> None: Initialize the data object.
- async def async_update(self): Get the latest data from... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SnmpData:
"""Get the latest data and update the states."""
def __init__(self, request_args, baseoid, accept_errors, default_value) -> None:
"""Initialize the data object."""
<|body_0|>
async def async_update(self):
"""Get the latest data from the remote SNMP capa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SnmpData:
"""Get the latest data and update the states."""
def __init__(self, request_args, baseoid, accept_errors, default_value) -> None:
"""Initialize the data object."""
self._request_args = request_args
self._baseoid = baseoid
self._accept_errors = accept_errors
... | the_stack_v2_python_sparse | homeassistant/components/snmp/sensor.py | home-assistant/core | train | 35,501 |
1ff5cf19221fcaf3017c0cc3f48325da8afe2ce5 | [
"try:\n db.show_by_id(show_id, session=session)\nexcept NoResultFound:\n raise NotFoundError('show with ID %s not found' % show_id)\ntry:\n episode = db.episode_by_id(ep_id, session)\nexcept NoResultFound:\n raise NotFoundError('episode with ID %s not found' % ep_id)\nif not db.episode_in_show(show_id, ... | <|body_start_0|>
try:
db.show_by_id(show_id, session=session)
except NoResultFound:
raise NotFoundError('show with ID %s not found' % show_id)
try:
episode = db.episode_by_id(ep_id, session)
except NoResultFound:
raise NotFoundError('episod... | SeriesEpisodeAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeriesEpisodeAPI:
def get(self, show_id, ep_id, session):
"""Get episode by show ID and episode ID"""
<|body_0|>
def delete(self, show_id, ep_id, session):
"""Forgets episode by show ID and episode ID"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_007165 | 47,001 | permissive | [
{
"docstring": "Get episode by show ID and episode ID",
"name": "get",
"signature": "def get(self, show_id, ep_id, session)"
},
{
"docstring": "Forgets episode by show ID and episode ID",
"name": "delete",
"signature": "def delete(self, show_id, ep_id, session)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000076 | Implement the Python class `SeriesEpisodeAPI` described below.
Class description:
Implement the SeriesEpisodeAPI class.
Method signatures and docstrings:
- def get(self, show_id, ep_id, session): Get episode by show ID and episode ID
- def delete(self, show_id, ep_id, session): Forgets episode by show ID and episode ... | Implement the Python class `SeriesEpisodeAPI` described below.
Class description:
Implement the SeriesEpisodeAPI class.
Method signatures and docstrings:
- def get(self, show_id, ep_id, session): Get episode by show ID and episode ID
- def delete(self, show_id, ep_id, session): Forgets episode by show ID and episode ... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class SeriesEpisodeAPI:
def get(self, show_id, ep_id, session):
"""Get episode by show ID and episode ID"""
<|body_0|>
def delete(self, show_id, ep_id, session):
"""Forgets episode by show ID and episode ID"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SeriesEpisodeAPI:
def get(self, show_id, ep_id, session):
"""Get episode by show ID and episode ID"""
try:
db.show_by_id(show_id, session=session)
except NoResultFound:
raise NotFoundError('show with ID %s not found' % show_id)
try:
episode =... | the_stack_v2_python_sparse | flexget/components/series/api.py | BrutuZ/Flexget | train | 1 | |
cd12156a6e7f73c286c45431e767df6dd0b40b10 | [
"self.url = url\nself.proxy = Http(cache=self.cache, timeout=self.timeout)\nself.proxy.disable_ssl_certificate_validation = not validate_ssl\nif isinstance(credential, UsernamePassword):\n self.proxy.add_credentials(credential.username, credential.password)",
"if url is None:\n url = self.url\nstatus, respo... | <|body_start_0|>
self.url = url
self.proxy = Http(cache=self.cache, timeout=self.timeout)
self.proxy.disable_ssl_certificate_validation = not validate_ssl
if isinstance(credential, UsernamePassword):
self.proxy.add_credentials(credential.username, credential.password)
<|end_b... | @summary: implements REST driver to fetch using http GET @cvar timeout: timeout of connection @type timeout: float @cvar cache: a cache directory @type cache: str @ivar url: a default document locator to be reused @type url: str @ivar proxy: an interface to the http server @type proxy: httplib2.Http | RESTDriver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RESTDriver:
"""@summary: implements REST driver to fetch using http GET @cvar timeout: timeout of connection @type timeout: float @cvar cache: a cache directory @type cache: str @ivar url: a default document locator to be reused @type url: str @ivar proxy: an interface to the http server @type pr... | stack_v2_sparse_classes_10k_train_007166 | 2,251 | no_license | [
{
"docstring": "@summary: initializes a proxy to the http service and saves a default document locator @param url: the default document locator @type url: str @param credential: an authentication secret @type credential: L{Credential} or None @param validate_ssl: whether to apply strick certificate validation, ... | 2 | stack_v2_sparse_classes_30k_train_005163 | Implement the Python class `RESTDriver` described below.
Class description:
@summary: implements REST driver to fetch using http GET @cvar timeout: timeout of connection @type timeout: float @cvar cache: a cache directory @type cache: str @ivar url: a default document locator to be reused @type url: str @ivar proxy: a... | Implement the Python class `RESTDriver` described below.
Class description:
@summary: implements REST driver to fetch using http GET @cvar timeout: timeout of connection @type timeout: float @cvar cache: a cache directory @type cache: str @ivar url: a default document locator to be reused @type url: str @ivar proxy: a... | 0932550a42ba1ca634225ccb3a4748336e69e022 | <|skeleton|>
class RESTDriver:
"""@summary: implements REST driver to fetch using http GET @cvar timeout: timeout of connection @type timeout: float @cvar cache: a cache directory @type cache: str @ivar url: a default document locator to be reused @type url: str @ivar proxy: an interface to the http server @type pr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RESTDriver:
"""@summary: implements REST driver to fetch using http GET @cvar timeout: timeout of connection @type timeout: float @cvar cache: a cache directory @type cache: str @ivar url: a default document locator to be reused @type url: str @ivar proxy: an interface to the http server @type proxy: httplib2... | the_stack_v2_python_sparse | Monitoring/MonitoringService/Driver/REST.py | vitorsfarias/novi-public | train | 0 |
5ac2dcc82b88e970d6a90cc69f91423b1a236eb9 | [
"SCons.Warnings._enabled = []\nSCons.Warnings._warningAsException = 0\nto = TestOutput()\nSCons.Warnings._warningOut = to\nSCons.Warnings.enableWarningClass(SCons.Warnings.SConsWarning)\nSCons.Warnings.warn(SCons.Warnings.DeprecatedWarning, 'Foo')\nassert to.out == 'Foo', to.out\nSCons.Warnings.warn(SCons.Warnings.... | <|body_start_0|>
SCons.Warnings._enabled = []
SCons.Warnings._warningAsException = 0
to = TestOutput()
SCons.Warnings._warningOut = to
SCons.Warnings.enableWarningClass(SCons.Warnings.SConsWarning)
SCons.Warnings.warn(SCons.Warnings.DeprecatedWarning, 'Foo')
asser... | WarningsTestCase | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WarningsTestCase:
def test_Warning(self) -> None:
"""Test warn function."""
<|body_0|>
def test_WarningAsExc(self) -> None:
"""Test warnings as exceptions."""
<|body_1|>
def test_Disable(self) -> None:
"""Test disabling/enabling warnings."""
... | stack_v2_sparse_classes_10k_train_007167 | 4,552 | permissive | [
{
"docstring": "Test warn function.",
"name": "test_Warning",
"signature": "def test_Warning(self) -> None"
},
{
"docstring": "Test warnings as exceptions.",
"name": "test_WarningAsExc",
"signature": "def test_WarningAsExc(self) -> None"
},
{
"docstring": "Test disabling/enabling... | 3 | null | Implement the Python class `WarningsTestCase` described below.
Class description:
Implement the WarningsTestCase class.
Method signatures and docstrings:
- def test_Warning(self) -> None: Test warn function.
- def test_WarningAsExc(self) -> None: Test warnings as exceptions.
- def test_Disable(self) -> None: Test dis... | Implement the Python class `WarningsTestCase` described below.
Class description:
Implement the WarningsTestCase class.
Method signatures and docstrings:
- def test_Warning(self) -> None: Test warn function.
- def test_WarningAsExc(self) -> None: Test warnings as exceptions.
- def test_Disable(self) -> None: Test dis... | b2a7d7066a2b854460a334a5fe737ea389655e6e | <|skeleton|>
class WarningsTestCase:
def test_Warning(self) -> None:
"""Test warn function."""
<|body_0|>
def test_WarningAsExc(self) -> None:
"""Test warnings as exceptions."""
<|body_1|>
def test_Disable(self) -> None:
"""Test disabling/enabling warnings."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WarningsTestCase:
def test_Warning(self) -> None:
"""Test warn function."""
SCons.Warnings._enabled = []
SCons.Warnings._warningAsException = 0
to = TestOutput()
SCons.Warnings._warningOut = to
SCons.Warnings.enableWarningClass(SCons.Warnings.SConsWarning)
... | the_stack_v2_python_sparse | SCons/WarningsTests.py | SCons/scons | train | 1,827 | |
829f3763db197ec7a84adff17d5e853293cdf327 | [
"if frame.name == self.name:\n raise ValueError('Cannot connect to a frame with the same name.')\nself._connected_frames[frame.name] = transformation_to_frame.inverse\nframe._connected_frames[self.name] = transformation_to_frame",
"if not hasattr(geom_obj, '_frame'):\n raise ValueError('Cannot transform obj... | <|body_start_0|>
if frame.name == self.name:
raise ValueError('Cannot connect to a frame with the same name.')
self._connected_frames[frame.name] = transformation_to_frame.inverse
frame._connected_frames[self.name] = transformation_to_frame
<|end_body_0|>
<|body_start_1|>
if... | Frame | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Frame:
def connect_to(self, frame: 'Frame', *, transformation_to_frame: TransformType):
"""Connect this frame to another frame through a transformation. This also connects the other frame to this one."""
<|body_0|>
def __call__(self, geom_obj):
"""Calling an instance... | stack_v2_sparse_classes_10k_train_007168 | 2,578 | permissive | [
{
"docstring": "Connect this frame to another frame through a transformation. This also connects the other frame to this one.",
"name": "connect_to",
"signature": "def connect_to(self, frame: 'Frame', *, transformation_to_frame: TransformType)"
},
{
"docstring": "Calling an instance transforms t... | 2 | stack_v2_sparse_classes_30k_train_005695 | Implement the Python class `Frame` described below.
Class description:
Implement the Frame class.
Method signatures and docstrings:
- def connect_to(self, frame: 'Frame', *, transformation_to_frame: TransformType): Connect this frame to another frame through a transformation. This also connects the other frame to thi... | Implement the Python class `Frame` described below.
Class description:
Implement the Frame class.
Method signatures and docstrings:
- def connect_to(self, frame: 'Frame', *, transformation_to_frame: TransformType): Connect this frame to another frame through a transformation. This also connects the other frame to thi... | 8a9438b5a24c288721ae0302889fe55e26046310 | <|skeleton|>
class Frame:
def connect_to(self, frame: 'Frame', *, transformation_to_frame: TransformType):
"""Connect this frame to another frame through a transformation. This also connects the other frame to this one."""
<|body_0|>
def __call__(self, geom_obj):
"""Calling an instance... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Frame:
def connect_to(self, frame: 'Frame', *, transformation_to_frame: TransformType):
"""Connect this frame to another frame through a transformation. This also connects the other frame to this one."""
if frame.name == self.name:
raise ValueError('Cannot connect to a frame with t... | the_stack_v2_python_sparse | simulation/utils/geometry/frame.py | KITcar-Team/kitcar-gazebo-simulation | train | 19 | |
969dabc5dd10af54bd649364e4f64d5c5f9e828b | [
"if root:\n if key == root.val:\n if not root.right and (not root.left):\n root = None\n elif root.right:\n tmp = self.get_successor(root)\n root.val = tmp.val\n root.right = self.deleteNode(root.right, tmp.val)\n else:\n tmp = self.get_... | <|body_start_0|>
if root:
if key == root.val:
if not root.right and (not root.left):
root = None
elif root.right:
tmp = self.get_successor(root)
root.val = tmp.val
root.right = self.delete... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteNode(self, root, key):
""":type root: TreeNode :type key: int :rtype: TreeNode"""
<|body_0|>
def get_successor(self, root):
"""Useful when successor is to the right of root."""
<|body_1|>
def get_predeccessor(self, root):
"""U... | stack_v2_sparse_classes_10k_train_007169 | 2,087 | no_license | [
{
"docstring": ":type root: TreeNode :type key: int :rtype: TreeNode",
"name": "deleteNode",
"signature": "def deleteNode(self, root, key)"
},
{
"docstring": "Useful when successor is to the right of root.",
"name": "get_successor",
"signature": "def get_successor(self, root)"
},
{
... | 3 | stack_v2_sparse_classes_30k_test_000041 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteNode(self, root, key): :type root: TreeNode :type key: int :rtype: TreeNode
- def get_successor(self, root): Useful when successor is to the right of root.
- def get_pr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteNode(self, root, key): :type root: TreeNode :type key: int :rtype: TreeNode
- def get_successor(self, root): Useful when successor is to the right of root.
- def get_pr... | 1639a4b13c692d87c658a7e0a11212bf0e98d443 | <|skeleton|>
class Solution:
def deleteNode(self, root, key):
""":type root: TreeNode :type key: int :rtype: TreeNode"""
<|body_0|>
def get_successor(self, root):
"""Useful when successor is to the right of root."""
<|body_1|>
def get_predeccessor(self, root):
"""U... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def deleteNode(self, root, key):
""":type root: TreeNode :type key: int :rtype: TreeNode"""
if root:
if key == root.val:
if not root.right and (not root.left):
root = None
elif root.right:
tmp = self.... | the_stack_v2_python_sparse | medium/delete_node_BST.py | Hashah1/Leetcode-Practice | train | 0 | |
5aac5c6838d935a925a7b4dc29bba06ad5ef82c3 | [
"self.n = n\nself.queens = list()\nif randomize:\n for q in range(n):\n empty_space = False\n while not empty_space:\n row = random.choice(range(n))\n col = random.choice(range(n))\n if not [row, col] in self.queens:\n empty_space = True\n self... | <|body_start_0|>
self.n = n
self.queens = list()
if randomize:
for q in range(n):
empty_space = False
while not empty_space:
row = random.choice(range(n))
col = random.choice(range(n))
if not ... | Class that represents n-queens placed on a chess board. | Board | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Board:
"""Class that represents n-queens placed on a chess board."""
def __init__(self, n, randomize=True):
"""This constructor initializes the board with n queens. n : The number of rows and columns of the chess. randomize : True indicates that the queen positions are choosen random... | stack_v2_sparse_classes_10k_train_007170 | 5,454 | no_license | [
{
"docstring": "This constructor initializes the board with n queens. n : The number of rows and columns of the chess. randomize : True indicates that the queen positions are choosen randomly. False indicates that the queen are placed on the first row.",
"name": "__init__",
"signature": "def __init__(se... | 5 | stack_v2_sparse_classes_30k_train_001254 | Implement the Python class `Board` described below.
Class description:
Class that represents n-queens placed on a chess board.
Method signatures and docstrings:
- def __init__(self, n, randomize=True): This constructor initializes the board with n queens. n : The number of rows and columns of the chess. randomize : T... | Implement the Python class `Board` described below.
Class description:
Class that represents n-queens placed on a chess board.
Method signatures and docstrings:
- def __init__(self, n, randomize=True): This constructor initializes the board with n queens. n : The number of rows and columns of the chess. randomize : T... | bc57784f95a8adfb0154a3fb3d1ef3245e7d22ae | <|skeleton|>
class Board:
"""Class that represents n-queens placed on a chess board."""
def __init__(self, n, randomize=True):
"""This constructor initializes the board with n queens. n : The number of rows and columns of the chess. randomize : True indicates that the queen positions are choosen random... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Board:
"""Class that represents n-queens placed on a chess board."""
def __init__(self, n, randomize=True):
"""This constructor initializes the board with n queens. n : The number of rows and columns of the chess. randomize : True indicates that the queen positions are choosen randomly. False ind... | the_stack_v2_python_sparse | Actividades/Problemas de busqueda local/n_queens_greedy_search.py | gherreraa1/ProjectoSistemasInteligentes | train | 0 |
703dc112382fbf2ddebf10f91d5a2149dd20ca96 | [
"self.key = key\nself.conn = conn\nself.major_opcode = 0\nself.first_event = 0\nself.first_error = 0",
"if self.conn.synchronous_check and request.is_void:\n request.is_checked = True\nxcb_req = libxcb.xcb_protocol_request_t()\nxcb_req.count = 2\nxcb_req.ext = ctypes.pointer(self.key.key) if self.key is not No... | <|body_start_0|>
self.key = key
self.conn = conn
self.major_opcode = 0
self.first_event = 0
self.first_error = 0
<|end_body_0|>
<|body_start_1|>
if self.conn.synchronous_check and request.is_void:
request.is_checked = True
xcb_req = libxcb.xcb_protoco... | A wrapper for an X11 extension. This class provides with a :meth:`Extension.send_request` method. You will most likely do not have to use this class directly. | Extension | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Extension:
"""A wrapper for an X11 extension. This class provides with a :meth:`Extension.send_request` method. You will most likely do not have to use this class directly."""
def __init__(self, conn, key=None):
""":type conn: :class:`ooxcb.conn.Connection` :param key: The correspond... | stack_v2_sparse_classes_10k_train_007171 | 4,339 | no_license | [
{
"docstring": ":type conn: :class:`ooxcb.conn.Connection` :param key: The corresponding :class:`ooxcb.extkey.ExtensionKey` instance (optional)",
"name": "__init__",
"signature": "def __init__(self, conn, key=None)"
},
{
"docstring": "sends *request* to the X server. Then it provides *cookie* wi... | 2 | stack_v2_sparse_classes_30k_train_005749 | Implement the Python class `Extension` described below.
Class description:
A wrapper for an X11 extension. This class provides with a :meth:`Extension.send_request` method. You will most likely do not have to use this class directly.
Method signatures and docstrings:
- def __init__(self, conn, key=None): :type conn: ... | Implement the Python class `Extension` described below.
Class description:
A wrapper for an X11 extension. This class provides with a :meth:`Extension.send_request` method. You will most likely do not have to use this class directly.
Method signatures and docstrings:
- def __init__(self, conn, key=None): :type conn: ... | 84c922db80c899fb2bc319b1f42d2bc0e3d4bfaa | <|skeleton|>
class Extension:
"""A wrapper for an X11 extension. This class provides with a :meth:`Extension.send_request` method. You will most likely do not have to use this class directly."""
def __init__(self, conn, key=None):
""":type conn: :class:`ooxcb.conn.Connection` :param key: The correspond... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Extension:
"""A wrapper for an X11 extension. This class provides with a :meth:`Extension.send_request` method. You will most likely do not have to use this class directly."""
def __init__(self, conn, key=None):
""":type conn: :class:`ooxcb.conn.Connection` :param key: The corresponding :class:`o... | the_stack_v2_python_sparse | ooxcb/ext.py | samurai-x/ooxcb | train | 3 |
1d43d0111833cc8e573a9b2362d205f2612e5e94 | [
"def find(s, l, r):\n while l >= 0 and r < len(s) and (s[l] == s[r]):\n l -= 1\n r += 1\n return s[l + 1:r]\nres = ''\nfor i in range(len(s)):\n res1 = find(s, i, i)\n res2 = find(s, i, i + 1)\n res = max([res, res1, res2], key=len)\nreturn res",
"if len(s) <= 1:\n return s\nmaxVal... | <|body_start_0|>
def find(s, l, r):
while l >= 0 and r < len(s) and (s[l] == s[r]):
l -= 1
r += 1
return s[l + 1:r]
res = ''
for i in range(len(s)):
res1 = find(s, i, i)
res2 = find(s, i, i + 1)
res = max... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def longestPalindrome3(self, s):
""":type s: str :rtype: strc #"""
<|body_2|>
... | stack_v2_sparse_classes_10k_train_007172 | 3,212 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome2",
"signature": "def longestPalindrome2(self, s)"
},
{
"docstring": ":type s: str :rtype:... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome2(self, s): :type s: str :rtype: str
- def longestPalindrome3(self, s): :type s: str :rtype: strc ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome2(self, s): :type s: str :rtype: str
- def longestPalindrome3(self, s): :type s: str :rtype: strc ... | 11c8fc663888b48b5417256aab1bf872190267ba | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def longestPalindrome3(self, s):
""":type s: str :rtype: strc #"""
<|body_2|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
def find(s, l, r):
while l >= 0 and r < len(s) and (s[l] == s[r]):
l -= 1
r += 1
return s[l + 1:r]
res = ''
for i in range(len(s)):
res1 ... | the_stack_v2_python_sparse | Longest Palindromic Substring.py | lfdyf20/Leetcode | train | 1 | |
2955a24ef7d61ddce4e07a01bdd518262cab889f | [
"differentiator.refresh()\nop = differentiator.generate_differentiable_op(analytic_op=op)\n\ndef exact_grad(theta):\n new_theta = 2 * np.pi * theta\n return -2 * np.pi * np.sin(new_theta) * np.exp(np.cos(new_theta))\nbit = cirq.GridQubit(0, 0)\ncircuits = util.convert_to_tensor([cirq.Circuit(cirq.X(bit) ** sy... | <|body_start_0|>
differentiator.refresh()
op = differentiator.generate_differentiable_op(analytic_op=op)
def exact_grad(theta):
new_theta = 2 * np.pi * theta
return -2 * np.pi * np.sin(new_theta) * np.exp(np.cos(new_theta))
bit = cirq.GridQubit(0, 0)
circ... | Test correctness of the differentiators to reference cirq algorithm. | AnalyticGradientCorrectnessTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalyticGradientCorrectnessTest:
"""Test correctness of the differentiators to reference cirq algorithm."""
def test_backprop(self, differentiator, op):
"""Test that gradients are correctly backpropagated through a quantum circuit via comparison to analytical results."""
<|bo... | stack_v2_sparse_classes_10k_train_007173 | 22,303 | permissive | [
{
"docstring": "Test that gradients are correctly backpropagated through a quantum circuit via comparison to analytical results.",
"name": "test_backprop",
"signature": "def test_backprop(self, differentiator, op)"
},
{
"docstring": "Compare TFQ differentiators to fine-grained noiseless cirq fin... | 4 | stack_v2_sparse_classes_30k_train_002070 | Implement the Python class `AnalyticGradientCorrectnessTest` described below.
Class description:
Test correctness of the differentiators to reference cirq algorithm.
Method signatures and docstrings:
- def test_backprop(self, differentiator, op): Test that gradients are correctly backpropagated through a quantum circ... | Implement the Python class `AnalyticGradientCorrectnessTest` described below.
Class description:
Test correctness of the differentiators to reference cirq algorithm.
Method signatures and docstrings:
- def test_backprop(self, differentiator, op): Test that gradients are correctly backpropagated through a quantum circ... | f56257bceb988b743790e1e480eac76fd036d4ff | <|skeleton|>
class AnalyticGradientCorrectnessTest:
"""Test correctness of the differentiators to reference cirq algorithm."""
def test_backprop(self, differentiator, op):
"""Test that gradients are correctly backpropagated through a quantum circuit via comparison to analytical results."""
<|bo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AnalyticGradientCorrectnessTest:
"""Test correctness of the differentiators to reference cirq algorithm."""
def test_backprop(self, differentiator, op):
"""Test that gradients are correctly backpropagated through a quantum circuit via comparison to analytical results."""
differentiator.re... | the_stack_v2_python_sparse | tensorflow_quantum/python/differentiators/gradient_test.py | tensorflow/quantum | train | 1,799 |
796c056f854fb5551e8706d4fc722aa7e0d2835b | [
"self.inactive = inactive\nself.magneto_entity_id = magneto_entity_id\nself.protection_jobs = protection_jobs",
"if dictionary is None:\n return None\ninactive = dictionary.get('inactive')\nmagneto_entity_id = dictionary.get('magnetoEntityId')\nprotection_jobs = None\nif dictionary.get('protectionJobs') != Non... | <|body_start_0|>
self.inactive = inactive
self.magneto_entity_id = magneto_entity_id
self.protection_jobs = protection_jobs
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
inactive = dictionary.get('inactive')
magneto_entity_id = dictionary... | Implementation of the 'ViewProtection' model. Specifies information about the Protection Jobs that are protecting the View. Attributes: inactive (bool): Specifies if this View is an inactive View that was created on this Remote Cluster to store the Snapshots created by replication. This inactive View cannot be NFS or S... | ViewProtection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewProtection:
"""Implementation of the 'ViewProtection' model. Specifies information about the Protection Jobs that are protecting the View. Attributes: inactive (bool): Specifies if this View is an inactive View that was created on this Remote Cluster to store the Snapshots created by replicat... | stack_v2_sparse_classes_10k_train_007174 | 2,558 | permissive | [
{
"docstring": "Constructor for the ViewProtection class",
"name": "__init__",
"signature": "def __init__(self, inactive=None, magneto_entity_id=None, protection_jobs=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary represe... | 2 | stack_v2_sparse_classes_30k_train_004483 | Implement the Python class `ViewProtection` described below.
Class description:
Implementation of the 'ViewProtection' model. Specifies information about the Protection Jobs that are protecting the View. Attributes: inactive (bool): Specifies if this View is an inactive View that was created on this Remote Cluster to ... | Implement the Python class `ViewProtection` described below.
Class description:
Implementation of the 'ViewProtection' model. Specifies information about the Protection Jobs that are protecting the View. Attributes: inactive (bool): Specifies if this View is an inactive View that was created on this Remote Cluster to ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ViewProtection:
"""Implementation of the 'ViewProtection' model. Specifies information about the Protection Jobs that are protecting the View. Attributes: inactive (bool): Specifies if this View is an inactive View that was created on this Remote Cluster to store the Snapshots created by replicat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ViewProtection:
"""Implementation of the 'ViewProtection' model. Specifies information about the Protection Jobs that are protecting the View. Attributes: inactive (bool): Specifies if this View is an inactive View that was created on this Remote Cluster to store the Snapshots created by replication. This ina... | the_stack_v2_python_sparse | cohesity_management_sdk/models/view_protection.py | cohesity/management-sdk-python | train | 24 |
2c5b3255f2bc9fa3d96f5af3b5885f817ee45e34 | [
"if minimum >= maximum:\n raise Error(\"Can't normalize to empty range: \" + f'[{(self.minimum, self.maximum)}]')\nself.minimum = tf.constant(minimum, dtype=tf.float32)\nself.maximum = tf.constant(maximum, dtype=tf.float32)\nsuper().__init__()",
"length = self.maximum - self.minimum\nrange_too_large = tf.math.... | <|body_start_0|>
if minimum >= maximum:
raise Error("Can't normalize to empty range: " + f'[{(self.minimum, self.maximum)}]')
self.minimum = tf.constant(minimum, dtype=tf.float32)
self.maximum = tf.constant(maximum, dtype=tf.float32)
super().__init__()
<|end_body_0|>
<|body_... | Normalize a number in a given range to the range -1, 1. | NormalizeRange | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormalizeRange:
"""Normalize a number in a given range to the range -1, 1."""
def __init__(self, minimum: float, maximum: float):
"""Create a NormalizeRange layer with the indicated range. Args: minimum: A float scalar representing the lower bound on the range. maximum: A float scala... | stack_v2_sparse_classes_10k_train_007175 | 14,886 | permissive | [
{
"docstring": "Create a NormalizeRange layer with the indicated range. Args: minimum: A float scalar representing the lower bound on the range. maximum: A float scalar representing the upper bound on the range. Raises: Error: If an empty range is specified.",
"name": "__init__",
"signature": "def __ini... | 2 | stack_v2_sparse_classes_30k_train_001012 | Implement the Python class `NormalizeRange` described below.
Class description:
Normalize a number in a given range to the range -1, 1.
Method signatures and docstrings:
- def __init__(self, minimum: float, maximum: float): Create a NormalizeRange layer with the indicated range. Args: minimum: A float scalar represen... | Implement the Python class `NormalizeRange` described below.
Class description:
Normalize a number in a given range to the range -1, 1.
Method signatures and docstrings:
- def __init__(self, minimum: float, maximum: float): Create a NormalizeRange layer with the indicated range. Args: minimum: A float scalar represen... | 26ab377a6853463b2efce40970e54d44b91e79ca | <|skeleton|>
class NormalizeRange:
"""Normalize a number in a given range to the range -1, 1."""
def __init__(self, minimum: float, maximum: float):
"""Create a NormalizeRange layer with the indicated range. Args: minimum: A float scalar representing the lower bound on the range. maximum: A float scala... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NormalizeRange:
"""Normalize a number in a given range to the range -1, 1."""
def __init__(self, minimum: float, maximum: float):
"""Create a NormalizeRange layer with the indicated range. Args: minimum: A float scalar representing the lower bound on the range. maximum: A float scalar representin... | the_stack_v2_python_sparse | service/learner/brains/layers.py | stewartmiles/falken | train | 1 |
3366cdec7d755a4e7561abdab73899e58ad0b0ea | [
"from dials.algorithms.background.gmodel import Creator\nmodel = global_model_cache.get(model)\nself._create = Creator(model=model, robust=robust, min_pixels=min_pixels)",
"if image_volume is None:\n success = self._create(reflections)\n reflections['background.mean'] = reflections['shoebox'].mean_modelled_... | <|body_start_0|>
from dials.algorithms.background.gmodel import Creator
model = global_model_cache.get(model)
self._create = Creator(model=model, robust=robust, min_pixels=min_pixels)
<|end_body_0|>
<|body_start_1|>
if image_volume is None:
success = self._create(reflections... | Class to do background subtraction. | BackgroundAlgorithm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackgroundAlgorithm:
"""Class to do background subtraction."""
def __init__(self, experiments, model=None, robust=False, tuning_constant=1.345, min_pixels=10):
"""Initialise the algorithm. :param experiments: The list of experiments :param model: The background model :param robust: U... | stack_v2_sparse_classes_10k_train_007176 | 2,824 | permissive | [
{
"docstring": "Initialise the algorithm. :param experiments: The list of experiments :param model: The background model :param robust: Use the robust background algorithm :param tuning_constant: The robust tuning constant",
"name": "__init__",
"signature": "def __init__(self, experiments, model=None, r... | 2 | null | Implement the Python class `BackgroundAlgorithm` described below.
Class description:
Class to do background subtraction.
Method signatures and docstrings:
- def __init__(self, experiments, model=None, robust=False, tuning_constant=1.345, min_pixels=10): Initialise the algorithm. :param experiments: The list of experi... | Implement the Python class `BackgroundAlgorithm` described below.
Class description:
Class to do background subtraction.
Method signatures and docstrings:
- def __init__(self, experiments, model=None, robust=False, tuning_constant=1.345, min_pixels=10): Initialise the algorithm. :param experiments: The list of experi... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class BackgroundAlgorithm:
"""Class to do background subtraction."""
def __init__(self, experiments, model=None, robust=False, tuning_constant=1.345, min_pixels=10):
"""Initialise the algorithm. :param experiments: The list of experiments :param model: The background model :param robust: U... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BackgroundAlgorithm:
"""Class to do background subtraction."""
def __init__(self, experiments, model=None, robust=False, tuning_constant=1.345, min_pixels=10):
"""Initialise the algorithm. :param experiments: The list of experiments :param model: The background model :param robust: Use the robust... | the_stack_v2_python_sparse | src/dials/algorithms/background/gmodel/algorithm.py | dials/dials | train | 71 |
5eaaaf7a891fe628366957175dac812bb10f7455 | [
"result = False\nif pRoot1 != None and pRoot2 != None:\n if pRoot1.val == pRoot2.val:\n result = self.same(pRoot1, pRoot2)\n if not result:\n result = self.HasSubtree(pRoot1.left, pRoot2)\n if not result:\n result = self.HasSubtree(pRoot1.right, pRoot2)\nreturn result",
"if pRoot2 ==... | <|body_start_0|>
result = False
if pRoot1 != None and pRoot2 != None:
if pRoot1.val == pRoot2.val:
result = self.same(pRoot1, pRoot2)
if not result:
result = self.HasSubtree(pRoot1.left, pRoot2)
if not result:
result = s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
"""递归实现:判断二叉树B是否为二叉树A的子结构,首先找到相同根结点"""
<|body_0|>
def same(self, pRoot1, pRoot2):
"""如果根结点相同,则分别判断左右子结点是否相同,直到二叉树B的子节点为空"""
<|body_1|>
def HasSubtree2(self, pRoot1, pRoot2):
"""非递归实现:判断二叉树B是否为二叉树A的子... | stack_v2_sparse_classes_10k_train_007177 | 4,104 | no_license | [
{
"docstring": "递归实现:判断二叉树B是否为二叉树A的子结构,首先找到相同根结点",
"name": "HasSubtree",
"signature": "def HasSubtree(self, pRoot1, pRoot2)"
},
{
"docstring": "如果根结点相同,则分别判断左右子结点是否相同,直到二叉树B的子节点为空",
"name": "same",
"signature": "def same(self, pRoot1, pRoot2)"
},
{
"docstring": "非递归实现:判断二叉树B是否为二叉... | 4 | stack_v2_sparse_classes_30k_train_003639 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def HasSubtree(self, pRoot1, pRoot2): 递归实现:判断二叉树B是否为二叉树A的子结构,首先找到相同根结点
- def same(self, pRoot1, pRoot2): 如果根结点相同,则分别判断左右子结点是否相同,直到二叉树B的子节点为空
- def HasSubtree2(self, pRoot1, pRoot... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def HasSubtree(self, pRoot1, pRoot2): 递归实现:判断二叉树B是否为二叉树A的子结构,首先找到相同根结点
- def same(self, pRoot1, pRoot2): 如果根结点相同,则分别判断左右子结点是否相同,直到二叉树B的子节点为空
- def HasSubtree2(self, pRoot1, pRoot... | 4e4f739402b95691f6c91411da26d7d3bfe042b6 | <|skeleton|>
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
"""递归实现:判断二叉树B是否为二叉树A的子结构,首先找到相同根结点"""
<|body_0|>
def same(self, pRoot1, pRoot2):
"""如果根结点相同,则分别判断左右子结点是否相同,直到二叉树B的子节点为空"""
<|body_1|>
def HasSubtree2(self, pRoot1, pRoot2):
"""非递归实现:判断二叉树B是否为二叉树A的子... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def HasSubtree(self, pRoot1, pRoot2):
"""递归实现:判断二叉树B是否为二叉树A的子结构,首先找到相同根结点"""
result = False
if pRoot1 != None and pRoot2 != None:
if pRoot1.val == pRoot2.val:
result = self.same(pRoot1, pRoot2)
if not result:
result = se... | the_stack_v2_python_sparse | 剑指offer/17.树的子结构.py | hugechuanqi/Algorithms-and-Data-Structures | train | 3 | |
5790083497e46ef6365b2f805fcbdcfad01e7824 | [
"self.name = name\nself.given_name = given_name\nself.middle_name = middle_name\nself.family_name = family_name\nself.address = address\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nname = dictionary.get('name')\ngiven_name = dictionary.get('givenName')\nmiddle_na... | <|body_start_0|>
self.name = name
self.given_name = given_name
self.middle_name = middle_name
self.family_name = family_name
self.address = address
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'Payroll Employee Record' model. TODO: type model description here. Attributes: name (string): Full name of the employee: first, middle (if stated), and last name. given_name (string): First name of employee middle_name (string): Middle name of employee, if stated family_name (string): Last name o... | PayrollEmployeeRecord | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PayrollEmployeeRecord:
"""Implementation of the 'Payroll Employee Record' model. TODO: type model description here. Attributes: name (string): Full name of the employee: first, middle (if stated), and last name. given_name (string): First name of employee middle_name (string): Middle name of empl... | stack_v2_sparse_classes_10k_train_007178 | 2,958 | permissive | [
{
"docstring": "Constructor for the PayrollEmployeeRecord class",
"name": "__init__",
"signature": "def __init__(self, name=None, given_name=None, middle_name=None, family_name=None, address=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary A... | 2 | stack_v2_sparse_classes_30k_test_000035 | Implement the Python class `PayrollEmployeeRecord` described below.
Class description:
Implementation of the 'Payroll Employee Record' model. TODO: type model description here. Attributes: name (string): Full name of the employee: first, middle (if stated), and last name. given_name (string): First name of employee mi... | Implement the Python class `PayrollEmployeeRecord` described below.
Class description:
Implementation of the 'Payroll Employee Record' model. TODO: type model description here. Attributes: name (string): Full name of the employee: first, middle (if stated), and last name. given_name (string): First name of employee mi... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class PayrollEmployeeRecord:
"""Implementation of the 'Payroll Employee Record' model. TODO: type model description here. Attributes: name (string): Full name of the employee: first, middle (if stated), and last name. given_name (string): First name of employee middle_name (string): Middle name of empl... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PayrollEmployeeRecord:
"""Implementation of the 'Payroll Employee Record' model. TODO: type model description here. Attributes: name (string): Full name of the employee: first, middle (if stated), and last name. given_name (string): First name of employee middle_name (string): Middle name of employee, if stat... | the_stack_v2_python_sparse | finicityapi/models/payroll_employee_record.py | monarchmoney/finicity-python | train | 0 |
a60a9d1d7b4bed0bfd34ee413200b467037d3910 | [
"self.initial_backoff = initial_backoff\nself.increment_base = increment_base\nself.random_jitter_range = random_jitter_range\nsuper(ExponentialRetry, self).__init__(retry_total=retry_total, retry_to_secondary=retry_to_secondary, **kwargs)",
"random_generator = random.Random()\nbackoff = self.initial_backoff + (0... | <|body_start_0|>
self.initial_backoff = initial_backoff
self.increment_base = increment_base
self.random_jitter_range = random_jitter_range
super(ExponentialRetry, self).__init__(retry_total=retry_total, retry_to_secondary=retry_to_secondary, **kwargs)
<|end_body_0|>
<|body_start_1|>
... | Exponential retry. | ExponentialRetry | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExponentialRetry:
"""Exponential retry."""
def __init__(self, initial_backoff=15, increment_base=3, retry_total=3, retry_to_secondary=False, random_jitter_range=3, **kwargs):
"""Constructs an Exponential retry object. The initial_backoff is used for the first retry. Subsequent retrie... | stack_v2_sparse_classes_10k_train_007179 | 26,717 | permissive | [
{
"docstring": "Constructs an Exponential retry object. The initial_backoff is used for the first retry. Subsequent retries are retried after initial_backoff + increment_power^retry_count seconds. For example, by default the first retry occurs after 15 seconds, the second after (15+3^1) = 18 seconds, and the th... | 2 | null | Implement the Python class `ExponentialRetry` described below.
Class description:
Exponential retry.
Method signatures and docstrings:
- def __init__(self, initial_backoff=15, increment_base=3, retry_total=3, retry_to_secondary=False, random_jitter_range=3, **kwargs): Constructs an Exponential retry object. The initi... | Implement the Python class `ExponentialRetry` described below.
Class description:
Exponential retry.
Method signatures and docstrings:
- def __init__(self, initial_backoff=15, increment_base=3, retry_total=3, retry_to_secondary=False, random_jitter_range=3, **kwargs): Constructs an Exponential retry object. The initi... | c2ca191e736bb06bfbbbc9493e8325763ba990bb | <|skeleton|>
class ExponentialRetry:
"""Exponential retry."""
def __init__(self, initial_backoff=15, increment_base=3, retry_total=3, retry_to_secondary=False, random_jitter_range=3, **kwargs):
"""Constructs an Exponential retry object. The initial_backoff is used for the first retry. Subsequent retrie... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExponentialRetry:
"""Exponential retry."""
def __init__(self, initial_backoff=15, increment_base=3, retry_total=3, retry_to_secondary=False, random_jitter_range=3, **kwargs):
"""Constructs an Exponential retry object. The initial_backoff is used for the first retry. Subsequent retries are retried... | the_stack_v2_python_sparse | sdk/eventhub/azure-eventhub-checkpointstoreblob-aio/azure/eventhub/extensions/checkpointstoreblobaio/_vendor/storage/blob/_shared/policies.py | Azure/azure-sdk-for-python | train | 4,046 |
ee774693af6da70f02410cb5857f1b0da6f27c4c | [
"self.vec = vec2d\nself.cur_ind = 0\nself.lst_ind = 0",
"ret = self.vec[self.cur_ind][self.lst_ind]\nif len(self.vec[self.cur_ind]) - 1 == self.lst_ind:\n self.cur_ind += 1\n self.lst_ind = 0\nelse:\n self.lst_ind += 1\nreturn ret",
"while self.cur_ind < len(self.vec):\n if self.vec[self.cur_ind]:\n... | <|body_start_0|>
self.vec = vec2d
self.cur_ind = 0
self.lst_ind = 0
<|end_body_0|>
<|body_start_1|>
ret = self.vec[self.cur_ind][self.lst_ind]
if len(self.vec[self.cur_ind]) - 1 == self.lst_ind:
self.cur_ind += 1
self.lst_ind = 0
else:
... | Vector2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_10k_train_007180 | 1,177 | no_license | [
{
"docstring": "Initialize your data structure here. :type vec2d: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, vec2d)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",... | 3 | stack_v2_sparse_classes_30k_train_005650 | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool
<|skeleton|>
class V... | b619498d2b8b5e53b629b664fabcff0b68c10897 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
self.vec = vec2d
self.cur_ind = 0
self.lst_ind = 0
def next(self):
""":rtype: int"""
ret = self.vec[self.cur_ind][self.lst_ind]
if len(self.... | the_stack_v2_python_sparse | flatten_2d.py | MatthewC221/Algorithms | train | 1 | |
ad9c7b8eea210efa758866d01b2cf23a4ee745bb | [
"pygame.init()\nself.screen = pygame.display.set_mode((1200, 800))\npygame.display.set_caption('Trench Run')\nself.falcon = Falcon(self)\nself.bg_color = (0, 0, 230)",
"while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n self.screen.fill(self.bg_co... | <|body_start_0|>
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption('Trench Run')
self.falcon = Falcon(self)
self.bg_color = (0, 0, 230)
<|end_body_0|>
<|body_start_1|>
while True:
for event in pygame.event.get():
... | Overall class to manage game assets and behavior. | TrenchRun | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrenchRun:
"""Overall class to manage game assets and behavior."""
def __init__(self):
"""Initialize the game and create the game resources"""
<|body_0|>
def run_game(self):
"""start the main loop of the game"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_10k_train_007181 | 1,155 | no_license | [
{
"docstring": "Initialize the game and create the game resources",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "start the main loop of the game",
"name": "run_game",
"signature": "def run_game(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000395 | Implement the Python class `TrenchRun` described below.
Class description:
Overall class to manage game assets and behavior.
Method signatures and docstrings:
- def __init__(self): Initialize the game and create the game resources
- def run_game(self): start the main loop of the game | Implement the Python class `TrenchRun` described below.
Class description:
Overall class to manage game assets and behavior.
Method signatures and docstrings:
- def __init__(self): Initialize the game and create the game resources
- def run_game(self): start the main loop of the game
<|skeleton|>
class TrenchRun:
... | 18784c7e3abfb74f85f8c96cb0f8e606cab6dccc | <|skeleton|>
class TrenchRun:
"""Overall class to manage game assets and behavior."""
def __init__(self):
"""Initialize the game and create the game resources"""
<|body_0|>
def run_game(self):
"""start the main loop of the game"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TrenchRun:
"""Overall class to manage game assets and behavior."""
def __init__(self):
"""Initialize the game and create the game resources"""
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption('Trench Run')
self.falcon = Fa... | the_stack_v2_python_sparse | chapter_12/falcon_game/blue_sky.py | mwnickerson/python-crash-course | train | 0 |
b39c5e6d3f0a30cb5d5c9348c1c341344b9e76de | [
"if not strs:\n return ''\nprefix = strs[0]\nfor i in range(1, len(strs)):\n prefix = self.prefix_of_two(prefix, strs[i])\nreturn prefix",
"min_len = min(len(first), len(second))\ni = 0\nwhile i < min_len and first[i] == second[i]:\n i += 1\nreturn first[0:i]",
"def recursion(prefix, ind):\n if ind ... | <|body_start_0|>
if not strs:
return ''
prefix = strs[0]
for i in range(1, len(strs)):
prefix = self.prefix_of_two(prefix, strs[i])
return prefix
<|end_body_0|>
<|body_start_1|>
min_len = min(len(first), len(second))
i = 0
while i < min_le... | Solution for Leetcode problem 14: Longest Common Prefix. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Solution for Leetcode problem 14: Longest Common Prefix."""
def longest_common_prefix(self, strs):
"""Find the longest common prefix of given strings. :type strs: List[str] :rtype: str"""
<|body_0|>
def prefix_of_two(self, first, second):
"""Find the... | stack_v2_sparse_classes_10k_train_007182 | 2,028 | no_license | [
{
"docstring": "Find the longest common prefix of given strings. :type strs: List[str] :rtype: str",
"name": "longest_common_prefix",
"signature": "def longest_common_prefix(self, strs)"
},
{
"docstring": "Find the common prefix of two strings.",
"name": "prefix_of_two",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_000161 | Implement the Python class `Solution` described below.
Class description:
Solution for Leetcode problem 14: Longest Common Prefix.
Method signatures and docstrings:
- def longest_common_prefix(self, strs): Find the longest common prefix of given strings. :type strs: List[str] :rtype: str
- def prefix_of_two(self, fir... | Implement the Python class `Solution` described below.
Class description:
Solution for Leetcode problem 14: Longest Common Prefix.
Method signatures and docstrings:
- def longest_common_prefix(self, strs): Find the longest common prefix of given strings. :type strs: List[str] :rtype: str
- def prefix_of_two(self, fir... | e11bfc454789e716055b80873af0817ec8588aea | <|skeleton|>
class Solution:
"""Solution for Leetcode problem 14: Longest Common Prefix."""
def longest_common_prefix(self, strs):
"""Find the longest common prefix of given strings. :type strs: List[str] :rtype: str"""
<|body_0|>
def prefix_of_two(self, first, second):
"""Find the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""Solution for Leetcode problem 14: Longest Common Prefix."""
def longest_common_prefix(self, strs):
"""Find the longest common prefix of given strings. :type strs: List[str] :rtype: str"""
if not strs:
return ''
prefix = strs[0]
for i in range(1, le... | the_stack_v2_python_sparse | p14/problem14.py | stanl3y/leetcode | train | 0 |
f0f3bdc3d9e98670d652e37d67ec6a640cdde081 | [
"correlationIterable = self._mergeCorrelationIterable(correlationIterable)\nif self._maximumValueCountThreshold is not None:\n correlationIterable = self._removeNodesWithTooManyValues(correlationIterable, self._maximumValueCountThreshold)\nreturn correlationIterable",
"lastCorrelation = None\nfor correlation i... | <|body_start_0|>
correlationIterable = self._mergeCorrelationIterable(correlationIterable)
if self._maximumValueCountThreshold is not None:
correlationIterable = self._removeNodesWithTooManyValues(correlationIterable, self._maximumValueCountThreshold)
return correlationIterable
<|end... | Takes care of merging correlations | CorrelationMergeDelegate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CorrelationMergeDelegate:
"""Takes care of merging correlations"""
def mergeCorrelationIterable(self, correlationIterable):
""":type correlationIterable: Iterable"""
<|body_0|>
def _mergeCorrelationIterable(self, correlationIterable):
""":type correlationIterable... | stack_v2_sparse_classes_10k_train_007183 | 7,995 | no_license | [
{
"docstring": ":type correlationIterable: Iterable",
"name": "mergeCorrelationIterable",
"signature": "def mergeCorrelationIterable(self, correlationIterable)"
},
{
"docstring": ":type correlationIterable: Iterable",
"name": "_mergeCorrelationIterable",
"signature": "def _mergeCorrelati... | 5 | stack_v2_sparse_classes_30k_train_006849 | Implement the Python class `CorrelationMergeDelegate` described below.
Class description:
Takes care of merging correlations
Method signatures and docstrings:
- def mergeCorrelationIterable(self, correlationIterable): :type correlationIterable: Iterable
- def _mergeCorrelationIterable(self, correlationIterable): :typ... | Implement the Python class `CorrelationMergeDelegate` described below.
Class description:
Takes care of merging correlations
Method signatures and docstrings:
- def mergeCorrelationIterable(self, correlationIterable): :type correlationIterable: Iterable
- def _mergeCorrelationIterable(self, correlationIterable): :typ... | 7915b67d07288145a2fa46a7fce3e47edad4e6c7 | <|skeleton|>
class CorrelationMergeDelegate:
"""Takes care of merging correlations"""
def mergeCorrelationIterable(self, correlationIterable):
""":type correlationIterable: Iterable"""
<|body_0|>
def _mergeCorrelationIterable(self, correlationIterable):
""":type correlationIterable... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CorrelationMergeDelegate:
"""Takes care of merging correlations"""
def mergeCorrelationIterable(self, correlationIterable):
""":type correlationIterable: Iterable"""
correlationIterable = self._mergeCorrelationIterable(correlationIterable)
if self._maximumValueCountThreshold is no... | the_stack_v2_python_sparse | modsecurity_exception_factory/correlation/correlation_merge_delegate.py | akadata/modsecurity-exception-factory | train | 0 |
4f2487efd3bb2d56cb4e502bf08783ff5ef3f2a4 | [
"pre_head = ListNode(-1)\nprev = pre_head\nwhile l1 and l2:\n if l1.val <= l2.val:\n prev.next = l1\n l1 = l1.next\n else:\n prev.next = l2\n l2 = l2.next\n prev = prev.next\nprev.next = l1 if l1 is not None else l2\nreturn pre_head.next",
"if not l1:\n return l2\nif not l2... | <|body_start_0|>
pre_head = ListNode(-1)
prev = pre_head
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
prev.next = l1... | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""迭代"""
<|body_0|>
def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode:
"""递归"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pre_head = ListNode(-... | stack_v2_sparse_classes_10k_train_007184 | 2,635 | no_license | [
{
"docstring": "迭代",
"name": "merge_two_lists",
"signature": "def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode"
},
{
"docstring": "递归",
"name": "merge_two_lists_2",
"signature": "def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode"
}
] | 2 | null | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode: 迭代
- def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode: 递归 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode: 迭代
- def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode: 递归
<|skeleton|>
clas... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class OfficialSolution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""迭代"""
<|body_0|>
def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode:
"""递归"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OfficialSolution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""迭代"""
pre_head = ListNode(-1)
prev = pre_head
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
... | the_stack_v2_python_sparse | 0021_merge-two-sorted-lists.py | Nigirimeshi/leetcode | train | 0 | |
793b9f393ca69ed8fb8cd628d77684031e5174b5 | [
"subsets_A = set()\nsubsets_B = set()\nused = set()\nfor i in range(len(graph)):\n if i not in used:\n subsets_A.add(i)\n cur_list = [i]\n count = 0\n while cur_list:\n next_list = []\n for j in cur_list:\n used.add(j)\n for opposite... | <|body_start_0|>
subsets_A = set()
subsets_B = set()
used = set()
for i in range(len(graph)):
if i not in used:
subsets_A.add(i)
cur_list = [i]
count = 0
while cur_list:
next_list = []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBipartite(self, graph):
""":type graph: List[List[int]] :rtype: bool 514ms"""
<|body_0|>
def isBipartite_1(self, graph):
""":type graph: List[List[int]] :rtype: bool 50ms"""
<|body_1|>
def isBipartite_2(self, graph):
""":type grap... | stack_v2_sparse_classes_10k_train_007185 | 4,734 | no_license | [
{
"docstring": ":type graph: List[List[int]] :rtype: bool 514ms",
"name": "isBipartite",
"signature": "def isBipartite(self, graph)"
},
{
"docstring": ":type graph: List[List[int]] :rtype: bool 50ms",
"name": "isBipartite_1",
"signature": "def isBipartite_1(self, graph)"
},
{
"do... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBipartite(self, graph): :type graph: List[List[int]] :rtype: bool 514ms
- def isBipartite_1(self, graph): :type graph: List[List[int]] :rtype: bool 50ms
- def isBipartite_2... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBipartite(self, graph): :type graph: List[List[int]] :rtype: bool 514ms
- def isBipartite_1(self, graph): :type graph: List[List[int]] :rtype: bool 50ms
- def isBipartite_2... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def isBipartite(self, graph):
""":type graph: List[List[int]] :rtype: bool 514ms"""
<|body_0|>
def isBipartite_1(self, graph):
""":type graph: List[List[int]] :rtype: bool 50ms"""
<|body_1|>
def isBipartite_2(self, graph):
""":type grap... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isBipartite(self, graph):
""":type graph: List[List[int]] :rtype: bool 514ms"""
subsets_A = set()
subsets_B = set()
used = set()
for i in range(len(graph)):
if i not in used:
subsets_A.add(i)
cur_list = [i]
... | the_stack_v2_python_sparse | IsGraphBipartite_MID_785.py | 953250587/leetcode-python | train | 2 | |
ac27729641320ff682f79f4bc86bd665046dbdbc | [
"self.archival_target = archival_target\nself.attempt_number = attempt_number\nself.cloud_deploy_target = cloud_deploy_target\nself.job_run_id = job_run_id\nself.job_uid = job_uid\nself.parent_source = parent_source\nself.restore_time_usecs = restore_time_usecs\nself.snapshot_relative_dir_path = snapshot_relative_d... | <|body_start_0|>
self.archival_target = archival_target
self.attempt_number = attempt_number
self.cloud_deploy_target = cloud_deploy_target
self.job_run_id = job_run_id
self.job_uid = job_uid
self.parent_source = parent_source
self.restore_time_usecs = restore_tim... | Implementation of the 'RestoreInfo' model. Specifies the info regarding a full SQL snapshot. Attributes: archival_target (ArchivalExternalTarget): Specifies the info related to the archival target. attempt_number (int): Specifies the attempt number. cloud_deploy_target (CloudDeployTargetDetails): Specifies the info rel... | RestoreInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreInfo:
"""Implementation of the 'RestoreInfo' model. Specifies the info regarding a full SQL snapshot. Attributes: archival_target (ArchivalExternalTarget): Specifies the info related to the archival target. attempt_number (int): Specifies the attempt number. cloud_deploy_target (CloudDeplo... | stack_v2_sparse_classes_10k_train_007186 | 5,776 | permissive | [
{
"docstring": "Constructor for the RestoreInfo class",
"name": "__init__",
"signature": "def __init__(self, archival_target=None, attempt_number=None, cloud_deploy_target=None, job_run_id=None, job_uid=None, parent_source=None, restore_time_usecs=None, snapshot_relative_dir_path=None, source=None, star... | 2 | null | Implement the Python class `RestoreInfo` described below.
Class description:
Implementation of the 'RestoreInfo' model. Specifies the info regarding a full SQL snapshot. Attributes: archival_target (ArchivalExternalTarget): Specifies the info related to the archival target. attempt_number (int): Specifies the attempt ... | Implement the Python class `RestoreInfo` described below.
Class description:
Implementation of the 'RestoreInfo' model. Specifies the info regarding a full SQL snapshot. Attributes: archival_target (ArchivalExternalTarget): Specifies the info related to the archival target. attempt_number (int): Specifies the attempt ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreInfo:
"""Implementation of the 'RestoreInfo' model. Specifies the info regarding a full SQL snapshot. Attributes: archival_target (ArchivalExternalTarget): Specifies the info related to the archival target. attempt_number (int): Specifies the attempt number. cloud_deploy_target (CloudDeplo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RestoreInfo:
"""Implementation of the 'RestoreInfo' model. Specifies the info regarding a full SQL snapshot. Attributes: archival_target (ArchivalExternalTarget): Specifies the info related to the archival target. attempt_number (int): Specifies the attempt number. cloud_deploy_target (CloudDeployTargetDetail... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_info.py | cohesity/management-sdk-python | train | 24 |
de859d29920751f60693d33d27c764ef6a1a3a94 | [
"import sys\nmax_area = 0\nn = len(heights)\nif n == 1:\n max_area = heights[0]\nfor i in range(n):\n min_height = sys.maxsize\n for j in range(i, n):\n min_height = min(heights[j], min_height)\n x = j - i + 1\n area = x * min_height\n max_area = max(max_area, area)\nprint(max_a... | <|body_start_0|>
import sys
max_area = 0
n = len(heights)
if n == 1:
max_area = heights[0]
for i in range(n):
min_height = sys.maxsize
for j in range(i, n):
min_height = min(heights[j], min_height)
x = j - i + 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_0|>
def largestRectangleArea2(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
def largestRectangleArea3(self, heights):
"""... | stack_v2_sparse_classes_10k_train_007187 | 2,560 | no_license | [
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, heights)"
},
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "largestRectangleArea2",
"signature": "def largestRectangleArea2(self, heights)"... | 3 | stack_v2_sparse_classes_30k_train_000392 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def largestRectangleArea2(self, heights): :type heights: List[int] :rtype: int
- def largestRectan... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def largestRectangleArea2(self, heights): :type heights: List[int] :rtype: int
- def largestRectan... | 3b13b36f37eb364410b3b5b4f10a1808d8b1111e | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_0|>
def largestRectangleArea2(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
def largestRectangleArea3(self, heights):
"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
import sys
max_area = 0
n = len(heights)
if n == 1:
max_area = heights[0]
for i in range(n):
min_height = sys.maxsize
for j in range... | the_stack_v2_python_sparse | leetcode/84.py | yanggelinux/algorithm-data-structure | train | 0 | |
d44ee11b31b99b9e325a3fc195c5f95565ecedb0 | [
"self.model = model\nself.hyperparams = hyperparams\nself.folds = folds\nself.max_parallel = max_parallel\nkeys, values = zip(*hyperparams.items())\nself.experiments: List[Dict[str, Any]] = [dict(zip(keys, v)) for v in product(*values)]",
"compute_scores_and_append = _ResultsAccumulator(measures)\nmodels = [self.... | <|body_start_0|>
self.model = model
self.hyperparams = hyperparams
self.folds = folds
self.max_parallel = max_parallel
keys, values = zip(*hyperparams.items())
self.experiments: List[Dict[str, Any]] = [dict(zip(keys, v)) for v in product(*values)]
<|end_body_0|>
<|body_s... | Object used to run cross-validation on a model. | CrossValidator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrossValidator:
"""Object used to run cross-validation on a model."""
def __init__(self, model: Type[InAlgorithm], hyperparams: Mapping[str, Sequence[Any]], folds: int=3, max_parallel: int=0):
"""The constructor takes the following arguments. Args: model: the class (not an instance) ... | stack_v2_sparse_classes_10k_train_007188 | 8,837 | no_license | [
{
"docstring": "The constructor takes the following arguments. Args: model: the class (not an instance) of the model for cross validation hyperparams: a dictionary where the keys are the names of hyperparameters and the values are lists of possible values for the hyperparameters folds: the number of folds max_p... | 3 | stack_v2_sparse_classes_30k_train_004865 | Implement the Python class `CrossValidator` described below.
Class description:
Object used to run cross-validation on a model.
Method signatures and docstrings:
- def __init__(self, model: Type[InAlgorithm], hyperparams: Mapping[str, Sequence[Any]], folds: int=3, max_parallel: int=0): The constructor takes the follo... | Implement the Python class `CrossValidator` described below.
Class description:
Object used to run cross-validation on a model.
Method signatures and docstrings:
- def __init__(self, model: Type[InAlgorithm], hyperparams: Mapping[str, Sequence[Any]], folds: int=3, max_parallel: int=0): The constructor takes the follo... | 3aecb7642d9611ae0a61cd47948931f8f47b6f76 | <|skeleton|>
class CrossValidator:
"""Object used to run cross-validation on a model."""
def __init__(self, model: Type[InAlgorithm], hyperparams: Mapping[str, Sequence[Any]], folds: int=3, max_parallel: int=0):
"""The constructor takes the following arguments. Args: model: the class (not an instance) ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CrossValidator:
"""Object used to run cross-validation on a model."""
def __init__(self, model: Type[InAlgorithm], hyperparams: Mapping[str, Sequence[Any]], folds: int=3, max_parallel: int=0):
"""The constructor takes the following arguments. Args: model: the class (not an instance) of the model ... | the_stack_v2_python_sparse | ethicml/evaluators/cross_validator.py | anonymous-iclr-3518/code-for-submission | train | 0 |
bc1b6eadf626558edb0e134e6c91ad242a012af1 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | AutoML Prediction API. On any input that is documented to expect a string parameter in snake_case or kebab-case, either of those cases is accepted. | PredictionServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PredictionServiceServicer:
"""AutoML Prediction API. On any input that is documented to expect a string parameter in snake_case or kebab-case, either of those cases is accepted."""
def Predict(self, request, context):
"""Perform an online prediction. The prediction result will be dir... | stack_v2_sparse_classes_10k_train_007189 | 4,461 | permissive | [
{
"docstring": "Perform an online prediction. The prediction result will be directly returned in the response. Available for following ML problems, and their expected request payloads: * Image Classification - Image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. * Image Object Detection - Image in .JPEG... | 2 | stack_v2_sparse_classes_30k_train_000398 | Implement the Python class `PredictionServiceServicer` described below.
Class description:
AutoML Prediction API. On any input that is documented to expect a string parameter in snake_case or kebab-case, either of those cases is accepted.
Method signatures and docstrings:
- def Predict(self, request, context): Perfor... | Implement the Python class `PredictionServiceServicer` described below.
Class description:
AutoML Prediction API. On any input that is documented to expect a string parameter in snake_case or kebab-case, either of those cases is accepted.
Method signatures and docstrings:
- def Predict(self, request, context): Perfor... | d897d56bce03d1fda98b79afb08264e51d46c421 | <|skeleton|>
class PredictionServiceServicer:
"""AutoML Prediction API. On any input that is documented to expect a string parameter in snake_case or kebab-case, either of those cases is accepted."""
def Predict(self, request, context):
"""Perform an online prediction. The prediction result will be dir... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PredictionServiceServicer:
"""AutoML Prediction API. On any input that is documented to expect a string parameter in snake_case or kebab-case, either of those cases is accepted."""
def Predict(self, request, context):
"""Perform an online prediction. The prediction result will be directly returne... | the_stack_v2_python_sparse | automl/google/cloud/automl_v1/proto/prediction_service_pb2_grpc.py | tswast/google-cloud-python | train | 1 |
0f8d2ecef4f95c75a59ceaa6267a8841fd9c93e8 | [
"p_list = list(p)\nif isinstance(p[1], dict):\n p[0] = p[1]\n if 'NO' in p_list:\n p[0]['encrypt']['salt'] = False\n elif 'USING' in p_list:\n p[0]['encrypt']['encryption_algorithm'] = p_list[-1]\n elif 'SALT' not in p_list:\n p[0]['encrypt']['integrity_algorithm'] = p_list[-1]\nels... | <|body_start_0|>
p_list = list(p)
if isinstance(p[1], dict):
p[0] = p[1]
if 'NO' in p_list:
p[0]['encrypt']['salt'] = False
elif 'USING' in p_list:
p[0]['encrypt']['encryption_algorithm'] = p_list[-1]
elif 'SALT' not in p_li... | Oracle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Oracle:
def p_encrypt(self, p):
"""encrypt : ENCRYPT | encrypt NO SALT | encrypt SALT | encrypt USING STRING | encrypt STRING"""
<|body_0|>
def p_storage(self, p):
"""storage : STORAGE LP | storage id id | storage id id RP"""
<|body_1|>
def p_expr_storag... | stack_v2_sparse_classes_10k_train_007190 | 1,438 | permissive | [
{
"docstring": "encrypt : ENCRYPT | encrypt NO SALT | encrypt SALT | encrypt USING STRING | encrypt STRING",
"name": "p_encrypt",
"signature": "def p_encrypt(self, p)"
},
{
"docstring": "storage : STORAGE LP | storage id id | storage id id RP",
"name": "p_storage",
"signature": "def p_st... | 3 | stack_v2_sparse_classes_30k_val_000290 | Implement the Python class `Oracle` described below.
Class description:
Implement the Oracle class.
Method signatures and docstrings:
- def p_encrypt(self, p): encrypt : ENCRYPT | encrypt NO SALT | encrypt SALT | encrypt USING STRING | encrypt STRING
- def p_storage(self, p): storage : STORAGE LP | storage id id | st... | Implement the Python class `Oracle` described below.
Class description:
Implement the Oracle class.
Method signatures and docstrings:
- def p_encrypt(self, p): encrypt : ENCRYPT | encrypt NO SALT | encrypt SALT | encrypt USING STRING | encrypt STRING
- def p_storage(self, p): storage : STORAGE LP | storage id id | st... | 8f69c9c3b58990f0d47dbe868fe4a572d51e2de7 | <|skeleton|>
class Oracle:
def p_encrypt(self, p):
"""encrypt : ENCRYPT | encrypt NO SALT | encrypt SALT | encrypt USING STRING | encrypt STRING"""
<|body_0|>
def p_storage(self, p):
"""storage : STORAGE LP | storage id id | storage id id RP"""
<|body_1|>
def p_expr_storag... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Oracle:
def p_encrypt(self, p):
"""encrypt : ENCRYPT | encrypt NO SALT | encrypt SALT | encrypt USING STRING | encrypt STRING"""
p_list = list(p)
if isinstance(p[1], dict):
p[0] = p[1]
if 'NO' in p_list:
p[0]['encrypt']['salt'] = False
... | the_stack_v2_python_sparse | simple_ddl_parser/dialects/oracle.py | bjmc/simple-ddl-parser | train | 0 | |
b90f1a88ebd0e56a2f0dda3f415de66afbbc0bf7 | [
"if 'type' in vals:\n if vals['type'] == 'sol_special':\n vals['current_amount'] = vals['amount']\nreturn super(enrich_category, self).create(vals)",
"if len(self.env['payment.enrich'].search([('enrich_category', '=', self.id), ('state', '!=', 'draft')])) > 0:\n raise exceptions.ValidationError(_('Ca... | <|body_start_0|>
if 'type' in vals:
if vals['type'] == 'sol_special':
vals['current_amount'] = vals['amount']
return super(enrich_category, self).create(vals)
<|end_body_0|>
<|body_start_1|>
if len(self.env['payment.enrich'].search([('enrich_category', '=', self.id),... | To manage enrich category | enrich_category | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class enrich_category:
"""To manage enrich category"""
def create(self, vals):
"""create operation @return: super create() method"""
<|body_0|>
def unlink(self):
"""delete the enrich category record if record in draft state, and create log message to the deleted record... | stack_v2_sparse_classes_10k_train_007191 | 32,018 | no_license | [
{
"docstring": "create operation @return: super create() method",
"name": "create",
"signature": "def create(self, vals)"
},
{
"docstring": "delete the enrich category record if record in draft state, and create log message to the deleted record. @return: super unlink() method",
"name": "unl... | 5 | null | Implement the Python class `enrich_category` described below.
Class description:
To manage enrich category
Method signatures and docstrings:
- def create(self, vals): create operation @return: super create() method
- def unlink(self): delete the enrich category record if record in draft state, and create log message ... | Implement the Python class `enrich_category` described below.
Class description:
To manage enrich category
Method signatures and docstrings:
- def create(self, vals): create operation @return: super create() method
- def unlink(self): delete the enrich category record if record in draft state, and create log message ... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class enrich_category:
"""To manage enrich category"""
def create(self, vals):
"""create operation @return: super create() method"""
<|body_0|>
def unlink(self):
"""delete the enrich category record if record in draft state, and create log message to the deleted record... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class enrich_category:
"""To manage enrich category"""
def create(self, vals):
"""create operation @return: super create() method"""
if 'type' in vals:
if vals['type'] == 'sol_special':
vals['current_amount'] = vals['amount']
return super(enrich_category, sel... | the_stack_v2_python_sparse | v_11/EBS-SVN/branches/ebs/enrich/models/enrich.py | musabahmed/baba | train | 0 |
90aa90e677a5de86568e842f6e8e083faeac00c4 | [
"avatar = self.cleaned_data.get('avatar', None)\nif avatar is not None:\n avatar_size = len(avatar) * 3 / 4 - avatar.count('=', -2)\n if avatar_size > settings.MAX_FILE_SIZES['avatar']:\n raise forms.ValidationError(_('Image file too large'))\nreturn avatar",
"user = info.context.user\ntouched = Fals... | <|body_start_0|>
avatar = self.cleaned_data.get('avatar', None)
if avatar is not None:
avatar_size = len(avatar) * 3 / 4 - avatar.count('=', -2)
if avatar_size > settings.MAX_FILE_SIZES['avatar']:
raise forms.ValidationError(_('Image file too large'))
retu... | For used by profile settings mutation. | ProfileSettingsForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileSettingsForm:
"""For used by profile settings mutation."""
def clean_avatar(self) -> str:
"""Add some custom validation to our avatar field"""
<|body_0|>
def save(self, info, commit: bool=True) -> User:
"""Saves the changes made to the database (if any)"""... | stack_v2_sparse_classes_10k_train_007192 | 10,299 | no_license | [
{
"docstring": "Add some custom validation to our avatar field",
"name": "clean_avatar",
"signature": "def clean_avatar(self) -> str"
},
{
"docstring": "Saves the changes made to the database (if any)",
"name": "save",
"signature": "def save(self, info, commit: bool=True) -> User"
}
] | 2 | stack_v2_sparse_classes_30k_train_006318 | Implement the Python class `ProfileSettingsForm` described below.
Class description:
For used by profile settings mutation.
Method signatures and docstrings:
- def clean_avatar(self) -> str: Add some custom validation to our avatar field
- def save(self, info, commit: bool=True) -> User: Saves the changes made to the... | Implement the Python class `ProfileSettingsForm` described below.
Class description:
For used by profile settings mutation.
Method signatures and docstrings:
- def clean_avatar(self) -> str: Add some custom validation to our avatar field
- def save(self, info, commit: bool=True) -> User: Saves the changes made to the... | fe24d0bd08952647d27940a336bd0504af1bae0c | <|skeleton|>
class ProfileSettingsForm:
"""For used by profile settings mutation."""
def clean_avatar(self) -> str:
"""Add some custom validation to our avatar field"""
<|body_0|>
def save(self, info, commit: bool=True) -> User:
"""Saves the changes made to the database (if any)"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProfileSettingsForm:
"""For used by profile settings mutation."""
def clean_avatar(self) -> str:
"""Add some custom validation to our avatar field"""
avatar = self.cleaned_data.get('avatar', None)
if avatar is not None:
avatar_size = len(avatar) * 3 / 4 - avatar.count(... | the_stack_v2_python_sparse | accounts/graphql/mutations.py | ApyMajul/Zola-Backend | train | 0 |
98cecb0e98adffa15e5dd566ed8507923ba97aeb | [
"self._encoder = encoder\nself._decoder = decoder\nself._rho = rho",
"posterior = self._encoder(input_data)\nsamples = self._encoder.sample(posterior, key)\nkls = jax.vmap(kl.kl_p_with_uniform_normal, [0])(posterior.mean, posterior.variance)\nrecons = self._decoder(samples)\ndata_fidelity = self._decoder.data_fid... | <|body_start_0|>
self._encoder = encoder
self._decoder = decoder
self._rho = rho
<|end_body_0|>
<|body_start_1|>
posterior = self._encoder(input_data)
samples = self._encoder.sample(posterior, key)
kls = jax.vmap(kl.kl_p_with_uniform_normal, [0])(posterior.mean, posterio... | VAE class. This class defines the ELBO used in training VAE models. It also adds function for forward passing data through VAE. | VAE | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VAE:
"""VAE class. This class defines the ELBO used in training VAE models. It also adds function for forward passing data through VAE."""
def __init__(self, encoder: encoders.EncoderBase, decoder: decoders.DecoderBase, rho: Optional[float]=None):
"""Class initializer. Args: encoder:... | stack_v2_sparse_classes_10k_train_007193 | 4,304 | permissive | [
{
"docstring": "Class initializer. Args: encoder: Encoder network architecture. decoder: Decoder network architecture. rho: Rho parameter used in AVAE training.",
"name": "__init__",
"signature": "def __init__(self, encoder: encoders.EncoderBase, decoder: decoders.DecoderBase, rho: Optional[float]=None)... | 4 | stack_v2_sparse_classes_30k_train_002095 | Implement the Python class `VAE` described below.
Class description:
VAE class. This class defines the ELBO used in training VAE models. It also adds function for forward passing data through VAE.
Method signatures and docstrings:
- def __init__(self, encoder: encoders.EncoderBase, decoder: decoders.DecoderBase, rho:... | Implement the Python class `VAE` described below.
Class description:
VAE class. This class defines the ELBO used in training VAE models. It also adds function for forward passing data through VAE.
Method signatures and docstrings:
- def __init__(self, encoder: encoders.EncoderBase, decoder: decoders.DecoderBase, rho:... | f5de0ede8430809180254ee957abf36ed62579ef | <|skeleton|>
class VAE:
"""VAE class. This class defines the ELBO used in training VAE models. It also adds function for forward passing data through VAE."""
def __init__(self, encoder: encoders.EncoderBase, decoder: decoders.DecoderBase, rho: Optional[float]=None):
"""Class initializer. Args: encoder:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VAE:
"""VAE class. This class defines the ELBO used in training VAE models. It also adds function for forward passing data through VAE."""
def __init__(self, encoder: encoders.EncoderBase, decoder: decoders.DecoderBase, rho: Optional[float]=None):
"""Class initializer. Args: encoder: Encoder netw... | the_stack_v2_python_sparse | avae/vae.py | vishalbelsare/deepmind-research | train | 0 |
d9e557ec3e189281715e55d81fa18c5f3dcfe623 | [
"B, C = features.shape[:2]\nfeatures = features.contiguous()\ncoords = coords.contiguous()\nouts, inds, wgts = trilinear_devoxelize_forward(resolution, is_training, coords, features)\nif is_training:\n ctx.save_for_backward(inds, wgts)\n ctx.r = resolution\nreturn outs",
"inds, wgts = ctx.saved_tensors\ngra... | <|body_start_0|>
B, C = features.shape[:2]
features = features.contiguous()
coords = coords.contiguous()
outs, inds, wgts = trilinear_devoxelize_forward(resolution, is_training, coords, features)
if is_training:
ctx.save_for_backward(inds, wgts)
ctx.r = re... | TrilinearDevoxelization | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrilinearDevoxelization:
def forward(ctx, features, coords, resolution, is_training=True):
"""Forward pass for the Op. Args: ctx: torch Autograd context. coords: the coordinates of points, FloatTensor[B, 3, N] features: FloatTensor[B, C, R, R, R] resolution: int, the voxel resolution. is... | stack_v2_sparse_classes_10k_train_007194 | 22,879 | permissive | [
{
"docstring": "Forward pass for the Op. Args: ctx: torch Autograd context. coords: the coordinates of points, FloatTensor[B, 3, N] features: FloatTensor[B, C, R, R, R] resolution: int, the voxel resolution. is_training: bool, training mode. Returns: torch.FloatTensor: devoxelized features (B, C, N)",
"name... | 2 | stack_v2_sparse_classes_30k_train_005245 | Implement the Python class `TrilinearDevoxelization` described below.
Class description:
Implement the TrilinearDevoxelization class.
Method signatures and docstrings:
- def forward(ctx, features, coords, resolution, is_training=True): Forward pass for the Op. Args: ctx: torch Autograd context. coords: the coordinate... | Implement the Python class `TrilinearDevoxelization` described below.
Class description:
Implement the TrilinearDevoxelization class.
Method signatures and docstrings:
- def forward(ctx, features, coords, resolution, is_training=True): Forward pass for the Op. Args: ctx: torch Autograd context. coords: the coordinate... | 51482281dc180786e7563c73c12ac5df89289748 | <|skeleton|>
class TrilinearDevoxelization:
def forward(ctx, features, coords, resolution, is_training=True):
"""Forward pass for the Op. Args: ctx: torch Autograd context. coords: the coordinates of points, FloatTensor[B, 3, N] features: FloatTensor[B, C, R, R, R] resolution: int, the voxel resolution. is... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TrilinearDevoxelization:
def forward(ctx, features, coords, resolution, is_training=True):
"""Forward pass for the Op. Args: ctx: torch Autograd context. coords: the coordinates of points, FloatTensor[B, 3, N] features: FloatTensor[B, C, R, R, R] resolution: int, the voxel resolution. is_training: boo... | the_stack_v2_python_sparse | ml3d/torch/models/pvcnn.py | CosmosHua/Open3D-ML | train | 0 | |
8e73fe7b8dd0aceaaa4c0739085c488d2649a286 | [
"new_brand = Brand(name=validated_data.get('name'))\nnew_brand.save()\nreturn new_brand",
"instance.name = validated_data.get('name', instance.name)\ninstance.save()\nreturn instance"
] | <|body_start_0|>
new_brand = Brand(name=validated_data.get('name'))
new_brand.save()
return new_brand
<|end_body_0|>
<|body_start_1|>
instance.name = validated_data.get('name', instance.name)
instance.save()
return instance
<|end_body_1|>
| BrandSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrandSerializer:
def create(self, validated_data):
"""create and return new 'Brand' instance"""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `Brand` instance"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_007195 | 6,342 | no_license | [
{
"docstring": "create and return new 'Brand' instance",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Update and return an existing `Brand` instance",
"name": "update",
"signature": "def update(self, instance, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007367 | Implement the Python class `BrandSerializer` described below.
Class description:
Implement the BrandSerializer class.
Method signatures and docstrings:
- def create(self, validated_data): create and return new 'Brand' instance
- def update(self, instance, validated_data): Update and return an existing `Brand` instanc... | Implement the Python class `BrandSerializer` described below.
Class description:
Implement the BrandSerializer class.
Method signatures and docstrings:
- def create(self, validated_data): create and return new 'Brand' instance
- def update(self, instance, validated_data): Update and return an existing `Brand` instanc... | dba8d1fdb96889e41328e792816a4968cbeb1ed4 | <|skeleton|>
class BrandSerializer:
def create(self, validated_data):
"""create and return new 'Brand' instance"""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `Brand` instance"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BrandSerializer:
def create(self, validated_data):
"""create and return new 'Brand' instance"""
new_brand = Brand(name=validated_data.get('name'))
new_brand.save()
return new_brand
def update(self, instance, validated_data):
"""Update and return an existing `Brand`... | the_stack_v2_python_sparse | cars_web/cars_app/serializers.py | Ignisor/cars_scrapper | train | 0 | |
083b582580d0b9a469e75ece9e933151b6b10ed3 | [
"self.capacity = capacity\nself.node_map = {}\nself.list = LinkedList()",
"if key not in self.node_map:\n return -1\nnode = self.node_map[key]\nself.list.remove(node)\nself.list.append(node)\nreturn node.val",
"if key in self.node_map:\n node = self.node_map[key]\n node.val = value\n self.list.remov... | <|body_start_0|>
self.capacity = capacity
self.node_map = {}
self.list = LinkedList()
<|end_body_0|>
<|body_start_1|>
if key not in self.node_map:
return -1
node = self.node_map[key]
self.list.remove(node)
self.list.append(node)
return node.va... | LRUCache | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k_train_007196 | 1,629 | permissive | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 36b02feea04b892f1256de090c4fcf7b6aa98873 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.node_map = {}
self.list = LinkedList()
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.node_map:
return -1
node = sel... | the_stack_v2_python_sparse | algorithms/design_x/cache/lru_cache.py | kevinshenyang07/Data-Structures-and-Algorithms | train | 0 | |
c884dd266eb3c1cecf302774bc47e794f5bd24f2 | [
"self.pool = object()\nself.nodes = {'nodes': []}\nself.clock = Clock()\nself.get_calls = 0\n\nclass FakeTreq(object):\n\n @classmethod\n def get(cls, url, headers, pool):\n self.get_calls += 1\n self.assertIs(self.pool, pool)\n self.assertEqual(['token'], headers.get('x-auth-token'))\n ... | <|body_start_0|>
self.pool = object()
self.nodes = {'nodes': []}
self.clock = Clock()
self.get_calls = 0
class FakeTreq(object):
@classmethod
def get(cls, url, headers, pool):
self.get_calls += 1
self.assertIs(self.pool, p... | Tests for :func:`CloudLoadBalancer.wait_for_nodes`. | WaitForNodesTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WaitForNodesTestCase:
"""Tests for :func:`CloudLoadBalancer.wait_for_nodes`."""
def setUp(self):
"""Set up fake pool, clock, treq, responses, and RCS."""
<|body_0|>
def test_retries_until_matcher_matches(self):
"""If the matcher does not matches the load balancer... | stack_v2_sparse_classes_10k_train_007197 | 18,654 | permissive | [
{
"docstring": "Set up fake pool, clock, treq, responses, and RCS.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "If the matcher does not matches the load balancer state, retries until it does.",
"name": "test_retries_until_matcher_matches",
"signature": "def test_r... | 3 | stack_v2_sparse_classes_30k_val_000256 | Implement the Python class `WaitForNodesTestCase` described below.
Class description:
Tests for :func:`CloudLoadBalancer.wait_for_nodes`.
Method signatures and docstrings:
- def setUp(self): Set up fake pool, clock, treq, responses, and RCS.
- def test_retries_until_matcher_matches(self): If the matcher does not matc... | Implement the Python class `WaitForNodesTestCase` described below.
Class description:
Tests for :func:`CloudLoadBalancer.wait_for_nodes`.
Method signatures and docstrings:
- def setUp(self): Set up fake pool, clock, treq, responses, and RCS.
- def test_retries_until_matcher_matches(self): If the matcher does not matc... | 7199cdd67255fe116dbcbedea660c13453671134 | <|skeleton|>
class WaitForNodesTestCase:
"""Tests for :func:`CloudLoadBalancer.wait_for_nodes`."""
def setUp(self):
"""Set up fake pool, clock, treq, responses, and RCS."""
<|body_0|>
def test_retries_until_matcher_matches(self):
"""If the matcher does not matches the load balancer... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WaitForNodesTestCase:
"""Tests for :func:`CloudLoadBalancer.wait_for_nodes`."""
def setUp(self):
"""Set up fake pool, clock, treq, responses, and RCS."""
self.pool = object()
self.nodes = {'nodes': []}
self.clock = Clock()
self.get_calls = 0
class FakeTreq... | the_stack_v2_python_sparse | otter/integration/lib/test_cloud_load_balancer.py | rackerlabs/otter | train | 20 |
79817d45b4be6f79b525a78cb4ea720a165d7453 | [
"stock_company = get_object_or_404(UserCompany, user=request.user, pk=id)\nurl = f'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={stock_company.companystock.symbol}&outputsize=compact&apikey={settings.STOCK_API_KEY}'\nres = requests.get(url)\ndata = res.json()\ndata = data['Time Serie... | <|body_start_0|>
stock_company = get_object_or_404(UserCompany, user=request.user, pk=id)
url = f'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={stock_company.companystock.symbol}&outputsize=compact&apikey={settings.STOCK_API_KEY}'
res = requests.get(url)
d... | CompanyStockView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompanyStockView:
def get(self, request, id):
"""Retorna los datos del mercado de la compañía"""
<|body_0|>
def post(self, request, id):
"""Suscribirse a una acción"""
<|body_1|>
def delete(self, request, id):
"""Elimina la suscripción a una acci... | stack_v2_sparse_classes_10k_train_007198 | 3,455 | no_license | [
{
"docstring": "Retorna los datos del mercado de la compañía",
"name": "get",
"signature": "def get(self, request, id)"
},
{
"docstring": "Suscribirse a una acción",
"name": "post",
"signature": "def post(self, request, id)"
},
{
"docstring": "Elimina la suscripción a una acción"... | 3 | stack_v2_sparse_classes_30k_train_006489 | Implement the Python class `CompanyStockView` described below.
Class description:
Implement the CompanyStockView class.
Method signatures and docstrings:
- def get(self, request, id): Retorna los datos del mercado de la compañía
- def post(self, request, id): Suscribirse a una acción
- def delete(self, request, id): ... | Implement the Python class `CompanyStockView` described below.
Class description:
Implement the CompanyStockView class.
Method signatures and docstrings:
- def get(self, request, id): Retorna los datos del mercado de la compañía
- def post(self, request, id): Suscribirse a una acción
- def delete(self, request, id): ... | db0c61cd66da56f9c904cffeae807b2605a96cc7 | <|skeleton|>
class CompanyStockView:
def get(self, request, id):
"""Retorna los datos del mercado de la compañía"""
<|body_0|>
def post(self, request, id):
"""Suscribirse a una acción"""
<|body_1|>
def delete(self, request, id):
"""Elimina la suscripción a una acci... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CompanyStockView:
def get(self, request, id):
"""Retorna los datos del mercado de la compañía"""
stock_company = get_object_or_404(UserCompany, user=request.user, pk=id)
url = f'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={stock_company.companystock.sym... | the_stack_v2_python_sparse | api/views/companystock.py | klasinky/FinaccessBackend | train | 2 | |
dcad37a8101e1054ceb0404e5dcec42041a1f2a3 | [
"BaseController.__init__(self, veh_id, car_following_params, delay=time_delay, fail_safe=fail_safe, noise=noise)\nself.veh_id = veh_id\nself.k_1 = k_1\nself.k_2 = k_2\nself.h = h\nself.tau = tau\nself.a = a",
"lead_id = env.k.vehicle.get_leader(self.veh_id)\nlead_vel = env.k.vehicle.get_speed(lead_id)\nthis_vel =... | <|body_start_0|>
BaseController.__init__(self, veh_id, car_following_params, delay=time_delay, fail_safe=fail_safe, noise=noise)
self.veh_id = veh_id
self.k_1 = k_1
self.k_2 = k_2
self.h = h
self.tau = tau
self.a = a
<|end_body_0|>
<|body_start_1|>
lead_i... | Linear Adaptive Cruise Control. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class k_1 : float design parameter (default: 0.8) k_2 : float design parameter (default: 0.9) h : float desired time gap (default: 1.0) tau : fl... | LACController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LACController:
"""Linear Adaptive Cruise Control. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class k_1 : float design parameter (default: 0.8) k_2 : float design parameter (default: 0.9) h : float... | stack_v2_sparse_classes_10k_train_007199 | 17,548 | permissive | [
{
"docstring": "Instantiate a Linear Adaptive Cruise controller.",
"name": "__init__",
"signature": "def __init__(self, veh_id, car_following_params, k_1=0.3, k_2=0.4, h=1, tau=0.1, a=0, time_delay=0.0, noise=0, fail_safe=None)"
},
{
"docstring": "See parent class.",
"name": "get_accel",
... | 2 | stack_v2_sparse_classes_30k_train_005329 | Implement the Python class `LACController` described below.
Class description:
Linear Adaptive Cruise Control. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class k_1 : float design parameter (default: 0.8) k_2 : float de... | Implement the Python class `LACController` described below.
Class description:
Linear Adaptive Cruise Control. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class k_1 : float design parameter (default: 0.8) k_2 : float de... | badac3da17f04d8d8ae5691ee8ba2af9d56fac35 | <|skeleton|>
class LACController:
"""Linear Adaptive Cruise Control. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class k_1 : float design parameter (default: 0.8) k_2 : float design parameter (default: 0.9) h : float... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LACController:
"""Linear Adaptive Cruise Control. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class k_1 : float design parameter (default: 0.8) k_2 : float design parameter (default: 0.9) h : float desired time... | the_stack_v2_python_sparse | flow/controllers/car_following_models.py | parthjaggi/flow | train | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.