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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f89b4c257775bcc222c8dc0203a5defabbbd1b04 | [
"if not digits:\n return []\ndigit_dict = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\ndq = collections.deque(list(digit_dict[digits[0]]))\nfor i, d in enumerate(digits[1:], 1):\n while len(dq[0]) <= i:\n s = dq.popleft()\n for c in digit_di... | <|body_start_0|>
if not digits:
return []
digit_dict = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
dq = collections.deque(list(digit_dict[digits[0]]))
for i, d in enumerate(digits[1:], 1):
while len(dq[0]) <= ... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations2(self, digits: str) -> List[str]:
"""AC: 05/09/2022 Runtime: 34 ms, faster than 76.96% Memory Usage: 13.9 MB, less than 79.68% :param digits: 0 <= digits.length <= 4 digits[i] is a digit in the range ['2', '9'] :return:"""
<|body_0|>
def lett... | stack_v2_sparse_classes_75kplus_train_072400 | 1,805 | permissive | [
{
"docstring": "AC: 05/09/2022 Runtime: 34 ms, faster than 76.96% Memory Usage: 13.9 MB, less than 79.68% :param digits: 0 <= digits.length <= 4 digits[i] is a digit in the range ['2', '9'] :return:",
"name": "letterCombinations2",
"signature": "def letterCombinations2(self, digits: str) -> List[str]"
... | 2 | stack_v2_sparse_classes_30k_train_026171 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations2(self, digits: str) -> List[str]: AC: 05/09/2022 Runtime: 34 ms, faster than 76.96% Memory Usage: 13.9 MB, less than 79.68% :param digits: 0 <= digits.leng... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations2(self, digits: str) -> List[str]: AC: 05/09/2022 Runtime: 34 ms, faster than 76.96% Memory Usage: 13.9 MB, less than 79.68% :param digits: 0 <= digits.leng... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def letterCombinations2(self, digits: str) -> List[str]:
"""AC: 05/09/2022 Runtime: 34 ms, faster than 76.96% Memory Usage: 13.9 MB, less than 79.68% :param digits: 0 <= digits.length <= 4 digits[i] is a digit in the range ['2', '9'] :return:"""
<|body_0|>
def lett... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def letterCombinations2(self, digits: str) -> List[str]:
"""AC: 05/09/2022 Runtime: 34 ms, faster than 76.96% Memory Usage: 13.9 MB, less than 79.68% :param digits: 0 <= digits.length <= 4 digits[i] is a digit in the range ['2', '9'] :return:"""
if not digits:
return []
... | the_stack_v2_python_sparse | src/17-LetterCombinationsOfAPhoneNumber.py | Jiezhi/myleetcode | train | 1 | |
c1587237eeb8861893253cf2a9b875ae26e9dfc0 | [
"user = create_user('new.user@example.org')\nuser.set_password('password')\nuser.save()\nresponse = self.client.post(reverse('ecs.users.views.request_password_reset'), {'email': 'new.user@example.org'})\nself.assertEqual(response.status_code, 200)\nmimetype, message = self.get_mimeparts(self.queue_get(0), 'text', '... | <|body_start_0|>
user = create_user('new.user@example.org')
user.set_password('password')
user.save()
response = self.client.post(reverse('ecs.users.views.request_password_reset'), {'email': 'new.user@example.org'})
self.assertEqual(response.status_code, 200)
mimetype, me... | Tests for password changing functionality High level tests for password changing and password reset functionality. | PasswordChangeTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordChangeTest:
"""Tests for password changing functionality High level tests for password changing and password reset functionality."""
def test_password_reset(self):
"""Makes sure that a user can reset his password, by following the link in a password reset mail message, settin... | stack_v2_sparse_classes_75kplus_train_072401 | 6,169 | permissive | [
{
"docstring": "Makes sure that a user can reset his password, by following the link in a password reset mail message, setting a new password and performing a test login with the newly set password.",
"name": "test_password_reset",
"signature": "def test_password_reset(self)"
},
{
"docstring": "... | 2 | null | Implement the Python class `PasswordChangeTest` described below.
Class description:
Tests for password changing functionality High level tests for password changing and password reset functionality.
Method signatures and docstrings:
- def test_password_reset(self): Makes sure that a user can reset his password, by fo... | Implement the Python class `PasswordChangeTest` described below.
Class description:
Tests for password changing functionality High level tests for password changing and password reset functionality.
Method signatures and docstrings:
- def test_password_reset(self): Makes sure that a user can reset his password, by fo... | b09f0d57572e0e320e51c8acb0229250892ecfbb | <|skeleton|>
class PasswordChangeTest:
"""Tests for password changing functionality High level tests for password changing and password reset functionality."""
def test_password_reset(self):
"""Makes sure that a user can reset his password, by following the link in a password reset mail message, settin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PasswordChangeTest:
"""Tests for password changing functionality High level tests for password changing and password reset functionality."""
def test_password_reset(self):
"""Makes sure that a user can reset his password, by following the link in a password reset mail message, setting a new passw... | the_stack_v2_python_sparse | ecs/users/tests.py | ecs-org/ecs | train | 10 |
0616caef67ad4bf6588f2c3a42f9fbe57b85fcec | [
"ret_list = [start_node.value]\nstart_node.visited = True\nedges_out = [e for e in start_node.edges if e.node_to.value != start_node.value]\nfor edge in edges_out:\n if not edge.node_to.visited:\n ret_list.extend(self.dfs_helper(edge.node_to))\nreturn ret_list",
"node = self.find_node(start_node_num)\ns... | <|body_start_0|>
ret_list = [start_node.value]
start_node.visited = True
edges_out = [e for e in start_node.edges if e.node_to.value != start_node.value]
for edge in edges_out:
if not edge.node_to.visited:
ret_list.extend(self.dfs_helper(edge.node_to))
... | Graph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Graph:
def dfs_helper(self, start_node):
"""The helper function for a recursive implementation of Depth First Search iterating through a node's edges. The output should be a list of numbers corresponding to the values of the traversed nodes. ARGUMENTS: start_node is the starting Node REQ... | stack_v2_sparse_classes_75kplus_train_072402 | 2,095 | permissive | [
{
"docstring": "The helper function for a recursive implementation of Depth First Search iterating through a node's edges. The output should be a list of numbers corresponding to the values of the traversed nodes. ARGUMENTS: start_node is the starting Node REQUIRES: self._clear_visited() to be called before MOD... | 2 | stack_v2_sparse_classes_30k_train_038607 | Implement the Python class `Graph` described below.
Class description:
Implement the Graph class.
Method signatures and docstrings:
- def dfs_helper(self, start_node): The helper function for a recursive implementation of Depth First Search iterating through a node's edges. The output should be a list of numbers corr... | Implement the Python class `Graph` described below.
Class description:
Implement the Graph class.
Method signatures and docstrings:
- def dfs_helper(self, start_node): The helper function for a recursive implementation of Depth First Search iterating through a node's edges. The output should be a list of numbers corr... | eae5ee9dd6829d52644c4df489d5514a0e0c8728 | <|skeleton|>
class Graph:
def dfs_helper(self, start_node):
"""The helper function for a recursive implementation of Depth First Search iterating through a node's edges. The output should be a list of numbers corresponding to the values of the traversed nodes. ARGUMENTS: start_node is the starting Node REQ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Graph:
def dfs_helper(self, start_node):
"""The helper function for a recursive implementation of Depth First Search iterating through a node's edges. The output should be a list of numbers corresponding to the values of the traversed nodes. ARGUMENTS: start_node is the starting Node REQUIRES: self._c... | the_stack_v2_python_sparse | udacity_tech_interview/graph_traversal_practice.py | sgrade/pytest | train | 0 | |
6bf97f809190655ad4afd0e0c9d1bce222e9ae6d | [
"word = ''\nresult = set([]) - generate_all_permutations(word)\nself.assertEqual(len(result), 0)",
"word = 'a'\nresult = set(['a']) - generate_all_permutations(word)\nself.assertEqual(len(result), 0)",
"word = 'ab'\nresult = set(['ab', 'ba']) - generate_all_permutations(word)\nself.assertEqual(len(result), 0)\n... | <|body_start_0|>
word = ''
result = set([]) - generate_all_permutations(word)
self.assertEqual(len(result), 0)
<|end_body_0|>
<|body_start_1|>
word = 'a'
result = set(['a']) - generate_all_permutations(word)
self.assertEqual(len(result), 0)
<|end_body_1|>
<|body_start_2... | Unit test for function: generate_all_permutation | GenerateAllPermutationTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenerateAllPermutationTest:
"""Unit test for function: generate_all_permutation"""
def test_generate_all_permutations_empty(self):
"""test empty input"""
<|body_0|>
def test_generate_all_permutations_1char(self):
"""test input word with 1 character"""
<|b... | stack_v2_sparse_classes_75kplus_train_072403 | 4,431 | no_license | [
{
"docstring": "test empty input",
"name": "test_generate_all_permutations_empty",
"signature": "def test_generate_all_permutations_empty(self)"
},
{
"docstring": "test input word with 1 character",
"name": "test_generate_all_permutations_1char",
"signature": "def test_generate_all_permu... | 4 | stack_v2_sparse_classes_30k_train_011485 | Implement the Python class `GenerateAllPermutationTest` described below.
Class description:
Unit test for function: generate_all_permutation
Method signatures and docstrings:
- def test_generate_all_permutations_empty(self): test empty input
- def test_generate_all_permutations_1char(self): test input word with 1 cha... | Implement the Python class `GenerateAllPermutationTest` described below.
Class description:
Unit test for function: generate_all_permutation
Method signatures and docstrings:
- def test_generate_all_permutations_empty(self): test empty input
- def test_generate_all_permutations_1char(self): test input word with 1 cha... | b27db09b577e992d5a5c28550ed796df768deb4d | <|skeleton|>
class GenerateAllPermutationTest:
"""Unit test for function: generate_all_permutation"""
def test_generate_all_permutations_empty(self):
"""test empty input"""
<|body_0|>
def test_generate_all_permutations_1char(self):
"""test input word with 1 character"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenerateAllPermutationTest:
"""Unit test for function: generate_all_permutation"""
def test_generate_all_permutations_empty(self):
"""test empty input"""
word = ''
result = set([]) - generate_all_permutations(word)
self.assertEqual(len(result), 0)
def test_generate_al... | the_stack_v2_python_sparse | codetest.py | Leo-Liu-us/Python | train | 0 |
70b2ff7ce842e4da34204a00ead7b22975a058dd | [
"try:\n obj = Client.objects.get(pk=pk)\n self.check_object_permissions(self.request, obj)\n return obj\nexcept Client.DoesNotExist:\n raise Http404",
"data = request.data\nclient = self.get_object(pk)\nserializer = UserStatusSerializer(client, data, partial=True)\nif serializer.is_valid():\n seria... | <|body_start_0|>
try:
obj = Client.objects.get(pk=pk)
self.check_object_permissions(self.request, obj)
return obj
except Client.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
data = request.data
client = self.get_object(pk)
... | Vista solo para que el admin pueda cambiar estatus a un cliente. | ChangeStatusClientView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeStatusClientView:
"""Vista solo para que el admin pueda cambiar estatus a un cliente."""
def get_object(self, pk):
"""Obtener objeto."""
<|body_0|>
def put(self, request, pk):
"""Actualizar Objeto."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_072404 | 4,645 | no_license | [
{
"docstring": "Obtener objeto.",
"name": "get_object",
"signature": "def get_object(self, pk)"
},
{
"docstring": "Actualizar Objeto.",
"name": "put",
"signature": "def put(self, request, pk)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001283 | Implement the Python class `ChangeStatusClientView` described below.
Class description:
Vista solo para que el admin pueda cambiar estatus a un cliente.
Method signatures and docstrings:
- def get_object(self, pk): Obtener objeto.
- def put(self, request, pk): Actualizar Objeto. | Implement the Python class `ChangeStatusClientView` described below.
Class description:
Vista solo para que el admin pueda cambiar estatus a un cliente.
Method signatures and docstrings:
- def get_object(self, pk): Obtener objeto.
- def put(self, request, pk): Actualizar Objeto.
<|skeleton|>
class ChangeStatusClient... | 3135a4142c38f367a152e1fc79fee8af8fca4bcc | <|skeleton|>
class ChangeStatusClientView:
"""Vista solo para que el admin pueda cambiar estatus a un cliente."""
def get_object(self, pk):
"""Obtener objeto."""
<|body_0|>
def put(self, request, pk):
"""Actualizar Objeto."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChangeStatusClientView:
"""Vista solo para que el admin pueda cambiar estatus a un cliente."""
def get_object(self, pk):
"""Obtener objeto."""
try:
obj = Client.objects.get(pk=pk)
self.check_object_permissions(self.request, obj)
return obj
excep... | the_stack_v2_python_sparse | api/views/authorization.py | darwinv/api-chat-lnk | train | 0 |
9be07ea28cd15451de63aa78237e14699e5b8704 | [
"self.window = window\nself.rho = rho\nself.corr_coef = None\nsuper().__init__()",
"super()._initialize(asset_prices, weights, resample_by)\nif not isinstance(self.window, int):\n raise ValueError('Window value must be an integer.')\nif self.window < 1:\n raise ValueError('Window value must be greater than ... | <|body_start_0|>
self.window = window
self.rho = rho
self.corr_coef = None
super().__init__()
<|end_body_0|>
<|body_start_1|>
super()._initialize(asset_prices, weights, resample_by)
if not isinstance(self.window, int):
raise ValueError('Window value must be a... | This class implements the Correlation Driven Nonparametric Learning strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S.C., & Gopalkrishnan, V. (2011). CORN: Correlation-driven nonparametric learning approach for portfolio selection. ACM TIST, 2, 21:1-21:29. <https://dl.acm.org/doi/ab... | CORN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CORN:
"""This class implements the Correlation Driven Nonparametric Learning strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S.C., & Gopalkrishnan, V. (2011). CORN: Correlation-driven nonparametric learning approach for portfolio selection. ACM TIST, 2, 21:1-2... | stack_v2_sparse_classes_75kplus_train_072405 | 6,165 | permissive | [
{
"docstring": "Initializes Correlation Driven Nonparametric Learning with the given window and rho value. :param window: (int) Number of windows to look back for similarity sets. Windows can be set to any values but typically work well in a shorter term of [1, 7]. :param rho: (float) Threshold for similarity w... | 5 | stack_v2_sparse_classes_30k_train_000500 | Implement the Python class `CORN` described below.
Class description:
This class implements the Correlation Driven Nonparametric Learning strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S.C., & Gopalkrishnan, V. (2011). CORN: Correlation-driven nonparametric learning approach for p... | Implement the Python class `CORN` described below.
Class description:
This class implements the Correlation Driven Nonparametric Learning strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S.C., & Gopalkrishnan, V. (2011). CORN: Correlation-driven nonparametric learning approach for p... | 046c47d995da08b1003bba3f9c07d5bfb73d9c1f | <|skeleton|>
class CORN:
"""This class implements the Correlation Driven Nonparametric Learning strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S.C., & Gopalkrishnan, V. (2011). CORN: Correlation-driven nonparametric learning approach for portfolio selection. ACM TIST, 2, 21:1-2... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CORN:
"""This class implements the Correlation Driven Nonparametric Learning strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S.C., & Gopalkrishnan, V. (2011). CORN: Correlation-driven nonparametric learning approach for portfolio selection. ACM TIST, 2, 21:1-21:29. <https:... | the_stack_v2_python_sparse | src/collection/portfoliolab/online_portfolio_selection/corn.py | Ta-nu-ki/dissertacao | train | 0 |
b70bf32f0bd39773c1acafbd78de998ece30f31f | [
"super(PointWiseFeedForward, self).__init__()\nself.conv1 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=1)\nself.dropout1 = torch.nn.Dropout(p=dropout_rate)\nself.relu = torch.nn.ReLU()\nself.conv2 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=1)\nself.dropout2 = torch.nn.Dropout(p=dropout_r... | <|body_start_0|>
super(PointWiseFeedForward, self).__init__()
self.conv1 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=1)
self.dropout1 = torch.nn.Dropout(p=dropout_rate)
self.relu = torch.nn.ReLU()
self.conv2 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=... | PointWise forward Module. | PointWiseFeedForward | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointWiseFeedForward:
"""PointWise forward Module."""
def __init__(self, hidden_units, dropout_rate):
"""Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate."""
<|body_0|>
def forward(self, inputs):
"""Forwa... | stack_v2_sparse_classes_75kplus_train_072406 | 9,120 | permissive | [
{
"docstring": "Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate.",
"name": "__init__",
"signature": "def __init__(self, hidden_units, dropout_rate)"
},
{
"docstring": "Forward functioin. Args: inputs ([type]): [description] Returns: [ty... | 2 | stack_v2_sparse_classes_30k_train_047294 | Implement the Python class `PointWiseFeedForward` described below.
Class description:
PointWise forward Module.
Method signatures and docstrings:
- def __init__(self, hidden_units, dropout_rate): Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate.
- def forward... | Implement the Python class `PointWiseFeedForward` described below.
Class description:
PointWise forward Module.
Method signatures and docstrings:
- def __init__(self, hidden_units, dropout_rate): Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate.
- def forward... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class PointWiseFeedForward:
"""PointWise forward Module."""
def __init__(self, hidden_units, dropout_rate):
"""Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate."""
<|body_0|>
def forward(self, inputs):
"""Forwa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PointWiseFeedForward:
"""PointWise forward Module."""
def __init__(self, hidden_units, dropout_rate):
"""Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate."""
super(PointWiseFeedForward, self).__init__()
self.conv1 = torch.... | the_stack_v2_python_sparse | beta_rec/models/sasrec.py | beta-team/beta-recsys | train | 156 |
b73ffda33853681d59c795061ab508641444e095 | [
"if len(s) == 0:\n self.answer = True\ncur_string = ''\nfor i in range(min(max_len, len(s))):\n cur_string += s[i]\n if cur_string in words:\n self.is_word_break(s[i + 1:], words, max_len)",
"if len(wordDict) == 0:\n return False\nself.answer = False\nmax_len = len(max(wordDict, key=len))\nself... | <|body_start_0|>
if len(s) == 0:
self.answer = True
cur_string = ''
for i in range(min(max_len, len(s))):
cur_string += s[i]
if cur_string in words:
self.is_word_break(s[i + 1:], words, max_len)
<|end_body_0|>
<|body_start_1|>
if len(w... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def is_word_break(self, s, words, max_len):
"""s: string words: set with words"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(s)... | stack_v2_sparse_classes_75kplus_train_072407 | 1,243 | no_license | [
{
"docstring": "s: string words: set with words",
"name": "is_word_break",
"signature": "def is_word_break(self, s, words, max_len)"
},
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007144 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_word_break(self, s, words, max_len): s: string words: set with words
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_word_break(self, s, words, max_len): s: string words: set with words
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
<|skeleton|>
... | 98f02403996e62d358d7ca589902698346ac91ec | <|skeleton|>
class Solution:
def is_word_break(self, s, words, max_len):
"""s: string words: set with words"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def is_word_break(self, s, words, max_len):
"""s: string words: set with words"""
if len(s) == 0:
self.answer = True
cur_string = ''
for i in range(min(max_len, len(s))):
cur_string += s[i]
if cur_string in words:
se... | the_stack_v2_python_sparse | onsite_solutions/139_word_break.py | owoshch/LeetCode | train | 1 | |
5acccd5684160effd45fcb697761f550939633a9 | [
"length = 0\nfor index in range(len(nums)):\n if nums[index] != val:\n nums[length] = nums[index]\n length += 1\nreturn length",
"if not nums:\n return 0\nleft, right = (0, len(nums))\nwhile left < right:\n if nums[left] == val:\n nums[left] = nums[right - 1]\n right -= 1\n ... | <|body_start_0|>
length = 0
for index in range(len(nums)):
if nums[index] != val:
nums[length] = nums[index]
length += 1
return length
<|end_body_0|>
<|body_start_1|>
if not nums:
return 0
left, right = (0, len(nums))
... | Elements | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Elements:
def remove(self, nums: List[int], val: int) -> int:
"""Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param nums: :param val: :return:"""
<|body_0|>
def remove_(self, nums: List[int], val: int) -> int:
"""Approach: Two Pointers when el... | stack_v2_sparse_classes_75kplus_train_072408 | 1,179 | no_license | [
{
"docstring": "Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param nums: :param val: :return:",
"name": "remove",
"signature": "def remove(self, nums: List[int], val: int) -> int"
},
{
"docstring": "Approach: Two Pointers when elements to be removed are rare. :param nums:... | 2 | stack_v2_sparse_classes_30k_train_020131 | Implement the Python class `Elements` described below.
Class description:
Implement the Elements class.
Method signatures and docstrings:
- def remove(self, nums: List[int], val: int) -> int: Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param nums: :param val: :return:
- def remove_(self, nums... | Implement the Python class `Elements` described below.
Class description:
Implement the Elements class.
Method signatures and docstrings:
- def remove(self, nums: List[int], val: int) -> int: Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param nums: :param val: :return:
- def remove_(self, nums... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Elements:
def remove(self, nums: List[int], val: int) -> int:
"""Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param nums: :param val: :return:"""
<|body_0|>
def remove_(self, nums: List[int], val: int) -> int:
"""Approach: Two Pointers when el... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Elements:
def remove(self, nums: List[int], val: int) -> int:
"""Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param nums: :param val: :return:"""
length = 0
for index in range(len(nums)):
if nums[index] != val:
nums[length] = nums[ind... | the_stack_v2_python_sparse | revisited/arrays/remove_elements.py | Shiv2157k/leet_code | train | 1 | |
e5ed1f32a3a24947fb6b217cb7289e597f594060 | [
"super().__init__()\nif not tags:\n self._tags = [ComputeTag, UncomputeTag]\nelif isinstance(tags, list):\n self._tags = tags\nelse:\n raise TypeError(f'tags should be a list! Got: {tags}')",
"for cmd in command_list:\n for tag in self._tags:\n cmd.tags = [t for t in cmd.tags if not isinstance(... | <|body_start_0|>
super().__init__()
if not tags:
self._tags = [ComputeTag, UncomputeTag]
elif isinstance(tags, list):
self._tags = tags
else:
raise TypeError(f'tags should be a list! Got: {tags}')
<|end_body_0|>
<|body_start_1|>
for cmd in com... | Compiler engine that remove temporary command tags. TagRemover is a compiler engine which removes temporary command tags (see the tag classes such as LoopTag in projectq.meta._loop). Removing tags is important (after having handled them if necessary) in order to enable optimizations across meta-function boundaries (com... | TagRemover | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagRemover:
"""Compiler engine that remove temporary command tags. TagRemover is a compiler engine which removes temporary command tags (see the tag classes such as LoopTag in projectq.meta._loop). Removing tags is important (after having handled them if necessary) in order to enable optimization... | stack_v2_sparse_classes_75kplus_train_072409 | 2,467 | permissive | [
{
"docstring": "Initialize a TagRemover object. Args: tags: A list of meta tag classes (e.g., [ComputeTag, UncomputeTag]) denoting the tags to remove",
"name": "__init__",
"signature": "def __init__(self, tags=None)"
},
{
"docstring": "Receive a list of commands. Receive a list of commands from ... | 2 | null | Implement the Python class `TagRemover` described below.
Class description:
Compiler engine that remove temporary command tags. TagRemover is a compiler engine which removes temporary command tags (see the tag classes such as LoopTag in projectq.meta._loop). Removing tags is important (after having handled them if nec... | Implement the Python class `TagRemover` described below.
Class description:
Compiler engine that remove temporary command tags. TagRemover is a compiler engine which removes temporary command tags (see the tag classes such as LoopTag in projectq.meta._loop). Removing tags is important (after having handled them if nec... | 67c660ca18725d23ab0b261a45e34873b6a58d03 | <|skeleton|>
class TagRemover:
"""Compiler engine that remove temporary command tags. TagRemover is a compiler engine which removes temporary command tags (see the tag classes such as LoopTag in projectq.meta._loop). Removing tags is important (after having handled them if necessary) in order to enable optimization... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TagRemover:
"""Compiler engine that remove temporary command tags. TagRemover is a compiler engine which removes temporary command tags (see the tag classes such as LoopTag in projectq.meta._loop). Removing tags is important (after having handled them if necessary) in order to enable optimizations across meta... | the_stack_v2_python_sparse | projectq/cengines/_tagremover.py | ProjectQ-Framework/ProjectQ | train | 886 |
bc6978c0db65919055b92d6c2f144093e4d7d600 | [
"errors = []\nif _Utils.validate_username(user_name) is False:\n errors.append('BadUserName')\nif _Utils.validate_email(email_id) is False:\n errors.append('BadEmailID')\nif _Utils.validate_password(password) is False:\n errors.append('ShortPassword')\nif _Utils.user_exists(user_name):\n errors.append('... | <|body_start_0|>
errors = []
if _Utils.validate_username(user_name) is False:
errors.append('BadUserName')
if _Utils.validate_email(email_id) is False:
errors.append('BadEmailID')
if _Utils.validate_password(password) is False:
errors.append('ShortPass... | Leverages user management functions. | Manage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Manage:
"""Leverages user management functions."""
def add(user_name, password, confirm_password, email_id):
"""Adds the User into Database."""
<|body_0|>
def delete(user_name):
"""Deletes the User from Database."""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_072410 | 12,328 | no_license | [
{
"docstring": "Adds the User into Database.",
"name": "add",
"signature": "def add(user_name, password, confirm_password, email_id)"
},
{
"docstring": "Deletes the User from Database.",
"name": "delete",
"signature": "def delete(user_name)"
}
] | 2 | null | Implement the Python class `Manage` described below.
Class description:
Leverages user management functions.
Method signatures and docstrings:
- def add(user_name, password, confirm_password, email_id): Adds the User into Database.
- def delete(user_name): Deletes the User from Database. | Implement the Python class `Manage` described below.
Class description:
Leverages user management functions.
Method signatures and docstrings:
- def add(user_name, password, confirm_password, email_id): Adds the User into Database.
- def delete(user_name): Deletes the User from Database.
<|skeleton|>
class Manage:
... | 0d0e8f07d8dcbb94da8b28b1f321538d6150710d | <|skeleton|>
class Manage:
"""Leverages user management functions."""
def add(user_name, password, confirm_password, email_id):
"""Adds the User into Database."""
<|body_0|>
def delete(user_name):
"""Deletes the User from Database."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Manage:
"""Leverages user management functions."""
def add(user_name, password, confirm_password, email_id):
"""Adds the User into Database."""
errors = []
if _Utils.validate_username(user_name) is False:
errors.append('BadUserName')
if _Utils.validate_email(em... | the_stack_v2_python_sparse | deprecated/App/user/model.py | madhulikamukherjee/survaider-app | train | 1 |
d1f2df7098596232a0f05e2aed5ddd3027b94ccc | [
"if not root:\n return 'X'\nleft = self.serialize(root.left)\nright = self.serialize(root.right)\nreturn str(root.val) + ',' + left + ',' + right",
"data_lst = data.split(',')\nroot = self.build_tree(data_lst)\nreturn root",
"root_val = data_lst.pop(0)\nif root_val == 'X':\n return None\nroot = TreeNode(r... | <|body_start_0|>
if not root:
return 'X'
left = self.serialize(root.left)
right = self.serialize(root.right)
return str(root.val) + ',' + left + ',' + right
<|end_body_0|>
<|body_start_1|>
data_lst = data.split(',')
root = self.build_tree(data_lst)
re... | 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|>
def build_tree(self, ... | stack_v2_sparse_classes_75kplus_train_072411 | 1,247 | 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... | 3 | stack_v2_sparse_classes_30k_train_051498 | 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:... | a75310a96d2b165b15d5ee10ec409a17cdc880ba | <|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|>
def build_tree(self, ... | 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"""
if not root:
return 'X'
left = self.serialize(root.left)
right = self.serialize(root.right)
return str(root.val) + ',' + left + ',' + right
def d... | the_stack_v2_python_sparse | leetcode/tree/code/sz.py | skyxyz-lang/CS_Note | train | 0 | |
e9bea720caf1317e2a4e5bc4a514a1a6e8f83415 | [
"if general_md is None:\n general_md = metadata_info.GeneralMd(name=_MODEL_NAME, description=_MODEL_DESCRIPTION)\nif input_md is None:\n input_md = metadata_info.InputTextTensorMd(name=_INPUT_NAME, description=_INPUT_DESCRIPTION)\nif output_md is None:\n output_md = metadata_info.ClassificationTensorMd(nam... | <|body_start_0|>
if general_md is None:
general_md = metadata_info.GeneralMd(name=_MODEL_NAME, description=_MODEL_DESCRIPTION)
if input_md is None:
input_md = metadata_info.InputTextTensorMd(name=_INPUT_NAME, description=_INPUT_DESCRIPTION)
if output_md is None:
... | Writes metadata into the NL classifier. | MetadataWriter | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"GPL-1.0-or-later",
"MIT",
"LGPL-2.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetadataWriter:
"""Writes metadata into the NL classifier."""
def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputTextTensorMd]=None, output_md: Optional[metadata_info.ClassificationTensorMd]=No... | stack_v2_sparse_classes_75kplus_train_072412 | 5,699 | permissive | [
{
"docstring": "Creates MetadataWriter based on general/input/output information. Args: model_buffer: valid buffer of the model file. general_md: general information about the model. If not specified, default general metadata will be generated. input_md: input text tensor information, if not specified, default ... | 2 | stack_v2_sparse_classes_30k_train_006505 | Implement the Python class `MetadataWriter` described below.
Class description:
Writes metadata into the NL classifier.
Method signatures and docstrings:
- def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputTextTensorMd... | Implement the Python class `MetadataWriter` described below.
Class description:
Writes metadata into the NL classifier.
Method signatures and docstrings:
- def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputTextTensorMd... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class MetadataWriter:
"""Writes metadata into the NL classifier."""
def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputTextTensorMd]=None, output_md: Optional[metadata_info.ClassificationTensorMd]=No... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetadataWriter:
"""Writes metadata into the NL classifier."""
def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputTextTensorMd]=None, output_md: Optional[metadata_info.ClassificationTensorMd]=None):
... | the_stack_v2_python_sparse | third_party/tflite_support/src/tensorflow_lite_support/metadata/python/metadata_writers/nl_classifier.py | chromium/chromium | train | 17,408 |
59c13283a5d7d15ce95180e44e0dabbb0e3bb36b | [
"p = Participant.query.get(kf_id)\nif p is None:\n abort(404, 'could not find {} `{}`'.format('participant', kf_id))\nreturn ParticipantSchema().jsonify(p)",
"p = Participant.query.get(kf_id)\nif p is None:\n abort(404, 'could not find {} `{}`'.format('participant', kf_id))\nbody = request.get_json(force=Tr... | <|body_start_0|>
p = Participant.query.get(kf_id)
if p is None:
abort(404, 'could not find {} `{}`'.format('participant', kf_id))
return ParticipantSchema().jsonify(p)
<|end_body_0|>
<|body_start_1|>
p = Participant.query.get(kf_id)
if p is None:
abort(40... | Participant API | ParticipantAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParticipantAPI:
"""Participant API"""
def get(self, kf_id):
"""Get a participant by id --- template: path: get_by_id.yml properties: resource: Participant"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing participant. Allows partial update --- template:... | stack_v2_sparse_classes_75kplus_train_072413 | 4,062 | permissive | [
{
"docstring": "Get a participant by id --- template: path: get_by_id.yml properties: resource: Participant",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing participant. Allows partial update --- template: path: update_by_id.yml properties: resource: Par... | 3 | stack_v2_sparse_classes_30k_train_012571 | Implement the Python class `ParticipantAPI` described below.
Class description:
Participant API
Method signatures and docstrings:
- def get(self, kf_id): Get a participant by id --- template: path: get_by_id.yml properties: resource: Participant
- def patch(self, kf_id): Update an existing participant. Allows partial... | Implement the Python class `ParticipantAPI` described below.
Class description:
Participant API
Method signatures and docstrings:
- def get(self, kf_id): Get a participant by id --- template: path: get_by_id.yml properties: resource: Participant
- def patch(self, kf_id): Update an existing participant. Allows partial... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class ParticipantAPI:
"""Participant API"""
def get(self, kf_id):
"""Get a participant by id --- template: path: get_by_id.yml properties: resource: Participant"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing participant. Allows partial update --- template:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParticipantAPI:
"""Participant API"""
def get(self, kf_id):
"""Get a participant by id --- template: path: get_by_id.yml properties: resource: Participant"""
p = Participant.query.get(kf_id)
if p is None:
abort(404, 'could not find {} `{}`'.format('participant', kf_id)... | the_stack_v2_python_sparse | dataservice/api/participant/resources.py | kids-first/kf-api-dataservice | train | 9 |
4d17e962b24138ddf96b9097d03eb0d5f1a046b4 | [
"self.input_mat_img = input_mat_img\nself.model_path = model_path\nself.cfg_path = cfg_path\nself.panoptic_seg = []\nself.segments_info = []\nself.cfg = []",
"labels = None\nif classes is not None and class_names is not None and (len(class_names) > 1):\n labels = [class_names[i] for i in classes]\nif scores is... | <|body_start_0|>
self.input_mat_img = input_mat_img
self.model_path = model_path
self.cfg_path = cfg_path
self.panoptic_seg = []
self.segments_info = []
self.cfg = []
<|end_body_0|>
<|body_start_1|>
labels = None
if classes is not None and class_names is ... | PanoramicSegmentation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PanoramicSegmentation:
def __init__(self, input_mat_img, model_path=COMMON_CONFIGS['PanoramicSegmentation']['MODEL_FILE'], cfg_path=COMMON_CONFIGS['PanoramicSegmentation']['CFG_FILE']):
""":param input_mat_img: 传入mat格式图片 :param model_path: 模型地址 :param cfg_path: cfg配置文件地址"""
<|bod... | stack_v2_sparse_classes_75kplus_train_072414 | 5,571 | no_license | [
{
"docstring": ":param input_mat_img: 传入mat格式图片 :param model_path: 模型地址 :param cfg_path: cfg配置文件地址",
"name": "__init__",
"signature": "def __init__(self, input_mat_img, model_path=COMMON_CONFIGS['PanoramicSegmentation']['MODEL_FILE'], cfg_path=COMMON_CONFIGS['PanoramicSegmentation']['CFG_FILE'])"
},
... | 3 | stack_v2_sparse_classes_30k_train_031135 | Implement the Python class `PanoramicSegmentation` described below.
Class description:
Implement the PanoramicSegmentation class.
Method signatures and docstrings:
- def __init__(self, input_mat_img, model_path=COMMON_CONFIGS['PanoramicSegmentation']['MODEL_FILE'], cfg_path=COMMON_CONFIGS['PanoramicSegmentation']['CF... | Implement the Python class `PanoramicSegmentation` described below.
Class description:
Implement the PanoramicSegmentation class.
Method signatures and docstrings:
- def __init__(self, input_mat_img, model_path=COMMON_CONFIGS['PanoramicSegmentation']['MODEL_FILE'], cfg_path=COMMON_CONFIGS['PanoramicSegmentation']['CF... | 8fcd4046bb2acbc3487d59106abb1a40a642cc1f | <|skeleton|>
class PanoramicSegmentation:
def __init__(self, input_mat_img, model_path=COMMON_CONFIGS['PanoramicSegmentation']['MODEL_FILE'], cfg_path=COMMON_CONFIGS['PanoramicSegmentation']['CFG_FILE']):
""":param input_mat_img: 传入mat格式图片 :param model_path: 模型地址 :param cfg_path: cfg配置文件地址"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PanoramicSegmentation:
def __init__(self, input_mat_img, model_path=COMMON_CONFIGS['PanoramicSegmentation']['MODEL_FILE'], cfg_path=COMMON_CONFIGS['PanoramicSegmentation']['CFG_FILE']):
""":param input_mat_img: 传入mat格式图片 :param model_path: 模型地址 :param cfg_path: cfg配置文件地址"""
self.input_mat_img ... | the_stack_v2_python_sparse | common_module/function_model/panoramic_segmentation/picture_panoramic_segmentation.py | zhangruipython/ai_platform | train | 5 | |
8fbe4b7520dbaf572c59d6f73b8f0a4537583b6f | [
"self.V = V\nself.num_param = num_param\nself.step = step\nif init_param.size == 0:\n self.init_param = np.zeros(num_param)\nelse:\n self.init_param = init_param\nself.max_iter = max_iter\nself.tol = tol\nself.report_data = []\nself.quad_conv = True\nself.grad = 0",
"b = FullMatrix(self.num_param, 1)\nif pa... | <|body_start_0|>
self.V = V
self.num_param = num_param
self.step = step
if init_param.size == 0:
self.init_param = np.zeros(num_param)
else:
self.init_param = init_param
self.max_iter = max_iter
self.tol = tol
self.report_data = []
... | An instance is a representation of the Quasi-Newton minimization problem. | QNM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QNM:
"""An instance is a representation of the Quasi-Newton minimization problem."""
def __init__(self, V, num_param, init_param=np.empty(0), tol=10 ** (-7), step=np.float(10 ** (-7)), max_iter=10 ** 2):
"""V: Objective Function [python function which takes a np.ndarray as an input a... | stack_v2_sparse_classes_75kplus_train_072415 | 3,785 | no_license | [
{
"docstring": "V: Objective Function [python function which takes a np.ndarray as an input and returns a float] num_param: Number of paramters [int] init_param: Initial guess of parameters [np.ndarray] tol: Tolerance [float] step: Step size for calculating derivatives [np.float64] max_iter: Number of maximum i... | 6 | stack_v2_sparse_classes_30k_train_038980 | Implement the Python class `QNM` described below.
Class description:
An instance is a representation of the Quasi-Newton minimization problem.
Method signatures and docstrings:
- def __init__(self, V, num_param, init_param=np.empty(0), tol=10 ** (-7), step=np.float(10 ** (-7)), max_iter=10 ** 2): V: Objective Functio... | Implement the Python class `QNM` described below.
Class description:
An instance is a representation of the Quasi-Newton minimization problem.
Method signatures and docstrings:
- def __init__(self, V, num_param, init_param=np.empty(0), tol=10 ** (-7), step=np.float(10 ** (-7)), max_iter=10 ** 2): V: Objective Functio... | 7439f25c7809f4198e452f70ae4269447873f7db | <|skeleton|>
class QNM:
"""An instance is a representation of the Quasi-Newton minimization problem."""
def __init__(self, V, num_param, init_param=np.empty(0), tol=10 ** (-7), step=np.float(10 ** (-7)), max_iter=10 ** 2):
"""V: Objective Function [python function which takes a np.ndarray as an input a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QNM:
"""An instance is a representation of the Quasi-Newton minimization problem."""
def __init__(self, V, num_param, init_param=np.empty(0), tol=10 ** (-7), step=np.float(10 ** (-7)), max_iter=10 ** 2):
"""V: Objective Function [python function which takes a np.ndarray as an input and returns a ... | the_stack_v2_python_sparse | PA3/quasi_newton_min.py | ta275/Scientific-Computing-in-Python | train | 0 |
f1120224241851c19baa225fddf63173832d53ab | [
"try:\n serializer = PatientHistorySerializers(PatientHistory.objects.all(), many=True)\n return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)\nexcept Exception as e:\n info_message = 'Internal Server Error'\n logger.error(info_message, e)\n return JsonResponse({'error'... | <|body_start_0|>
try:
serializer = PatientHistorySerializers(PatientHistory.objects.all(), many=True)
return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)
except Exception as e:
info_message = 'Internal Server Error'
logger.e... | PatientHistoryView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatientHistoryView:
def get(self, request):
"""Get all patients"""
<|body_0|>
def post(self, request):
"""Save patient data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
serializer = PatientHistorySerializers(PatientHistory.object... | stack_v2_sparse_classes_75kplus_train_072416 | 12,219 | no_license | [
{
"docstring": "Get all patients",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Save patient data",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036899 | Implement the Python class `PatientHistoryView` described below.
Class description:
Implement the PatientHistoryView class.
Method signatures and docstrings:
- def get(self, request): Get all patients
- def post(self, request): Save patient data | Implement the Python class `PatientHistoryView` described below.
Class description:
Implement the PatientHistoryView class.
Method signatures and docstrings:
- def get(self, request): Get all patients
- def post(self, request): Save patient data
<|skeleton|>
class PatientHistoryView:
def get(self, request):
... | b63849983a592fd6a1f654191020fd86aa0787ae | <|skeleton|>
class PatientHistoryView:
def get(self, request):
"""Get all patients"""
<|body_0|>
def post(self, request):
"""Save patient data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PatientHistoryView:
def get(self, request):
"""Get all patients"""
try:
serializer = PatientHistorySerializers(PatientHistory.objects.all(), many=True)
return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)
except Exception as e:
... | the_stack_v2_python_sparse | patient/views.py | RupeshKurlekar/biocare | train | 1 | |
873de64e006566dcd79f8e167559a92b83b1b928 | [
"process = subprocess.Popen(scriptfiles_parametrize, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\nstdout, stderr = process.communicate()\nretcode = process.returncode\nassert retcode == 2\nassert stdout == ''\nassert stderr.startswith('usage')",
"process = subprocess.Popen... | <|body_start_0|>
process = subprocess.Popen(scriptfiles_parametrize, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
stdout, stderr = process.communicate()
retcode = process.returncode
assert retcode == 2
assert stdout == ''
assert std... | TestHelp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHelp:
def test_ShortHelp(self, scriptfiles_parametrize):
"""Test the abbreviated help for each script"""
<|body_0|>
def test_LongHelp(self, scriptfiles_parametrize):
"""Test the full help for each script"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_072417 | 1,954 | permissive | [
{
"docstring": "Test the abbreviated help for each script",
"name": "test_ShortHelp",
"signature": "def test_ShortHelp(self, scriptfiles_parametrize)"
},
{
"docstring": "Test the full help for each script",
"name": "test_LongHelp",
"signature": "def test_LongHelp(self, scriptfiles_parame... | 2 | stack_v2_sparse_classes_30k_train_034768 | Implement the Python class `TestHelp` described below.
Class description:
Implement the TestHelp class.
Method signatures and docstrings:
- def test_ShortHelp(self, scriptfiles_parametrize): Test the abbreviated help for each script
- def test_LongHelp(self, scriptfiles_parametrize): Test the full help for each scrip... | Implement the Python class `TestHelp` described below.
Class description:
Implement the TestHelp class.
Method signatures and docstrings:
- def test_ShortHelp(self, scriptfiles_parametrize): Test the abbreviated help for each script
- def test_LongHelp(self, scriptfiles_parametrize): Test the full help for each scrip... | 2a0d8a541431f84e4d887821cd66a5ea525e3026 | <|skeleton|>
class TestHelp:
def test_ShortHelp(self, scriptfiles_parametrize):
"""Test the abbreviated help for each script"""
<|body_0|>
def test_LongHelp(self, scriptfiles_parametrize):
"""Test the full help for each script"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestHelp:
def test_ShortHelp(self, scriptfiles_parametrize):
"""Test the abbreviated help for each script"""
process = subprocess.Popen(scriptfiles_parametrize, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
stdout, stderr = process.communicate()
... | the_stack_v2_python_sparse | test_sfauto/test_20_help.py | cseelye/sfauto | train | 0 | |
80b2a3d354ac07150d7149ccdb5aaf806e3457ce | [
"TemplateConfig.__init__(self)\nself.extended = {}\nself.merge({u'DEFAULT': {u'hooks': hooks_location}})\nself._initialize(config, template_dirs)\nself.interpolation = 'template'\nif isinstance(config, str) and os.path.exists(config):\n self.filename = config",
"def extend(config, template_dirs):\n \"\"\"\n... | <|body_start_0|>
TemplateConfig.__init__(self)
self.extended = {}
self.merge({u'DEFAULT': {u'hooks': hooks_location}})
self._initialize(config, template_dirs)
self.interpolation = 'template'
if isinstance(config, str) and os.path.exists(config):
self.filename ... | The ProjectConfig is a class that extends the TemplateConfig by the ability of inheritance of template configurations. | ProjectConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectConfig:
"""The ProjectConfig is a class that extends the TemplateConfig by the ability of inheritance of template configurations."""
def __init__(self, config, hooks_location='hooks', template_dirs=None):
"""Constructor. :param config: The path or a splittedline configuration ... | stack_v2_sparse_classes_75kplus_train_072418 | 30,337 | permissive | [
{
"docstring": "Constructor. :param config: The path or a splittedline configuration string. See the U(ConfigObj documentation<http://www.voi dspace.org.uk/python/configobj.html#reading-a-co nfig-file>) for more details. :type config: string :param hooks_location: The location of the hooks directory. :type hook... | 2 | null | Implement the Python class `ProjectConfig` described below.
Class description:
The ProjectConfig is a class that extends the TemplateConfig by the ability of inheritance of template configurations.
Method signatures and docstrings:
- def __init__(self, config, hooks_location='hooks', template_dirs=None): Constructor.... | Implement the Python class `ProjectConfig` described below.
Class description:
The ProjectConfig is a class that extends the TemplateConfig by the ability of inheritance of template configurations.
Method signatures and docstrings:
- def __init__(self, config, hooks_location='hooks', template_dirs=None): Constructor.... | d2b4277a9290b65d93148be75000ae5070970973 | <|skeleton|>
class ProjectConfig:
"""The ProjectConfig is a class that extends the TemplateConfig by the ability of inheritance of template configurations."""
def __init__(self, config, hooks_location='hooks', template_dirs=None):
"""Constructor. :param config: The path or a splittedline configuration ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectConfig:
"""The ProjectConfig is a class that extends the TemplateConfig by the ability of inheritance of template configurations."""
def __init__(self, config, hooks_location='hooks', template_dirs=None):
"""Constructor. :param config: The path or a splittedline configuration string. See t... | the_stack_v2_python_sparse | src/repoguard/core/config.py | kerwin612/RepoGuard | train | 0 |
edea30083027e1b0df41cf9d3ffffe637b3b5c65 | [
"QObject.__init__(self, ui)\nself.__ui = ui\nself.__action = None\nself.__translator = None\nself.__loadTranslator()\nself.__initAction()",
"e5App().getObject('ToolbarManager').addAction(self.__action, 'Tools')\nmenu = self.__ui.getMenu('extras')\nmenu.addAction(self.__action)\nreturn (None, True)",
"e5App().ge... | <|body_start_0|>
QObject.__init__(self, ui)
self.__ui = ui
self.__action = None
self.__translator = None
self.__loadTranslator()
self.__initAction()
<|end_body_0|>
<|body_start_1|>
e5App().getObject('ToolbarManager').addAction(self.__action, 'Tools')
menu... | Class implementing the virtualenv wizard plug-in. | WizardVirtualenvPlugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WizardVirtualenvPlugin:
"""Class implementing the virtualenv wizard plug-in."""
def __init__(self, ui):
"""Constructor @param ui reference to the user interface object (UI.UserInterface)"""
<|body_0|>
def activate(self):
"""Public method to activate this plug-in.... | stack_v2_sparse_classes_75kplus_train_072419 | 4,443 | no_license | [
{
"docstring": "Constructor @param ui reference to the user interface object (UI.UserInterface)",
"name": "__init__",
"signature": "def __init__(self, ui)"
},
{
"docstring": "Public method to activate this plug-in. @return tuple of None and activation status (boolean)",
"name": "activate",
... | 6 | stack_v2_sparse_classes_30k_train_053645 | Implement the Python class `WizardVirtualenvPlugin` described below.
Class description:
Class implementing the virtualenv wizard plug-in.
Method signatures and docstrings:
- def __init__(self, ui): Constructor @param ui reference to the user interface object (UI.UserInterface)
- def activate(self): Public method to a... | Implement the Python class `WizardVirtualenvPlugin` described below.
Class description:
Class implementing the virtualenv wizard plug-in.
Method signatures and docstrings:
- def __init__(self, ui): Constructor @param ui reference to the user interface object (UI.UserInterface)
- def activate(self): Public method to a... | 3df0c805225a8d4f2709565d7eda4e07a050c986 | <|skeleton|>
class WizardVirtualenvPlugin:
"""Class implementing the virtualenv wizard plug-in."""
def __init__(self, ui):
"""Constructor @param ui reference to the user interface object (UI.UserInterface)"""
<|body_0|>
def activate(self):
"""Public method to activate this plug-in.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WizardVirtualenvPlugin:
"""Class implementing the virtualenv wizard plug-in."""
def __init__(self, ui):
"""Constructor @param ui reference to the user interface object (UI.UserInterface)"""
QObject.__init__(self, ui)
self.__ui = ui
self.__action = None
self.__trans... | the_stack_v2_python_sparse | eric6/.eric6/eric6plugins/PluginWizardVirtualenv.py | metamarcdw/.dotfiles | train | 0 |
8d9310c8105b4998961751ce6d42fffc275e12dd | [
"super(Sequential, self).__init__(force_cpu, training_device, random_state)\nself.__layers = []\nself.__build = False",
"if self.__build:\n raise Exception('You have built this model already, you can not make any changes in this model')\nself.__layers.append(layer)",
"layers = build_layer... | <|body_start_0|>
super(Sequential, self).__init__(force_cpu, training_device, random_state)
self.__layers = []
self.__build = False
<|end_body_0|>
<|body_start_1|>
if self.__build:
raise Exception('You have built this model already, you can not make any changes in ... | Sequential is a linear stack of layers with single input and output layer. It is one of the simplest types of models. In Sequential models, each layer has a single input and output tensor. Supported Arguments: force_cpu=False: (Boolean) If True, then uses CPU even if CUDA is available training_device=None: (NeuralPy de... | Sequential | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sequential:
"""Sequential is a linear stack of layers with single input and output layer. It is one of the simplest types of models. In Sequential models, each layer has a single input and output tensor. Supported Arguments: force_cpu=False: (Boolean) If True, then uses CPU even if CUDA is availa... | stack_v2_sparse_classes_75kplus_train_072420 | 2,947 | permissive | [
{
"docstring": "__init__ method for Sequential Model Supported Arguments: force_cpu=False: (Boolean) If True, then uses CPU even if CUDA is available training_device=None: (NeuralPy device class) Device that will be used for training predictions random_state: (Integer) Random state for the device",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_024901 | Implement the Python class `Sequential` described below.
Class description:
Sequential is a linear stack of layers with single input and output layer. It is one of the simplest types of models. In Sequential models, each layer has a single input and output tensor. Supported Arguments: force_cpu=False: (Boolean) If Tru... | Implement the Python class `Sequential` described below.
Class description:
Sequential is a linear stack of layers with single input and output layer. It is one of the simplest types of models. In Sequential models, each layer has a single input and output tensor. Supported Arguments: force_cpu=False: (Boolean) If Tru... | b8c0ce14287d981a17054490241d52f55cef7abf | <|skeleton|>
class Sequential:
"""Sequential is a linear stack of layers with single input and output layer. It is one of the simplest types of models. In Sequential models, each layer has a single input and output tensor. Supported Arguments: force_cpu=False: (Boolean) If True, then uses CPU even if CUDA is availa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sequential:
"""Sequential is a linear stack of layers with single input and output layer. It is one of the simplest types of models. In Sequential models, each layer has a single input and output tensor. Supported Arguments: force_cpu=False: (Boolean) If True, then uses CPU even if CUDA is available training_... | the_stack_v2_python_sparse | neuralpy/models/sequential.py | 321HG/NeuralPy | train | 0 |
a013be26c1ce662e05766a981e8945a13e137c19 | [
"if not email:\n raise ValueError(_('El usuario debe tener un email'))\nextra_fields.setdefault('is_active', False)\nuser = self.model(email=self.normalize_email(email), **extra_fields)\nuser.set_password(password)\nuser.save()\nreturn user",
"extra_fields.setdefault('is_superuser', True)\nextra_fields.setdefa... | <|body_start_0|>
if not email:
raise ValueError(_('El usuario debe tener un email'))
extra_fields.setdefault('is_active', False)
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save()
return user
<|end_body... | User Manager for CustomUser model | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
"""User Manager for CustomUser model"""
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a User with the given email"""
<|body_0|>
def create_superuser(self, email, password, **extra_fields):
"""Creates and save... | stack_v2_sparse_classes_75kplus_train_072421 | 1,448 | no_license | [
{
"docstring": "Creates and saves a User with the given email",
"name": "create_user",
"signature": "def create_user(self, email, password=None, **extra_fields)"
},
{
"docstring": "Creates and saves a superuser with the given email and password.",
"name": "create_superuser",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_026941 | Implement the Python class `CustomUserManager` described below.
Class description:
User Manager for CustomUser model
Method signatures and docstrings:
- def create_user(self, email, password=None, **extra_fields): Creates and saves a User with the given email
- def create_superuser(self, email, password, **extra_fiel... | Implement the Python class `CustomUserManager` described below.
Class description:
User Manager for CustomUser model
Method signatures and docstrings:
- def create_user(self, email, password=None, **extra_fields): Creates and saves a User with the given email
- def create_superuser(self, email, password, **extra_fiel... | 1241b809564757c2d6affa8471389f2e53551653 | <|skeleton|>
class CustomUserManager:
"""User Manager for CustomUser model"""
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a User with the given email"""
<|body_0|>
def create_superuser(self, email, password, **extra_fields):
"""Creates and save... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomUserManager:
"""User Manager for CustomUser model"""
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a User with the given email"""
if not email:
raise ValueError(_('El usuario debe tener un email'))
extra_fields.setdefault('is_a... | the_stack_v2_python_sparse | pocketLaw_back_end/account/managers.py | sergiorvs/PocketLaw | train | 0 |
7d638562274983dc2e8b6e9d6ab961921810ebfd | [
"self.functional_file = functional_file\nself.top = top\nself.node_file = node_file\nself.term_id_to_values = self.parse_functional_profile()",
"term_id_to_values = {}\nwith open(self.functional_file, 'r') as f:\n for line in f:\n if line[0] == '#':\n continue\n term_id, term_name, num... | <|body_start_0|>
self.functional_file = functional_file
self.top = top
self.node_file = node_file
self.term_id_to_values = self.parse_functional_profile()
<|end_body_0|>
<|body_start_1|>
term_id_to_values = {}
with open(self.functional_file, 'r') as f:
for li... | Class defining a GUILD profile object | FunctionalProfile | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionalProfile:
"""Class defining a GUILD profile object"""
def __init__(self, functional_file, top, node_file):
"""@param: functional_file @pdef: File resulting from the functional enrichment analysis, which contains the enriched functions @ptype: {String} @param: top @pdef: Perc... | stack_v2_sparse_classes_75kplus_train_072422 | 41,145 | permissive | [
{
"docstring": "@param: functional_file @pdef: File resulting from the functional enrichment analysis, which contains the enriched functions @ptype: {String} @param: top @pdef: Percentage of the nodes with respect to the initial GUILD file (100, 10...) @ptype: {String} @param: node_file @pdef: Node profile file... | 2 | stack_v2_sparse_classes_30k_train_043397 | Implement the Python class `FunctionalProfile` described below.
Class description:
Class defining a GUILD profile object
Method signatures and docstrings:
- def __init__(self, functional_file, top, node_file): @param: functional_file @pdef: File resulting from the functional enrichment analysis, which contains the en... | Implement the Python class `FunctionalProfile` described below.
Class description:
Class defining a GUILD profile object
Method signatures and docstrings:
- def __init__(self, functional_file, top, node_file): @param: functional_file @pdef: File resulting from the functional enrichment analysis, which contains the en... | 930da0ea91ad87e354061af18db6c437a3318366 | <|skeleton|>
class FunctionalProfile:
"""Class defining a GUILD profile object"""
def __init__(self, functional_file, top, node_file):
"""@param: functional_file @pdef: File resulting from the functional enrichment analysis, which contains the enriched functions @ptype: {String} @param: top @pdef: Perc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FunctionalProfile:
"""Class defining a GUILD profile object"""
def __init__(self, functional_file, top, node_file):
"""@param: functional_file @pdef: File resulting from the functional enrichment analysis, which contains the enriched functions @ptype: {String} @param: top @pdef: Percentage of the... | the_stack_v2_python_sparse | diana/classes/network_analysis.py | quimaguirre/diana | train | 3 |
1d82f5414888f03edba06a9fa81d86b4bbd38aca | [
"if not nums:\n return 0\nres = float('inf')\nleft = 0\ncurrent_sum = 0\nfor right in range(len(nums)):\n if current_sum < s:\n current_sum += nums[right]\n while current_sum >= s:\n res = min(right - left + 1, res)\n current_sum -= nums[left]\n left += 1\nreturn res if res != f... | <|body_start_0|>
if not nums:
return 0
res = float('inf')
left = 0
current_sum = 0
for right in range(len(nums)):
if current_sum < s:
current_sum += nums[right]
while current_sum >= s:
res = min(right - left + 1,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def min_subarray_len(self, s: int, nums: List[int]) -> int:
"""Two pointer. time complexity: O(N)"""
<|body_0|>
def min_subarray_len_binary_search(self, s: int, nums: List[int]) -> int:
"""Construct a accumulative sum array and for each element greater than... | stack_v2_sparse_classes_75kplus_train_072423 | 1,537 | no_license | [
{
"docstring": "Two pointer. time complexity: O(N)",
"name": "min_subarray_len",
"signature": "def min_subarray_len(self, s: int, nums: List[int]) -> int"
},
{
"docstring": "Construct a accumulative sum array and for each element greater than s, apply binary search to find the start position. ti... | 2 | stack_v2_sparse_classes_30k_train_013272 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def min_subarray_len(self, s: int, nums: List[int]) -> int: Two pointer. time complexity: O(N)
- def min_subarray_len_binary_search(self, s: int, nums: List[int]) -> int: Constru... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def min_subarray_len(self, s: int, nums: List[int]) -> int: Two pointer. time complexity: O(N)
- def min_subarray_len_binary_search(self, s: int, nums: List[int]) -> int: Constru... | 5625e6396b746255f3343253c75447ead95879c7 | <|skeleton|>
class Solution:
def min_subarray_len(self, s: int, nums: List[int]) -> int:
"""Two pointer. time complexity: O(N)"""
<|body_0|>
def min_subarray_len_binary_search(self, s: int, nums: List[int]) -> int:
"""Construct a accumulative sum array and for each element greater than... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def min_subarray_len(self, s: int, nums: List[int]) -> int:
"""Two pointer. time complexity: O(N)"""
if not nums:
return 0
res = float('inf')
left = 0
current_sum = 0
for right in range(len(nums)):
if current_sum < s:
... | the_stack_v2_python_sparse | 209_minimum_size_subarray_sum/solution.py | FluffyFu/Leetcode | train | 0 | |
2571988bd5e306c130bbfce5e690abf08c8a305b | [
"input_specs = {}\nfor level in range(model_id):\n input_specs[str(level + 1)] = tf.TensorShape([1, 128 // 2 ** level, 128 // 2 ** level, 128 // 2 ** level, 1])\nnetwork = decoders.UNet3DDecoder(model_id=model_id, input_specs=input_specs, use_sync_bn=True, use_batch_normalization=True, use_deconvolution=True)\nm... | <|body_start_0|>
input_specs = {}
for level in range(model_id):
input_specs[str(level + 1)] = tf.TensorShape([1, 128 // 2 ** level, 128 // 2 ** level, 128 // 2 ** level, 1])
network = decoders.UNet3DDecoder(model_id=model_id, input_specs=input_specs, use_sync_bn=True, use_batch_norma... | FactoryTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactoryTest:
def test_unet_3d_decoder_creation(self, model_id):
"""Test creation of UNet 3D decoder."""
<|body_0|>
def test_identity_creation(self):
"""Test creation of identity decoder."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
input_specs = ... | stack_v2_sparse_classes_75kplus_train_072424 | 3,008 | permissive | [
{
"docstring": "Test creation of UNet 3D decoder.",
"name": "test_unet_3d_decoder_creation",
"signature": "def test_unet_3d_decoder_creation(self, model_id)"
},
{
"docstring": "Test creation of identity decoder.",
"name": "test_identity_creation",
"signature": "def test_identity_creation... | 2 | stack_v2_sparse_classes_30k_train_007019 | Implement the Python class `FactoryTest` described below.
Class description:
Implement the FactoryTest class.
Method signatures and docstrings:
- def test_unet_3d_decoder_creation(self, model_id): Test creation of UNet 3D decoder.
- def test_identity_creation(self): Test creation of identity decoder. | Implement the Python class `FactoryTest` described below.
Class description:
Implement the FactoryTest class.
Method signatures and docstrings:
- def test_unet_3d_decoder_creation(self, model_id): Test creation of UNet 3D decoder.
- def test_identity_creation(self): Test creation of identity decoder.
<|skeleton|>
cl... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class FactoryTest:
def test_unet_3d_decoder_creation(self, model_id):
"""Test creation of UNet 3D decoder."""
<|body_0|>
def test_identity_creation(self):
"""Test creation of identity decoder."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FactoryTest:
def test_unet_3d_decoder_creation(self, model_id):
"""Test creation of UNet 3D decoder."""
input_specs = {}
for level in range(model_id):
input_specs[str(level + 1)] = tf.TensorShape([1, 128 // 2 ** level, 128 // 2 ** level, 128 // 2 ** level, 1])
netwo... | the_stack_v2_python_sparse | official/projects/volumetric_models/modeling/decoders/factory_test.py | jianzhnie/models | train | 2 | |
40e0a7dc076abea856e2b79a6f647c93acab3e12 | [
"tip_label1 = widgets.Label(u'策略相关性交叉验证暂不支持实时网络数据模式', layout=widgets.Layout(width='300px'))\ntip_label2 = widgets.Label(u\"需先用'数据下载界面操作'进行下载\", layout=widgets.Layout(width='300px'))\nself.bf = BuyFactorWGManager()\nself.sf = SellFactorWGManager(show_add_buy=True)\nsub_widget_tab = widgets.Tab()\nsub_widget_tab.chil... | <|body_start_0|>
tip_label1 = widgets.Label(u'策略相关性交叉验证暂不支持实时网络数据模式', layout=widgets.Layout(width='300px'))
tip_label2 = widgets.Label(u"需先用'数据下载界面操作'进行下载", layout=widgets.Layout(width='300px'))
self.bf = BuyFactorWGManager()
self.sf = SellFactorWGManager(show_add_buy=True)
sub_w... | 策略相关性交叉验证ui类 | WidgetCrossVal | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WidgetCrossVal:
"""策略相关性交叉验证ui类"""
def __init__(self):
"""构建回测需要的各个组件形成tab"""
<|body_0|>
def run_cross_val(self, bt):
"""交叉相关性验证策略有效性的button按钮"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
tip_label1 = widgets.Label(u'策略相关性交叉验证暂不支持实时网络数据模式', l... | stack_v2_sparse_classes_75kplus_train_072425 | 3,865 | permissive | [
{
"docstring": "构建回测需要的各个组件形成tab",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "交叉相关性验证策略有效性的button按钮",
"name": "run_cross_val",
"signature": "def run_cross_val(self, bt)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020591 | Implement the Python class `WidgetCrossVal` described below.
Class description:
策略相关性交叉验证ui类
Method signatures and docstrings:
- def __init__(self): 构建回测需要的各个组件形成tab
- def run_cross_val(self, bt): 交叉相关性验证策略有效性的button按钮 | Implement the Python class `WidgetCrossVal` described below.
Class description:
策略相关性交叉验证ui类
Method signatures and docstrings:
- def __init__(self): 构建回测需要的各个组件形成tab
- def run_cross_val(self, bt): 交叉相关性验证策略有效性的button按钮
<|skeleton|>
class WidgetCrossVal:
"""策略相关性交叉验证ui类"""
def __init__(self):
"""构建回测... | 2e5ab17f2d20deb3c68c927f6208ea89db7c639d | <|skeleton|>
class WidgetCrossVal:
"""策略相关性交叉验证ui类"""
def __init__(self):
"""构建回测需要的各个组件形成tab"""
<|body_0|>
def run_cross_val(self, bt):
"""交叉相关性验证策略有效性的button按钮"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WidgetCrossVal:
"""策略相关性交叉验证ui类"""
def __init__(self):
"""构建回测需要的各个组件形成tab"""
tip_label1 = widgets.Label(u'策略相关性交叉验证暂不支持实时网络数据模式', layout=widgets.Layout(width='300px'))
tip_label2 = widgets.Label(u"需先用'数据下载界面操作'进行下载", layout=widgets.Layout(width='300px'))
self.bf = BuyFact... | the_stack_v2_python_sparse | abupy/WidgetBu/ABuWGCrossVal.py | luqin/firefly | train | 1 |
f50413552e5f447dea656e6d9d8366198a51bb7a | [
"for amc_key, amc_value in lnt_dict.items():\n url = self.start_url[0] + amc_value + '/' + str(YEAR)\n yield scrapy.Request(url=url, callback=self.parser, meta={'amc_key': amc_key})",
"link = {}\nlink.update({response.meta.get('amc_key'): response.css(lnt_path[0]).getall()[0]})\nfor amc, url_value in link.i... | <|body_start_0|>
for amc_key, amc_value in lnt_dict.items():
url = self.start_url[0] + amc_value + '/' + str(YEAR)
yield scrapy.Request(url=url, callback=self.parser, meta={'amc_key': amc_key})
<|end_body_0|>
<|body_start_1|>
link = {}
link.update({response.meta.get('amc... | LTAdvisorKhoj | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LTAdvisorKhoj:
def start_requests(self):
"""This function will loop through all the AMC's in the given dictionary with the Query parameters of the URL. With the built up URL, the Scrapy Request will be sent."""
<|body_0|>
def parser(self, response):
"""This function ... | stack_v2_sparse_classes_75kplus_train_072426 | 1,757 | no_license | [
{
"docstring": "This function will loop through all the AMC's in the given dictionary with the Query parameters of the URL. With the built up URL, the Scrapy Request will be sent.",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "This function gets the Respon... | 2 | stack_v2_sparse_classes_30k_val_002147 | Implement the Python class `LTAdvisorKhoj` described below.
Class description:
Implement the LTAdvisorKhoj class.
Method signatures and docstrings:
- def start_requests(self): This function will loop through all the AMC's in the given dictionary with the Query parameters of the URL. With the built up URL, the Scrapy ... | Implement the Python class `LTAdvisorKhoj` described below.
Class description:
Implement the LTAdvisorKhoj class.
Method signatures and docstrings:
- def start_requests(self): This function will loop through all the AMC's in the given dictionary with the Query parameters of the URL. With the built up URL, the Scrapy ... | 946e1c35b785bfc3ea31d5903e021d4bc99fe302 | <|skeleton|>
class LTAdvisorKhoj:
def start_requests(self):
"""This function will loop through all the AMC's in the given dictionary with the Query parameters of the URL. With the built up URL, the Scrapy Request will be sent."""
<|body_0|>
def parser(self, response):
"""This function ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LTAdvisorKhoj:
def start_requests(self):
"""This function will loop through all the AMC's in the given dictionary with the Query parameters of the URL. With the built up URL, the Scrapy Request will be sent."""
for amc_key, amc_value in lnt_dict.items():
url = self.start_url[0] + a... | the_stack_v2_python_sparse | FundRatingAMCFiles/fund_rating_file_extraction/fund_rating_file_extraction/spiders/l&t.py | pavithra-ft/ft-automation | train | 0 | |
cc13d79a4b151a0bbc7c117f974e4fb6299b8ace | [
"soup = BeautifulSoup(response.content, 'html.parser')\nmenu_tag = soup.find_all(class_='uk-nav uk-nav-side')[1]\nfor li in menu_tag.find_all('li'):\n url = li.a.get('href')\n if not url.satrtswith('http'):\n url = ''.join([self.domain, url])\n yield url",
"try:\n soup = BeautifulSoup(response.... | <|body_start_0|>
soup = BeautifulSoup(response.content, 'html.parser')
menu_tag = soup.find_all(class_='uk-nav uk-nav-side')[1]
for li in menu_tag.find_all('li'):
url = li.a.get('href')
if not url.satrtswith('http'):
url = ''.join([self.domain, url])
... | 廖雪峰python3教程 | LiaoXueFengPythonCrawler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LiaoXueFengPythonCrawler:
"""廖雪峰python3教程"""
def parse_menu(self, response):
"""解析目录结构,获取所有URL目录列表 :param response: 爬虫所返回的response对象 :return: url生成器"""
<|body_0|>
def parse_body(self, response):
"""解析正文 :param response: 爬虫返回的response对象 :return: url生成器"""
... | stack_v2_sparse_classes_75kplus_train_072427 | 2,528 | no_license | [
{
"docstring": "解析目录结构,获取所有URL目录列表 :param response: 爬虫所返回的response对象 :return: url生成器",
"name": "parse_menu",
"signature": "def parse_menu(self, response)"
},
{
"docstring": "解析正文 :param response: 爬虫返回的response对象 :return: url生成器",
"name": "parse_body",
"signature": "def parse_body(self, r... | 2 | stack_v2_sparse_classes_30k_train_021626 | Implement the Python class `LiaoXueFengPythonCrawler` described below.
Class description:
廖雪峰python3教程
Method signatures and docstrings:
- def parse_menu(self, response): 解析目录结构,获取所有URL目录列表 :param response: 爬虫所返回的response对象 :return: url生成器
- def parse_body(self, response): 解析正文 :param response: 爬虫返回的response对象 :retur... | Implement the Python class `LiaoXueFengPythonCrawler` described below.
Class description:
廖雪峰python3教程
Method signatures and docstrings:
- def parse_menu(self, response): 解析目录结构,获取所有URL目录列表 :param response: 爬虫所返回的response对象 :return: url生成器
- def parse_body(self, response): 解析正文 :param response: 爬虫返回的response对象 :retur... | 9dc81fc32c18ef4e988fcdff2d9274d1a7cb8497 | <|skeleton|>
class LiaoXueFengPythonCrawler:
"""廖雪峰python3教程"""
def parse_menu(self, response):
"""解析目录结构,获取所有URL目录列表 :param response: 爬虫所返回的response对象 :return: url生成器"""
<|body_0|>
def parse_body(self, response):
"""解析正文 :param response: 爬虫返回的response对象 :return: url生成器"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LiaoXueFengPythonCrawler:
"""廖雪峰python3教程"""
def parse_menu(self, response):
"""解析目录结构,获取所有URL目录列表 :param response: 爬虫所返回的response对象 :return: url生成器"""
soup = BeautifulSoup(response.content, 'html.parser')
menu_tag = soup.find_all(class_='uk-nav uk-nav-side')[1]
for li in ... | the_stack_v2_python_sparse | pdf/liaoxuefeng_python_crawler.py | qq34384878/Spider | train | 0 |
0a052a277ae607acd9a81affe76050c38f0727c9 | [
"bin_path = '/usr/local/bin/'\nself.prefix = bin_path + 'aws s3api'\nif options is None:\n options = []\nself.operation = operation\nself.options = ' '.join(options)",
"if params is None:\n params = []\ncommand_list = [self.prefix, self.options, self.operation] + params\ncmd = list(filter(lambda cmd: len(cm... | <|body_start_0|>
bin_path = '/usr/local/bin/'
self.prefix = bin_path + 'aws s3api'
if options is None:
options = []
self.operation = operation
self.options = ' '.join(options)
<|end_body_0|>
<|body_start_1|>
if params is None:
params = []
... | AWS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AWS:
def __init__(self, operation, options=None):
"""Constructor for aws class operation(str): aws operations options(list): Optional options for the command"""
<|body_0|>
def command(self, params=None):
"""Args: params(list): list of params to be passed in the comma... | stack_v2_sparse_classes_75kplus_train_072428 | 973 | permissive | [
{
"docstring": "Constructor for aws class operation(str): aws operations options(list): Optional options for the command",
"name": "__init__",
"signature": "def __init__(self, operation, options=None)"
},
{
"docstring": "Args: params(list): list of params to be passed in the command Returns: com... | 2 | stack_v2_sparse_classes_30k_val_001770 | Implement the Python class `AWS` described below.
Class description:
Implement the AWS class.
Method signatures and docstrings:
- def __init__(self, operation, options=None): Constructor for aws class operation(str): aws operations options(list): Optional options for the command
- def command(self, params=None): Args... | Implement the Python class `AWS` described below.
Class description:
Implement the AWS class.
Method signatures and docstrings:
- def __init__(self, operation, options=None): Constructor for aws class operation(str): aws operations options(list): Optional options for the command
- def command(self, params=None): Args... | 4c3b9b3e8e7f42d43270a9b79299a8b404a76046 | <|skeleton|>
class AWS:
def __init__(self, operation, options=None):
"""Constructor for aws class operation(str): aws operations options(list): Optional options for the command"""
<|body_0|>
def command(self, params=None):
"""Args: params(list): list of params to be passed in the comma... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AWS:
def __init__(self, operation, options=None):
"""Constructor for aws class operation(str): aws operations options(list): Optional options for the command"""
bin_path = '/usr/local/bin/'
self.prefix = bin_path + 'aws s3api'
if options is None:
options = []
... | the_stack_v2_python_sparse | rgw/v2/lib/aws/resource_op.py | red-hat-storage/ceph-qe-scripts | train | 9 | |
db5392730296201fc393727bab4d48779fbfa707 | [
"super().__init__(name, card_no, expiry_date, address)\nself._csv = csv\nself._card_type = card_type",
"expiry = ''\nif self._expiry_date is not None:\n expiry = f\"Expires on {self._expiry_date.strftime('%Y-%m-%d')}\\n\"\nreturn f'\\n====== {self._card_type.upper()} CARD (ID {self.id})======\\n{self._name}\\n... | <|body_start_0|>
super().__init__(name, card_no, expiry_date, address)
self._csv = csv
self._card_type = card_type
<|end_body_0|>
<|body_start_1|>
expiry = ''
if self._expiry_date is not None:
expiry = f"Expires on {self._expiry_date.strftime('%Y-%m-%d')}\n"
... | Represent credit and debit cards. | MoneyCard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MoneyCard:
"""Represent credit and debit cards."""
def __init__(self, csv, card_type, name, card_no, expiry_date, address):
"""Initialises MoneyCard. :param csv: int :param card_type: String :param name: String :param card_no: String :param expiry_date: Datetime :param address: Addre... | stack_v2_sparse_classes_75kplus_train_072429 | 10,626 | no_license | [
{
"docstring": "Initialises MoneyCard. :param csv: int :param card_type: String :param name: String :param card_no: String :param expiry_date: Datetime :param address: Address",
"name": "__init__",
"signature": "def __init__(self, csv, card_type, name, card_no, expiry_date, address)"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_004062 | Implement the Python class `MoneyCard` described below.
Class description:
Represent credit and debit cards.
Method signatures and docstrings:
- def __init__(self, csv, card_type, name, card_no, expiry_date, address): Initialises MoneyCard. :param csv: int :param card_type: String :param name: String :param card_no: ... | Implement the Python class `MoneyCard` described below.
Class description:
Represent credit and debit cards.
Method signatures and docstrings:
- def __init__(self, csv, card_type, name, card_no, expiry_date, address): Initialises MoneyCard. :param csv: int :param card_type: String :param name: String :param card_no: ... | b7695cc7cf0860aa9c8bf492b1bd06bd88b9af41 | <|skeleton|>
class MoneyCard:
"""Represent credit and debit cards."""
def __init__(self, csv, card_type, name, card_no, expiry_date, address):
"""Initialises MoneyCard. :param csv: int :param card_type: String :param name: String :param card_no: String :param expiry_date: Datetime :param address: Addre... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MoneyCard:
"""Represent credit and debit cards."""
def __init__(self, csv, card_type, name, card_no, expiry_date, address):
"""Initialises MoneyCard. :param csv: int :param card_type: String :param name: String :param card_no: String :param expiry_date: Datetime :param address: Address"""
... | the_stack_v2_python_sparse | Assignments/Assignment 2/card.py | sakshambhardwaj523/Python-OOP-Projects | train | 0 |
387a0d462c0a65b0d8751a70265e4faf43628067 | [
"self.mydict = {}\nself.big = big\nself.medium = medium\nself.small = small\nself.mydict[1] = big\nself.mydict[2] = medium\nself.mydict[3] = small",
"if self.mydict[carType] > 0:\n self.mydict[carType] -= 1\n return True\nelse:\n return False"
] | <|body_start_0|>
self.mydict = {}
self.big = big
self.medium = medium
self.small = small
self.mydict[1] = big
self.mydict[2] = medium
self.mydict[3] = small
<|end_body_0|>
<|body_start_1|>
if self.mydict[carType] > 0:
self.mydict[carType] -= 1... | ParkingSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParkingSystem:
def __init__(self, big, medium, small):
""":type big: int :type medium: int :type small: int"""
<|body_0|>
def addCar(self, carType):
""":type carType: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.mydict = {}
... | stack_v2_sparse_classes_75kplus_train_072430 | 720 | no_license | [
{
"docstring": ":type big: int :type medium: int :type small: int",
"name": "__init__",
"signature": "def __init__(self, big, medium, small)"
},
{
"docstring": ":type carType: int :rtype: bool",
"name": "addCar",
"signature": "def addCar(self, carType)"
}
] | 2 | null | Implement the Python class `ParkingSystem` described below.
Class description:
Implement the ParkingSystem class.
Method signatures and docstrings:
- def __init__(self, big, medium, small): :type big: int :type medium: int :type small: int
- def addCar(self, carType): :type carType: int :rtype: bool | Implement the Python class `ParkingSystem` described below.
Class description:
Implement the ParkingSystem class.
Method signatures and docstrings:
- def __init__(self, big, medium, small): :type big: int :type medium: int :type small: int
- def addCar(self, carType): :type carType: int :rtype: bool
<|skeleton|>
cla... | 690b685048c8e89d26047b6bc48b5f9af7d59cbb | <|skeleton|>
class ParkingSystem:
def __init__(self, big, medium, small):
""":type big: int :type medium: int :type small: int"""
<|body_0|>
def addCar(self, carType):
""":type carType: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParkingSystem:
def __init__(self, big, medium, small):
""":type big: int :type medium: int :type small: int"""
self.mydict = {}
self.big = big
self.medium = medium
self.small = small
self.mydict[1] = big
self.mydict[2] = medium
self.mydict[3] = s... | the_stack_v2_python_sparse | 双周赛/5515. 设计停车系统.py | SimmonsChen/LeetCode | train | 0 | |
f78d61307f2194e88050b8af022705ef5bedda71 | [
"self._col_to_NINF_repl = None\nself._col_to_PINF_repl = None\nself._col_to_NAN_repl = None\nself.col_to_NINF_repl_preset = col_to_NINF_repl_preset\nself.col_to_PINF_repl_preset = col_to_PINF_repl_preset\nself.col_to_NAN_repl_preset = col_to_NAN_repl_preset",
"if not isinstance(X, pd.DataFrame):\n X = pd.DataF... | <|body_start_0|>
self._col_to_NINF_repl = None
self._col_to_PINF_repl = None
self._col_to_NAN_repl = None
self.col_to_NINF_repl_preset = col_to_NINF_repl_preset
self.col_to_PINF_repl_preset = col_to_PINF_repl_preset
self.col_to_NAN_repl_preset = col_to_NAN_repl_preset
<|e... | Sklearn-compatible estimator, for column-wise imputing DataFrames by replacing all ``NaNs`` and ``infs`` with with average/extreme values from the same columns. It is basically a wrapper around :func:`~tsfresh.utilities.dataframe_functions.impute`. Each occurring ``inf`` or ``NaN`` in the DataFrame is replaced by * ``-... | PerColumnImputer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PerColumnImputer:
"""Sklearn-compatible estimator, for column-wise imputing DataFrames by replacing all ``NaNs`` and ``infs`` with with average/extreme values from the same columns. It is basically a wrapper around :func:`~tsfresh.utilities.dataframe_functions.impute`. Each occurring ``inf`` or `... | stack_v2_sparse_classes_75kplus_train_072431 | 5,205 | permissive | [
{
"docstring": "Create a new PerColumnImputer instance, optionally with dictionaries containing replacements for ``NaNs`` and ``infs``. :param col_to_NINF_repl: Dictionary mapping column names to ``-inf`` replacement values :type col_to_NINF_repl: dict :param col_to_PINF_repl: Dictionary mapping column names to... | 3 | stack_v2_sparse_classes_30k_train_044295 | Implement the Python class `PerColumnImputer` described below.
Class description:
Sklearn-compatible estimator, for column-wise imputing DataFrames by replacing all ``NaNs`` and ``infs`` with with average/extreme values from the same columns. It is basically a wrapper around :func:`~tsfresh.utilities.dataframe_functio... | Implement the Python class `PerColumnImputer` described below.
Class description:
Sklearn-compatible estimator, for column-wise imputing DataFrames by replacing all ``NaNs`` and ``infs`` with with average/extreme values from the same columns. It is basically a wrapper around :func:`~tsfresh.utilities.dataframe_functio... | f3a6a7c6fc851ec0ab98e7f3a227c89ca41560af | <|skeleton|>
class PerColumnImputer:
"""Sklearn-compatible estimator, for column-wise imputing DataFrames by replacing all ``NaNs`` and ``infs`` with with average/extreme values from the same columns. It is basically a wrapper around :func:`~tsfresh.utilities.dataframe_functions.impute`. Each occurring ``inf`` or `... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PerColumnImputer:
"""Sklearn-compatible estimator, for column-wise imputing DataFrames by replacing all ``NaNs`` and ``infs`` with with average/extreme values from the same columns. It is basically a wrapper around :func:`~tsfresh.utilities.dataframe_functions.impute`. Each occurring ``inf`` or ``NaN`` in the... | the_stack_v2_python_sparse | tsfresh/transformers/per_column_imputer.py | blue-yonder/tsfresh | train | 8,031 |
4327e0da4092842fe05b17a80e4c013bcad5a767 | [
"if size is None:\n self.__size = 151\nelse:\n self.__size = size\nif skip is None:\n self.__skip = 3\nelse:\n self.__skip = skip\nself.__buckets = [None] * self.__size",
"if value is None:\n return None\nelif type(value) is Student:\n return value.getId() % self.__size\nelse:\n return value ... | <|body_start_0|>
if size is None:
self.__size = 151
else:
self.__size = size
if skip is None:
self.__skip = 3
else:
self.__skip = skip
self.__buckets = [None] * self.__size
<|end_body_0|>
<|body_start_1|>
if value is None:
... | Linear probing hash table class | HashTableProbing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HashTableProbing:
"""Linear probing hash table class"""
def __init__(self, size=None, skip=None):
"""Create a hash table with buckets of a certain size. size - the number of buckets in the table, defaults to 151 skip - the number fo buckets being skipped if that bucket is full"""
... | stack_v2_sparse_classes_75kplus_train_072432 | 3,131 | no_license | [
{
"docstring": "Create a hash table with buckets of a certain size. size - the number of buckets in the table, defaults to 151 skip - the number fo buckets being skipped if that bucket is full",
"name": "__init__",
"signature": "def __init__(self, size=None, skip=None)"
},
{
"docstring": "Codes ... | 5 | stack_v2_sparse_classes_30k_train_012203 | Implement the Python class `HashTableProbing` described below.
Class description:
Linear probing hash table class
Method signatures and docstrings:
- def __init__(self, size=None, skip=None): Create a hash table with buckets of a certain size. size - the number of buckets in the table, defaults to 151 skip - the numb... | Implement the Python class `HashTableProbing` described below.
Class description:
Linear probing hash table class
Method signatures and docstrings:
- def __init__(self, size=None, skip=None): Create a hash table with buckets of a certain size. size - the number of buckets in the table, defaults to 151 skip - the numb... | ddfee86a0ca725dc98fc3387a6739493c302d689 | <|skeleton|>
class HashTableProbing:
"""Linear probing hash table class"""
def __init__(self, size=None, skip=None):
"""Create a hash table with buckets of a certain size. size - the number of buckets in the table, defaults to 151 skip - the number fo buckets being skipped if that bucket is full"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HashTableProbing:
"""Linear probing hash table class"""
def __init__(self, size=None, skip=None):
"""Create a hash table with buckets of a certain size. size - the number of buckets in the table, defaults to 151 skip - the number fo buckets being skipped if that bucket is full"""
if size ... | the_stack_v2_python_sparse | hashing/HashTableProbing.py | StevieLawrence/DataStructures | train | 0 |
bcb1f799fb994fa0855ff35aa681be1ae862ac4a | [
"body = {'modelId': task['modelId'], 'taskId': task['taskId'], 'taskType': task['taskType'], 'plateCode': 3}\nres = await self.get(session, 'task/sendPrize', body)\nif res['code'] != '0':\n println('{}, 无法领取任务:《{}》奖励!'.format(self.account, task['taskName']))\nelse:\n println('{}, 成功领取任务: 《{}》奖励!'.format(self.... | <|body_start_0|>
body = {'modelId': task['modelId'], 'taskId': task['taskId'], 'taskType': task['taskType'], 'plateCode': 3}
res = await self.get(session, 'task/sendPrize', body)
if res['code'] != '0':
println('{}, 无法领取任务:《{}》奖励!'.format(self.account, task['taskName']))
else:... | 京东到家相关活动基类 | DjBean | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DjBean:
"""京东到家相关活动基类"""
async def get_task_award(self, session, task):
"""获取任务奖励鲜豆 :param task: :param session: :return:"""
<|body_0|>
async def init(self, session):
""":return:"""
<|body_1|>
async def daily_sign(self, session):
"""每日签到 :par... | stack_v2_sparse_classes_75kplus_train_072433 | 4,828 | no_license | [
{
"docstring": "获取任务奖励鲜豆 :param task: :param session: :return:",
"name": "get_task_award",
"signature": "async def get_task_award(self, session, task)"
},
{
"docstring": ":return:",
"name": "init",
"signature": "async def init(self, session)"
},
{
"docstring": "每日签到 :param sessio... | 5 | null | Implement the Python class `DjBean` described below.
Class description:
京东到家相关活动基类
Method signatures and docstrings:
- async def get_task_award(self, session, task): 获取任务奖励鲜豆 :param task: :param session: :return:
- async def init(self, session): :return:
- async def daily_sign(self, session): 每日签到 :param session: :re... | Implement the Python class `DjBean` described below.
Class description:
京东到家相关活动基类
Method signatures and docstrings:
- async def get_task_award(self, session, task): 获取任务奖励鲜豆 :param task: :param session: :return:
- async def init(self, session): :return:
- async def daily_sign(self, session): 每日签到 :param session: :re... | 17155143372fdc0d56a353d7fbbe8c52141c6e2c | <|skeleton|>
class DjBean:
"""京东到家相关活动基类"""
async def get_task_award(self, session, task):
"""获取任务奖励鲜豆 :param task: :param session: :return:"""
<|body_0|>
async def init(self, session):
""":return:"""
<|body_1|>
async def daily_sign(self, session):
"""每日签到 :par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DjBean:
"""京东到家相关活动基类"""
async def get_task_award(self, session, task):
"""获取任务奖励鲜豆 :param task: :param session: :return:"""
body = {'modelId': task['modelId'], 'taskId': task['taskId'], 'taskType': task['taskType'], 'plateCode': 3}
res = await self.get(session, 'task/sendPrize', ... | the_stack_v2_python_sparse | dj_bean.py | binbin1213/jd_py | train | 0 |
54d0880a9f717d6c635f670547c351655ba950b2 | [
"Serializable._init(self, locals())\nsuper().__init__(min_rollouts=min_rollouts, min_steps=min_steps)\nself.env = env\nself.policy = policy\nself.bernoulli_reset = bernoulli_reset\nif self.policy.device == 'cuda':\n mp.set_start_method('spawn', force=True)\nself.pool = SamplerPool(num_envs)\nif seed is not None:... | <|body_start_0|>
Serializable._init(self, locals())
super().__init__(min_rollouts=min_rollouts, min_steps=min_steps)
self.env = env
self.policy = policy
self.bernoulli_reset = bernoulli_reset
if self.policy.device == 'cuda':
mp.set_start_method('spawn', force=... | Class for sampling from multiple environments in parallel | ParallelSampler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallelSampler:
"""Class for sampling from multiple environments in parallel"""
def __init__(self, env, policy, num_envs: int, *, min_rollouts: int=None, min_steps: int=None, bernoulli_reset: bool=None, seed: int=None):
"""Constructor :param env: environment to sample from :param po... | stack_v2_sparse_classes_75kplus_train_072434 | 4,523 | permissive | [
{
"docstring": "Constructor :param env: environment to sample from :param policy: policy to act in the environment (can also be an exploration strategy) :param num_envs: number of parallel samplers :param min_rollouts: minimum number of complete rollouts to sample. :param min_steps: minimum total number of step... | 3 | stack_v2_sparse_classes_30k_train_009830 | Implement the Python class `ParallelSampler` described below.
Class description:
Class for sampling from multiple environments in parallel
Method signatures and docstrings:
- def __init__(self, env, policy, num_envs: int, *, min_rollouts: int=None, min_steps: int=None, bernoulli_reset: bool=None, seed: int=None): Con... | Implement the Python class `ParallelSampler` described below.
Class description:
Class for sampling from multiple environments in parallel
Method signatures and docstrings:
- def __init__(self, env, policy, num_envs: int, *, min_rollouts: int=None, min_steps: int=None, bernoulli_reset: bool=None, seed: int=None): Con... | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | <|skeleton|>
class ParallelSampler:
"""Class for sampling from multiple environments in parallel"""
def __init__(self, env, policy, num_envs: int, *, min_rollouts: int=None, min_steps: int=None, bernoulli_reset: bool=None, seed: int=None):
"""Constructor :param env: environment to sample from :param po... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParallelSampler:
"""Class for sampling from multiple environments in parallel"""
def __init__(self, env, policy, num_envs: int, *, min_rollouts: int=None, min_steps: int=None, bernoulli_reset: bool=None, seed: int=None):
"""Constructor :param env: environment to sample from :param policy: policy ... | the_stack_v2_python_sparse | Pyrado/pyrado/sampling/parallel_sampler.py | jacarvalho/SimuRLacra | train | 0 |
f9244ce8cf0cb88bffeb9c890dc97da0fea29fe3 | [
"neg = (dividend < 0 or divisor < 0) and (not (dividend < 0 and divisor < 0))\nx, y = (abs(dividend), abs(divisor))\nzgen = range(y, x, y)\nzlen = len(zgen)\nif y > x:\n return 0\nif x == y:\n return -1 if neg else 1\nif zgen[-1] + y <= x:\n zlen += 1\nif neg:\n return 0 - zlen\nreturn min(max(-21474836... | <|body_start_0|>
neg = (dividend < 0 or divisor < 0) and (not (dividend < 0 and divisor < 0))
x, y = (abs(dividend), abs(divisor))
zgen = range(y, x, y)
zlen = len(zgen)
if y > x:
return 0
if x == y:
return -1 if neg else 1
if zgen[-1] + y ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def divide(self, dividend, divisor):
""":type dividend: int :type divisor: int :rtype: int"""
<|body_0|>
def divide_work(self, dividend, divisor):
""":type dividend: int :type divisor: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_072435 | 2,372 | no_license | [
{
"docstring": ":type dividend: int :type divisor: int :rtype: int",
"name": "divide",
"signature": "def divide(self, dividend, divisor)"
},
{
"docstring": ":type dividend: int :type divisor: int :rtype: int",
"name": "divide_work",
"signature": "def divide_work(self, dividend, divisor)"... | 2 | stack_v2_sparse_classes_30k_train_021090 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def divide(self, dividend, divisor): :type dividend: int :type divisor: int :rtype: int
- def divide_work(self, dividend, divisor): :type dividend: int :type divisor: int :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def divide(self, dividend, divisor): :type dividend: int :type divisor: int :rtype: int
- def divide_work(self, dividend, divisor): :type dividend: int :type divisor: int :rtype:... | 3f0ffd519404165fd1a735441b212c801fd1ad1e | <|skeleton|>
class Solution:
def divide(self, dividend, divisor):
""":type dividend: int :type divisor: int :rtype: int"""
<|body_0|>
def divide_work(self, dividend, divisor):
""":type dividend: int :type divisor: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def divide(self, dividend, divisor):
""":type dividend: int :type divisor: int :rtype: int"""
neg = (dividend < 0 or divisor < 0) and (not (dividend < 0 and divisor < 0))
x, y = (abs(dividend), abs(divisor))
zgen = range(y, x, y)
zlen = len(zgen)
if y ... | the_stack_v2_python_sparse | Problems/0001_0099/0029_Divide_Two_Integers/project_Python3/Divide_Two_Integers.py | NobuyukiInoue/LeetCode | train | 0 | |
981010cc2f88b91e8d171b7a5ca86b4b3f2d2086 | [
"if root is None:\n return 0\nmax_size = [1]\n\ndef largestBSTSubtreeHelper(root):\n if root.left is None and root.right is None:\n return (1, root.val, root.val)\n left_size, left_min, left_max = (0, root.val, root.val)\n if root.left is not None:\n left_size, left_min, left_max = largest... | <|body_start_0|>
if root is None:
return 0
max_size = [1]
def largestBSTSubtreeHelper(root):
if root.left is None and root.right is None:
return (1, root.val, root.val)
left_size, left_min, left_max = (0, root.val, root.val)
if roo... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestBSTSubtree(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def largestBSTSubtree2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
retur... | stack_v2_sparse_classes_75kplus_train_072436 | 5,231 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "largestBSTSubtree",
"signature": "def largestBSTSubtree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "largestBSTSubtree2",
"signature": "def largestBSTSubtree2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049212 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestBSTSubtree(self, root): :type root: TreeNode :rtype: int
- def largestBSTSubtree2(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestBSTSubtree(self, root): :type root: TreeNode :rtype: int
- def largestBSTSubtree2(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def ... | 0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c | <|skeleton|>
class Solution:
def largestBSTSubtree(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def largestBSTSubtree2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def largestBSTSubtree(self, root):
""":type root: TreeNode :rtype: int"""
if root is None:
return 0
max_size = [1]
def largestBSTSubtreeHelper(root):
if root.left is None and root.right is None:
return (1, root.val, root.val)
... | the_stack_v2_python_sparse | cs15211/LargestBSTSubtree.py | JulyKikuAkita/PythonPrac | train | 1 | |
ca0d77c1d52fd1ab79fbd6ac5a9e59996c39377d | [
"from collections import deque\nif not grid:\n return 0\nrows, cols, island_count = (len(grid), len(grid[0]), 0)\nq = deque([])\n\ndef helper(grid: List[List[str]], q: 'deque'):\n while q:\n r, c = q.popleft()\n for dr, dc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):\n if 0 <=... | <|body_start_0|>
from collections import deque
if not grid:
return 0
rows, cols, island_count = (len(grid), len(grid[0]), 0)
q = deque([])
def helper(grid: List[List[str]], q: 'deque'):
while q:
r, c = q.popleft()
for dr, d... | Islands | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Islands:
def total_number_(self, grid: List[List[str]]) -> str:
"""Approach: BFS Time Complexity: O(M*N) Space Complexity: O(min(M,N)) :param grid: :return:"""
<|body_0|>
def total_number(self, grid: List[List[str]]) -> str:
"""Approach: DFS/ Back tracking Time Compl... | stack_v2_sparse_classes_75kplus_train_072437 | 2,392 | no_license | [
{
"docstring": "Approach: BFS Time Complexity: O(M*N) Space Complexity: O(min(M,N)) :param grid: :return:",
"name": "total_number_",
"signature": "def total_number_(self, grid: List[List[str]]) -> str"
},
{
"docstring": "Approach: DFS/ Back tracking Time Complexity: O(M*N) Space Complexity: O(M*... | 2 | stack_v2_sparse_classes_30k_train_022296 | Implement the Python class `Islands` described below.
Class description:
Implement the Islands class.
Method signatures and docstrings:
- def total_number_(self, grid: List[List[str]]) -> str: Approach: BFS Time Complexity: O(M*N) Space Complexity: O(min(M,N)) :param grid: :return:
- def total_number(self, grid: List... | Implement the Python class `Islands` described below.
Class description:
Implement the Islands class.
Method signatures and docstrings:
- def total_number_(self, grid: List[List[str]]) -> str: Approach: BFS Time Complexity: O(M*N) Space Complexity: O(min(M,N)) :param grid: :return:
- def total_number(self, grid: List... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Islands:
def total_number_(self, grid: List[List[str]]) -> str:
"""Approach: BFS Time Complexity: O(M*N) Space Complexity: O(min(M,N)) :param grid: :return:"""
<|body_0|>
def total_number(self, grid: List[List[str]]) -> str:
"""Approach: DFS/ Back tracking Time Compl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Islands:
def total_number_(self, grid: List[List[str]]) -> str:
"""Approach: BFS Time Complexity: O(M*N) Space Complexity: O(min(M,N)) :param grid: :return:"""
from collections import deque
if not grid:
return 0
rows, cols, island_count = (len(grid), len(grid[0]), 0... | the_stack_v2_python_sparse | revisited_2021/2d_array/number_of_islands.py | Shiv2157k/leet_code | train | 1 | |
e03a48b7292927fac36bc3f4bb86685efbe147fa | [
"self.num_generations = generations\nself.max_pruning = max_pruning\nself.train_steps = train_steps\nself.pruner = LeGRPruner(pruning_ctrl, target_model)\ninit_filter_norms = self.pruner.init_filter_norms\nagent_hparams = {'num_generations': self.num_generations}\nself.agent = EvolutionOptimizer(init_filter_norms, ... | <|body_start_0|>
self.num_generations = generations
self.max_pruning = max_pruning
self.train_steps = train_steps
self.pruner = LeGRPruner(pruning_ctrl, target_model)
init_filter_norms = self.pruner.init_filter_norms
agent_hparams = {'num_generations': self.num_generation... | Class for training global ranking coefficients with Evolution optimization agent (but this agent can be easily replaced by any other RL agent with a similar interface) and LeGR-optimization environment. | LeGR | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeGR:
"""Class for training global ranking coefficients with Evolution optimization agent (but this agent can be easily replaced by any other RL agent with a similar interface) and LeGR-optimization environment."""
def __init__(self, pruning_ctrl: 'FilterPruningController', target_model: nn.... | stack_v2_sparse_classes_75kplus_train_072438 | 5,353 | permissive | [
{
"docstring": "Initializing all necessary structures for optimization- LeGREvolutionEnv environment and EvolutionOptimizer agent. :param pruning_ctrl: pruning controller, an instance of FilterPruningController class :param target_model: model for which layers ranking coefficient will be trained :param legr_ini... | 2 | stack_v2_sparse_classes_30k_train_044801 | Implement the Python class `LeGR` described below.
Class description:
Class for training global ranking coefficients with Evolution optimization agent (but this agent can be easily replaced by any other RL agent with a similar interface) and LeGR-optimization environment.
Method signatures and docstrings:
- def __ini... | Implement the Python class `LeGR` described below.
Class description:
Class for training global ranking coefficients with Evolution optimization agent (but this agent can be easily replaced by any other RL agent with a similar interface) and LeGR-optimization environment.
Method signatures and docstrings:
- def __ini... | c027c8b43c4865d46b8de01d8350dd338ec5a874 | <|skeleton|>
class LeGR:
"""Class for training global ranking coefficients with Evolution optimization agent (but this agent can be easily replaced by any other RL agent with a similar interface) and LeGR-optimization environment."""
def __init__(self, pruning_ctrl: 'FilterPruningController', target_model: nn.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LeGR:
"""Class for training global ranking coefficients with Evolution optimization agent (but this agent can be easily replaced by any other RL agent with a similar interface) and LeGR-optimization environment."""
def __init__(self, pruning_ctrl: 'FilterPruningController', target_model: nn.Module, legr_... | the_stack_v2_python_sparse | nncf/torch/pruning/filter_pruning/global_ranking/legr.py | openvinotoolkit/nncf | train | 558 |
3679abfd060c127cd3deca608367d329c05271e3 | [
"convert = lambda text: int(text) if text.isdigit() else text.lower()\nalphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]\nreturn sorted(data, key=alphanum_key)",
"files = self.sorted_alphanumeric(listdir(configs['cv_simulated']['directory']))\npath = configs['cv_simulated']['directory'] +... | <|body_start_0|>
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(data, key=alphanum_key)
<|end_body_0|>
<|body_start_1|>
files = self.sorted_alphanumeric(listdir(configs['cv_sim... | vision class for managing cv | Vision | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vision:
"""vision class for managing cv"""
def sorted_alphanumeric(cls, data):
"""sorts data alphanumerically"""
<|body_0|>
def cv_simulation(self, configs):
"""simulation for VTOL cv"""
<|body_1|>
def init_camera(cls, configs):
"""initialize... | stack_v2_sparse_classes_75kplus_train_072439 | 2,068 | no_license | [
{
"docstring": "sorts data alphanumerically",
"name": "sorted_alphanumeric",
"signature": "def sorted_alphanumeric(cls, data)"
},
{
"docstring": "simulation for VTOL cv",
"name": "cv_simulation",
"signature": "def cv_simulation(self, configs)"
},
{
"docstring": "initialize camera... | 4 | stack_v2_sparse_classes_30k_train_009725 | Implement the Python class `Vision` described below.
Class description:
vision class for managing cv
Method signatures and docstrings:
- def sorted_alphanumeric(cls, data): sorts data alphanumerically
- def cv_simulation(self, configs): simulation for VTOL cv
- def init_camera(cls, configs): initialize camera for 3DR... | Implement the Python class `Vision` described below.
Class description:
vision class for managing cv
Method signatures and docstrings:
- def sorted_alphanumeric(cls, data): sorts data alphanumerically
- def cv_simulation(self, configs): simulation for VTOL cv
- def init_camera(cls, configs): initialize camera for 3DR... | 25bd099192dfd230f70d7283c8471d66de888e6a | <|skeleton|>
class Vision:
"""vision class for managing cv"""
def sorted_alphanumeric(cls, data):
"""sorts data alphanumerically"""
<|body_0|>
def cv_simulation(self, configs):
"""simulation for VTOL cv"""
<|body_1|>
def init_camera(cls, configs):
"""initialize... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Vision:
"""vision class for managing cv"""
def sorted_alphanumeric(cls, data):
"""sorts data alphanumerically"""
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(da... | the_stack_v2_python_sparse | src/cv.py | NGCP/VTOL | train | 12 |
e13a5dba785546764b30fd6639ff865c0b48838f | [
"parser.add_argument('VIEW_ID', help='Id of the view to update.')\nparser.add_argument('--description', help='New description for the view.')\nparser.add_argument('--log-filter', help='New filter for the view.')\nutil.AddParentArgs(parser, 'view to update')\nutil.AddBucketLocationArg(parser, True, 'Location of the ... | <|body_start_0|>
parser.add_argument('VIEW_ID', help='Id of the view to update.')
parser.add_argument('--description', help='New description for the view.')
parser.add_argument('--log-filter', help='New filter for the view.')
util.AddParentArgs(parser, 'view to update')
util.AddB... | Update a view. Changes one or more properties associated with a view. | Update | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Update:
"""Update a view. Changes one or more properties associated with a view."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse names... | stack_v2_sparse_classes_75kplus_train_072440 | 3,426 | permissive | [
{
"docstring": "Register flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: The updated... | 2 | stack_v2_sparse_classes_30k_train_013726 | Implement the Python class `Update` described below.
Class description:
Update a view. Changes one or more properties associated with a view.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: ar... | Implement the Python class `Update` described below.
Class description:
Update a view. Changes one or more properties associated with a view.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: ar... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Update:
"""Update a view. Changes one or more properties associated with a view."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse names... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Update:
"""Update a view. Changes one or more properties associated with a view."""
def Args(parser):
"""Register flags for this command."""
parser.add_argument('VIEW_ID', help='Id of the view to update.')
parser.add_argument('--description', help='New description for the view.')
... | the_stack_v2_python_sparse | lib/surface/logging/views/update.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
477e8a03cb0a1e0cca9841347a9726f74ba73b9f | [
"queryset = super(CreateAndEmbedLinkView, self).get_queryset()\nif 'external_url' in self.request.POST:\n queryset = queryset.filter(link_type=Link.LINK_TYPE_EXTERNAL)\nif 'email' in self.request.POST:\n queryset = queryset.filter(link_type=Link.LINK_TYPE_EMAIL)\nreturn queryset",
"if 'external_url' in self... | <|body_start_0|>
queryset = super(CreateAndEmbedLinkView, self).get_queryset()
if 'external_url' in self.request.POST:
queryset = queryset.filter(link_type=Link.LINK_TYPE_EXTERNAL)
if 'email' in self.request.POST:
queryset = queryset.filter(link_type=Link.LINK_TYPE_EMAIL)... | View that allows a link to be created and immediately embedded in a rich-text field. | CreateAndEmbedLinkView | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateAndEmbedLinkView:
"""View that allows a link to be created and immediately embedded in a rich-text field."""
def get_queryset(self):
"""Returns queryset based on POST variables. :rtype: django.db.models.query.QuerySet."""
<|body_0|>
def form_invalid(self, form):
... | stack_v2_sparse_classes_75kplus_train_072441 | 4,768 | permissive | [
{
"docstring": "Returns queryset based on POST variables. :rtype: django.db.models.query.QuerySet.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Processes unsuccessful form submittal. :param form: the form instance. :rtype: django.http.HttpResponse.",
"na... | 3 | stack_v2_sparse_classes_30k_train_034226 | Implement the Python class `CreateAndEmbedLinkView` described below.
Class description:
View that allows a link to be created and immediately embedded in a rich-text field.
Method signatures and docstrings:
- def get_queryset(self): Returns queryset based on POST variables. :rtype: django.db.models.query.QuerySet.
- ... | Implement the Python class `CreateAndEmbedLinkView` described below.
Class description:
View that allows a link to be created and immediately embedded in a rich-text field.
Method signatures and docstrings:
- def get_queryset(self): Returns queryset based on POST variables. :rtype: django.db.models.query.QuerySet.
- ... | 096143fc2f4659f4ee9d63126fe30882950a6f59 | <|skeleton|>
class CreateAndEmbedLinkView:
"""View that allows a link to be created and immediately embedded in a rich-text field."""
def get_queryset(self):
"""Returns queryset based on POST variables. :rtype: django.db.models.query.QuerySet."""
<|body_0|>
def form_invalid(self, form):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateAndEmbedLinkView:
"""View that allows a link to be created and immediately embedded in a rich-text field."""
def get_queryset(self):
"""Returns queryset based on POST variables. :rtype: django.db.models.query.QuerySet."""
queryset = super(CreateAndEmbedLinkView, self).get_queryset()... | the_stack_v2_python_sparse | wagtailplus/wagtaillinks/views/choosers.py | MechanisM/wagtailplus | train | 10 |
b3eb44630285f3220d850c754d7de636c2e0f8cc | [
"if current_iter == 0:\n logging.debug('init a new train model')\n self.init_corpus_with_file(data_file)\n self.dir_path = dir_path\n self.model_name = model_name\n self.current_iter = current_iter\n self.iters_num = iters_num\n self.topics_num = topics_num\n self.K = topics_num\n self.tw... | <|body_start_0|>
if current_iter == 0:
logging.debug('init a new train model')
self.init_corpus_with_file(data_file)
self.dir_path = dir_path
self.model_name = model_name
self.current_iter = current_iter
self.iters_num = iters_num
... | LDA模型定义,主要实现训练、继续训练、推断的过程 | LdaModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LdaModel:
"""LDA模型定义,主要实现训练、继续训练、推断的过程"""
def init_train_model(self, dir_path, model_name, current_iter, iters_num=None, topics_num=10, twords_num=200, alpha=-1.0, beta=0.01, data_file='', prior_file=''):
""":key: 初始化训练模型,根据参数current_iter(是否等于0)决定是初始化新模型,还是加载已有模型 :key: 当初始化新模型时,除了pri... | stack_v2_sparse_classes_75kplus_train_072442 | 28,257 | no_license | [
{
"docstring": ":key: 初始化训练模型,根据参数current_iter(是否等于0)决定是初始化新模型,还是加载已有模型 :key: 当初始化新模型时,除了prior_file先验文件外,其余所有的参数都需要,且current_iter等于0 :key: 当加载已有模型时,只需要dir_path, model_name, current_iter(不等于0), iters_num, twords_num即可 :param iters_num: 可以为整数值或者“auto”",
"name": "init_train_model",
"signature": "def init_t... | 4 | stack_v2_sparse_classes_30k_train_041774 | Implement the Python class `LdaModel` described below.
Class description:
LDA模型定义,主要实现训练、继续训练、推断的过程
Method signatures and docstrings:
- def init_train_model(self, dir_path, model_name, current_iter, iters_num=None, topics_num=10, twords_num=200, alpha=-1.0, beta=0.01, data_file='', prior_file=''): :key: 初始化训练模型,根据参数c... | Implement the Python class `LdaModel` described below.
Class description:
LDA模型定义,主要实现训练、继续训练、推断的过程
Method signatures and docstrings:
- def init_train_model(self, dir_path, model_name, current_iter, iters_num=None, topics_num=10, twords_num=200, alpha=-1.0, beta=0.01, data_file='', prior_file=''): :key: 初始化训练模型,根据参数c... | ed6b3190964371797c295346378f79197a9ce05e | <|skeleton|>
class LdaModel:
"""LDA模型定义,主要实现训练、继续训练、推断的过程"""
def init_train_model(self, dir_path, model_name, current_iter, iters_num=None, topics_num=10, twords_num=200, alpha=-1.0, beta=0.01, data_file='', prior_file=''):
""":key: 初始化训练模型,根据参数current_iter(是否等于0)决定是初始化新模型,还是加载已有模型 :key: 当初始化新模型时,除了pri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LdaModel:
"""LDA模型定义,主要实现训练、继续训练、推断的过程"""
def init_train_model(self, dir_path, model_name, current_iter, iters_num=None, topics_num=10, twords_num=200, alpha=-1.0, beta=0.01, data_file='', prior_file=''):
""":key: 初始化训练模型,根据参数current_iter(是否等于0)决定是初始化新模型,还是加载已有模型 :key: 当初始化新模型时,除了prior_file先验文件外,... | the_stack_v2_python_sparse | 01-programming_language/01-python/code/python_lda.py | MachineLP/CodeFun | train | 44 |
e2b53bdb38addb8dbea319cee8cbf75d6a072d56 | [
"sub_string_list = []\nlength = 0\nlongest_substring = ''\nfor x in s:\n if x in sub_string_list:\n if len(sub_string_list) > length:\n length = len(sub_string_list)\n longest_substring = ''.join(sub_string_list)\n sub_string_list = sub_string_list[sub_string_list.index(x) + 1... | <|body_start_0|>
sub_string_list = []
length = 0
longest_substring = ''
for x in s:
if x in sub_string_list:
if len(sub_string_list) > length:
length = len(sub_string_list)
longest_substring = ''.join(sub_string_list)
... | 给定一个字符串,找出最长的字母不重复的子串,返回子串长度 Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Note that the ans... | LongestSubstringWithoutRepeatingCharacters | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LongestSubstringWithoutRepeatingCharacters:
"""给定一个字符串,找出最长的字母不重复的子串,返回子串长度 Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given ... | stack_v2_sparse_classes_75kplus_train_072443 | 2,022 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "symb",
"signature": "def symb(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002631 | Implement the Python class `LongestSubstringWithoutRepeatingCharacters` described below.
Class description:
给定一个字符串,找出最长的字母不重复的子串,返回子串长度 Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answ... | Implement the Python class `LongestSubstringWithoutRepeatingCharacters` described below.
Class description:
给定一个字符串,找出最长的字母不重复的子串,返回子串长度 Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answ... | 7a6de1767eaabb6464ea4c90756606d59b868d7c | <|skeleton|>
class LongestSubstringWithoutRepeatingCharacters:
"""给定一个字符串,找出最长的字母不重复的子串,返回子串长度 Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LongestSubstringWithoutRepeatingCharacters:
"""给定一个字符串,找出最长的字母不重复的子串,返回子串长度 Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the... | the_stack_v2_python_sparse | demo/3.LongestSubstringWithoutRepeatingCharacters.py | symbooo/LeetCodeSymb | train | 0 |
6061407931ff3a37c9a11e4ce1f5e1dca0bb1096 | [
"super(DessedDNNEncoder, self).__init__()\nself.in_channels: int = in_channels\nself.cnn_channels: int = cnn_channels\nself.dnn = DepthWiseSeparableDNN(cnn_channels=cnn_channels, cnn_dropout=0.2, inner_kernel_size=inner_kernel_size, inner_padding=inner_padding)\nself.fc_audioset = Linear(last_dim, last_dim, bias=Tr... | <|body_start_0|>
super(DessedDNNEncoder, self).__init__()
self.in_channels: int = in_channels
self.cnn_channels: int = cnn_channels
self.dnn = DepthWiseSeparableDNN(cnn_channels=cnn_channels, cnn_dropout=0.2, inner_kernel_size=inner_kernel_size, inner_padding=inner_padding)
self.... | DessedDNNEncoder | [
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DessedDNNEncoder:
def __init__(self, in_channels: int, cnn_channels: int, inner_kernel_size: int, inner_padding: int, last_dim: int) -> None:
"""DessedDNNEncoder module. :param in_channels: Input channels. :type in_channels: int :param cnn_channels: Amount of output CNN channels. :type c... | stack_v2_sparse_classes_75kplus_train_072444 | 2,163 | permissive | [
{
"docstring": "DessedDNNEncoder module. :param in_channels: Input channels. :type in_channels: int :param cnn_channels: Amount of output CNN channels. :type cnn_channels: int :param inner_kernel_size: Kernel shape/size of the second convolution for DWS-DNN. :type inner_kernel_size: int :param inner_padding: In... | 2 | stack_v2_sparse_classes_30k_train_038654 | Implement the Python class `DessedDNNEncoder` described below.
Class description:
Implement the DessedDNNEncoder class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, cnn_channels: int, inner_kernel_size: int, inner_padding: int, last_dim: int) -> None: DessedDNNEncoder module. :param in_cha... | Implement the Python class `DessedDNNEncoder` described below.
Class description:
Implement the DessedDNNEncoder class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, cnn_channels: int, inner_kernel_size: int, inner_padding: int, last_dim: int) -> None: DessedDNNEncoder module. :param in_cha... | c78458ac0887851a743b7f47101b0fff97724b4f | <|skeleton|>
class DessedDNNEncoder:
def __init__(self, in_channels: int, cnn_channels: int, inner_kernel_size: int, inner_padding: int, last_dim: int) -> None:
"""DessedDNNEncoder module. :param in_channels: Input channels. :type in_channels: int :param cnn_channels: Amount of output CNN channels. :type c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DessedDNNEncoder:
def __init__(self, in_channels: int, cnn_channels: int, inner_kernel_size: int, inner_padding: int, last_dim: int) -> None:
"""DessedDNNEncoder module. :param in_channels: Input channels. :type in_channels: int :param cnn_channels: Amount of output CNN channels. :type cnn_channels: i... | the_stack_v2_python_sparse | modules/dessed_dnn_encoder.py | audio-captioning/wavetransformer | train | 0 | |
9892ad5ee58e7127f37626b9651d03f46fb4c87e | [
"self.global_configs = global_configs\nself.scanner_configs = scanner_configs\nself.service_config = service_config\nself.model_name = model_name\nself.snapshot_timestamp = snapshot_timestamp\nself.scanner_name = scanner_name",
"runnable_scanners = []\nif self.scanner_name:\n scanner = self._instantiate_scanne... | <|body_start_0|>
self.global_configs = global_configs
self.scanner_configs = scanner_configs
self.service_config = service_config
self.model_name = model_name
self.snapshot_timestamp = snapshot_timestamp
self.scanner_name = scanner_name
<|end_body_0|>
<|body_start_1|>
... | Scanner Builder. | ScannerBuilder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScannerBuilder:
"""Scanner Builder."""
def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, scanner_name=None):
"""Initialize the scanner builder. Args: global_configs (dict): Global configurations. scanner_configs (dict): Scanner config... | stack_v2_sparse_classes_75kplus_train_072445 | 5,021 | permissive | [
{
"docstring": "Initialize the scanner builder. Args: global_configs (dict): Global configurations. scanner_configs (dict): Scanner configurations. service_config (ServiceConfig): Service configuration. model_name (str): name of the data model snapshot_timestamp (str): The snapshot timestamp scanner_name (str):... | 3 | stack_v2_sparse_classes_30k_train_004379 | Implement the Python class `ScannerBuilder` described below.
Class description:
Scanner Builder.
Method signatures and docstrings:
- def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, scanner_name=None): Initialize the scanner builder. Args: global_configs (dict): Glob... | Implement the Python class `ScannerBuilder` described below.
Class description:
Scanner Builder.
Method signatures and docstrings:
- def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, scanner_name=None): Initialize the scanner builder. Args: global_configs (dict): Glob... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class ScannerBuilder:
"""Scanner Builder."""
def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, scanner_name=None):
"""Initialize the scanner builder. Args: global_configs (dict): Global configurations. scanner_configs (dict): Scanner config... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScannerBuilder:
"""Scanner Builder."""
def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, scanner_name=None):
"""Initialize the scanner builder. Args: global_configs (dict): Global configurations. scanner_configs (dict): Scanner configurations. ser... | the_stack_v2_python_sparse | google/cloud/forseti/scanner/scanner_builder.py | kevensen/forseti-security | train | 1 |
7f036376eb6a439bae7ab6ac06f31b6bd1d00a55 | [
"if params.shape[-1] != 4 or len(params.shape) > 2:\n raise ValueError('params must be of shape (B, 4) for PINHOLE Camera')\nsuper().__init__(AffineTransform(), Z1Projection(), image_size, params)",
"z = zeros_like(self.fx)\nrow1 = stack((self.fx, z, self.cx), -1)\nrow2 = stack((z, self.fy, self.cy), -1)\nrow3... | <|body_start_0|>
if params.shape[-1] != 4 or len(params.shape) > 2:
raise ValueError('params must be of shape (B, 4) for PINHOLE Camera')
super().__init__(AffineTransform(), Z1Projection(), image_size, params)
<|end_body_0|>
<|body_start_1|>
z = zeros_like(self.fx)
row1 = st... | Class to represent Pinhole Camera Model. The pinhole camera model describes the mathematical relationship between the coordinates of a point in three-dimensional space and its projection onto the image plane of an ideal pinhole camera, where the camera aperture is described as a point and no lenses are used to focus li... | PinholeModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PinholeModel:
"""Class to represent Pinhole Camera Model. The pinhole camera model describes the mathematical relationship between the coordinates of a point in three-dimensional space and its projection onto the image plane of an ideal pinhole camera, where the camera aperture is described as a ... | stack_v2_sparse_classes_75kplus_train_072446 | 11,694 | permissive | [
{
"docstring": "Constructor method for PinholeModel class. Args: image_size: Image size params: Camera parameters of shape :math:`(B, 4)` of the form :math:`(fx, fy, cx, cy)`.",
"name": "__init__",
"signature": "def __init__(self, image_size: ImageSize, params: Tensor) -> None"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_009661 | Implement the Python class `PinholeModel` described below.
Class description:
Class to represent Pinhole Camera Model. The pinhole camera model describes the mathematical relationship between the coordinates of a point in three-dimensional space and its projection onto the image plane of an ideal pinhole camera, where... | Implement the Python class `PinholeModel` described below.
Class description:
Class to represent Pinhole Camera Model. The pinhole camera model describes the mathematical relationship between the coordinates of a point in three-dimensional space and its projection onto the image plane of an ideal pinhole camera, where... | 1e0f8baa7318c05b17ea6dbb48605691bca8972f | <|skeleton|>
class PinholeModel:
"""Class to represent Pinhole Camera Model. The pinhole camera model describes the mathematical relationship between the coordinates of a point in three-dimensional space and its projection onto the image plane of an ideal pinhole camera, where the camera aperture is described as a ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PinholeModel:
"""Class to represent Pinhole Camera Model. The pinhole camera model describes the mathematical relationship between the coordinates of a point in three-dimensional space and its projection onto the image plane of an ideal pinhole camera, where the camera aperture is described as a point and no ... | the_stack_v2_python_sparse | kornia/sensors/camera/camera_model.py | kornia/kornia | train | 7,351 |
09ceeff88db61da4ecf6a84878bedc5302bdf39a | [
"if self.request.version == 'v6':\n return IngestDetailsSerializerV6\nelif self.request.version == 'v7':\n return IngestDetailsSerializerV6",
"if request.version == 'v6' or request.version == 'v7':\n return self.retrieve_v6(request, ingest_id)\nraise Http404()",
"try:\n is_staff = False\n if requ... | <|body_start_0|>
if self.request.version == 'v6':
return IngestDetailsSerializerV6
elif self.request.version == 'v7':
return IngestDetailsSerializerV6
<|end_body_0|>
<|body_start_1|>
if request.version == 'v6' or request.version == 'v7':
return self.retrieve_... | This view is the endpoint for retrieving/updating details of an ingest. | IngestDetailsView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IngestDetailsView:
"""This view is the endpoint for retrieving/updating details of an ingest."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
<|body_0|>
def retrieve(self, request, ingest_id=None,... | stack_v2_sparse_classes_75kplus_train_072447 | 30,689 | permissive | [
{
"docstring": "Returns the appropriate serializer based off the requests version of the REST API",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Determine api version and call specific method :param request: the HTTP GET request :type request: ... | 3 | stack_v2_sparse_classes_30k_test_001345 | Implement the Python class `IngestDetailsView` described below.
Class description:
This view is the endpoint for retrieving/updating details of an ingest.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def retriev... | Implement the Python class `IngestDetailsView` described below.
Class description:
This view is the endpoint for retrieving/updating details of an ingest.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def retriev... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class IngestDetailsView:
"""This view is the endpoint for retrieving/updating details of an ingest."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
<|body_0|>
def retrieve(self, request, ingest_id=None,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IngestDetailsView:
"""This view is the endpoint for retrieving/updating details of an ingest."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
if self.request.version == 'v6':
return IngestDetailsSeriali... | the_stack_v2_python_sparse | scale/ingest/views.py | kfconsultant/scale | train | 0 |
53cbfd730196465980ecafc646c9872812d24bab | [
"start = sel_day.strftime('%Y%m%d')\nstart_time = pd.to_datetime(f'{start} 00:00:00')\nend = (sel_day + pd.to_timedelta(1, 'D')).strftime('%Y%m%d')\nend_time = pd.to_datetime(f'{end} 00:00:00')\ntime_bins = pd.date_range(start_time, end_time, freq=freq)\nreturn time_bins",
"if file_type == '12-00':\n url = 'ht... | <|body_start_0|>
start = sel_day.strftime('%Y%m%d')
start_time = pd.to_datetime(f'{start} 00:00:00')
end = (sel_day + pd.to_timedelta(1, 'D')).strftime('%Y%m%d')
end_time = pd.to_datetime(f'{end} 00:00:00')
time_bins = pd.date_range(start_time, end_time, freq=freq)
return... | This class contains useful tools | Util | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Util:
"""This class contains useful tools"""
def get_time_bins(sel_day, freq='10min'):
"""Bins estimation Creating time bins for a given day and time resolution"""
<|body_0|>
def get_sample_data(sample_path, file_type):
"""Downloading data It downloads the sample... | stack_v2_sparse_classes_75kplus_train_072448 | 5,444 | permissive | [
{
"docstring": "Bins estimation Creating time bins for a given day and time resolution",
"name": "get_time_bins",
"signature": "def get_time_bins(sel_day, freq='10min')"
},
{
"docstring": "Downloading data It downloads the sample needed for the examples.",
"name": "get_sample_data",
"sig... | 3 | null | Implement the Python class `Util` described below.
Class description:
This class contains useful tools
Method signatures and docstrings:
- def get_time_bins(sel_day, freq='10min'): Bins estimation Creating time bins for a given day and time resolution
- def get_sample_data(sample_path, file_type): Downloading data It... | Implement the Python class `Util` described below.
Class description:
This class contains useful tools
Method signatures and docstrings:
- def get_time_bins(sel_day, freq='10min'): Bins estimation Creating time bins for a given day and time resolution
- def get_sample_data(sample_path, file_type): Downloading data It... | b6121bfe3a9dca0cbd6b19884372d5eefeea085f | <|skeleton|>
class Util:
"""This class contains useful tools"""
def get_time_bins(sel_day, freq='10min'):
"""Bins estimation Creating time bins for a given day and time resolution"""
<|body_0|>
def get_sample_data(sample_path, file_type):
"""Downloading data It downloads the sample... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Util:
"""This class contains useful tools"""
def get_time_bins(sel_day, freq='10min'):
"""Bins estimation Creating time bins for a given day and time resolution"""
start = sel_day.strftime('%Y%m%d')
start_time = pd.to_datetime(f'{start} 00:00:00')
end = (sel_day + pd.to_ti... | the_stack_v2_python_sparse | lidarSuit/utilities.py | jdiasn/lidarSuit | train | 11 |
59cb629ba2c0377424c24dad821472ceb67d22e2 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn NetworkConnection()",
"from .connection_direction import ConnectionDirection\nfrom .connection_status import ConnectionStatus\nfrom .security_network_protocol import SecurityNetworkProtocol\nfrom .connection_direction import Connection... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return NetworkConnection()
<|end_body_0|>
<|body_start_1|>
from .connection_direction import ConnectionDirection
from .connection_status import ConnectionStatus
from .security_network_p... | NetworkConnection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkConnection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object... | stack_v2_sparse_classes_75kplus_train_072449 | 9,109 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: NetworkConnection",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_v... | 3 | stack_v2_sparse_classes_30k_train_029567 | Implement the Python class `NetworkConnection` described below.
Class description:
Implement the NetworkConnection class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection: Creates a new instance of the appropriate class based on discrim... | Implement the Python class `NetworkConnection` described below.
Class description:
Implement the NetworkConnection class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection: Creates a new instance of the appropriate class based on discrim... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class NetworkConnection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NetworkConnection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Netw... | the_stack_v2_python_sparse | msgraph/generated/models/network_connection.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
209eb70c13499fa687c92769f6111a196c4fe5c7 | [
"super().__init__(grid_proportion)\nself.logo_path = logo_path\nself.major_line = major_line\nself.minor_line = minor_line\nif date is None:\n date = datetime.date.today()\nself.date = date_to_str(date, DateFormat.LONG_DATE)",
"env = templates.environment\ntemplate = env.get_template('page_header.html')\nretur... | <|body_start_0|>
super().__init__(grid_proportion)
self.logo_path = logo_path
self.major_line = major_line
self.minor_line = minor_line
if date is None:
date = datetime.date.today()
self.date = date_to_str(date, DateFormat.LONG_DATE)
<|end_body_0|>
<|body_sta... | PageHeaderElement | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PageHeaderElement:
def __init__(self, logo_path: str=None, major_line: str='', minor_line: str='', date: datetime=None, grid_proportion: GridProportion=GridProportion.Eight):
"""A stylised header element, consists of a major title (on left and right), subtitle and logo (loaded from the s... | stack_v2_sparse_classes_75kplus_train_072450 | 2,260 | permissive | [
{
"docstring": "A stylised header element, consists of a major title (on left and right), subtitle and logo (loaded from the specified path).",
"name": "__init__",
"signature": "def __init__(self, logo_path: str=None, major_line: str='', minor_line: str='', date: datetime=None, grid_proportion: GridProp... | 2 | null | Implement the Python class `PageHeaderElement` described below.
Class description:
Implement the PageHeaderElement class.
Method signatures and docstrings:
- def __init__(self, logo_path: str=None, major_line: str='', minor_line: str='', date: datetime=None, grid_proportion: GridProportion=GridProportion.Eight): A st... | Implement the Python class `PageHeaderElement` described below.
Class description:
Implement the PageHeaderElement class.
Method signatures and docstrings:
- def __init__(self, logo_path: str=None, major_line: str='', minor_line: str='', date: datetime=None, grid_proportion: GridProportion=GridProportion.Eight): A st... | f707e51bc2ff45f6e46dcdd24d59d83ce7dc4f94 | <|skeleton|>
class PageHeaderElement:
def __init__(self, logo_path: str=None, major_line: str='', minor_line: str='', date: datetime=None, grid_proportion: GridProportion=GridProportion.Eight):
"""A stylised header element, consists of a major title (on left and right), subtitle and logo (loaded from the s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PageHeaderElement:
def __init__(self, logo_path: str=None, major_line: str='', minor_line: str='', date: datetime=None, grid_proportion: GridProportion=GridProportion.Eight):
"""A stylised header element, consists of a major title (on left and right), subtitle and logo (loaded from the specified path)... | the_stack_v2_python_sparse | qf_lib/documents_utils/document_exporting/element/page_header.py | quarkfin/qf-lib | train | 379 | |
c336e6fedebb6933da3335d5303ef5256ba154b4 | [
"team = ProjectUsersAssociation.find_all_by_project_id(project_id)\ndata = TeamSchema().dump(team, many=True)\nuser = g.user\nfor team_member in data:\n team_member['isCurrentUser'] = team_member['userId'] == user.id\nreturn (jsonify({'team': data}), HTTPStatus.OK)",
"team_json = request.get_json()\ntry:\n ... | <|body_start_0|>
team = ProjectUsersAssociation.find_all_by_project_id(project_id)
data = TeamSchema().dump(team, many=True)
user = g.user
for team_member in data:
team_member['isCurrentUser'] = team_member['userId'] == user.id
return (jsonify({'team': data}), HTTPSta... | Resource for managing team. | TeamResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamResource:
"""Resource for managing team."""
def get(project_id):
"""Get team."""
<|body_0|>
def post(project_id):
"""Post a new team using the request body."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
team = ProjectUsersAssociation.find_... | stack_v2_sparse_classes_75kplus_train_072451 | 6,372 | permissive | [
{
"docstring": "Get team.",
"name": "get",
"signature": "def get(project_id)"
},
{
"docstring": "Post a new team using the request body.",
"name": "post",
"signature": "def post(project_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013294 | Implement the Python class `TeamResource` described below.
Class description:
Resource for managing team.
Method signatures and docstrings:
- def get(project_id): Get team.
- def post(project_id): Post a new team using the request body. | Implement the Python class `TeamResource` described below.
Class description:
Resource for managing team.
Method signatures and docstrings:
- def get(project_id): Get team.
- def post(project_id): Post a new team using the request body.
<|skeleton|>
class TeamResource:
"""Resource for managing team."""
def ... | 3bfe09c100a0f5b98d61228324336d5f45ad93ad | <|skeleton|>
class TeamResource:
"""Resource for managing team."""
def get(project_id):
"""Get team."""
<|body_0|>
def post(project_id):
"""Post a new team using the request body."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TeamResource:
"""Resource for managing team."""
def get(project_id):
"""Get team."""
team = ProjectUsersAssociation.find_all_by_project_id(project_id)
data = TeamSchema().dump(team, many=True)
user = g.user
for team_member in data:
team_member['isCurren... | the_stack_v2_python_sparse | selfservice-api/src/selfservice_api/resources/team.py | bcgov/BCSC-SS | train | 2 |
013bc5a866004a31b76988e120380745f7db745f | [
"parser = self._parser.add_parser('start', help='Start the Asciipic worker.')\nparser.add_argument('--redis_port', dest='redis_port', type=int, default=CONFIG.worker.redis_port, help='The port that should be used by the current worker.')\nparser.add_argument('--redis_host', dest='redis_host', type=str, default=CONF... | <|body_start_0|>
parser = self._parser.add_parser('start', help='Start the Asciipic worker.')
parser.add_argument('--redis_port', dest='redis_port', type=int, default=CONFIG.worker.redis_port, help='The port that should be used by the current worker.')
parser.add_argument('--redis_host', dest='r... | Start the Asciipic API. | Start | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Start:
"""Start the Asciipic API."""
def setup(self):
"""Extend the parser configuration in order to expose this command."""
<|body_0|>
def _work(self):
"""Start the Asciipic Worker."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
parser = self.... | stack_v2_sparse_classes_75kplus_train_072452 | 3,888 | permissive | [
{
"docstring": "Extend the parser configuration in order to expose this command.",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Start the Asciipic Worker.",
"name": "_work",
"signature": "def _work(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049197 | Implement the Python class `Start` described below.
Class description:
Start the Asciipic API.
Method signatures and docstrings:
- def setup(self): Extend the parser configuration in order to expose this command.
- def _work(self): Start the Asciipic Worker. | Implement the Python class `Start` described below.
Class description:
Start the Asciipic API.
Method signatures and docstrings:
- def setup(self): Extend the parser configuration in order to expose this command.
- def _work(self): Start the Asciipic Worker.
<|skeleton|>
class Start:
"""Start the Asciipic API.""... | 88ffe70c7ded003c9a2dc497c1f1105f57a533f2 | <|skeleton|>
class Start:
"""Start the Asciipic API."""
def setup(self):
"""Extend the parser configuration in order to expose this command."""
<|body_0|>
def _work(self):
"""Start the Asciipic Worker."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Start:
"""Start the Asciipic API."""
def setup(self):
"""Extend the parser configuration in order to expose this command."""
parser = self._parser.add_parser('start', help='Start the Asciipic worker.')
parser.add_argument('--redis_port', dest='redis_port', type=int, default=CONFIG... | the_stack_v2_python_sparse | asciipic/cli/commands/worker.py | mateimicu/asciipic | train | 0 |
b99c93fd9ed6c267aa22eb43e1ffa19090f91057 | [
"owner_set = Resource.objects.filter(owners=self.request.user)\nmaintainer_set = Resource.objects.filter(maintainers=self.request.user)\nreader_set = Resource.objects.filter(readers=self.request.user)\ndeletion_set = Resource.objects.filter(deletionrequest__sender=self.request.user)\naccess_set = Resource.objects.f... | <|body_start_0|>
owner_set = Resource.objects.filter(owners=self.request.user)
maintainer_set = Resource.objects.filter(maintainers=self.request.user)
reader_set = Resource.objects.filter(readers=self.request.user)
deletion_set = Resource.objects.filter(deletionrequest__sender=self.reque... | MyResourcesView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyResourcesView:
def get_queryset(self):
"""@return: @rtype:"""
<|body_0|>
def get_context_data(self, **kwargs):
"""@param kwargs: @type kwargs: @return: @rtype:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
owner_set = Resource.objects.filter(own... | stack_v2_sparse_classes_75kplus_train_072453 | 49,724 | permissive | [
{
"docstring": "@return: @rtype:",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "@param kwargs: @type kwargs: @return: @rtype:",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | null | Implement the Python class `MyResourcesView` described below.
Class description:
Implement the MyResourcesView class.
Method signatures and docstrings:
- def get_queryset(self): @return: @rtype:
- def get_context_data(self, **kwargs): @param kwargs: @type kwargs: @return: @rtype: | Implement the Python class `MyResourcesView` described below.
Class description:
Implement the MyResourcesView class.
Method signatures and docstrings:
- def get_queryset(self): @return: @rtype:
- def get_context_data(self, **kwargs): @param kwargs: @type kwargs: @return: @rtype:
<|skeleton|>
class MyResourcesView:
... | 9055095cbe796d6d6e2ce744d727ff60e27e09ed | <|skeleton|>
class MyResourcesView:
def get_queryset(self):
"""@return: @rtype:"""
<|body_0|>
def get_context_data(self, **kwargs):
"""@param kwargs: @type kwargs: @return: @rtype:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyResourcesView:
def get_queryset(self):
"""@return: @rtype:"""
owner_set = Resource.objects.filter(owners=self.request.user)
maintainer_set = Resource.objects.filter(maintainers=self.request.user)
reader_set = Resource.objects.filter(readers=self.request.user)
deletion... | the_stack_v2_python_sparse | author_manage/views.py | VForWaTer/vforwater-portal | train | 8 | |
80c6b8358432cf7154f8f49aee162932d6dd34a4 | [
"super(PipedImagerPQProcess, self).__init__(group=None, target=None, name='PipedImagerPQ')\nself.__cmndpipe = cmndpipe\nself.__rspdpipe = rspdpipe\nself.__app = None\nself.__viewer = None",
"self.__app = QApplication(['PipedImagerPQ'])\nself.__viewer = PipedImagerPQ(self.__cmndpipe, self.__rspdpipe)\nmyresult = s... | <|body_start_0|>
super(PipedImagerPQProcess, self).__init__(group=None, target=None, name='PipedImagerPQ')
self.__cmndpipe = cmndpipe
self.__rspdpipe = rspdpipe
self.__app = None
self.__viewer = None
<|end_body_0|>
<|body_start_1|>
self.__app = QApplication(['PipedImager... | A Process specifically tailored for creating a PipedImagerPQ. | PipedImagerPQProcess | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipedImagerPQProcess:
"""A Process specifically tailored for creating a PipedImagerPQ."""
def __init__(self, cmndpipe, rspdpipe):
"""Create a Process that will produce a PipedImagerPQ attached to the given Pipes when run."""
<|body_0|>
def run(self):
"""Create a ... | stack_v2_sparse_classes_75kplus_train_072454 | 40,479 | permissive | [
{
"docstring": "Create a Process that will produce a PipedImagerPQ attached to the given Pipes when run.",
"name": "__init__",
"signature": "def __init__(self, cmndpipe, rspdpipe)"
},
{
"docstring": "Create a PipedImagerPQ that is attached to the Pipe of this instance.",
"name": "run",
"... | 2 | stack_v2_sparse_classes_30k_train_046036 | Implement the Python class `PipedImagerPQProcess` described below.
Class description:
A Process specifically tailored for creating a PipedImagerPQ.
Method signatures and docstrings:
- def __init__(self, cmndpipe, rspdpipe): Create a Process that will produce a PipedImagerPQ attached to the given Pipes when run.
- def... | Implement the Python class `PipedImagerPQProcess` described below.
Class description:
A Process specifically tailored for creating a PipedImagerPQ.
Method signatures and docstrings:
- def __init__(self, cmndpipe, rspdpipe): Create a Process that will produce a PipedImagerPQ attached to the given Pipes when run.
- def... | f21d878c776286ee333a44b99e0b31ad53d8917a | <|skeleton|>
class PipedImagerPQProcess:
"""A Process specifically tailored for creating a PipedImagerPQ."""
def __init__(self, cmndpipe, rspdpipe):
"""Create a Process that will produce a PipedImagerPQ attached to the given Pipes when run."""
<|body_0|>
def run(self):
"""Create a ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PipedImagerPQProcess:
"""A Process specifically tailored for creating a PipedImagerPQ."""
def __init__(self, cmndpipe, rspdpipe):
"""Create a Process that will produce a PipedImagerPQ attached to the given Pipes when run."""
super(PipedImagerPQProcess, self).__init__(group=None, target=No... | the_stack_v2_python_sparse | pviewmod/pipedimagerpq.py | NOAA-PMEL/PyFerret | train | 61 |
60bebdb674c976fd92bd1d7304e6dd380e1371db | [
"if ctx.config.get('csrf', True):\n headers = request.headers\n provided_token = _extract_token_from_headers(headers)\n if provided_token is None:\n raise CsrfTokenRequired()\n if provided_token not in _get_tokens():\n raise CsrfTokenInvalid()",
"new_token = _generate_token()\n_store_tok... | <|body_start_0|>
if ctx.config.get('csrf', True):
headers = request.headers
provided_token = _extract_token_from_headers(headers)
if provided_token is None:
raise CsrfTokenRequired()
if provided_token not in _get_tokens():
raise Csr... | A CSRF protection plugin for Micron. | Plugin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Plugin:
"""A CSRF protection plugin for Micron."""
def check_access(self, ctx):
"""Checks for an CSRF token in the CSRF token request header and checks if its value is a valid CSRF token."""
<|body_0|>
def process_response(self, ctx):
"""Generates a new CSRF toke... | stack_v2_sparse_classes_75kplus_train_072455 | 7,949 | permissive | [
{
"docstring": "Checks for an CSRF token in the CSRF token request header and checks if its value is a valid CSRF token.",
"name": "check_access",
"signature": "def check_access(self, ctx)"
},
{
"docstring": "Generates a new CSRF token, adds it to the session data and hands over the token to the... | 2 | stack_v2_sparse_classes_30k_train_049638 | Implement the Python class `Plugin` described below.
Class description:
A CSRF protection plugin for Micron.
Method signatures and docstrings:
- def check_access(self, ctx): Checks for an CSRF token in the CSRF token request header and checks if its value is a valid CSRF token.
- def process_response(self, ctx): Gene... | Implement the Python class `Plugin` described below.
Class description:
A CSRF protection plugin for Micron.
Method signatures and docstrings:
- def check_access(self, ctx): Checks for an CSRF token in the CSRF token request header and checks if its value is a valid CSRF token.
- def process_response(self, ctx): Gene... | 1cfa6b021152142556d67a084e01083dbb032dce | <|skeleton|>
class Plugin:
"""A CSRF protection plugin for Micron."""
def check_access(self, ctx):
"""Checks for an CSRF token in the CSRF token request header and checks if its value is a valid CSRF token."""
<|body_0|>
def process_response(self, ctx):
"""Generates a new CSRF toke... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Plugin:
"""A CSRF protection plugin for Micron."""
def check_access(self, ctx):
"""Checks for an CSRF token in the CSRF token request header and checks if its value is a valid CSRF token."""
if ctx.config.get('csrf', True):
headers = request.headers
provided_token ... | the_stack_v2_python_sparse | ATTIC/csrf-plugin.py | mmakaay/flask_micron | train | 4 |
d83d45c3bcd021bc6231bdd9c1c2e1495b60626f | [
"super().__init__(cfg=cfg, parent=parent, **kwargs)\ncanonical_box_size = (int(cfg.canonical_box_size * canonical_box_scale),)\ncanonical_level = (cfg.canonical_level,)\nif isinstance(output_size, int):\n output_size = (output_size, output_size)\nassert len(output_size) == 2\nassert isinstance(output_size[0], in... | <|body_start_0|>
super().__init__(cfg=cfg, parent=parent, **kwargs)
canonical_box_size = (int(cfg.canonical_box_size * canonical_box_scale),)
canonical_level = (cfg.canonical_level,)
if isinstance(output_size, int):
output_size = (output_size, output_size)
assert len(... | Region of interest feature map pooler that supports pooling from one or more feature maps. | ROIPooler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ROIPooler:
"""Region of interest feature map pooler that supports pooling from one or more feature maps."""
def __init__(self, cfg, parent, output_size=[7, 7], bin_size=[2, 2], pooler_type='ROIAlign', canonical_box_scale=1.0, **kwargs):
"""Args: output_size (int, tuple[int] or list[i... | stack_v2_sparse_classes_75kplus_train_072456 | 6,559 | permissive | [
{
"docstring": "Args: output_size (int, tuple[int] or list[int]): output size of the pooled region, e.g., 14 x 14. If tuple or list is given, the length must be 2. pooler_type (string): Name of the type of pooling operation that should be applied. For instance, \"ROIPool\" or \"ROIAlign\". cfg.canonical_box_siz... | 2 | null | Implement the Python class `ROIPooler` described below.
Class description:
Region of interest feature map pooler that supports pooling from one or more feature maps.
Method signatures and docstrings:
- def __init__(self, cfg, parent, output_size=[7, 7], bin_size=[2, 2], pooler_type='ROIAlign', canonical_box_scale=1.0... | Implement the Python class `ROIPooler` described below.
Class description:
Region of interest feature map pooler that supports pooling from one or more feature maps.
Method signatures and docstrings:
- def __init__(self, cfg, parent, output_size=[7, 7], bin_size=[2, 2], pooler_type='ROIAlign', canonical_box_scale=1.0... | 8fbf060088816cd1a366d7cbd5dfe1a0e00f8d79 | <|skeleton|>
class ROIPooler:
"""Region of interest feature map pooler that supports pooling from one or more feature maps."""
def __init__(self, cfg, parent, output_size=[7, 7], bin_size=[2, 2], pooler_type='ROIAlign', canonical_box_scale=1.0, **kwargs):
"""Args: output_size (int, tuple[int] or list[i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ROIPooler:
"""Region of interest feature map pooler that supports pooling from one or more feature maps."""
def __init__(self, cfg, parent, output_size=[7, 7], bin_size=[2, 2], pooler_type='ROIAlign', canonical_box_scale=1.0, **kwargs):
"""Args: output_size (int, tuple[int] or list[int]): output ... | the_stack_v2_python_sparse | object_detection2/modeling/poolers.py | seantangtao/wml | train | 0 |
e0fe56975cc73becdc5b8364b51699dd7c60ce9c | [
"if self.request.user.is_superuser:\n return models.Workflow.objects.all()\nreturn models.Workflow.objects.filter(Q(user=self.request.user) | Q(shared=self.request.user)).distinct()",
"if self.request.user.is_superuser:\n serializer.save()\nelse:\n serializer.save(user=self.request.user)"
] | <|body_start_0|>
if self.request.user.is_superuser:
return models.Workflow.objects.all()
return models.Workflow.objects.filter(Q(user=self.request.user) | Q(shared=self.request.user)).distinct()
<|end_body_0|>
<|body_start_1|>
if self.request.user.is_superuser:
serialize... | Access the workflow. get: Return a list of available workflows post: Create a new workflow given name, description and attributes | WorkflowAPIListCreate | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkflowAPIListCreate:
"""Access the workflow. get: Return a list of available workflows post: Create a new workflow given name, description and attributes"""
def get_queryset(self):
"""Access the required workflow."""
<|body_0|>
def perform_create(self, serializer):
... | stack_v2_sparse_classes_75kplus_train_072457 | 4,435 | permissive | [
{
"docstring": "Access the required workflow.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Create the new workflow.",
"name": "perform_create",
"signature": "def perform_create(self, serializer)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054266 | Implement the Python class `WorkflowAPIListCreate` described below.
Class description:
Access the workflow. get: Return a list of available workflows post: Create a new workflow given name, description and attributes
Method signatures and docstrings:
- def get_queryset(self): Access the required workflow.
- def perfo... | Implement the Python class `WorkflowAPIListCreate` described below.
Class description:
Access the workflow. get: Return a list of available workflows post: Create a new workflow given name, description and attributes
Method signatures and docstrings:
- def get_queryset(self): Access the required workflow.
- def perfo... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class WorkflowAPIListCreate:
"""Access the workflow. get: Return a list of available workflows post: Create a new workflow given name, description and attributes"""
def get_queryset(self):
"""Access the required workflow."""
<|body_0|>
def perform_create(self, serializer):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkflowAPIListCreate:
"""Access the workflow. get: Return a list of available workflows post: Create a new workflow given name, description and attributes"""
def get_queryset(self):
"""Access the required workflow."""
if self.request.user.is_superuser:
return models.Workflow.... | the_stack_v2_python_sparse | ontask/workflow/api.py | abelardopardo/ontask_b | train | 43 |
8312b62875618ffa1551588ca99d8077254ec440 | [
"Delay.__init__(self, nome, fgva, next_event)\nself._nome_da_entidade = nome_entidade\nself._quantos_por_vez = quantos_por_vez\nself._quantas_vezes = quantas_vezes\nself.add_evento_futuro(0, None, nome)\npass",
"for _ in range(self._quantos_por_vez):\n self.add_evento_futuro(0, Entity(self._nome_da_entidade), ... | <|body_start_0|>
Delay.__init__(self, nome, fgva, next_event)
self._nome_da_entidade = nome_entidade
self._quantos_por_vez = quantos_por_vez
self._quantas_vezes = quantas_vezes
self.add_evento_futuro(0, None, nome)
pass
<|end_body_0|>
<|body_start_1|>
for _ in ra... | Classe responsável por criar novas entidades. @cvar _nome_da_entidade: Nome da entidade a ser criada @cvar _quantos_por_vez: Quantas entidades serão criadas por evento @cvar _quantas_vezes: Quantas vezes o evento será executado | Create | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Create:
"""Classe responsável por criar novas entidades. @cvar _nome_da_entidade: Nome da entidade a ser criada @cvar _quantos_por_vez: Quantas entidades serão criadas por evento @cvar _quantas_vezes: Quantas vezes o evento será executado"""
def __init__(self, nome, next_event, fgva, nome_en... | stack_v2_sparse_classes_75kplus_train_072458 | 2,415 | no_license | [
{
"docstring": "Construtor do evento 'create' @param nome: Nome do módulo @type nome: string @param fgva: Gerador de variáveis aleatórias para o delay entre criações de entidades. @type fgva: Simulador.FGVA @param nome_entidade: Nome da entidade a ser criada @type nome_entidade: string @param quantos_por_vez: Q... | 2 | null | Implement the Python class `Create` described below.
Class description:
Classe responsável por criar novas entidades. @cvar _nome_da_entidade: Nome da entidade a ser criada @cvar _quantos_por_vez: Quantas entidades serão criadas por evento @cvar _quantas_vezes: Quantas vezes o evento será executado
Method signatures ... | Implement the Python class `Create` described below.
Class description:
Classe responsável por criar novas entidades. @cvar _nome_da_entidade: Nome da entidade a ser criada @cvar _quantos_por_vez: Quantas entidades serão criadas por evento @cvar _quantas_vezes: Quantas vezes o evento será executado
Method signatures ... | f914f50ab02f222b13aa35ae2dc0be30ba309925 | <|skeleton|>
class Create:
"""Classe responsável por criar novas entidades. @cvar _nome_da_entidade: Nome da entidade a ser criada @cvar _quantos_por_vez: Quantas entidades serão criadas por evento @cvar _quantas_vezes: Quantas vezes o evento será executado"""
def __init__(self, nome, next_event, fgva, nome_en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Create:
"""Classe responsável por criar novas entidades. @cvar _nome_da_entidade: Nome da entidade a ser criada @cvar _quantos_por_vez: Quantas entidades serão criadas por evento @cvar _quantas_vezes: Quantas vezes o evento será executado"""
def __init__(self, nome, next_event, fgva, nome_entidade, quant... | the_stack_v2_python_sparse | src/Simulador/Componente/Evento/Create.py | cesarecorrea94/MeS.py | train | 0 |
ec350f2fc5388fd89478bc0155447bc9bc8d6bed | [
"ZIP_FILEPATH = 'temp/new.zip'\nwith zipfile.ZipFile(str(ZIP_FILEPATH), 'w', compression=zipfile.ZIP_DEFLATED) as zfile:\n zfile.write('data/file_a.txt')\n zfile.write('data/file_b.txt')",
"ZIP_FILEPATH = 'temp/new.zip'\nEXPAND_DIR = 'temp/expand'\nwith zipfile.ZipFile(str(ZIP_FILEPATH)) as zfile:\n zfil... | <|body_start_0|>
ZIP_FILEPATH = 'temp/new.zip'
with zipfile.ZipFile(str(ZIP_FILEPATH), 'w', compression=zipfile.ZIP_DEFLATED) as zfile:
zfile.write('data/file_a.txt')
zfile.write('data/file_b.txt')
<|end_body_0|>
<|body_start_1|>
ZIP_FILEPATH = 'temp/new.zip'
EXP... | TestZip | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestZip:
def test_zip(self) -> None:
"""指定したファイルを zip ファイルに圧縮する。"""
<|body_0|>
def test_unzip(self) -> None:
"""zipファイル中の全てのデータを解凍"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ZIP_FILEPATH = 'temp/new.zip'
with zipfile.ZipFile(str(ZIP_FIL... | stack_v2_sparse_classes_75kplus_train_072459 | 762 | permissive | [
{
"docstring": "指定したファイルを zip ファイルに圧縮する。",
"name": "test_zip",
"signature": "def test_zip(self) -> None"
},
{
"docstring": "zipファイル中の全てのデータを解凍",
"name": "test_unzip",
"signature": "def test_unzip(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_val_000240 | Implement the Python class `TestZip` described below.
Class description:
Implement the TestZip class.
Method signatures and docstrings:
- def test_zip(self) -> None: 指定したファイルを zip ファイルに圧縮する。
- def test_unzip(self) -> None: zipファイル中の全てのデータを解凍 | Implement the Python class `TestZip` described below.
Class description:
Implement the TestZip class.
Method signatures and docstrings:
- def test_zip(self) -> None: 指定したファイルを zip ファイルに圧縮する。
- def test_unzip(self) -> None: zipファイル中の全てのデータを解凍
<|skeleton|>
class TestZip:
def test_zip(self) -> None:
"""指定し... | a3994d272d812261ba694954554cfa213dfe795e | <|skeleton|>
class TestZip:
def test_zip(self) -> None:
"""指定したファイルを zip ファイルに圧縮する。"""
<|body_0|>
def test_unzip(self) -> None:
"""zipファイル中の全てのデータを解凍"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestZip:
def test_zip(self) -> None:
"""指定したファイルを zip ファイルに圧縮する。"""
ZIP_FILEPATH = 'temp/new.zip'
with zipfile.ZipFile(str(ZIP_FILEPATH), 'w', compression=zipfile.ZIP_DEFLATED) as zfile:
zfile.write('data/file_a.txt')
zfile.write('data/file_b.txt')
def test... | the_stack_v2_python_sparse | python/zipfile/test_zip.py | samsgood0310/til | train | 0 | |
55154b36dba31bea2dc471c885789711c43ab30c | [
"super().__init__(healthy_data, broken_data, data_labels, dataset_name, windows_size)\nself.model_name = FORWARD_NETWORK\nself.reshape_data()\nself.model = self.define_model()",
"log.info('Defining FeedForward Autoencoder neural network architecture...')\nmodel = Sequential()\nmodel.add(Dense(PRIMARY_UNITS_SIZE, ... | <|body_start_0|>
super().__init__(healthy_data, broken_data, data_labels, dataset_name, windows_size)
self.model_name = FORWARD_NETWORK
self.reshape_data()
self.model = self.define_model()
<|end_body_0|>
<|body_start_1|>
log.info('Defining FeedForward Autoencoder neural network ... | FFModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FFModel:
def __init__(self, healthy_data: ndarray, broken_data: ndarray, data_labels: array, dataset_name: str, windows_size: int) -> None:
"""Initialize the FFModel class. Args: healthy_data (ndarray): Healthy data for training. broken_data (ndarray): Data with anomalies to detect. data... | stack_v2_sparse_classes_75kplus_train_072460 | 2,399 | no_license | [
{
"docstring": "Initialize the FFModel class. Args: healthy_data (ndarray): Healthy data for training. broken_data (ndarray): Data with anomalies to detect. data_labels (array): Data labels. dataset_name (str): Name of the dataset. windows_size (int): Step in time per example.",
"name": "__init__",
"sig... | 2 | stack_v2_sparse_classes_30k_val_002674 | Implement the Python class `FFModel` described below.
Class description:
Implement the FFModel class.
Method signatures and docstrings:
- def __init__(self, healthy_data: ndarray, broken_data: ndarray, data_labels: array, dataset_name: str, windows_size: int) -> None: Initialize the FFModel class. Args: healthy_data ... | Implement the Python class `FFModel` described below.
Class description:
Implement the FFModel class.
Method signatures and docstrings:
- def __init__(self, healthy_data: ndarray, broken_data: ndarray, data_labels: array, dataset_name: str, windows_size: int) -> None: Initialize the FFModel class. Args: healthy_data ... | 322a27511eb5a270ad88b4e83e30c44bc8943369 | <|skeleton|>
class FFModel:
def __init__(self, healthy_data: ndarray, broken_data: ndarray, data_labels: array, dataset_name: str, windows_size: int) -> None:
"""Initialize the FFModel class. Args: healthy_data (ndarray): Healthy data for training. broken_data (ndarray): Data with anomalies to detect. data... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FFModel:
def __init__(self, healthy_data: ndarray, broken_data: ndarray, data_labels: array, dataset_name: str, windows_size: int) -> None:
"""Initialize the FFModel class. Args: healthy_data (ndarray): Healthy data for training. broken_data (ndarray): Data with anomalies to detect. data_labels (array... | the_stack_v2_python_sparse | PYTHON/AnomalyDetection/Models/DeepLearningModels/Forward.py | dwisniewski1993/Machine-Learning | train | 4 | |
134eb205c3cd9e5af7b1b56dec10a468e539243f | [
"self.root = root\nself.stack = []\nfake_root = root\nif root is not None:\n self.stack.append(root)\n while fake_root.left is not None:\n self.stack.append(fake_root.left)\n fake_root = fake_root.left",
"if len(self.stack) == 0:\n return False\nreturn True",
"if self.hasNext:\n next_n... | <|body_start_0|>
self.root = root
self.stack = []
fake_root = root
if root is not None:
self.stack.append(root)
while fake_root.left is not None:
self.stack.append(fake_root.left)
fake_root = fake_root.left
<|end_body_0|>
<|body_st... | BSTIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def hasNext(self):
""":rtype: bool"""
<|body_1|>
def next(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.root = root
... | stack_v2_sparse_classes_75kplus_train_072461 | 1,075 | no_license | [
{
"docstring": ":type root: TreeNode",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",
"signature": "def hasNext(self)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_050585 | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def hasNext(self): :rtype: bool
- def next(self): :rtype: int | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def hasNext(self): :rtype: bool
- def next(self): :rtype: int
<|skeleton|>
class BSTIterator:
def __init__(self, root... | 4aa3a3a0da8b911e140446352debb9b567b6d78b | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def hasNext(self):
""":rtype: bool"""
<|body_1|>
def next(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
self.root = root
self.stack = []
fake_root = root
if root is not None:
self.stack.append(root)
while fake_root.left is not None:
self.stack.append(fake_root.left)
... | the_stack_v2_python_sparse | binary_search_tree_iterator_173.py | adiggo/leetcode_py | train | 0 | |
c3d2feb12adb97291a7424abbfd07976f982b13e | [
"self.front = None\nself.rear = None\nself.size = 0",
"node = self.Node(val)\nif self.size == 0:\n self.front = self.rear = node\nelse:\n node.prev = None\n node.next = self.front\n self.front.prev = node\n self.front = node\nself.size += 1",
"if self.size == 0:\n return\ncurr = self.rear.prev... | <|body_start_0|>
self.front = None
self.rear = None
self.size = 0
<|end_body_0|>
<|body_start_1|>
node = self.Node(val)
if self.size == 0:
self.front = self.rear = node
else:
node.prev = None
node.next = self.front
self.fro... | LQueue | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LQueue:
def __init__(self):
"""Initialize queue datastructure."""
<|body_0|>
def enqueue(self, val: int) -> None:
"""add a val in the queue"""
<|body_1|>
def dequeue(self) -> None:
"""delete the first element in the queue, if not empty"""
... | stack_v2_sparse_classes_75kplus_train_072462 | 1,607 | permissive | [
{
"docstring": "Initialize queue datastructure.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "add a val in the queue",
"name": "enqueue",
"signature": "def enqueue(self, val: int) -> None"
},
{
"docstring": "delete the first element in the queue, if n... | 4 | stack_v2_sparse_classes_30k_train_006310 | Implement the Python class `LQueue` described below.
Class description:
Implement the LQueue class.
Method signatures and docstrings:
- def __init__(self): Initialize queue datastructure.
- def enqueue(self, val: int) -> None: add a val in the queue
- def dequeue(self) -> None: delete the first element in the queue, ... | Implement the Python class `LQueue` described below.
Class description:
Implement the LQueue class.
Method signatures and docstrings:
- def __init__(self): Initialize queue datastructure.
- def enqueue(self, val: int) -> None: add a val in the queue
- def dequeue(self) -> None: delete the first element in the queue, ... | 4e5134631a47178ed29add42fbe68d7c55a7d6f1 | <|skeleton|>
class LQueue:
def __init__(self):
"""Initialize queue datastructure."""
<|body_0|>
def enqueue(self, val: int) -> None:
"""add a val in the queue"""
<|body_1|>
def dequeue(self) -> None:
"""delete the first element in the queue, if not empty"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LQueue:
def __init__(self):
"""Initialize queue datastructure."""
self.front = None
self.rear = None
self.size = 0
def enqueue(self, val: int) -> None:
"""add a val in the queue"""
node = self.Node(val)
if self.size == 0:
self.front = se... | the_stack_v2_python_sparse | queue/queue.py | AnupamKP/py-coding | train | 0 | |
4e3f10edbf1912df0c0d37d28e605d17cbcb8b95 | [
"Job.__init__(self, *args, **kwargs)\nself.script_path = self.job_specific['script_path']\nself.script_name = self.script_path.split('/')[-1]\nself.use_root = self.job_specific['use_root']\nself.root_version = self.job_specific['root_version']\nself.output = self.job_specific['output']\nself.additional_files = self... | <|body_start_0|>
Job.__init__(self, *args, **kwargs)
self.script_path = self.job_specific['script_path']
self.script_name = self.script_path.split('/')[-1]
self.use_root = self.job_specific['use_root']
self.root_version = self.job_specific['root_version']
self.output = se... | A class to contain a single job comfiguration, but to be used on many input datasets | JobPrun | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobPrun:
"""A class to contain a single job comfiguration, but to be used on many input datasets"""
def __init__(self, *args, **kwargs):
"""Constructor"""
<|body_0|>
def create_directory(self):
"""copy the script over"""
<|body_1|>
def construct_comm... | stack_v2_sparse_classes_75kplus_train_072463 | 5,093 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "copy the script over",
"name": "create_directory",
"signature": "def create_directory(self)"
},
{
"docstring": "constructs a prun command",
"name": "constru... | 3 | stack_v2_sparse_classes_30k_train_000167 | Implement the Python class `JobPrun` described below.
Class description:
A class to contain a single job comfiguration, but to be used on many input datasets
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor
- def create_directory(self): copy the script over
- def construct_command(... | Implement the Python class `JobPrun` described below.
Class description:
A class to contain a single job comfiguration, but to be used on many input datasets
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor
- def create_directory(self): copy the script over
- def construct_command(... | 59d244d9bc04aeae222a93969e1a2537f541008f | <|skeleton|>
class JobPrun:
"""A class to contain a single job comfiguration, but to be used on many input datasets"""
def __init__(self, *args, **kwargs):
"""Constructor"""
<|body_0|>
def create_directory(self):
"""copy the script over"""
<|body_1|>
def construct_comm... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobPrun:
"""A class to contain a single job comfiguration, but to be used on many input datasets"""
def __init__(self, *args, **kwargs):
"""Constructor"""
Job.__init__(self, *args, **kwargs)
self.script_path = self.job_specific['script_path']
self.script_name = self.script... | the_stack_v2_python_sparse | core/job_prun.py | emitc2h/kBook | train | 0 |
ba26881eae5ce5235b2e1d1d5d333303e72e3d5a | [
"self.use_tf_idf = use_tf_idf\nself.preprocess = preprocess\nself.n_gram_range = n_gram_range",
"scores = []\nsubmit_df = pd.DataFrame()\nsubmit_df['id'] = test_df['id']\nclf = MultinomialNB(alpha=1)\nif self.preprocess != -1:\n clean_dataframe(train_df, self.preprocess, target_col)\n clean_dataframe(test_d... | <|body_start_0|>
self.use_tf_idf = use_tf_idf
self.preprocess = preprocess
self.n_gram_range = n_gram_range
<|end_body_0|>
<|body_start_1|>
scores = []
submit_df = pd.DataFrame()
submit_df['id'] = test_df['id']
clf = MultinomialNB(alpha=1)
if self.preproc... | A class to perfrorm Naive Bayes | NaiveBayes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NaiveBayes:
"""A class to perfrorm Naive Bayes"""
def __init__(self, use_tf_idf=True, n_gram_range=(1, 1), preprocess=-1):
"""Constructor for the Naive Bayes Arguments: use_tf_idf(bool): Uses `TfIdfVectorizer` if true else uses `CountVectorizer` if false n_gram_range(list): The vecto... | stack_v2_sparse_classes_75kplus_train_072464 | 4,168 | permissive | [
{
"docstring": "Constructor for the Naive Bayes Arguments: use_tf_idf(bool): Uses `TfIdfVectorizer` if true else uses `CountVectorizer` if false n_gram_range(list): The vectorizer uses this to build the vocabulary preprocess(int): Indicates different preprocess techniques represented in `preprocess`",
"name... | 2 | stack_v2_sparse_classes_30k_train_014160 | Implement the Python class `NaiveBayes` described below.
Class description:
A class to perfrorm Naive Bayes
Method signatures and docstrings:
- def __init__(self, use_tf_idf=True, n_gram_range=(1, 1), preprocess=-1): Constructor for the Naive Bayes Arguments: use_tf_idf(bool): Uses `TfIdfVectorizer` if true else uses... | Implement the Python class `NaiveBayes` described below.
Class description:
A class to perfrorm Naive Bayes
Method signatures and docstrings:
- def __init__(self, use_tf_idf=True, n_gram_range=(1, 1), preprocess=-1): Constructor for the Naive Bayes Arguments: use_tf_idf(bool): Uses `TfIdfVectorizer` if true else uses... | eca0e591895b9d997ad76272f48a448ec6a18865 | <|skeleton|>
class NaiveBayes:
"""A class to perfrorm Naive Bayes"""
def __init__(self, use_tf_idf=True, n_gram_range=(1, 1), preprocess=-1):
"""Constructor for the Naive Bayes Arguments: use_tf_idf(bool): Uses `TfIdfVectorizer` if true else uses `CountVectorizer` if false n_gram_range(list): The vecto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NaiveBayes:
"""A class to perfrorm Naive Bayes"""
def __init__(self, use_tf_idf=True, n_gram_range=(1, 1), preprocess=-1):
"""Constructor for the Naive Bayes Arguments: use_tf_idf(bool): Uses `TfIdfVectorizer` if true else uses `CountVectorizer` if false n_gram_range(list): The vectorizer uses th... | the_stack_v2_python_sparse | toxcom/models/nb.py | aashishyadavally/toxcom | train | 0 |
0c85fc1591fd0b74d4525818d2e60ca42ae2147f | [
"edr = pygmx.open(edrfile)\nself.time, data = edr.read()\nself.types, self.units = zip(*edr.types)\nself.data = data.T",
"if type in self.types:\n return self.data[self.types.index(type)]\nelse:\n raise KeyError('Energy type {} not found in Energy File.'.format(type))"
] | <|body_start_0|>
edr = pygmx.open(edrfile)
self.time, data = edr.read()
self.types, self.units = zip(*edr.types)
self.data = data.T
<|end_body_0|>
<|body_start_1|>
if type in self.types:
return self.data[self.types.index(type)]
else:
raise KeyErro... | A reader for Gromacs energy files. | EnergyReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnergyReader:
"""A reader for Gromacs energy files."""
def __init__(self, edrfile):
"""Args: edrfile: Filename of the energy file topology (opt.): Filename of the topology, speeds up file io since the length of the energy file is known"""
<|body_0|>
def __getitem__(self,... | stack_v2_sparse_classes_75kplus_train_072465 | 12,347 | permissive | [
{
"docstring": "Args: edrfile: Filename of the energy file topology (opt.): Filename of the topology, speeds up file io since the length of the energy file is known",
"name": "__init__",
"signature": "def __init__(self, edrfile)"
},
{
"docstring": "Get time series of an energy type.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_033640 | Implement the Python class `EnergyReader` described below.
Class description:
A reader for Gromacs energy files.
Method signatures and docstrings:
- def __init__(self, edrfile): Args: edrfile: Filename of the energy file topology (opt.): Filename of the topology, speeds up file io since the length of the energy file ... | Implement the Python class `EnergyReader` described below.
Class description:
A reader for Gromacs energy files.
Method signatures and docstrings:
- def __init__(self, edrfile): Args: edrfile: Filename of the energy file topology (opt.): Filename of the topology, speeds up file io since the length of the energy file ... | 204d206df45e1a8d2dbdc36428eb6ce24672d384 | <|skeleton|>
class EnergyReader:
"""A reader for Gromacs energy files."""
def __init__(self, edrfile):
"""Args: edrfile: Filename of the energy file topology (opt.): Filename of the topology, speeds up file io since the length of the energy file is known"""
<|body_0|>
def __getitem__(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnergyReader:
"""A reader for Gromacs energy files."""
def __init__(self, edrfile):
"""Args: edrfile: Filename of the energy file topology (opt.): Filename of the topology, speeds up file io since the length of the energy file is known"""
edr = pygmx.open(edrfile)
self.time, data ... | the_stack_v2_python_sparse | mdevaluate/reader.py | thonmaker/mdevaluate | train | 1 |
1bcb5881f29ec49006628787bbad48696157f7ef | [
"self.f = f\nself.gp = GP(X_init, Y_init, l, sigma_f)\nX_s = np.linspace(bounds[0], bounds[1], num=ac_samples)\nself.X_s = X_s.reshape(-1, 1)\nself.xsi = xsi\nself.minimize = minimize",
"mu, sigma = self.gp.predict(self.X_s)\nif self.minimize is True:\n Y_sample = np.min(self.gp.Y)\n imp = Y_sample - mu - s... | <|body_start_0|>
self.f = f
self.gp = GP(X_init, Y_init, l, sigma_f)
X_s = np.linspace(bounds[0], bounds[1], num=ac_samples)
self.X_s = X_s.reshape(-1, 1)
self.xsi = xsi
self.minimize = minimize
<|end_body_0|>
<|body_start_1|>
mu, sigma = self.gp.predict(self.X_s... | Bayesian optimization on a noiseless 1D Gaussian process | BayesianOptimization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianOptimization:
"""Bayesian optimization on a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""init method for bayesian optimization Args: f: the black-box function to be optimized X_init: nu... | stack_v2_sparse_classes_75kplus_train_072466 | 2,738 | no_license | [
{
"docstring": "init method for bayesian optimization Args: f: the black-box function to be optimized X_init: numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function Y_init: numpy.ndarray of shape (t, 1) representing the outputs of the black-box function for each input ... | 2 | stack_v2_sparse_classes_30k_train_045938 | Implement the Python class `BayesianOptimization` described below.
Class description:
Bayesian optimization on a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): init method for bayesian optimization A... | Implement the Python class `BayesianOptimization` described below.
Class description:
Bayesian optimization on a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): init method for bayesian optimization A... | 7f9a040f23eda32c5aa154c991c930a01b490f0f | <|skeleton|>
class BayesianOptimization:
"""Bayesian optimization on a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""init method for bayesian optimization Args: f: the black-box function to be optimized X_init: nu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BayesianOptimization:
"""Bayesian optimization on a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""init method for bayesian optimization Args: f: the black-box function to be optimized X_init: numpy.ndarray o... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/4-bayes_opt.py | dbaroli/holbertonschool-machine_learning | train | 0 |
0b9b6a167f83897cf41297c371875086b7913480 | [
"Inventory.__init__(self, product_code, description, market_price, rental_price)\nself.brand = brand\nself.voltage = voltage",
"output_dict = Inventory.return_as_dictionary(self)\noutput_dict['brand'] = self.brand\noutput_dict['voltage'] = self.voltage\nreturn output_dict"
] | <|body_start_0|>
Inventory.__init__(self, product_code, description, market_price, rental_price)
self.brand = brand
self.voltage = voltage
<|end_body_0|>
<|body_start_1|>
output_dict = Inventory.return_as_dictionary(self)
output_dict['brand'] = self.brand
output_dict['vo... | Class ElectricAppliances inherites from Inventtory class | ElectricAppliances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectricAppliances:
"""Class ElectricAppliances inherites from Inventtory class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Creates common instance variables from the parent class"""
<|body_0|>
def return_as_dictionary... | stack_v2_sparse_classes_75kplus_train_072467 | 825 | no_license | [
{
"docstring": "Creates common instance variables from the parent class",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price, brand, voltage)"
},
{
"docstring": "return ElectricAppliances class attributes",
"name": "return_as_dictionary... | 2 | stack_v2_sparse_classes_30k_train_008885 | Implement the Python class `ElectricAppliances` described below.
Class description:
Class ElectricAppliances inherites from Inventtory class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): Creates common instance variables from the parent ... | Implement the Python class `ElectricAppliances` described below.
Class description:
Class ElectricAppliances inherites from Inventtory class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): Creates common instance variables from the parent ... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class ElectricAppliances:
"""Class ElectricAppliances inherites from Inventtory class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Creates common instance variables from the parent class"""
<|body_0|>
def return_as_dictionary... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ElectricAppliances:
"""Class ElectricAppliances inherites from Inventtory class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Creates common instance variables from the parent class"""
Inventory.__init__(self, product_code, description, m... | the_stack_v2_python_sparse | students/ttlarson/lesson01/assignment/inventory_management/electric_appliances_class.py | JavaRod/SP_Python220B_2019 | train | 1 |
5f0ff1eaf11698158d404e3a5d1565c841b9709f | [
"nums = sorted(nums)\nresult = []\nfor i in range(len(nums)):\n current = nums[i]\n two_sum = self.twoSum(nums, 0 - current, i)\n if two_sum:\n for ts in two_sum:\n ans = sorted([current] + ts)\n if ans not in result:\n result.append(ans)\nreturn sorted(result)",... | <|body_start_0|>
nums = sorted(nums)
result = []
for i in range(len(nums)):
current = nums[i]
two_sum = self.twoSum(nums, 0 - current, i)
if two_sum:
for ts in two_sum:
ans = sorted([current] + ts)
if ans... | Solution_E | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_E:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""Use modified method of two_sum with every number, check the rest of array for two_sum of (0-number) O(N^2), max time limit exceeded"""
<|body_0|>
def twoSum(self, numbers: List[int], target: int, jump: in... | stack_v2_sparse_classes_75kplus_train_072468 | 8,683 | permissive | [
{
"docstring": "Use modified method of two_sum with every number, check the rest of array for two_sum of (0-number) O(N^2), max time limit exceeded",
"name": "threeSum",
"signature": "def threeSum(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "Helper E # 提取LC167 two sum II 中的头尾缩进法... | 2 | stack_v2_sparse_classes_30k_train_032707 | Implement the Python class `Solution_E` described below.
Class description:
Implement the Solution_E class.
Method signatures and docstrings:
- def threeSum(self, nums: List[int]) -> List[List[int]]: Use modified method of two_sum with every number, check the rest of array for two_sum of (0-number) O(N^2), max time l... | Implement the Python class `Solution_E` described below.
Class description:
Implement the Solution_E class.
Method signatures and docstrings:
- def threeSum(self, nums: List[int]) -> List[List[int]]: Use modified method of two_sum with every number, check the rest of array for two_sum of (0-number) O(N^2), max time l... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution_E:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""Use modified method of two_sum with every number, check the rest of array for two_sum of (0-number) O(N^2), max time limit exceeded"""
<|body_0|>
def twoSum(self, numbers: List[int], target: int, jump: in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution_E:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""Use modified method of two_sum with every number, check the rest of array for two_sum of (0-number) O(N^2), max time limit exceeded"""
nums = sorted(nums)
result = []
for i in range(len(nums)):
c... | the_stack_v2_python_sparse | LeetCode/LC015_3sum.py | jxie0755/Learning_Python | train | 0 | |
679ed362b417426834e4a63c70aa986721ec2eeb | [
"self.stack = []\nself.flag = False\nvisited = [0] * numCourses\ncourses = {}\nfor x in prerequisites:\n courses[x[1]] = courses.get(x[1], []) + [x[0]]\nfor i in range(numCourses):\n self.DFS(i, numCourses, visited, courses)\nreturn self.stack[::-1] if not self.flag else []",
"if visited[i] != 0:\n if vi... | <|body_start_0|>
self.stack = []
self.flag = False
visited = [0] * numCourses
courses = {}
for x in prerequisites:
courses[x[1]] = courses.get(x[1], []) + [x[0]]
for i in range(numCourses):
self.DFS(i, numCourses, visited, courses)
return s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
"""https://www.youtube.com/watch?v=qe_pQCh09yU (course II) https://www.youtube.com/watch?v=kXy0ABd1vwo (course I) topological sorting. DAG: directed acyclic diagram O(V+E) V:vertex, E: edge good ... | stack_v2_sparse_classes_75kplus_train_072469 | 1,837 | no_license | [
{
"docstring": "https://www.youtube.com/watch?v=qe_pQCh09yU (course II) https://www.youtube.com/watch?v=kXy0ABd1vwo (course I) topological sorting. DAG: directed acyclic diagram O(V+E) V:vertex, E: edge good test examples: * [[1,0], [2,1], [3,2], [0,3]], cyclic * [[2,5],[0,5],[2,4],[1,4],[1,3],[3,0],[2,0]], sor... | 2 | stack_v2_sparse_classes_30k_train_027483 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: https://www.youtube.com/watch?v=qe_pQCh09yU (course II) https://www.youtube.com/watch?v=kXy0ABd... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: https://www.youtube.com/watch?v=qe_pQCh09yU (course II) https://www.youtube.com/watch?v=kXy0ABd... | 54d777e11b91c5debe49c1aef723234c66a5d2cc | <|skeleton|>
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
"""https://www.youtube.com/watch?v=qe_pQCh09yU (course II) https://www.youtube.com/watch?v=kXy0ABd1vwo (course I) topological sorting. DAG: directed acyclic diagram O(V+E) V:vertex, E: edge good ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
"""https://www.youtube.com/watch?v=qe_pQCh09yU (course II) https://www.youtube.com/watch?v=kXy0ABd1vwo (course I) topological sorting. DAG: directed acyclic diagram O(V+E) V:vertex, E: edge good test examples:... | the_stack_v2_python_sparse | leetcode_solution/graph/#210.Course_Schedule_II.py | HsiangHung/Code-Challenges | train | 0 | |
bc948902a4877fcb219627d213bc93d6063e7b5f | [
"self.model_conf = model_conf\nself.inputs = inputs\nself.utils = utils\nself.layer = None",
"with tf.keras.backend.name_scope('GRU'):\n mask = tf.keras.layers.Masking()(self.inputs)\n self.layer = tf.keras.layers.GRU(units=self.model_conf.units_num * 2, return_sequences=True, input_shape=mask.shape)\n o... | <|body_start_0|>
self.model_conf = model_conf
self.inputs = inputs
self.utils = utils
self.layer = None
<|end_body_0|>
<|body_start_1|>
with tf.keras.backend.name_scope('GRU'):
mask = tf.keras.layers.Masking()(self.inputs)
self.layer = tf.keras.layers.GRU... | GRU | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRU:
def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils):
""":param model_conf: 配置 :param inputs: 网络上一层输入tf.keras.layers.Input/tf.Tensor类型 :param utils: 网络工具类"""
<|body_0|>
def build(self):
"""循环层构建参数 :return: 返回循环层的输出层"""
<|bo... | stack_v2_sparse_classes_75kplus_train_072470 | 2,557 | permissive | [
{
"docstring": ":param model_conf: 配置 :param inputs: 网络上一层输入tf.keras.layers.Input/tf.Tensor类型 :param utils: 网络工具类",
"name": "__init__",
"signature": "def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils)"
},
{
"docstring": "循环层构建参数 :return: 返回循环层的输出层",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_034761 | Implement the Python class `GRU` described below.
Class description:
Implement the GRU class.
Method signatures and docstrings:
- def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils): :param model_conf: 配置 :param inputs: 网络上一层输入tf.keras.layers.Input/tf.Tensor类型 :param utils: 网络工具类
- def... | Implement the Python class `GRU` described below.
Class description:
Implement the GRU class.
Method signatures and docstrings:
- def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils): :param model_conf: 配置 :param inputs: 网络上一层输入tf.keras.layers.Input/tf.Tensor类型 :param utils: 网络工具类
- def... | 6fd35c0c789aaa43130de46d4c04622ec2948052 | <|skeleton|>
class GRU:
def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils):
""":param model_conf: 配置 :param inputs: 网络上一层输入tf.keras.layers.Input/tf.Tensor类型 :param utils: 网络工具类"""
<|body_0|>
def build(self):
"""循环层构建参数 :return: 返回循环层的输出层"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GRU:
def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils):
""":param model_conf: 配置 :param inputs: 网络上一层输入tf.keras.layers.Input/tf.Tensor类型 :param utils: 网络工具类"""
self.model_conf = model_conf
self.inputs = inputs
self.utils = utils
self.la... | the_stack_v2_python_sparse | network/GRU.py | kerlomz/captcha_trainer | train | 2,977 | |
1d98a5839b3c5fe7159892a1dc55a9bc9ac74510 | [
"pnt = geom.centroid\nqs = super(BioregionManager, self).get_query_set().filter(geometry__contains=pnt)\nif qs.count() > 1:\n raise Exception('The submitted geometry has a centroid that is in more than one bioregion. Either there is something wrong with the bioregions geometry or the fabric of the universe has b... | <|body_start_0|>
pnt = geom.centroid
qs = super(BioregionManager, self).get_query_set().filter(geometry__contains=pnt)
if qs.count() > 1:
raise Exception('The submitted geometry has a centroid that is in more than one bioregion. Either there is something wrong with the bioregions geo... | BioregionManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BioregionManager:
def which_bioregion(self, geom):
"""Given a geometry, this method will return the name of the bioregion that contains that geometry's centroid."""
<|body_0|>
def spans_multiple(self, geom):
"""Will return True if geometry spans multiple bioregions. ... | stack_v2_sparse_classes_75kplus_train_072471 | 2,779 | no_license | [
{
"docstring": "Given a geometry, this method will return the name of the bioregion that contains that geometry's centroid.",
"name": "which_bioregion",
"signature": "def which_bioregion(self, geom)"
},
{
"docstring": "Will return True if geometry spans multiple bioregions. False otherwise.",
... | 2 | stack_v2_sparse_classes_30k_train_001493 | Implement the Python class `BioregionManager` described below.
Class description:
Implement the BioregionManager class.
Method signatures and docstrings:
- def which_bioregion(self, geom): Given a geometry, this method will return the name of the bioregion that contains that geometry's centroid.
- def spans_multiple(... | Implement the Python class `BioregionManager` described below.
Class description:
Implement the BioregionManager class.
Method signatures and docstrings:
- def which_bioregion(self, geom): Given a geometry, this method will return the name of the bioregion that contains that geometry's centroid.
- def spans_multiple(... | c001e16615caa2178c65ca0684e1b6fd56d3f93d | <|skeleton|>
class BioregionManager:
def which_bioregion(self, geom):
"""Given a geometry, this method will return the name of the bioregion that contains that geometry's centroid."""
<|body_0|>
def spans_multiple(self, geom):
"""Will return True if geometry spans multiple bioregions. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BioregionManager:
def which_bioregion(self, geom):
"""Given a geometry, this method will return the name of the bioregion that contains that geometry's centroid."""
pnt = geom.centroid
qs = super(BioregionManager, self).get_query_set().filter(geometry__contains=pnt)
if qs.count... | the_stack_v2_python_sparse | lingcod/bioregions/models.py | FlavioFalcao/marinemap | train | 0 | |
b9e2cba9c454e3e86a86e358200315c9b9949078 | [
"if not root:\n return None\nres = TreeNode(root.val)\nif root.children:\n res.left = self.encode(root.children[0])\ncur = res.left\nfor i in range(1, len(root.children)):\n cur.right = self.encode(root.children[i])\n cur = cur.right\nreturn res",
"if not data:\n return None\nres = Node(data.val, [... | <|body_start_0|>
if not root:
return None
res = TreeNode(root.val)
if root.children:
res.left = self.encode(root.children[0])
cur = res.left
for i in range(1, len(root.children)):
cur.right = self.encode(root.children[i])
cur = cur.... | Codec2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec2:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
<|body_0|>
def decode(self, data):
"""Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_072472 | 1,961 | no_license | [
{
"docstring": "Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode",
"name": "encode",
"signature": "def encode(self, root)"
},
{
"docstring": "Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node",
"name": "decode",
"signature": "def decode... | 2 | stack_v2_sparse_classes_30k_test_000734 | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode
- def decode(self, data): Decodes your binary tree to an n-ary tree. :type data: Tre... | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode
- def decode(self, data): Decodes your binary tree to an n-ary tree. :type data: Tre... | 3e50f6a936b98ad75c47d7c1719e69163c648235 | <|skeleton|>
class Codec2:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
<|body_0|>
def decode(self, data):
"""Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec2:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
if not root:
return None
res = TreeNode(root.val)
if root.children:
res.left = self.encode(root.children[0])
cur = res.left
fo... | the_stack_v2_python_sparse | LeetcodeNew/Tree/LC_431_Encode_N_ary_Tree_to_Binary_Tree.py | Taoge123/OptimizedLeetcode | train | 9 | |
977363adde53c3c5f9d31f7ae2b9b18a3360c2a3 | [
"super().__init__(self.PROBLEM_NAME)\nself.number_vertices = number_vertices\nself.input_graph = input_graph",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nvisited_list = [False] * self.number_vertices\nsort_list = []\nfor vertex in range(self.number_vertices):\n if not visited_list[vertex]:\n ... | <|body_start_0|>
super().__init__(self.PROBLEM_NAME)
self.number_vertices = number_vertices
self.input_graph = input_graph
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
visited_list = [False] * self.number_vertices
sort_list = ... | TopologicalSortingDAG | TopologicalSortingDAG | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopologicalSortingDAG:
"""TopologicalSortingDAG"""
def __init__(self, number_vertices, input_graph):
"""Topological Sorting of DAG Args: number_vertices: Number of vertices in the graph input_graph: Graph for which to find the minimum spanning tree Returns: None Raises: None"""
... | stack_v2_sparse_classes_75kplus_train_072473 | 2,682 | no_license | [
{
"docstring": "Topological Sorting of DAG Args: number_vertices: Number of vertices in the graph input_graph: Graph for which to find the minimum spanning tree Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, number_vertices, input_graph)"
},
{
"docstring": "Sol... | 3 | stack_v2_sparse_classes_30k_train_044007 | Implement the Python class `TopologicalSortingDAG` described below.
Class description:
TopologicalSortingDAG
Method signatures and docstrings:
- def __init__(self, number_vertices, input_graph): Topological Sorting of DAG Args: number_vertices: Number of vertices in the graph input_graph: Graph for which to find the ... | Implement the Python class `TopologicalSortingDAG` described below.
Class description:
TopologicalSortingDAG
Method signatures and docstrings:
- def __init__(self, number_vertices, input_graph): Topological Sorting of DAG Args: number_vertices: Number of vertices in the graph input_graph: Graph for which to find the ... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class TopologicalSortingDAG:
"""TopologicalSortingDAG"""
def __init__(self, number_vertices, input_graph):
"""Topological Sorting of DAG Args: number_vertices: Number of vertices in the graph input_graph: Graph for which to find the minimum spanning tree Returns: None Raises: None"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TopologicalSortingDAG:
"""TopologicalSortingDAG"""
def __init__(self, number_vertices, input_graph):
"""Topological Sorting of DAG Args: number_vertices: Number of vertices in the graph input_graph: Graph for which to find the minimum spanning tree Returns: None Raises: None"""
super().__... | the_stack_v2_python_sparse | python/problems/graphs/topological_sorting_dag.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
83e087177777b3620b1fb78d63af8e6370e75653 | [
"if sys_name == 'operation':\n url = get_config.get_address_operation() + 'uaa/oauth/token'\n authorization = get_config.get_operation_authorization()\n header = {'content-type': 'application/x-www-form-urlencoded', 'Authorization': authorization}\n data = 'grant_type=password&password=' + get_config.ge... | <|body_start_0|>
if sys_name == 'operation':
url = get_config.get_address_operation() + 'uaa/oauth/token'
authorization = get_config.get_operation_authorization()
header = {'content-type': 'application/x-www-form-urlencoded', 'Authorization': authorization}
data =... | Login_Token | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Login_Token:
def get_token(sefl, sys_name):
"""获取token,入参operation:管理端 tenant:租户端 agent:坐席端"""
<|body_0|>
def json_header(self, sys_name):
"""json格式的头"""
<|body_1|>
def str_header(self, sys_name):
"""字符串格式的头"""
<|body_2|>
def upload_... | stack_v2_sparse_classes_75kplus_train_072474 | 4,391 | no_license | [
{
"docstring": "获取token,入参operation:管理端 tenant:租户端 agent:坐席端",
"name": "get_token",
"signature": "def get_token(sefl, sys_name)"
},
{
"docstring": "json格式的头",
"name": "json_header",
"signature": "def json_header(self, sys_name)"
},
{
"docstring": "字符串格式的头",
"name": "str_heade... | 6 | stack_v2_sparse_classes_30k_train_011629 | Implement the Python class `Login_Token` described below.
Class description:
Implement the Login_Token class.
Method signatures and docstrings:
- def get_token(sefl, sys_name): 获取token,入参operation:管理端 tenant:租户端 agent:坐席端
- def json_header(self, sys_name): json格式的头
- def str_header(self, sys_name): 字符串格式的头
- def uplo... | Implement the Python class `Login_Token` described below.
Class description:
Implement the Login_Token class.
Method signatures and docstrings:
- def get_token(sefl, sys_name): 获取token,入参operation:管理端 tenant:租户端 agent:坐席端
- def json_header(self, sys_name): json格式的头
- def str_header(self, sys_name): 字符串格式的头
- def uplo... | 3a70e7f7fa794ff62a2be590020d5223eb19f08c | <|skeleton|>
class Login_Token:
def get_token(sefl, sys_name):
"""获取token,入参operation:管理端 tenant:租户端 agent:坐席端"""
<|body_0|>
def json_header(self, sys_name):
"""json格式的头"""
<|body_1|>
def str_header(self, sys_name):
"""字符串格式的头"""
<|body_2|>
def upload_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Login_Token:
def get_token(sefl, sys_name):
"""获取token,入参operation:管理端 tenant:租户端 agent:坐席端"""
if sys_name == 'operation':
url = get_config.get_address_operation() + 'uaa/oauth/token'
authorization = get_config.get_operation_authorization()
header = {'conten... | the_stack_v2_python_sparse | Common/get_token.py | zhongyuan111/auto_4.0-swjl2 | train | 0 | |
c0b4c87aaa163e72d45bcdf5d48a4ca8405bffde | [
"base_dir = os.path.dirname(os.path.abspath(__file__))\nbase_app.__init__(self, base_dir)\nbase_app.index.im_func.exposed = True\nbase_app.input_select.im_func.exposed = True\nbase_app.input_upload.im_func.exposed = True\nbase_app.params.im_func.exposed = True\nbase_app.result.im_func.exposed = True\nself.timestamp... | <|body_start_0|>
base_dir = os.path.dirname(os.path.abspath(__file__))
base_app.__init__(self, base_dir)
base_app.index.im_func.exposed = True
base_app.input_select.im_func.exposed = True
base_app.input_upload.im_func.exposed = True
base_app.params.im_func.exposed = True
... | Automatic Lens Distortion Correction Using One Parameter Division Models app | app | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class app:
"""Automatic Lens Distortion Correction Using One Parameter Division Models app"""
def __init__(self):
"""app setup"""
<|body_0|>
def build(self):
"""program build/update"""
<|body_1|>
def params(self, newrun=False, msg=None):
"""configu... | stack_v2_sparse_classes_75kplus_train_072475 | 8,364 | no_license | [
{
"docstring": "app setup",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "program build/update",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "configure the algo execution",
"name": "params",
"signature": "def params(self, n... | 6 | stack_v2_sparse_classes_30k_train_022005 | Implement the Python class `app` described below.
Class description:
Automatic Lens Distortion Correction Using One Parameter Division Models app
Method signatures and docstrings:
- def __init__(self): app setup
- def build(self): program build/update
- def params(self, newrun=False, msg=None): configure the algo exe... | Implement the Python class `app` described below.
Class description:
Automatic Lens Distortion Correction Using One Parameter Division Models app
Method signatures and docstrings:
- def __init__(self): app setup
- def build(self): program build/update
- def params(self, newrun=False, msg=None): configure the algo exe... | 1ee176ad8578be2f0d48d2ffcacf7a0073e1b630 | <|skeleton|>
class app:
"""Automatic Lens Distortion Correction Using One Parameter Division Models app"""
def __init__(self):
"""app setup"""
<|body_0|>
def build(self):
"""program build/update"""
<|body_1|>
def params(self, newrun=False, msg=None):
"""configu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class app:
"""Automatic Lens Distortion Correction Using One Parameter Division Models app"""
def __init__(self):
"""app setup"""
base_dir = os.path.dirname(os.path.abspath(__file__))
base_app.__init__(self, base_dir)
base_app.index.im_func.exposed = True
base_app.input_... | the_stack_v2_python_sparse | app/106/app.py | nilx/ipol_demo | train | 1 |
00463ef5bf7a318bfe7bcf4ddaf69cb8dac74afb | [
"if SuperUserPermission().can():\n registry_size = get_registry_size()\n if registry_size is not None:\n return {'size_bytes': registry_size.size_bytes, 'last_ran': registry_size.completed_ms, 'queued': registry_size.queued, 'running': registry_size.running}\n else:\n return {'size_bytes': 0,... | <|body_start_0|>
if SuperUserPermission().can():
registry_size = get_registry_size()
if registry_size is not None:
return {'size_bytes': registry_size.size_bytes, 'last_ran': registry_size.completed_ms, 'queued': registry_size.queued, 'running': registry_size.running}
... | Resource for the current registry size. | SuperUserRegistrySize | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperUserRegistrySize:
"""Resource for the current registry size."""
def get(self):
"""Returns size of the registry"""
<|body_0|>
def post(self):
"""Queues registry size calculation"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if SuperUserPer... | stack_v2_sparse_classes_75kplus_train_072476 | 40,556 | permissive | [
{
"docstring": "Returns size of the registry",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Queues registry size calculation",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041879 | Implement the Python class `SuperUserRegistrySize` described below.
Class description:
Resource for the current registry size.
Method signatures and docstrings:
- def get(self): Returns size of the registry
- def post(self): Queues registry size calculation | Implement the Python class `SuperUserRegistrySize` described below.
Class description:
Resource for the current registry size.
Method signatures and docstrings:
- def get(self): Returns size of the registry
- def post(self): Queues registry size calculation
<|skeleton|>
class SuperUserRegistrySize:
"""Resource f... | e400a0c22c5f89dd35d571654b13d262b1f6e3b3 | <|skeleton|>
class SuperUserRegistrySize:
"""Resource for the current registry size."""
def get(self):
"""Returns size of the registry"""
<|body_0|>
def post(self):
"""Queues registry size calculation"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SuperUserRegistrySize:
"""Resource for the current registry size."""
def get(self):
"""Returns size of the registry"""
if SuperUserPermission().can():
registry_size = get_registry_size()
if registry_size is not None:
return {'size_bytes': registry_s... | the_stack_v2_python_sparse | endpoints/api/superuser.py | quay/quay | train | 2,363 |
428df5d2abcce9fd2764e6e2418f6ea27c9a9dd4 | [
"self.ID_STUDENT = id_student\nself.fullname = fullname\nself.DATE = date\nself.STATUS = status",
"attendance_list = []\nattendance = Attendance.query.filter_by(DATE=date).all()\nif attendance:\n for student in attendance:\n user = Student.query.filter_by(ID=student.ID_STUDENT).first()\n fullname... | <|body_start_0|>
self.ID_STUDENT = id_student
self.fullname = fullname
self.DATE = date
self.STATUS = status
<|end_body_0|>
<|body_start_1|>
attendance_list = []
attendance = Attendance.query.filter_by(DATE=date).all()
if attendance:
for student in at... | Class of students submission. | Attendance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attendance:
"""Class of students submission."""
def __init__(self, id_student, date, fullname='', status='None'):
"""Create Attendance object :param id_student: string (user id) :param date: string (date: DD.MM.YYYY) :param status: string (Present/Late/Absent)"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_072477 | 2,917 | no_license | [
{
"docstring": "Create Attendance object :param id_student: string (user id) :param date: string (date: DD.MM.YYYY) :param status: string (Present/Late/Absent)",
"name": "__init__",
"signature": "def __init__(self, id_student, date, fullname='', status='None')"
},
{
"docstring": "Creates attenda... | 4 | stack_v2_sparse_classes_30k_train_045457 | Implement the Python class `Attendance` described below.
Class description:
Class of students submission.
Method signatures and docstrings:
- def __init__(self, id_student, date, fullname='', status='None'): Create Attendance object :param id_student: string (user id) :param date: string (date: DD.MM.YYYY) :param sta... | Implement the Python class `Attendance` described below.
Class description:
Class of students submission.
Method signatures and docstrings:
- def __init__(self, id_student, date, fullname='', status='None'): Create Attendance object :param id_student: string (user id) :param date: string (date: DD.MM.YYYY) :param sta... | 7f8fbacf4801f22f3d694b836491c3b33aed764f | <|skeleton|>
class Attendance:
"""Class of students submission."""
def __init__(self, id_student, date, fullname='', status='None'):
"""Create Attendance object :param id_student: string (user id) :param date: string (date: DD.MM.YYYY) :param status: string (Present/Late/Absent)"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Attendance:
"""Class of students submission."""
def __init__(self, id_student, date, fullname='', status='None'):
"""Create Attendance object :param id_student: string (user id) :param date: string (date: DD.MM.YYYY) :param status: string (Present/Late/Absent)"""
self.ID_STUDENT = id_stud... | the_stack_v2_python_sparse | app/modules/mod_attendance/attendance.py | patiem/ccms-for-school-python-flask-SQLAlchemy | train | 0 |
61f9948d1b883fbfedb6da7fe5a350094cdf5242 | [
"self.adder = Adder()\nself.subtracter = Subtracter()\nself.multiplier = Multiplier()\nself.divider = Divider()\nself.calculator = Calculator(self.adder, self.subtracter, self.multiplier, self.divider)",
"self.calculator.enter_number(0)\nwith self.assertRaises(InsufficientOperands):\n self.calculator.add()",
... | <|body_start_0|>
self.adder = Adder()
self.subtracter = Subtracter()
self.multiplier = Multiplier()
self.divider = Divider()
self.calculator = Calculator(self.adder, self.subtracter, self.multiplier, self.divider)
<|end_body_0|>
<|body_start_1|>
self.calculator.enter_num... | Class for testing the Calculator | CalculatorTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalculatorTests:
"""Class for testing the Calculator"""
def setUp(self):
"""Configure a new Adder, Subtractor, Multiplier, and Divider to instantiate a calculator"""
<|body_0|>
def test_insufficient_operands(self):
"""At least two operands are needed."""
... | stack_v2_sparse_classes_75kplus_train_072478 | 3,649 | no_license | [
{
"docstring": "Configure a new Adder, Subtractor, Multiplier, and Divider to instantiate a calculator",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "At least two operands are needed.",
"name": "test_insufficient_operands",
"signature": "def test_insufficient_operan... | 6 | stack_v2_sparse_classes_30k_train_031194 | Implement the Python class `CalculatorTests` described below.
Class description:
Class for testing the Calculator
Method signatures and docstrings:
- def setUp(self): Configure a new Adder, Subtractor, Multiplier, and Divider to instantiate a calculator
- def test_insufficient_operands(self): At least two operands ar... | Implement the Python class `CalculatorTests` described below.
Class description:
Class for testing the Calculator
Method signatures and docstrings:
- def setUp(self): Configure a new Adder, Subtractor, Multiplier, and Divider to instantiate a calculator
- def test_insufficient_operands(self): At least two operands ar... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class CalculatorTests:
"""Class for testing the Calculator"""
def setUp(self):
"""Configure a new Adder, Subtractor, Multiplier, and Divider to instantiate a calculator"""
<|body_0|>
def test_insufficient_operands(self):
"""At least two operands are needed."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CalculatorTests:
"""Class for testing the Calculator"""
def setUp(self):
"""Configure a new Adder, Subtractor, Multiplier, and Divider to instantiate a calculator"""
self.adder = Adder()
self.subtracter = Subtracter()
self.multiplier = Multiplier()
self.divider = D... | the_stack_v2_python_sparse | students/roy_t/lesson06/unittest_calculator.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
dcbb5323d2dcea15a3658048558a97125e057866 | [
"final_queens = []\n\ndef back(queen_str):\n if len(queen_str) == nums:\n final_queens.append(queen_str)\n return\n for col in range(nums):\n flag = self.valid(queen_str, col)\n if not flag:\n back(queen_str + str(col))\nback(queen_str)\nreturn final_queens",
"rows = l... | <|body_start_0|>
final_queens = []
def back(queen_str):
if len(queen_str) == nums:
final_queens.append(queen_str)
return
for col in range(nums):
flag = self.valid(queen_str, col)
if not flag:
bac... | 回溯法思想 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""回溯法思想"""
def queens(self, nums=8, queen_str=''):
""":param nums: 整个棋盘中想要存放皇后的个数 :param queen_str: 当前皇后以前所存的皇后的列的位置 :return: final_queens: List[int] 最后符合要求的皇后的位置"""
<|body_0|>
def valid(self, queen_str, current_queen):
""":param queen_str: 当前皇后以前所存的皇后... | stack_v2_sparse_classes_75kplus_train_072479 | 2,043 | no_license | [
{
"docstring": ":param nums: 整个棋盘中想要存放皇后的个数 :param queen_str: 当前皇后以前所存的皇后的列的位置 :return: final_queens: List[int] 最后符合要求的皇后的位置",
"name": "queens",
"signature": "def queens(self, nums=8, queen_str='')"
},
{
"docstring": ":param queen_str: 当前皇后以前所存的皇后的列的位置 :param current_queen: 当前皇后的位置(列) :return: f... | 2 | stack_v2_sparse_classes_30k_train_010198 | Implement the Python class `Solution` described below.
Class description:
回溯法思想
Method signatures and docstrings:
- def queens(self, nums=8, queen_str=''): :param nums: 整个棋盘中想要存放皇后的个数 :param queen_str: 当前皇后以前所存的皇后的列的位置 :return: final_queens: List[int] 最后符合要求的皇后的位置
- def valid(self, queen_str, current_queen): :param q... | Implement the Python class `Solution` described below.
Class description:
回溯法思想
Method signatures and docstrings:
- def queens(self, nums=8, queen_str=''): :param nums: 整个棋盘中想要存放皇后的个数 :param queen_str: 当前皇后以前所存的皇后的列的位置 :return: final_queens: List[int] 最后符合要求的皇后的位置
- def valid(self, queen_str, current_queen): :param q... | 14fb97af36c5fb1d69439585adb0db0ce9eae45d | <|skeleton|>
class Solution:
"""回溯法思想"""
def queens(self, nums=8, queen_str=''):
""":param nums: 整个棋盘中想要存放皇后的个数 :param queen_str: 当前皇后以前所存的皇后的列的位置 :return: final_queens: List[int] 最后符合要求的皇后的位置"""
<|body_0|>
def valid(self, queen_str, current_queen):
""":param queen_str: 当前皇后以前所存的皇后... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""回溯法思想"""
def queens(self, nums=8, queen_str=''):
""":param nums: 整个棋盘中想要存放皇后的个数 :param queen_str: 当前皇后以前所存的皇后的列的位置 :return: final_queens: List[int] 最后符合要求的皇后的位置"""
final_queens = []
def back(queen_str):
if len(queen_str) == nums:
final_que... | the_stack_v2_python_sparse | 八皇后问题.py | zhanvwei/targetoffer | train | 0 |
5a976f78cfc1f328587da8a2af12e06927b42e40 | [
"print('Getting agent versions distribution...')\ncur = self.conn.cursor()\ncur.execute(f\"\"\"\\n SELECT CONCAT(av.agent_name, '-', av.agent_version), count(DISTINCT peer_id) \"count\"\\n FROM visits v\\n INNER JOIN (\\n SELECT id,\\n C... | <|body_start_0|>
print('Getting agent versions distribution...')
cur = self.conn.cursor()
cur.execute(f"""\n SELECT CONCAT(av.agent_name, '-', av.agent_version), count(DISTINCT peer_id) "count"\n FROM visits v\n INNER JOIN (\n SELECT id,\n... | DBClientFilecoin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBClientFilecoin:
def get_agent_versions_distribution(self) -> list[tuple[str, int]]:
"""get_agent_versions_distribution returns all agent versions with a count of peers that were discovered with such an agent version."""
<|body_0|>
def get_agent_versions_for_peer_ids(self, ... | stack_v2_sparse_classes_75kplus_train_072480 | 4,093 | permissive | [
{
"docstring": "get_agent_versions_distribution returns all agent versions with a count of peers that were discovered with such an agent version.",
"name": "get_agent_versions_distribution",
"signature": "def get_agent_versions_distribution(self) -> list[tuple[str, int]]"
},
{
"docstring": "get_... | 2 | stack_v2_sparse_classes_30k_train_043406 | Implement the Python class `DBClientFilecoin` described below.
Class description:
Implement the DBClientFilecoin class.
Method signatures and docstrings:
- def get_agent_versions_distribution(self) -> list[tuple[str, int]]: get_agent_versions_distribution returns all agent versions with a count of peers that were dis... | Implement the Python class `DBClientFilecoin` described below.
Class description:
Implement the DBClientFilecoin class.
Method signatures and docstrings:
- def get_agent_versions_distribution(self) -> list[tuple[str, int]]: get_agent_versions_distribution returns all agent versions with a count of peers that were dis... | f858941da142a7476864f8eec56e5232e9dae641 | <|skeleton|>
class DBClientFilecoin:
def get_agent_versions_distribution(self) -> list[tuple[str, int]]:
"""get_agent_versions_distribution returns all agent versions with a count of peers that were discovered with such an agent version."""
<|body_0|>
def get_agent_versions_for_peer_ids(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DBClientFilecoin:
def get_agent_versions_distribution(self) -> list[tuple[str, int]]:
"""get_agent_versions_distribution returns all agent versions with a count of peers that were discovered with such an agent version."""
print('Getting agent versions distribution...')
cur = self.conn.... | the_stack_v2_python_sparse | analysis/report/lib_db_filecoin.py | TrendingTechnology/nebula-crawler | train | 0 | |
ec8a807bb69129d6f31bf02de255dbca408fbd85 | [
"self.uri = uri\nself.schema_file = schema_file\nself.http_method = http_method\nself.params = params\nself.test = test\nself.runner = runner\nself.headers = {k: ACCEPT_HEADER[k] for k in ACCEPT_HEADER.keys()}\nself.full_message = []",
"for header_name, header_value in self.runner.headers.items():\n self.heade... | <|body_start_0|>
self.uri = uri
self.schema_file = schema_file
self.http_method = http_method
self.params = params
self.test = test
self.runner = runner
self.headers = {k: ACCEPT_HEADER[k] for k in ACCEPT_HEADER.keys()}
self.full_message = []
<|end_body_0|... | Executes API request, validates response and sets result to pass/fail The SingleTestExecutor is a generalized model for executing tests against the API. It executes a request, checks for response code, and validates the returned object against a schema. Attributes: uri (str): uri to be requested schema_file (str): JSON... | SingleTestExecutor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleTestExecutor:
"""Executes API request, validates response and sets result to pass/fail The SingleTestExecutor is a generalized model for executing tests against the API. It executes a request, checks for response code, and validates the returned object against a schema. Attributes: uri (str... | stack_v2_sparse_classes_75kplus_train_072481 | 5,877 | permissive | [
{
"docstring": "instantiates a SingleTestExecutor object Args: uri (str): uri to be requested schema_file (str): JSON schema file to validate response against http_method (int): GET or POST request params (dict): parameters/filters to submit with query test (Test): reference to Test object runner (TestRunner): ... | 3 | stack_v2_sparse_classes_30k_train_018434 | Implement the Python class `SingleTestExecutor` described below.
Class description:
Executes API request, validates response and sets result to pass/fail The SingleTestExecutor is a generalized model for executing tests against the API. It executes a request, checks for response code, and validates the returned object... | Implement the Python class `SingleTestExecutor` described below.
Class description:
Executes API request, validates response and sets result to pass/fail The SingleTestExecutor is a generalized model for executing tests against the API. It executes a request, checks for response code, and validates the returned object... | 0e764005d476aa3c370eadf890a633d927d2374c | <|skeleton|>
class SingleTestExecutor:
"""Executes API request, validates response and sets result to pass/fail The SingleTestExecutor is a generalized model for executing tests against the API. It executes a request, checks for response code, and validates the returned object against a schema. Attributes: uri (str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SingleTestExecutor:
"""Executes API request, validates response and sets result to pass/fail The SingleTestExecutor is a generalized model for executing tests against the API. It executes a request, checks for response code, and validates the returned object against a schema. Attributes: uri (str): uri to be ... | the_stack_v2_python_sparse | compliance_suite/single_test_executor.py | alipski/rnaget-compliance-suite | train | 0 |
2cbc2239add2f5386e37b4c148e99d9565a36f22 | [
"if not l and (not r):\n lst.append(string)\nelif not l and r:\n self.recursion(lst, string + ')', l, r - 1)\nelif l == r:\n self.recursion(lst, string + '(', l - 1, r)\nelif r:\n self.recursion(lst, string + '(', l - 1, r)\n self.recursion(lst, string + ')', l, r - 1)",
"if n <= 0:\n return []\... | <|body_start_0|>
if not l and (not r):
lst.append(string)
elif not l and r:
self.recursion(lst, string + ')', l, r - 1)
elif l == r:
self.recursion(lst, string + '(', l - 1, r)
elif r:
self.recursion(lst, string + '(', l - 1, r)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def recursion(self, lst, string, l, r):
""":type: List[str] :type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not l and (not ... | stack_v2_sparse_classes_75kplus_train_072482 | 1,321 | no_license | [
{
"docstring": ":type: List[str] :type n: int :rtype: List[str]",
"name": "recursion",
"signature": "def recursion(self, lst, string, l, r)"
},
{
"docstring": ":type n: int :rtype: List[str]",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recursion(self, lst, string, l, r): :type: List[str] :type n: int :rtype: List[str]
- def generateParenthesis(self, n): :type n: int :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recursion(self, lst, string, l, r): :type: List[str] :type n: int :rtype: List[str]
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
<|skeleton|>
class Sol... | 315693f03faecef72c9d73a8e40fee7c6b75e97d | <|skeleton|>
class Solution:
def recursion(self, lst, string, l, r):
""":type: List[str] :type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def recursion(self, lst, string, l, r):
""":type: List[str] :type n: int :rtype: List[str]"""
if not l and (not r):
lst.append(string)
elif not l and r:
self.recursion(lst, string + ')', l, r - 1)
elif l == r:
self.recursion(lst, st... | the_stack_v2_python_sparse | Medium/generate_parentheses.py | Travmatth/LeetCode | train | 0 | |
eef7c1e8fe2d8b740c1f6b1425d41b4b489e60e0 | [
"super(MultiHeadedAttention, self).__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.linear1 = nn.Linear(d_model, d_model)\nself.linear2 = nn.Linear(d_model, d_model)\nself.attn = None\nself.dropout = nn.Dropout(p=dropout)\nself.size = d_model",
"if mask is not None:\n mask = mask.... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linear1 = nn.Linear(d_model, d_model)
self.linear2 = nn.Linear(d_model, d_model)
self.attn = None
self.dropout = nn.Dropout(p=drop... | MultiHeadedAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.5):
"""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... | stack_v2_sparse_classes_75kplus_train_072483 | 27,486 | permissive | [
{
"docstring": "Take in model size and number of heads.",
"name": "__init__",
"signature": "def __init__(self, h, d_model, dropout=0.5)"
},
{
"docstring": "Implements Figure 2",
"name": "forward",
"signature": "def forward(self, query, key, value, mask=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013645 | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.5): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure ... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.5): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure ... | 0e4bf3f7f301570b652490f697758361c866f3c1 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.5):
"""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 MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.5):
"""Take in model size and number of heads."""
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linear1 = nn.Linear(d_model, d_model)
... | the_stack_v2_python_sparse | gmac_model_with_verb.py | thilinicooray/mac-network-pytorch | train | 0 | |
f2707682f9ea1237be1231c7be7f36cf7fbe94dc | [
"Frame.__init__(self)\nself.make_widgets()\nself.pack()",
"Label(self, text='Please enter a numeric expression:').pack()\nself.ent = Entry(self)\nself.ent.pack()\nButton(self, text='+2', command=self.addtwo).pack(side=LEFT)\nButton(self, text='Clear', command=lambda: self.ent.delete(0, END)).pack(side=RIGHT)",
... | <|body_start_0|>
Frame.__init__(self)
self.make_widgets()
self.pack()
<|end_body_0|>
<|body_start_1|>
Label(self, text='Please enter a numeric expression:').pack()
self.ent = Entry(self)
self.ent.pack()
Button(self, text='+2', command=self.addtwo).pack(side=LEFT)... | PlusTwo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlusTwo:
def __init__(self):
"""the constructor for the GUI"""
<|body_0|>
def make_widgets(self):
"""create the widgets for the GUI"""
<|body_1|>
def addtwo(self):
"""the event handler for the +2 button"""
<|body_2|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_75kplus_train_072484 | 4,292 | no_license | [
{
"docstring": "the constructor for the GUI",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "create the widgets for the GUI",
"name": "make_widgets",
"signature": "def make_widgets(self)"
},
{
"docstring": "the event handler for the +2 button",
"name... | 3 | stack_v2_sparse_classes_30k_train_028953 | Implement the Python class `PlusTwo` described below.
Class description:
Implement the PlusTwo class.
Method signatures and docstrings:
- def __init__(self): the constructor for the GUI
- def make_widgets(self): create the widgets for the GUI
- def addtwo(self): the event handler for the +2 button | Implement the Python class `PlusTwo` described below.
Class description:
Implement the PlusTwo class.
Method signatures and docstrings:
- def __init__(self): the constructor for the GUI
- def make_widgets(self): create the widgets for the GUI
- def addtwo(self): the event handler for the +2 button
<|skeleton|>
class... | 9524f9df064bf9b1e2d6bdac55e850e1ae2549d9 | <|skeleton|>
class PlusTwo:
def __init__(self):
"""the constructor for the GUI"""
<|body_0|>
def make_widgets(self):
"""create the widgets for the GUI"""
<|body_1|>
def addtwo(self):
"""the event handler for the +2 button"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlusTwo:
def __init__(self):
"""the constructor for the GUI"""
Frame.__init__(self)
self.make_widgets()
self.pack()
def make_widgets(self):
"""create the widgets for the GUI"""
Label(self, text='Please enter a numeric expression:').pack()
self.ent =... | the_stack_v2_python_sparse | csc242-603midterm.py | brandonPauly/pythonToys | train | 0 | |
4c7be724b1e2cd059a840082a61c26cfe132baa1 | [
"super().__init__(**kwargs)\nused_op = None\nif backend == 'noiseless':\n used_op = circuit_execution_ops.get_sampling_op(None)\nelif backend == 'noisy':\n used_op = noisy_samples_op.samples\nelse:\n used_op = circuit_execution_ops.get_sampling_op(backend)\nself.sample_op = used_op",
"if repetitions is N... | <|body_start_0|>
super().__init__(**kwargs)
used_op = None
if backend == 'noiseless':
used_op = circuit_execution_ops.get_sampling_op(None)
elif backend == 'noisy':
used_op = noisy_samples_op.samples
else:
used_op = circuit_execution_ops.get_sa... | A Layer that samples from a quantum circuit. Given an input circuit and set of parameter values, output samples taken from the end of the circuit. First lets define a simple circuit to sample from: >>> def get_circuit(): ... q0 = cirq.GridQubit(0, 0) ... q1 = cirq.GridQubit(1, 0) ... circuit = cirq.Circuit( ... cirq.X(... | Sample | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sample:
"""A Layer that samples from a quantum circuit. Given an input circuit and set of parameter values, output samples taken from the end of the circuit. First lets define a simple circuit to sample from: >>> def get_circuit(): ... q0 = cirq.GridQubit(0, 0) ... q1 = cirq.GridQubit(1, 0) ... c... | stack_v2_sparse_classes_75kplus_train_072485 | 7,611 | permissive | [
{
"docstring": "Instantiate this Layer. Create a layer that will output bitstring samples taken from either a simulated quantum state or a real quantum computer Args: backend: Optional Backend to use to simulate this state. Defaults to the noiseless simulator. Options are {'noisy', 'noiseless'}, however users m... | 2 | stack_v2_sparse_classes_30k_train_041709 | Implement the Python class `Sample` described below.
Class description:
A Layer that samples from a quantum circuit. Given an input circuit and set of parameter values, output samples taken from the end of the circuit. First lets define a simple circuit to sample from: >>> def get_circuit(): ... q0 = cirq.GridQubit(0,... | Implement the Python class `Sample` described below.
Class description:
A Layer that samples from a quantum circuit. Given an input circuit and set of parameter values, output samples taken from the end of the circuit. First lets define a simple circuit to sample from: >>> def get_circuit(): ... q0 = cirq.GridQubit(0,... | f56257bceb988b743790e1e480eac76fd036d4ff | <|skeleton|>
class Sample:
"""A Layer that samples from a quantum circuit. Given an input circuit and set of parameter values, output samples taken from the end of the circuit. First lets define a simple circuit to sample from: >>> def get_circuit(): ... q0 = cirq.GridQubit(0, 0) ... q1 = cirq.GridQubit(1, 0) ... c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sample:
"""A Layer that samples from a quantum circuit. Given an input circuit and set of parameter values, output samples taken from the end of the circuit. First lets define a simple circuit to sample from: >>> def get_circuit(): ... q0 = cirq.GridQubit(0, 0) ... q1 = cirq.GridQubit(1, 0) ... circuit = cirq... | the_stack_v2_python_sparse | tensorflow_quantum/python/layers/circuit_executors/sample.py | tensorflow/quantum | train | 1,799 |
bf80fbf75a5f385eaa84053f0e2be6a0e24067b1 | [
"try:\n quiz = Quiz.objects.get(id=pk)\nexcept Quiz.DoesNotExist:\n return InvalidQuizIdResponse\nif quiz.startTime <= timezone.now() <= quiz.endTime:\n if request.query_params.get('picture', False) == 'true':\n questions = Question.objects.filter(quiz_id=quiz)\n else:\n questions = Questi... | <|body_start_0|>
try:
quiz = Quiz.objects.get(id=pk)
except Quiz.DoesNotExist:
return InvalidQuizIdResponse
if quiz.startTime <= timezone.now() <= quiz.endTime:
if request.query_params.get('picture', False) == 'true':
questions = Question.objec... | Create Quiz Question | QuestionView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionView:
"""Create Quiz Question"""
def get(self, request: Request, pk):
"""Get Quiz Questions"""
<|body_0|>
def post(self, request: Request, pk):
"""Create Quiz Question"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
quiz... | stack_v2_sparse_classes_75kplus_train_072486 | 9,462 | no_license | [
{
"docstring": "Get Quiz Questions",
"name": "get",
"signature": "def get(self, request: Request, pk)"
},
{
"docstring": "Create Quiz Question",
"name": "post",
"signature": "def post(self, request: Request, pk)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023865 | Implement the Python class `QuestionView` described below.
Class description:
Create Quiz Question
Method signatures and docstrings:
- def get(self, request: Request, pk): Get Quiz Questions
- def post(self, request: Request, pk): Create Quiz Question | Implement the Python class `QuestionView` described below.
Class description:
Create Quiz Question
Method signatures and docstrings:
- def get(self, request: Request, pk): Get Quiz Questions
- def post(self, request: Request, pk): Create Quiz Question
<|skeleton|>
class QuestionView:
"""Create Quiz Question"""
... | da6cd01041bc268067295665b3a60fff772be865 | <|skeleton|>
class QuestionView:
"""Create Quiz Question"""
def get(self, request: Request, pk):
"""Get Quiz Questions"""
<|body_0|>
def post(self, request: Request, pk):
"""Create Quiz Question"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuestionView:
"""Create Quiz Question"""
def get(self, request: Request, pk):
"""Get Quiz Questions"""
try:
quiz = Quiz.objects.get(id=pk)
except Quiz.DoesNotExist:
return InvalidQuizIdResponse
if quiz.startTime <= timezone.now() <= quiz.endTime:
... | the_stack_v2_python_sparse | nimbusBackend/quiz/views.py | moulikbhardwaj/nimbus2021 | train | 5 |
e336cb00e430531d6fa8ac14b154fab498aad6db | [
"self.log = log.Log().log_print()\nself.log.info('初始化Download类')\nself.dict_header = dict_header\nself.int_retries = int_retries\nself.int_delay = int_delay\nself.int_timeout = int_timeout\nself.valve_obj = Valve(int_delay)",
"self.valve_obj.valve_wait(str_url)\ntry:\n response_obj = requests.get(str_url, head... | <|body_start_0|>
self.log = log.Log().log_print()
self.log.info('初始化Download类')
self.dict_header = dict_header
self.int_retries = int_retries
self.int_delay = int_delay
self.int_timeout = int_timeout
self.valve_obj = Valve(int_delay)
<|end_body_0|>
<|body_start_1... | 下载类 | Download | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Download:
"""下载类"""
def __init__(self, dict_header: dict=None, int_retries: int=3, int_delay: int=2, int_timeout: int=30):
"""【初始化】 dict_header:标头 int_retries:重试 delay:延迟 timeout:超时"""
<|body_0|>
def download_all(self, str_url: str, bool_json: bool):
"""【下载页面】 st... | stack_v2_sparse_classes_75kplus_train_072487 | 8,214 | no_license | [
{
"docstring": "【初始化】 dict_header:标头 int_retries:重试 delay:延迟 timeout:超时",
"name": "__init__",
"signature": "def __init__(self, dict_header: dict=None, int_retries: int=3, int_delay: int=2, int_timeout: int=30)"
},
{
"docstring": "【下载页面】 str_url:地址 bool_json:是否json类型",
"name": "download_all",... | 2 | null | Implement the Python class `Download` described below.
Class description:
下载类
Method signatures and docstrings:
- def __init__(self, dict_header: dict=None, int_retries: int=3, int_delay: int=2, int_timeout: int=30): 【初始化】 dict_header:标头 int_retries:重试 delay:延迟 timeout:超时
- def download_all(self, str_url: str, bool_j... | Implement the Python class `Download` described below.
Class description:
下载类
Method signatures and docstrings:
- def __init__(self, dict_header: dict=None, int_retries: int=3, int_delay: int=2, int_timeout: int=30): 【初始化】 dict_header:标头 int_retries:重试 delay:延迟 timeout:超时
- def download_all(self, str_url: str, bool_j... | bd7152899dcb04aa76ed9f65b36e6a8ccc0affd0 | <|skeleton|>
class Download:
"""下载类"""
def __init__(self, dict_header: dict=None, int_retries: int=3, int_delay: int=2, int_timeout: int=30):
"""【初始化】 dict_header:标头 int_retries:重试 delay:延迟 timeout:超时"""
<|body_0|>
def download_all(self, str_url: str, bool_json: bool):
"""【下载页面】 st... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Download:
"""下载类"""
def __init__(self, dict_header: dict=None, int_retries: int=3, int_delay: int=2, int_timeout: int=30):
"""【初始化】 dict_header:标头 int_retries:重试 delay:延迟 timeout:超时"""
self.log = log.Log().log_print()
self.log.info('初始化Download类')
self.dict_header = dict_h... | the_stack_v2_python_sparse | part03/week03/crawler.py | tea8336/test | train | 0 |
d728af8f917c2998061704a760563328a38239ed | [
"self.count = {}\nself.queue = collections.deque()\nfor num in nums:\n self.add(num)",
"for num in self.queue:\n if self.count[num] == 1:\n return num\nreturn -1",
"if value not in self.count:\n self.count[value] = 1\n self.queue.append(value)\nelse:\n self.count[value] += 1"
] | <|body_start_0|>
self.count = {}
self.queue = collections.deque()
for num in nums:
self.add(num)
<|end_body_0|>
<|body_start_1|>
for num in self.queue:
if self.count[num] == 1:
return num
return -1
<|end_body_1|>
<|body_start_2|>
... | FirstUnique | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirstUnique:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def showFirstUnique(self):
""":rtype: int"""
<|body_1|>
def add(self, value):
""":type value: int :rtype: None"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_072488 | 843 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":rtype: int",
"name": "showFirstUnique",
"signature": "def showFirstUnique(self)"
},
{
"docstring": ":type value: int :rtype: None",
"name": "add",
"sign... | 3 | stack_v2_sparse_classes_30k_train_051327 | Implement the Python class `FirstUnique` described below.
Class description:
Implement the FirstUnique class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def showFirstUnique(self): :rtype: int
- def add(self, value): :type value: int :rtype: None | Implement the Python class `FirstUnique` described below.
Class description:
Implement the FirstUnique class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def showFirstUnique(self): :rtype: int
- def add(self, value): :type value: int :rtype: None
<|skeleton|>
class FirstUniq... | 474886c5c43a6192db2708e664663542c2e39548 | <|skeleton|>
class FirstUnique:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def showFirstUnique(self):
""":rtype: int"""
<|body_1|>
def add(self, value):
""":type value: int :rtype: None"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FirstUnique:
def __init__(self, nums):
""":type nums: List[int]"""
self.count = {}
self.queue = collections.deque()
for num in nums:
self.add(num)
def showFirstUnique(self):
""":rtype: int"""
for num in self.queue:
if self.count[num]... | the_stack_v2_python_sparse | question_leetcode/1429_1.py | paul0920/leetcode | train | 1 | |
532c398be31e0e5d9a3dbd04071cbce0837c90e3 | [
"self.camera_list = camera_list\nfor camera in camera_list:\n if camera not in ['E', 'SE', 'SW', 'W']:\n raise RuntimeError('Camera: \"' + camera + '\" not understood')\nself._base_url = 'http://sailing.mit.edu/img/'\nself._image_name = '/latest.jpg'\nsuper(DataFetcher, self).__init__()",
"url_list = []... | <|body_start_0|>
self.camera_list = camera_list
for camera in camera_list:
if camera not in ['E', 'SE', 'SW', 'W']:
raise RuntimeError('Camera: "' + camera + '" not understood')
self._base_url = 'http://sailing.mit.edu/img/'
self._image_name = '/latest.jpg'
... | Data Fetcher for retrieving webcam images from the MIT Sailing Pavilion | DataFetcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataFetcher:
"""Data Fetcher for retrieving webcam images from the MIT Sailing Pavilion"""
def __init__(self, camera_list=['E', 'SE', 'SW', 'W']):
"""@param camera_list: Which camera to retrieve from (List that contains one or more of the following: 'E', 'SE', 'SW', or 'W')"""
... | stack_v2_sparse_classes_75kplus_train_072489 | 2,645 | permissive | [
{
"docstring": "@param camera_list: Which camera to retrieve from (List that contains one or more of the following: 'E', 'SE', 'SW', or 'W')",
"name": "__init__",
"signature": "def __init__(self, camera_list=['E', 'SE', 'SW', 'W'])"
},
{
"docstring": "Retrieve data from webcams at the MIT Sailin... | 2 | stack_v2_sparse_classes_30k_train_000235 | Implement the Python class `DataFetcher` described below.
Class description:
Data Fetcher for retrieving webcam images from the MIT Sailing Pavilion
Method signatures and docstrings:
- def __init__(self, camera_list=['E', 'SE', 'SW', 'W']): @param camera_list: Which camera to retrieve from (List that contains one or ... | Implement the Python class `DataFetcher` described below.
Class description:
Data Fetcher for retrieving webcam images from the MIT Sailing Pavilion
Method signatures and docstrings:
- def __init__(self, camera_list=['E', 'SE', 'SW', 'W']): @param camera_list: Which camera to retrieve from (List that contains one or ... | 935bfd54149abd9542fe38e77b7eabab48b1c3a1 | <|skeleton|>
class DataFetcher:
"""Data Fetcher for retrieving webcam images from the MIT Sailing Pavilion"""
def __init__(self, camera_list=['E', 'SE', 'SW', 'W']):
"""@param camera_list: Which camera to retrieve from (List that contains one or more of the following: 'E', 'SE', 'SW', or 'W')"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataFetcher:
"""Data Fetcher for retrieving webcam images from the MIT Sailing Pavilion"""
def __init__(self, camera_list=['E', 'SE', 'SW', 'W']):
"""@param camera_list: Which camera to retrieve from (List that contains one or more of the following: 'E', 'SE', 'SW', or 'W')"""
self.camera... | the_stack_v2_python_sparse | skdaccess/engineering/webcam/mit_sailing/stream.py | MITHaystack/scikit-dataaccess | train | 41 |
6c332649851f1ee551eedb5b8daac3639cb1395b | [
"super().__init__(coordinator, description)\nenpower = self.data.enpower\nassert enpower is not None\nself._attr_unique_id = f'{enpower.serial_number}_{description.key}'\nself._attr_device_info = DeviceInfo(identifiers={(DOMAIN, enpower.serial_number)}, manufacturer='Enphase', model='Enpower', name=f'Enpower {enpow... | <|body_start_0|>
super().__init__(coordinator, description)
enpower = self.data.enpower
assert enpower is not None
self._attr_unique_id = f'{enpower.serial_number}_{description.key}'
self._attr_device_info = DeviceInfo(identifiers={(DOMAIN, enpower.serial_number)}, manufacturer='... | Defines an Enpower binary_sensor entity. | EnvoyEnpowerBinarySensorEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvoyEnpowerBinarySensorEntity:
"""Defines an Enpower binary_sensor entity."""
def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerBinarySensorEntityDescription) -> None:
"""Init the Enpower base entity."""
<|body_0|>
def is_on(self) -> boo... | stack_v2_sparse_classes_75kplus_train_072490 | 5,991 | permissive | [
{
"docstring": "Init the Enpower base entity.",
"name": "__init__",
"signature": "def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerBinarySensorEntityDescription) -> None"
},
{
"docstring": "Return the state of the Enpower binary_sensor.",
"name": "is_on",
... | 2 | stack_v2_sparse_classes_30k_train_023292 | Implement the Python class `EnvoyEnpowerBinarySensorEntity` described below.
Class description:
Defines an Enpower binary_sensor entity.
Method signatures and docstrings:
- def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerBinarySensorEntityDescription) -> None: Init the Enpower base ... | Implement the Python class `EnvoyEnpowerBinarySensorEntity` described below.
Class description:
Defines an Enpower binary_sensor entity.
Method signatures and docstrings:
- def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerBinarySensorEntityDescription) -> None: Init the Enpower base ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EnvoyEnpowerBinarySensorEntity:
"""Defines an Enpower binary_sensor entity."""
def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerBinarySensorEntityDescription) -> None:
"""Init the Enpower base entity."""
<|body_0|>
def is_on(self) -> boo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnvoyEnpowerBinarySensorEntity:
"""Defines an Enpower binary_sensor entity."""
def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerBinarySensorEntityDescription) -> None:
"""Init the Enpower base entity."""
super().__init__(coordinator, description)
... | the_stack_v2_python_sparse | homeassistant/components/enphase_envoy/binary_sensor.py | home-assistant/core | train | 35,501 |
88679f0cfe3bb55c5facf1f5e7725bf0572b5b98 | [
"self.api_key = str.encode(config['api_key'])\nself.endpoint = config['endpoint'].replace('http:', 'https:')\nself.namespace = config['namespace']\nself.runtime = config['action_name']\nauth = base64.encodestring(self.api_key).replace(b'\\n', b'')\nself.headers = {'content-type': 'application/json', 'Authorization'... | <|body_start_0|>
self.api_key = str.encode(config['api_key'])
self.endpoint = config['endpoint'].replace('http:', 'https:')
self.namespace = config['namespace']
self.runtime = config['action_name']
auth = base64.encodestring(self.api_key).replace(b'\n', b'')
self.headers ... | CloudFunctions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudFunctions:
def __init__(self, config):
"""Constructor"""
<|body_0|>
def create_action(self, action_name, memory=None, timeout=None, code=None, is_binary=True, overwrite=True):
"""Create an IBM Cloud Function"""
<|body_1|>
def get_action(self, action... | stack_v2_sparse_classes_75kplus_train_072491 | 6,087 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Create an IBM Cloud Function",
"name": "create_action",
"signature": "def create_action(self, action_name, memory=None, timeout=None, code=None, is_binary=True, overwrite=True)"... | 5 | null | Implement the Python class `CloudFunctions` described below.
Class description:
Implement the CloudFunctions class.
Method signatures and docstrings:
- def __init__(self, config): Constructor
- def create_action(self, action_name, memory=None, timeout=None, code=None, is_binary=True, overwrite=True): Create an IBM Cl... | Implement the Python class `CloudFunctions` described below.
Class description:
Implement the CloudFunctions class.
Method signatures and docstrings:
- def __init__(self, config): Constructor
- def create_action(self, action_name, memory=None, timeout=None, code=None, is_binary=True, overwrite=True): Create an IBM Cl... | f4dd2b606c1156602186a15b503b34de9429013d | <|skeleton|>
class CloudFunctions:
def __init__(self, config):
"""Constructor"""
<|body_0|>
def create_action(self, action_name, memory=None, timeout=None, code=None, is_binary=True, overwrite=True):
"""Create an IBM Cloud Function"""
<|body_1|>
def get_action(self, action... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CloudFunctions:
def __init__(self, config):
"""Constructor"""
self.api_key = str.encode(config['api_key'])
self.endpoint = config['endpoint'].replace('http:', 'https:')
self.namespace = config['namespace']
self.runtime = config['action_name']
auth = base64.encod... | the_stack_v2_python_sparse | pywren/pywren_ibm_cloud/cf_connector.py | jroakes/pywren-ibm-cloud | train | 0 | |
ee472d95019ee0b71ea510c38ccf1360ee8fa25d | [
"self.post_reqparser = reqparse.RequestParser()\nself.post_reqparser.add_argument('widgetID', help='widgetID required', location=['form', 'json'])\nself.post_reqparser.add_argument('x', help='Widget layout: x coordinate found', location=['form', 'json'])\nself.post_reqparser.add_argument('y', help='Widget layout: y... | <|body_start_0|>
self.post_reqparser = reqparse.RequestParser()
self.post_reqparser.add_argument('widgetID', help='widgetID required', location=['form', 'json'])
self.post_reqparser.add_argument('x', help='Widget layout: x coordinate found', location=['form', 'json'])
self.post_reqparser... | Creates a Widget layout to the database table 'layouts' Parameters can be passed using a POST request that contains a JSON with the following fields: :param widgetID: The widget identification the layout belongs to :param x: x coordinate of the widget layout :param y: y coordinate of the widget layout :param h: height ... | CreateWidgetLayout | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateWidgetLayout:
"""Creates a Widget layout to the database table 'layouts' Parameters can be passed using a POST request that contains a JSON with the following fields: :param widgetID: The widget identification the layout belongs to :param x: x coordinate of the widget layout :param y: y coo... | stack_v2_sparse_classes_75kplus_train_072492 | 4,557 | permissive | [
{
"docstring": "Instantiates the create widget endpoint Parameters can be passed using a POST request that contains a JSON with the following fields: :param widgetID: The widget identification the layout belongs to :param x: x coordinate of the widget layout :param y: y coordinate of the widget layout :param h:... | 2 | stack_v2_sparse_classes_30k_train_038602 | Implement the Python class `CreateWidgetLayout` described below.
Class description:
Creates a Widget layout to the database table 'layouts' Parameters can be passed using a POST request that contains a JSON with the following fields: :param widgetID: The widget identification the layout belongs to :param x: x coordina... | Implement the Python class `CreateWidgetLayout` described below.
Class description:
Creates a Widget layout to the database table 'layouts' Parameters can be passed using a POST request that contains a JSON with the following fields: :param widgetID: The widget identification the layout belongs to :param x: x coordina... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class CreateWidgetLayout:
"""Creates a Widget layout to the database table 'layouts' Parameters can be passed using a POST request that contains a JSON with the following fields: :param widgetID: The widget identification the layout belongs to :param x: x coordinate of the widget layout :param y: y coo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateWidgetLayout:
"""Creates a Widget layout to the database table 'layouts' Parameters can be passed using a POST request that contains a JSON with the following fields: :param widgetID: The widget identification the layout belongs to :param x: x coordinate of the widget layout :param y: y coordinate of th... | the_stack_v2_python_sparse | Analytics/resources/Widgets/create_widget_layout.py | thanosbnt/SharingCitiesDashboard | train | 0 |
32deaced353c44932cd31cf6ee85ba507ab554eb | [
"agent_keys = list(self._agents.keys())\nif shuffled:\n self.model.random.shuffle(agent_keys)\nfor key in agent_keys:\n if key in self._agents:\n yield (key, self._agents[key])",
"for key, agent in self.agent_buffer():\n try:\n shape = gdf.at[key, 'geometry']\n except KeyError:\n ... | <|body_start_0|>
agent_keys = list(self._agents.keys())
if shuffled:
self.model.random.shuffle(agent_keys)
for key in agent_keys:
if key in self._agents:
yield (key, self._agents[key])
<|end_body_0|>
<|body_start_1|>
for key, agent in self.agent_b... | Scheduler with data consumption on each step. | DataScheduler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataScheduler:
"""Scheduler with data consumption on each step."""
def agent_buffer(self, shuffled: bool=False) -> Iterator[Tuple]:
"""Simple generator that yields the agents while letting the user remove and/or add agents during stepping."""
<|body_0|>
def step(self, gd... | stack_v2_sparse_classes_75kplus_train_072493 | 1,166 | no_license | [
{
"docstring": "Simple generator that yields the agents while letting the user remove and/or add agents during stepping.",
"name": "agent_buffer",
"signature": "def agent_buffer(self, shuffled: bool=False) -> Iterator[Tuple]"
},
{
"docstring": "Execute the step of all agents, one at a time, in r... | 2 | stack_v2_sparse_classes_30k_train_040215 | Implement the Python class `DataScheduler` described below.
Class description:
Scheduler with data consumption on each step.
Method signatures and docstrings:
- def agent_buffer(self, shuffled: bool=False) -> Iterator[Tuple]: Simple generator that yields the agents while letting the user remove and/or add agents duri... | Implement the Python class `DataScheduler` described below.
Class description:
Scheduler with data consumption on each step.
Method signatures and docstrings:
- def agent_buffer(self, shuffled: bool=False) -> Iterator[Tuple]: Simple generator that yields the agents while letting the user remove and/or add agents duri... | 26f5fe15be93fd277f3086a2fabddca4228bf963 | <|skeleton|>
class DataScheduler:
"""Scheduler with data consumption on each step."""
def agent_buffer(self, shuffled: bool=False) -> Iterator[Tuple]:
"""Simple generator that yields the agents while letting the user remove and/or add agents during stepping."""
<|body_0|>
def step(self, gd... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataScheduler:
"""Scheduler with data consumption on each step."""
def agent_buffer(self, shuffled: bool=False) -> Iterator[Tuple]:
"""Simple generator that yields the agents while letting the user remove and/or add agents during stepping."""
agent_keys = list(self._agents.keys())
... | the_stack_v2_python_sparse | geocovid/scheduler.py | awolfmann/geocovid | train | 0 |
29bca8ed922d090c4488f1303dfc0fd2cc02bbfe | [
"Environment_Base.__init__(self)\nself.num_cars = [num_cars_init, num_cars_init]\nself.num_cars_max = num_cars_max\nself.done = False\nself.reward = None\nself.cars_rent = [3, 4]\nself.cars_return = [3, 4]\nself.credit_one_car = 10\nself.cost_trans = 2",
"if num >= self.num_cars_max:\n diff = 0\n val_return... | <|body_start_0|>
Environment_Base.__init__(self)
self.num_cars = [num_cars_init, num_cars_init]
self.num_cars_max = num_cars_max
self.done = False
self.reward = None
self.cars_rent = [3, 4]
self.cars_return = [3, 4]
self.credit_one_car = 10
self.co... | Rewrite the Env_base and realize the file of Car_Rental | Car_Rental | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Car_Rental:
"""Rewrite the Env_base and realize the file of Car_Rental"""
def __init__(self, num_cars_init, num_cars_max):
"""for init the env arg: num_cars_init: the num of the cars of the two locations num_cars_max: the max num of the cars in the two locations"""
<|body_0|>... | stack_v2_sparse_classes_75kplus_train_072494 | 3,485 | no_license | [
{
"docstring": "for init the env arg: num_cars_init: the num of the cars of the two locations num_cars_max: the max num of the cars in the two locations",
"name": "__init__",
"signature": "def __init__(self, num_cars_init, num_cars_max)"
},
{
"docstring": "this func for number check return the d... | 3 | stack_v2_sparse_classes_30k_train_049595 | Implement the Python class `Car_Rental` described below.
Class description:
Rewrite the Env_base and realize the file of Car_Rental
Method signatures and docstrings:
- def __init__(self, num_cars_init, num_cars_max): for init the env arg: num_cars_init: the num of the cars of the two locations num_cars_max: the max n... | Implement the Python class `Car_Rental` described below.
Class description:
Rewrite the Env_base and realize the file of Car_Rental
Method signatures and docstrings:
- def __init__(self, num_cars_init, num_cars_max): for init the env arg: num_cars_init: the num of the cars of the two locations num_cars_max: the max n... | 180cc4d6370953e52b02822e7f7b54030ba656fa | <|skeleton|>
class Car_Rental:
"""Rewrite the Env_base and realize the file of Car_Rental"""
def __init__(self, num_cars_init, num_cars_max):
"""for init the env arg: num_cars_init: the num of the cars of the two locations num_cars_max: the max num of the cars in the two locations"""
<|body_0|>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Car_Rental:
"""Rewrite the Env_base and realize the file of Car_Rental"""
def __init__(self, num_cars_init, num_cars_max):
"""for init the env arg: num_cars_init: the num of the cars of the two locations num_cars_max: the max num of the cars in the two locations"""
Environment_Base.__init... | the_stack_v2_python_sparse | car_rental/car_rental.py | DKuan/Reinforcement_Learning2018 | train | 0 |
785a2ace1e7d76b2755d63b89e855df3976a4c86 | [
"super(RNNEncoder, self).__init__()\nself.batch = batch\nself.units = units\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)",
"initializer = tf.keras.initializers.Zeros()\nhiddenQ... | <|body_start_0|>
super(RNNEncoder, self).__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
<|end_bod... | class rnn encoder | RNNEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""class rnn encoder"""
def __init__(self, vocab, embedding, units, batch):
"""Inititalizer function Args: batch: integer representing the batch size"""
<|body_0|>
def initialize_hidden_state(self):
"""Inititalize hidden states Returns: tensor of shap... | stack_v2_sparse_classes_75kplus_train_072495 | 1,642 | no_license | [
{
"docstring": "Inititalizer function Args: batch: integer representing the batch size",
"name": "__init__",
"signature": "def __init__(self, vocab, embedding, units, batch)"
},
{
"docstring": "Inititalize hidden states Returns: tensor of shape (batch, units) containing the initialized hidden st... | 3 | stack_v2_sparse_classes_30k_train_022983 | Implement the Python class `RNNEncoder` described below.
Class description:
class rnn encoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Inititalizer function Args: batch: integer representing the batch size
- def initialize_hidden_state(self): Inititalize hidden states Re... | Implement the Python class `RNNEncoder` described below.
Class description:
class rnn encoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Inititalizer function Args: batch: integer representing the batch size
- def initialize_hidden_state(self): Inititalize hidden states Re... | a51fbcb76dae9281ff34ace0fb762ef899b4c380 | <|skeleton|>
class RNNEncoder:
"""class rnn encoder"""
def __init__(self, vocab, embedding, units, batch):
"""Inititalizer function Args: batch: integer representing the batch size"""
<|body_0|>
def initialize_hidden_state(self):
"""Inititalize hidden states Returns: tensor of shap... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNEncoder:
"""class rnn encoder"""
def __init__(self, vocab, embedding, units, batch):
"""Inititalizer function Args: batch: integer representing the batch size"""
super(RNNEncoder, self).__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.l... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/0-rnn_encoder.py | Diegokernel/holbertonschool-machine_learning | train | 0 |
cc43bd908d879d665d666e88ee30e7a60b1d25b4 | [
"self.position = position\nself.num_trials = num_trials\nself.position_value = np.true_divide(1000, self.position)\nif self.position == 1:\n self.position_word = ' position '\nelse:\n self.position_word = ' positions '",
"investment_outcome = []\nfor i in range(self.position * self.num_trials):\n outcome... | <|body_start_0|>
self.position = position
self.num_trials = num_trials
self.position_value = np.true_divide(1000, self.position)
if self.position == 1:
self.position_word = ' position '
else:
self.position_word = ' positions '
<|end_body_0|>
<|body_start_... | investment_instrument | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class investment_instrument:
def __init__(self, position, num_trials):
"""Initiate an instance of the investment_instrument class. A function of an investment position"""
<|body_0|>
def generate_daily_returns(self):
"""For each position, simulate n daily returns, where n i... | stack_v2_sparse_classes_75kplus_train_072496 | 3,339 | no_license | [
{
"docstring": "Initiate an instance of the investment_instrument class. A function of an investment position",
"name": "__init__",
"signature": "def __init__(self, position, num_trials)"
},
{
"docstring": "For each position, simulate n daily returns, where n is num_trials",
"name": "generat... | 4 | stack_v2_sparse_classes_30k_train_029260 | Implement the Python class `investment_instrument` described below.
Class description:
Implement the investment_instrument class.
Method signatures and docstrings:
- def __init__(self, position, num_trials): Initiate an instance of the investment_instrument class. A function of an investment position
- def generate_d... | Implement the Python class `investment_instrument` described below.
Class description:
Implement the investment_instrument class.
Method signatures and docstrings:
- def __init__(self, position, num_trials): Initiate an instance of the investment_instrument class. A function of an investment position
- def generate_d... | 5b904060e8bced7f91547ad7f7819773a7450a1e | <|skeleton|>
class investment_instrument:
def __init__(self, position, num_trials):
"""Initiate an instance of the investment_instrument class. A function of an investment position"""
<|body_0|>
def generate_daily_returns(self):
"""For each position, simulate n daily returns, where n i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class investment_instrument:
def __init__(self, position, num_trials):
"""Initiate an instance of the investment_instrument class. A function of an investment position"""
self.position = position
self.num_trials = num_trials
self.position_value = np.true_divide(1000, self.position)
... | the_stack_v2_python_sparse | zvz201/investment_instrument.py | ds-ga-1007/assignment8 | train | 1 | |
b290fb490048d4dbc63779f03b394aa9f2f7bd0a | [
"text_labels = []\npredicted, expected = ([], [])\nfor result in self.results:\n text_labels, predicted = self._update_raw_result(result.predicted, text_labels, predicted)\n text_labels, expected = self._update_raw_result(result.expected, text_labels, expected)\nreturn RawResults(predicted=predicted, expected... | <|body_start_0|>
text_labels = []
predicted, expected = ([], [])
for result in self.results:
text_labels, predicted = self._update_raw_result(result.predicted, text_labels, predicted)
text_labels, expected = self._update_raw_result(result.expected, text_labels, expected)
... | StandardModelEvaluation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StandardModelEvaluation:
def raw_results(self):
"""Returns the raw results of the model evaluation"""
<|body_0|>
def get_stats(self):
"""Prints model evaluation stats in a table to stdout"""
<|body_1|>
def print_stats(self):
"""Prints model evalu... | stack_v2_sparse_classes_75kplus_train_072497 | 22,141 | permissive | [
{
"docstring": "Returns the raw results of the model evaluation",
"name": "raw_results",
"signature": "def raw_results(self)"
},
{
"docstring": "Prints model evaluation stats in a table to stdout",
"name": "get_stats",
"signature": "def get_stats(self)"
},
{
"docstring": "Prints ... | 3 | stack_v2_sparse_classes_30k_train_046769 | Implement the Python class `StandardModelEvaluation` described below.
Class description:
Implement the StandardModelEvaluation class.
Method signatures and docstrings:
- def raw_results(self): Returns the raw results of the model evaluation
- def get_stats(self): Prints model evaluation stats in a table to stdout
- d... | Implement the Python class `StandardModelEvaluation` described below.
Class description:
Implement the StandardModelEvaluation class.
Method signatures and docstrings:
- def raw_results(self): Returns the raw results of the model evaluation
- def get_stats(self): Prints model evaluation stats in a table to stdout
- d... | bd3547d5c1bd092dbd4a64a90528dfc2e2b3844a | <|skeleton|>
class StandardModelEvaluation:
def raw_results(self):
"""Returns the raw results of the model evaluation"""
<|body_0|>
def get_stats(self):
"""Prints model evaluation stats in a table to stdout"""
<|body_1|>
def print_stats(self):
"""Prints model evalu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StandardModelEvaluation:
def raw_results(self):
"""Returns the raw results of the model evaluation"""
text_labels = []
predicted, expected = ([], [])
for result in self.results:
text_labels, predicted = self._update_raw_result(result.predicted, text_labels, predicte... | the_stack_v2_python_sparse | mindmeld/models/evaluation.py | cisco/mindmeld | train | 671 | |
400f13836414d7042113e33413fa78a61ed73576 | [
"super().__init__()\nimport sklearn\nimport sklearn.svm\nself.model = sklearn.svm.LinearSVC",
"specs = super(LinearSVC, cls).getInputSpecification()\nspecs.description = 'The \\\\xmlNode{LinearSVC} \\\\textit{Linear Support Vector Classification} is\\n similar to SVC with parameter kern... | <|body_start_0|>
super().__init__()
import sklearn
import sklearn.svm
self.model = sklearn.svm.LinearSVC
<|end_body_0|>
<|body_start_1|>
specs = super(LinearSVC, cls).getInputSpecification()
specs.description = 'The \\xmlNode{LinearSVC} \\textit{Linear Support Vector Cla... | Linear Support Vector Classifier | LinearSVC | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearSVC:
"""Linear Support Vector Classifier"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that ... | stack_v2_sparse_classes_75kplus_train_072498 | 9,587 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 3 | stack_v2_sparse_classes_30k_train_022833 | Implement the Python class `LinearSVC` described below.
Class description:
Linear Support Vector Classifier
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a refer... | Implement the Python class `LinearSVC` described below.
Class description:
Linear Support Vector Classifier
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a refer... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class LinearSVC:
"""Linear Support Vector Classifier"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinearSVC:
"""Linear Support Vector Classifier"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
import sklearn
import sklearn.svm
self.model = sklearn.svm.LinearSVC
... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/SVM/LinearSVC.py | idaholab/raven | train | 201 |
d744553582f583f0511df77036c9fe6129c60953 | [
"self.hab = hab\nself.msgs = decking.Deck()\nself.cues = cues if cues is not None else decking.Deck()\nself.wallet = wallet\nsuper(RequestHandler, self).__init__(**kwa)",
"while True:\n while self.msgs:\n msg = self.msgs.popleft()\n payload = msg['payload']\n requestor = msg['pre']\n ... | <|body_start_0|>
self.hab = hab
self.msgs = decking.Deck()
self.cues = cues if cues is not None else decking.Deck()
self.wallet = wallet
super(RequestHandler, self).__init__(**kwa)
<|end_body_0|>
<|body_start_1|>
while True:
while self.msgs:
m... | Processor for a credential request with input descriptors in the payload used to match saved credentials based on a schema. The payload of the request is expected to have the following format: { ""submission_requirements": [{ "name": "Proof of LEI", "rule": "pick", "count": 1, "from": "A" }] "input_descriptors": [ { "x... | RequestHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestHandler:
"""Processor for a credential request with input descriptors in the payload used to match saved credentials based on a schema. The payload of the request is expected to have the following format: { ""submission_requirements": [{ "name": "Proof of LEI", "rule": "pick", "count": 1, ... | stack_v2_sparse_classes_75kplus_train_072499 | 22,714 | permissive | [
{
"docstring": "Create an `exn` request handler for processing credential presentation requests Parameters hab (Habitate) is the environment wallet (Wallet) is the wallet holding the credentials to present cues (decking.Deck) of responses cue'ed up by this handler",
"name": "__init__",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_041586 | Implement the Python class `RequestHandler` described below.
Class description:
Processor for a credential request with input descriptors in the payload used to match saved credentials based on a schema. The payload of the request is expected to have the following format: { ""submission_requirements": [{ "name": "Proo... | Implement the Python class `RequestHandler` described below.
Class description:
Processor for a credential request with input descriptors in the payload used to match saved credentials based on a schema. The payload of the request is expected to have the following format: { ""submission_requirements": [{ "name": "Proo... | 467f952912b17dede8a8f4ebce73241408b63e8c | <|skeleton|>
class RequestHandler:
"""Processor for a credential request with input descriptors in the payload used to match saved credentials based on a schema. The payload of the request is expected to have the following format: { ""submission_requirements": [{ "name": "Proof of LEI", "rule": "pick", "count": 1, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RequestHandler:
"""Processor for a credential request with input descriptors in the payload used to match saved credentials based on a schema. The payload of the request is expected to have the following format: { ""submission_requirements": [{ "name": "Proof of LEI", "rule": "pick", "count": 1, "from": "A" }... | the_stack_v2_python_sparse | src/keri/vc/handling.py | dlandi/keripy-1 | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.