blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ba98bebd93a7511d75ec2b85ac86579c146460fb | [
"X_train = X_train.astype(np.float32)\ny_train = y_train.astype(np.float32)\nX_test = X_test.astype(np.float32)\ny_test = y_test.astype(np.float32)\nX_val = X_val.astype(np.float32)\ny_val = y_val.astype(np.float32)\nif debug:\n print('Train Shape', X_train.shape)\n print('Test Shape', X_test.shape)\nearlySto... | <|body_start_0|>
X_train = X_train.astype(np.float32)
y_train = y_train.astype(np.float32)
X_test = X_test.astype(np.float32)
y_test = y_test.astype(np.float32)
X_val = X_val.astype(np.float32)
y_val = y_val.astype(np.float32)
if debug:
print('Train Sh... | NetworkTrainingModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkTrainingModule:
def trainModelEarlyStop(self, model, X_train, y_train, X_val, y_val, X_test, y_test, batchSize=128, epochs=300, debug=True, verbose=1):
"""The following function trains a model with the given train data and validation data. At the same time it checks the performanc... | stack_v2_sparse_classes_75kplus_train_070300 | 14,562 | no_license | [
{
"docstring": "The following function trains a model with the given train data and validation data. At the same time it checks the performance of the model in the testing set through the EarlyStoppingCallback class. After training, the model is returned to the step in time where the best validation accuracy is... | 2 | null | Implement the Python class `NetworkTrainingModule` described below.
Class description:
Implement the NetworkTrainingModule class.
Method signatures and docstrings:
- def trainModelEarlyStop(self, model, X_train, y_train, X_val, y_val, X_test, y_test, batchSize=128, epochs=300, debug=True, verbose=1): The following fu... | Implement the Python class `NetworkTrainingModule` described below.
Class description:
Implement the NetworkTrainingModule class.
Method signatures and docstrings:
- def trainModelEarlyStop(self, model, X_train, y_train, X_val, y_val, X_test, y_test, batchSize=128, epochs=300, debug=True, verbose=1): The following fu... | 3f7a7183593eb54a63efcff3762fb2144a0af2df | <|skeleton|>
class NetworkTrainingModule:
def trainModelEarlyStop(self, model, X_train, y_train, X_val, y_val, X_test, y_test, batchSize=128, epochs=300, debug=True, verbose=1):
"""The following function trains a model with the given train data and validation data. At the same time it checks the performanc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NetworkTrainingModule:
def trainModelEarlyStop(self, model, X_train, y_train, X_val, y_val, X_test, y_test, batchSize=128, epochs=300, debug=True, verbose=1):
"""The following function trains a model with the given train data and validation data. At the same time it checks the performance of the model... | the_stack_v2_python_sparse | PowerClassification/Utils/ShimmerModule.py | jabarragann/eeg_project_gnaut_power_band_analysis | train | 1 | |
b7fb5916f850092f066f97069ca3f8650d7dae24 | [
"self.locale = locale\nself.participant = participant\nself.utterancetierTypes = utterancetierTypes\nself.wordtierTypes = wordtierTypes\nself.postierTypes = postierTypes\nself.morphemetierTypes = None\nself.glosstierTypes = None\nself.translationtierTypes = translationtierTypes\nself.interlineartype = POS\nself.ann... | <|body_start_0|>
self.locale = locale
self.participant = participant
self.utterancetierTypes = utterancetierTypes
self.wordtierTypes = wordtierTypes
self.postierTypes = postierTypes
self.morphemetierTypes = None
self.glosstierTypes = None
self.translationt... | The class EafPosCorpusReader implements a part of the corpus reader API described in the Natual Language Toolkit (NLTK). The class reads in all the .eaf files (from the linguistics annotation software called Elan) in a given directory and makes this data accessible through several functions. The data contains "tags", w... | PosCorpusReader | [
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PosCorpusReader:
"""The class EafPosCorpusReader implements a part of the corpus reader API described in the Natual Language Toolkit (NLTK). The class reads in all the .eaf files (from the linguistics annotation software called Elan) in a given directory and makes this data accessible through sev... | stack_v2_sparse_classes_75kplus_train_070301 | 20,569 | permissive | [
{
"docstring": "root: is the directory where your .eaf files are stored. Only the files in the given directory are read, there is no recursive reading right now. This parameter is obligatory. files: a regular expression for the filenames to read. The default value is \"*.eaf\" locale: restricts the corpus data ... | 4 | stack_v2_sparse_classes_30k_train_017001 | Implement the Python class `PosCorpusReader` described below.
Class description:
The class EafPosCorpusReader implements a part of the corpus reader API described in the Natual Language Toolkit (NLTK). The class reads in all the .eaf files (from the linguistics annotation software called Elan) in a given directory and... | Implement the Python class `PosCorpusReader` described below.
Class description:
The class EafPosCorpusReader implements a part of the corpus reader API described in the Natual Language Toolkit (NLTK). The class reads in all the .eaf files (from the linguistics annotation software called Elan) in a given directory and... | ac2bed9b6e759033d17b6ed9e8fa1e79dad68ae6 | <|skeleton|>
class PosCorpusReader:
"""The class EafPosCorpusReader implements a part of the corpus reader API described in the Natual Language Toolkit (NLTK). The class reads in all the .eaf files (from the linguistics annotation software called Elan) in a given directory and makes this data accessible through sev... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PosCorpusReader:
"""The class EafPosCorpusReader implements a part of the corpus reader API described in the Natual Language Toolkit (NLTK). The class reads in all the .eaf files (from the linguistics annotation software called Elan) in a given directory and makes this data accessible through several function... | the_stack_v2_python_sparse | src/poioapi/corpusreader.py | IgorBMSTU/poio-api | train | 0 |
b56536f902c7431e296a9dc130e2f05936723980 | [
"super(Model, self).__init__()\nself.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2... | <|body_start_0|>
super(Model, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_... | CNN. | Model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
"""CNN."""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(self, x):
"""Perform forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Model, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_chan... | stack_v2_sparse_classes_75kplus_train_070302 | 5,133 | no_license | [
{
"docstring": "CNN Builder.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Perform forward.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046380 | Implement the Python class `Model` described below.
Class description:
CNN.
Method signatures and docstrings:
- def __init__(self): CNN Builder.
- def forward(self, x): Perform forward. | Implement the Python class `Model` described below.
Class description:
CNN.
Method signatures and docstrings:
- def __init__(self): CNN Builder.
- def forward(self, x): Perform forward.
<|skeleton|>
class Model:
"""CNN."""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(se... | a91698b940e7e69720ef26c4ac98f7a9d4c30285 | <|skeleton|>
class Model:
"""CNN."""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(self, x):
"""Perform forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Model:
"""CNN."""
def __init__(self):
"""CNN Builder."""
super(Model, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_... | the_stack_v2_python_sparse | Neural Networks with CV/run_q6.1.3.py | shayeree96/Computer-Vision---16720 | train | 0 |
5adefd1794e950c971cb085ff22b7c6bb36c2dab | [
"if are_redundant_fn is None:\n are_redundant_fn = naive_redundant_filter.redundant_shift_and_mismatch_count(shift=0, mismatch_thres=0)\nself.are_redundant_fn = are_redundant_fn",
"input = list(input)\nsets = defaultdict(set)\nfor i in range(len(input)):\n if i % 100 == 0:\n logger.info('Making set f... | <|body_start_0|>
if are_redundant_fn is None:
are_redundant_fn = naive_redundant_filter.redundant_shift_and_mismatch_count(shift=0, mismatch_thres=0)
self.are_redundant_fn = are_redundant_fn
<|end_body_0|>
<|body_start_1|>
input = list(input)
sets = defaultdict(set)
... | Filter that selects candidate probes with a dominating set approach. | DominatingSetFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DominatingSetFilter:
"""Filter that selects candidate probes with a dominating set approach."""
def __init__(self, are_redundant_fn=None):
"""Args: are_redundant_fn: function that takes as input two probes and returns True iff the two are deemed redundant"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus_train_070303 | 3,706 | permissive | [
{
"docstring": "Args: are_redundant_fn: function that takes as input two probes and returns True iff the two are deemed redundant",
"name": "__init__",
"signature": "def __init__(self, are_redundant_fn=None)"
},
{
"docstring": "Return a subset of the input probes.",
"name": "_filter",
"s... | 2 | null | Implement the Python class `DominatingSetFilter` described below.
Class description:
Filter that selects candidate probes with a dominating set approach.
Method signatures and docstrings:
- def __init__(self, are_redundant_fn=None): Args: are_redundant_fn: function that takes as input two probes and returns True iff ... | Implement the Python class `DominatingSetFilter` described below.
Class description:
Filter that selects candidate probes with a dominating set approach.
Method signatures and docstrings:
- def __init__(self, are_redundant_fn=None): Args: are_redundant_fn: function that takes as input two probes and returns True iff ... | 9c4696c28e32fd102fbae30c55a9470cb2ad8d3d | <|skeleton|>
class DominatingSetFilter:
"""Filter that selects candidate probes with a dominating set approach."""
def __init__(self, are_redundant_fn=None):
"""Args: are_redundant_fn: function that takes as input two probes and returns True iff the two are deemed redundant"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DominatingSetFilter:
"""Filter that selects candidate probes with a dominating set approach."""
def __init__(self, are_redundant_fn=None):
"""Args: are_redundant_fn: function that takes as input two probes and returns True iff the two are deemed redundant"""
if are_redundant_fn is None:
... | the_stack_v2_python_sparse | catch/filter/dominating_set_filter.py | broadinstitute/catch | train | 69 |
6491a8498e4b72cf6ff9c754788ab538dc74c2f7 | [
"self.is_mail_enabled = is_mail_enabled\nself.is_security_enabled = is_security_enabled\nself.member_count = member_count\nself.visibility = visibility",
"if dictionary is None:\n return None\nis_mail_enabled = dictionary.get('isMailEnabled')\nis_security_enabled = dictionary.get('isSecurityEnabled')\nmember_c... | <|body_start_0|>
self.is_mail_enabled = is_mail_enabled
self.is_security_enabled = is_security_enabled
self.member_count = member_count
self.visibility = visibility
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_mail_enabled = dictionar... | Implementation of the 'Office365GroupInfo' model. Specifies information about a M365 Group. Attributes: is_mail_enabled (bool): Specifies whether the Group is mail enabled. Mail enabled groups are used within Microsoft to distribute messages. is_security_enabled (bool): Specifies whether the Group is security enabled. ... | Office365GroupInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Office365GroupInfo:
"""Implementation of the 'Office365GroupInfo' model. Specifies information about a M365 Group. Attributes: is_mail_enabled (bool): Specifies whether the Group is mail enabled. Mail enabled groups are used within Microsoft to distribute messages. is_security_enabled (bool): Spe... | stack_v2_sparse_classes_75kplus_train_070304 | 2,486 | permissive | [
{
"docstring": "Constructor for the Office365GroupInfo class",
"name": "__init__",
"signature": "def __init__(self, is_mail_enabled=None, is_security_enabled=None, member_count=None, visibility=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictio... | 2 | stack_v2_sparse_classes_30k_train_034034 | Implement the Python class `Office365GroupInfo` described below.
Class description:
Implementation of the 'Office365GroupInfo' model. Specifies information about a M365 Group. Attributes: is_mail_enabled (bool): Specifies whether the Group is mail enabled. Mail enabled groups are used within Microsoft to distribute me... | Implement the Python class `Office365GroupInfo` described below.
Class description:
Implementation of the 'Office365GroupInfo' model. Specifies information about a M365 Group. Attributes: is_mail_enabled (bool): Specifies whether the Group is mail enabled. Mail enabled groups are used within Microsoft to distribute me... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class Office365GroupInfo:
"""Implementation of the 'Office365GroupInfo' model. Specifies information about a M365 Group. Attributes: is_mail_enabled (bool): Specifies whether the Group is mail enabled. Mail enabled groups are used within Microsoft to distribute messages. is_security_enabled (bool): Spe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Office365GroupInfo:
"""Implementation of the 'Office365GroupInfo' model. Specifies information about a M365 Group. Attributes: is_mail_enabled (bool): Specifies whether the Group is mail enabled. Mail enabled groups are used within Microsoft to distribute messages. is_security_enabled (bool): Specifies whethe... | the_stack_v2_python_sparse | cohesity_management_sdk/models/office_365_group_info.py | cohesity/management-sdk-python | train | 24 |
d6e1d00460b784c7d11f08e9ad9c00f33132d7b5 | [
"length = 0\nnode = head\nwhile node is not None:\n node = node.next\n length += 1\nreturn length",
"found_node = head\nfor i in range(1, index + 1):\n found_node = found_node.next\nreturn found_node",
"length = self.calc_len(head)\nif length == 0 or k % length == 0:\n return head\nsteps_count = k %... | <|body_start_0|>
length = 0
node = head
while node is not None:
node = node.next
length += 1
return length
<|end_body_0|>
<|body_start_1|>
found_node = head
for i in range(1, index + 1):
found_node = found_node.next
return foun... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calc_len(self, head):
""":type head: ListNode :rtype: int"""
<|body_0|>
def find_node(self, head, index):
""":type head: ListNode :type index: int :rtype: ListNode"""
<|body_1|>
def rotateRight(self, head, k):
""":type head: ListNod... | stack_v2_sparse_classes_75kplus_train_070305 | 1,520 | no_license | [
{
"docstring": ":type head: ListNode :rtype: int",
"name": "calc_len",
"signature": "def calc_len(self, head)"
},
{
"docstring": ":type head: ListNode :type index: int :rtype: ListNode",
"name": "find_node",
"signature": "def find_node(self, head, index)"
},
{
"docstring": ":type... | 3 | stack_v2_sparse_classes_30k_train_041482 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calc_len(self, head): :type head: ListNode :rtype: int
- def find_node(self, head, index): :type head: ListNode :type index: int :rtype: ListNode
- def rotateRight(self, head... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calc_len(self, head): :type head: ListNode :rtype: int
- def find_node(self, head, index): :type head: ListNode :type index: int :rtype: ListNode
- def rotateRight(self, head... | c5a165d14c56f7ce29b923933d2bda4576eab8a2 | <|skeleton|>
class Solution:
def calc_len(self, head):
""":type head: ListNode :rtype: int"""
<|body_0|>
def find_node(self, head, index):
""":type head: ListNode :type index: int :rtype: ListNode"""
<|body_1|>
def rotateRight(self, head, k):
""":type head: ListNod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def calc_len(self, head):
""":type head: ListNode :rtype: int"""
length = 0
node = head
while node is not None:
node = node.next
length += 1
return length
def find_node(self, head, index):
""":type head: ListNode :type inde... | the_stack_v2_python_sparse | LeetCode/Linked Lists/Rotate_List_61.py | unterumarmung/practice | train | 3 | |
eac34677b256ce5527eb4b12698be65fa4ca9717 | [
"super(GraphAttentionLayer, self).__init__()\nself.output_dim = output_dim\nself.W = nn.Parameter(torch.Tensor(input_dim, output_dim))\nself.a = nn.Parameter(torch.Tensor(2 * output_dim, 1))\nif bias:\n self.bias = nn.Parameter(torch.FloatTensor(output_dim))\nelse:\n self.register_parameter('bias', None)\nsel... | <|body_start_0|>
super(GraphAttentionLayer, self).__init__()
self.output_dim = output_dim
self.W = nn.Parameter(torch.Tensor(input_dim, output_dim))
self.a = nn.Parameter(torch.Tensor(2 * output_dim, 1))
if bias:
self.bias = nn.Parameter(torch.FloatTensor(output_dim))... | Graph Attention层 (dense input) | GraphAttentionLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphAttentionLayer:
"""Graph Attention层 (dense input)"""
def __init__(self, input_dim, output_dim, dropout, alpha, bias=True):
"""Graph Attention层 (dense input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 bias: bo... | stack_v2_sparse_classes_75kplus_train_070306 | 6,215 | permissive | [
{
"docstring": "Graph Attention层 (dense input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 bias: boolean, 是否使用偏置",
"name": "__init__",
"signature": "def __init__(self, input_dim, output_dim, dropout, alpha, bias=True)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_val_001210 | Implement the Python class `GraphAttentionLayer` described below.
Class description:
Graph Attention层 (dense input)
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim, dropout, alpha, bias=True): Graph Attention层 (dense input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout... | Implement the Python class `GraphAttentionLayer` described below.
Class description:
Graph Attention层 (dense input)
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim, dropout, alpha, bias=True): Graph Attention层 (dense input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout... | ee16c37fd065ba4c732138096f715f04c0ad6fcf | <|skeleton|>
class GraphAttentionLayer:
"""Graph Attention层 (dense input)"""
def __init__(self, input_dim, output_dim, dropout, alpha, bias=True):
"""Graph Attention层 (dense input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 bias: bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraphAttentionLayer:
"""Graph Attention层 (dense input)"""
def __init__(self, input_dim, output_dim, dropout, alpha, bias=True):
"""Graph Attention层 (dense input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 bias: boolean, 是否使用偏置... | the_stack_v2_python_sparse | Node/GAT/script/layers.py | robbinc91/GNN-Pytorch | train | 0 |
24fd2d46a110d765fc903e80ade5bd718c68629f | [
"self.login_browser_user()\nself.assertTrue(self.browser.get_cookie('sessionid') is not None)\nurl = self.live_server_url + self.LOGOUT_URL\nself.browser.get(url)\nself.assertTrue(self.browser.get_cookie('sessionid') is None)",
"url = self.live_server_url + self.LOGOUT_URL\nself.browser.get(url)\nself.assertEqual... | <|body_start_0|>
self.login_browser_user()
self.assertTrue(self.browser.get_cookie('sessionid') is not None)
url = self.live_server_url + self.LOGOUT_URL
self.browser.get(url)
self.assertTrue(self.browser.get_cookie('sessionid') is None)
<|end_body_0|>
<|body_start_1|>
u... | LogoutTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogoutTests:
def test_logout_authorized_user(self):
"""Logout view logs out authorized users."""
<|body_0|>
def test_logout_anon_users_login(self):
"""Anonymous users accessing logout view are redirected to login page."""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_070307 | 12,112 | no_license | [
{
"docstring": "Logout view logs out authorized users.",
"name": "test_logout_authorized_user",
"signature": "def test_logout_authorized_user(self)"
},
{
"docstring": "Anonymous users accessing logout view are redirected to login page.",
"name": "test_logout_anon_users_login",
"signature... | 2 | stack_v2_sparse_classes_30k_train_037642 | Implement the Python class `LogoutTests` described below.
Class description:
Implement the LogoutTests class.
Method signatures and docstrings:
- def test_logout_authorized_user(self): Logout view logs out authorized users.
- def test_logout_anon_users_login(self): Anonymous users accessing logout view are redirected... | Implement the Python class `LogoutTests` described below.
Class description:
Implement the LogoutTests class.
Method signatures and docstrings:
- def test_logout_authorized_user(self): Logout view logs out authorized users.
- def test_logout_anon_users_login(self): Anonymous users accessing logout view are redirected... | 21a3771c90f395458d071dc6d6f0cb4d9542a05a | <|skeleton|>
class LogoutTests:
def test_logout_authorized_user(self):
"""Logout view logs out authorized users."""
<|body_0|>
def test_logout_anon_users_login(self):
"""Anonymous users accessing logout view are redirected to login page."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogoutTests:
def test_logout_authorized_user(self):
"""Logout view logs out authorized users."""
self.login_browser_user()
self.assertTrue(self.browser.get_cookie('sessionid') is not None)
url = self.live_server_url + self.LOGOUT_URL
self.browser.get(url)
self.a... | the_stack_v2_python_sparse | accounts/tests_selenium.py | Gilles00/delivery-1 | train | 0 | |
ad9929e7ffe4d03904bc652fa318fcbff8036b43 | [
"board = sum(board, [])\nr_index = board.index('R')\nr_row = r_index // 8\nr_col = r_index % 8\ndir_size = [-1, 1, -8, 8]\nstep_range = [r_col, 7 - r_col, r_row, 7 - r_row]\nn_pawn = 0\nfor d in range(4):\n ds = dir_size[d]\n for one_step in range(step_range[d]):\n if board[r_index + ds * (one_step + 1... | <|body_start_0|>
board = sum(board, [])
r_index = board.index('R')
r_row = r_index // 8
r_col = r_index % 8
dir_size = [-1, 1, -8, 8]
step_range = [r_col, 7 - r_col, r_row, 7 - r_row]
n_pawn = 0
for d in range(4):
ds = dir_size[d]
f... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numRookCaptures(self, board):
"""change 2-dim into 1-dim, then use mod 8 table"""
<|body_0|>
def numRookCaptures2(self, board):
"""string method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
board = sum(board, [])
r_index = b... | stack_v2_sparse_classes_75kplus_train_070308 | 3,703 | permissive | [
{
"docstring": "change 2-dim into 1-dim, then use mod 8 table",
"name": "numRookCaptures",
"signature": "def numRookCaptures(self, board)"
},
{
"docstring": "string method",
"name": "numRookCaptures2",
"signature": "def numRookCaptures2(self, board)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numRookCaptures(self, board): change 2-dim into 1-dim, then use mod 8 table
- def numRookCaptures2(self, board): string method | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numRookCaptures(self, board): change 2-dim into 1-dim, then use mod 8 table
- def numRookCaptures2(self, board): string method
<|skeleton|>
class Solution:
def numRookC... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def numRookCaptures(self, board):
"""change 2-dim into 1-dim, then use mod 8 table"""
<|body_0|>
def numRookCaptures2(self, board):
"""string method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numRookCaptures(self, board):
"""change 2-dim into 1-dim, then use mod 8 table"""
board = sum(board, [])
r_index = board.index('R')
r_row = r_index // 8
r_col = r_index % 8
dir_size = [-1, 1, -8, 8]
step_range = [r_col, 7 - r_col, r_row, 7 ... | the_stack_v2_python_sparse | leetcode/0999_available_captures_for_rook.py | chaosWsF/Python-Practice | train | 1 | |
78ff6b848e1a5e08057f166e22ea8b605f045956 | [
"self.client_node = SlaveNode(debug=debug)\nself.client_node.initialize()\nself.client_node.wait_for_initialize()\nself.debug = debug\nself.images = None",
"self.optimizer = optimizer(debug=True)\nwhile True:\n task_data = self.client_node.wait_for_task()\n if not self.images:\n self.images = self.op... | <|body_start_0|>
self.client_node = SlaveNode(debug=debug)
self.client_node.initialize()
self.client_node.wait_for_initialize()
self.debug = debug
self.images = None
<|end_body_0|>
<|body_start_1|>
self.optimizer = optimizer(debug=True)
while True:
ta... | Provides the logic for a worker class that dynamically optimizes a scenario | OptimizerWorker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizerWorker:
"""Provides the logic for a worker class that dynamically optimizes a scenario"""
def __init__(self, debug=False):
"""Initialize the worker"""
<|body_0|>
def run(self, optimizer):
"""Run the worker with a specific optimizer. :param optimizer: The... | stack_v2_sparse_classes_75kplus_train_070309 | 1,167 | permissive | [
{
"docstring": "Initialize the worker",
"name": "__init__",
"signature": "def __init__(self, debug=False)"
},
{
"docstring": "Run the worker with a specific optimizer. :param optimizer: The optimizer to use during optimization",
"name": "run",
"signature": "def run(self, optimizer)"
}
... | 2 | stack_v2_sparse_classes_30k_train_011491 | Implement the Python class `OptimizerWorker` described below.
Class description:
Provides the logic for a worker class that dynamically optimizes a scenario
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize the worker
- def run(self, optimizer): Run the worker with a specific optimizer. ... | Implement the Python class `OptimizerWorker` described below.
Class description:
Provides the logic for a worker class that dynamically optimizes a scenario
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize the worker
- def run(self, optimizer): Run the worker with a specific optimizer. ... | fc31dd8de624f4a71c2c4b1bfe47a18f0b5d2f84 | <|skeleton|>
class OptimizerWorker:
"""Provides the logic for a worker class that dynamically optimizes a scenario"""
def __init__(self, debug=False):
"""Initialize the worker"""
<|body_0|>
def run(self, optimizer):
"""Run the worker with a specific optimizer. :param optimizer: The... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OptimizerWorker:
"""Provides the logic for a worker class that dynamically optimizes a scenario"""
def __init__(self, debug=False):
"""Initialize the worker"""
self.client_node = SlaveNode(debug=debug)
self.client_node.initialize()
self.client_node.wait_for_initialize()
... | the_stack_v2_python_sparse | SUASImageParser/optimizers/worker.py | peterhusisian/SUAS-Competition | train | 0 |
51f9163a6b47aed9ae0be811cb09e2338ce3b003 | [
"msg = ''\ncompany_id = self.pool.get('report.company').search(cr, uid, [('name', '=', comapny)])\nif not company_id:\n msg = 'company'\nreport_type_id = self.pool.get('report.type').search(cr, uid, [('name', '=', report_type)])\nif not report_type_id:\n msg = msg + ' report_type'\ntry:\n int(year)\nexcept... | <|body_start_0|>
msg = ''
company_id = self.pool.get('report.company').search(cr, uid, [('name', '=', comapny)])
if not company_id:
msg = 'company'
report_type_id = self.pool.get('report.type').search(cr, uid, [('name', '=', report_type)])
if not report_type_id:
... | report_data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class report_data:
def check_input(self, cr, uid, comapny, report_type, year, month):
"""验证输入数据是否合法,合法则返回相应ID"""
<|body_0|>
def get_report_data(self, cr, uid, company, report_type, year, month):
"""传入 company,report_type,year,month 传出row,column,text,value四列的list"""
... | stack_v2_sparse_classes_75kplus_train_070310 | 30,185 | no_license | [
{
"docstring": "验证输入数据是否合法,合法则返回相应ID",
"name": "check_input",
"signature": "def check_input(self, cr, uid, comapny, report_type, year, month)"
},
{
"docstring": "传入 company,report_type,year,month 传出row,column,text,value四列的list",
"name": "get_report_data",
"signature": "def get_report_dat... | 3 | null | Implement the Python class `report_data` described below.
Class description:
Implement the report_data class.
Method signatures and docstrings:
- def check_input(self, cr, uid, comapny, report_type, year, month): 验证输入数据是否合法,合法则返回相应ID
- def get_report_data(self, cr, uid, company, report_type, year, month): 传入 company,... | Implement the Python class `report_data` described below.
Class description:
Implement the report_data class.
Method signatures and docstrings:
- def check_input(self, cr, uid, comapny, report_type, year, month): 验证输入数据是否合法,合法则返回相应ID
- def get_report_data(self, cr, uid, company, report_type, year, month): 传入 company,... | 6ef7e12249eb45410231ff178cb71e24b0006339 | <|skeleton|>
class report_data:
def check_input(self, cr, uid, comapny, report_type, year, month):
"""验证输入数据是否合法,合法则返回相应ID"""
<|body_0|>
def get_report_data(self, cr, uid, company, report_type, year, month):
"""传入 company,report_type,year,month 传出row,column,text,value四列的list"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class report_data:
def check_input(self, cr, uid, comapny, report_type, year, month):
"""验证输入数据是否合法,合法则返回相应ID"""
msg = ''
company_id = self.pool.get('report.company').search(cr, uid, [('name', '=', comapny)])
if not company_id:
msg = 'company'
report_type_id = sel... | the_stack_v2_python_sparse | 20110214/oecn_report_merge/oecn_report_merge.py | vixiaoan/cloudteam | train | 0 | |
556a7bbeb7f661d24b39e4901a5fbe82e6aeb109 | [
"try:\n models.Meet.objects.all().exclude(id=int(pk)).update(is_current_meet=False, enable_ranking=False)\n meet = models.Meet.objects.get(id=int(pk))\n meet.is_current_meet = True\n meet.save()\nexcept Exception:\n request.session['meet'] = {}\n return Response({'status': 'active meet cleared'}, ... | <|body_start_0|>
try:
models.Meet.objects.all().exclude(id=int(pk)).update(is_current_meet=False, enable_ranking=False)
meet = models.Meet.objects.get(id=int(pk))
meet.is_current_meet = True
meet.save()
except Exception:
request.session['meet']... | Retrieve a meet by its id | MeetViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeetViewSet:
"""Retrieve a meet by its id"""
def set_active(self, request, pk=None):
"""Sets a meet as active, storing it in the user's session --- omit_serializer: true"""
<|body_0|>
def toggle_ranking(self, request, pk=None):
"""Changes the enable_ranking flag ... | stack_v2_sparse_classes_75kplus_train_070311 | 7,293 | no_license | [
{
"docstring": "Sets a meet as active, storing it in the user's session --- omit_serializer: true",
"name": "set_active",
"signature": "def set_active(self, request, pk=None)"
},
{
"docstring": "Changes the enable_ranking flag to its opposite --- omit_serializer: true",
"name": "toggle_ranki... | 2 | stack_v2_sparse_classes_30k_train_014326 | Implement the Python class `MeetViewSet` described below.
Class description:
Retrieve a meet by its id
Method signatures and docstrings:
- def set_active(self, request, pk=None): Sets a meet as active, storing it in the user's session --- omit_serializer: true
- def toggle_ranking(self, request, pk=None): Changes the... | Implement the Python class `MeetViewSet` described below.
Class description:
Retrieve a meet by its id
Method signatures and docstrings:
- def set_active(self, request, pk=None): Sets a meet as active, storing it in the user's session --- omit_serializer: true
- def toggle_ranking(self, request, pk=None): Changes the... | 0c3280050e1caa34f42d350dfab00fd3b1dbe5ad | <|skeleton|>
class MeetViewSet:
"""Retrieve a meet by its id"""
def set_active(self, request, pk=None):
"""Sets a meet as active, storing it in the user's session --- omit_serializer: true"""
<|body_0|>
def toggle_ranking(self, request, pk=None):
"""Changes the enable_ranking flag ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MeetViewSet:
"""Retrieve a meet by its id"""
def set_active(self, request, pk=None):
"""Sets a meet as active, storing it in the user's session --- omit_serializer: true"""
try:
models.Meet.objects.all().exclude(id=int(pk)).update(is_current_meet=False, enable_ranking=False)
... | the_stack_v2_python_sparse | fairplay/meet/views.py | Greymalkin/fairplay | train | 0 |
0456f52a5aba090e3fce44ca6e21a59434e04914 | [
"rest_utils.validate_inputs({'blueprint_id': blueprint_id})\nvisibility = rest_utils.get_visibility_parameter(optional=True, is_argument=True, valid_values=VisibilityState.STATES)\nreturn UploadedBlueprintsManager().receive_uploaded_data(data_id=blueprint_id, visibility=visibility)",
"query_args = get_args_and_ve... | <|body_start_0|>
rest_utils.validate_inputs({'blueprint_id': blueprint_id})
visibility = rest_utils.get_visibility_parameter(optional=True, is_argument=True, valid_values=VisibilityState.STATES)
return UploadedBlueprintsManager().receive_uploaded_data(data_id=blueprint_id, visibility=visibility)... | BlueprintsId | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlueprintsId:
def put(self, blueprint_id, **kwargs):
"""Upload a blueprint (id specified)"""
<|body_0|>
def delete(self, blueprint_id, **kwargs):
"""Delete blueprint by id"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rest_utils.validate_inputs({'... | stack_v2_sparse_classes_75kplus_train_070312 | 4,110 | permissive | [
{
"docstring": "Upload a blueprint (id specified)",
"name": "put",
"signature": "def put(self, blueprint_id, **kwargs)"
},
{
"docstring": "Delete blueprint by id",
"name": "delete",
"signature": "def delete(self, blueprint_id, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007626 | Implement the Python class `BlueprintsId` described below.
Class description:
Implement the BlueprintsId class.
Method signatures and docstrings:
- def put(self, blueprint_id, **kwargs): Upload a blueprint (id specified)
- def delete(self, blueprint_id, **kwargs): Delete blueprint by id | Implement the Python class `BlueprintsId` described below.
Class description:
Implement the BlueprintsId class.
Method signatures and docstrings:
- def put(self, blueprint_id, **kwargs): Upload a blueprint (id specified)
- def delete(self, blueprint_id, **kwargs): Delete blueprint by id
<|skeleton|>
class Blueprints... | 3e062e8dec16c89d2ab180d0b761cbf76d3f7ddc | <|skeleton|>
class BlueprintsId:
def put(self, blueprint_id, **kwargs):
"""Upload a blueprint (id specified)"""
<|body_0|>
def delete(self, blueprint_id, **kwargs):
"""Delete blueprint by id"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BlueprintsId:
def put(self, blueprint_id, **kwargs):
"""Upload a blueprint (id specified)"""
rest_utils.validate_inputs({'blueprint_id': blueprint_id})
visibility = rest_utils.get_visibility_parameter(optional=True, is_argument=True, valid_values=VisibilityState.STATES)
return ... | the_stack_v2_python_sparse | rest-service/manager_rest/rest/resources_v3_1/blueprints.py | TS-at-WS/cloudify-manager | train | 0 | |
403432ad1af7debf921f448fec32b13c2f4896ae | [
"if fname.endswith('.gz'):\n with gzip.open(fname, 'rt') as fasta:\n return [line.strip() for line in fasta if not line.startswith('>')]\nelse:\n with open(fname, 'r') as fasta:\n return [line.strip() for line in fasta if not line.startswith('>')]",
"TMPDIR = os.environ.get('TMPDIR')\nbasename... | <|body_start_0|>
if fname.endswith('.gz'):
with gzip.open(fname, 'rt') as fasta:
return [line.strip() for line in fasta if not line.startswith('>')]
else:
with open(fname, 'r') as fasta:
return [line.strip() for line in fasta if not line.startswith... | Produce a summary of alignment metrics from BAM file. Tool from Picard, wrapped by GATK4. See GATK CollectAlignmentSummaryMetrics for more information. | AlignmentSummary | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlignmentSummary:
"""Produce a summary of alignment metrics from BAM file. Tool from Picard, wrapped by GATK4. See GATK CollectAlignmentSummaryMetrics for more information."""
def get_sequences(self, fname):
"""Get a list of sequences from FASTA file."""
<|body_0|>
def r... | stack_v2_sparse_classes_75kplus_train_070313 | 4,769 | permissive | [
{
"docstring": "Get a list of sequences from FASTA file.",
"name": "get_sequences",
"signature": "def get_sequences(self, fname)"
},
{
"docstring": "Run analysis.",
"name": "run",
"signature": "def run(self, inputs, outputs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027400 | Implement the Python class `AlignmentSummary` described below.
Class description:
Produce a summary of alignment metrics from BAM file. Tool from Picard, wrapped by GATK4. See GATK CollectAlignmentSummaryMetrics for more information.
Method signatures and docstrings:
- def get_sequences(self, fname): Get a list of se... | Implement the Python class `AlignmentSummary` described below.
Class description:
Produce a summary of alignment metrics from BAM file. Tool from Picard, wrapped by GATK4. See GATK CollectAlignmentSummaryMetrics for more information.
Method signatures and docstrings:
- def get_sequences(self, fname): Get a list of se... | 4f881f852064a841c337fa60b2084659fe58b6ba | <|skeleton|>
class AlignmentSummary:
"""Produce a summary of alignment metrics from BAM file. Tool from Picard, wrapped by GATK4. See GATK CollectAlignmentSummaryMetrics for more information."""
def get_sequences(self, fname):
"""Get a list of sequences from FASTA file."""
<|body_0|>
def r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlignmentSummary:
"""Produce a summary of alignment metrics from BAM file. Tool from Picard, wrapped by GATK4. See GATK CollectAlignmentSummaryMetrics for more information."""
def get_sequences(self, fname):
"""Get a list of sequences from FASTA file."""
if fname.endswith('.gz'):
... | the_stack_v2_python_sparse | resolwe_bio/processes/support_processors/alignment_summary.py | genialis/resolwe-bio | train | 18 |
9f114b834ef9b9bc326e68b4d85caa4296b60cdb | [
"dims = (wrapper.num_people, wrapper.num_people, wrapper.num_samples)\nsuper().__init__(wrapper, dims)\nself.embedder = embedder\nself.transformer = transformer",
"style_pid, source_pid, source_sid = coords_from_index(index, self.dims)\nsource_audio = self.wrapper.mel_from_ids(source_pid, source_sid)[None, :]\nst... | <|body_start_0|>
dims = (wrapper.num_people, wrapper.num_people, wrapper.num_samples)
super().__init__(wrapper, dims)
self.embedder = embedder
self.transformer = transformer
<|end_body_0|>
<|body_start_1|>
style_pid, source_pid, source_sid = coords_from_index(index, self.dims)
... | A class for training the isvoice discriminator with negative (generated) examples | Isvoice_Dataset_Fake | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Isvoice_Dataset_Fake:
"""A class for training the isvoice discriminator with negative (generated) examples"""
def __init__(self, wrapper, embedder, transformer):
"""There are (people * samples) original "real" files, and (people) possible transformations of each of files."""
... | stack_v2_sparse_classes_75kplus_train_070314 | 12,382 | no_license | [
{
"docstring": "There are (people * samples) original \"real\" files, and (people) possible transformations of each of files.",
"name": "__init__",
"signature": "def __init__(self, wrapper, embedder, transformer)"
},
{
"docstring": "# TODO Work on some sort of caching if there are speed/memory i... | 2 | stack_v2_sparse_classes_30k_train_027504 | Implement the Python class `Isvoice_Dataset_Fake` described below.
Class description:
A class for training the isvoice discriminator with negative (generated) examples
Method signatures and docstrings:
- def __init__(self, wrapper, embedder, transformer): There are (people * samples) original "real" files, and (peopl... | Implement the Python class `Isvoice_Dataset_Fake` described below.
Class description:
A class for training the isvoice discriminator with negative (generated) examples
Method signatures and docstrings:
- def __init__(self, wrapper, embedder, transformer): There are (people * samples) original "real" files, and (peopl... | ceb1b9580f515df744f7c7bfb94e6a2ae6a18c87 | <|skeleton|>
class Isvoice_Dataset_Fake:
"""A class for training the isvoice discriminator with negative (generated) examples"""
def __init__(self, wrapper, embedder, transformer):
"""There are (people * samples) original "real" files, and (people) possible transformations of each of files."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Isvoice_Dataset_Fake:
"""A class for training the isvoice discriminator with negative (generated) examples"""
def __init__(self, wrapper, embedder, transformer):
"""There are (people * samples) original "real" files, and (people) possible transformations of each of files."""
dims = (wrapp... | the_stack_v2_python_sparse | vocal-mimicry/dataset.py | anlsh/cs4803 | train | 0 |
f8424298e7a91b8a26c913665867563ebb67177e | [
"if k == 1 or not nums or len(nums) == 0:\n return nums\nrs, index_list = ([], [])\nn = 0\nfor i, num in enumerate(nums):\n n += 1\n while len(index_list) > 0 and num >= nums[index_list[-1]]:\n index_list.pop()\n index_list.append(i)\n if n >= k:\n rs.append(nums[index_list[0]])\n if... | <|body_start_0|>
if k == 1 or not nums or len(nums) == 0:
return nums
rs, index_list = ([], [])
n = 0
for i, num in enumerate(nums):
n += 1
while len(index_list) > 0 and num >= nums[index_list[-1]]:
index_list.pop()
index_li... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxSlidingWindow1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_070315 | 1,280 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxSlidingWindow",
"signature": "def maxSlidingWindow(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxSlidingWindow1",
"signature": "def maxSlidingWindow1... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxSlidingWindow1(self, nums, k): :type nums: List[int] :type k: int :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxSlidingWindow1(self, nums, k): :type nums: List[int] :type k: int :rtype: List[... | d4a33dc28a6d3f99d5179fdb6a83b2ab8c5a0beb | <|skeleton|>
class Solution:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxSlidingWindow1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
if k == 1 or not nums or len(nums) == 0:
return nums
rs, index_list = ([], [])
n = 0
for i, num in enumerate(nums):
n += 1
while... | the_stack_v2_python_sparse | leetcode/239_slide_window_max.py | 294150302hxq/python_learn | train | 0 | |
bb6fa62c52a84fd01c965ba04e8696c6195896f7 | [
"self.ip = ip\nself.is_bot = is_bot\nself.is_exploit_bot = is_exploit_bot\nself.is_malware = is_malware\nself.is_spider = is_spider\nself.is_dshield = is_dshield\nself.list_count = list_count\nself.is_proxy = is_proxy\nself.is_hijacked = is_hijacked\nself.is_tor = is_tor\nself.is_spyware = is_spyware\nself.is_spam_... | <|body_start_0|>
self.ip = ip
self.is_bot = is_bot
self.is_exploit_bot = is_exploit_bot
self.is_malware = is_malware
self.is_spider = is_spider
self.is_dshield = is_dshield
self.list_count = list_count
self.is_proxy = is_proxy
self.is_hijacked = is... | Implementation of the 'IP Blocklist Response' model. TODO: type model description here. Attributes: ip (string): The IP address is_bot (bool): IP is hosting a malicious bot or is part of a botnet. Includes brute-force crackers is_exploit_bot (bool): IP is hosting an exploit finding bot or is running exploit scanning so... | IPBlocklistResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPBlocklistResponse:
"""Implementation of the 'IP Blocklist Response' model. TODO: type model description here. Attributes: ip (string): The IP address is_bot (bool): IP is hosting a malicious bot or is part of a botnet. Includes brute-force crackers is_exploit_bot (bool): IP is hosting an exploi... | stack_v2_sparse_classes_75kplus_train_070316 | 6,111 | permissive | [
{
"docstring": "Constructor for the IPBlocklistResponse class",
"name": "__init__",
"signature": "def __init__(self, ip=None, is_bot=None, is_exploit_bot=None, is_malware=None, is_spider=None, is_dshield=None, list_count=None, is_proxy=None, is_hijacked=None, is_tor=None, is_spyware=None, is_spam_bot=No... | 2 | stack_v2_sparse_classes_30k_train_054232 | Implement the Python class `IPBlocklistResponse` described below.
Class description:
Implementation of the 'IP Blocklist Response' model. TODO: type model description here. Attributes: ip (string): The IP address is_bot (bool): IP is hosting a malicious bot or is part of a botnet. Includes brute-force crackers is_expl... | Implement the Python class `IPBlocklistResponse` described below.
Class description:
Implementation of the 'IP Blocklist Response' model. TODO: type model description here. Attributes: ip (string): The IP address is_bot (bool): IP is hosting a malicious bot or is part of a botnet. Includes brute-force crackers is_expl... | cc00933eefef0f40710f606e9fbf2dfb97a4f063 | <|skeleton|>
class IPBlocklistResponse:
"""Implementation of the 'IP Blocklist Response' model. TODO: type model description here. Attributes: ip (string): The IP address is_bot (bool): IP is hosting a malicious bot or is part of a botnet. Includes brute-force crackers is_exploit_bot (bool): IP is hosting an exploi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IPBlocklistResponse:
"""Implementation of the 'IP Blocklist Response' model. TODO: type model description here. Attributes: ip (string): The IP address is_bot (bool): IP is hosting a malicious bot or is part of a botnet. Includes brute-force crackers is_exploit_bot (bool): IP is hosting an exploit finding bot... | the_stack_v2_python_sparse | neutrino_api/models/ip_blocklist_response.py | NeutrinoAPI/NeutrinoAPI-Python | train | 3 |
78dbf8b796a3ea604ab52f25d59a50bc958aff2f | [
"assert isinstance(labels, type([])) or labels is None\nassert name is not None\nself.name = name\nself._labels = labels\nself._monitor_num = monitor_num\nself._bounding_box = bounding_box\nself._zone_names = zone_names\nself._min_score = min_score\nself._callable = callable\nself._no_zone = no_zone",
"if self._m... | <|body_start_0|>
assert isinstance(labels, type([])) or labels is None
assert name is not None
self.name = name
self._labels = labels
self._monitor_num = monitor_num
self._bounding_box = bounding_box
self._zone_names = zone_names
self._min_score = min_scor... | Class to filter out an object from object detection results. | IgnoredObject | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IgnoredObject:
"""Class to filter out an object from object detection results."""
def __init__(self, name, labels, monitor_num=None, bounding_box=None, zone_names=None, min_score=None, callable=None, no_zone=False):
"""Initialize an IgnoredObject instance. When object detection is ru... | stack_v2_sparse_classes_75kplus_train_070317 | 4,976 | no_license | [
{
"docstring": "Initialize an IgnoredObject instance. When object detection is run on Frames, each found object is passed through the ``should_ignore()`` method of each instance of this class. If that method returns True, the object information will be drawn in gray on the analyzed image and will not be passed ... | 2 | null | Implement the Python class `IgnoredObject` described below.
Class description:
Class to filter out an object from object detection results.
Method signatures and docstrings:
- def __init__(self, name, labels, monitor_num=None, bounding_box=None, zone_names=None, min_score=None, callable=None, no_zone=False): Initiali... | Implement the Python class `IgnoredObject` described below.
Class description:
Class to filter out an object from object detection results.
Method signatures and docstrings:
- def __init__(self, name, labels, monitor_num=None, bounding_box=None, zone_names=None, min_score=None, callable=None, no_zone=False): Initiali... | 7f12d383dc19cbb6906a6c71c1b502f108a9c2ed | <|skeleton|>
class IgnoredObject:
"""Class to filter out an object from object detection results."""
def __init__(self, name, labels, monitor_num=None, bounding_box=None, zone_names=None, min_score=None, callable=None, no_zone=False):
"""Initialize an IgnoredObject instance. When object detection is ru... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IgnoredObject:
"""Class to filter out an object from object detection results."""
def __init__(self, name, labels, monitor_num=None, bounding_box=None, zone_names=None, min_score=None, callable=None, no_zone=False):
"""Initialize an IgnoredObject instance. When object detection is run on Frames, ... | the_stack_v2_python_sparse | zoneminder/zmevent_object_filter.py | jantman/home-automation-configs | train | 38 |
f57ab5bbd8777682142fac3b55b317198070b98d | [
"if name is None:\n r = list()\n for p in ProjectManager.PROJECTS:\n r.append(p.to_dict())\nelse:\n r = ProjectManager.get_project(name)\n r = r.to_dict()\ne = Entity(status=Status.SUCCESS, data=r)\nreturn e.to_dict()",
"e = Entity()\nif isinstance(flask_restful.request.get_json(), str):\n d... | <|body_start_0|>
if name is None:
r = list()
for p in ProjectManager.PROJECTS:
r.append(p.to_dict())
else:
r = ProjectManager.get_project(name)
r = r.to_dict()
e = Entity(status=Status.SUCCESS, data=r)
return e.to_dict()
<|e... | Project | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Project:
def get(self, name=None):
"""Description: GET single project by name or all registered projects :param name: <<Optional>> project name :return: Project JSON response"""
<|body_0|>
def post(self):
"""Description: POST register project :return: Registration st... | stack_v2_sparse_classes_75kplus_train_070318 | 3,708 | permissive | [
{
"docstring": "Description: GET single project by name or all registered projects :param name: <<Optional>> project name :return: Project JSON response",
"name": "get",
"signature": "def get(self, name=None)"
},
{
"docstring": "Description: POST register project :return: Registration status",
... | 3 | stack_v2_sparse_classes_30k_train_043150 | Implement the Python class `Project` described below.
Class description:
Implement the Project class.
Method signatures and docstrings:
- def get(self, name=None): Description: GET single project by name or all registered projects :param name: <<Optional>> project name :return: Project JSON response
- def post(self):... | Implement the Python class `Project` described below.
Class description:
Implement the Project class.
Method signatures and docstrings:
- def get(self, name=None): Description: GET single project by name or all registered projects :param name: <<Optional>> project name :return: Project JSON response
- def post(self):... | f65ad2c3bf6f01acb26660505f6ceded0bee888f | <|skeleton|>
class Project:
def get(self, name=None):
"""Description: GET single project by name or all registered projects :param name: <<Optional>> project name :return: Project JSON response"""
<|body_0|>
def post(self):
"""Description: POST register project :return: Registration st... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Project:
def get(self, name=None):
"""Description: GET single project by name or all registered projects :param name: <<Optional>> project name :return: Project JSON response"""
if name is None:
r = list()
for p in ProjectManager.PROJECTS:
r.append(p.to_... | the_stack_v2_python_sparse | GeneratorAPI/main/resources/python.py | alexZaicev/BlueprintsEdu | train | 0 | |
26ee07307cb543a6aba562cddb82d4ad8aceab9d | [
"component_spc = kwargs['spc'] if 'spc' in kwargs else spc.SPC\nwx_panel.COMPONENT.__init__(self, parent=parent, resource=resource, spc=component_spc, context=context)\nolap_query_browser.iqOLAPQueryBrowserProto.__init__(self, *args, parent=parent, **kwargs)",
"psp = self.getAttribute('olap_server')\nlog_func.deb... | <|body_start_0|>
component_spc = kwargs['spc'] if 'spc' in kwargs else spc.SPC
wx_panel.COMPONENT.__init__(self, parent=parent, resource=resource, spc=component_spc, context=context)
olap_query_browser.iqOLAPQueryBrowserProto.__init__(self, *args, parent=parent, **kwargs)
<|end_body_0|>
<|body_... | OLAP server query browser component. | iqWxOLAPQueryBrowser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class iqWxOLAPQueryBrowser:
"""OLAP server query browser component."""
def __init__(self, parent=None, resource=None, context=None, *args, **kwargs):
"""Standard component constructor. :param parent: Parent object. :param resource: Object resource dictionary. :param context: Context dictio... | stack_v2_sparse_classes_75kplus_train_070319 | 1,543 | no_license | [
{
"docstring": "Standard component constructor. :param parent: Parent object. :param resource: Object resource dictionary. :param context: Context dictionary.",
"name": "__init__",
"signature": "def __init__(self, parent=None, resource=None, context=None, *args, **kwargs)"
},
{
"docstring": "OLA... | 3 | stack_v2_sparse_classes_30k_train_035968 | Implement the Python class `iqWxOLAPQueryBrowser` described below.
Class description:
OLAP server query browser component.
Method signatures and docstrings:
- def __init__(self, parent=None, resource=None, context=None, *args, **kwargs): Standard component constructor. :param parent: Parent object. :param resource: O... | Implement the Python class `iqWxOLAPQueryBrowser` described below.
Class description:
OLAP server query browser component.
Method signatures and docstrings:
- def __init__(self, parent=None, resource=None, context=None, *args, **kwargs): Standard component constructor. :param parent: Parent object. :param resource: O... | 7550e242746cb2fb1219474463f8db21f8e3e114 | <|skeleton|>
class iqWxOLAPQueryBrowser:
"""OLAP server query browser component."""
def __init__(self, parent=None, resource=None, context=None, *args, **kwargs):
"""Standard component constructor. :param parent: Parent object. :param resource: Object resource dictionary. :param context: Context dictio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class iqWxOLAPQueryBrowser:
"""OLAP server query browser component."""
def __init__(self, parent=None, resource=None, context=None, *args, **kwargs):
"""Standard component constructor. :param parent: Parent object. :param resource: Object resource dictionary. :param context: Context dictionary."""
... | the_stack_v2_python_sparse | iq/components/wx_olap_query_browser/component.py | XHermitOne/iq_framework | train | 1 |
3b712ab8074120d6a1c6f48660e9c86e5c337f51 | [
"app = TaskGenomicFile.query.get(kf_id)\nif app is None:\n abort(404, 'could not find {} `{}`'.format('task_genomic_file', kf_id))\nreturn TaskGenomicFileSchema().jsonify(app)",
"app = TaskGenomicFile.query.get(kf_id)\nif app is None:\n abort(404, 'could not find {} `{}`'.format('task_genomic_file', kf_id))... | <|body_start_0|>
app = TaskGenomicFile.query.get(kf_id)
if app is None:
abort(404, 'could not find {} `{}`'.format('task_genomic_file', kf_id))
return TaskGenomicFileSchema().jsonify(app)
<|end_body_0|>
<|body_start_1|>
app = TaskGenomicFile.query.get(kf_id)
if app i... | TaskGenomicFile API | TaskGenomicFileAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskGenomicFileAPI:
"""TaskGenomicFile API"""
def get(self, kf_id):
"""Get a task_genomic_file by id --- template: path: get_by_id.yml properties: resource: TaskGenomicFile"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing task_genomic_file. Allows part... | stack_v2_sparse_classes_75kplus_train_070320 | 5,124 | permissive | [
{
"docstring": "Get a task_genomic_file by id --- template: path: get_by_id.yml properties: resource: TaskGenomicFile",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing task_genomic_file. Allows partial update --- template: path: update_by_id.yml propertie... | 3 | stack_v2_sparse_classes_30k_train_015993 | Implement the Python class `TaskGenomicFileAPI` described below.
Class description:
TaskGenomicFile API
Method signatures and docstrings:
- def get(self, kf_id): Get a task_genomic_file by id --- template: path: get_by_id.yml properties: resource: TaskGenomicFile
- def patch(self, kf_id): Update an existing task_geno... | Implement the Python class `TaskGenomicFileAPI` described below.
Class description:
TaskGenomicFile API
Method signatures and docstrings:
- def get(self, kf_id): Get a task_genomic_file by id --- template: path: get_by_id.yml properties: resource: TaskGenomicFile
- def patch(self, kf_id): Update an existing task_geno... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class TaskGenomicFileAPI:
"""TaskGenomicFile API"""
def get(self, kf_id):
"""Get a task_genomic_file by id --- template: path: get_by_id.yml properties: resource: TaskGenomicFile"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing task_genomic_file. Allows part... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TaskGenomicFileAPI:
"""TaskGenomicFile API"""
def get(self, kf_id):
"""Get a task_genomic_file by id --- template: path: get_by_id.yml properties: resource: TaskGenomicFile"""
app = TaskGenomicFile.query.get(kf_id)
if app is None:
abort(404, 'could not find {} `{}`'.fo... | the_stack_v2_python_sparse | dataservice/api/task_genomic_file/resources.py | kids-first/kf-api-dataservice | train | 9 |
3db3572409e9bbdb3307f4e3aaedc5000188290e | [
"try:\n original = self.__class__.objects.get(pk=self.pk)\n self.created = original.created\n self.created_by = original.created_by\nexcept self.__class__.DoesNotExist:\n pass",
"self.updated = timezone.now()\nself.full_clean(exclude=None)\nself.preserve_created_and_created_by()\nsuper(AbstractBase, s... | <|body_start_0|>
try:
original = self.__class__.objects.get(pk=self.pk)
self.created = original.created
self.created_by = original.created_by
except self.__class__.DoesNotExist:
pass
<|end_body_0|>
<|body_start_1|>
self.updated = timezone.now()
... | Base class for all models that belong to pesa_exchange application. | AbstractBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractBase:
"""Base class for all models that belong to pesa_exchange application."""
def preserve_created_and_created_by(self):
"""Ensure that created and created_by are not changed during updates."""
<|body_0|>
def save(self, *args, **kwargs):
"""Ensure valid... | stack_v2_sparse_classes_75kplus_train_070321 | 9,982 | no_license | [
{
"docstring": "Ensure that created and created_by are not changed during updates.",
"name": "preserve_created_and_created_by",
"signature": "def preserve_created_and_created_by(self)"
},
{
"docstring": "Ensure validations are run and updated/created preserved.",
"name": "save",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_017635 | Implement the Python class `AbstractBase` described below.
Class description:
Base class for all models that belong to pesa_exchange application.
Method signatures and docstrings:
- def preserve_created_and_created_by(self): Ensure that created and created_by are not changed during updates.
- def save(self, *args, **... | Implement the Python class `AbstractBase` described below.
Class description:
Base class for all models that belong to pesa_exchange application.
Method signatures and docstrings:
- def preserve_created_and_created_by(self): Ensure that created and created_by are not changed during updates.
- def save(self, *args, **... | b5b1941988236890a7cb05e6612295afa2df39e0 | <|skeleton|>
class AbstractBase:
"""Base class for all models that belong to pesa_exchange application."""
def preserve_created_and_created_by(self):
"""Ensure that created and created_by are not changed during updates."""
<|body_0|>
def save(self, *args, **kwargs):
"""Ensure valid... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AbstractBase:
"""Base class for all models that belong to pesa_exchange application."""
def preserve_created_and_created_by(self):
"""Ensure that created and created_by are not changed during updates."""
try:
original = self.__class__.objects.get(pk=self.pk)
self.c... | the_stack_v2_python_sparse | pesa_exchange/common/models.py | jimmyaduvagah/pesa-exchange | train | 0 |
98d9df822fd3b722acdb5e2e0c3f3ee0915146f9 | [
"super().__init__()\nself.win_size = win_length if win_length is not None else n_fft\nself.hop_size = hop_length\nself.fft_size = n_fft\nself.istft_pre = torch.nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=padding)\nself.net = ConvReluNorm(hidden_channels, hidden_channels, hidden_channels, kernel... | <|body_start_0|>
super().__init__()
self.win_size = win_length if win_length is not None else n_fft
self.hop_size = hop_length
self.fft_size = n_fft
self.istft_pre = torch.nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=padding)
self.net = ConvReluNorm(hi... | Generator_Noise | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator_Noise:
def __init__(self, win_length: int=1024, hop_length: int=256, n_fft: int=1024, hidden_channels: int=192, kernel_size: int=3, padding: int=1, dropout_rate: float=0.1):
"""Initialize the Generator_Noise module. Args: win_length (int, optional): Window length. If None, set ... | stack_v2_sparse_classes_75kplus_train_070322 | 35,285 | permissive | [
{
"docstring": "Initialize the Generator_Noise module. Args: win_length (int, optional): Window length. If None, set to `n_fft`. hop_length (int): Hop length. n_fft (int): FFT size. hidden_channels (int): Number of hidden representation channels. kernel_size (int): Size of the convolutional kernel. padding (int... | 2 | null | Implement the Python class `Generator_Noise` described below.
Class description:
Implement the Generator_Noise class.
Method signatures and docstrings:
- def __init__(self, win_length: int=1024, hop_length: int=256, n_fft: int=1024, hidden_channels: int=192, kernel_size: int=3, padding: int=1, dropout_rate: float=0.1... | Implement the Python class `Generator_Noise` described below.
Class description:
Implement the Generator_Noise class.
Method signatures and docstrings:
- def __init__(self, win_length: int=1024, hop_length: int=256, n_fft: int=1024, hidden_channels: int=192, kernel_size: int=3, padding: int=1, dropout_rate: float=0.1... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class Generator_Noise:
def __init__(self, win_length: int=1024, hop_length: int=256, n_fft: int=1024, hidden_channels: int=192, kernel_size: int=3, padding: int=1, dropout_rate: float=0.1):
"""Initialize the Generator_Noise module. Args: win_length (int, optional): Window length. If None, set ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Generator_Noise:
def __init__(self, win_length: int=1024, hop_length: int=256, n_fft: int=1024, hidden_channels: int=192, kernel_size: int=3, padding: int=1, dropout_rate: float=0.1):
"""Initialize the Generator_Noise module. Args: win_length (int, optional): Window length. If None, set to `n_fft`. ho... | the_stack_v2_python_sparse | espnet2/gan_svs/visinger2/visinger2_vocoder.py | espnet/espnet | train | 7,242 | |
6ea84b27e1aacc2fef00b14632368c2a2a487eb4 | [
"self.metadata = MetadataCatalog.get(cfg.DATASETS.TEST[0] if len(cfg.DATASETS.TEST) else '__unused').set(thing_classes=['G1/G2', 'S', 'M', 'E'])\nself.cpu_device = torch.device('cpu')\nself.instance_mode = instance_mode\nself.parallel = parallel\nif parallel:\n num_gpu = torch.cuda.device_count()\n self.predi... | <|body_start_0|>
self.metadata = MetadataCatalog.get(cfg.DATASETS.TEST[0] if len(cfg.DATASETS.TEST) else '__unused').set(thing_classes=['G1/G2', 'S', 'M', 'E'])
self.cpu_device = torch.device('cpu')
self.instance_mode = instance_mode
self.parallel = parallel
if parallel:
... | VisualizationDemo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisualizationDemo:
def __init__(self, cfg, instance_mode=ColorMode.IMAGE, parallel=False):
"""Copied from Facebook Detectron2 Demo. Apache 2.0 Licence. Args: cfg (CfgNode): instance_mode (ColorMode): parallel (bool): whether to run the model in different processes from visualization. Use... | stack_v2_sparse_classes_75kplus_train_070323 | 13,593 | permissive | [
{
"docstring": "Copied from Facebook Detectron2 Demo. Apache 2.0 Licence. Args: cfg (CfgNode): instance_mode (ColorMode): parallel (bool): whether to run the model in different processes from visualization. Useful since the visualization logic can be slow.",
"name": "__init__",
"signature": "def __init_... | 2 | stack_v2_sparse_classes_30k_train_038382 | Implement the Python class `VisualizationDemo` described below.
Class description:
Implement the VisualizationDemo class.
Method signatures and docstrings:
- def __init__(self, cfg, instance_mode=ColorMode.IMAGE, parallel=False): Copied from Facebook Detectron2 Demo. Apache 2.0 Licence. Args: cfg (CfgNode): instance_... | Implement the Python class `VisualizationDemo` described below.
Class description:
Implement the VisualizationDemo class.
Method signatures and docstrings:
- def __init__(self, cfg, instance_mode=ColorMode.IMAGE, parallel=False): Copied from Facebook Detectron2 Demo. Apache 2.0 Licence. Args: cfg (CfgNode): instance_... | 16f8128167c143dfd9cb6cf25046725a5cf1273a | <|skeleton|>
class VisualizationDemo:
def __init__(self, cfg, instance_mode=ColorMode.IMAGE, parallel=False):
"""Copied from Facebook Detectron2 Demo. Apache 2.0 Licence. Args: cfg (CfgNode): instance_mode (ColorMode): parallel (bool): whether to run the model in different processes from visualization. Use... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VisualizationDemo:
def __init__(self, cfg, instance_mode=ColorMode.IMAGE, parallel=False):
"""Copied from Facebook Detectron2 Demo. Apache 2.0 Licence. Args: cfg (CfgNode): instance_mode (ColorMode): parallel (bool): whether to run the model in different processes from visualization. Useful since the ... | the_stack_v2_python_sparse | bin/pcnaDeep/predictor.py | kuanyoow/PCNAdeep | train | 0 | |
27e675b6fdffa1b26dedcbb194741c2215c2cb41 | [
"try:\n cls.abrir_conexion()\n sql = 'select * from direcciones where idDireccion = %s'\n values = (idDireccion,)\n cls.cursor.execute(sql, values)\n direccion = cls.cursor.fetchone()\n return Direccion(direccion[0], direccion[1], direccion[2], direccion[3], direccion[4], direccion[5])\nexcept Exc... | <|body_start_0|>
try:
cls.abrir_conexion()
sql = 'select * from direcciones where idDireccion = %s'
values = (idDireccion,)
cls.cursor.execute(sql, values)
direccion = cls.cursor.fetchone()
return Direccion(direccion[0], direccion[1], direc... | DatosDireccion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatosDireccion:
def get_one_id(cls, idDireccion, noClose=False):
"""Obtiene una dirección por su ID de la BD."""
<|body_0|>
def alta_direccion(cls, direccion, noClose=False):
"""Añade una direccion a la BD."""
<|body_1|>
def mod_direccion(cls, direccion,... | stack_v2_sparse_classes_75kplus_train_070324 | 3,294 | no_license | [
{
"docstring": "Obtiene una dirección por su ID de la BD.",
"name": "get_one_id",
"signature": "def get_one_id(cls, idDireccion, noClose=False)"
},
{
"docstring": "Añade una direccion a la BD.",
"name": "alta_direccion",
"signature": "def alta_direccion(cls, direccion, noClose=False)"
... | 3 | stack_v2_sparse_classes_30k_train_008509 | Implement the Python class `DatosDireccion` described below.
Class description:
Implement the DatosDireccion class.
Method signatures and docstrings:
- def get_one_id(cls, idDireccion, noClose=False): Obtiene una dirección por su ID de la BD.
- def alta_direccion(cls, direccion, noClose=False): Añade una direccion a ... | Implement the Python class `DatosDireccion` described below.
Class description:
Implement the DatosDireccion class.
Method signatures and docstrings:
- def get_one_id(cls, idDireccion, noClose=False): Obtiene una dirección por su ID de la BD.
- def alta_direccion(cls, direccion, noClose=False): Añade una direccion a ... | 57ca674dba4dabd2526c450ba7210933240f19c5 | <|skeleton|>
class DatosDireccion:
def get_one_id(cls, idDireccion, noClose=False):
"""Obtiene una dirección por su ID de la BD."""
<|body_0|>
def alta_direccion(cls, direccion, noClose=False):
"""Añade una direccion a la BD."""
<|body_1|>
def mod_direccion(cls, direccion,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatosDireccion:
def get_one_id(cls, idDireccion, noClose=False):
"""Obtiene una dirección por su ID de la BD."""
try:
cls.abrir_conexion()
sql = 'select * from direcciones where idDireccion = %s'
values = (idDireccion,)
cls.cursor.execute(sql, va... | the_stack_v2_python_sparse | data/data_direccion.py | JoaquinCardonaRuiz/proyecto-final | train | 0 | |
282ade2e50c7c481faeff487ca2012751830b1c2 | [
"nome = 'Francisco Souza'\nemail = 'chico@django.com'\ndestinatario = mixer.blend(Destinatario, nome=nome, email=email)\ndestinatario_result = Destinatario.objects.last()\nassert destinatario_result.nome == nome",
"nome = 'Marlene da Silva'\nemail = 'marlene@django.com'\ndestinatario = mixer.blend(Destinatario, n... | <|body_start_0|>
nome = 'Francisco Souza'
email = 'chico@django.com'
destinatario = mixer.blend(Destinatario, nome=nome, email=email)
destinatario_result = Destinatario.objects.last()
assert destinatario_result.nome == nome
<|end_body_0|>
<|body_start_1|>
nome = 'Marlene... | Classe para teste do modelo Destinatario | TestDestinatarioModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDestinatarioModel:
"""Classe para teste do modelo Destinatario"""
def test_destinatario_create(self):
"""Teste de criação de uma instância de Destinatario"""
<|body_0|>
def test_str_return(self):
"""Teste de retorno __str__ para uma instância de Destinatario"... | stack_v2_sparse_classes_75kplus_train_070325 | 3,332 | permissive | [
{
"docstring": "Teste de criação de uma instância de Destinatario",
"name": "test_destinatario_create",
"signature": "def test_destinatario_create(self)"
},
{
"docstring": "Teste de retorno __str__ para uma instância de Destinatario",
"name": "test_str_return",
"signature": "def test_str... | 2 | stack_v2_sparse_classes_30k_val_001246 | Implement the Python class `TestDestinatarioModel` described below.
Class description:
Classe para teste do modelo Destinatario
Method signatures and docstrings:
- def test_destinatario_create(self): Teste de criação de uma instância de Destinatario
- def test_str_return(self): Teste de retorno __str__ para uma instâ... | Implement the Python class `TestDestinatarioModel` described below.
Class description:
Classe para teste do modelo Destinatario
Method signatures and docstrings:
- def test_destinatario_create(self): Teste de criação de uma instância de Destinatario
- def test_str_return(self): Teste de retorno __str__ para uma instâ... | f0511728ffe0e2dd9d20059d2a187b8b72d3d88c | <|skeleton|>
class TestDestinatarioModel:
"""Classe para teste do modelo Destinatario"""
def test_destinatario_create(self):
"""Teste de criação de uma instância de Destinatario"""
<|body_0|>
def test_str_return(self):
"""Teste de retorno __str__ para uma instância de Destinatario"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDestinatarioModel:
"""Classe para teste do modelo Destinatario"""
def test_destinatario_create(self):
"""Teste de criação de uma instância de Destinatario"""
nome = 'Francisco Souza'
email = 'chico@django.com'
destinatario = mixer.blend(Destinatario, nome=nome, email=e... | the_stack_v2_python_sparse | luiza_api/tests.py | danembaum/com_api | train | 0 |
638f7ca1e20429496a40f832437aa97793d70a64 | [
"rectangles = []\nconfidences = []\nnum_rows, num_cols = prob.shape[2:4]\nfor y in range(0, num_rows):\n prob_data = prob[0, 0, y]\n coord = [boxes[0, i, y] for i in range(4)]\n angles = boxes[0, 4, y]\n for x in range(0, num_cols):\n if prob_data[x] < 0.5:\n continue\n h = coor... | <|body_start_0|>
rectangles = []
confidences = []
num_rows, num_cols = prob.shape[2:4]
for y in range(0, num_rows):
prob_data = prob[0, 0, y]
coord = [boxes[0, i, y] for i in range(4)]
angles = boxes[0, 4, y]
for x in range(0, num_cols):
... | TextDetector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextDetector:
def localize_post_process(prob, boxes):
"""process raw bounding boxes :param prob: probability of text :param boxes: raw boxes around text :return: boxes on the scaled image"""
<|body_0|>
def localize_text(frame, scale=(320, 320)):
"""localize bounding ... | stack_v2_sparse_classes_75kplus_train_070326 | 4,023 | permissive | [
{
"docstring": "process raw bounding boxes :param prob: probability of text :param boxes: raw boxes around text :return: boxes on the scaled image",
"name": "localize_post_process",
"signature": "def localize_post_process(prob, boxes)"
},
{
"docstring": "localize bounding boxes around text area ... | 4 | stack_v2_sparse_classes_30k_train_008869 | Implement the Python class `TextDetector` described below.
Class description:
Implement the TextDetector class.
Method signatures and docstrings:
- def localize_post_process(prob, boxes): process raw bounding boxes :param prob: probability of text :param boxes: raw boxes around text :return: boxes on the scaled image... | Implement the Python class `TextDetector` described below.
Class description:
Implement the TextDetector class.
Method signatures and docstrings:
- def localize_post_process(prob, boxes): process raw bounding boxes :param prob: probability of text :param boxes: raw boxes around text :return: boxes on the scaled image... | 429b2209ac0484a57e84d320a1f556f7e31c3996 | <|skeleton|>
class TextDetector:
def localize_post_process(prob, boxes):
"""process raw bounding boxes :param prob: probability of text :param boxes: raw boxes around text :return: boxes on the scaled image"""
<|body_0|>
def localize_text(frame, scale=(320, 320)):
"""localize bounding ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextDetector:
def localize_post_process(prob, boxes):
"""process raw bounding boxes :param prob: probability of text :param boxes: raw boxes around text :return: boxes on the scaled image"""
rectangles = []
confidences = []
num_rows, num_cols = prob.shape[2:4]
for y in ... | the_stack_v2_python_sparse | modules/text_detection.py | anujanegi/VQA | train | 12 | |
8613b18e9a67bcfd19303ab3a8c2c958cbf23c7d | [
"self.logger = logging.getLogger(__name__)\nself.filename = filename\nif display is None:\n display = os.environ['DISPLAY']\nself.display = display\nif size is None:\n size = (1024, 768)\nself.size = size\nself.p = None",
"cmd = 'ffmpeg -y' + ' -video_size %sx%s' % self.size + ' -framerate 25' + ' -preset u... | <|body_start_0|>
self.logger = logging.getLogger(__name__)
self.filename = filename
if display is None:
display = os.environ['DISPLAY']
self.display = display
if size is None:
size = (1024, 768)
self.size = size
self.p = None
<|end_body_0|>... | WebRecordXvfb | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebRecordXvfb:
def __init__(self, filename, size=None, display=None):
"""record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (W,H) (ex. (1024,768)). display: the DISPLAY to record (ex. ':0.0')."""
<|body_0|>
def sta... | stack_v2_sparse_classes_75kplus_train_070327 | 3,050 | permissive | [
{
"docstring": "record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (W,H) (ex. (1024,768)). display: the DISPLAY to record (ex. ':0.0').",
"name": "__init__",
"signature": "def __init__(self, filename, size=None, display=None)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_049668 | Implement the Python class `WebRecordXvfb` described below.
Class description:
Implement the WebRecordXvfb class.
Method signatures and docstrings:
- def __init__(self, filename, size=None, display=None): record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (... | Implement the Python class `WebRecordXvfb` described below.
Class description:
Implement the WebRecordXvfb class.
Method signatures and docstrings:
- def __init__(self, filename, size=None, display=None): record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (... | 2ff506eb56ba00f035300862f8848e4168452a17 | <|skeleton|>
class WebRecordXvfb:
def __init__(self, filename, size=None, display=None):
"""record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (W,H) (ex. (1024,768)). display: the DISPLAY to record (ex. ':0.0')."""
<|body_0|>
def sta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WebRecordXvfb:
def __init__(self, filename, size=None, display=None):
"""record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (W,H) (ex. (1024,768)). display: the DISPLAY to record (ex. ':0.0')."""
self.logger = logging.getLogger(__nam... | the_stack_v2_python_sparse | hubcheck/utils/record.py | ken2190/hubcheck | train | 0 | |
e3f696c7779863c6bee0963f1ca34d494b11beb7 | [
"invoice_vals = super(SaleOrderLine, self)._prepare_order_line_invoice_line(account_id=account_id)\nif self.sale_layout_cat_id:\n invoice_vals['sale_layout_cat_id'] = self.sale_layout_cat_id.id\nif self.categ_sequence:\n invoice_vals['categ_sequence'] = self.categ_sequence\nreturn invoice_vals",
"res = supe... | <|body_start_0|>
invoice_vals = super(SaleOrderLine, self)._prepare_order_line_invoice_line(account_id=account_id)
if self.sale_layout_cat_id:
invoice_vals['sale_layout_cat_id'] = self.sale_layout_cat_id.id
if self.categ_sequence:
invoice_vals['categ_sequence'] = self.cat... | SaleOrderLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaleOrderLine:
def _prepare_order_line_invoice_line(self, account_id=False):
"""Save the layout when converting to an invoice line."""
<|body_0|>
def _prepare_invoice_line(self, qty):
"""Prepare the dict of values to create the new invoice line for a sales order line... | stack_v2_sparse_classes_75kplus_train_070328 | 3,772 | no_license | [
{
"docstring": "Save the layout when converting to an invoice line.",
"name": "_prepare_order_line_invoice_line",
"signature": "def _prepare_order_line_invoice_line(self, account_id=False)"
},
{
"docstring": "Prepare the dict of values to create the new invoice line for a sales order line. :para... | 2 | stack_v2_sparse_classes_30k_train_048309 | Implement the Python class `SaleOrderLine` described below.
Class description:
Implement the SaleOrderLine class.
Method signatures and docstrings:
- def _prepare_order_line_invoice_line(self, account_id=False): Save the layout when converting to an invoice line.
- def _prepare_invoice_line(self, qty): Prepare the di... | Implement the Python class `SaleOrderLine` described below.
Class description:
Implement the SaleOrderLine class.
Method signatures and docstrings:
- def _prepare_order_line_invoice_line(self, account_id=False): Save the layout when converting to an invoice line.
- def _prepare_invoice_line(self, qty): Prepare the di... | a12caeabf64662fb134c2b10c4ede8006173edfd | <|skeleton|>
class SaleOrderLine:
def _prepare_order_line_invoice_line(self, account_id=False):
"""Save the layout when converting to an invoice line."""
<|body_0|>
def _prepare_invoice_line(self, qty):
"""Prepare the dict of values to create the new invoice line for a sales order line... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SaleOrderLine:
def _prepare_order_line_invoice_line(self, account_id=False):
"""Save the layout when converting to an invoice line."""
invoice_vals = super(SaleOrderLine, self)._prepare_order_line_invoice_line(account_id=account_id)
if self.sale_layout_cat_id:
invoice_vals[... | the_stack_v2_python_sparse | talentys_custom/models/sale_layout.py | lekaizen210/addons_talentys | train | 0 | |
76bd06a35b90e91d728cbef2fcbb340d055c44e1 | [
"if roles.Roles.is_super_admin():\n exit_url = '%s?tab=google_service_account' % handler.LINK_URL\nelse:\n exit_url = cls.request.referer\nrest_url = GoogleServiceAccountRESTHandler.URI\ntemplate_values = {}\ntemplate_values['page_title'] = handler.format_title('Google Service Accounts')\ncontent = safe_dom.N... | <|body_start_0|>
if roles.Roles.is_super_admin():
exit_url = '%s?tab=google_service_account' % handler.LINK_URL
else:
exit_url = cls.request.referer
rest_url = GoogleServiceAccountRESTHandler.URI
template_values = {}
template_values['page_title'] = handler... | GoogleServiceAccountBaseAdminHandler | [
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleServiceAccountBaseAdminHandler:
def get_google_service_account(cls, handler):
"""Displays list of service account settings."""
<|body_0|>
def get_edit_google_service_account(cls, handler):
"""Handles 'get_add_google_service_account_settings' action and renders ... | stack_v2_sparse_classes_75kplus_train_070329 | 13,602 | permissive | [
{
"docstring": "Displays list of service account settings.",
"name": "get_google_service_account",
"signature": "def get_google_service_account(cls, handler)"
},
{
"docstring": "Handles 'get_add_google_service_account_settings' action and renders new course entry editor.",
"name": "get_edit_... | 3 | stack_v2_sparse_classes_30k_train_042312 | Implement the Python class `GoogleServiceAccountBaseAdminHandler` described below.
Class description:
Implement the GoogleServiceAccountBaseAdminHandler class.
Method signatures and docstrings:
- def get_google_service_account(cls, handler): Displays list of service account settings.
- def get_edit_google_service_acc... | Implement the Python class `GoogleServiceAccountBaseAdminHandler` described below.
Class description:
Implement the GoogleServiceAccountBaseAdminHandler class.
Method signatures and docstrings:
- def get_google_service_account(cls, handler): Displays list of service account settings.
- def get_edit_google_service_acc... | 2bca9d64499e160b2da9bed6e97fcda712feec72 | <|skeleton|>
class GoogleServiceAccountBaseAdminHandler:
def get_google_service_account(cls, handler):
"""Displays list of service account settings."""
<|body_0|>
def get_edit_google_service_account(cls, handler):
"""Handles 'get_add_google_service_account_settings' action and renders ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoogleServiceAccountBaseAdminHandler:
def get_google_service_account(cls, handler):
"""Displays list of service account settings."""
if roles.Roles.is_super_admin():
exit_url = '%s?tab=google_service_account' % handler.LINK_URL
else:
exit_url = cls.request.refer... | the_stack_v2_python_sparse | coursebuilder/modules/google_service_account/settings.py | RavinderSinghPB/seek | train | 0 | |
85f47f0d3e6a9c0418d427d00de354e8fc2f4223 | [
"self.wind_speed = np.ones((3, 4), dtype=np.float32)\nself.sin_wind_dir = np.full((3, 4), 0.4, dtype=np.float32)\nself.cos_wind_dir = np.full((3, 4), np.sqrt(0.84), dtype=np.float32)\nself.plugin = OrographicEnhancement()\nself.plugin.grid_spacing_km = 3.0",
"distance = self.plugin._get_point_distances(self.wind_... | <|body_start_0|>
self.wind_speed = np.ones((3, 4), dtype=np.float32)
self.sin_wind_dir = np.full((3, 4), 0.4, dtype=np.float32)
self.cos_wind_dir = np.full((3, 4), np.sqrt(0.84), dtype=np.float32)
self.plugin = OrographicEnhancement()
self.plugin.grid_spacing_km = 3.0
<|end_body_... | Test the _locate_source_points method | Test__locate_source_points | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__locate_source_points:
"""Test the _locate_source_points method"""
def setUp(self):
"""Define input matrices and plugin"""
<|body_0|>
def test_basic(self):
"""Test location of source points"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
se... | stack_v2_sparse_classes_75kplus_train_070330 | 34,979 | permissive | [
{
"docstring": "Define input matrices and plugin",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test location of source points",
"name": "test_basic",
"signature": "def test_basic(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039229 | Implement the Python class `Test__locate_source_points` described below.
Class description:
Test the _locate_source_points method
Method signatures and docstrings:
- def setUp(self): Define input matrices and plugin
- def test_basic(self): Test location of source points | Implement the Python class `Test__locate_source_points` described below.
Class description:
Test the _locate_source_points method
Method signatures and docstrings:
- def setUp(self): Define input matrices and plugin
- def test_basic(self): Test location of source points
<|skeleton|>
class Test__locate_source_points:... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__locate_source_points:
"""Test the _locate_source_points method"""
def setUp(self):
"""Define input matrices and plugin"""
<|body_0|>
def test_basic(self):
"""Test location of source points"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test__locate_source_points:
"""Test the _locate_source_points method"""
def setUp(self):
"""Define input matrices and plugin"""
self.wind_speed = np.ones((3, 4), dtype=np.float32)
self.sin_wind_dir = np.full((3, 4), 0.4, dtype=np.float32)
self.cos_wind_dir = np.full((3, 4)... | the_stack_v2_python_sparse | improver_tests/orographic_enhancement/test_OrographicEnhancement.py | metoppv/improver | train | 101 |
c39af27c34f715466f6d9833d962ce4df0d249a1 | [
"RangeNode.__init__(self, *args, **kwargs)\nself.Length = Length\nself.Array = Array",
"if not self.Length:\n self.Array = vec.copy()\nelse:\n self.Array = mutate_array(vec, self.Length)\ncurr_children = self.Children\ncurr_arrays = [self.Array] * len(curr_children)\nwhile len(curr_children):\n new_child... | <|body_start_0|>
RangeNode.__init__(self, *args, **kwargs)
self.Length = Length
self.Array = Array
<|end_body_0|>
<|body_start_1|>
if not self.Length:
self.Array = vec.copy()
else:
self.Array = mutate_array(vec, self.Length)
curr_children = self.C... | MicroarrayNode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MicroarrayNode:
def __init__(self, Length=0, Array=None, *args, **kwargs):
"""Returns new MicroarrayNode object. Length: float giving the branch length (sd to add to data) Array: array of float giving the expression vector, or None Additional args for superclass: Name: usually a text lab... | stack_v2_sparse_classes_75kplus_train_070331 | 2,238 | permissive | [
{
"docstring": "Returns new MicroarrayNode object. Length: float giving the branch length (sd to add to data) Array: array of float giving the expression vector, or None Additional args for superclass: Name: usually a text label giving the name of the node LeafRange: range of leaves that the node spans Id: uniq... | 2 | stack_v2_sparse_classes_30k_train_012206 | Implement the Python class `MicroarrayNode` described below.
Class description:
Implement the MicroarrayNode class.
Method signatures and docstrings:
- def __init__(self, Length=0, Array=None, *args, **kwargs): Returns new MicroarrayNode object. Length: float giving the branch length (sd to add to data) Array: array ... | Implement the Python class `MicroarrayNode` described below.
Class description:
Implement the MicroarrayNode class.
Method signatures and docstrings:
- def __init__(self, Length=0, Array=None, *args, **kwargs): Returns new MicroarrayNode object. Length: float giving the branch length (sd to add to data) Array: array ... | fe6f8c8dfed86d39c80f2804a753c05bb2e485b4 | <|skeleton|>
class MicroarrayNode:
def __init__(self, Length=0, Array=None, *args, **kwargs):
"""Returns new MicroarrayNode object. Length: float giving the branch length (sd to add to data) Array: array of float giving the expression vector, or None Additional args for superclass: Name: usually a text lab... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MicroarrayNode:
def __init__(self, Length=0, Array=None, *args, **kwargs):
"""Returns new MicroarrayNode object. Length: float giving the branch length (sd to add to data) Array: array of float giving the expression vector, or None Additional args for superclass: Name: usually a text label giving the ... | the_stack_v2_python_sparse | scripts/venv/lib/python2.7/site-packages/cogent/seqsim/microarray.py | sauloal/cnidaria | train | 3 | |
7f79c63e2ace12c00bd64007466083135eb391c2 | [
"data = {'username': 'python31', 'password': 'lemonban'}\nexpected = {'code': 0, 'msg': '登录成功'}\nres = login_check(**data)\nself.assertEqual(expected, res)",
"data = {'username': 'python31', 'password': 'lemonban111'}\nexpected = {'code': 1, 'msg': '账号或密码不正确'}\nres = login_check(**data)\nself.assertEqual(expected... | <|body_start_0|>
data = {'username': 'python31', 'password': 'lemonban'}
expected = {'code': 0, 'msg': '登录成功'}
res = login_check(**data)
self.assertEqual(expected, res)
<|end_body_0|>
<|body_start_1|>
data = {'username': 'python31', 'password': 'lemonban111'}
expected = ... | 登录的测试用例类 | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
"""登录的测试用例类"""
def test_login_pass(self):
"""登录成功的用例"""
<|body_0|>
def test_login_pwd_error(self):
"""密码错误"""
<|body_1|>
def test_login_pwd_is_none(self):
"""密码为空"""
<|body_2|>
def test_login_user_is_none(self):
... | stack_v2_sparse_classes_75kplus_train_070332 | 3,469 | no_license | [
{
"docstring": "登录成功的用例",
"name": "test_login_pass",
"signature": "def test_login_pass(self)"
},
{
"docstring": "密码错误",
"name": "test_login_pwd_error",
"signature": "def test_login_pwd_error(self)"
},
{
"docstring": "密码为空",
"name": "test_login_pwd_is_none",
"signature": "... | 5 | stack_v2_sparse_classes_30k_train_004697 | Implement the Python class `TestLogin` described below.
Class description:
登录的测试用例类
Method signatures and docstrings:
- def test_login_pass(self): 登录成功的用例
- def test_login_pwd_error(self): 密码错误
- def test_login_pwd_is_none(self): 密码为空
- def test_login_user_is_none(self): 账号为空
- def test_login_user_error(self): 账号错误 | Implement the Python class `TestLogin` described below.
Class description:
登录的测试用例类
Method signatures and docstrings:
- def test_login_pass(self): 登录成功的用例
- def test_login_pwd_error(self): 密码错误
- def test_login_pwd_is_none(self): 密码为空
- def test_login_user_is_none(self): 账号为空
- def test_login_user_error(self): 账号错误
... | 734a049ecd84bfddc607ef852366eb5b7d16c6cb | <|skeleton|>
class TestLogin:
"""登录的测试用例类"""
def test_login_pass(self):
"""登录成功的用例"""
<|body_0|>
def test_login_pwd_error(self):
"""密码错误"""
<|body_1|>
def test_login_pwd_is_none(self):
"""密码为空"""
<|body_2|>
def test_login_user_is_none(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestLogin:
"""登录的测试用例类"""
def test_login_pass(self):
"""登录成功的用例"""
data = {'username': 'python31', 'password': 'lemonban'}
expected = {'code': 0, 'msg': '登录成功'}
res = login_check(**data)
self.assertEqual(expected, res)
def test_login_pwd_error(self):
"... | the_stack_v2_python_sparse | day13unittest初识/day13_teacher/demo_02单元测试框架.py | guoyunfei0603/py31 | train | 0 |
8bd831f08308c039edeba572172d98a79e2e2a78 | [
"self.part_map = {}\nself.part_landmark_map = {}\nself.added_lane_ids = []\nself.added_landmark_ids = []\nself.removed_lane_ids = []\nself.removed_landmark_ids = []\nself.added_partitions = []\nself.removed_partitions = []",
"self.added_lane_ids = []\nself.added_landmark_ids = []\nself.removed_lane_ids = []\nself... | <|body_start_0|>
self.part_map = {}
self.part_landmark_map = {}
self.added_lane_ids = []
self.added_landmark_ids = []
self.removed_lane_ids = []
self.removed_landmark_ids = []
self.added_partitions = []
self.removed_partitions = []
<|end_body_0|>
<|body_s... | ... | PartitionManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartitionManager:
"""..."""
def __init__(self):
"""..."""
<|body_0|>
def reset(self):
"""..."""
<|body_1|>
def clear(self):
"""..."""
<|body_2|>
def add_lane(self, part, lane_id):
"""..."""
<|body_3|>
def rem... | stack_v2_sparse_classes_75kplus_train_070333 | 1,932 | permissive | [
{
"docstring": "...",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "...",
"name": "reset",
"signature": "def reset(self)"
},
{
"docstring": "...",
"name": "clear",
"signature": "def clear(self)"
},
{
"docstring": "...",
"name": "add_... | 6 | stack_v2_sparse_classes_30k_train_047210 | Implement the Python class `PartitionManager` described below.
Class description:
...
Method signatures and docstrings:
- def __init__(self): ...
- def reset(self): ...
- def clear(self): ...
- def add_lane(self, part, lane_id): ...
- def remove_lane(self, lane_id): ...
- def debug_print(self): ... | Implement the Python class `PartitionManager` described below.
Class description:
...
Method signatures and docstrings:
- def __init__(self): ...
- def reset(self): ...
- def clear(self): ...
- def add_lane(self, part, lane_id): ...
- def remove_lane(self, lane_id): ...
- def debug_print(self): ...
<|skeleton|>
clas... | cc9618fd005bc28ad08d0f89f30911bb7a75a41e | <|skeleton|>
class PartitionManager:
"""..."""
def __init__(self):
"""..."""
<|body_0|>
def reset(self):
"""..."""
<|body_1|>
def clear(self):
"""..."""
<|body_2|>
def add_lane(self, part, lane_id):
"""..."""
<|body_3|>
def rem... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PartitionManager:
"""..."""
def __init__(self):
"""..."""
self.part_map = {}
self.part_landmark_map = {}
self.added_lane_ids = []
self.added_landmark_ids = []
self.removed_lane_ids = []
self.removed_landmark_ids = []
self.added_partitions = ... | the_stack_v2_python_sparse | tools/ad_map_access_qgis/ad_map_access_qgis/PartitionManager.py | carla-simulator/map | train | 87 |
5594a08c80f300fc45484c7212f64a27db93d924 | [
"if isinstance(jobtype_name, STRING_TYPES):\n jobtype = JobType.query.filter_by(name=jobtype_name).first()\nelse:\n jobtype = JobType.query.filter_by(id=jobtype_name).first()\nif not jobtype:\n return (jsonify(error='JobType %s not found' % jobtype_name), NOT_FOUND)\ncurrent_version = JobTypeVersion.query.... | <|body_start_0|>
if isinstance(jobtype_name, STRING_TYPES):
jobtype = JobType.query.filter_by(name=jobtype_name).first()
else:
jobtype = JobType.query.filter_by(id=jobtype_name).first()
if not jobtype:
return (jsonify(error='JobType %s not found' % jobtype_nam... | JobTypeSoftwareRequirementAPI | [
"BSD-3-Clause",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobTypeSoftwareRequirementAPI:
def get(self, jobtype_name, software):
"""A ``GET`` to this endpoint will return the specified software requirement from the newest version of the requested jobtype. .. http:get:: /api/v1/jobtypes/[<str:name>|<int:id>]/software_requirements/<int:id> HTTP/1.... | stack_v2_sparse_classes_75kplus_train_070334 | 42,171 | permissive | [
{
"docstring": "A ``GET`` to this endpoint will return the specified software requirement from the newest version of the requested jobtype. .. http:get:: /api/v1/jobtypes/[<str:name>|<int:id>]/software_requirements/<int:id> HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/jobtypes/TestJobType/software_requ... | 2 | null | Implement the Python class `JobTypeSoftwareRequirementAPI` described below.
Class description:
Implement the JobTypeSoftwareRequirementAPI class.
Method signatures and docstrings:
- def get(self, jobtype_name, software): A ``GET`` to this endpoint will return the specified software requirement from the newest version... | Implement the Python class `JobTypeSoftwareRequirementAPI` described below.
Class description:
Implement the JobTypeSoftwareRequirementAPI class.
Method signatures and docstrings:
- def get(self, jobtype_name, software): A ``GET`` to this endpoint will return the specified software requirement from the newest version... | ea04bbcb807eb669415c569417b4b1b68e75d29d | <|skeleton|>
class JobTypeSoftwareRequirementAPI:
def get(self, jobtype_name, software):
"""A ``GET`` to this endpoint will return the specified software requirement from the newest version of the requested jobtype. .. http:get:: /api/v1/jobtypes/[<str:name>|<int:id>]/software_requirements/<int:id> HTTP/1.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobTypeSoftwareRequirementAPI:
def get(self, jobtype_name, software):
"""A ``GET`` to this endpoint will return the specified software requirement from the newest version of the requested jobtype. .. http:get:: /api/v1/jobtypes/[<str:name>|<int:id>]/software_requirements/<int:id> HTTP/1.1 **Request** ... | the_stack_v2_python_sparse | pyfarm/master/api/jobtypes.py | pyfarm/pyfarm-master | train | 2 | |
e25192bcc4e1f7229d8162c3575ea0a858f245c1 | [
"rows = super(Table, self).rows\nif len(rows) == 1 and self.row_empty.is_present:\n return []\nelse:\n return rows",
"_columns = {}\nfor pos, cell in enumerate(self.header.cells, 1):\n column = cell.get_attribute('innerText').strip()\n if column:\n column = re.sub('[ -]', '_', column).lower()\n... | <|body_start_0|>
rows = super(Table, self).rows
if len(rows) == 1 and self.row_empty.is_present:
return []
else:
return rows
<|end_body_0|>
<|body_start_1|>
_columns = {}
for pos, cell in enumerate(self.header.cells, 1):
column = cell.get_attr... | Custom table. | Table | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Table:
"""Custom table."""
def rows(self):
"""Table rows."""
<|body_0|>
def columns(self):
"""Table columns {'name': position}."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rows = super(Table, self).rows
if len(rows) == 1 and self.row... | stack_v2_sparse_classes_75kplus_train_070335 | 2,719 | no_license | [
{
"docstring": "Table rows.",
"name": "rows",
"signature": "def rows(self)"
},
{
"docstring": "Table columns {'name': position}.",
"name": "columns",
"signature": "def columns(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023254 | Implement the Python class `Table` described below.
Class description:
Custom table.
Method signatures and docstrings:
- def rows(self): Table rows.
- def columns(self): Table columns {'name': position}. | Implement the Python class `Table` described below.
Class description:
Custom table.
Method signatures and docstrings:
- def rows(self): Table rows.
- def columns(self): Table columns {'name': position}.
<|skeleton|>
class Table:
"""Custom table."""
def rows(self):
"""Table rows."""
<|body_0... | e7583444cd24893ec6ae237b47db7c605b99b0c5 | <|skeleton|>
class Table:
"""Custom table."""
def rows(self):
"""Table rows."""
<|body_0|>
def columns(self):
"""Table columns {'name': position}."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Table:
"""Custom table."""
def rows(self):
"""Table rows."""
rows = super(Table, self).rows
if len(rows) == 1 and self.row_empty.is_present:
return []
else:
return rows
def columns(self):
"""Table columns {'name': position}."""
... | the_stack_v2_python_sparse | stepler/horizon/app/ui/table.py | Mirantis/stepler | train | 16 |
53340980c9dfab87579ad5a890bba8bf61deaf70 | [
"try:\n if not full_access_to_name_request(request):\n return ({'message': 'You do not have access to this NameRequest.'}, 403)\n nr_model = Request.query.get(nr_id)\n self.initialize()\n nr_svc = self.nr_service\n nr_svc.nr_num = nr_model.nrNum\n nr_svc.nr_id = nr_model.id\n\n def valid... | <|body_start_0|>
try:
if not full_access_to_name_request(request):
return ({'message': 'You do not have access to this NameRequest.'}, 403)
nr_model = Request.query.get(nr_id)
self.initialize()
nr_svc = self.nr_service
nr_svc.nr_num = n... | NameRequestRollback | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NameRequestRollback:
def patch(self, nr_id, action):
"""Roll back a Name Request to a usable state in case of a frontend error. :param nr_id: :param action: :return:"""
<|body_0|>
def handle_patch_rollback(self, nr_model: Request, action: str):
"""Roll back the Name ... | stack_v2_sparse_classes_75kplus_train_070336 | 22,574 | permissive | [
{
"docstring": "Roll back a Name Request to a usable state in case of a frontend error. :param nr_id: :param action: :return:",
"name": "patch",
"signature": "def patch(self, nr_id, action)"
},
{
"docstring": "Roll back the Name Request. :param nr_model: :param action: :return:",
"name": "ha... | 2 | stack_v2_sparse_classes_30k_train_037274 | Implement the Python class `NameRequestRollback` described below.
Class description:
Implement the NameRequestRollback class.
Method signatures and docstrings:
- def patch(self, nr_id, action): Roll back a Name Request to a usable state in case of a frontend error. :param nr_id: :param action: :return:
- def handle_p... | Implement the Python class `NameRequestRollback` described below.
Class description:
Implement the NameRequestRollback class.
Method signatures and docstrings:
- def patch(self, nr_id, action): Roll back a Name Request to a usable state in case of a frontend error. :param nr_id: :param action: :return:
- def handle_p... | 0175587b7322a3e41076b8bd7a3976f486491a5c | <|skeleton|>
class NameRequestRollback:
def patch(self, nr_id, action):
"""Roll back a Name Request to a usable state in case of a frontend error. :param nr_id: :param action: :return:"""
<|body_0|>
def handle_patch_rollback(self, nr_model: Request, action: str):
"""Roll back the Name ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NameRequestRollback:
def patch(self, nr_id, action):
"""Roll back a Name Request to a usable state in case of a frontend error. :param nr_id: :param action: :return:"""
try:
if not full_access_to_name_request(request):
return ({'message': 'You do not have access to ... | the_stack_v2_python_sparse | api/namex/resources/name_requests/name_request.py | bcgov/namex | train | 5 | |
695cee99cf12c7c750bdd02cbb215e58afb2e2f2 | [
"super().__init__()\nout_channels = channels * self.expansion\nif cardinality == 1:\n rc = channels\nelse:\n width_ratio = channels * (width / self.start_filts)\n rc = cardinality * math.floor(width_ratio)\nself.conv_reduce = ConvNdTorch(n_dim, in_channels, rc, kernel_size=1, stride=1, padding=0, bias=Fals... | <|body_start_0|>
super().__init__()
out_channels = channels * self.expansion
if cardinality == 1:
rc = channels
else:
width_ratio = channels * (width / self.start_filts)
rc = cardinality * math.floor(width_ratio)
self.conv_reduce = ConvNdTorch(... | SEBottleneckXTorch | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SEBottleneckXTorch:
def __init__(self, in_channels, channels, stride, cardinality, width, n_dim, norm_layer, avg_down, reduction=16):
"""Squeeze and Excitation ResNeXt Block Parameters ---------- in_channels : int number of input channels stride : int stride of 3x3 convolution layer card... | stack_v2_sparse_classes_75kplus_train_070337 | 8,979 | permissive | [
{
"docstring": "Squeeze and Excitation ResNeXt Block Parameters ---------- in_channels : int number of input channels stride : int stride of 3x3 convolution layer cardinality : int number of convolution groups width : int width of resnext block n_dim : int dimensionality of convolutions norm_layer : str type of... | 2 | stack_v2_sparse_classes_30k_train_021146 | Implement the Python class `SEBottleneckXTorch` described below.
Class description:
Implement the SEBottleneckXTorch class.
Method signatures and docstrings:
- def __init__(self, in_channels, channels, stride, cardinality, width, n_dim, norm_layer, avg_down, reduction=16): Squeeze and Excitation ResNeXt Block Paramet... | Implement the Python class `SEBottleneckXTorch` described below.
Class description:
Implement the SEBottleneckXTorch class.
Method signatures and docstrings:
- def __init__(self, in_channels, channels, stride, cardinality, width, n_dim, norm_layer, avg_down, reduction=16): Squeeze and Excitation ResNeXt Block Paramet... | d944aa67d319bd63a2add5cb89e8308413943de6 | <|skeleton|>
class SEBottleneckXTorch:
def __init__(self, in_channels, channels, stride, cardinality, width, n_dim, norm_layer, avg_down, reduction=16):
"""Squeeze and Excitation ResNeXt Block Parameters ---------- in_channels : int number of input channels stride : int stride of 3x3 convolution layer card... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SEBottleneckXTorch:
def __init__(self, in_channels, channels, stride, cardinality, width, n_dim, norm_layer, avg_down, reduction=16):
"""Squeeze and Excitation ResNeXt Block Parameters ---------- in_channels : int number of input channels stride : int stride of 3x3 convolution layer cardinality : int ... | the_stack_v2_python_sparse | deliravision/torch/models/backbones/seblocks.py | delira-dev/vision_torch | train | 5 | |
7440e2ba36343186bf83d171d6a27428a081ceb8 | [
"self.kVal = k\nself.heapList = []\nfor num in nums:\n self.add(num)",
"import heapq\nif len(self.heapList) < self.kVal:\n heapq.heappush(self.heapList, val)\nelif val > self.heapList[0]:\n heapq.heappop(self.heapList)\n heapq.heappush(self.heapList, val)\nreturn self.heapList[0]"
] | <|body_start_0|>
self.kVal = k
self.heapList = []
for num in nums:
self.add(num)
<|end_body_0|>
<|body_start_1|>
import heapq
if len(self.heapList) < self.kVal:
heapq.heappush(self.heapList, val)
elif val > self.heapList[0]:
heapq.heap... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.kVal = k
self.heapList = []
for num i... | stack_v2_sparse_classes_75kplus_train_070338 | 811 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023363 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 234fd3d0e3b09b1bf64e840274b064d0303187e9 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.kVal = k
self.heapList = []
for num in nums:
self.add(num)
def add(self, val):
""":type val: int :rtype: int"""
import heapq
if len(self.heapList) < s... | the_stack_v2_python_sparse | Heap/KthLargestStream.py | vikrant1998/Python-World | train | 0 | |
77e6ef8c446011b837e612d1a412756f43a10c43 | [
"nums1_copy = nums1[0:m]\nnums1[:] = []\np1, p2 = (0, 0)\nwhile p1 < m and p2 < n:\n if nums1_copy[p1] < nums2[p2]:\n nums1.append(nums1_copy[p1])\n p1 += 1\n else:\n nums1.append(nums2[p2])\n p2 += 1\nnums1[p1 + p2:] = nums2[p2:] if p2 < n else nums1_copy[p1:]",
"p, p1, p2 = (m ... | <|body_start_0|>
nums1_copy = nums1[0:m]
nums1[:] = []
p1, p2 = (0, 0)
while p1 < m and p2 < n:
if nums1_copy[p1] < nums2[p2]:
nums1.append(nums1_copy[p1])
p1 += 1
else:
nums1.append(nums2[p2])
p2 += ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, mod... | stack_v2_sparse_classes_75kplus_train_070339 | 1,238 | no_license | [
{
"docstring": "Do not return anything, modify nums1 in-place instead.",
"name": "merge1",
"signature": "def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None"
},
{
"docstring": "Do not return anything, modify nums1 in-place instead.",
"name": "merge",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_054651 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: Do not return anything, modify nums1 in-place instead.
- def merge(self, nums1: List[int], m: int, n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: Do not return anything, modify nums1 in-place instead.
- def merge(self, nums1: List[int], m: int, n... | 41fa7e7719c3573716c967a4307dd792263aa14d | <|skeleton|>
class Solution:
def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, mod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, modify nums1 in-place instead."""
nums1_copy = nums1[0:m]
nums1[:] = []
p1, p2 = (0, 0)
while p1 < m and p2 < n:
if nums1_copy[p1] < nums2[p2]:... | the_stack_v2_python_sparse | python/88. 合并两个有序数组/leetcode.py | Sihaiyinan/leetcode-record | train | 3 | |
1813abf401214184a47e0f68daeb9397d7fffd2e | [
"self.driver.switch_to.default_content()\nself.driver.switch_to.frame(self.frame_menu)\nif not self.menu_snmp.is_visible():\n self.menu_system_maintenance.click()\nself.menu_snmp.click()\nself.driver.switch_to.default_content()\nself.driver.switch_to.frame(self.frame_main)",
"self.driver.switch_to.default_cont... | <|body_start_0|>
self.driver.switch_to.default_content()
self.driver.switch_to.frame(self.frame_menu)
if not self.menu_snmp.is_visible():
self.menu_system_maintenance.click()
self.menu_snmp.click()
self.driver.switch_to.default_content()
self.driver.switch_to.... | Selenium Page Object Model: Menu Navigation. | MenuNavigator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuNavigator:
"""Selenium Page Object Model: Menu Navigation."""
def open_sysmain_snmp(self):
"""Navigate the menus to open the SNMP configuration panel."""
<|body_0|>
def open_sysmain_management(self, tab: Link):
"""Navigate the menus to open the SNMP configura... | stack_v2_sparse_classes_75kplus_train_070340 | 3,160 | permissive | [
{
"docstring": "Navigate the menus to open the SNMP configuration panel.",
"name": "open_sysmain_snmp",
"signature": "def open_sysmain_snmp(self)"
},
{
"docstring": "Navigate the menus to open the SNMP configuration panel.",
"name": "open_sysmain_management",
"signature": "def open_sysma... | 5 | stack_v2_sparse_classes_30k_train_014272 | Implement the Python class `MenuNavigator` described below.
Class description:
Selenium Page Object Model: Menu Navigation.
Method signatures and docstrings:
- def open_sysmain_snmp(self): Navigate the menus to open the SNMP configuration panel.
- def open_sysmain_management(self, tab: Link): Navigate the menus to op... | Implement the Python class `MenuNavigator` described below.
Class description:
Selenium Page Object Model: Menu Navigation.
Method signatures and docstrings:
- def open_sysmain_snmp(self): Navigate the menus to open the SNMP configuration panel.
- def open_sysmain_management(self, tab: Link): Navigate the menus to op... | 0b3e96b892fb332a1252fc231b30561b2374071f | <|skeleton|>
class MenuNavigator:
"""Selenium Page Object Model: Menu Navigation."""
def open_sysmain_snmp(self):
"""Navigate the menus to open the SNMP configuration panel."""
<|body_0|>
def open_sysmain_management(self, tab: Link):
"""Navigate the menus to open the SNMP configura... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MenuNavigator:
"""Selenium Page Object Model: Menu Navigation."""
def open_sysmain_snmp(self):
"""Navigate the menus to open the SNMP configuration panel."""
self.driver.switch_to.default_content()
self.driver.switch_to.frame(self.frame_menu)
if not self.menu_snmp.is_visib... | the_stack_v2_python_sparse | draytekwebadmin/pages/menu_navigator.py | dMajoIT/Draytek-Web-Auto-Configuration | train | 0 |
92c5314c081a1479a1db6a48458bcadd98c453af | [
"self.change_rate = change_rate\nself.cluster_id = cluster_id\nself.cluster_incarnation_id = cluster_incarnation_id\nself.cluster_name = cluster_name\nself.read_bandwidth = read_bandwidth\nself.stats_by_env = stats_by_env\nself.vault_group = vault_group\nself.vault_id = vault_id\nself.vault_type = vault_type\nself.... | <|body_start_0|>
self.change_rate = change_rate
self.cluster_id = cluster_id
self.cluster_incarnation_id = cluster_incarnation_id
self.cluster_name = cluster_name
self.read_bandwidth = read_bandwidth
self.stats_by_env = stats_by_env
self.vault_group = vault_group
... | Implementation of the 'VaultProviderStatsInfo' model. Specifies the stats for each vault. Attributes: change_rate (long|int): Specifies the relative change of size of entities on the vault. cluster_id (long|int): Specifies the cluster id. cluster_incarnation_id (long|int): Specifies the cluster incarnation id. cluster_... | VaultProviderStatsInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VaultProviderStatsInfo:
"""Implementation of the 'VaultProviderStatsInfo' model. Specifies the stats for each vault. Attributes: change_rate (long|int): Specifies the relative change of size of entities on the vault. cluster_id (long|int): Specifies the cluster id. cluster_incarnation_id (long|in... | stack_v2_sparse_classes_75kplus_train_070341 | 4,509 | permissive | [
{
"docstring": "Constructor for the VaultProviderStatsInfo class",
"name": "__init__",
"signature": "def __init__(self, change_rate=None, cluster_id=None, cluster_incarnation_id=None, cluster_name=None, read_bandwidth=None, stats_by_env=None, vault_group=None, vault_id=None, vault_type=None, vaultname=N... | 2 | stack_v2_sparse_classes_30k_train_006426 | Implement the Python class `VaultProviderStatsInfo` described below.
Class description:
Implementation of the 'VaultProviderStatsInfo' model. Specifies the stats for each vault. Attributes: change_rate (long|int): Specifies the relative change of size of entities on the vault. cluster_id (long|int): Specifies the clus... | Implement the Python class `VaultProviderStatsInfo` described below.
Class description:
Implementation of the 'VaultProviderStatsInfo' model. Specifies the stats for each vault. Attributes: change_rate (long|int): Specifies the relative change of size of entities on the vault. cluster_id (long|int): Specifies the clus... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VaultProviderStatsInfo:
"""Implementation of the 'VaultProviderStatsInfo' model. Specifies the stats for each vault. Attributes: change_rate (long|int): Specifies the relative change of size of entities on the vault. cluster_id (long|int): Specifies the cluster id. cluster_incarnation_id (long|in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VaultProviderStatsInfo:
"""Implementation of the 'VaultProviderStatsInfo' model. Specifies the stats for each vault. Attributes: change_rate (long|int): Specifies the relative change of size of entities on the vault. cluster_id (long|int): Specifies the cluster id. cluster_incarnation_id (long|int): Specifies... | the_stack_v2_python_sparse | cohesity_management_sdk/models/vault_provider_stats_info.py | cohesity/management-sdk-python | train | 24 |
e2242486d3cffbeaa72969c014b426277c821ef4 | [
"Action.__init__(self, 'trace', 'out')\nself.enabled = True\nself.terminal = True\nself.branching = False\nself.start_ttl = start_ttl\nself.end_ttl = end_ttl\nself.ran = False\nself.socket = conf.L3socket(iface=actions.utils.get_interface())",
"logger.debug(' - Starting Trace action')\nif not packet.haslayer('IP... | <|body_start_0|>
Action.__init__(self, 'trace', 'out')
self.enabled = True
self.terminal = True
self.branching = False
self.start_ttl = start_ttl
self.end_ttl = end_ttl
self.ran = False
self.socket = conf.L3socket(iface=actions.utils.get_interface())
<|end... | The Trace Action is used to TTL probe/traceroute a censor. When the action fires, it sends the captured packet with increasing ttls within a certain range TraceAction is an experimental action that is never used in actual evolution | TraceAction | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TraceAction:
"""The Trace Action is used to TTL probe/traceroute a censor. When the action fires, it sends the captured packet with increasing ttls within a certain range TraceAction is an experimental action that is never used in actual evolution"""
def __init__(self, start_ttl=1, end_ttl=6... | stack_v2_sparse_classes_75kplus_train_070342 | 3,105 | permissive | [
{
"docstring": "Initializes the trace action. Args: start_ttl (int): Starting TTL to use end_ttl (int): TTL to end with environment_id (str, optional): Environment ID associated with the strategy we are a part of",
"name": "__init__",
"signature": "def __init__(self, start_ttl=1, end_ttl=64, environment... | 4 | stack_v2_sparse_classes_30k_train_011495 | Implement the Python class `TraceAction` described below.
Class description:
The Trace Action is used to TTL probe/traceroute a censor. When the action fires, it sends the captured packet with increasing ttls within a certain range TraceAction is an experimental action that is never used in actual evolution
Method si... | Implement the Python class `TraceAction` described below.
Class description:
The Trace Action is used to TTL probe/traceroute a censor. When the action fires, it sends the captured packet with increasing ttls within a certain range TraceAction is an experimental action that is never used in actual evolution
Method si... | 6b091060ed0946b98a2ff9196dfbf93d85cbb28a | <|skeleton|>
class TraceAction:
"""The Trace Action is used to TTL probe/traceroute a censor. When the action fires, it sends the captured packet with increasing ttls within a certain range TraceAction is an experimental action that is never used in actual evolution"""
def __init__(self, start_ttl=1, end_ttl=6... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TraceAction:
"""The Trace Action is used to TTL probe/traceroute a censor. When the action fires, it sends the captured packet with increasing ttls within a certain range TraceAction is an experimental action that is never used in actual evolution"""
def __init__(self, start_ttl=1, end_ttl=64, environmen... | the_stack_v2_python_sparse | actions/trace.py | Kkevsterrr/geneva | train | 1,771 |
daf7ce02d1a3d3a275d7e2a771f708388619e0df | [
"self.log.info('login from Live')\ncode = context.get('code')\nif not code:\n return None\naccess_token = self.get_token(code)\nuser_info = self.get_user_info(access_token)\nname = user_info['name']\nemail = user_info['emails']['account']\nemail_list = [{'name': name, 'email': email, 'verified': 1, 'primary': 1}... | <|body_start_0|>
self.log.info('login from Live')
code = context.get('code')
if not code:
return None
access_token = self.get_token(code)
user_info = self.get_user_info(access_token)
name = user_info['name']
email = user_info['emails']['account']
... | Sign in with live :Example: from client.user.login import LiveLogin LiveLogin() .. notes:: | LiveLogin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LiveLogin:
"""Sign in with live :Example: from client.user.login import LiveLogin LiveLogin() .. notes::"""
def login(self, context):
"""live Login :type context: Context :param context: :rtype: dict :return: token and instance of user"""
<|body_0|>
def get_token(self, c... | stack_v2_sparse_classes_75kplus_train_070343 | 17,886 | permissive | [
{
"docstring": "live Login :type context: Context :param context: :rtype: dict :return: token and instance of user",
"name": "login",
"signature": "def login(self, context)"
},
{
"docstring": "Get live access token :type code: str :param code: :rtype: str :return: access token and uid",
"nam... | 3 | stack_v2_sparse_classes_30k_train_043399 | Implement the Python class `LiveLogin` described below.
Class description:
Sign in with live :Example: from client.user.login import LiveLogin LiveLogin() .. notes::
Method signatures and docstrings:
- def login(self, context): live Login :type context: Context :param context: :rtype: dict :return: token and instance... | Implement the Python class `LiveLogin` described below.
Class description:
Sign in with live :Example: from client.user.login import LiveLogin LiveLogin() .. notes::
Method signatures and docstrings:
- def login(self, context): live Login :type context: Context :param context: :rtype: dict :return: token and instance... | 945c4fd2755f5b0dea11e54eb649eeb37ec93d01 | <|skeleton|>
class LiveLogin:
"""Sign in with live :Example: from client.user.login import LiveLogin LiveLogin() .. notes::"""
def login(self, context):
"""live Login :type context: Context :param context: :rtype: dict :return: token and instance of user"""
<|body_0|>
def get_token(self, c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LiveLogin:
"""Sign in with live :Example: from client.user.login import LiveLogin LiveLogin() .. notes::"""
def login(self, context):
"""live Login :type context: Context :param context: :rtype: dict :return: token and instance of user"""
self.log.info('login from Live')
code = co... | the_stack_v2_python_sparse | open-hackathon-server/src/hackathon/user/oauth_login.py | kaiyuanshe/open-hackathon | train | 46 |
43f4e632ea9cf887eb67f0b86e9d308954d71ea1 | [
"l, h = (0, len(nums) - 1)\nm = (l + h) // 2\nif len(nums) <= 2:\n return min(nums)\nmid = nums[m]\nlast = nums[h]\nif mid > last:\n return self.findMin(nums[m:h + 1])\nreturn self.findMin(nums[l:m + 1])",
"l, h = (0, len(nums) - 1)\nwhile h - l > 2:\n m = (l + h) // 2\n mid = nums[m]\n last = nums... | <|body_start_0|>
l, h = (0, len(nums) - 1)
m = (l + h) // 2
if len(nums) <= 2:
return min(nums)
mid = nums[m]
last = nums[h]
if mid > last:
return self.findMin(nums[m:h + 1])
return self.findMin(nums[l:m + 1])
<|end_body_0|>
<|body_start_1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMinIterative(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l, h = (0, len(nums) - 1)
m = (l + h... | stack_v2_sparse_classes_75kplus_train_070344 | 853 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin",
"signature": "def findMin(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMinIterative",
"signature": "def findMinIterative(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int
- def findMinIterative(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int
- def findMinIterative(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def findMin(se... | 39509b6187d4cb3b3615fe93ffe524b35f88a59f | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMinIterative(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
l, h = (0, len(nums) - 1)
m = (l + h) // 2
if len(nums) <= 2:
return min(nums)
mid = nums[m]
last = nums[h]
if mid > last:
return self.findMin(nums[m:h + 1... | the_stack_v2_python_sparse | python/findMinRotated.py | huangsam/leetcode | train | 5 | |
e4f1e5dd71852db8e7e278816437c384f9176139 | [
"public_ip = NETWORK.LOCAL_IP\ntry:\n public_ip = UtilityBox.do_request(PUBLIC_IP_URL)['ip']\nexcept (NameError, TypeError):\n LOG.log('info', 'The request for a public ip has failed')\n if raise_exception:\n raise ServiceNotAvailableException('Unable to get public IP from ' + PUBLIC_IP_URL)\nreturn... | <|body_start_0|>
public_ip = NETWORK.LOCAL_IP
try:
public_ip = UtilityBox.do_request(PUBLIC_IP_URL)['ip']
except (NameError, TypeError):
LOG.log('info', 'The request for a public ip has failed')
if raise_exception:
raise ServiceNotAvailableExce... | Class containing the static IP related methods. | IpGetter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IpGetter:
"""Class containing the static IP related methods."""
def get_public_ip(raise_exception=False):
"""Gets and returns the public ip of the local computer."""
<|body_0|>
def get_local_ip(raise_exception=False):
"""Gets and returns the IP assigned by the lo... | stack_v2_sparse_classes_75kplus_train_070345 | 3,689 | no_license | [
{
"docstring": "Gets and returns the public ip of the local computer.",
"name": "get_public_ip",
"signature": "def get_public_ip(raise_exception=False)"
},
{
"docstring": "Gets and returns the IP assigned by the local network to this computer. Schema: 192.X.X.X",
"name": "get_local_ip",
... | 3 | stack_v2_sparse_classes_30k_train_004250 | Implement the Python class `IpGetter` described below.
Class description:
Class containing the static IP related methods.
Method signatures and docstrings:
- def get_public_ip(raise_exception=False): Gets and returns the public ip of the local computer.
- def get_local_ip(raise_exception=False): Gets and returns the ... | Implement the Python class `IpGetter` described below.
Class description:
Class containing the static IP related methods.
Method signatures and docstrings:
- def get_public_ip(raise_exception=False): Gets and returns the public ip of the local computer.
- def get_local_ip(raise_exception=False): Gets and returns the ... | d80a812712fb72294d383f87573ee5778e42f3de | <|skeleton|>
class IpGetter:
"""Class containing the static IP related methods."""
def get_public_ip(raise_exception=False):
"""Gets and returns the public ip of the local computer."""
<|body_0|>
def get_local_ip(raise_exception=False):
"""Gets and returns the IP assigned by the lo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IpGetter:
"""Class containing the static IP related methods."""
def get_public_ip(raise_exception=False):
"""Gets and returns the public ip of the local computer."""
public_ip = NETWORK.LOCAL_IP
try:
public_ip = UtilityBox.do_request(PUBLIC_IP_URL)['ip']
except... | the_stack_v2_python_sparse | obj/utilities/ip_parser.py | Hinjeniero/sava_drow | train | 0 |
e00c33434d3a8795a7f19ff8b0184a14f19a470e | [
"if date1 == date2:\n return 0\ndate1 = date1.split('.')\nday1 = int(date1[0])\nmonth1 = int(date1[1])\ndate2 = date2.split('.')\nday2 = int(date2[0])\nmonth2 = int(date2[1])\nif month1 == month2:\n return day1 - day2\nelse:\n return month1 - month2",
"ok = 1\nwhile ok:\n ok = 0\n i = 0\n while ... | <|body_start_0|>
if date1 == date2:
return 0
date1 = date1.split('.')
day1 = int(date1[0])
month1 = int(date1[1])
date2 = date2.split('.')
day2 = int(date2[0])
month2 = int(date2[1])
if month1 == month2:
return day1 - day2
e... | sort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sort:
def datecmp(date1, date2):
"""Description: Compares date1 and date2 Input: date1, date2 Precondition: date1 and date2 are dates Output: date1 - date2 Postcondition: if date1 > date2, a > 0 number is returned/ 0 is returned if they are equal/ a < 0 number is returned otherwise"""
... | stack_v2_sparse_classes_75kplus_train_070346 | 2,170 | no_license | [
{
"docstring": "Description: Compares date1 and date2 Input: date1, date2 Precondition: date1 and date2 are dates Output: date1 - date2 Postcondition: if date1 > date2, a > 0 number is returned/ 0 is returned if they are equal/ a < 0 number is returned otherwise",
"name": "datecmp",
"signature": "def da... | 3 | stack_v2_sparse_classes_30k_train_019054 | Implement the Python class `sort` described below.
Class description:
Implement the sort class.
Method signatures and docstrings:
- def datecmp(date1, date2): Description: Compares date1 and date2 Input: date1, date2 Precondition: date1 and date2 are dates Output: date1 - date2 Postcondition: if date1 > date2, a > 0 ... | Implement the Python class `sort` described below.
Class description:
Implement the sort class.
Method signatures and docstrings:
- def datecmp(date1, date2): Description: Compares date1 and date2 Input: date1, date2 Precondition: date1 and date2 are dates Output: date1 - date2 Postcondition: if date1 > date2, a > 0 ... | 7cdf3b2d30829c866718a1aa53692e843930748a | <|skeleton|>
class sort:
def datecmp(date1, date2):
"""Description: Compares date1 and date2 Input: date1, date2 Precondition: date1 and date2 are dates Output: date1 - date2 Postcondition: if date1 > date2, a > 0 number is returned/ 0 is returned if they are equal/ a < 0 number is returned otherwise"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class sort:
def datecmp(date1, date2):
"""Description: Compares date1 and date2 Input: date1, date2 Precondition: date1 and date2 are dates Output: date1 - date2 Postcondition: if date1 > date2, a > 0 number is returned/ 0 is returned if they are equal/ a < 0 number is returned otherwise"""
if date1... | the_stack_v2_python_sparse | fp/lab5-7v2/sort.py | anflorea/courses | train | 5 | |
ffab28c7146255e16c435e134be71713068f8968 | [
"user = User.query.get(g.user.id)\nif user:\n return jsonify(dict(twoFAKey=user.twoFAKey, twoFALoggedin=user.twoFALoggedin))",
"args = twofaParser.parse_args()\nuser = User.query.get(g.user.id)\nif user.check_twoFAKey(args.get('otp')):\n return jsonify(dict(success=True))\nreturn abort(401, 'otp code is not... | <|body_start_0|>
user = User.query.get(g.user.id)
if user:
return jsonify(dict(twoFAKey=user.twoFAKey, twoFALoggedin=user.twoFALoggedin))
<|end_body_0|>
<|body_start_1|>
args = twofaParser.parse_args()
user = User.query.get(g.user.id)
if user.check_twoFAKey(args.get(... | setup_twofa | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class setup_twofa:
def get(self):
"""get otp twofa details"""
<|body_0|>
def put(self):
"""setup twofa"""
<|body_1|>
def delete(self):
"""disable twofa login"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
user = User.query.get(g.user... | stack_v2_sparse_classes_75kplus_train_070347 | 9,160 | no_license | [
{
"docstring": "get otp twofa details",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "setup twofa",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "disable twofa login",
"name": "delete",
"signature": "def delete(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_004813 | Implement the Python class `setup_twofa` described below.
Class description:
Implement the setup_twofa class.
Method signatures and docstrings:
- def get(self): get otp twofa details
- def put(self): setup twofa
- def delete(self): disable twofa login | Implement the Python class `setup_twofa` described below.
Class description:
Implement the setup_twofa class.
Method signatures and docstrings:
- def get(self): get otp twofa details
- def put(self): setup twofa
- def delete(self): disable twofa login
<|skeleton|>
class setup_twofa:
def get(self):
"""ge... | 1c7d812e214590e0f4759e6c5be411bd64f8e3c4 | <|skeleton|>
class setup_twofa:
def get(self):
"""get otp twofa details"""
<|body_0|>
def put(self):
"""setup twofa"""
<|body_1|>
def delete(self):
"""disable twofa login"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class setup_twofa:
def get(self):
"""get otp twofa details"""
user = User.query.get(g.user.id)
if user:
return jsonify(dict(twoFAKey=user.twoFAKey, twoFALoggedin=user.twoFALoggedin))
def put(self):
"""setup twofa"""
args = twofaParser.parse_args()
use... | the_stack_v2_python_sparse | apis/auth.py | ajutor-app/backend | train | 0 | |
9d0dc154fee95255fc3fade0d5110fe1d19f8e60 | [
"self.tiles = tiles\napp_children = []\nif appBar is None:\n appBar = AppBar(translator=translator)\nself.appBar = appBar\napp_children.append(self.appBar)\nif navDrawer is not None:\n [di.display_tile(tiles) for di in navDrawer.items]\n navDrawer.display_drawer(self.appBar.toggle_button)\n self.navDraw... | <|body_start_0|>
self.tiles = tiles
app_children = []
if appBar is None:
appBar = AppBar(translator=translator)
self.appBar = appBar
app_children.append(self.appBar)
if navDrawer is not None:
[di.display_tile(tiles) for di in navDrawer.items]
... | App | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class App:
def __init__(self, tiles: List[v.Card]=[], appBar: Optional[AppBar]=None, footer: Optional[Footer]=None, navDrawer: Optional[NavDrawer]=None, translator: Optional[Translator]=None, **kwargs) -> None:
"""Custom App display with the tiles created by the user using the sepal color fram... | stack_v2_sparse_classes_75kplus_train_070348 | 25,326 | permissive | [
{
"docstring": "Custom App display with the tiles created by the user using the sepal color framework. Display false appBar if not filled. Navdrawer is fully optional. The drawerItem will be linked to the app tile and they will be able to control their display If the navdrawer exist, it will be linked to the ap... | 6 | stack_v2_sparse_classes_30k_train_045746 | Implement the Python class `App` described below.
Class description:
Implement the App class.
Method signatures and docstrings:
- def __init__(self, tiles: List[v.Card]=[], appBar: Optional[AppBar]=None, footer: Optional[Footer]=None, navDrawer: Optional[NavDrawer]=None, translator: Optional[Translator]=None, **kwarg... | Implement the Python class `App` described below.
Class description:
Implement the App class.
Method signatures and docstrings:
- def __init__(self, tiles: List[v.Card]=[], appBar: Optional[AppBar]=None, footer: Optional[Footer]=None, navDrawer: Optional[NavDrawer]=None, translator: Optional[Translator]=None, **kwarg... | b26c7d698659d5c5a2029d02fc94dcd9daf0df98 | <|skeleton|>
class App:
def __init__(self, tiles: List[v.Card]=[], appBar: Optional[AppBar]=None, footer: Optional[Footer]=None, navDrawer: Optional[NavDrawer]=None, translator: Optional[Translator]=None, **kwargs) -> None:
"""Custom App display with the tiles created by the user using the sepal color fram... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class App:
def __init__(self, tiles: List[v.Card]=[], appBar: Optional[AppBar]=None, footer: Optional[Footer]=None, navDrawer: Optional[NavDrawer]=None, translator: Optional[Translator]=None, **kwargs) -> None:
"""Custom App display with the tiles created by the user using the sepal color framework. Display... | the_stack_v2_python_sparse | sepal_ui/sepalwidgets/app.py | 12rambau/sepal_ui | train | 17 | |
5632a874d92f4e5186e2f6fc66b4fb5dea18b8e0 | [
"if value is None:\n return SkillEffectiveness.StandardPeriodic\nif isinstance(value, SkillEffectiveness):\n return value\nmapping = dict()\nif hasattr(SkillEffectiveness, 'Small'):\n mapping[CommonSkillEffectiveness.SMALL] = SkillEffectiveness.Small\nif hasattr(SkillEffectiveness, 'Large'):\n mapping[C... | <|body_start_0|>
if value is None:
return SkillEffectiveness.StandardPeriodic
if isinstance(value, SkillEffectiveness):
return value
mapping = dict()
if hasattr(SkillEffectiveness, 'Small'):
mapping[CommonSkillEffectiveness.SMALL] = SkillEffectiveness.... | Various Skill Effectiveness. | CommonSkillEffectiveness | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonSkillEffectiveness:
"""Various Skill Effectiveness."""
def convert_to_vanilla(value: 'CommonSkillEffectiveness') -> SkillEffectiveness:
"""convert_to_vanilla(value) Convert a value into a vanilla SkillEffectiveness value. :param value: An instance of CommonSkillEffectiveness :t... | stack_v2_sparse_classes_75kplus_train_070349 | 5,822 | permissive | [
{
"docstring": "convert_to_vanilla(value) Convert a value into a vanilla SkillEffectiveness value. :param value: An instance of CommonSkillEffectiveness :type value: CommonSkillEffectiveness :return: The specified value translated to an SkillEffectiveness or StandardPeriodic if the value could not be translated... | 2 | stack_v2_sparse_classes_30k_train_007217 | Implement the Python class `CommonSkillEffectiveness` described below.
Class description:
Various Skill Effectiveness.
Method signatures and docstrings:
- def convert_to_vanilla(value: 'CommonSkillEffectiveness') -> SkillEffectiveness: convert_to_vanilla(value) Convert a value into a vanilla SkillEffectiveness value.... | Implement the Python class `CommonSkillEffectiveness` described below.
Class description:
Various Skill Effectiveness.
Method signatures and docstrings:
- def convert_to_vanilla(value: 'CommonSkillEffectiveness') -> SkillEffectiveness: convert_to_vanilla(value) Convert a value into a vanilla SkillEffectiveness value.... | 58e7beb30b9c818b294d35abd2436a0192cd3e82 | <|skeleton|>
class CommonSkillEffectiveness:
"""Various Skill Effectiveness."""
def convert_to_vanilla(value: 'CommonSkillEffectiveness') -> SkillEffectiveness:
"""convert_to_vanilla(value) Convert a value into a vanilla SkillEffectiveness value. :param value: An instance of CommonSkillEffectiveness :t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommonSkillEffectiveness:
"""Various Skill Effectiveness."""
def convert_to_vanilla(value: 'CommonSkillEffectiveness') -> SkillEffectiveness:
"""convert_to_vanilla(value) Convert a value into a vanilla SkillEffectiveness value. :param value: An instance of CommonSkillEffectiveness :type value: Co... | the_stack_v2_python_sparse | Scripts/sims4communitylib/enums/common_skill_effectiveness.py | ColonolNutty/Sims4CommunityLibrary | train | 183 |
dafd781d47a561d87f484dfda90249f9b97289b0 | [
"data = pd.read_excel(mining_file, sheetname='Mining_6D_US_MMBtu', index_col='NAICS_2012')\ndata.loc[:, 'Other'] = data.Misc + data.Crude\ndata.drop(['fac_count_2012', 'val_ship_dollars', 'Misc', 'Crude'], axis=1, inplace=True)\nnational_2014_TBtu = data.multiply(data.Production_growth / 1000000.0, axis='index')\nn... | <|body_start_0|>
data = pd.read_excel(mining_file, sheetname='Mining_6D_US_MMBtu', index_col='NAICS_2012')
data.loc[:, 'Other'] = data.Misc + data.Crude
data.drop(['fac_count_2012', 'val_ship_dollars', 'Misc', 'Crude'], axis=1, inplace=True)
national_2014_TBtu = data.multiply(data.Produc... | Methods for calculating count-level energy data for mining sector. | Mining | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mining:
"""Methods for calculating count-level energy data for mining sector."""
def national_data(mining_file):
"""Import 2012 Economic Census data for mining. Fuel use in MMBtu."""
<|body_0|>
def county_frac_calc(cbp_corrected):
"""Apply mining intensities by f... | stack_v2_sparse_classes_75kplus_train_070350 | 2,889 | permissive | [
{
"docstring": "Import 2012 Economic Census data for mining. Fuel use in MMBtu.",
"name": "national_data",
"signature": "def national_data(mining_file)"
},
{
"docstring": "Apply mining intensities by fuel type and 6-digit NAICS codes to corrected 2014 CBP facility counts. Does not included elect... | 3 | stack_v2_sparse_classes_30k_train_019432 | Implement the Python class `Mining` described below.
Class description:
Methods for calculating count-level energy data for mining sector.
Method signatures and docstrings:
- def national_data(mining_file): Import 2012 Economic Census data for mining. Fuel use in MMBtu.
- def county_frac_calc(cbp_corrected): Apply mi... | Implement the Python class `Mining` described below.
Class description:
Methods for calculating count-level energy data for mining sector.
Method signatures and docstrings:
- def national_data(mining_file): Import 2012 Economic Census data for mining. Fuel use in MMBtu.
- def county_frac_calc(cbp_corrected): Apply mi... | a7f9d93c73c9392dc4e26e13b36fab9146196a43 | <|skeleton|>
class Mining:
"""Methods for calculating count-level energy data for mining sector."""
def national_data(mining_file):
"""Import 2012 Economic Census data for mining. Fuel use in MMBtu."""
<|body_0|>
def county_frac_calc(cbp_corrected):
"""Apply mining intensities by f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Mining:
"""Methods for calculating count-level energy data for mining sector."""
def national_data(mining_file):
"""Import 2012 Economic Census data for mining. Fuel use in MMBtu."""
data = pd.read_excel(mining_file, sheetname='Mining_6D_US_MMBtu', index_col='NAICS_2012')
data.loc... | the_stack_v2_python_sparse | data_foundation/Calculate_Mining.py | NREL/Industry-Energy-Tool | train | 12 |
a7b6fa09182ed79244a86c8925762b58ad12de9d | [
"identity = (yield gen.Task(Identity.Query, self._client, identity_key, None))\ntry:\n yield identity.VerifyAccessToken(self._client, identity.access_token)\nexcept Exception as ex:\n logging.info('error during access token verification: %s', ex)\n raise ExpiredError(EXPIRED_EMAIL_LINK_ERROR)\nself.render(... | <|body_start_0|>
identity = (yield gen.Task(Identity.Query, self._client, identity_key, None))
try:
yield identity.VerifyAccessToken(self._client, identity.access_token)
except Exception as ex:
logging.info('error during access token verification: %s', ex)
rai... | This web request handler is invoked when a user clicks an identity verification link in an email that was triggered by a web site page. It renders a page that guides the user through the completion of the auth action. This may include confirmation of the user's password, and ends with a "well done" kind of page to noti... | VerifyIdWebHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerifyIdWebHandler:
"""This web request handler is invoked when a user clicks an identity verification link in an email that was triggered by a web site page. It renders a page that guides the user through the completion of the auth action. This may include confirmation of the user's password, an... | stack_v2_sparse_classes_75kplus_train_070351 | 34,668 | permissive | [
{
"docstring": "This handler is invoked when the user clicks a ShortURL link in a verification email that was sent to them. Returns a page that guides the user through the completion of the operation.",
"name": "_HandleGet",
"signature": "def _HandleGet(self, short_url, action, identity_key, user_name, ... | 2 | stack_v2_sparse_classes_30k_train_024227 | Implement the Python class `VerifyIdWebHandler` described below.
Class description:
This web request handler is invoked when a user clicks an identity verification link in an email that was triggered by a web site page. It renders a page that guides the user through the completion of the auth action. This may include ... | Implement the Python class `VerifyIdWebHandler` described below.
Class description:
This web request handler is invoked when a user clicks an identity verification link in an email that was triggered by a web site page. It renders a page that guides the user through the completion of the auth action. This may include ... | 992209086d01be0ef6506f325cf89b84d374f969 | <|skeleton|>
class VerifyIdWebHandler:
"""This web request handler is invoked when a user clicks an identity verification link in an email that was triggered by a web site page. It renders a page that guides the user through the completion of the auth action. This may include confirmation of the user's password, an... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VerifyIdWebHandler:
"""This web request handler is invoked when a user clicks an identity verification link in an email that was triggered by a web site page. It renders a page that guides the user through the completion of the auth action. This may include confirmation of the user's password, and ends with a... | the_stack_v2_python_sparse | backend/www/auth_viewfinder.py | xuantan/viewfinder | train | 0 |
5da3f315171c28cd9fcb65d3148badb1aebd3619 | [
"if shell_result.status != 0:\n my_logger.error('the cmd (%s) did not succeed' % self)\n return []\nlzone = []\nfor line in shell_result.stdout:\n zone = self.from_zoneadm_list_entry(line)\n lzone.append(zone)\nreturn lzone",
"zone_list_entry = output_line.split(':')\nzone_list_entry = zone_list_entry... | <|body_start_0|>
if shell_result.status != 0:
my_logger.error('the cmd (%s) did not succeed' % self)
return []
lzone = []
for line in shell_result.stdout:
zone = self.from_zoneadm_list_entry(line)
lzone.append(zone)
return lzone
<|end_body_... | CmdListZone | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CmdListZone:
def factory(self, shell_result):
"""call by Factor"""
<|body_0|>
def from_zoneadm_list_entry(output_line):
"""output_line: "1:grouper3:running:/zones/grouper3_pool/grouper3:40cc68e3-f061-e385-cac9-ec6aefc6ae3a:solaris:excl:-:none:"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_070352 | 15,426 | no_license | [
{
"docstring": "call by Factor",
"name": "factory",
"signature": "def factory(self, shell_result)"
},
{
"docstring": "output_line: \"1:grouper3:running:/zones/grouper3_pool/grouper3:40cc68e3-f061-e385-cac9-ec6aefc6ae3a:solaris:excl:-:none:",
"name": "from_zoneadm_list_entry",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_006411 | Implement the Python class `CmdListZone` described below.
Class description:
Implement the CmdListZone class.
Method signatures and docstrings:
- def factory(self, shell_result): call by Factor
- def from_zoneadm_list_entry(output_line): output_line: "1:grouper3:running:/zones/grouper3_pool/grouper3:40cc68e3-f061-e38... | Implement the Python class `CmdListZone` described below.
Class description:
Implement the CmdListZone class.
Method signatures and docstrings:
- def factory(self, shell_result): call by Factor
- def from_zoneadm_list_entry(output_line): output_line: "1:grouper3:running:/zones/grouper3_pool/grouper3:40cc68e3-f061-e38... | 583c24239214b916da42fcd8923c7e27b1e482e9 | <|skeleton|>
class CmdListZone:
def factory(self, shell_result):
"""call by Factor"""
<|body_0|>
def from_zoneadm_list_entry(output_line):
"""output_line: "1:grouper3:running:/zones/grouper3_pool/grouper3:40cc68e3-f061-e385-cac9-ec6aefc6ae3a:solaris:excl:-:none:"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CmdListZone:
def factory(self, shell_result):
"""call by Factor"""
if shell_result.status != 0:
my_logger.error('the cmd (%s) did not succeed' % self)
return []
lzone = []
for line in shell_result.stdout:
zone = self.from_zoneadm_list_entry(l... | the_stack_v2_python_sparse | libcbr/mzone.py | briner/libcbr-test | train | 0 | |
6a9d9086dff51b7616028164667ff1129866639c | [
"bucket_url = blr.storage_url\nbucket_metadata = self.gsutil_api.GetBucket(bucket_url.bucket_name, fields=['autoclass'], provider=bucket_url.scheme)\nbucket = str(bucket_url).rstrip('/')\nif bucket_metadata.autoclass:\n enabled = getattr(bucket_metadata.autoclass, 'enabled', False)\n toggle_time = getattr(buc... | <|body_start_0|>
bucket_url = blr.storage_url
bucket_metadata = self.gsutil_api.GetBucket(bucket_url.bucket_name, fields=['autoclass'], provider=bucket_url.scheme)
bucket = str(bucket_url).rstrip('/')
if bucket_metadata.autoclass:
enabled = getattr(bucket_metadata.autoclass, ... | Implements the gsutil autoclass command. | AutoclassCommand | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoclassCommand:
"""Implements the gsutil autoclass command."""
def _get_autoclass(self, blr):
"""Gets the autoclass setting for a bucket."""
<|body_0|>
def _set_autoclass(self, blr, setting_arg):
"""Turns autoclass on or off for a bucket."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_070353 | 9,099 | permissive | [
{
"docstring": "Gets the autoclass setting for a bucket.",
"name": "_get_autoclass",
"signature": "def _get_autoclass(self, blr)"
},
{
"docstring": "Turns autoclass on or off for a bucket.",
"name": "_set_autoclass",
"signature": "def _set_autoclass(self, blr, setting_arg)"
},
{
... | 4 | null | Implement the Python class `AutoclassCommand` described below.
Class description:
Implements the gsutil autoclass command.
Method signatures and docstrings:
- def _get_autoclass(self, blr): Gets the autoclass setting for a bucket.
- def _set_autoclass(self, blr, setting_arg): Turns autoclass on or off for a bucket.
-... | Implement the Python class `AutoclassCommand` described below.
Class description:
Implements the gsutil autoclass command.
Method signatures and docstrings:
- def _get_autoclass(self, blr): Gets the autoclass setting for a bucket.
- def _set_autoclass(self, blr, setting_arg): Turns autoclass on or off for a bucket.
-... | 3656d7ef1564d99e173246a6ebebab0af09e4d5b | <|skeleton|>
class AutoclassCommand:
"""Implements the gsutil autoclass command."""
def _get_autoclass(self, blr):
"""Gets the autoclass setting for a bucket."""
<|body_0|>
def _set_autoclass(self, blr, setting_arg):
"""Turns autoclass on or off for a bucket."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutoclassCommand:
"""Implements the gsutil autoclass command."""
def _get_autoclass(self, blr):
"""Gets the autoclass setting for a bucket."""
bucket_url = blr.storage_url
bucket_metadata = self.gsutil_api.GetBucket(bucket_url.bucket_name, fields=['autoclass'], provider=bucket_url... | the_stack_v2_python_sparse | gslib/commands/autoclass.py | GoogleCloudPlatform/gsutil | train | 753 |
278166612c1bee739de46c04ae58862edba89ec9 | [
"log_info('Loading ranker from %s...' % model_fname)\nwith file_stream(model_fname, 'rb', encoding=None) as fh:\n return pickle.load(fh)",
"log_info('Saving ranker to %s...' % model_fname)\nwith file_stream(model_fname, 'wb', encoding=None) as fh:\n pickle.dump(self, fh, protocol=pickle.HIGHEST_PROTOCOL)"
] | <|body_start_0|>
log_info('Loading ranker from %s...' % model_fname)
with file_stream(model_fname, 'rb', encoding=None) as fh:
return pickle.load(fh)
<|end_body_0|>
<|body_start_1|>
log_info('Saving ranker to %s...' % model_fname)
with file_stream(model_fname, 'wb', encoding... | Base class for rankers. | Ranker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ranker:
"""Base class for rankers."""
def load_from_file(model_fname):
"""Load a pre-trained model from a file."""
<|body_0|>
def save_to_file(self, model_fname):
"""Save the model to a file."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
log_i... | stack_v2_sparse_classes_75kplus_train_070354 | 30,576 | no_license | [
{
"docstring": "Load a pre-trained model from a file.",
"name": "load_from_file",
"signature": "def load_from_file(model_fname)"
},
{
"docstring": "Save the model to a file.",
"name": "save_to_file",
"signature": "def save_to_file(self, model_fname)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036452 | Implement the Python class `Ranker` described below.
Class description:
Base class for rankers.
Method signatures and docstrings:
- def load_from_file(model_fname): Load a pre-trained model from a file.
- def save_to_file(self, model_fname): Save the model to a file. | Implement the Python class `Ranker` described below.
Class description:
Base class for rankers.
Method signatures and docstrings:
- def load_from_file(model_fname): Load a pre-trained model from a file.
- def save_to_file(self, model_fname): Save the model to a file.
<|skeleton|>
class Ranker:
"""Base class for ... | fb738681da71edabe18b2b673de02b72af9791a1 | <|skeleton|>
class Ranker:
"""Base class for rankers."""
def load_from_file(model_fname):
"""Load a pre-trained model from a file."""
<|body_0|>
def save_to_file(self, model_fname):
"""Save the model to a file."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ranker:
"""Base class for rankers."""
def load_from_file(model_fname):
"""Load a pre-trained model from a file."""
log_info('Loading ranker from %s...' % model_fname)
with file_stream(model_fname, 'rb', encoding=None) as fh:
return pickle.load(fh)
def save_to_file... | the_stack_v2_python_sparse | tgen/rank.py | ProjectsUCSC/E2E-NLG-Personage | train | 4 |
9dd0949d702b04aefff79acabd2b3a03d4bfbd6b | [
"permission_classes = (IsAuthenticated,)\ncontext = {'request': request}\narticle = request.data.copy()\narticle['slug'] = ArticleSerializer().create_slug(request.data['title'])\nserializer = self.serializer_class(data=article, context=context)\nif serializer.is_valid():\n serializer.save(author=request.user)\n ... | <|body_start_0|>
permission_classes = (IsAuthenticated,)
context = {'request': request}
article = request.data.copy()
article['slug'] = ArticleSerializer().create_slug(request.data['title'])
serializer = self.serializer_class(data=article, context=context)
if serializer.i... | Article endpoints | ArticleAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleAPIView:
"""Article endpoints"""
def post(self, request):
"""POST /api/v1/articles/"""
<|body_0|>
def get(self, request):
"""GET /api/v1/articles/"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
permission_classes = (IsAuthenticated,)
... | stack_v2_sparse_classes_75kplus_train_070355 | 11,537 | permissive | [
{
"docstring": "POST /api/v1/articles/",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "GET /api/v1/articles/",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032075 | Implement the Python class `ArticleAPIView` described below.
Class description:
Article endpoints
Method signatures and docstrings:
- def post(self, request): POST /api/v1/articles/
- def get(self, request): GET /api/v1/articles/ | Implement the Python class `ArticleAPIView` described below.
Class description:
Article endpoints
Method signatures and docstrings:
- def post(self, request): POST /api/v1/articles/
- def get(self, request): GET /api/v1/articles/
<|skeleton|>
class ArticleAPIView:
"""Article endpoints"""
def post(self, requ... | 1824afd73bfba708f0e56fbd7cbb8d7521f06a1a | <|skeleton|>
class ArticleAPIView:
"""Article endpoints"""
def post(self, request):
"""POST /api/v1/articles/"""
<|body_0|>
def get(self, request):
"""GET /api/v1/articles/"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArticleAPIView:
"""Article endpoints"""
def post(self, request):
"""POST /api/v1/articles/"""
permission_classes = (IsAuthenticated,)
context = {'request': request}
article = request.data.copy()
article['slug'] = ArticleSerializer().create_slug(request.data['title'... | the_stack_v2_python_sparse | authors/apps/articles/views.py | jamesbeamie/bolt-J | train | 1 |
92872a245f28e297972a39a98b9c5bbf02c48000 | [
"self.start = start\nself.home = home\nself.seed = seed",
"w = Walker(self.start, self.home)\nwhile not w.is_at_home():\n w.move()\nreturn w.get_steps()",
"r.seed(self.seed)\nmoves_count = [self.single_walk() for _ in range(num_walks)]\nreturn moves_count"
] | <|body_start_0|>
self.start = start
self.home = home
self.seed = seed
<|end_body_0|>
<|body_start_1|>
w = Walker(self.start, self.home)
while not w.is_at_home():
w.move()
return w.get_steps()
<|end_body_1|>
<|body_start_2|>
r.seed(self.seed)
... | Simulation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulation:
def __init__(self, start, home, seed):
"""Initialise the simulation Arguments -------- start : int The walker's initial position home : int The walk ends when the walker reaches home seed : int Random number generator"""
<|body_0|>
def single_walk(self):
... | stack_v2_sparse_classes_75kplus_train_070356 | 3,229 | no_license | [
{
"docstring": "Initialise the simulation Arguments -------- start : int The walker's initial position home : int The walk ends when the walker reaches home seed : int Random number generator",
"name": "__init__",
"signature": "def __init__(self, start, home, seed)"
},
{
"docstring": "Simulate s... | 3 | stack_v2_sparse_classes_30k_train_000861 | Implement the Python class `Simulation` described below.
Class description:
Implement the Simulation class.
Method signatures and docstrings:
- def __init__(self, start, home, seed): Initialise the simulation Arguments -------- start : int The walker's initial position home : int The walk ends when the walker reaches... | Implement the Python class `Simulation` described below.
Class description:
Implement the Simulation class.
Method signatures and docstrings:
- def __init__(self, start, home, seed): Initialise the simulation Arguments -------- start : int The walker's initial position home : int The walk ends when the walker reaches... | 9bfa22c85866eeb019c2c24bc5bbfcd600fadcb5 | <|skeleton|>
class Simulation:
def __init__(self, start, home, seed):
"""Initialise the simulation Arguments -------- start : int The walker's initial position home : int The walk ends when the walker reaches home seed : int Random number generator"""
<|body_0|>
def single_walk(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Simulation:
def __init__(self, start, home, seed):
"""Initialise the simulation Arguments -------- start : int The walker's initial position home : int The walk ends when the walker reaches home seed : int Random number generator"""
self.start = start
self.home = home
self.seed... | the_stack_v2_python_sparse | src/petter_hetland_ex/ex05/walker_sim.py | pkhetland/INF200-2019-Exercises | train | 1 | |
c191ffad197cbef0e833252b837318915672e4c0 | [
"self.type = atype\nself.bq = bq\nself.score = None\nself.children = None\nself.current = cplayer\nself.target = tplayer",
"if not self.children:\n self.children = []\nself.children.append(state)"
] | <|body_start_0|>
self.type = atype
self.bq = bq
self.score = None
self.children = None
self.current = cplayer
self.target = tplayer
<|end_body_0|>
<|body_start_1|>
if not self.children:
self.children = []
self.children.append(state)
<|end_body... | A state node class. | StateNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StateNode:
"""A state node class."""
def __init__(self, atype: str, cplayer: 'Character', tplayer: 'Character', bq: 'BattleQueue') -> None:
"""Init this state node."""
<|body_0|>
def add_child(self, state: 'StateNode') -> None:
"""Add a child to this state. >>> f... | stack_v2_sparse_classes_75kplus_train_070357 | 11,109 | no_license | [
{
"docstring": "Init this state node.",
"name": "__init__",
"signature": "def __init__(self, atype: str, cplayer: 'Character', tplayer: 'Character', bq: 'BattleQueue') -> None"
},
{
"docstring": "Add a child to this state. >>> from a2_battle_queue import BattleQueue >>> from a2_characters import... | 2 | stack_v2_sparse_classes_30k_train_010407 | Implement the Python class `StateNode` described below.
Class description:
A state node class.
Method signatures and docstrings:
- def __init__(self, atype: str, cplayer: 'Character', tplayer: 'Character', bq: 'BattleQueue') -> None: Init this state node.
- def add_child(self, state: 'StateNode') -> None: Add a child... | Implement the Python class `StateNode` described below.
Class description:
A state node class.
Method signatures and docstrings:
- def __init__(self, atype: str, cplayer: 'Character', tplayer: 'Character', bq: 'BattleQueue') -> None: Init this state node.
- def add_child(self, state: 'StateNode') -> None: Add a child... | 9a777677d0b11fe8b920abf63dde4e03d2347ab0 | <|skeleton|>
class StateNode:
"""A state node class."""
def __init__(self, atype: str, cplayer: 'Character', tplayer: 'Character', bq: 'BattleQueue') -> None:
"""Init this state node."""
<|body_0|>
def add_child(self, state: 'StateNode') -> None:
"""Add a child to this state. >>> f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StateNode:
"""A state node class."""
def __init__(self, atype: str, cplayer: 'Character', tplayer: 'Character', bq: 'BattleQueue') -> None:
"""Init this state node."""
self.type = atype
self.bq = bq
self.score = None
self.children = None
self.current = cpla... | the_stack_v2_python_sparse | summer 2018/A2/a2_playstyle.py | Yangfan999/csc148-assignments | train | 3 |
bbd9d4f005ab541bcb4f70b7c5fb94ccd49eef6f | [
"self.cache = dict()\nself.link_list = DoubleLinkList()\nself.capacity = capacity\nself.count = 0",
"if key not in self.cache:\n return -1\nnode = self.cache[key]\nself.link_list.del_node(node)\nself.link_list.add(node)\nreturn node.value",
"if key not in self.cache:\n if self.count >= self.capacity:\n ... | <|body_start_0|>
self.cache = dict()
self.link_list = DoubleLinkList()
self.capacity = capacity
self.count = 0
<|end_body_0|>
<|body_start_1|>
if key not in self.cache:
return -1
node = self.cache[key]
self.link_list.del_node(node)
self.link_l... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_070358 | 2,974 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_test_000111 | 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... | e4bc30a0de7a434fd6c51f5b84a51aa650a90967 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.cache = dict()
self.link_list = DoubleLinkList()
self.capacity = capacity
self.count = 0
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.cache:
... | the_stack_v2_python_sparse | LRU_Cache.py | cocoonYh/leetcode | train | 0 | |
1694593318d43b242c72d1ee2a0d815063095efb | [
"try:\n qs = self.get_queryset()\n date_from = request.query_params.get('date_from', None)\n date_to = request.query_params.get('date_to', None)\n print(date_from, date_to)\n if date_from is not None and date_to is not None:\n data = qs.filter(birthday__range=(date_from, date_to))\n else:\n... | <|body_start_0|>
try:
qs = self.get_queryset()
date_from = request.query_params.get('date_from', None)
date_to = request.query_params.get('date_to', None)
print(date_from, date_to)
if date_from is not None and date_to is not None:
data ... | User_birthday | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User_birthday:
def list(self, request, *args, **kwargs):
"""This method will show all the records and also filter the records based on daterange using birthday coloumn. :param request: :param args: :param kwargs: :return: response with records"""
<|body_0|>
def avgage(self, ... | stack_v2_sparse_classes_75kplus_train_070359 | 3,285 | no_license | [
{
"docstring": "This method will show all the records and also filter the records based on daterange using birthday coloumn. :param request: :param args: :param kwargs: :return: response with records",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstring": "Thi... | 3 | stack_v2_sparse_classes_30k_train_053759 | Implement the Python class `User_birthday` described below.
Class description:
Implement the User_birthday class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): This method will show all the records and also filter the records based on daterange using birthday coloumn. :param request: :... | Implement the Python class `User_birthday` described below.
Class description:
Implement the User_birthday class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): This method will show all the records and also filter the records based on daterange using birthday coloumn. :param request: :... | 3d3f5bf8129508e03226168f41e12e1034f52207 | <|skeleton|>
class User_birthday:
def list(self, request, *args, **kwargs):
"""This method will show all the records and also filter the records based on daterange using birthday coloumn. :param request: :param args: :param kwargs: :return: response with records"""
<|body_0|>
def avgage(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class User_birthday:
def list(self, request, *args, **kwargs):
"""This method will show all the records and also filter the records based on daterange using birthday coloumn. :param request: :param args: :param kwargs: :return: response with records"""
try:
qs = self.get_queryset()
... | the_stack_v2_python_sparse | RosenmeisterApp/views_user_birthday.py | psurender7200/New2 | train | 0 | |
0ab0f106b694d5c9b2465dffa69ebdb879b6ba05 | [
"super(MultiHeadAttention, self).__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.linears = clones(nn.Linear(d_model, d_model, bias=True), 4)\nself.attn = None\nself.dropout = nn.Dropout(p=dropout)",
"if len(query.shape) > 3:\n batch_dim = len(query.shape) - 2\n batch = query.s... | <|body_start_0|>
super(MultiHeadAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model, bias=True), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
<|end_body_0|>
<|body_sta... | MultiHeadAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(M... | stack_v2_sparse_classes_75kplus_train_070360 | 34,916 | no_license | [
{
"docstring": "Take in model size and number of heads.",
"name": "__init__",
"signature": "def __init__(self, h, d_model, dropout=0.1)"
},
{
"docstring": "Implements Figure 2",
"name": "forward",
"signature": "def forward(self, query, key, value, mask=None)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001666 | Implement the Python class `MultiHeadAttention` described below.
Class description:
Implement the MultiHeadAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure 2 | Implement the Python class `MultiHeadAttention` described below.
Class description:
Implement the MultiHeadAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure 2
<... | 9dfbacd21a48a75f67592a8ca1f5b5d30d13fb5d | <|skeleton|>
class MultiHeadAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiHeadAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
super(MultiHeadAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model,... | the_stack_v2_python_sparse | models/utils.py | Alan-LanFeng/StarPlatinum | train | 1 | |
8ddbe18a6d3448aaf07b0ba1bfd50208fac2a1b9 | [
"if not kwargs:\n user_settings = get_account_settings(request)\nelse:\n param_handler = SettingParamsHandler(kwargs['setting'], request)\n user_settings = param_handler.get_user_settings().data\nuser_settings = UserSettingSerializer(user_settings, many=False).data\npaginated = ListPaginator(user_settings,... | <|body_start_0|>
if not kwargs:
user_settings = get_account_settings(request)
else:
param_handler = SettingParamsHandler(kwargs['setting'], request)
user_settings = param_handler.get_user_settings().data
user_settings = UserSettingSerializer(user_settings, man... | Settings views for all user settings. | AccountSettings | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountSettings:
"""Settings views for all user settings."""
def get(self, request, *args, **kwargs):
"""Gets a list of users current settings."""
<|body_0|>
def put(self, request, **kwargs):
"""Set the user cost type preference."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_070361 | 4,703 | permissive | [
{
"docstring": "Gets a list of users current settings.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Set the user cost type preference.",
"name": "put",
"signature": "def put(self, request, **kwargs)"
}
] | 2 | null | Implement the Python class `AccountSettings` described below.
Class description:
Settings views for all user settings.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Gets a list of users current settings.
- def put(self, request, **kwargs): Set the user cost type preference. | Implement the Python class `AccountSettings` described below.
Class description:
Settings views for all user settings.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Gets a list of users current settings.
- def put(self, request, **kwargs): Set the user cost type preference.
<|skeleton|... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class AccountSettings:
"""Settings views for all user settings."""
def get(self, request, *args, **kwargs):
"""Gets a list of users current settings."""
<|body_0|>
def put(self, request, **kwargs):
"""Set the user cost type preference."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountSettings:
"""Settings views for all user settings."""
def get(self, request, *args, **kwargs):
"""Gets a list of users current settings."""
if not kwargs:
user_settings = get_account_settings(request)
else:
param_handler = SettingParamsHandler(kwargs... | the_stack_v2_python_sparse | koku/api/user_settings/views.py | project-koku/koku | train | 225 |
9553cb74e1d1576a1d53f86ab705c756b8fcc9f8 | [
"groups = defaultdict(dict)\nfor key, rollout in rollouts.items():\n annID, entID = key\n assert key not in groups[annID]\n groups[annID][key] = rollout\nreturn groups",
"ret, groups = ([], Batcher.grouped(inputs))\nfor groupKey, group in groups.items():\n group = list(group.items())\n update, upda... | <|body_start_0|>
groups = defaultdict(dict)
for key, rollout in rollouts.items():
annID, entID = key
assert key not in groups[annID]
groups[annID][key] = rollout
return groups
<|end_body_0|>
<|body_start_1|>
ret, groups = ([], Batcher.grouped(inputs))... | Static experience batcher class used internally by RolloutManager | Batcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Batcher:
"""Static experience batcher class used internally by RolloutManager"""
def grouped(rollouts):
"""Group by population"""
<|body_0|>
def batched(inputs, nUpdates):
"""Batch by group key to maximum fixed size"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_070362 | 1,490 | permissive | [
{
"docstring": "Group by population",
"name": "grouped",
"signature": "def grouped(rollouts)"
},
{
"docstring": "Batch by group key to maximum fixed size",
"name": "batched",
"signature": "def batched(inputs, nUpdates)"
}
] | 2 | stack_v2_sparse_classes_30k_train_028426 | Implement the Python class `Batcher` described below.
Class description:
Static experience batcher class used internally by RolloutManager
Method signatures and docstrings:
- def grouped(rollouts): Group by population
- def batched(inputs, nUpdates): Batch by group key to maximum fixed size | Implement the Python class `Batcher` described below.
Class description:
Static experience batcher class used internally by RolloutManager
Method signatures and docstrings:
- def grouped(rollouts): Group by population
- def batched(inputs, nUpdates): Batch by group key to maximum fixed size
<|skeleton|>
class Batche... | cde2c666225d1382abb33243735f60e37113a267 | <|skeleton|>
class Batcher:
"""Static experience batcher class used internally by RolloutManager"""
def grouped(rollouts):
"""Group by population"""
<|body_0|>
def batched(inputs, nUpdates):
"""Batch by group key to maximum fixed size"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Batcher:
"""Static experience batcher class used internally by RolloutManager"""
def grouped(rollouts):
"""Group by population"""
groups = defaultdict(dict)
for key, rollout in rollouts.items():
annID, entID = key
assert key not in groups[annID]
... | the_stack_v2_python_sparse | forge/ethyr/experience/batcher.py | Justin-Yuan/neural-mmo | train | 0 |
df43ed036ddb9c7e83839db4c5693204ce819d38 | [
"super(VariationalAutoEncoder, self).__init__(encoder, decoder, name=name, **kwargs)\nif isinstance(z_sampler, torch.nn.Module):\n self.add_module('z_sampler', z_sampler)\nelse:\n self.z_sampler = z_sampler",
"y = self.encoder(x)\nz, mu, sigma = self.z_sampler(y)\nx_hat = self.decoder(z)\nreturn (x_hat, mu,... | <|body_start_0|>
super(VariationalAutoEncoder, self).__init__(encoder, decoder, name=name, **kwargs)
if isinstance(z_sampler, torch.nn.Module):
self.add_module('z_sampler', z_sampler)
else:
self.z_sampler = z_sampler
<|end_body_0|>
<|body_start_1|>
y = self.encod... | A class representing a variational autoencoder Attributes ---------- z_sampler : callable Methods ------- forward(x) returns the autoencoder output | VariationalAutoEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VariationalAutoEncoder:
"""A class representing a variational autoencoder Attributes ---------- z_sampler : callable Methods ------- forward(x) returns the autoencoder output"""
def __init__(self, encoder, decoder, z_sampler=VariationalSampler(), name='VariationalAutoEncoder', **kwargs):
... | stack_v2_sparse_classes_75kplus_train_070363 | 4,636 | permissive | [
{
"docstring": "Parameters ---------- encoder : torch.nn.Module the encoder architecture decoder : torch.nn.Module the decoder architecture z_sampler : callable (optional) the z tensor sampler (default is VariationalSampler()) name : str (optional) the name of the autoencoder (default is 'VariationalAutoEncoder... | 2 | stack_v2_sparse_classes_30k_train_031179 | Implement the Python class `VariationalAutoEncoder` described below.
Class description:
A class representing a variational autoencoder Attributes ---------- z_sampler : callable Methods ------- forward(x) returns the autoencoder output
Method signatures and docstrings:
- def __init__(self, encoder, decoder, z_sampler... | Implement the Python class `VariationalAutoEncoder` described below.
Class description:
A class representing a variational autoencoder Attributes ---------- z_sampler : callable Methods ------- forward(x) returns the autoencoder output
Method signatures and docstrings:
- def __init__(self, encoder, decoder, z_sampler... | 2615b66dd4addfd5c03d9d91a24c7da414294308 | <|skeleton|>
class VariationalAutoEncoder:
"""A class representing a variational autoencoder Attributes ---------- z_sampler : callable Methods ------- forward(x) returns the autoencoder output"""
def __init__(self, encoder, decoder, z_sampler=VariationalSampler(), name='VariationalAutoEncoder', **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VariationalAutoEncoder:
"""A class representing a variational autoencoder Attributes ---------- z_sampler : callable Methods ------- forward(x) returns the autoencoder output"""
def __init__(self, encoder, decoder, z_sampler=VariationalSampler(), name='VariationalAutoEncoder', **kwargs):
"""Param... | the_stack_v2_python_sparse | ACME/model/variational_autoencoder.py | mauriziokovacic/ACME | train | 3 |
b9b1d8b3ec2ec8c7bb72e7621bc60fea0c7d2be5 | [
"self.status_stats = {}\nself.combined_status = defaultdict(int)\nself.combined_httpver = defaultdict(int)\nself.reg = re.compile('\\n ^(?P<ip>(\\\\d{1,3}\\\\.?){4})\\n \\\\s-\\\\s-\\\\s\\n \\\\[(?P<timestamp>.*)\\\\]\\\\s\\n \"(?P<method>\\\\w+)\\\\s\\n /(?P<firstsegment>[^/?]+)(... | <|body_start_0|>
self.status_stats = {}
self.combined_status = defaultdict(int)
self.combined_httpver = defaultdict(int)
self.reg = re.compile('\n ^(?P<ip>(\\d{1,3}\\.?){4})\n \\s-\\s-\\s\n \\[(?P<timestamp>.*)\\]\\s\n "(?P<method>\\w+)\\s\n /(?P<firsts... | UrlFirstSegmentLogster | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UrlFirstSegmentLogster:
def __init__(self, option_string=None):
"""Initialize any data structures or variables needed for keeping track of the tasty bits we find in the log we are parsing."""
<|body_0|>
def parse_line(self, line):
"""This function should digest the c... | stack_v2_sparse_classes_75kplus_train_070364 | 3,552 | no_license | [
{
"docstring": "Initialize any data structures or variables needed for keeping track of the tasty bits we find in the log we are parsing.",
"name": "__init__",
"signature": "def __init__(self, option_string=None)"
},
{
"docstring": "This function should digest the contents of one line at a time,... | 3 | null | Implement the Python class `UrlFirstSegmentLogster` described below.
Class description:
Implement the UrlFirstSegmentLogster class.
Method signatures and docstrings:
- def __init__(self, option_string=None): Initialize any data structures or variables needed for keeping track of the tasty bits we find in the log we a... | Implement the Python class `UrlFirstSegmentLogster` described below.
Class description:
Implement the UrlFirstSegmentLogster class.
Method signatures and docstrings:
- def __init__(self, option_string=None): Initialize any data structures or variables needed for keeping track of the tasty bits we find in the log we a... | 75e0dd3698efa8e7cf95f6ef1348d16a299faa82 | <|skeleton|>
class UrlFirstSegmentLogster:
def __init__(self, option_string=None):
"""Initialize any data structures or variables needed for keeping track of the tasty bits we find in the log we are parsing."""
<|body_0|>
def parse_line(self, line):
"""This function should digest the c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UrlFirstSegmentLogster:
def __init__(self, option_string=None):
"""Initialize any data structures or variables needed for keeping track of the tasty bits we find in the log we are parsing."""
self.status_stats = {}
self.combined_status = defaultdict(int)
self.combined_httpver =... | the_stack_v2_python_sparse | modules/toollabs/files/toolsweblogster.py | dkuspawono/puppet | train | 0 | |
42398571c16fee0eae33629247cfd2f0a6a33334 | [
"self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]",
"direction = choice([1, -1])\ndistance = choice([0, 1, 2, 3, 4])\nstep = direction * distance\nreturn step",
"while len(self.x_values) < self.num_points:\n x_step = self.get_step()\n y_step = self.get_step()\n if x_step == 0 and ... | <|body_start_0|>
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
direction = choice([1, -1])
distance = choice([0, 1, 2, 3, 4])
step = direction * distance
return step
<|end_body_1|>
<|body_start_2|>
w... | A class to generate random walks. | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
"""A class to generate random walks."""
def __init__(self, num_points=5000):
"""Initialize attributes of a walk."""
<|body_0|>
def get_step(self):
"""Determine the direction and distance for a step."""
<|body_1|>
def fill_walk(self):
... | stack_v2_sparse_classes_75kplus_train_070365 | 1,747 | no_license | [
{
"docstring": "Initialize attributes of a walk.",
"name": "__init__",
"signature": "def __init__(self, num_points=5000)"
},
{
"docstring": "Determine the direction and distance for a step.",
"name": "get_step",
"signature": "def get_step(self)"
},
{
"docstring": "Calculate all t... | 3 | stack_v2_sparse_classes_30k_train_000753 | Implement the Python class `RandomWalk` described below.
Class description:
A class to generate random walks.
Method signatures and docstrings:
- def __init__(self, num_points=5000): Initialize attributes of a walk.
- def get_step(self): Determine the direction and distance for a step.
- def fill_walk(self): Calculat... | Implement the Python class `RandomWalk` described below.
Class description:
A class to generate random walks.
Method signatures and docstrings:
- def __init__(self, num_points=5000): Initialize attributes of a walk.
- def get_step(self): Determine the direction and distance for a step.
- def fill_walk(self): Calculat... | a9aae761e3b1953d23fc3c77f5848a217e93170d | <|skeleton|>
class RandomWalk:
"""A class to generate random walks."""
def __init__(self, num_points=5000):
"""Initialize attributes of a walk."""
<|body_0|>
def get_step(self):
"""Determine the direction and distance for a step."""
<|body_1|>
def fill_walk(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomWalk:
"""A class to generate random walks."""
def __init__(self, num_points=5000):
"""Initialize attributes of a walk."""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def get_step(self):
"""Determine the direction and distance for... | the_stack_v2_python_sparse | python_work/python编程从入门到实践/practice15-5.py | nanyangcheng/chengpeng.github.io | train | 0 |
c8e10950b2156bac71ea04adfaba9379bf416f77 | [
"self.driver.get(url)\nself.driver.pause(2)\nself.driver.execute_script('window.scrollTo(0, 900)')\nself.driver.pause(2)\nself.driver.click(Locator_Home.ncar)\nself.driver.pause(2)\ntest_ncar = self.driver.is_display(Locator_Home.ncar_label)\ntt_check.assertTrue(test_ncar, '新车签是否显示, %s' % test_ncar)",
"Newcar_exp... | <|body_start_0|>
self.driver.get(url)
self.driver.pause(2)
self.driver.execute_script('window.scrollTo(0, 900)')
self.driver.pause(2)
self.driver.click(Locator_Home.ncar)
self.driver.pause(2)
test_ncar = self.driver.is_display(Locator_Home.ncar_label)
tt_c... | Newcar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Newcar:
def test_ncar(self):
"""测试点击首页新车推荐,跳转新车是否包含新车签,@author:xulanzhong"""
<|body_0|>
def test_Newcar(self):
"""测试默认品牌名称,@author:xulanzhong"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.driver.get(url)
self.driver.pause(2)
s... | stack_v2_sparse_classes_75kplus_train_070366 | 1,950 | no_license | [
{
"docstring": "测试点击首页新车推荐,跳转新车是否包含新车签,@author:xulanzhong",
"name": "test_ncar",
"signature": "def test_ncar(self)"
},
{
"docstring": "测试默认品牌名称,@author:xulanzhong",
"name": "test_Newcar",
"signature": "def test_Newcar(self)"
}
] | 2 | null | Implement the Python class `Newcar` described below.
Class description:
Implement the Newcar class.
Method signatures and docstrings:
- def test_ncar(self): 测试点击首页新车推荐,跳转新车是否包含新车签,@author:xulanzhong
- def test_Newcar(self): 测试默认品牌名称,@author:xulanzhong | Implement the Python class `Newcar` described below.
Class description:
Implement the Newcar class.
Method signatures and docstrings:
- def test_ncar(self): 测试点击首页新车推荐,跳转新车是否包含新车签,@author:xulanzhong
- def test_Newcar(self): 测试默认品牌名称,@author:xulanzhong
<|skeleton|>
class Newcar:
def test_ncar(self):
"""测... | 204856bd33c06d25f2970eba13799db75d4fd4fe | <|skeleton|>
class Newcar:
def test_ncar(self):
"""测试点击首页新车推荐,跳转新车是否包含新车签,@author:xulanzhong"""
<|body_0|>
def test_Newcar(self):
"""测试默认品牌名称,@author:xulanzhong"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Newcar:
def test_ncar(self):
"""测试点击首页新车推荐,跳转新车是否包含新车签,@author:xulanzhong"""
self.driver.get(url)
self.driver.pause(2)
self.driver.execute_script('window.scrollTo(0, 900)')
self.driver.pause(2)
self.driver.click(Locator_Home.ncar)
self.driver.pause(2)
... | the_stack_v2_python_sparse | mc/taocheM/test_home/test_Newcar.py | boeai/mc | train | 0 | |
ddfc4e875d9cb20e04696927218a63b50f5d991d | [
"PinshCmd.PinshCmd.__init__(self, name, token_delimeter='')\nself.help_text = '<RestoreTargetField>\\ta timestamp for a restore action'\nself.cmd_owner = 0",
"cnm = system_state.cnm_connector\nmachine_name = command_line[index - 3]\npackage_name = command_line[index - 1]\nrestore_targets = cnm.get_restore_targets... | <|body_start_0|>
PinshCmd.PinshCmd.__init__(self, name, token_delimeter='')
self.help_text = '<RestoreTargetField>\ta timestamp for a restore action'
self.cmd_owner = 0
<|end_body_0|>
<|body_start_1|>
cnm = system_state.cnm_connector
machine_name = command_line[index - 3]
... | This class provides command-line completion for restore targets | RestoreTargetField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreTargetField:
"""This class provides command-line completion for restore targets"""
def __init__(self, name='RestoreTargetField'):
"""Just sets up the basics"""
<|body_0|>
def preferred_names(self, command_line, index):
"""Provide a list of names that the s... | stack_v2_sparse_classes_75kplus_train_070367 | 3,464 | no_license | [
{
"docstring": "Just sets up the basics",
"name": "__init__",
"signature": "def __init__(self, name='RestoreTargetField')"
},
{
"docstring": "Provide a list of names that the system would prefer to use, other than that which was typed in by the user. For example, 'sho mach localh' will return 'l... | 3 | null | Implement the Python class `RestoreTargetField` described below.
Class description:
This class provides command-line completion for restore targets
Method signatures and docstrings:
- def __init__(self, name='RestoreTargetField'): Just sets up the basics
- def preferred_names(self, command_line, index): Provide a lis... | Implement the Python class `RestoreTargetField` described below.
Class description:
This class provides command-line completion for restore targets
Method signatures and docstrings:
- def __init__(self, name='RestoreTargetField'): Just sets up the basics
- def preferred_names(self, command_line, index): Provide a lis... | bb528eed464a63e0f6772fa27a9d472ef3a407aa | <|skeleton|>
class RestoreTargetField:
"""This class provides command-line completion for restore targets"""
def __init__(self, name='RestoreTargetField'):
"""Just sets up the basics"""
<|body_0|>
def preferred_names(self, command_line, index):
"""Provide a list of names that the s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RestoreTargetField:
"""This class provides command-line completion for restore targets"""
def __init__(self, name='RestoreTargetField'):
"""Just sets up the basics"""
PinshCmd.PinshCmd.__init__(self, name, token_delimeter='')
self.help_text = '<RestoreTargetField>\ta timestamp for... | the_stack_v2_python_sparse | cli/lib/RestoreTargetField.py | psbanka/bombardier | train | 0 |
1732d5b7c63ff0329a0cc5299b4f3ce9cbe490c3 | [
"def serialize(root):\n if not root:\n return\n nodes.append(root.val)\n serialize(root.left)\n serialize(root.right)\nnodes = []\nserialize(root)\nreturn ' '.join(map(str, nodes))",
"def deseralize(q, minVal, maxVal):\n if not q:\n return None\n if q[0] > maxVal or q[0] < minVal:\... | <|body_start_0|>
def serialize(root):
if not root:
return
nodes.append(root.val)
serialize(root.left)
serialize(root.right)
nodes = []
serialize(root)
return ' '.join(map(str, nodes))
<|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_75kplus_train_070368 | 1,425 | 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_test_002309 | 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:... | fa02b469344cf7c82510249fba9aa59ae0cb4cc0 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def serialize(root):
if not root:
return
nodes.append(root.val)
serialize(root.left)
serialize(root.right)
nodes =... | the_stack_v2_python_sparse | SerializeandDeserializeBST.py | jiangshen95/UbuntuLeetCode | train | 0 | |
1c6b3eb5a901c2524b83e570236be272a60cdbed | [
"if user not in connector:\n uuid = str(uuid4())\n connector.setdefault(uuid, user)\n logger.debug('用户:%s,加入连接' % connector.get(uuid))\n return uuid",
"logger.debug('用户:%s,断开连接' % uuid)\ntry:\n del connector[uuid]\nexcept Exception as e:\n logger.error(e)\nelse:\n logger.success('成功清理用户:%s连接信... | <|body_start_0|>
if user not in connector:
uuid = str(uuid4())
connector.setdefault(uuid, user)
logger.debug('用户:%s,加入连接' % connector.get(uuid))
return uuid
<|end_body_0|>
<|body_start_1|>
logger.debug('用户:%s,断开连接' % uuid)
try:
del con... | 用户控制及推送 | PushCore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PushCore:
"""用户控制及推送"""
def user_connect(user):
"""pass :param user: :return:"""
<|body_0|>
def user_remove(uuid):
"""pass :param uuid: :return:"""
<|body_1|>
def trigger(message, uuid=None):
"""向已被记录的客户端推送最新内容 :param uuid: :param message: :r... | stack_v2_sparse_classes_75kplus_train_070369 | 2,077 | no_license | [
{
"docstring": "pass :param user: :return:",
"name": "user_connect",
"signature": "def user_connect(user)"
},
{
"docstring": "pass :param uuid: :return:",
"name": "user_remove",
"signature": "def user_remove(uuid)"
},
{
"docstring": "向已被记录的客户端推送最新内容 :param uuid: :param message: :... | 3 | stack_v2_sparse_classes_30k_train_001600 | Implement the Python class `PushCore` described below.
Class description:
用户控制及推送
Method signatures and docstrings:
- def user_connect(user): pass :param user: :return:
- def user_remove(uuid): pass :param uuid: :return:
- def trigger(message, uuid=None): 向已被记录的客户端推送最新内容 :param uuid: :param message: :return: | Implement the Python class `PushCore` described below.
Class description:
用户控制及推送
Method signatures and docstrings:
- def user_connect(user): pass :param user: :return:
- def user_remove(uuid): pass :param uuid: :return:
- def trigger(message, uuid=None): 向已被记录的客户端推送最新内容 :param uuid: :param message: :return:
<|skele... | 00ca5023d500a0f08389fb1b961776808cd260ab | <|skeleton|>
class PushCore:
"""用户控制及推送"""
def user_connect(user):
"""pass :param user: :return:"""
<|body_0|>
def user_remove(uuid):
"""pass :param uuid: :return:"""
<|body_1|>
def trigger(message, uuid=None):
"""向已被记录的客户端推送最新内容 :param uuid: :param message: :r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PushCore:
"""用户控制及推送"""
def user_connect(user):
"""pass :param user: :return:"""
if user not in connector:
uuid = str(uuid4())
connector.setdefault(uuid, user)
logger.debug('用户:%s,加入连接' % connector.get(uuid))
return uuid
def user_remove... | the_stack_v2_python_sparse | Core/ConnectCore.py | Clare-York/tornado_demo | train | 1 |
f187006e01fc57789e714d7778b7868779b7bbe4 | [
"context = super().get_context_data(*args, **kwargs)\nsearch_text = self.request.GET['product_search']\nproducts = self.get_products(search_text)\ncontext['suppliers'] = sort_products_by_supplier(products)\nreorders = models.Reorder.objects.filter(product__in=products).open()\ncontext['reorder_counts'] = {}\ncontex... | <|body_start_0|>
context = super().get_context_data(*args, **kwargs)
search_text = self.request.GET['product_search']
products = self.get_products(search_text)
context['suppliers'] = sort_products_by_supplier(products)
reorders = models.Reorder.objects.filter(product__in=products... | View for restock page search results. | SearchResults | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchResults:
"""View for restock page search results."""
def get_context_data(self, *args, **kwargs):
"""Return context for the template."""
<|body_0|>
def get_products(self, search_text):
"""Return products matching the search string."""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus_train_070370 | 6,889 | no_license | [
{
"docstring": "Return context for the template.",
"name": "get_context_data",
"signature": "def get_context_data(self, *args, **kwargs)"
},
{
"docstring": "Return products matching the search string.",
"name": "get_products",
"signature": "def get_products(self, search_text)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033175 | Implement the Python class `SearchResults` described below.
Class description:
View for restock page search results.
Method signatures and docstrings:
- def get_context_data(self, *args, **kwargs): Return context for the template.
- def get_products(self, search_text): Return products matching the search string. | Implement the Python class `SearchResults` described below.
Class description:
View for restock page search results.
Method signatures and docstrings:
- def get_context_data(self, *args, **kwargs): Return context for the template.
- def get_products(self, search_text): Return products matching the search string.
<|s... | ba51d4e304b1aeb296fa2fe16611c892fcdbd471 | <|skeleton|>
class SearchResults:
"""View for restock page search results."""
def get_context_data(self, *args, **kwargs):
"""Return context for the template."""
<|body_0|>
def get_products(self, search_text):
"""Return products matching the search string."""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SearchResults:
"""View for restock page search results."""
def get_context_data(self, *args, **kwargs):
"""Return context for the template."""
context = super().get_context_data(*args, **kwargs)
search_text = self.request.GET['product_search']
products = self.get_products(... | the_stack_v2_python_sparse | restock/views.py | stcstores/stcadmin | train | 0 |
a9747852ad7e169afc32b526da3bb5c13aa403a9 | [
"if not grads_splits or grads_splits[0] is None:\n return None\nif isinstance(grads_splits[0], ops.IndexedSlices):\n tensor_values, tensor_indices = zip(*[(t.values, t.indices) for t in grads_splits])\n dense_shape = grads_splits[0].dense_shape\n accumulated_values = array_ops.concat(tensor_values, axis... | <|body_start_0|>
if not grads_splits or grads_splits[0] is None:
return None
if isinstance(grads_splits[0], ops.IndexedSlices):
tensor_values, tensor_indices = zip(*[(t.values, t.indices) for t in grads_splits])
dense_shape = grads_splits[0].dense_shape
ac... | Class to apply pipeline in optimizer. | PipelinedOptimizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelinedOptimizer:
"""Class to apply pipeline in optimizer."""
def _accumulate_grads(self, grads_splits):
"""Accumulate and compute gradients. Args: grads_splits: List of `Tensor` or list of list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`.... | stack_v2_sparse_classes_75kplus_train_070371 | 8,904 | permissive | [
{
"docstring": "Accumulate and compute gradients. Args: grads_splits: List of `Tensor` or list of list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`. Returns: Accumulated gradients.",
"name": "_accumulate_grads",
"signature": "def _accumulate_grads(self, grads_sp... | 2 | stack_v2_sparse_classes_30k_train_000463 | Implement the Python class `PipelinedOptimizer` described below.
Class description:
Class to apply pipeline in optimizer.
Method signatures and docstrings:
- def _accumulate_grads(self, grads_splits): Accumulate and compute gradients. Args: grads_splits: List of `Tensor` or list of list of tensors the same size as `y... | Implement the Python class `PipelinedOptimizer` described below.
Class description:
Class to apply pipeline in optimizer.
Method signatures and docstrings:
- def _accumulate_grads(self, grads_splits): Accumulate and compute gradients. Args: grads_splits: List of `Tensor` or list of list of tensors the same size as `y... | 4486ba138515a1dbdb6f7d542d7ad23a27476524 | <|skeleton|>
class PipelinedOptimizer:
"""Class to apply pipeline in optimizer."""
def _accumulate_grads(self, grads_splits):
"""Accumulate and compute gradients. Args: grads_splits: List of `Tensor` or list of list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PipelinedOptimizer:
"""Class to apply pipeline in optimizer."""
def _accumulate_grads(self, grads_splits):
"""Accumulate and compute gradients. Args: grads_splits: List of `Tensor` or list of list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`. Returns: Acc... | the_stack_v2_python_sparse | hybridbackend/tensorflow/pipeline/pipeline_lib.py | DeepRec-AI/HybridBackend | train | 10 |
a54adec3134dec4eaa5d71497cebcc8620f57e5d | [
"base_options = _BaseOptions(model_asset_path=model_path)\noptions = AudioClassifierOptions(base_options=base_options, running_mode=_RunningMode.AUDIO_CLIPS)\nreturn cls.create_from_options(options)",
"def packets_callback(output_packets: Mapping[str, packet.Packet]):\n timestamp_ms = output_packets[_CLASSIFIC... | <|body_start_0|>
base_options = _BaseOptions(model_asset_path=model_path)
options = AudioClassifierOptions(base_options=base_options, running_mode=_RunningMode.AUDIO_CLIPS)
return cls.create_from_options(options)
<|end_body_0|>
<|body_start_1|>
def packets_callback(output_packets: Mappi... | Class that performs audio classification on audio data. This API expects a TFLite model with mandatory TFLite Model Metadata that contains the mandatory AudioProperties of the solo input audio tensor and the optional (but recommended) category labels as AssociatedFiles with type TENSOR_AXIS_LABELS per output classifica... | AudioClassifier | [
"Apache-2.0",
"dtoa"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AudioClassifier:
"""Class that performs audio classification on audio data. This API expects a TFLite model with mandatory TFLite Model Metadata that contains the mandatory AudioProperties of the solo input audio tensor and the optional (but recommended) category labels as AssociatedFiles with ty... | stack_v2_sparse_classes_75kplus_train_070372 | 14,933 | permissive | [
{
"docstring": "Creates an `AudioClassifier` object from a TensorFlow Lite model and the default `AudioClassifierOptions`. Note that the created `AudioClassifier` instance is in audio clips mode, for classifying on independent audio clips. Args: model_path: Path to the model. Returns: `AudioClassifier` object t... | 4 | stack_v2_sparse_classes_30k_train_026588 | Implement the Python class `AudioClassifier` described below.
Class description:
Class that performs audio classification on audio data. This API expects a TFLite model with mandatory TFLite Model Metadata that contains the mandatory AudioProperties of the solo input audio tensor and the optional (but recommended) cat... | Implement the Python class `AudioClassifier` described below.
Class description:
Class that performs audio classification on audio data. This API expects a TFLite model with mandatory TFLite Model Metadata that contains the mandatory AudioProperties of the solo input audio tensor and the optional (but recommended) cat... | 007824594bf1d07c7c1467df03a43886f8a4b3ad | <|skeleton|>
class AudioClassifier:
"""Class that performs audio classification on audio data. This API expects a TFLite model with mandatory TFLite Model Metadata that contains the mandatory AudioProperties of the solo input audio tensor and the optional (but recommended) category labels as AssociatedFiles with ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AudioClassifier:
"""Class that performs audio classification on audio data. This API expects a TFLite model with mandatory TFLite Model Metadata that contains the mandatory AudioProperties of the solo input audio tensor and the optional (but recommended) category labels as AssociatedFiles with type TENSOR_AXI... | the_stack_v2_python_sparse | mediapipe/tasks/python/audio/audio_classifier.py | google/mediapipe | train | 23,940 |
0c7c692536dc5e58d65661314e16b826ad56779f | [
"kw = super(AssignmentCreateView, self).get_form_kwargs()\nkw.update({'organization': self.request.user.organization})\nreturn kw",
"self.object = assignment = form.save(commit=False)\nassignment.editor = self.request.user.talenteditorprofile\nassignment.organization = self.request.user.organization\nassignment.s... | <|body_start_0|>
kw = super(AssignmentCreateView, self).get_form_kwargs()
kw.update({'organization': self.request.user.organization})
return kw
<|end_body_0|>
<|body_start_1|>
self.object = assignment = form.save(commit=False)
assignment.editor = self.request.user.talenteditorpr... | Create a new assignment. | AssignmentCreateView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssignmentCreateView:
"""Create a new assignment."""
def get_form_kwargs(self):
"""Pass current user organization to the form."""
<|body_0|>
def form_valid(self, form):
"""Save -- but first same some details."""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_070373 | 28,644 | permissive | [
{
"docstring": "Pass current user organization to the form.",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self)"
},
{
"docstring": "Save -- but first same some details.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017245 | Implement the Python class `AssignmentCreateView` described below.
Class description:
Create a new assignment.
Method signatures and docstrings:
- def get_form_kwargs(self): Pass current user organization to the form.
- def form_valid(self, form): Save -- but first same some details. | Implement the Python class `AssignmentCreateView` described below.
Class description:
Create a new assignment.
Method signatures and docstrings:
- def get_form_kwargs(self): Pass current user organization to the form.
- def form_valid(self, form): Save -- but first same some details.
<|skeleton|>
class AssignmentCre... | dc6bc79d450f7e2bdf59cfbcd306d05a736e4db9 | <|skeleton|>
class AssignmentCreateView:
"""Create a new assignment."""
def get_form_kwargs(self):
"""Pass current user organization to the form."""
<|body_0|>
def form_valid(self, form):
"""Save -- but first same some details."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AssignmentCreateView:
"""Create a new assignment."""
def get_form_kwargs(self):
"""Pass current user organization to the form."""
kw = super(AssignmentCreateView, self).get_form_kwargs()
kw.update({'organization': self.request.user.organization})
return kw
def form_va... | the_stack_v2_python_sparse | project/editorial/views/contractors.py | ProjectFacet/facet | train | 25 |
0aff25a3e11e61d402462bb89ca428320a8e3d5a | [
"self.dim = dim\nself.syms = list(sym.symbols('x y z')[0:self.dim]) + [Symbol('t')]\nself.phi = phi\nself.kappa = kappa if kappa is not None else [1] * self.dim\nself.v = v if v is not None else [0] * self.dim\nself.f = self.compute_analytical_forcing_function()\nself.lambdified_MS = self.create_lambdified_fns()",
... | <|body_start_0|>
self.dim = dim
self.syms = list(sym.symbols('x y z')[0:self.dim]) + [Symbol('t')]
self.phi = phi
self.kappa = kappa if kappa is not None else [1] * self.dim
self.v = v if v is not None else [0] * self.dim
self.f = self.compute_analytical_forcing_function(... | ADR_MS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ADR_MS:
def __init__(self, phi, dim, kappa=None, v=None, *args, **kwargs):
"""phi, kappa, v are sympy expressions for each quantity; note that by default, there is no advection, and kappa is 1, reducing to a poisson equation. @param phi sympy expression of the problem solution @param dim... | stack_v2_sparse_classes_75kplus_train_070374 | 5,123 | permissive | [
{
"docstring": "phi, kappa, v are sympy expressions for each quantity; note that by default, there is no advection, and kappa is 1, reducing to a poisson equation. @param phi sympy expression of the problem solution @param dim problem dimension -- note that this can not be inferred @param kappa list of sympy ex... | 3 | stack_v2_sparse_classes_30k_train_015408 | Implement the Python class `ADR_MS` described below.
Class description:
Implement the ADR_MS class.
Method signatures and docstrings:
- def __init__(self, phi, dim, kappa=None, v=None, *args, **kwargs): phi, kappa, v are sympy expressions for each quantity; note that by default, there is no advection, and kappa is 1,... | Implement the Python class `ADR_MS` described below.
Class description:
Implement the ADR_MS class.
Method signatures and docstrings:
- def __init__(self, phi, dim, kappa=None, v=None, *args, **kwargs): phi, kappa, v are sympy expressions for each quantity; note that by default, there is no advection, and kappa is 1,... | 9bad34d9ed7cbdd740e3a4b67f433779dd53b264 | <|skeleton|>
class ADR_MS:
def __init__(self, phi, dim, kappa=None, v=None, *args, **kwargs):
"""phi, kappa, v are sympy expressions for each quantity; note that by default, there is no advection, and kappa is 1, reducing to a poisson equation. @param phi sympy expression of the problem solution @param dim... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ADR_MS:
def __init__(self, phi, dim, kappa=None, v=None, *args, **kwargs):
"""phi, kappa, v are sympy expressions for each quantity; note that by default, there is no advection, and kappa is 1, reducing to a poisson equation. @param phi sympy expression of the problem solution @param dim problem dimen... | the_stack_v2_python_sparse | codes/src/ms/MMS.py | CorbinFoucart/FEMexperiment | train | 2 | |
add36473b73d4b6904eecc1b267a8bc77eea0395 | [
"self.parameters = ['rmse_tol', 'n_init', 'n_max', 'replications']\nif rmse_tol:\n self.rmse_tol = float(rmse_tol)\nelse:\n self.rmse_tol = float(abs_tol) / norm.ppf(1 - alpha / 2)\nself.n_init = float(n_init)\nself.n_max = float(n_max)\nself.replications = float(replications)\nself.levels_min = levels_min\ns... | <|body_start_0|>
self.parameters = ['rmse_tol', 'n_init', 'n_max', 'replications']
if rmse_tol:
self.rmse_tol = float(rmse_tol)
else:
self.rmse_tol = float(abs_tol) / norm.ppf(1 - alpha / 2)
self.n_init = float(n_init)
self.n_max = float(n_max)
sel... | Stopping criterion based on multi-level quasi-Monte Carlo. >>> mlco = MLCallOptions(Lattice(seed=7)) >>> sc = CubQMCML(mlco,abs_tol=.05) >>> solution,data = sc.integrate() >>> data MLQMCData (AccumulateData Object) solution 10.434 n_total 172032 n_level [4096. 256. 256. 256. 256. 256.] levels 6 mean_level [10.053 0.183... | CubQMCML | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CubQMCML:
"""Stopping criterion based on multi-level quasi-Monte Carlo. >>> mlco = MLCallOptions(Lattice(seed=7)) >>> sc = CubQMCML(mlco,abs_tol=.05) >>> solution,data = sc.integrate() >>> data MLQMCData (AccumulateData Object) solution 10.434 n_total 172032 n_level [4096. 256. 256. 256. 256. 256... | stack_v2_sparse_classes_75kplus_train_070375 | 6,478 | permissive | [
{
"docstring": "Args: integrand (Integrand): integrand with multi-level g method abs_tol (float): absolute tolerance alpha (float): uncertaintly level. If rmse_tol not supplied, then rmse_tol = abs_tol/norm.ppf(1-alpha/2) rmse_tol (float): root mean squared error If supplied (not None), then absolute tolerance ... | 3 | stack_v2_sparse_classes_30k_train_023684 | Implement the Python class `CubQMCML` described below.
Class description:
Stopping criterion based on multi-level quasi-Monte Carlo. >>> mlco = MLCallOptions(Lattice(seed=7)) >>> sc = CubQMCML(mlco,abs_tol=.05) >>> solution,data = sc.integrate() >>> data MLQMCData (AccumulateData Object) solution 10.434 n_total 172032... | Implement the Python class `CubQMCML` described below.
Class description:
Stopping criterion based on multi-level quasi-Monte Carlo. >>> mlco = MLCallOptions(Lattice(seed=7)) >>> sc = CubQMCML(mlco,abs_tol=.05) >>> solution,data = sc.integrate() >>> data MLQMCData (AccumulateData Object) solution 10.434 n_total 172032... | 96af0449bafe027191f9d976ceef47557b0127d4 | <|skeleton|>
class CubQMCML:
"""Stopping criterion based on multi-level quasi-Monte Carlo. >>> mlco = MLCallOptions(Lattice(seed=7)) >>> sc = CubQMCML(mlco,abs_tol=.05) >>> solution,data = sc.integrate() >>> data MLQMCData (AccumulateData Object) solution 10.434 n_total 172032 n_level [4096. 256. 256. 256. 256. 256... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CubQMCML:
"""Stopping criterion based on multi-level quasi-Monte Carlo. >>> mlco = MLCallOptions(Lattice(seed=7)) >>> sc = CubQMCML(mlco,abs_tol=.05) >>> solution,data = sc.integrate() >>> data MLQMCData (AccumulateData Object) solution 10.434 n_total 172032 n_level [4096. 256. 256. 256. 256. 256.] levels 6 m... | the_stack_v2_python_sparse | qmcpy/stopping_criterion/cub_qmc_ml.py | QMCSoftware/QMCSoftware | train | 54 |
d140bf9c95dd9bfff1c69bfbd1a6ceb9f1117d81 | [
"user = self.model(email=email)\nuser.set_password(password)\nuser.is_staff = false\nuser.is_active = True\nuser.save()\nreturn user",
"user = self.model(email=email)\nuser.set_password(password)\nuser.is_staff = True\nuser.is_active = True\nuser.save()\nreturn user"
] | <|body_start_0|>
user = self.model(email=email)
user.set_password(password)
user.is_staff = false
user.is_active = True
user.save()
return user
<|end_body_0|>
<|body_start_1|>
user = self.model(email=email)
user.set_password(password)
user.is_staf... | Manager de usuarios | UsuarioManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsuarioManager:
"""Manager de usuarios"""
def create_user(self, email, password=None):
"""Crea y persiste un usuario SIN privilegios de admin Parameters ---------- email : Correo electronico valido password : Clave Returns ------- Usuario creado"""
<|body_0|>
def create_... | stack_v2_sparse_classes_75kplus_train_070376 | 3,256 | permissive | [
{
"docstring": "Crea y persiste un usuario SIN privilegios de admin Parameters ---------- email : Correo electronico valido password : Clave Returns ------- Usuario creado",
"name": "create_user",
"signature": "def create_user(self, email, password=None)"
},
{
"docstring": "Crea y persiste un us... | 2 | stack_v2_sparse_classes_30k_train_037851 | Implement the Python class `UsuarioManager` described below.
Class description:
Manager de usuarios
Method signatures and docstrings:
- def create_user(self, email, password=None): Crea y persiste un usuario SIN privilegios de admin Parameters ---------- email : Correo electronico valido password : Clave Returns ----... | Implement the Python class `UsuarioManager` described below.
Class description:
Manager de usuarios
Method signatures and docstrings:
- def create_user(self, email, password=None): Crea y persiste un usuario SIN privilegios de admin Parameters ---------- email : Correo electronico valido password : Clave Returns ----... | f123595afc697ddfa862114a228d7351e2f8fd73 | <|skeleton|>
class UsuarioManager:
"""Manager de usuarios"""
def create_user(self, email, password=None):
"""Crea y persiste un usuario SIN privilegios de admin Parameters ---------- email : Correo electronico valido password : Clave Returns ------- Usuario creado"""
<|body_0|>
def create_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UsuarioManager:
"""Manager de usuarios"""
def create_user(self, email, password=None):
"""Crea y persiste un usuario SIN privilegios de admin Parameters ---------- email : Correo electronico valido password : Clave Returns ------- Usuario creado"""
user = self.model(email=email)
u... | the_stack_v2_python_sparse | website/policia/models.py | garnachod/ConcursoPolicia | train | 0 |
dc65257598c4d3225bf9a102626fec4a011a5389 | [
"data = np.array([0.9 * np.ones((3, 3)), 0.5 * np.ones((3, 3)), 0.1 * np.ones((3, 3))], dtype=np.float32)\nthresholds = np.array([273.0, 275.0, 277.0], dtype=np.float32)\ntime_point = dt(2015, 11, 23, 7)\nself.cube_enuk = set_up_probability_cube(data.copy(), thresholds, standard_grid_metadata='uk_ens', time=time_po... | <|body_start_0|>
data = np.array([0.9 * np.ones((3, 3)), 0.5 * np.ones((3, 3)), 0.1 * np.ones((3, 3))], dtype=np.float32)
thresholds = np.array([273.0, 275.0, 277.0], dtype=np.float32)
time_point = dt(2015, 11, 23, 7)
self.cube_enuk = set_up_probability_cube(data.copy(), thresholds, stan... | Test the _create_model_coordinates method | Test__create_model_coordinates | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__create_model_coordinates:
"""Test the _create_model_coordinates method"""
def setUp(self):
"""Set up some probability cubes from different models"""
<|body_0|>
def test_values(self):
"""Test values of model coordinates are as expected"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_070377 | 20,203 | permissive | [
{
"docstring": "Set up some probability cubes from different models",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test values of model coordinates are as expected",
"name": "test_values",
"signature": "def test_values(self)"
},
{
"docstring": "Test error if... | 4 | stack_v2_sparse_classes_30k_test_000685 | Implement the Python class `Test__create_model_coordinates` described below.
Class description:
Test the _create_model_coordinates method
Method signatures and docstrings:
- def setUp(self): Set up some probability cubes from different models
- def test_values(self): Test values of model coordinates are as expected
-... | Implement the Python class `Test__create_model_coordinates` described below.
Class description:
Test the _create_model_coordinates method
Method signatures and docstrings:
- def setUp(self): Set up some probability cubes from different models
- def test_values(self): Test values of model coordinates are as expected
-... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__create_model_coordinates:
"""Test the _create_model_coordinates method"""
def setUp(self):
"""Set up some probability cubes from different models"""
<|body_0|>
def test_values(self):
"""Test values of model coordinates are as expected"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test__create_model_coordinates:
"""Test the _create_model_coordinates method"""
def setUp(self):
"""Set up some probability cubes from different models"""
data = np.array([0.9 * np.ones((3, 3)), 0.5 * np.ones((3, 3)), 0.1 * np.ones((3, 3))], dtype=np.float32)
thresholds = np.array... | the_stack_v2_python_sparse | improver_tests/blending/weighted_blend/test_MergeCubesForWeightedBlending.py | metoppv/improver | train | 101 |
efa8c265f300f619381be34ccb5b36ef6605feb4 | [
"self.event_threshold = event_threshold\nself._label_indices = {name: i for i, name in enumerate(label_names)}\nself.perf_data = {}\nfor label in label_names:\n for bench_name, bench_iterations in benchmark_names_and_iterations:\n for i in xrange(bench_iterations):\n report = read_perf_report(l... | <|body_start_0|>
self.event_threshold = event_threshold
self._label_indices = {name: i for i, name in enumerate(label_names)}
self.perf_data = {}
for label in label_names:
for bench_name, bench_iterations in benchmark_names_and_iterations:
for i in xrange(benc... | Generates dicts from a perf table. Dicts look like: {'benchmark_name': {'perf_event_name': [LabelData]}} where LabelData is a list of perf dicts, each perf dict coming from the same label. Each perf dict looks like {'function_name': 0.10, ...} (where 0.10 is the percentage of time spent in function_name). | _PerfTable | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _PerfTable:
"""Generates dicts from a perf table. Dicts look like: {'benchmark_name': {'perf_event_name': [LabelData]}} where LabelData is a list of perf dicts, each perf dict coming from the same label. Each perf dict looks like {'function_name': 0.10, ...} (where 0.10 is the percentage of time ... | stack_v2_sparse_classes_75kplus_train_070378 | 25,882 | permissive | [
{
"docstring": "Constructor. read_perf_report is a function that takes a label name, benchmark name, and benchmark iteration, and returns a dictionary describing the perf output for that given run.",
"name": "__init__",
"signature": "def __init__(self, benchmark_names_and_iterations, label_names, read_p... | 2 | stack_v2_sparse_classes_30k_train_040569 | Implement the Python class `_PerfTable` described below.
Class description:
Generates dicts from a perf table. Dicts look like: {'benchmark_name': {'perf_event_name': [LabelData]}} where LabelData is a list of perf dicts, each perf dict coming from the same label. Each perf dict looks like {'function_name': 0.10, ...}... | Implement the Python class `_PerfTable` described below.
Class description:
Generates dicts from a perf table. Dicts look like: {'benchmark_name': {'perf_event_name': [LabelData]}} where LabelData is a list of perf dicts, each perf dict coming from the same label. Each perf dict looks like {'function_name': 0.10, ...}... | e2745b756317aac3c7a27a4c10bdfe0921a82a1c | <|skeleton|>
class _PerfTable:
"""Generates dicts from a perf table. Dicts look like: {'benchmark_name': {'perf_event_name': [LabelData]}} where LabelData is a list of perf dicts, each perf dict coming from the same label. Each perf dict looks like {'function_name': 0.10, ...} (where 0.10 is the percentage of time ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _PerfTable:
"""Generates dicts from a perf table. Dicts look like: {'benchmark_name': {'perf_event_name': [LabelData]}} where LabelData is a list of perf dicts, each perf dict coming from the same label. Each perf dict looks like {'function_name': 0.10, ...} (where 0.10 is the percentage of time spent in func... | the_stack_v2_python_sparse | app/src/main/java/com/syd/source/aosp/external/toolchain-utils/crosperf/results_report.py | lz-purple/Source | train | 4 |
173567c5f93001837948d8172ef77e09f7e207b7 | [
"runs_tup = []\nfor run in runs:\n monitor = run.get_alg_monitor()\n max_reward = max(monitor.rewards)\n runs_tup.append((run, max_reward))\nself._result = sorted(runs_tup, key=itemgetter(1), reverse=True)",
"if not hasattr(self, '_result'):\n self._result = None\nreturn self._result",
"if self.resu... | <|body_start_0|>
runs_tup = []
for run in runs:
monitor = run.get_alg_monitor()
max_reward = max(monitor.rewards)
runs_tup.append((run, max_reward))
self._result = sorted(runs_tup, key=itemgetter(1), reverse=True)
<|end_body_0|>
<|body_start_1|>
if no... | Find the best performance achieved within runs. | BestPerformance | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BestPerformance:
"""Find the best performance achieved within runs."""
def __call__(self, runs):
"""Sort content of runs by performance. This class creates a tuple with a BenchRun and its respective best performance and then stores in a descending sorted list. The results are accessi... | stack_v2_sparse_classes_75kplus_train_070379 | 4,432 | permissive | [
{
"docstring": "Sort content of runs by performance. This class creates a tuple with a BenchRun and its respective best performance and then stores in a descending sorted list. The results are accessible through the result method. Parameters ---------- runs : List of BenchRun instances May be any subset of Benc... | 3 | stack_v2_sparse_classes_30k_train_040378 | Implement the Python class `BestPerformance` described below.
Class description:
Find the best performance achieved within runs.
Method signatures and docstrings:
- def __call__(self, runs): Sort content of runs by performance. This class creates a tuple with a BenchRun and its respective best performance and then st... | Implement the Python class `BestPerformance` described below.
Class description:
Find the best performance achieved within runs.
Method signatures and docstrings:
- def __call__(self, runs): Sort content of runs by performance. This class creates a tuple with a BenchRun and its respective best performance and then st... | 8500c8dd90a2b59a91b988a3c83e529f6c69332f | <|skeleton|>
class BestPerformance:
"""Find the best performance achieved within runs."""
def __call__(self, runs):
"""Sort content of runs by performance. This class creates a tuple with a BenchRun and its respective best performance and then stores in a descending sorted list. The results are accessi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BestPerformance:
"""Find the best performance achieved within runs."""
def __call__(self, runs):
"""Sort content of runs by performance. This class creates a tuple with a BenchRun and its respective best performance and then stores in a descending sorted list. The results are accessible through t... | the_stack_v2_python_sparse | Safe-RL/Safe-RL-Benchmark/SafeRLBench/measure.py | chauncygu/Safe-Reinforcement-Learning-Baselines | train | 233 |
0ccbe8cf9e20ca38114ece312ac4aa7d55fb2611 | [
"super().__init__()\nself.embed, self.encoders, self.enc_out, self.conv_subsampling_factor = build_blocks('encoder', idim, input_layer, enc_arch, repeat_block=repeat_block, self_attn_type=self_attn_type, positional_encoding_type=positional_encoding_type, positionwise_layer_type=positionwise_layer_type, positionwise... | <|body_start_0|>
super().__init__()
self.embed, self.encoders, self.enc_out, self.conv_subsampling_factor = build_blocks('encoder', idim, input_layer, enc_arch, repeat_block=repeat_block, self_attn_type=self_attn_type, positional_encoding_type=positional_encoding_type, positionwise_layer_type=positionwi... | Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self-attention type. positional_encoding_type: Positional encoding type. positionwis... | CustomEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomEncoder:
"""Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self-attention type. positional_encoding_ty... | stack_v2_sparse_classes_75kplus_train_070380 | 4,661 | permissive | [
{
"docstring": "Construct an CustomEncoder object.",
"name": "__init__",
"signature": "def __init__(self, idim: int, enc_arch: List, input_layer: str='linear', repeat_block: int=1, self_attn_type: str='selfattn', positional_encoding_type: str='abs_pos', positionwise_layer_type: str='linear', positionwis... | 2 | stack_v2_sparse_classes_30k_val_000231 | Implement the Python class `CustomEncoder` described below.
Class description:
Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self... | Implement the Python class `CustomEncoder` described below.
Class description:
Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class CustomEncoder:
"""Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self-attention type. positional_encoding_ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomEncoder:
"""Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self-attention type. positional_encoding_type: Positiona... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transducer/custom_encoder.py | espnet/espnet | train | 7,242 |
77a9a8ae36b5a9f452fa6accaf680ac54f150a01 | [
"stk = []\nret = 0\nfor s in S:\n if s == '(':\n stk.append(0)\n else:\n cur = stk.pop()\n score = max(2 * cur, 1)\n if stk:\n stk[-1] += score\n else:\n ret += score\nreturn ret",
"ret = 0\ncur_stk = []\nfor s in S:\n if s == '(':\n cur_stk... | <|body_start_0|>
stk = []
ret = 0
for s in S:
if s == '(':
stk.append(0)
else:
cur = stk.pop()
score = max(2 * cur, 1)
if stk:
stk[-1] += score
else:
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def scoreOfParentheses(self, S: str) -> int:
"""stk Every position in the string has a depth - some number of matching parentheses surrounding it"""
<|body_0|>
def scoreOfParentheses_error(self, S: str) -> int:
"""stk"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_75kplus_train_070381 | 1,710 | no_license | [
{
"docstring": "stk Every position in the string has a depth - some number of matching parentheses surrounding it",
"name": "scoreOfParentheses",
"signature": "def scoreOfParentheses(self, S: str) -> int"
},
{
"docstring": "stk",
"name": "scoreOfParentheses_error",
"signature": "def scor... | 2 | stack_v2_sparse_classes_30k_train_006725 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def scoreOfParentheses(self, S: str) -> int: stk Every position in the string has a depth - some number of matching parentheses surrounding it
- def scoreOfParentheses_error(self... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def scoreOfParentheses(self, S: str) -> int: stk Every position in the string has a depth - some number of matching parentheses surrounding it
- def scoreOfParentheses_error(self... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def scoreOfParentheses(self, S: str) -> int:
"""stk Every position in the string has a depth - some number of matching parentheses surrounding it"""
<|body_0|>
def scoreOfParentheses_error(self, S: str) -> int:
"""stk"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def scoreOfParentheses(self, S: str) -> int:
"""stk Every position in the string has a depth - some number of matching parentheses surrounding it"""
stk = []
ret = 0
for s in S:
if s == '(':
stk.append(0)
else:
c... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/856 Score of Parentheses.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
fad122f85e9dd22a456ec50e7b0ac3ca091d6ae2 | [
"if matrix is None or not matrix:\n return\nrows = len(matrix)\ncolumns = len(matrix[0])\nself.dp = [[0 for _ in range(columns)] for _ in range(rows)]\nself.dp[0][0] = matrix[0][0]\nfor _column in range(1, columns):\n self.dp[0][_column] = self.dp[0][_column - 1] + matrix[0][_column]\nfor _row in range(1, row... | <|body_start_0|>
if matrix is None or not matrix:
return
rows = len(matrix)
columns = len(matrix[0])
self.dp = [[0 for _ in range(columns)] for _ in range(rows)]
self.dp[0][0] = matrix[0][0]
for _column in range(1, columns):
self.dp[0][_column] = s... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_070382 | 4,418 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_023444 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | 5f98270fbcd2d28d0f2abd344c3348255a12882a | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
if matrix is None or not matrix:
return
rows = len(matrix)
columns = len(matrix[0])
self.dp = [[0 for _ in range(columns)] for _ in range(rows)]
self.dp[0][0] = matrix[0][0]
... | the_stack_v2_python_sparse | 304. Range Sum Query 2D - Immutable.py | lxyshuai/leetcode | train | 0 | |
7da045574d75dc059612e12a489a9812428e9ba9 | [
"super().__init__()\nself.num_tokens = config['num_tokens']\nself.token_embedding = nn.Embedding(embedding_dim=config['emb'], num_embeddings=self.num_tokens)\nself.pos_embedding = nn.Embedding(embedding_dim=config['emb'], num_embeddings=config['seq_length'])\nself.unify_embeddings = nn.Linear(2 * config['emb'], con... | <|body_start_0|>
super().__init__()
self.num_tokens = config['num_tokens']
self.token_embedding = nn.Embedding(embedding_dim=config['emb'], num_embeddings=self.num_tokens)
self.pos_embedding = nn.Embedding(embedding_dim=config['emb'], num_embeddings=config['seq_length'])
self.uni... | Transformer for generating text (character based) | GTransformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GTransformer:
"""Transformer for generating text (character based)"""
def __init__(self, config):
"""config has emb, heads, depth, seq_length, num_tokens"""
<|body_0|>
def forward(self, x):
"""x is a batch of seq_length vectors of token indices"""
<|body_... | stack_v2_sparse_classes_75kplus_train_070383 | 1,553 | no_license | [
{
"docstring": "config has emb, heads, depth, seq_length, num_tokens",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "x is a batch of seq_length vectors of token indices",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018953 | Implement the Python class `GTransformer` described below.
Class description:
Transformer for generating text (character based)
Method signatures and docstrings:
- def __init__(self, config): config has emb, heads, depth, seq_length, num_tokens
- def forward(self, x): x is a batch of seq_length vectors of token indic... | Implement the Python class `GTransformer` described below.
Class description:
Transformer for generating text (character based)
Method signatures and docstrings:
- def __init__(self, config): config has emb, heads, depth, seq_length, num_tokens
- def forward(self, x): x is a batch of seq_length vectors of token indic... | ef253f9f465a04a3de9d859d816eb913f896fa09 | <|skeleton|>
class GTransformer:
"""Transformer for generating text (character based)"""
def __init__(self, config):
"""config has emb, heads, depth, seq_length, num_tokens"""
<|body_0|>
def forward(self, x):
"""x is a batch of seq_length vectors of token indices"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GTransformer:
"""Transformer for generating text (character based)"""
def __init__(self, config):
"""config has emb, heads, depth, seq_length, num_tokens"""
super().__init__()
self.num_tokens = config['num_tokens']
self.token_embedding = nn.Embedding(embedding_dim=config['... | the_stack_v2_python_sparse | Attention/transformers.py | gadm21/AI | train | 0 |
cdeb5720d9aee8be256f75de5756bfe887d9477c | [
"filter_params_str = self.request.query_params.get('filter')\nif filter_params_str is not None:\n return json.loads(filter_params_str.replace(\"'\", '\"'))\nreturn {}",
"sort_field = 'id'\nsort_order = 'ASC'\nsort_params_str = self.request.query_params.get('sort')\nif sort_params_str is not None:\n sort_fie... | <|body_start_0|>
filter_params_str = self.request.query_params.get('filter')
if filter_params_str is not None:
return json.loads(filter_params_str.replace("'", '"'))
return {}
<|end_body_0|>
<|body_start_1|>
sort_field = 'id'
sort_order = 'ASC'
sort_params_st... | ApiBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiBase:
def get_filter(self):
"""return filter params"""
<|body_0|>
def get_sort(self):
"""db sorting of results"""
<|body_1|>
def apply_range(self, queryset):
"""depricated: apply range params to queryset if requested"""
<|body_2|>
<|e... | stack_v2_sparse_classes_75kplus_train_070384 | 1,610 | no_license | [
{
"docstring": "return filter params",
"name": "get_filter",
"signature": "def get_filter(self)"
},
{
"docstring": "db sorting of results",
"name": "get_sort",
"signature": "def get_sort(self)"
},
{
"docstring": "depricated: apply range params to queryset if requested",
"name... | 3 | stack_v2_sparse_classes_30k_train_021249 | Implement the Python class `ApiBase` described below.
Class description:
Implement the ApiBase class.
Method signatures and docstrings:
- def get_filter(self): return filter params
- def get_sort(self): db sorting of results
- def apply_range(self, queryset): depricated: apply range params to queryset if requested | Implement the Python class `ApiBase` described below.
Class description:
Implement the ApiBase class.
Method signatures and docstrings:
- def get_filter(self): return filter params
- def get_sort(self): db sorting of results
- def apply_range(self, queryset): depricated: apply range params to queryset if requested
<... | db7b1c75183d8dd9f5e8ee6751b1c44641413c6c | <|skeleton|>
class ApiBase:
def get_filter(self):
"""return filter params"""
<|body_0|>
def get_sort(self):
"""db sorting of results"""
<|body_1|>
def apply_range(self, queryset):
"""depricated: apply range params to queryset if requested"""
<|body_2|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApiBase:
def get_filter(self):
"""return filter params"""
filter_params_str = self.request.query_params.get('filter')
if filter_params_str is not None:
return json.loads(filter_params_str.replace("'", '"'))
return {}
def get_sort(self):
"""db sorting of... | the_stack_v2_python_sparse | dashboard/dashboard/lib/api_base.py | fuxlab/datafrontend | train | 0 | |
d9c05f5000f19cead2328aa721056c99ba20dc24 | [
"Construct.__init__(self)\nif not isinstance(find, list):\n find = [find]\nself.find = find\nself.max_length = max_length",
"start = stream.tell()\nread_bytes = ''\nif self.max_length:\n read_bytes = stream.read(self.max_length)\nelse:\n read_bytes = stream.read()\ncandidates = []\nfor f in self.find:\n ... | <|body_start_0|>
Construct.__init__(self)
if not isinstance(find, list):
find = [find]
self.find = find
self.max_length = max_length
<|end_body_0|>
<|body_start_1|>
start = stream.tell()
read_bytes = ''
if self.max_length:
read_bytes = str... | Find bytes, and read past them. | Find | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Find:
"""Find bytes, and read past them."""
def __init__(self, find, max_length):
"""Initiallize."""
<|body_0|>
def _parse(self, stream, context, path):
"""Parse stream to find a given byte string."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_070385 | 9,639 | permissive | [
{
"docstring": "Initiallize.",
"name": "__init__",
"signature": "def __init__(self, find, max_length)"
},
{
"docstring": "Parse stream to find a given byte string.",
"name": "_parse",
"signature": "def _parse(self, stream, context, path)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019672 | Implement the Python class `Find` described below.
Class description:
Find bytes, and read past them.
Method signatures and docstrings:
- def __init__(self, find, max_length): Initiallize.
- def _parse(self, stream, context, path): Parse stream to find a given byte string. | Implement the Python class `Find` described below.
Class description:
Find bytes, and read past them.
Method signatures and docstrings:
- def __init__(self, find, max_length): Initiallize.
- def _parse(self, stream, context, path): Parse stream to find a given byte string.
<|skeleton|>
class Find:
"""Find bytes,... | c479f8932fa4d27b5e0c9d36f6d743ba9300d6e3 | <|skeleton|>
class Find:
"""Find bytes, and read past them."""
def __init__(self, find, max_length):
"""Initiallize."""
<|body_0|>
def _parse(self, stream, context, path):
"""Parse stream to find a given byte string."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Find:
"""Find bytes, and read past them."""
def __init__(self, find, max_length):
"""Initiallize."""
Construct.__init__(self)
if not isinstance(find, list):
find = [find]
self.find = find
self.max_length = max_length
def _parse(self, stream, contex... | the_stack_v2_python_sparse | mgz/util.py | happyleavesaoc/aoc-mgz | train | 174 |
6e9b448f0df18d1f0b98a2fc9a72ae5a9f49d647 | [
"field_dict = {}\nfor field in fields or []:\n if '.' in field:\n parent, key = field.split('.')\n if parent not in field_dict:\n field_dict[parent] = {key}\n else:\n field_dict[parent].add(key)\n else:\n field_dict[field] = ...\nreturn field_dict",
"include... | <|body_start_0|>
field_dict = {}
for field in fields or []:
if '.' in field:
parent, key = field.split('.')
if parent not in field_dict:
field_dict[parent] = {key}
else:
field_dict[parent].add(key)
... | FieldsExtension. Attributes: include: set of fields to include. exclude: set of fields to exclude. | FieldsExtension | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FieldsExtension:
"""FieldsExtension. Attributes: include: set of fields to include. exclude: set of fields to exclude."""
def _get_field_dict(fields: Optional[Set[str]]) -> Dict:
"""Pydantic include/excludes notation. Internal method to create a dictionary for advanced include or exc... | stack_v2_sparse_classes_75kplus_train_070386 | 3,530 | permissive | [
{
"docstring": "Pydantic include/excludes notation. Internal method to create a dictionary for advanced include or exclude of pydantic fields on model export Ref: https://pydantic-docs.helpmanual.io/usage/exporting_models/#advanced-include-and-exclude",
"name": "_get_field_dict",
"signature": "def _get_... | 2 | stack_v2_sparse_classes_30k_train_043934 | Implement the Python class `FieldsExtension` described below.
Class description:
FieldsExtension. Attributes: include: set of fields to include. exclude: set of fields to exclude.
Method signatures and docstrings:
- def _get_field_dict(fields: Optional[Set[str]]) -> Dict: Pydantic include/excludes notation. Internal ... | Implement the Python class `FieldsExtension` described below.
Class description:
FieldsExtension. Attributes: include: set of fields to include. exclude: set of fields to exclude.
Method signatures and docstrings:
- def _get_field_dict(fields: Optional[Set[str]]) -> Dict: Pydantic include/excludes notation. Internal ... | 3219b65a850926b622197ee6a7c3f5fb07c0d5cf | <|skeleton|>
class FieldsExtension:
"""FieldsExtension. Attributes: include: set of fields to include. exclude: set of fields to exclude."""
def _get_field_dict(fields: Optional[Set[str]]) -> Dict:
"""Pydantic include/excludes notation. Internal method to create a dictionary for advanced include or exc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FieldsExtension:
"""FieldsExtension. Attributes: include: set of fields to include. exclude: set of fields to exclude."""
def _get_field_dict(fields: Optional[Set[str]]) -> Dict:
"""Pydantic include/excludes notation. Internal method to create a dictionary for advanced include or exclude of pydan... | the_stack_v2_python_sparse | stac_fastapi/types/stac_fastapi/types/search.py | cuulee/stac-fastapi | train | 0 |
37a00cc28e9012c07ef55ced741290f62404f5c8 | [
"classes = [cls]\nparameterschema = {'type': 'object', 'additionalProperties': False}\nwhile len(classes):\n curr_cls = classes.pop(0)\n classes.extend(curr_cls.__bases__)\n if not hasattr(curr_cls, 'arguments_structure'):\n continue\n add_parameterschema_argument(parameterschema, curr_cls.argume... | <|body_start_0|>
classes = [cls]
parameterschema = {'type': 'object', 'additionalProperties': False}
while len(classes):
curr_cls = classes.pop(0)
classes.extend(curr_cls.__bases__)
if not hasattr(curr_cls, 'arguments_structure'):
continue
... | Class responsible for creating parsers for arguments from command line or json configs. The child class should define its own `arguments_structure` and from_argparse/from_json methods so that it could be instantiated from command line arguments or json config. | ArgumentsHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgumentsHandler:
"""Class responsible for creating parsers for arguments from command line or json configs. The child class should define its own `arguments_structure` and from_argparse/from_json methods so that it could be instantiated from command line arguments or json config."""
def for... | stack_v2_sparse_classes_75kplus_train_070387 | 17,901 | permissive | [
{
"docstring": "Creates parameter schema based on `arguments_structure` of class and its all parent classes. Returns ------- Dict : Parameter schema for the class.",
"name": "form_parameterschema",
"signature": "def form_parameterschema(cls) -> Dict"
},
{
"docstring": "Creates argparse parser ba... | 2 | stack_v2_sparse_classes_30k_train_022398 | Implement the Python class `ArgumentsHandler` described below.
Class description:
Class responsible for creating parsers for arguments from command line or json configs. The child class should define its own `arguments_structure` and from_argparse/from_json methods so that it could be instantiated from command line ar... | Implement the Python class `ArgumentsHandler` described below.
Class description:
Class responsible for creating parsers for arguments from command line or json configs. The child class should define its own `arguments_structure` and from_argparse/from_json methods so that it could be instantiated from command line ar... | 9ec31ca0da1ba4d3445b98c08a8de4da45a198a8 | <|skeleton|>
class ArgumentsHandler:
"""Class responsible for creating parsers for arguments from command line or json configs. The child class should define its own `arguments_structure` and from_argparse/from_json methods so that it could be instantiated from command line arguments or json config."""
def for... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArgumentsHandler:
"""Class responsible for creating parsers for arguments from command line or json configs. The child class should define its own `arguments_structure` and from_argparse/from_json methods so that it could be instantiated from command line arguments or json config."""
def form_parametersc... | the_stack_v2_python_sparse | kenning/utils/args_manager.py | antmicro/kenning | train | 55 |
006471db5d8777534dd8c077b2e709b4f0c97e55 | [
"page = requests.get('https://www.traderscockpit.com/?pageView=live-nse-advance-decline-ratio-chart')\nsoup = BeautifulSoup(page.content, 'lxml')\nlatest_updated_on = soup.find('span', {'class': 'hm-time'})\ndivs = soup.find_all('div', {'class': 'col-sm-6'})\nreturn (divs, latest_updated_on)",
"self.volume_up = f... | <|body_start_0|>
page = requests.get('https://www.traderscockpit.com/?pageView=live-nse-advance-decline-ratio-chart')
soup = BeautifulSoup(page.content, 'lxml')
latest_updated_on = soup.find('span', {'class': 'hm-time'})
divs = soup.find_all('div', {'class': 'col-sm-6'})
return (... | Get the market sentiment based on TICK, TRIN etc | MarketSentiment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MarketSentiment:
"""Get the market sentiment based on TICK, TRIN etc"""
def check_fresh_data(self):
"""Get fresh updated data scraped from the website https://www.traderscockpit.com/?pageView=live-nse-advance-decline-ratio-chart"""
<|body_0|>
def get_TRIN(self, divs):
... | stack_v2_sparse_classes_75kplus_train_070388 | 9,217 | no_license | [
{
"docstring": "Get fresh updated data scraped from the website https://www.traderscockpit.com/?pageView=live-nse-advance-decline-ratio-chart",
"name": "check_fresh_data",
"signature": "def check_fresh_data(self)"
},
{
"docstring": "Get the TRIN or so called Arm's Index of the market at any give... | 5 | null | Implement the Python class `MarketSentiment` described below.
Class description:
Get the market sentiment based on TICK, TRIN etc
Method signatures and docstrings:
- def check_fresh_data(self): Get fresh updated data scraped from the website https://www.traderscockpit.com/?pageView=live-nse-advance-decline-ratio-char... | Implement the Python class `MarketSentiment` described below.
Class description:
Get the market sentiment based on TICK, TRIN etc
Method signatures and docstrings:
- def check_fresh_data(self): Get fresh updated data scraped from the website https://www.traderscockpit.com/?pageView=live-nse-advance-decline-ratio-char... | 34311c080103a3d43106f62a3f59d2a3aeb9b856 | <|skeleton|>
class MarketSentiment:
"""Get the market sentiment based on TICK, TRIN etc"""
def check_fresh_data(self):
"""Get fresh updated data scraped from the website https://www.traderscockpit.com/?pageView=live-nse-advance-decline-ratio-chart"""
<|body_0|>
def get_TRIN(self, divs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MarketSentiment:
"""Get the market sentiment based on TICK, TRIN etc"""
def check_fresh_data(self):
"""Get fresh updated data scraped from the website https://www.traderscockpit.com/?pageView=live-nse-advance-decline-ratio-chart"""
page = requests.get('https://www.traderscockpit.com/?page... | the_stack_v2_python_sparse | helpers/intraday.py | JasmeetLuthra/NSE-Stock-Scanner | train | 0 |
34cba581901fe43c7eaf4fb14437b77d3efa79f5 | [
"self.start = start\nself.graph = graph\nself.followedRoute = []\nself.routeCost = 0",
"lowest_cost = float('Inf')\nnearest = None\nfor neighbour in neighbours:\n cost = self.graph.cost(origin, neighbour)\n if cost < lowest_cost:\n lowest_cost = cost\n nearest = neighbour\nreturn nearest",
"... | <|body_start_0|>
self.start = start
self.graph = graph
self.followedRoute = []
self.routeCost = 0
<|end_body_0|>
<|body_start_1|>
lowest_cost = float('Inf')
nearest = None
for neighbour in neighbours:
cost = self.graph.cost(origin, neighbour)
... | NearestNeighbour | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NearestNeighbour:
def __init__(self, start, graph):
"""Solution of shortest path problem using nearest neighbour algorithm"""
<|body_0|>
def nearest_neighbour(self, origin, neighbours):
"""Returns the nearest neighbour of a vertice origin"""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus_train_070389 | 2,247 | permissive | [
{
"docstring": "Solution of shortest path problem using nearest neighbour algorithm",
"name": "__init__",
"signature": "def __init__(self, start, graph)"
},
{
"docstring": "Returns the nearest neighbour of a vertice origin",
"name": "nearest_neighbour",
"signature": "def nearest_neighbou... | 3 | stack_v2_sparse_classes_30k_train_049886 | Implement the Python class `NearestNeighbour` described below.
Class description:
Implement the NearestNeighbour class.
Method signatures and docstrings:
- def __init__(self, start, graph): Solution of shortest path problem using nearest neighbour algorithm
- def nearest_neighbour(self, origin, neighbours): Returns t... | Implement the Python class `NearestNeighbour` described below.
Class description:
Implement the NearestNeighbour class.
Method signatures and docstrings:
- def __init__(self, start, graph): Solution of shortest path problem using nearest neighbour algorithm
- def nearest_neighbour(self, origin, neighbours): Returns t... | f83bcf6df4e44b230226509685e6a21eaa14479f | <|skeleton|>
class NearestNeighbour:
def __init__(self, start, graph):
"""Solution of shortest path problem using nearest neighbour algorithm"""
<|body_0|>
def nearest_neighbour(self, origin, neighbours):
"""Returns the nearest neighbour of a vertice origin"""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NearestNeighbour:
def __init__(self, start, graph):
"""Solution of shortest path problem using nearest neighbour algorithm"""
self.start = start
self.graph = graph
self.followedRoute = []
self.routeCost = 0
def nearest_neighbour(self, origin, neighbours):
"... | the_stack_v2_python_sparse | src/nearest_neighbour.py | fernandojunior/searching-techniques | train | 0 | |
8d281c9677935eb83a7de1afe43c5ee04c9d01ae | [
"self.abs_tol = abs_tol\nself.rel_tol = rel_tol\nself.n_max = n_max\nself.alpha = alpha\nself.inflate = inflate\nself.stage = 'sigma'\nself.data = MeanVarData(len(true_measure), n_init)\nallowed_distribs = ['IIDStdUniform', 'IIDStdGaussian']\nsuper().__init__(discrete_distrib, allowed_distribs)",
"if self.stage =... | <|body_start_0|>
self.abs_tol = abs_tol
self.rel_tol = rel_tol
self.n_max = n_max
self.alpha = alpha
self.inflate = inflate
self.stage = 'sigma'
self.data = MeanVarData(len(true_measure), n_init)
allowed_distribs = ['IIDStdUniform', 'IIDStdGaussian']
... | Stopping criterion based on the Central Limit Theorem (CLT) | CLT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CLT:
"""Stopping criterion based on the Central Limit Theorem (CLT)"""
def __init__(self, discrete_distrib, true_measure, inflate=1.2, alpha=0.01, abs_tol=0.01, rel_tol=0, n_init=1024, n_max=10000000000.0):
"""Args: discrete_distrib true_measure: an instance of DiscreteDistribution i... | stack_v2_sparse_classes_75kplus_train_070390 | 3,558 | no_license | [
{
"docstring": "Args: discrete_distrib true_measure: an instance of DiscreteDistribution inflate: inflation factor when estimating variance alpha: significance level for confidence interval abs_tol: absolute error tolerance rel_tol: relative error tolerance n_max: maximum number of samples",
"name": "__init... | 2 | stack_v2_sparse_classes_30k_train_049634 | Implement the Python class `CLT` described below.
Class description:
Stopping criterion based on the Central Limit Theorem (CLT)
Method signatures and docstrings:
- def __init__(self, discrete_distrib, true_measure, inflate=1.2, alpha=0.01, abs_tol=0.01, rel_tol=0, n_init=1024, n_max=10000000000.0): Args: discrete_di... | Implement the Python class `CLT` described below.
Class description:
Stopping criterion based on the Central Limit Theorem (CLT)
Method signatures and docstrings:
- def __init__(self, discrete_distrib, true_measure, inflate=1.2, alpha=0.01, abs_tol=0.01, rel_tol=0, n_init=1024, n_max=10000000000.0): Args: discrete_di... | 9f37eb67f74c4b1a4ccfb5547a2b284cb5897d37 | <|skeleton|>
class CLT:
"""Stopping criterion based on the Central Limit Theorem (CLT)"""
def __init__(self, discrete_distrib, true_measure, inflate=1.2, alpha=0.01, abs_tol=0.01, rel_tol=0, n_init=1024, n_max=10000000000.0):
"""Args: discrete_distrib true_measure: an instance of DiscreteDistribution i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CLT:
"""Stopping criterion based on the Central Limit Theorem (CLT)"""
def __init__(self, discrete_distrib, true_measure, inflate=1.2, alpha=0.01, abs_tol=0.01, rel_tol=0, n_init=1024, n_max=10000000000.0):
"""Args: discrete_distrib true_measure: an instance of DiscreteDistribution inflate: infla... | the_stack_v2_python_sparse | python_prototype/qmcpy/stopping_criterion/clt.py | jagadeesr/QMCSoftware | train | 0 |
80d4c817b15a509f9577ee94fdc236477bf53318 | [
"if title is not None:\n try:\n manager = plt.get_current_fig_manager()\n manager.window.title(title)\n except:\n pass",
"plt.show._needmain = False\nif p.filename is not None:\n fullname = p.filename + p.filename_suffix + str(topo.sim.time()) + '.' + p.file_format\n plt.savefig(n... | <|body_start_0|>
if title is not None:
try:
manager = plt.get_current_fig_manager()
manager.window.title(title)
except:
pass
<|end_body_0|>
<|body_start_1|>
plt.show._needmain = False
if p.filename is not None:
... | Parameterized command for plotting using Matplotlib/Pylab. | PylabPlotCommand | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PylabPlotCommand:
"""Parameterized command for plotting using Matplotlib/Pylab."""
def _set_windowtitle(self, title):
"""Helper function to set the title (if not None) of this PyLab plot window."""
<|body_0|>
def _generate_figure(self, p):
"""Helper function to d... | stack_v2_sparse_classes_75kplus_train_070391 | 26,497 | permissive | [
{
"docstring": "Helper function to set the title (if not None) of this PyLab plot window.",
"name": "_set_windowtitle",
"signature": "def _set_windowtitle(self, title)"
},
{
"docstring": "Helper function to display a figure on screen or save to a file. p should be a ParamOverrides instance conta... | 2 | stack_v2_sparse_classes_30k_train_020958 | Implement the Python class `PylabPlotCommand` described below.
Class description:
Parameterized command for plotting using Matplotlib/Pylab.
Method signatures and docstrings:
- def _set_windowtitle(self, title): Helper function to set the title (if not None) of this PyLab plot window.
- def _generate_figure(self, p):... | Implement the Python class `PylabPlotCommand` described below.
Class description:
Parameterized command for plotting using Matplotlib/Pylab.
Method signatures and docstrings:
- def _set_windowtitle(self, title): Helper function to set the title (if not None) of this PyLab plot window.
- def _generate_figure(self, p):... | 1e097e2df9938a6ce9f48cefbf25672cbbf9a4db | <|skeleton|>
class PylabPlotCommand:
"""Parameterized command for plotting using Matplotlib/Pylab."""
def _set_windowtitle(self, title):
"""Helper function to set the title (if not None) of this PyLab plot window."""
<|body_0|>
def _generate_figure(self, p):
"""Helper function to d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PylabPlotCommand:
"""Parameterized command for plotting using Matplotlib/Pylab."""
def _set_windowtitle(self, title):
"""Helper function to set the title (if not None) of this PyLab plot window."""
if title is not None:
try:
manager = plt.get_current_fig_manage... | the_stack_v2_python_sparse | topo/command/pylabplot.py | ioam/topographica | train | 43 |
7043e7c5adce5ae77859b989e46abb93a6bc47fe | [
"if p is not None and q is not None:\n return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\nreturn p is q",
"stack = [(p, q)]\nwhile stack:\n x, y = stack.pop()\n if x is None and y is None:\n continue\n if x is None or y is None:\n return Fals... | <|body_start_0|>
if p is not None and q is not None:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p is q
<|end_body_0|>
<|body_start_1|>
stack = [(p, q)]
while stack:
x, y = stack.pop()
if x is... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_0|>
def isSameTree2(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if p is not None... | stack_v2_sparse_classes_75kplus_train_070392 | 1,034 | no_license | [
{
"docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q)"
},
{
"docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool",
"name": "isSameTree2",
"signature": "def isSameTree2(self, p, q)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
- def isSameTree2(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
- def isSameTree2(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
<|skeleton|>
class S... | 9dd98d903e492fc509f0096115caccfd4c9fe8e8 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_0|>
def isSameTree2(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
if p is not None and q is not None:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p is q
def isSameTree2(self, p, q):
... | the_stack_v2_python_sparse | 100-Same Tree.py | zzhznx/LeetCode-Python | train | 0 | |
82e51e82ada853c5ccca92ef79246a9abd7920ba | [
"norep = [num for num, _ in groupby(nums)]\ntriples = zip(norep, norep[1:], norep[2:])\nreturn sum(((b > a) == (b > c) for a, b, c in triples)) + len(norep[:2])",
"norep = [num for num, _ in groupby(nums)]\nif len(norep) < 2:\n return len(norep)\ntriples = zip(norep, norep[1:], norep[2:])\nreturn 2 + sum((a < ... | <|body_start_0|>
norep = [num for num, _ in groupby(nums)]
triples = zip(norep, norep[1:], norep[2:])
return sum(((b > a) == (b > c) for a, b, c in triples)) + len(norep[:2])
<|end_body_0|>
<|body_start_1|>
norep = [num for num, _ in groupby(nums)]
if len(norep) < 2:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wiggleMaxLength(self, nums):
""":type nums: List[int] :rtype: int beats 44.44%"""
<|body_0|>
def wiggleMaxLength1(self, nums):
""":param nums: :return: beats 97.22%"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
norep = [num for num, ... | stack_v2_sparse_classes_75kplus_train_070393 | 704 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int beats 44.44%",
"name": "wiggleMaxLength",
"signature": "def wiggleMaxLength(self, nums)"
},
{
"docstring": ":param nums: :return: beats 97.22%",
"name": "wiggleMaxLength1",
"signature": "def wiggleMaxLength1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050343 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wiggleMaxLength(self, nums): :type nums: List[int] :rtype: int beats 44.44%
- def wiggleMaxLength1(self, nums): :param nums: :return: beats 97.22% | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wiggleMaxLength(self, nums): :type nums: List[int] :rtype: int beats 44.44%
- def wiggleMaxLength1(self, nums): :param nums: :return: beats 97.22%
<|skeleton|>
class Solutio... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def wiggleMaxLength(self, nums):
""":type nums: List[int] :rtype: int beats 44.44%"""
<|body_0|>
def wiggleMaxLength1(self, nums):
""":param nums: :return: beats 97.22%"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def wiggleMaxLength(self, nums):
""":type nums: List[int] :rtype: int beats 44.44%"""
norep = [num for num, _ in groupby(nums)]
triples = zip(norep, norep[1:], norep[2:])
return sum(((b > a) == (b > c) for a, b, c in triples)) + len(norep[:2])
def wiggleMaxLength... | the_stack_v2_python_sparse | LeetCode/376_wiggle_subsequence.py | yao23/Machine_Learning_Playground | train | 12 | |
f10a0eafdab7bb71456fa11e50d5d1886dd0f02d | [
"super(TLENETRegressor, self).__init__(model_name=model_name, model_save_directory=model_save_directory)\nself.verbose = verbose\nself._is_fitted = False\nself.nb_epochs = nb_epochs\nself.batch_size = batch_size\nself.warping_ratios = warping_ratios\nself.slice_ratio = slice_ratio\nself.callbacks = callbacks\nself.... | <|body_start_0|>
super(TLENETRegressor, self).__init__(model_name=model_name, model_save_directory=model_save_directory)
self.verbose = verbose
self._is_fitted = False
self.nb_epochs = nb_epochs
self.batch_size = batch_size
self.warping_ratios = warping_ratios
sel... | Time Le-Net (TLENET). Adapted from the implementation from Fawaz et. al https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/tlenet.py Network originally defined in: @inproceedings{le2016data, title={Data augmentation for time series classification using convolutional neural networks}, author={Le Guennec, Arthur ... | TLENETRegressor | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TLENETRegressor:
"""Time Le-Net (TLENET). Adapted from the implementation from Fawaz et. al https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/tlenet.py Network originally defined in: @inproceedings{le2016data, title={Data augmentation for time series classification using convolutional ne... | stack_v2_sparse_classes_75kplus_train_070394 | 7,265 | permissive | [
{
"docstring": ":param nb_epochs: int, the number of epochs to train the model :param batch_size: int, specifying the length of the 1D convolution window :param warping_ratios: list of floats, warping ratio for each window :param slice_ratio: float, ratio of the time series used to create a slice :param callbac... | 4 | null | Implement the Python class `TLENETRegressor` described below.
Class description:
Time Le-Net (TLENET). Adapted from the implementation from Fawaz et. al https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/tlenet.py Network originally defined in: @inproceedings{le2016data, title={Data augmentation for time serie... | Implement the Python class `TLENETRegressor` described below.
Class description:
Time Le-Net (TLENET). Adapted from the implementation from Fawaz et. al https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/tlenet.py Network originally defined in: @inproceedings{le2016data, title={Data augmentation for time serie... | b565b7499f58f43da7314f1bf26eccce94e88134 | <|skeleton|>
class TLENETRegressor:
"""Time Le-Net (TLENET). Adapted from the implementation from Fawaz et. al https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/tlenet.py Network originally defined in: @inproceedings{le2016data, title={Data augmentation for time series classification using convolutional ne... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TLENETRegressor:
"""Time Le-Net (TLENET). Adapted from the implementation from Fawaz et. al https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/tlenet.py Network originally defined in: @inproceedings{le2016data, title={Data augmentation for time series classification using convolutional neural networks... | the_stack_v2_python_sparse | sktime_dl/regression/_tlenet.py | sktime/sktime-dl | train | 586 |
ad3e822a848fb09cb289c5f4a5df3359ac7a962e | [
"if self.request.method == 'GET':\n return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsAbleToRetrieveInvitation())\nelif self.request.method == 'POST':\n return (permissions.IsAuthenticated(),)\nelif self.request.method in ('PUT', 'PATCH'):\n return (permissions.IsAuthenticated(), IsInActiveCo... | <|body_start_0|>
if self.request.method == 'GET':
return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsAbleToRetrieveInvitation())
elif self.request.method == 'POST':
return (permissions.IsAuthenticated(),)
elif self.request.method in ('PUT', 'PATCH'):
... | Invitation view set | InvitationViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvitationViewSet:
"""Invitation view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
"""List invitations"""
... | stack_v2_sparse_classes_75kplus_train_070395 | 27,778 | permissive | [
{
"docstring": "Get permissions",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Get serializer class",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "List invitations",
"name": "list",
... | 5 | stack_v2_sparse_classes_30k_train_011181 | Implement the Python class `InvitationViewSet` described below.
Class description:
Invitation view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List invitations
- def create(self, r... | Implement the Python class `InvitationViewSet` described below.
Class description:
Invitation view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List invitations
- def create(self, r... | cf429f43251ad7e77c0d9bc9fe91bb030ca8bae8 | <|skeleton|>
class InvitationViewSet:
"""Invitation view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
"""List invitations"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InvitationViewSet:
"""Invitation view set"""
def get_permissions(self):
"""Get permissions"""
if self.request.method == 'GET':
return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsAbleToRetrieveInvitation())
elif self.request.method == 'POST':
re... | the_stack_v2_python_sparse | membership/views.py | 810Teams/clubs-and-events-backend | train | 3 |
3a5739ae36764f3d0a76f7a2bb50dfa434857cae | [
"self.function_to_call = function_to_call\nself.function_to_call_name = function_to_call_name or function_to_call.__name__\nself.logger = logger",
"fulljson = json.loads(request.body)\nargs = fulljson.get('args')\nkwargs = fulljson.get('kwargs')\nkwargs['request'] = request\ntry:\n r = self.function_to_call(*a... | <|body_start_0|>
self.function_to_call = function_to_call
self.function_to_call_name = function_to_call_name or function_to_call.__name__
self.logger = logger
<|end_body_0|>
<|body_start_1|>
fulljson = json.loads(request.body)
args = fulljson.get('args')
kwargs = fulljso... | wrapper object for callable object which provides abstraction layer for packing and unpacking json (to function arguments) as well as wrapping function return object into http request, as well as encoding exceptions raised by function into approperiate http status_codes. | JsonWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonWrapper:
"""wrapper object for callable object which provides abstraction layer for packing and unpacking json (to function arguments) as well as wrapping function return object into http request, as well as encoding exceptions raised by function into approperiate http status_codes."""
d... | stack_v2_sparse_classes_75kplus_train_070396 | 13,571 | permissive | [
{
"docstring": ":param function_to_call_name: this name will be used with any error handling, defaults to function_to_call.__name__ should be used in case of using decorators on base function :type function_to_call_name: str :param function_to_call: callable object which will be wrapped by JsonWrapper :type fun... | 2 | stack_v2_sparse_classes_30k_train_047571 | Implement the Python class `JsonWrapper` described below.
Class description:
wrapper object for callable object which provides abstraction layer for packing and unpacking json (to function arguments) as well as wrapping function return object into http request, as well as encoding exceptions raised by function into ap... | Implement the Python class `JsonWrapper` described below.
Class description:
wrapper object for callable object which provides abstraction layer for packing and unpacking json (to function arguments) as well as wrapping function return object into http request, as well as encoding exceptions raised by function into ap... | 8113673fa13b6fe195cea99dedab9616aeca3ae8 | <|skeleton|>
class JsonWrapper:
"""wrapper object for callable object which provides abstraction layer for packing and unpacking json (to function arguments) as well as wrapping function return object into http request, as well as encoding exceptions raised by function into approperiate http status_codes."""
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JsonWrapper:
"""wrapper object for callable object which provides abstraction layer for packing and unpacking json (to function arguments) as well as wrapping function return object into http request, as well as encoding exceptions raised by function into approperiate http status_codes."""
def __init__(s... | the_stack_v2_python_sparse | src/common/restlib.py | jochym/cc1 | train | 0 |
4faacf1b147506b1b85297286d40e8961afeef66 | [
"self.menu = Menu(fenetre)\nself.set_fichier()\nself.set_affichage()\nself.set_aide()\nfenetre.config(menu=self.menu)",
"self.fichier = Menu(self.menu, tearoff=0)\nself.fichier.add_command(label=GT_('Quitter'))\nself.menu.add_cascade(label=GT_('Fichier'), menu=self.fichier)",
"self.affichage = Menu(self.menu, t... | <|body_start_0|>
self.menu = Menu(fenetre)
self.set_fichier()
self.set_affichage()
self.set_aide()
fenetre.config(menu=self.menu)
<|end_body_0|>
<|body_start_1|>
self.fichier = Menu(self.menu, tearoff=0)
self.fichier.add_command(label=GT_('Quitter'))
self... | Vue du menu | Menubar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Menubar:
"""Vue du menu"""
def __init__(self, fenetre):
"""Construteur du menu"""
<|body_0|>
def set_fichier(self):
"""Create the "Fichier" menu and sub-menu"""
<|body_1|>
def set_affichage(self):
"""Create the "Affichage" menu and sub-menu""... | stack_v2_sparse_classes_75kplus_train_070397 | 1,332 | no_license | [
{
"docstring": "Construteur du menu",
"name": "__init__",
"signature": "def __init__(self, fenetre)"
},
{
"docstring": "Create the \"Fichier\" menu and sub-menu",
"name": "set_fichier",
"signature": "def set_fichier(self)"
},
{
"docstring": "Create the \"Affichage\" menu and sub-... | 4 | stack_v2_sparse_classes_30k_test_001097 | Implement the Python class `Menubar` described below.
Class description:
Vue du menu
Method signatures and docstrings:
- def __init__(self, fenetre): Construteur du menu
- def set_fichier(self): Create the "Fichier" menu and sub-menu
- def set_affichage(self): Create the "Affichage" menu and sub-menu
- def set_aide(s... | Implement the Python class `Menubar` described below.
Class description:
Vue du menu
Method signatures and docstrings:
- def __init__(self, fenetre): Construteur du menu
- def set_fichier(self): Create the "Fichier" menu and sub-menu
- def set_affichage(self): Create the "Affichage" menu and sub-menu
- def set_aide(s... | 51f6d813a717aebdd3e2ecc509ba25cb76afdb6f | <|skeleton|>
class Menubar:
"""Vue du menu"""
def __init__(self, fenetre):
"""Construteur du menu"""
<|body_0|>
def set_fichier(self):
"""Create the "Fichier" menu and sub-menu"""
<|body_1|>
def set_affichage(self):
"""Create the "Affichage" menu and sub-menu""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Menubar:
"""Vue du menu"""
def __init__(self, fenetre):
"""Construteur du menu"""
self.menu = Menu(fenetre)
self.set_fichier()
self.set_affichage()
self.set_aide()
fenetre.config(menu=self.menu)
def set_fichier(self):
"""Create the "Fichier" me... | the_stack_v2_python_sparse | vue/menubar.py | 4383/WebForge | train | 0 |
9bd784154218b79b3450a95d022c262cbf1d5ff2 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('cxiao_jchew1', 'cxiao_jchew1')\nurl = 'https://data.cityofboston.gov/resource/29yf-ye7n.json'\nresponse = urllib.request.urlopen(url).read().decode('utf-8')\nr = json.loads(response)\ns = json.dumps(r, s... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('cxiao_jchew1', 'cxiao_jchew1')
url = 'https://data.cityofboston.gov/resource/29yf-ye7n.json'
response = urllib.request.urlopen(url).read().decode(... | example | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class example:
def execute(trial=False):
"""Acquire data"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Creating provenance"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
startTime = datetime.datetime.now()
... | stack_v2_sparse_classes_75kplus_train_070398 | 3,640 | no_license | [
{
"docstring": "Acquire data",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Creating provenance",
"name": "provenance",
"signature": "def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014963 | Implement the Python class `example` described below.
Class description:
Implement the example class.
Method signatures and docstrings:
- def execute(trial=False): Acquire data
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Creating provenance | Implement the Python class `example` described below.
Class description:
Implement the example class.
Method signatures and docstrings:
- def execute(trial=False): Acquire data
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Creating provenance
<|skeleton|>
class example:
def exec... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class example:
def execute(trial=False):
"""Acquire data"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Creating provenance"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class example:
def execute(trial=False):
"""Acquire data"""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('cxiao_jchew1', 'cxiao_jchew1')
url = 'https://data.cityofboston.gov/resource/29yf-ye7n.json'
... | the_stack_v2_python_sparse | cxiao_jchew1/crimerate.py | lingyigu/course-2017-spr-proj | train | 0 | |
d06099f8c3fd861fd2b32acaa6d0f90e490897d2 | [
"if not root:\n return True\n\ndef helper(tree):\n if not tree:\n return 0\n h_l = helper(tree.left)\n h_r = helper(tree.right)\n if h_l == -1 or h_r == -1 or abs(h_l - h_r) > 1:\n return -1\n return max(h_l, h_r) + 1\nreturn helper(root) >= 0",
"if not root:\n return True\nstac... | <|body_start_0|>
if not root:
return True
def helper(tree):
if not tree:
return 0
h_l = helper(tree.left)
h_r = helper(tree.right)
if h_l == -1 or h_r == -1 or abs(h_l - h_r) > 1:
return -1
return ma... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBalanced(self, root):
"""DFS (recursive)"""
<|body_0|>
def isBalanced2(self, root):
"""DFS (iteration)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return True
def helper(tree):
if not... | stack_v2_sparse_classes_75kplus_train_070399 | 1,781 | permissive | [
{
"docstring": "DFS (recursive)",
"name": "isBalanced",
"signature": "def isBalanced(self, root)"
},
{
"docstring": "DFS (iteration)",
"name": "isBalanced2",
"signature": "def isBalanced2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011952 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): DFS (recursive)
- def isBalanced2(self, root): DFS (iteration) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): DFS (recursive)
- def isBalanced2(self, root): DFS (iteration)
<|skeleton|>
class Solution:
def isBalanced(self, root):
"""DFS (recursiv... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def isBalanced(self, root):
"""DFS (recursive)"""
<|body_0|>
def isBalanced2(self, root):
"""DFS (iteration)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isBalanced(self, root):
"""DFS (recursive)"""
if not root:
return True
def helper(tree):
if not tree:
return 0
h_l = helper(tree.left)
h_r = helper(tree.right)
if h_l == -1 or h_r == -1 or abs(h_... | the_stack_v2_python_sparse | leetcode/0110_balanced_binary_tree.py | chaosWsF/Python-Practice | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.